From baf498e7b08d24682b585f2e01fd425e03a199da Mon Sep 17 00:00:00 2001 From: Shubham Date: Wed, 2 Jul 2025 19:48:33 +0530 Subject: [PATCH 01/32] chore: use Object for anyType (#873) * fix: use Object for types instead of Map * fix: use Object for anyType * fix: use Object for anyType --- .../twilio/rest/accounts/v1/BulkConsents.java | 4 +- .../rest/accounts/v1/BulkConsentsCreator.java | 16 +- .../twilio/rest/accounts/v1/BulkContacts.java | 4 +- .../rest/accounts/v1/BulkContactsCreator.java | 16 +- .../com/twilio/rest/api/v2010/Account.java | 12 +- .../v2010/account/AuthorizedConnectApp.java | 8 +- .../twilio/rest/api/v2010/account/Call.java | 8 +- .../rest/api/v2010/account/Conference.java | 12 +- .../rest/api/v2010/account/ConnectApp.java | 8 +- .../v2010/account/IncomingPhoneNumber.java | 26 ++-- .../rest/api/v2010/account/Message.java | 14 +- .../api/v2010/account/MessageCreator.java | 2 +- .../rest/api/v2010/account/Recording.java | 12 +- .../rest/api/v2010/account/Transcription.java | 8 +- .../account/ValidationRequestCreator.java | 2 +- .../account/address/DependentPhoneNumber.java | 14 +- .../v2010/account/call/PaymentCreator.java | 11 +- .../api/v2010/account/call/Recording.java | 18 +-- .../rest/api/v2010/account/call/Siprec.java | 10 +- .../rest/api/v2010/account/call/Stream.java | 10 +- .../api/v2010/account/call/Transcription.java | 10 +- .../v2010/account/conference/Participant.java | 6 +- .../v2010/account/conference/Recording.java | 18 +-- .../account/incomingphonenumber/Local.java | 26 ++-- .../incomingphonenumber/LocalCreator.java | 2 +- .../account/incomingphonenumber/Mobile.java | 26 ++-- .../incomingphonenumber/MobileCreator.java | 2 +- .../account/incomingphonenumber/TollFree.java | 26 ++-- .../incomingphonenumber/TollFreeCreator.java | 2 +- .../api/v2010/account/message/Feedback.java | 6 +- .../v2010/account/recording/AddOnResult.java | 6 +- .../account/recording/Transcription.java | 8 +- .../rest/api/v2010/account/usage/Record.java | 8 +- .../rest/api/v2010/account/usage/Trigger.java | 24 ++- .../v2010/account/usage/record/AllTime.java | 8 +- .../api/v2010/account/usage/record/Daily.java | 8 +- .../v2010/account/usage/record/LastMonth.java | 8 +- .../v2010/account/usage/record/Monthly.java | 8 +- .../v2010/account/usage/record/ThisMonth.java | 8 +- .../api/v2010/account/usage/record/Today.java | 8 +- .../v2010/account/usage/record/Yearly.java | 8 +- .../v2010/account/usage/record/Yesterday.java | 8 +- .../twilio/rest/assistants/v1/Assistant.java | 15 +- .../twilio/rest/assistants/v1/Knowledge.java | 23 +-- .../com/twilio/rest/assistants/v1/Tool.java | 29 ++-- .../assistants/v1/assistant/Feedback.java | 2 +- .../rest/assistants/v1/assistant/Message.java | 2 +- .../v1/export/ExportCustomJob.java | 9 +- .../rest/bulkexports/v1/export/Job.java | 9 +- .../com/twilio/rest/chat/v1/Credential.java | 8 +- .../twilio/rest/chat/v1/service/Channel.java | 6 +- .../com/twilio/rest/chat/v1/service/Role.java | 8 +- .../chat/v1/service/user/UserChannel.java | 6 +- .../com/twilio/rest/chat/v2/Credential.java | 8 +- .../twilio/rest/chat/v2/service/Binding.java | 6 +- .../twilio/rest/chat/v2/service/Channel.java | 6 +- .../com/twilio/rest/chat/v2/service/Role.java | 8 +- .../rest/chat/v2/service/channel/Webhook.java | 2 +- .../chat/v2/service/user/UserBinding.java | 6 +- .../chat/v2/service/user/UserChannel.java | 12 +- .../java/com/twilio/rest/chat/v3/Channel.java | 6 +- .../com/twilio/rest/content/v1/Content.java | 2 +- .../content/v1/content/ApprovalCreate.java | 2 +- .../v1/AddressConfiguration.java | 38 ++--- .../rest/conversations/v1/Conversation.java | 6 +- .../v1/ConversationWithParticipants.java | 6 +- .../rest/conversations/v1/Credential.java | 8 +- .../v1/ParticipantConversation.java | 8 +- .../twilio/rest/conversations/v1/Role.java | 8 +- .../v1/configuration/Webhook.java | 12 +- .../v1/conversation/Webhook.java | 6 +- .../conversation/message/DeliveryReceipt.java | 6 +- .../conversations/v1/service/Binding.java | 6 +- .../v1/service/Conversation.java | 6 +- .../service/ConversationWithParticipants.java | 6 +- .../v1/service/ParticipantConversation.java | 8 +- .../rest/conversations/v1/service/Role.java | 8 +- .../v1/service/configuration/Webhook.java | 6 +- .../v1/service/conversation/Webhook.java | 6 +- .../conversation/message/DeliveryReceipt.java | 6 +- .../v1/service/user/UserConversation.java | 14 +- .../v1/user/UserConversation.java | 14 +- .../java/com/twilio/rest/events/v1/Sink.java | 16 +- .../twilio/rest/events/v1/SinkCreator.java | 12 +- .../twilio/rest/events/v1/Subscription.java | 2 +- .../rest/events/v1/SubscriptionCreator.java | 16 +- .../twilio/rest/flexapi/v1/Configuration.java | 6 +- .../com/twilio/rest/flexapi/v1/FlexFlow.java | 16 +- .../twilio/rest/flexapi/v1/Interaction.java | 4 +- .../rest/flexapi/v1/InteractionCreator.java | 16 +- .../v1/PluginConfigurationCreator.java | 18 +-- .../rest/flexapi/v1/ProvisioningStatus.java | 6 +- .../v1/interaction/InteractionChannel.java | 14 +- .../InteractionChannelUpdater.java | 9 +- .../InteractionChannelInvite.java | 2 +- .../InteractionChannelInviteCreator.java | 12 +- .../InteractionChannelParticipant.java | 12 +- .../InteractionChannelParticipantCreator.java | 16 +- .../InteractionTransfer.java | 12 +- .../com/twilio/rest/frontlineapi/v1/User.java | 6 +- .../rest/insights/v1/CallSummaries.java | 26 ++-- .../twilio/rest/insights/v1/Conference.java | 40 +++-- .../com/twilio/rest/insights/v1/Room.java | 50 +++--- .../rest/insights/v1/call/Annotation.java | 12 +- .../rest/insights/v1/call/CallSummary.java | 26 ++-- .../twilio/rest/insights/v1/call/Event.java | 12 +- .../twilio/rest/insights/v1/call/Metric.java | 12 +- .../v1/conference/ConferenceParticipant.java | 54 +++---- .../rest/insights/v1/room/Participant.java | 26 ++-- .../rest/intelligence/v2/CustomOperator.java | 12 +- .../v2/CustomOperatorCreator.java | 10 +- .../v2/CustomOperatorUpdater.java | 9 +- .../twilio/rest/intelligence/v2/Operator.java | 6 +- .../rest/intelligence/v2/OperatorType.java | 20 ++- .../intelligence/v2/PrebuiltOperator.java | 8 +- .../twilio/rest/intelligence/v2/Service.java | 8 +- .../rest/intelligence/v2/Transcript.java | 8 +- .../intelligence/v2/TranscriptCreator.java | 13 +- .../v2/transcript/OperatorResult.java | 8 +- .../rest/ipmessaging/v1/Credential.java | 8 +- .../rest/ipmessaging/v1/service/Channel.java | 6 +- .../rest/ipmessaging/v1/service/Role.java | 8 +- .../v1/service/user/UserChannel.java | 6 +- .../rest/ipmessaging/v2/Credential.java | 8 +- .../rest/ipmessaging/v2/service/Binding.java | 6 +- .../rest/ipmessaging/v2/service/Channel.java | 6 +- .../rest/ipmessaging/v2/service/Role.java | 8 +- .../v2/service/channel/Webhook.java | 2 +- .../v2/service/user/UserBinding.java | 6 +- .../v2/service/user/UserChannel.java | 12 +- .../twilio/rest/knowledge/v1/Knowledge.java | 23 +-- .../twilio/rest/lookups/v2/PhoneNumber.java | 6 +- .../marketplace/v1/ReferralConversion.java | 2 +- .../installedaddon/InstalledAddOnUsage.java | 2 +- .../rest/messaging/v1/BrandRegistration.java | 22 ++- .../com/twilio/rest/messaging/v1/Service.java | 6 +- .../messaging/v1/TollfreeVerification.java | 16 +- .../v1/brandregistration/BrandVetting.java | 10 +- .../rest/messaging/v2/ChannelsSender.java | 145 +++++++++++++++--- .../com/twilio/rest/notify/v1/Credential.java | 8 +- .../rest/notify/v1/service/Binding.java | 2 +- .../rest/notify/v1/service/Notification.java | 6 +- .../v1/service/NotificationCreator.java | 44 +++--- .../rest/numbers/v1/PortingPortability.java | 8 +- .../numbers/v1/PortingPortabilityFetcher.java | 2 +- .../v1/PortingWebhookConfigurationDelete.java | 2 +- .../numbers/v2/AuthorizationDocument.java | 6 +- .../v2/AuthorizationDocumentCreator.java | 2 +- .../numbers/v2/BulkHostedNumberOrder.java | 8 +- .../twilio/rest/numbers/v2/BundleClone.java | 6 +- .../rest/numbers/v2/HostedNumberOrder.java | 14 +- .../numbers/v2/HostedNumberOrderCreator.java | 4 +- .../DependentHostedNumberOrder.java | 6 +- .../v2/regulatorycompliance/Bundle.java | 6 +- .../v2/regulatorycompliance/EndUser.java | 8 +- .../regulatorycompliance/EndUserCreator.java | 11 +- .../regulatorycompliance/EndUserUpdater.java | 10 +- .../v2/regulatorycompliance/Regulation.java | 6 +- .../SupportingDocument.java | 6 +- .../SupportingDocumentCreator.java | 13 +- .../SupportingDocumentUpdater.java | 12 +- .../bundle/BundleCopy.java | 6 +- .../bundle/Evaluation.java | 6 +- .../bundle/ReplaceItems.java | 6 +- .../hostedNumbers/AuthorizationDocument.java | 6 +- .../hostedNumbers/HostedNumberOrder.java | 12 +- .../HostedNumberOrderCreator.java | 2 +- .../DependentHostedNumberOrder.java | 12 +- .../marketplace/InstalledAddOnCreator.java | 10 +- .../marketplace/InstalledAddOnUpdater.java | 9 +- .../previewiam/organizations/Account.java | 6 +- .../organizations/RoleAssignment.java | 2 +- .../rest/previewiam/organizations/User.java | 4 +- .../rest/pricing/v1/messaging/Country.java | 2 +- .../rest/pricing/v1/phonenumber/Country.java | 2 +- .../twilio/rest/pricing/v1/voice/Country.java | 2 +- .../twilio/rest/pricing/v1/voice/Number.java | 2 +- .../rest/pricing/v1/voice/NumberFetcher.java | 3 +- .../com/twilio/rest/pricing/v2/Country.java | 2 +- .../com/twilio/rest/pricing/v2/Number.java | 2 +- .../twilio/rest/pricing/v2/NumberFetcher.java | 2 +- .../twilio/rest/pricing/v2/voice/Country.java | 2 +- .../twilio/rest/pricing/v2/voice/Number.java | 2 +- .../rest/pricing/v2/voice/NumberFetcher.java | 2 +- .../com/twilio/rest/proxy/v1/Service.java | 14 +- .../twilio/rest/proxy/v1/service/Session.java | 12 +- .../rest/proxy/v1/service/SessionCreator.java | 18 +-- .../proxy/v1/service/session/Interaction.java | 18 +-- .../participant/MessageInteraction.java | 18 +-- .../rest/serverless/v1/service/Build.java | 12 +- .../v1/service/asset/AssetVersion.java | 6 +- .../v1/service/build/BuildStatus.java | 6 +- .../v1/service/environment/Log.java | 30 +--- .../v1/service/function/FunctionVersion.java | 6 +- .../java/com/twilio/rest/studio/v1/Flow.java | 6 +- .../rest/studio/v1/flow/Engagement.java | 6 +- .../studio/v1/flow/EngagementCreator.java | 17 +- .../twilio/rest/studio/v1/flow/Execution.java | 8 +- .../rest/studio/v1/flow/ExecutionCreator.java | 17 +- .../java/com/twilio/rest/studio/v2/Flow.java | 12 +- .../twilio/rest/studio/v2/FlowCreator.java | 13 +- .../twilio/rest/studio/v2/FlowUpdater.java | 10 +- .../twilio/rest/studio/v2/FlowValidate.java | 6 +- .../rest/studio/v2/FlowValidateUpdater.java | 14 +- .../twilio/rest/studio/v2/flow/Execution.java | 8 +- .../rest/studio/v2/flow/ExecutionCreator.java | 17 +- .../rest/studio/v2/flow/FlowRevision.java | 6 +- .../twilio/rest/supersim/v1/EsimProfile.java | 6 +- .../com/twilio/rest/supersim/v1/Fleet.java | 6 +- .../twilio/rest/supersim/v1/IpCommand.java | 18 +-- .../rest/supersim/v1/SettingsUpdate.java | 6 +- .../java/com/twilio/rest/supersim/v1/Sim.java | 6 +- .../twilio/rest/supersim/v1/SmsCommand.java | 12 +- .../twilio/rest/supersim/v1/UsageRecord.java | 2 +- .../rest/supersim/v1/sim/BillingPeriod.java | 6 +- .../rest/supersim/v1/sim/SimIpAddress.java | 6 +- .../rest/sync/v1/service/DocumentCreator.java | 8 +- .../rest/sync/v1/service/DocumentUpdater.java | 7 +- .../v1/service/synclist/SyncListItem.java | 2 +- .../service/synclist/SyncListItemCreator.java | 10 +- .../service/synclist/SyncListItemUpdater.java | 7 +- .../sync/v1/service/syncmap/SyncMapItem.java | 2 +- .../service/syncmap/SyncMapItemCreator.java | 10 +- .../service/syncmap/SyncMapItemUpdater.java | 7 +- .../v1/service/syncstream/StreamMessage.java | 2 +- .../syncstream/StreamMessageCreator.java | 10 +- .../twilio/rest/taskrouter/v1/Workspace.java | 6 +- .../rest/taskrouter/v1/workspace/Task.java | 6 +- .../taskrouter/v1/workspace/TaskQueue.java | 6 +- .../v1/workspace/task/Reservation.java | 8 +- .../v1/workspace/worker/Reservation.java | 8 +- .../com/twilio/rest/trunking/v1/Trunk.java | 12 +- .../rest/trunking/v1/trunk/PhoneNumber.java | 6 +- .../rest/trunking/v1/trunk/Recording.java | 12 +- .../v1/ComplianceRegistrationInquiries.java | 4 +- .../ComplianceTollfreeInquiriesCreator.java | 2 +- .../rest/trusthub/v1/CustomerProfiles.java | 6 +- .../rest/trusthub/v1/EndUserCreator.java | 11 +- .../rest/trusthub/v1/EndUserUpdater.java | 10 +- .../rest/trusthub/v1/SupportingDocument.java | 6 +- .../v1/SupportingDocumentCreator.java | 13 +- .../v1/SupportingDocumentUpdater.java | 12 +- .../rest/trusthub/v1/TrustProducts.java | 6 +- .../CustomerProfilesEvaluations.java | 6 +- .../TrustProductsEvaluations.java | 6 +- .../java/com/twilio/rest/verify/v2/Form.java | 8 +- .../rest/verify/v2/VerificationAttempt.java | 12 +- .../rest/verify/v2/service/AccessToken.java | 8 +- .../rest/verify/v2/service/Verification.java | 8 +- .../verify/v2/service/VerificationCheck.java | 6 +- .../v2/service/VerificationCreator.java | 19 ++- .../rest/verify/v2/service/Webhook.java | 18 +-- .../verify/v2/service/entity/Challenge.java | 18 +-- .../v2/service/entity/ChallengeCreator.java | 27 +--- .../v2/service/entity/ChallengeUpdater.java | 7 +- .../rest/verify/v2/service/entity/Factor.java | 12 +- .../verify/v2/service/entity/NewFactor.java | 14 +- .../v2/service/entity/NewFactorCreator.java | 8 +- .../com/twilio/rest/video/v1/Composition.java | 12 +- .../twilio/rest/video/v1/CompositionHook.java | 6 +- .../com/twilio/rest/video/v1/Recording.java | 26 ++-- .../java/com/twilio/rest/video/v1/Room.java | 20 +-- .../rest/video/v1/room/Participant.java | 6 +- .../rest/video/v1/room/RoomRecording.java | 26 ++-- .../video/v1/room/participant/Anonymize.java | 6 +- .../v1/room/participant/PublishedTrack.java | 6 +- .../v1/room/participant/SubscribedTrack.java | 6 +- .../com/twilio/rest/wireless/v1/Command.java | 24 +-- .../java/com/twilio/rest/wireless/v1/Sim.java | 12 +- src/test/java/com/twilio/ClusterTest.java | 10 +- 270 files changed, 1365 insertions(+), 1478 deletions(-) diff --git a/src/main/java/com/twilio/rest/accounts/v1/BulkConsents.java b/src/main/java/com/twilio/rest/accounts/v1/BulkConsents.java index 2ef3ff3e24..8c8eee79da 100644 --- a/src/main/java/com/twilio/rest/accounts/v1/BulkConsents.java +++ b/src/main/java/com/twilio/rest/accounts/v1/BulkConsents.java @@ -38,9 +38,7 @@ public class BulkConsents extends Resource { private static final long serialVersionUID = 126137950684284L; - public static BulkConsentsCreator creator( - final List> items - ) { + public static BulkConsentsCreator creator(final List items) { return new BulkConsentsCreator(items); } diff --git a/src/main/java/com/twilio/rest/accounts/v1/BulkConsentsCreator.java b/src/main/java/com/twilio/rest/accounts/v1/BulkConsentsCreator.java index 93a1b73bbf..ad5acc7da5 100644 --- a/src/main/java/com/twilio/rest/accounts/v1/BulkConsentsCreator.java +++ b/src/main/java/com/twilio/rest/accounts/v1/BulkConsentsCreator.java @@ -16,8 +16,6 @@ import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; -import com.twilio.converter.Converter; -import com.twilio.converter.Converter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; @@ -29,23 +27,21 @@ import com.twilio.rest.Domains; import java.util.List; import java.util.List; -import java.util.Map; -import java.util.Map; public class BulkConsentsCreator extends Creator { - private List> items; + private List items; - public BulkConsentsCreator(final List> items) { + public BulkConsentsCreator(final List items) { this.items = items; } - public BulkConsentsCreator setItems(final List> items) { + public BulkConsentsCreator setItems(final List items) { this.items = items; return this; } - public BulkConsentsCreator setItems(final Map items) { + public BulkConsentsCreator setItems(final Object items) { return setItems(Promoter.listOfOne(items)); } @@ -89,8 +85,8 @@ public BulkConsents create(final TwilioRestClient client) { private void addPostParams(final Request request) { if (items != null) { - for (Map prop : items) { - request.addPostParam("Items", Converter.mapToJson(prop)); + for (Object prop : items) { + request.addPostParam("Items", prop.toString()); } } } diff --git a/src/main/java/com/twilio/rest/accounts/v1/BulkContacts.java b/src/main/java/com/twilio/rest/accounts/v1/BulkContacts.java index fbb28d1b7f..b4ff307a19 100644 --- a/src/main/java/com/twilio/rest/accounts/v1/BulkContacts.java +++ b/src/main/java/com/twilio/rest/accounts/v1/BulkContacts.java @@ -38,9 +38,7 @@ public class BulkContacts extends Resource { private static final long serialVersionUID = 126137950684284L; - public static BulkContactsCreator creator( - final List> items - ) { + public static BulkContactsCreator creator(final List items) { return new BulkContactsCreator(items); } diff --git a/src/main/java/com/twilio/rest/accounts/v1/BulkContactsCreator.java b/src/main/java/com/twilio/rest/accounts/v1/BulkContactsCreator.java index 0f3653b994..2939c5c60d 100644 --- a/src/main/java/com/twilio/rest/accounts/v1/BulkContactsCreator.java +++ b/src/main/java/com/twilio/rest/accounts/v1/BulkContactsCreator.java @@ -16,8 +16,6 @@ import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; -import com.twilio.converter.Converter; -import com.twilio.converter.Converter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; @@ -29,23 +27,21 @@ import com.twilio.rest.Domains; import java.util.List; import java.util.List; -import java.util.Map; -import java.util.Map; public class BulkContactsCreator extends Creator { - private List> items; + private List items; - public BulkContactsCreator(final List> items) { + public BulkContactsCreator(final List items) { this.items = items; } - public BulkContactsCreator setItems(final List> items) { + public BulkContactsCreator setItems(final List items) { this.items = items; return this; } - public BulkContactsCreator setItems(final Map items) { + public BulkContactsCreator setItems(final Object items) { return setItems(Promoter.listOfOne(items)); } @@ -89,8 +85,8 @@ public BulkContacts create(final TwilioRestClient client) { private void addPostParams(final Request request) { if (items != null) { - for (Map prop : items) { - request.addPostParam("Items", Converter.mapToJson(prop)); + for (Object prop : items) { + request.addPostParam("Items", prop.toString()); } } } diff --git a/src/main/java/com/twilio/rest/api/v2010/Account.java b/src/main/java/com/twilio/rest/api/v2010/Account.java index 7ab47a5b18..814acb9477 100644 --- a/src/main/java/com/twilio/rest/api/v2010/Account.java +++ b/src/main/java/com/twilio/rest/api/v2010/Account.java @@ -113,9 +113,9 @@ public static Account fromJson( private final String friendlyName; private final String ownerAccountSid; private final String sid; - private final Account.Status status; + private final Status status; private final Map subresourceUris; - private final Account.Type type; + private final Type type; private final String uri; @JsonCreator @@ -126,12 +126,12 @@ private Account( @JsonProperty("friendly_name") final String friendlyName, @JsonProperty("owner_account_sid") final String ownerAccountSid, @JsonProperty("sid") final String sid, - @JsonProperty("status") final Account.Status status, + @JsonProperty("status") final Status status, @JsonProperty("subresource_uris") final Map< String, String > subresourceUris, - @JsonProperty("type") final Account.Type type, + @JsonProperty("type") final Type type, @JsonProperty("uri") final String uri ) { this.authToken = authToken; @@ -170,7 +170,7 @@ public final String getSid() { return this.sid; } - public final Account.Status getStatus() { + public final Status getStatus() { return this.status; } @@ -178,7 +178,7 @@ public final Map getSubresourceUris() { return this.subresourceUris; } - public final Account.Type getType() { + public final Type getType() { return this.type; } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/AuthorizedConnectApp.java b/src/main/java/com/twilio/rest/api/v2010/account/AuthorizedConnectApp.java index f7e1d9f67f..a58a35511e 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/AuthorizedConnectApp.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/AuthorizedConnectApp.java @@ -113,7 +113,7 @@ public static AuthorizedConnectApp fromJson( private final String connectAppFriendlyName; private final URI connectAppHomepageUrl; private final String connectAppSid; - private final List permissions; + private final List permissions; private final String uri; @JsonCreator @@ -132,9 +132,7 @@ private AuthorizedConnectApp( "connect_app_homepage_url" ) final URI connectAppHomepageUrl, @JsonProperty("connect_app_sid") final String connectAppSid, - @JsonProperty("permissions") final List< - AuthorizedConnectApp.Permission - > permissions, + @JsonProperty("permissions") final List permissions, @JsonProperty("uri") final String uri ) { this.accountSid = accountSid; @@ -171,7 +169,7 @@ public final String getConnectAppSid() { return this.connectAppSid; } - public final List getPermissions() { + public final List getPermissions() { return this.permissions; } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/Call.java b/src/main/java/com/twilio/rest/api/v2010/account/Call.java index 8eaf7c203d..59e9b2a099 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/Call.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/Call.java @@ -189,7 +189,7 @@ public static Call fromJson( private final String from; private final String fromFormatted; private final String phoneNumberSid; - private final Call.Status status; + private final Status status; private final ZonedDateTime startTime; private final ZonedDateTime endTime; private final String duration; @@ -218,13 +218,13 @@ private Call( @JsonProperty("from") final String from, @JsonProperty("from_formatted") final String fromFormatted, @JsonProperty("phone_number_sid") final String phoneNumberSid, - @JsonProperty("status") final Call.Status status, + @JsonProperty("status") final Status status, @JsonProperty("start_time") final String startTime, @JsonProperty("end_time") final String endTime, @JsonProperty("duration") final String duration, @JsonProperty("price") final String price, @JsonProperty("price_unit") @JsonDeserialize( - using = com.twilio.converter.CurrencyDeserializer.class + using = CurrencyDeserializer.class ) final Currency priceUnit, @JsonProperty("direction") final String direction, @JsonProperty("answered_by") final String answeredBy, @@ -308,7 +308,7 @@ public final String getPhoneNumberSid() { return this.phoneNumberSid; } - public final Call.Status getStatus() { + public final Status getStatus() { return this.status; } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/Conference.java b/src/main/java/com/twilio/rest/api/v2010/account/Conference.java index bcb13ce3df..a35e39b51c 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/Conference.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/Conference.java @@ -120,10 +120,10 @@ public static Conference fromJson( private final String friendlyName; private final String region; private final String sid; - private final Conference.Status status; + private final Status status; private final String uri; private final Map subresourceUris; - private final Conference.ReasonConferenceEnded reasonConferenceEnded; + private final ReasonConferenceEnded reasonConferenceEnded; private final String callSidEndingConference; @JsonCreator @@ -135,7 +135,7 @@ private Conference( @JsonProperty("friendly_name") final String friendlyName, @JsonProperty("region") final String region, @JsonProperty("sid") final String sid, - @JsonProperty("status") final Conference.Status status, + @JsonProperty("status") final Status status, @JsonProperty("uri") final String uri, @JsonProperty("subresource_uris") final Map< String, @@ -143,7 +143,7 @@ private Conference( > subresourceUris, @JsonProperty( "reason_conference_ended" - ) final Conference.ReasonConferenceEnded reasonConferenceEnded, + ) final ReasonConferenceEnded reasonConferenceEnded, @JsonProperty( "call_sid_ending_conference" ) final String callSidEndingConference @@ -190,7 +190,7 @@ public final String getSid() { return this.sid; } - public final Conference.Status getStatus() { + public final Status getStatus() { return this.status; } @@ -202,7 +202,7 @@ public final Map getSubresourceUris() { return this.subresourceUris; } - public final Conference.ReasonConferenceEnded getReasonConferenceEnded() { + public final ReasonConferenceEnded getReasonConferenceEnded() { return this.reasonConferenceEnded; } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/ConnectApp.java b/src/main/java/com/twilio/rest/api/v2010/account/ConnectApp.java index 64e5e6198c..da84d010e6 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/ConnectApp.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/ConnectApp.java @@ -131,7 +131,7 @@ public static ConnectApp fromJson( private final String description; private final String friendlyName; private final URI homepageUrl; - private final List permissions; + private final List permissions; private final String sid; private final String uri; @@ -149,9 +149,7 @@ private ConnectApp( @JsonProperty("description") final String description, @JsonProperty("friendly_name") final String friendlyName, @JsonProperty("homepage_url") final URI homepageUrl, - @JsonProperty("permissions") final List< - ConnectApp.Permission - > permissions, + @JsonProperty("permissions") final List permissions, @JsonProperty("sid") final String sid, @JsonProperty("uri") final String uri ) { @@ -200,7 +198,7 @@ public final URI getHomepageUrl() { return this.homepageUrl; } - public final List getPermissions() { + public final List getPermissions() { return this.permissions; } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/IncomingPhoneNumber.java b/src/main/java/com/twilio/rest/api/v2010/account/IncomingPhoneNumber.java index 6c202374e5..f59bdac73f 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/IncomingPhoneNumber.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/IncomingPhoneNumber.java @@ -153,7 +153,7 @@ public static IncomingPhoneNumber fromJson( private final String accountSid; private final String addressSid; - private final IncomingPhoneNumber.AddressRequirement addressRequirements; + private final AddressRequirement addressRequirements; private final String apiVersion; private final Boolean beta; private final PhoneNumberCapabilities capabilities; @@ -173,16 +173,16 @@ public static IncomingPhoneNumber fromJson( private final HttpMethod statusCallbackMethod; private final String trunkSid; private final String uri; - private final IncomingPhoneNumber.VoiceReceiveMode voiceReceiveMode; + private final VoiceReceiveMode voiceReceiveMode; private final String voiceApplicationSid; private final Boolean voiceCallerIdLookup; private final HttpMethod voiceFallbackMethod; private final URI voiceFallbackUrl; private final HttpMethod voiceMethod; private final URI voiceUrl; - private final IncomingPhoneNumber.EmergencyStatus emergencyStatus; + private final EmergencyStatus emergencyStatus; private final String emergencyAddressSid; - private final IncomingPhoneNumber.EmergencyAddressStatus emergencyAddressStatus; + private final EmergencyAddressStatus emergencyAddressStatus; private final String bundleSid; private final String status; @@ -192,7 +192,7 @@ private IncomingPhoneNumber( @JsonProperty("address_sid") final String addressSid, @JsonProperty( "address_requirements" - ) final IncomingPhoneNumber.AddressRequirement addressRequirements, + ) final AddressRequirement addressRequirements, @JsonProperty("api_version") final String apiVersion, @JsonProperty("beta") final Boolean beta, @JsonProperty( @@ -220,7 +220,7 @@ private IncomingPhoneNumber( @JsonProperty("uri") final String uri, @JsonProperty( "voice_receive_mode" - ) final IncomingPhoneNumber.VoiceReceiveMode voiceReceiveMode, + ) final VoiceReceiveMode voiceReceiveMode, @JsonProperty("voice_application_sid") final String voiceApplicationSid, @JsonProperty( "voice_caller_id_lookup" @@ -231,13 +231,11 @@ private IncomingPhoneNumber( @JsonProperty("voice_fallback_url") final URI voiceFallbackUrl, @JsonProperty("voice_method") final HttpMethod voiceMethod, @JsonProperty("voice_url") final URI voiceUrl, - @JsonProperty( - "emergency_status" - ) final IncomingPhoneNumber.EmergencyStatus emergencyStatus, + @JsonProperty("emergency_status") final EmergencyStatus emergencyStatus, @JsonProperty("emergency_address_sid") final String emergencyAddressSid, @JsonProperty( "emergency_address_status" - ) final IncomingPhoneNumber.EmergencyAddressStatus emergencyAddressStatus, + ) final EmergencyAddressStatus emergencyAddressStatus, @JsonProperty("bundle_sid") final String bundleSid, @JsonProperty("status") final String status ) { @@ -285,7 +283,7 @@ public final String getAddressSid() { return this.addressSid; } - public final IncomingPhoneNumber.AddressRequirement getAddressRequirements() { + public final AddressRequirement getAddressRequirements() { return this.addressRequirements; } @@ -365,7 +363,7 @@ public final String getUri() { return this.uri; } - public final IncomingPhoneNumber.VoiceReceiveMode getVoiceReceiveMode() { + public final VoiceReceiveMode getVoiceReceiveMode() { return this.voiceReceiveMode; } @@ -393,7 +391,7 @@ public final URI getVoiceUrl() { return this.voiceUrl; } - public final IncomingPhoneNumber.EmergencyStatus getEmergencyStatus() { + public final EmergencyStatus getEmergencyStatus() { return this.emergencyStatus; } @@ -401,7 +399,7 @@ public final String getEmergencyAddressSid() { return this.emergencyAddressSid; } - public final IncomingPhoneNumber.EmergencyAddressStatus getEmergencyAddressStatus() { + public final EmergencyAddressStatus getEmergencyAddressStatus() { return this.emergencyAddressStatus; } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/Message.java b/src/main/java/com/twilio/rest/api/v2010/account/Message.java index 548b52b068..dce011b3df 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/Message.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/Message.java @@ -209,7 +209,7 @@ public static Message fromJson( private final String body; private final String numSegments; - private final Message.Direction direction; + private final Direction direction; private final com.twilio.type.PhoneNumber from; private final String to; private final ZonedDateTime dateUpdated; @@ -218,7 +218,7 @@ public static Message fromJson( private final String uri; private final String accountSid; private final String numMedia; - private final Message.Status status; + private final Status status; private final String messagingServiceSid; private final String sid; private final ZonedDateTime dateSent; @@ -232,7 +232,7 @@ public static Message fromJson( private Message( @JsonProperty("body") final String body, @JsonProperty("num_segments") final String numSegments, - @JsonProperty("direction") final Message.Direction direction, + @JsonProperty("direction") final Direction direction, @JsonProperty("from") final com.twilio.type.PhoneNumber from, @JsonProperty("to") final String to, @JsonProperty("date_updated") final String dateUpdated, @@ -241,14 +241,14 @@ private Message( @JsonProperty("uri") final String uri, @JsonProperty("account_sid") final String accountSid, @JsonProperty("num_media") final String numMedia, - @JsonProperty("status") final Message.Status status, + @JsonProperty("status") final Status status, @JsonProperty("messaging_service_sid") final String messagingServiceSid, @JsonProperty("sid") final String sid, @JsonProperty("date_sent") final String dateSent, @JsonProperty("date_created") final String dateCreated, @JsonProperty("error_code") final Integer errorCode, @JsonProperty("price_unit") @JsonDeserialize( - using = com.twilio.converter.CurrencyDeserializer.class + using = CurrencyDeserializer.class ) final Currency priceUnit, @JsonProperty("api_version") final String apiVersion, @JsonProperty("subresource_uris") final Map< @@ -286,7 +286,7 @@ public final String getNumSegments() { return this.numSegments; } - public final Message.Direction getDirection() { + public final Direction getDirection() { return this.direction; } @@ -322,7 +322,7 @@ public final String getNumMedia() { return this.numMedia; } - public final Message.Status getStatus() { + public final Status getStatus() { return this.status; } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/MessageCreator.java b/src/main/java/com/twilio/rest/api/v2010/account/MessageCreator.java index 4ee0387373..c938512a64 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/MessageCreator.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/MessageCreator.java @@ -318,7 +318,7 @@ public Message create(final TwilioRestClient client) { "{" + "AccountSid" + "}", this.pathAccountSid.toString() ); - path = path.replace("{" + "To" + "}", this.to.encode("utf-8")); + path = path.replace("{" + "To" + "}", this.to.toString()); Request request = new Request( HttpMethod.POST, diff --git a/src/main/java/com/twilio/rest/api/v2010/account/Recording.java b/src/main/java/com/twilio/rest/api/v2010/account/Recording.java index 88e79667f7..e36eee0d13 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/Recording.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/Recording.java @@ -125,9 +125,9 @@ public static Recording fromJson( private final String sid; private final String price; private final String priceUnit; - private final Recording.Status status; + private final Status status; private final Integer channels; - private final Recording.Source source; + private final Source source; private final Integer errorCode; private final String uri; private final Map encryptionDetails; @@ -147,9 +147,9 @@ private Recording( @JsonProperty("sid") final String sid, @JsonProperty("price") final String price, @JsonProperty("price_unit") final String priceUnit, - @JsonProperty("status") final Recording.Status status, + @JsonProperty("status") final Status status, @JsonProperty("channels") final Integer channels, - @JsonProperty("source") final Recording.Source source, + @JsonProperty("source") final Source source, @JsonProperty("error_code") final Integer errorCode, @JsonProperty("uri") final String uri, @JsonProperty("encryption_details") final Map< @@ -227,7 +227,7 @@ public final String getPriceUnit() { return this.priceUnit; } - public final Recording.Status getStatus() { + public final Status getStatus() { return this.status; } @@ -235,7 +235,7 @@ public final Integer getChannels() { return this.channels; } - public final Recording.Source getSource() { + public final Source getSource() { return this.source; } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/Transcription.java b/src/main/java/com/twilio/rest/api/v2010/account/Transcription.java index a9525ed472..e801e42350 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/Transcription.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/Transcription.java @@ -124,7 +124,7 @@ public static Transcription fromJson( private final Currency priceUnit; private final String recordingSid; private final String sid; - private final Transcription.Status status; + private final Status status; private final String transcriptionText; private final String type; private final String uri; @@ -138,11 +138,11 @@ private Transcription( @JsonProperty("duration") final String duration, @JsonProperty("price") final BigDecimal price, @JsonProperty("price_unit") @JsonDeserialize( - using = com.twilio.converter.CurrencyDeserializer.class + using = CurrencyDeserializer.class ) final Currency priceUnit, @JsonProperty("recording_sid") final String recordingSid, @JsonProperty("sid") final String sid, - @JsonProperty("status") final Transcription.Status status, + @JsonProperty("status") final Status status, @JsonProperty("transcription_text") final String transcriptionText, @JsonProperty("type") final String type, @JsonProperty("uri") final String uri @@ -198,7 +198,7 @@ public final String getSid() { return this.sid; } - public final Transcription.Status getStatus() { + public final Status getStatus() { return this.status; } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/ValidationRequestCreator.java b/src/main/java/com/twilio/rest/api/v2010/account/ValidationRequestCreator.java index b98f8f62b9..15486f1597 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/ValidationRequestCreator.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/ValidationRequestCreator.java @@ -115,7 +115,7 @@ public ValidationRequest create(final TwilioRestClient client) { path = path.replace( "{" + "PhoneNumber" + "}", - this.phoneNumber.encode("utf-8") + this.phoneNumber.toString() ); Request request = new Request( diff --git a/src/main/java/com/twilio/rest/api/v2010/account/address/DependentPhoneNumber.java b/src/main/java/com/twilio/rest/api/v2010/account/address/DependentPhoneNumber.java index 3c65422d55..ff8e7f4f78 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/address/DependentPhoneNumber.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/address/DependentPhoneNumber.java @@ -113,7 +113,7 @@ public static DependentPhoneNumber fromJson( private final URI smsFallbackUrl; private final HttpMethod smsMethod; private final URI smsUrl; - private final DependentPhoneNumber.AddressRequirement addressRequirements; + private final AddressRequirement addressRequirements; private final Map capabilities; private final URI statusCallback; private final HttpMethod statusCallbackMethod; @@ -121,7 +121,7 @@ public static DependentPhoneNumber fromJson( private final String smsApplicationSid; private final String voiceApplicationSid; private final String trunkSid; - private final DependentPhoneNumber.EmergencyStatus emergencyStatus; + private final EmergencyStatus emergencyStatus; private final String emergencyAddressSid; private final String uri; @@ -150,7 +150,7 @@ private DependentPhoneNumber( @JsonProperty("sms_url") final URI smsUrl, @JsonProperty( "address_requirements" - ) final DependentPhoneNumber.AddressRequirement addressRequirements, + ) final AddressRequirement addressRequirements, @JsonProperty("capabilities") final Map capabilities, @JsonProperty("status_callback") final URI statusCallback, @JsonProperty( @@ -160,9 +160,7 @@ private DependentPhoneNumber( @JsonProperty("sms_application_sid") final String smsApplicationSid, @JsonProperty("voice_application_sid") final String voiceApplicationSid, @JsonProperty("trunk_sid") final String trunkSid, - @JsonProperty( - "emergency_status" - ) final DependentPhoneNumber.EmergencyStatus emergencyStatus, + @JsonProperty("emergency_status") final EmergencyStatus emergencyStatus, @JsonProperty("emergency_address_sid") final String emergencyAddressSid, @JsonProperty("uri") final String uri ) { @@ -254,7 +252,7 @@ public final URI getSmsUrl() { return this.smsUrl; } - public final DependentPhoneNumber.AddressRequirement getAddressRequirements() { + public final AddressRequirement getAddressRequirements() { return this.addressRequirements; } @@ -286,7 +284,7 @@ public final String getTrunkSid() { return this.trunkSid; } - public final DependentPhoneNumber.EmergencyStatus getEmergencyStatus() { + public final EmergencyStatus getEmergencyStatus() { return this.emergencyStatus; } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/call/PaymentCreator.java b/src/main/java/com/twilio/rest/api/v2010/account/call/PaymentCreator.java index b92f9468f1..c34dfa3202 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/call/PaymentCreator.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/call/PaymentCreator.java @@ -31,8 +31,6 @@ import java.math.BigDecimal; import java.net.URI; import java.net.URI; -import java.util.Map; -import java.util.Map; public class PaymentCreator extends Creator { @@ -46,7 +44,7 @@ public class PaymentCreator extends Creator { private String description; private String input; private Integer minPostalCodeLength; - private Map parameter; + private Object parameter; private String paymentConnector; private Payment.PaymentMethod paymentMethod; private Boolean postalCode; @@ -125,7 +123,7 @@ public PaymentCreator setMinPostalCodeLength( return this; } - public PaymentCreator setParameter(final Map parameter) { + public PaymentCreator setParameter(final Object parameter) { this.parameter = parameter; return this; } @@ -251,7 +249,10 @@ private void addPostParams(final Request request) { ); } if (parameter != null) { - request.addPostParam("Parameter", Converter.mapToJson(parameter)); + request.addPostParam( + "Parameter", + Converter.objectToJson(parameter) + ); } if (paymentConnector != null) { request.addPostParam("PaymentConnector", paymentConnector); diff --git a/src/main/java/com/twilio/rest/api/v2010/account/call/Recording.java b/src/main/java/com/twilio/rest/api/v2010/account/call/Recording.java index 12054b2b44..23d275246f 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/call/Recording.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/call/Recording.java @@ -99,7 +99,7 @@ public static RecordingReader reader( public static RecordingUpdater updater( final String pathCallSid, final String pathSid, - final Recording.Status status + final Status status ) { return new RecordingUpdater(pathCallSid, pathSid, status); } @@ -108,7 +108,7 @@ public static RecordingUpdater updater( final String pathAccountSid, final String pathCallSid, final String pathSid, - final Recording.Status status + final Status status ) { return new RecordingUpdater( pathAccountSid, @@ -174,9 +174,9 @@ public static Recording fromJson( private final String uri; private final Map encryptionDetails; private final Currency priceUnit; - private final Recording.Status status; + private final Status status; private final Integer channels; - private final Recording.Source source; + private final Source source; private final Integer errorCode; private final String track; @@ -198,11 +198,11 @@ private Recording( Object > encryptionDetails, @JsonProperty("price_unit") @JsonDeserialize( - using = com.twilio.converter.CurrencyDeserializer.class + using = CurrencyDeserializer.class ) final Currency priceUnit, - @JsonProperty("status") final Recording.Status status, + @JsonProperty("status") final Status status, @JsonProperty("channels") final Integer channels, - @JsonProperty("source") final Recording.Source source, + @JsonProperty("source") final Source source, @JsonProperty("error_code") final Integer errorCode, @JsonProperty("track") final String track ) { @@ -278,7 +278,7 @@ public final Currency getPriceUnit() { return this.priceUnit; } - public final Recording.Status getStatus() { + public final Status getStatus() { return this.status; } @@ -286,7 +286,7 @@ public final Integer getChannels() { return this.channels; } - public final Recording.Source getSource() { + public final Source getSource() { return this.source; } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/call/Siprec.java b/src/main/java/com/twilio/rest/api/v2010/account/call/Siprec.java index 376b870d65..87912457a3 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/call/Siprec.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/call/Siprec.java @@ -52,7 +52,7 @@ public static SiprecCreator creator( public static SiprecUpdater updater( final String pathCallSid, final String pathSid, - final Siprec.UpdateStatus status + final UpdateStatus status ) { return new SiprecUpdater(pathCallSid, pathSid, status); } @@ -61,7 +61,7 @@ public static SiprecUpdater updater( final String pathAccountSid, final String pathCallSid, final String pathSid, - final Siprec.UpdateStatus status + final UpdateStatus status ) { return new SiprecUpdater(pathAccountSid, pathCallSid, pathSid, status); } @@ -113,7 +113,7 @@ public static Siprec fromJson( private final String accountSid; private final String callSid; private final String name; - private final Siprec.Status status; + private final Status status; private final ZonedDateTime dateUpdated; private final String uri; @@ -123,7 +123,7 @@ private Siprec( @JsonProperty("account_sid") final String accountSid, @JsonProperty("call_sid") final String callSid, @JsonProperty("name") final String name, - @JsonProperty("status") final Siprec.Status status, + @JsonProperty("status") final Status status, @JsonProperty("date_updated") final String dateUpdated, @JsonProperty("uri") final String uri ) { @@ -152,7 +152,7 @@ public final String getName() { return this.name; } - public final Siprec.Status getStatus() { + public final Status getStatus() { return this.status; } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/call/Stream.java b/src/main/java/com/twilio/rest/api/v2010/account/call/Stream.java index c646360c75..6fcf583011 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/call/Stream.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/call/Stream.java @@ -57,7 +57,7 @@ public static StreamCreator creator( public static StreamUpdater updater( final String pathCallSid, final String pathSid, - final Stream.UpdateStatus status + final UpdateStatus status ) { return new StreamUpdater(pathCallSid, pathSid, status); } @@ -66,7 +66,7 @@ public static StreamUpdater updater( final String pathAccountSid, final String pathCallSid, final String pathSid, - final Stream.UpdateStatus status + final UpdateStatus status ) { return new StreamUpdater(pathAccountSid, pathCallSid, pathSid, status); } @@ -118,7 +118,7 @@ public static Stream fromJson( private final String accountSid; private final String callSid; private final String name; - private final Stream.Status status; + private final Status status; private final ZonedDateTime dateUpdated; private final String uri; @@ -128,7 +128,7 @@ private Stream( @JsonProperty("account_sid") final String accountSid, @JsonProperty("call_sid") final String callSid, @JsonProperty("name") final String name, - @JsonProperty("status") final Stream.Status status, + @JsonProperty("status") final Status status, @JsonProperty("date_updated") final String dateUpdated, @JsonProperty("uri") final String uri ) { @@ -157,7 +157,7 @@ public final String getName() { return this.name; } - public final Stream.Status getStatus() { + public final Status getStatus() { return this.status; } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/call/Transcription.java b/src/main/java/com/twilio/rest/api/v2010/account/call/Transcription.java index 1f1083335a..e7aec1241e 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/call/Transcription.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/call/Transcription.java @@ -52,7 +52,7 @@ public static TranscriptionCreator creator( public static TranscriptionUpdater updater( final String pathCallSid, final String pathSid, - final Transcription.UpdateStatus status + final UpdateStatus status ) { return new TranscriptionUpdater(pathCallSid, pathSid, status); } @@ -61,7 +61,7 @@ public static TranscriptionUpdater updater( final String pathAccountSid, final String pathCallSid, final String pathSid, - final Transcription.UpdateStatus status + final UpdateStatus status ) { return new TranscriptionUpdater( pathAccountSid, @@ -118,7 +118,7 @@ public static Transcription fromJson( private final String accountSid; private final String callSid; private final String name; - private final Transcription.Status status; + private final Status status; private final ZonedDateTime dateUpdated; private final String uri; @@ -128,7 +128,7 @@ private Transcription( @JsonProperty("account_sid") final String accountSid, @JsonProperty("call_sid") final String callSid, @JsonProperty("name") final String name, - @JsonProperty("status") final Transcription.Status status, + @JsonProperty("status") final Status status, @JsonProperty("date_updated") final String dateUpdated, @JsonProperty("uri") final String uri ) { @@ -157,7 +157,7 @@ public final String getName() { return this.name; } - public final Transcription.Status getStatus() { + public final Status getStatus() { return this.status; } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/conference/Participant.java b/src/main/java/com/twilio/rest/api/v2010/account/conference/Participant.java index 1eb8a9218a..f386803124 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/conference/Participant.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/conference/Participant.java @@ -183,7 +183,7 @@ public static Participant fromJson( private final Boolean muted; private final Boolean hold; private final Boolean startConferenceOnEnter; - private final Participant.Status status; + private final Status status; private final String queueTime; private final String uri; @@ -205,7 +205,7 @@ private Participant( @JsonProperty( "start_conference_on_enter" ) final Boolean startConferenceOnEnter, - @JsonProperty("status") final Participant.Status status, + @JsonProperty("status") final Status status, @JsonProperty("queue_time") final String queueTime, @JsonProperty("uri") final String uri ) { @@ -274,7 +274,7 @@ public final Boolean getStartConferenceOnEnter() { return this.startConferenceOnEnter; } - public final Participant.Status getStatus() { + public final Status getStatus() { return this.status; } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/conference/Recording.java b/src/main/java/com/twilio/rest/api/v2010/account/conference/Recording.java index 0a4e1b2876..cb19e56da8 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/conference/Recording.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/conference/Recording.java @@ -87,7 +87,7 @@ public static RecordingReader reader( public static RecordingUpdater updater( final String pathConferenceSid, final String pathSid, - final Recording.Status status + final Status status ) { return new RecordingUpdater(pathConferenceSid, pathSid, status); } @@ -96,7 +96,7 @@ public static RecordingUpdater updater( final String pathAccountSid, final String pathConferenceSid, final String pathSid, - final Recording.Status status + final Status status ) { return new RecordingUpdater( pathAccountSid, @@ -160,9 +160,9 @@ public static Recording fromJson( private final String sid; private final String price; private final Currency priceUnit; - private final Recording.Status status; + private final Status status; private final Integer channels; - private final Recording.Source source; + private final Source source; private final Integer errorCode; private final Map encryptionDetails; private final String uri; @@ -180,11 +180,11 @@ private Recording( @JsonProperty("sid") final String sid, @JsonProperty("price") final String price, @JsonProperty("price_unit") @JsonDeserialize( - using = com.twilio.converter.CurrencyDeserializer.class + using = CurrencyDeserializer.class ) final Currency priceUnit, - @JsonProperty("status") final Recording.Status status, + @JsonProperty("status") final Status status, @JsonProperty("channels") final Integer channels, - @JsonProperty("source") final Recording.Source source, + @JsonProperty("source") final Source source, @JsonProperty("error_code") final Integer errorCode, @JsonProperty("encryption_details") final Map< String, @@ -255,7 +255,7 @@ public final Currency getPriceUnit() { return this.priceUnit; } - public final Recording.Status getStatus() { + public final Status getStatus() { return this.status; } @@ -263,7 +263,7 @@ public final Integer getChannels() { return this.channels; } - public final Recording.Source getSource() { + public final Source getSource() { return this.source; } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/incomingphonenumber/Local.java b/src/main/java/com/twilio/rest/api/v2010/account/incomingphonenumber/Local.java index 801ff7fc75..cb3531a74c 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/incomingphonenumber/Local.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/incomingphonenumber/Local.java @@ -107,7 +107,7 @@ public static Local fromJson( private final String accountSid; private final String addressSid; - private final Local.AddressRequirement addressRequirements; + private final AddressRequirement addressRequirements; private final String apiVersion; private final Boolean beta; private final PhoneNumberCapabilities capabilities; @@ -127,16 +127,16 @@ public static Local fromJson( private final HttpMethod statusCallbackMethod; private final String trunkSid; private final String uri; - private final Local.VoiceReceiveMode voiceReceiveMode; + private final VoiceReceiveMode voiceReceiveMode; private final String voiceApplicationSid; private final Boolean voiceCallerIdLookup; private final HttpMethod voiceFallbackMethod; private final URI voiceFallbackUrl; private final HttpMethod voiceMethod; private final URI voiceUrl; - private final Local.EmergencyStatus emergencyStatus; + private final EmergencyStatus emergencyStatus; private final String emergencyAddressSid; - private final Local.EmergencyAddressStatus emergencyAddressStatus; + private final EmergencyAddressStatus emergencyAddressStatus; private final String bundleSid; private final String status; @@ -146,7 +146,7 @@ private Local( @JsonProperty("address_sid") final String addressSid, @JsonProperty( "address_requirements" - ) final Local.AddressRequirement addressRequirements, + ) final AddressRequirement addressRequirements, @JsonProperty("api_version") final String apiVersion, @JsonProperty("beta") final Boolean beta, @JsonProperty( @@ -174,7 +174,7 @@ private Local( @JsonProperty("uri") final String uri, @JsonProperty( "voice_receive_mode" - ) final Local.VoiceReceiveMode voiceReceiveMode, + ) final VoiceReceiveMode voiceReceiveMode, @JsonProperty("voice_application_sid") final String voiceApplicationSid, @JsonProperty( "voice_caller_id_lookup" @@ -185,13 +185,11 @@ private Local( @JsonProperty("voice_fallback_url") final URI voiceFallbackUrl, @JsonProperty("voice_method") final HttpMethod voiceMethod, @JsonProperty("voice_url") final URI voiceUrl, - @JsonProperty( - "emergency_status" - ) final Local.EmergencyStatus emergencyStatus, + @JsonProperty("emergency_status") final EmergencyStatus emergencyStatus, @JsonProperty("emergency_address_sid") final String emergencyAddressSid, @JsonProperty( "emergency_address_status" - ) final Local.EmergencyAddressStatus emergencyAddressStatus, + ) final EmergencyAddressStatus emergencyAddressStatus, @JsonProperty("bundle_sid") final String bundleSid, @JsonProperty("status") final String status ) { @@ -239,7 +237,7 @@ public final String getAddressSid() { return this.addressSid; } - public final Local.AddressRequirement getAddressRequirements() { + public final AddressRequirement getAddressRequirements() { return this.addressRequirements; } @@ -319,7 +317,7 @@ public final String getUri() { return this.uri; } - public final Local.VoiceReceiveMode getVoiceReceiveMode() { + public final VoiceReceiveMode getVoiceReceiveMode() { return this.voiceReceiveMode; } @@ -347,7 +345,7 @@ public final URI getVoiceUrl() { return this.voiceUrl; } - public final Local.EmergencyStatus getEmergencyStatus() { + public final EmergencyStatus getEmergencyStatus() { return this.emergencyStatus; } @@ -355,7 +353,7 @@ public final String getEmergencyAddressSid() { return this.emergencyAddressSid; } - public final Local.EmergencyAddressStatus getEmergencyAddressStatus() { + public final EmergencyAddressStatus getEmergencyAddressStatus() { return this.emergencyAddressStatus; } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/incomingphonenumber/LocalCreator.java b/src/main/java/com/twilio/rest/api/v2010/account/incomingphonenumber/LocalCreator.java index 27ecf933c4..25a74eb499 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/incomingphonenumber/LocalCreator.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/incomingphonenumber/LocalCreator.java @@ -241,7 +241,7 @@ public Local create(final TwilioRestClient client) { path = path.replace( "{" + "PhoneNumber" + "}", - this.phoneNumber.encode("utf-8") + this.phoneNumber.toString() ); Request request = new Request( diff --git a/src/main/java/com/twilio/rest/api/v2010/account/incomingphonenumber/Mobile.java b/src/main/java/com/twilio/rest/api/v2010/account/incomingphonenumber/Mobile.java index 62c6156f9e..78bdb0710f 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/incomingphonenumber/Mobile.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/incomingphonenumber/Mobile.java @@ -107,7 +107,7 @@ public static Mobile fromJson( private final String accountSid; private final String addressSid; - private final Mobile.AddressRequirement addressRequirements; + private final AddressRequirement addressRequirements; private final String apiVersion; private final Boolean beta; private final PhoneNumberCapabilities capabilities; @@ -127,16 +127,16 @@ public static Mobile fromJson( private final HttpMethod statusCallbackMethod; private final String trunkSid; private final String uri; - private final Mobile.VoiceReceiveMode voiceReceiveMode; + private final VoiceReceiveMode voiceReceiveMode; private final String voiceApplicationSid; private final Boolean voiceCallerIdLookup; private final HttpMethod voiceFallbackMethod; private final URI voiceFallbackUrl; private final HttpMethod voiceMethod; private final URI voiceUrl; - private final Mobile.EmergencyStatus emergencyStatus; + private final EmergencyStatus emergencyStatus; private final String emergencyAddressSid; - private final Mobile.EmergencyAddressStatus emergencyAddressStatus; + private final EmergencyAddressStatus emergencyAddressStatus; private final String bundleSid; private final String status; @@ -146,7 +146,7 @@ private Mobile( @JsonProperty("address_sid") final String addressSid, @JsonProperty( "address_requirements" - ) final Mobile.AddressRequirement addressRequirements, + ) final AddressRequirement addressRequirements, @JsonProperty("api_version") final String apiVersion, @JsonProperty("beta") final Boolean beta, @JsonProperty( @@ -174,7 +174,7 @@ private Mobile( @JsonProperty("uri") final String uri, @JsonProperty( "voice_receive_mode" - ) final Mobile.VoiceReceiveMode voiceReceiveMode, + ) final VoiceReceiveMode voiceReceiveMode, @JsonProperty("voice_application_sid") final String voiceApplicationSid, @JsonProperty( "voice_caller_id_lookup" @@ -185,13 +185,11 @@ private Mobile( @JsonProperty("voice_fallback_url") final URI voiceFallbackUrl, @JsonProperty("voice_method") final HttpMethod voiceMethod, @JsonProperty("voice_url") final URI voiceUrl, - @JsonProperty( - "emergency_status" - ) final Mobile.EmergencyStatus emergencyStatus, + @JsonProperty("emergency_status") final EmergencyStatus emergencyStatus, @JsonProperty("emergency_address_sid") final String emergencyAddressSid, @JsonProperty( "emergency_address_status" - ) final Mobile.EmergencyAddressStatus emergencyAddressStatus, + ) final EmergencyAddressStatus emergencyAddressStatus, @JsonProperty("bundle_sid") final String bundleSid, @JsonProperty("status") final String status ) { @@ -239,7 +237,7 @@ public final String getAddressSid() { return this.addressSid; } - public final Mobile.AddressRequirement getAddressRequirements() { + public final AddressRequirement getAddressRequirements() { return this.addressRequirements; } @@ -319,7 +317,7 @@ public final String getUri() { return this.uri; } - public final Mobile.VoiceReceiveMode getVoiceReceiveMode() { + public final VoiceReceiveMode getVoiceReceiveMode() { return this.voiceReceiveMode; } @@ -347,7 +345,7 @@ public final URI getVoiceUrl() { return this.voiceUrl; } - public final Mobile.EmergencyStatus getEmergencyStatus() { + public final EmergencyStatus getEmergencyStatus() { return this.emergencyStatus; } @@ -355,7 +353,7 @@ public final String getEmergencyAddressSid() { return this.emergencyAddressSid; } - public final Mobile.EmergencyAddressStatus getEmergencyAddressStatus() { + public final EmergencyAddressStatus getEmergencyAddressStatus() { return this.emergencyAddressStatus; } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/incomingphonenumber/MobileCreator.java b/src/main/java/com/twilio/rest/api/v2010/account/incomingphonenumber/MobileCreator.java index 5a40e409a0..6fe7fa36c0 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/incomingphonenumber/MobileCreator.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/incomingphonenumber/MobileCreator.java @@ -241,7 +241,7 @@ public Mobile create(final TwilioRestClient client) { path = path.replace( "{" + "PhoneNumber" + "}", - this.phoneNumber.encode("utf-8") + this.phoneNumber.toString() ); Request request = new Request( diff --git a/src/main/java/com/twilio/rest/api/v2010/account/incomingphonenumber/TollFree.java b/src/main/java/com/twilio/rest/api/v2010/account/incomingphonenumber/TollFree.java index 4e1e3cf74c..af9f39055a 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/incomingphonenumber/TollFree.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/incomingphonenumber/TollFree.java @@ -107,7 +107,7 @@ public static TollFree fromJson( private final String accountSid; private final String addressSid; - private final TollFree.AddressRequirement addressRequirements; + private final AddressRequirement addressRequirements; private final String apiVersion; private final Boolean beta; private final PhoneNumberCapabilities capabilities; @@ -127,16 +127,16 @@ public static TollFree fromJson( private final HttpMethod statusCallbackMethod; private final String trunkSid; private final String uri; - private final TollFree.VoiceReceiveMode voiceReceiveMode; + private final VoiceReceiveMode voiceReceiveMode; private final String voiceApplicationSid; private final Boolean voiceCallerIdLookup; private final HttpMethod voiceFallbackMethod; private final URI voiceFallbackUrl; private final HttpMethod voiceMethod; private final URI voiceUrl; - private final TollFree.EmergencyStatus emergencyStatus; + private final EmergencyStatus emergencyStatus; private final String emergencyAddressSid; - private final TollFree.EmergencyAddressStatus emergencyAddressStatus; + private final EmergencyAddressStatus emergencyAddressStatus; private final String bundleSid; private final String status; @@ -146,7 +146,7 @@ private TollFree( @JsonProperty("address_sid") final String addressSid, @JsonProperty( "address_requirements" - ) final TollFree.AddressRequirement addressRequirements, + ) final AddressRequirement addressRequirements, @JsonProperty("api_version") final String apiVersion, @JsonProperty("beta") final Boolean beta, @JsonProperty( @@ -174,7 +174,7 @@ private TollFree( @JsonProperty("uri") final String uri, @JsonProperty( "voice_receive_mode" - ) final TollFree.VoiceReceiveMode voiceReceiveMode, + ) final VoiceReceiveMode voiceReceiveMode, @JsonProperty("voice_application_sid") final String voiceApplicationSid, @JsonProperty( "voice_caller_id_lookup" @@ -185,13 +185,11 @@ private TollFree( @JsonProperty("voice_fallback_url") final URI voiceFallbackUrl, @JsonProperty("voice_method") final HttpMethod voiceMethod, @JsonProperty("voice_url") final URI voiceUrl, - @JsonProperty( - "emergency_status" - ) final TollFree.EmergencyStatus emergencyStatus, + @JsonProperty("emergency_status") final EmergencyStatus emergencyStatus, @JsonProperty("emergency_address_sid") final String emergencyAddressSid, @JsonProperty( "emergency_address_status" - ) final TollFree.EmergencyAddressStatus emergencyAddressStatus, + ) final EmergencyAddressStatus emergencyAddressStatus, @JsonProperty("bundle_sid") final String bundleSid, @JsonProperty("status") final String status ) { @@ -239,7 +237,7 @@ public final String getAddressSid() { return this.addressSid; } - public final TollFree.AddressRequirement getAddressRequirements() { + public final AddressRequirement getAddressRequirements() { return this.addressRequirements; } @@ -319,7 +317,7 @@ public final String getUri() { return this.uri; } - public final TollFree.VoiceReceiveMode getVoiceReceiveMode() { + public final VoiceReceiveMode getVoiceReceiveMode() { return this.voiceReceiveMode; } @@ -347,7 +345,7 @@ public final URI getVoiceUrl() { return this.voiceUrl; } - public final TollFree.EmergencyStatus getEmergencyStatus() { + public final EmergencyStatus getEmergencyStatus() { return this.emergencyStatus; } @@ -355,7 +353,7 @@ public final String getEmergencyAddressSid() { return this.emergencyAddressSid; } - public final TollFree.EmergencyAddressStatus getEmergencyAddressStatus() { + public final EmergencyAddressStatus getEmergencyAddressStatus() { return this.emergencyAddressStatus; } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/incomingphonenumber/TollFreeCreator.java b/src/main/java/com/twilio/rest/api/v2010/account/incomingphonenumber/TollFreeCreator.java index c6426ab2ce..61034d20c3 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/incomingphonenumber/TollFreeCreator.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/incomingphonenumber/TollFreeCreator.java @@ -243,7 +243,7 @@ public TollFree create(final TwilioRestClient client) { path = path.replace( "{" + "PhoneNumber" + "}", - this.phoneNumber.encode("utf-8") + this.phoneNumber.toString() ); Request request = new Request( diff --git a/src/main/java/com/twilio/rest/api/v2010/account/message/Feedback.java b/src/main/java/com/twilio/rest/api/v2010/account/message/Feedback.java index 66db8761d3..86601603c3 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/message/Feedback.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/message/Feedback.java @@ -94,7 +94,7 @@ public static Feedback fromJson( private final String accountSid; private final String messageSid; - private final Feedback.Outcome outcome; + private final Outcome outcome; private final ZonedDateTime dateCreated; private final ZonedDateTime dateUpdated; private final String uri; @@ -103,7 +103,7 @@ public static Feedback fromJson( private Feedback( @JsonProperty("account_sid") final String accountSid, @JsonProperty("message_sid") final String messageSid, - @JsonProperty("outcome") final Feedback.Outcome outcome, + @JsonProperty("outcome") final Outcome outcome, @JsonProperty("date_created") final String dateCreated, @JsonProperty("date_updated") final String dateUpdated, @JsonProperty("uri") final String uri @@ -124,7 +124,7 @@ public final String getMessageSid() { return this.messageSid; } - public final Feedback.Outcome getOutcome() { + public final Outcome getOutcome() { return this.outcome; } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/recording/AddOnResult.java b/src/main/java/com/twilio/rest/api/v2010/account/recording/AddOnResult.java index c20e30dcb0..42b02433c7 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/recording/AddOnResult.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/recording/AddOnResult.java @@ -134,7 +134,7 @@ public static AddOnResult fromJson( private final String sid; private final String accountSid; - private final AddOnResult.Status status; + private final Status status; private final String addOnSid; private final String addOnConfigurationSid; private final ZonedDateTime dateCreated; @@ -147,7 +147,7 @@ public static AddOnResult fromJson( private AddOnResult( @JsonProperty("sid") final String sid, @JsonProperty("account_sid") final String accountSid, - @JsonProperty("status") final AddOnResult.Status status, + @JsonProperty("status") final Status status, @JsonProperty("add_on_sid") final String addOnSid, @JsonProperty( "add_on_configuration_sid" @@ -182,7 +182,7 @@ public final String getAccountSid() { return this.accountSid; } - public final AddOnResult.Status getStatus() { + public final Status getStatus() { return this.status; } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/recording/Transcription.java b/src/main/java/com/twilio/rest/api/v2010/account/recording/Transcription.java index c265b98c28..ba9df4ae95 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/recording/Transcription.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/recording/Transcription.java @@ -143,7 +143,7 @@ public static Transcription fromJson( private final Currency priceUnit; private final String recordingSid; private final String sid; - private final Transcription.Status status; + private final Status status; private final String transcriptionText; private final String type; private final String uri; @@ -157,11 +157,11 @@ private Transcription( @JsonProperty("duration") final String duration, @JsonProperty("price") final BigDecimal price, @JsonProperty("price_unit") @JsonDeserialize( - using = com.twilio.converter.CurrencyDeserializer.class + using = CurrencyDeserializer.class ) final Currency priceUnit, @JsonProperty("recording_sid") final String recordingSid, @JsonProperty("sid") final String sid, - @JsonProperty("status") final Transcription.Status status, + @JsonProperty("status") final Status status, @JsonProperty("transcription_text") final String transcriptionText, @JsonProperty("type") final String type, @JsonProperty("uri") final String uri @@ -217,7 +217,7 @@ public final String getSid() { return this.sid; } - public final Transcription.Status getStatus() { + public final Status getStatus() { return this.status; } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/usage/Record.java b/src/main/java/com/twilio/rest/api/v2010/account/usage/Record.java index 5c05e36626..de6b0f6a44 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/usage/Record.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/usage/Record.java @@ -98,7 +98,7 @@ public static Record fromJson( private final String accountSid; private final String apiVersion; private final String asOf; - private final Record.Category category; + private final Category category; private final String count; private final String countUnit; private final String description; @@ -116,14 +116,14 @@ private Record( @JsonProperty("account_sid") final String accountSid, @JsonProperty("api_version") final String apiVersion, @JsonProperty("as_of") final String asOf, - @JsonProperty("category") final Record.Category category, + @JsonProperty("category") final Category category, @JsonProperty("count") final String count, @JsonProperty("count_unit") final String countUnit, @JsonProperty("description") final String description, @JsonProperty("end_date") final String endDate, @JsonProperty("price") final BigDecimal price, @JsonProperty("price_unit") @JsonDeserialize( - using = com.twilio.converter.CurrencyDeserializer.class + using = CurrencyDeserializer.class ) final Currency priceUnit, @JsonProperty("start_date") final String startDate, @JsonProperty("subresource_uris") final Map< @@ -163,7 +163,7 @@ public final String getAsOf() { return this.asOf; } - public final Record.Category getCategory() { + public final Category getCategory() { return this.category; } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/usage/Trigger.java b/src/main/java/com/twilio/rest/api/v2010/account/usage/Trigger.java index e18017d6e6..287dcf8236 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/usage/Trigger.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/usage/Trigger.java @@ -43,7 +43,7 @@ public class Trigger extends Resource { public static TriggerCreator creator( final URI callbackUrl, final String triggerValue, - final Trigger.UsageCategory usageCategory + final UsageCategory usageCategory ) { return new TriggerCreator(callbackUrl, triggerValue, usageCategory); } @@ -52,7 +52,7 @@ public static TriggerCreator creator( final String pathAccountSid, final URI callbackUrl, final String triggerValue, - final Trigger.UsageCategory usageCategory + final UsageCategory usageCategory ) { return new TriggerCreator( pathAccountSid, @@ -155,12 +155,12 @@ public static Trigger fromJson( private final ZonedDateTime dateFired; private final ZonedDateTime dateUpdated; private final String friendlyName; - private final Trigger.Recurring recurring; + private final Recurring recurring; private final String sid; - private final Trigger.TriggerField triggerBy; + private final TriggerField triggerBy; private final String triggerValue; private final String uri; - private final Trigger.UsageCategory usageCategory; + private final UsageCategory usageCategory; private final String usageRecordUri; @JsonCreator @@ -174,14 +174,12 @@ private Trigger( @JsonProperty("date_fired") final String dateFired, @JsonProperty("date_updated") final String dateUpdated, @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("recurring") final Trigger.Recurring recurring, + @JsonProperty("recurring") final Recurring recurring, @JsonProperty("sid") final String sid, - @JsonProperty("trigger_by") final Trigger.TriggerField triggerBy, + @JsonProperty("trigger_by") final TriggerField triggerBy, @JsonProperty("trigger_value") final String triggerValue, @JsonProperty("uri") final String uri, - @JsonProperty( - "usage_category" - ) final Trigger.UsageCategory usageCategory, + @JsonProperty("usage_category") final UsageCategory usageCategory, @JsonProperty("usage_record_uri") final String usageRecordUri ) { this.accountSid = accountSid; @@ -238,7 +236,7 @@ public final String getFriendlyName() { return this.friendlyName; } - public final Trigger.Recurring getRecurring() { + public final Recurring getRecurring() { return this.recurring; } @@ -246,7 +244,7 @@ public final String getSid() { return this.sid; } - public final Trigger.TriggerField getTriggerBy() { + public final TriggerField getTriggerBy() { return this.triggerBy; } @@ -258,7 +256,7 @@ public final String getUri() { return this.uri; } - public final Trigger.UsageCategory getUsageCategory() { + public final UsageCategory getUsageCategory() { return this.usageCategory; } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/usage/record/AllTime.java b/src/main/java/com/twilio/rest/api/v2010/account/usage/record/AllTime.java index 2e5e8e1938..576f6ddd09 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/usage/record/AllTime.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/usage/record/AllTime.java @@ -98,7 +98,7 @@ public static AllTime fromJson( private final String accountSid; private final String apiVersion; private final String asOf; - private final AllTime.Category category; + private final Category category; private final String count; private final String countUnit; private final String description; @@ -116,14 +116,14 @@ private AllTime( @JsonProperty("account_sid") final String accountSid, @JsonProperty("api_version") final String apiVersion, @JsonProperty("as_of") final String asOf, - @JsonProperty("category") final AllTime.Category category, + @JsonProperty("category") final Category category, @JsonProperty("count") final String count, @JsonProperty("count_unit") final String countUnit, @JsonProperty("description") final String description, @JsonProperty("end_date") final String endDate, @JsonProperty("price") final BigDecimal price, @JsonProperty("price_unit") @JsonDeserialize( - using = com.twilio.converter.CurrencyDeserializer.class + using = CurrencyDeserializer.class ) final Currency priceUnit, @JsonProperty("start_date") final String startDate, @JsonProperty("subresource_uris") final Map< @@ -163,7 +163,7 @@ public final String getAsOf() { return this.asOf; } - public final AllTime.Category getCategory() { + public final Category getCategory() { return this.category; } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/usage/record/Daily.java b/src/main/java/com/twilio/rest/api/v2010/account/usage/record/Daily.java index c562e8b219..22c683d023 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/usage/record/Daily.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/usage/record/Daily.java @@ -98,7 +98,7 @@ public static Daily fromJson( private final String accountSid; private final String apiVersion; private final String asOf; - private final Daily.Category category; + private final Category category; private final String count; private final String countUnit; private final String description; @@ -116,14 +116,14 @@ private Daily( @JsonProperty("account_sid") final String accountSid, @JsonProperty("api_version") final String apiVersion, @JsonProperty("as_of") final String asOf, - @JsonProperty("category") final Daily.Category category, + @JsonProperty("category") final Category category, @JsonProperty("count") final String count, @JsonProperty("count_unit") final String countUnit, @JsonProperty("description") final String description, @JsonProperty("end_date") final String endDate, @JsonProperty("price") final BigDecimal price, @JsonProperty("price_unit") @JsonDeserialize( - using = com.twilio.converter.CurrencyDeserializer.class + using = CurrencyDeserializer.class ) final Currency priceUnit, @JsonProperty("start_date") final String startDate, @JsonProperty("subresource_uris") final Map< @@ -163,7 +163,7 @@ public final String getAsOf() { return this.asOf; } - public final Daily.Category getCategory() { + public final Category getCategory() { return this.category; } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/usage/record/LastMonth.java b/src/main/java/com/twilio/rest/api/v2010/account/usage/record/LastMonth.java index 471a20a4d8..fcbf30024c 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/usage/record/LastMonth.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/usage/record/LastMonth.java @@ -98,7 +98,7 @@ public static LastMonth fromJson( private final String accountSid; private final String apiVersion; private final String asOf; - private final LastMonth.Category category; + private final Category category; private final String count; private final String countUnit; private final String description; @@ -116,14 +116,14 @@ private LastMonth( @JsonProperty("account_sid") final String accountSid, @JsonProperty("api_version") final String apiVersion, @JsonProperty("as_of") final String asOf, - @JsonProperty("category") final LastMonth.Category category, + @JsonProperty("category") final Category category, @JsonProperty("count") final String count, @JsonProperty("count_unit") final String countUnit, @JsonProperty("description") final String description, @JsonProperty("end_date") final String endDate, @JsonProperty("price") final BigDecimal price, @JsonProperty("price_unit") @JsonDeserialize( - using = com.twilio.converter.CurrencyDeserializer.class + using = CurrencyDeserializer.class ) final Currency priceUnit, @JsonProperty("start_date") final String startDate, @JsonProperty("subresource_uris") final Map< @@ -163,7 +163,7 @@ public final String getAsOf() { return this.asOf; } - public final LastMonth.Category getCategory() { + public final Category getCategory() { return this.category; } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/usage/record/Monthly.java b/src/main/java/com/twilio/rest/api/v2010/account/usage/record/Monthly.java index 315837e39e..64b1070365 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/usage/record/Monthly.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/usage/record/Monthly.java @@ -98,7 +98,7 @@ public static Monthly fromJson( private final String accountSid; private final String apiVersion; private final String asOf; - private final Monthly.Category category; + private final Category category; private final String count; private final String countUnit; private final String description; @@ -116,14 +116,14 @@ private Monthly( @JsonProperty("account_sid") final String accountSid, @JsonProperty("api_version") final String apiVersion, @JsonProperty("as_of") final String asOf, - @JsonProperty("category") final Monthly.Category category, + @JsonProperty("category") final Category category, @JsonProperty("count") final String count, @JsonProperty("count_unit") final String countUnit, @JsonProperty("description") final String description, @JsonProperty("end_date") final String endDate, @JsonProperty("price") final BigDecimal price, @JsonProperty("price_unit") @JsonDeserialize( - using = com.twilio.converter.CurrencyDeserializer.class + using = CurrencyDeserializer.class ) final Currency priceUnit, @JsonProperty("start_date") final String startDate, @JsonProperty("subresource_uris") final Map< @@ -163,7 +163,7 @@ public final String getAsOf() { return this.asOf; } - public final Monthly.Category getCategory() { + public final Category getCategory() { return this.category; } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/usage/record/ThisMonth.java b/src/main/java/com/twilio/rest/api/v2010/account/usage/record/ThisMonth.java index f0799a55f9..f545f03970 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/usage/record/ThisMonth.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/usage/record/ThisMonth.java @@ -98,7 +98,7 @@ public static ThisMonth fromJson( private final String accountSid; private final String apiVersion; private final String asOf; - private final ThisMonth.Category category; + private final Category category; private final String count; private final String countUnit; private final String description; @@ -116,14 +116,14 @@ private ThisMonth( @JsonProperty("account_sid") final String accountSid, @JsonProperty("api_version") final String apiVersion, @JsonProperty("as_of") final String asOf, - @JsonProperty("category") final ThisMonth.Category category, + @JsonProperty("category") final Category category, @JsonProperty("count") final String count, @JsonProperty("count_unit") final String countUnit, @JsonProperty("description") final String description, @JsonProperty("end_date") final String endDate, @JsonProperty("price") final BigDecimal price, @JsonProperty("price_unit") @JsonDeserialize( - using = com.twilio.converter.CurrencyDeserializer.class + using = CurrencyDeserializer.class ) final Currency priceUnit, @JsonProperty("start_date") final String startDate, @JsonProperty("subresource_uris") final Map< @@ -163,7 +163,7 @@ public final String getAsOf() { return this.asOf; } - public final ThisMonth.Category getCategory() { + public final Category getCategory() { return this.category; } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/usage/record/Today.java b/src/main/java/com/twilio/rest/api/v2010/account/usage/record/Today.java index 38c0f84024..09fced5595 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/usage/record/Today.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/usage/record/Today.java @@ -98,7 +98,7 @@ public static Today fromJson( private final String accountSid; private final String apiVersion; private final String asOf; - private final Today.Category category; + private final Category category; private final String count; private final String countUnit; private final String description; @@ -116,14 +116,14 @@ private Today( @JsonProperty("account_sid") final String accountSid, @JsonProperty("api_version") final String apiVersion, @JsonProperty("as_of") final String asOf, - @JsonProperty("category") final Today.Category category, + @JsonProperty("category") final Category category, @JsonProperty("count") final String count, @JsonProperty("count_unit") final String countUnit, @JsonProperty("description") final String description, @JsonProperty("end_date") final String endDate, @JsonProperty("price") final BigDecimal price, @JsonProperty("price_unit") @JsonDeserialize( - using = com.twilio.converter.CurrencyDeserializer.class + using = CurrencyDeserializer.class ) final Currency priceUnit, @JsonProperty("start_date") final String startDate, @JsonProperty("subresource_uris") final Map< @@ -163,7 +163,7 @@ public final String getAsOf() { return this.asOf; } - public final Today.Category getCategory() { + public final Category getCategory() { return this.category; } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/usage/record/Yearly.java b/src/main/java/com/twilio/rest/api/v2010/account/usage/record/Yearly.java index bc447957ac..c55164426b 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/usage/record/Yearly.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/usage/record/Yearly.java @@ -98,7 +98,7 @@ public static Yearly fromJson( private final String accountSid; private final String apiVersion; private final String asOf; - private final Yearly.Category category; + private final Category category; private final String count; private final String countUnit; private final String description; @@ -116,14 +116,14 @@ private Yearly( @JsonProperty("account_sid") final String accountSid, @JsonProperty("api_version") final String apiVersion, @JsonProperty("as_of") final String asOf, - @JsonProperty("category") final Yearly.Category category, + @JsonProperty("category") final Category category, @JsonProperty("count") final String count, @JsonProperty("count_unit") final String countUnit, @JsonProperty("description") final String description, @JsonProperty("end_date") final String endDate, @JsonProperty("price") final BigDecimal price, @JsonProperty("price_unit") @JsonDeserialize( - using = com.twilio.converter.CurrencyDeserializer.class + using = CurrencyDeserializer.class ) final Currency priceUnit, @JsonProperty("start_date") final String startDate, @JsonProperty("subresource_uris") final Map< @@ -163,7 +163,7 @@ public final String getAsOf() { return this.asOf; } - public final Yearly.Category getCategory() { + public final Category getCategory() { return this.category; } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/usage/record/Yesterday.java b/src/main/java/com/twilio/rest/api/v2010/account/usage/record/Yesterday.java index f271504c4b..d908600933 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/usage/record/Yesterday.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/usage/record/Yesterday.java @@ -98,7 +98,7 @@ public static Yesterday fromJson( private final String accountSid; private final String apiVersion; private final String asOf; - private final Yesterday.Category category; + private final Category category; private final String count; private final String countUnit; private final String description; @@ -116,14 +116,14 @@ private Yesterday( @JsonProperty("account_sid") final String accountSid, @JsonProperty("api_version") final String apiVersion, @JsonProperty("as_of") final String asOf, - @JsonProperty("category") final Yesterday.Category category, + @JsonProperty("category") final Category category, @JsonProperty("count") final String count, @JsonProperty("count_unit") final String countUnit, @JsonProperty("description") final String description, @JsonProperty("end_date") final String endDate, @JsonProperty("price") final BigDecimal price, @JsonProperty("price_unit") @JsonDeserialize( - using = com.twilio.converter.CurrencyDeserializer.class + using = CurrencyDeserializer.class ) final Currency priceUnit, @JsonProperty("start_date") final String startDate, @JsonProperty("subresource_uris") final Map< @@ -163,7 +163,7 @@ public final String getAsOf() { return this.asOf; } - public final Yesterday.Category getCategory() { + public final Category getCategory() { return this.category; } diff --git a/src/main/java/com/twilio/rest/assistants/v1/Assistant.java b/src/main/java/com/twilio/rest/assistants/v1/Assistant.java index 94f290b45d..ac3ca71dda 100644 --- a/src/main/java/com/twilio/rest/assistants/v1/Assistant.java +++ b/src/main/java/com/twilio/rest/assistants/v1/Assistant.java @@ -23,7 +23,6 @@ import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; -import com.twilio.converter.Converter; import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; @@ -136,7 +135,9 @@ public static class AssistantsV1ServiceCreateAssistantRequest { @Setter private AssistantsV1ServiceSegmentCredential segmentCredential; - public AssistantsV1ServiceCreateAssistantRequest() {} + public AssistantsV1ServiceCreateAssistantRequest(final String name) { + this.name = name; + } public static AssistantsV1ServiceCreateAssistantRequest fromJson( String jsonString, @@ -222,10 +223,6 @@ public static class AssistantsV1ServiceKnowledge { @Setter private Map knowledgeSourceDetails; - public String getKnowledgeSourceDetails() { - return Converter.mapToJson(knowledgeSourceDetails); - } - @JsonInclude(JsonInclude.Include.NON_EMPTY) @JsonProperty("name") @Getter @@ -320,10 +317,6 @@ public static class AssistantsV1ServiceTool { @Setter private Map meta; - public String getMeta() { - return Converter.mapToJson(meta); - } - @JsonInclude(JsonInclude.Include.NON_EMPTY) @JsonProperty("name") @Getter @@ -377,7 +370,7 @@ public static AssistantsV1ServiceTool fromJson( } public static AssistantCreator creator( - final Assistant.AssistantsV1ServiceCreateAssistantRequest assistantsV1ServiceCreateAssistantRequest + final AssistantsV1ServiceCreateAssistantRequest assistantsV1ServiceCreateAssistantRequest ) { return new AssistantCreator(assistantsV1ServiceCreateAssistantRequest); } diff --git a/src/main/java/com/twilio/rest/assistants/v1/Knowledge.java b/src/main/java/com/twilio/rest/assistants/v1/Knowledge.java index 0f5b469bb2..b412f115bb 100644 --- a/src/main/java/com/twilio/rest/assistants/v1/Knowledge.java +++ b/src/main/java/com/twilio/rest/assistants/v1/Knowledge.java @@ -23,7 +23,6 @@ import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; -import com.twilio.converter.Converter; import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; @@ -71,10 +70,6 @@ public static class AssistantsV1ServiceCreatePolicyRequest { @Setter private Object policyDetails; - public String getPolicyDetails() { - return Converter.objectToJson(policyDetails); - } - @JsonInclude(JsonInclude.Include.NON_EMPTY) @JsonProperty("type") @Getter @@ -113,10 +108,6 @@ public static class AssistantsV1ServiceCreateKnowledgeRequest { @Setter private Map knowledgeSourceDetails; - public String getKnowledgeSourceDetails() { - return Converter.mapToJson(knowledgeSourceDetails); - } - @JsonInclude(JsonInclude.Include.NON_EMPTY) @JsonProperty("name") @Getter @@ -141,7 +132,13 @@ public String getKnowledgeSourceDetails() { @Setter private String embeddingModel; - public AssistantsV1ServiceCreateKnowledgeRequest() {} + public AssistantsV1ServiceCreateKnowledgeRequest( + final String name, + final String type + ) { + this.name = name; + this.type = type; + } public static AssistantsV1ServiceCreateKnowledgeRequest fromJson( String jsonString, @@ -169,10 +166,6 @@ public static class AssistantsV1ServiceUpdateKnowledgeRequest { @Setter private Map knowledgeSourceDetails; - public String getKnowledgeSourceDetails() { - return Converter.mapToJson(knowledgeSourceDetails); - } - @JsonInclude(JsonInclude.Include.NON_EMPTY) @JsonProperty("name") @Getter @@ -211,7 +204,7 @@ public static AssistantsV1ServiceUpdateKnowledgeRequest fromJson( } public static KnowledgeCreator creator( - final Knowledge.AssistantsV1ServiceCreateKnowledgeRequest assistantsV1ServiceCreateKnowledgeRequest + final AssistantsV1ServiceCreateKnowledgeRequest assistantsV1ServiceCreateKnowledgeRequest ) { return new KnowledgeCreator(assistantsV1ServiceCreateKnowledgeRequest); } diff --git a/src/main/java/com/twilio/rest/assistants/v1/Tool.java b/src/main/java/com/twilio/rest/assistants/v1/Tool.java index c4dbbf3be2..2f9b5aacb0 100644 --- a/src/main/java/com/twilio/rest/assistants/v1/Tool.java +++ b/src/main/java/com/twilio/rest/assistants/v1/Tool.java @@ -23,7 +23,6 @@ import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; -import com.twilio.converter.Converter; import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; @@ -72,10 +71,6 @@ public static class AssistantsV1ServiceCreatePolicyRequest { @Setter private Object policyDetails; - public String getPolicyDetails() { - return Converter.objectToJson(policyDetails); - } - @JsonInclude(JsonInclude.Include.NON_EMPTY) @JsonProperty("type") @Getter @@ -120,10 +115,6 @@ public static class AssistantsV1ServiceCreateToolRequest { @Setter private Map meta; - public String getMeta() { - return Converter.mapToJson(meta); - } - @JsonInclude(JsonInclude.Include.NON_EMPTY) @JsonProperty("name") @Getter @@ -142,7 +133,15 @@ public String getMeta() { @Setter private String type; - public AssistantsV1ServiceCreateToolRequest() {} + public AssistantsV1ServiceCreateToolRequest( + final Boolean enabled, + final String name, + final String type + ) { + this.enabled = enabled; + this.name = name; + this.type = type; + } public static AssistantsV1ServiceCreateToolRequest fromJson( String jsonString, @@ -182,10 +181,6 @@ public static class AssistantsV1ServiceUpdateToolRequest { @Setter private Map meta; - public String getMeta() { - return Converter.mapToJson(meta); - } - @JsonInclude(JsonInclude.Include.NON_EMPTY) @JsonProperty("name") @Getter @@ -262,10 +257,6 @@ public static class AssistantsV1ServicePolicy { @Setter private Map policyDetails; - public String getPolicyDetails() { - return Converter.mapToJson(policyDetails); - } - @JsonInclude(JsonInclude.Include.NON_EMPTY) @JsonProperty("dateCreated") @Getter @@ -298,7 +289,7 @@ public static AssistantsV1ServicePolicy fromJson( } public static ToolCreator creator( - final Tool.AssistantsV1ServiceCreateToolRequest assistantsV1ServiceCreateToolRequest + final AssistantsV1ServiceCreateToolRequest assistantsV1ServiceCreateToolRequest ) { return new ToolCreator(assistantsV1ServiceCreateToolRequest); } diff --git a/src/main/java/com/twilio/rest/assistants/v1/assistant/Feedback.java b/src/main/java/com/twilio/rest/assistants/v1/assistant/Feedback.java index c607c9c472..57cb442b4a 100644 --- a/src/main/java/com/twilio/rest/assistants/v1/assistant/Feedback.java +++ b/src/main/java/com/twilio/rest/assistants/v1/assistant/Feedback.java @@ -87,7 +87,7 @@ public static AssistantsV1ServiceCreateFeedbackRequest fromJson( public static FeedbackCreator creator( final String pathId, - final Feedback.AssistantsV1ServiceCreateFeedbackRequest assistantsV1ServiceCreateFeedbackRequest + final AssistantsV1ServiceCreateFeedbackRequest assistantsV1ServiceCreateFeedbackRequest ) { return new FeedbackCreator( pathId, diff --git a/src/main/java/com/twilio/rest/assistants/v1/assistant/Message.java b/src/main/java/com/twilio/rest/assistants/v1/assistant/Message.java index 3891e48b3e..b2922bd6e9 100644 --- a/src/main/java/com/twilio/rest/assistants/v1/assistant/Message.java +++ b/src/main/java/com/twilio/rest/assistants/v1/assistant/Message.java @@ -93,7 +93,7 @@ public static AssistantsV1ServiceAssistantSendMessageRequest fromJson( public static MessageCreator creator( final String pathId, - final Message.AssistantsV1ServiceAssistantSendMessageRequest assistantsV1ServiceAssistantSendMessageRequest + final AssistantsV1ServiceAssistantSendMessageRequest assistantsV1ServiceAssistantSendMessageRequest ) { return new MessageCreator( pathId, diff --git a/src/main/java/com/twilio/rest/bulkexports/v1/export/ExportCustomJob.java b/src/main/java/com/twilio/rest/bulkexports/v1/export/ExportCustomJob.java index 058ef9a15c..ee3bc089bb 100644 --- a/src/main/java/com/twilio/rest/bulkexports/v1/export/ExportCustomJob.java +++ b/src/main/java/com/twilio/rest/bulkexports/v1/export/ExportCustomJob.java @@ -25,6 +25,7 @@ import com.twilio.exception.ApiException; import java.io.IOException; import java.io.InputStream; +import java.util.List; import java.util.Map; import java.util.Map; import java.util.Objects; @@ -35,7 +36,7 @@ @ToString public class ExportCustomJob extends Resource { - private static final long serialVersionUID = 125242558228L; + private static final long serialVersionUID = 87737406045908L; public static ExportCustomJobCreator creator( final String pathResourceType, @@ -106,7 +107,7 @@ public static ExportCustomJob fromJson( private final String webhookMethod; private final String email; private final String jobSid; - private final Map details; + private final List> details; private final String jobQueuePosition; private final String estimatedCompletionTime; @@ -120,7 +121,7 @@ private ExportCustomJob( @JsonProperty("webhook_method") final String webhookMethod, @JsonProperty("email") final String email, @JsonProperty("job_sid") final String jobSid, - @JsonProperty("details") final Map details, + @JsonProperty("details") final List> details, @JsonProperty("job_queue_position") final String jobQueuePosition, @JsonProperty( "estimated_completion_time" @@ -171,7 +172,7 @@ public final String getJobSid() { return this.jobSid; } - public final Map getDetails() { + public final List> getDetails() { return this.details; } diff --git a/src/main/java/com/twilio/rest/bulkexports/v1/export/Job.java b/src/main/java/com/twilio/rest/bulkexports/v1/export/Job.java index 52fce1b2eb..685913964b 100644 --- a/src/main/java/com/twilio/rest/bulkexports/v1/export/Job.java +++ b/src/main/java/com/twilio/rest/bulkexports/v1/export/Job.java @@ -26,6 +26,7 @@ import java.io.IOException; import java.io.InputStream; import java.net.URI; +import java.util.List; import java.util.Map; import java.util.Map; import java.util.Objects; @@ -36,7 +37,7 @@ @ToString public class Job extends Resource { - private static final long serialVersionUID = 103628862500013L; + private static final long serialVersionUID = 152000944333983L; public static JobDeleter deleter(final String pathJobSid) { return new JobDeleter(pathJobSid); @@ -91,7 +92,7 @@ public static Job fromJson( private final String resourceType; private final String friendlyName; - private final Map details; + private final List> details; private final String startDay; private final String endDay; private final String jobSid; @@ -106,7 +107,7 @@ public static Job fromJson( private Job( @JsonProperty("resource_type") final String resourceType, @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("details") final Map details, + @JsonProperty("details") final List> details, @JsonProperty("start_day") final String startDay, @JsonProperty("end_day") final String endDay, @JsonProperty("job_sid") final String jobSid, @@ -141,7 +142,7 @@ public final String getFriendlyName() { return this.friendlyName; } - public final Map getDetails() { + public final List> getDetails() { return this.details; } diff --git a/src/main/java/com/twilio/rest/chat/v1/Credential.java b/src/main/java/com/twilio/rest/chat/v1/Credential.java index 270e61e3fe..8b91dfa3ef 100644 --- a/src/main/java/com/twilio/rest/chat/v1/Credential.java +++ b/src/main/java/com/twilio/rest/chat/v1/Credential.java @@ -39,7 +39,7 @@ public class Credential extends Resource { private static final long serialVersionUID = 161183169234848L; - public static CredentialCreator creator(final Credential.PushService type) { + public static CredentialCreator creator(final PushService type) { return new CredentialCreator(type); } @@ -105,7 +105,7 @@ public static Credential fromJson( private final String sid; private final String accountSid; private final String friendlyName; - private final Credential.PushService type; + private final PushService type; private final String sandbox; private final ZonedDateTime dateCreated; private final ZonedDateTime dateUpdated; @@ -116,7 +116,7 @@ private Credential( @JsonProperty("sid") final String sid, @JsonProperty("account_sid") final String accountSid, @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("type") final Credential.PushService type, + @JsonProperty("type") final PushService type, @JsonProperty("sandbox") final String sandbox, @JsonProperty("date_created") final String dateCreated, @JsonProperty("date_updated") final String dateUpdated, @@ -144,7 +144,7 @@ public final String getFriendlyName() { return this.friendlyName; } - public final Credential.PushService getType() { + public final PushService getType() { return this.type; } diff --git a/src/main/java/com/twilio/rest/chat/v1/service/Channel.java b/src/main/java/com/twilio/rest/chat/v1/service/Channel.java index d8f46724b0..0b026f0db2 100644 --- a/src/main/java/com/twilio/rest/chat/v1/service/Channel.java +++ b/src/main/java/com/twilio/rest/chat/v1/service/Channel.java @@ -119,7 +119,7 @@ public static Channel fromJson( private final String friendlyName; private final String uniqueName; private final String attributes; - private final Channel.ChannelType type; + private final ChannelType type; private final ZonedDateTime dateCreated; private final ZonedDateTime dateUpdated; private final String createdBy; @@ -136,7 +136,7 @@ private Channel( @JsonProperty("friendly_name") final String friendlyName, @JsonProperty("unique_name") final String uniqueName, @JsonProperty("attributes") final String attributes, - @JsonProperty("type") final Channel.ChannelType type, + @JsonProperty("type") final ChannelType type, @JsonProperty("date_created") final String dateCreated, @JsonProperty("date_updated") final String dateUpdated, @JsonProperty("created_by") final String createdBy, @@ -185,7 +185,7 @@ public final String getAttributes() { return this.attributes; } - public final Channel.ChannelType getType() { + public final ChannelType getType() { return this.type; } diff --git a/src/main/java/com/twilio/rest/chat/v1/service/Role.java b/src/main/java/com/twilio/rest/chat/v1/service/Role.java index eaf3e01555..d2a44ff7dc 100644 --- a/src/main/java/com/twilio/rest/chat/v1/service/Role.java +++ b/src/main/java/com/twilio/rest/chat/v1/service/Role.java @@ -43,7 +43,7 @@ public class Role extends Resource { public static RoleCreator creator( final String pathServiceSid, final String friendlyName, - final Role.RoleType type, + final RoleType type, final List permission ) { return new RoleCreator(pathServiceSid, friendlyName, type, permission); @@ -122,7 +122,7 @@ public static Role fromJson( private final String accountSid; private final String serviceSid; private final String friendlyName; - private final Role.RoleType type; + private final RoleType type; private final List permissions; private final ZonedDateTime dateCreated; private final ZonedDateTime dateUpdated; @@ -134,7 +134,7 @@ private Role( @JsonProperty("account_sid") final String accountSid, @JsonProperty("service_sid") final String serviceSid, @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("type") final Role.RoleType type, + @JsonProperty("type") final RoleType type, @JsonProperty("permissions") final List permissions, @JsonProperty("date_created") final String dateCreated, @JsonProperty("date_updated") final String dateUpdated, @@ -167,7 +167,7 @@ public final String getFriendlyName() { return this.friendlyName; } - public final Role.RoleType getType() { + public final RoleType getType() { return this.type; } diff --git a/src/main/java/com/twilio/rest/chat/v1/service/user/UserChannel.java b/src/main/java/com/twilio/rest/chat/v1/service/user/UserChannel.java index 245f4d1b5d..667c61e4eb 100644 --- a/src/main/java/com/twilio/rest/chat/v1/service/user/UserChannel.java +++ b/src/main/java/com/twilio/rest/chat/v1/service/user/UserChannel.java @@ -92,7 +92,7 @@ public static UserChannel fromJson( private final String serviceSid; private final String channelSid; private final String memberSid; - private final UserChannel.ChannelStatus status; + private final ChannelStatus status; private final Integer lastConsumedMessageIndex; private final Integer unreadMessagesCount; private final Map links; @@ -103,7 +103,7 @@ private UserChannel( @JsonProperty("service_sid") final String serviceSid, @JsonProperty("channel_sid") final String channelSid, @JsonProperty("member_sid") final String memberSid, - @JsonProperty("status") final UserChannel.ChannelStatus status, + @JsonProperty("status") final ChannelStatus status, @JsonProperty( "last_consumed_message_index" ) final Integer lastConsumedMessageIndex, @@ -138,7 +138,7 @@ public final String getMemberSid() { return this.memberSid; } - public final UserChannel.ChannelStatus getStatus() { + public final ChannelStatus getStatus() { return this.status; } diff --git a/src/main/java/com/twilio/rest/chat/v2/Credential.java b/src/main/java/com/twilio/rest/chat/v2/Credential.java index b02f30cb1e..8be42a05aa 100644 --- a/src/main/java/com/twilio/rest/chat/v2/Credential.java +++ b/src/main/java/com/twilio/rest/chat/v2/Credential.java @@ -39,7 +39,7 @@ public class Credential extends Resource { private static final long serialVersionUID = 161183169234848L; - public static CredentialCreator creator(final Credential.PushService type) { + public static CredentialCreator creator(final PushService type) { return new CredentialCreator(type); } @@ -105,7 +105,7 @@ public static Credential fromJson( private final String sid; private final String accountSid; private final String friendlyName; - private final Credential.PushService type; + private final PushService type; private final String sandbox; private final ZonedDateTime dateCreated; private final ZonedDateTime dateUpdated; @@ -116,7 +116,7 @@ private Credential( @JsonProperty("sid") final String sid, @JsonProperty("account_sid") final String accountSid, @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("type") final Credential.PushService type, + @JsonProperty("type") final PushService type, @JsonProperty("sandbox") final String sandbox, @JsonProperty("date_created") final String dateCreated, @JsonProperty("date_updated") final String dateUpdated, @@ -144,7 +144,7 @@ public final String getFriendlyName() { return this.friendlyName; } - public final Credential.PushService getType() { + public final PushService getType() { return this.type; } diff --git a/src/main/java/com/twilio/rest/chat/v2/service/Binding.java b/src/main/java/com/twilio/rest/chat/v2/service/Binding.java index 3ace8bfd8d..87b187143a 100644 --- a/src/main/java/com/twilio/rest/chat/v2/service/Binding.java +++ b/src/main/java/com/twilio/rest/chat/v2/service/Binding.java @@ -111,7 +111,7 @@ public static Binding fromJson( private final String endpoint; private final String identity; private final String credentialSid; - private final Binding.BindingType bindingType; + private final BindingType bindingType; private final List messageTypes; private final URI url; private final Map links; @@ -126,7 +126,7 @@ private Binding( @JsonProperty("endpoint") final String endpoint, @JsonProperty("identity") final String identity, @JsonProperty("credential_sid") final String credentialSid, - @JsonProperty("binding_type") final Binding.BindingType bindingType, + @JsonProperty("binding_type") final BindingType bindingType, @JsonProperty("message_types") final List messageTypes, @JsonProperty("url") final URI url, @JsonProperty("links") final Map links @@ -177,7 +177,7 @@ public final String getCredentialSid() { return this.credentialSid; } - public final Binding.BindingType getBindingType() { + public final BindingType getBindingType() { return this.bindingType; } diff --git a/src/main/java/com/twilio/rest/chat/v2/service/Channel.java b/src/main/java/com/twilio/rest/chat/v2/service/Channel.java index d950169893..b4a9182d10 100644 --- a/src/main/java/com/twilio/rest/chat/v2/service/Channel.java +++ b/src/main/java/com/twilio/rest/chat/v2/service/Channel.java @@ -119,7 +119,7 @@ public static Channel fromJson( private final String friendlyName; private final String uniqueName; private final String attributes; - private final Channel.ChannelType type; + private final ChannelType type; private final ZonedDateTime dateCreated; private final ZonedDateTime dateUpdated; private final String createdBy; @@ -136,7 +136,7 @@ private Channel( @JsonProperty("friendly_name") final String friendlyName, @JsonProperty("unique_name") final String uniqueName, @JsonProperty("attributes") final String attributes, - @JsonProperty("type") final Channel.ChannelType type, + @JsonProperty("type") final ChannelType type, @JsonProperty("date_created") final String dateCreated, @JsonProperty("date_updated") final String dateUpdated, @JsonProperty("created_by") final String createdBy, @@ -185,7 +185,7 @@ public final String getAttributes() { return this.attributes; } - public final Channel.ChannelType getType() { + public final ChannelType getType() { return this.type; } diff --git a/src/main/java/com/twilio/rest/chat/v2/service/Role.java b/src/main/java/com/twilio/rest/chat/v2/service/Role.java index 83550db69d..b6dd5785ac 100644 --- a/src/main/java/com/twilio/rest/chat/v2/service/Role.java +++ b/src/main/java/com/twilio/rest/chat/v2/service/Role.java @@ -43,7 +43,7 @@ public class Role extends Resource { public static RoleCreator creator( final String pathServiceSid, final String friendlyName, - final Role.RoleType type, + final RoleType type, final List permission ) { return new RoleCreator(pathServiceSid, friendlyName, type, permission); @@ -122,7 +122,7 @@ public static Role fromJson( private final String accountSid; private final String serviceSid; private final String friendlyName; - private final Role.RoleType type; + private final RoleType type; private final List permissions; private final ZonedDateTime dateCreated; private final ZonedDateTime dateUpdated; @@ -134,7 +134,7 @@ private Role( @JsonProperty("account_sid") final String accountSid, @JsonProperty("service_sid") final String serviceSid, @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("type") final Role.RoleType type, + @JsonProperty("type") final RoleType type, @JsonProperty("permissions") final List permissions, @JsonProperty("date_created") final String dateCreated, @JsonProperty("date_updated") final String dateUpdated, @@ -167,7 +167,7 @@ public final String getFriendlyName() { return this.friendlyName; } - public final Role.RoleType getType() { + public final RoleType getType() { return this.type; } diff --git a/src/main/java/com/twilio/rest/chat/v2/service/channel/Webhook.java b/src/main/java/com/twilio/rest/chat/v2/service/channel/Webhook.java index 969a28cc11..b75b26253e 100644 --- a/src/main/java/com/twilio/rest/chat/v2/service/channel/Webhook.java +++ b/src/main/java/com/twilio/rest/chat/v2/service/channel/Webhook.java @@ -44,7 +44,7 @@ public class Webhook extends Resource { public static WebhookCreator creator( final String pathServiceSid, final String pathChannelSid, - final Webhook.Type type + final Type type ) { return new WebhookCreator(pathServiceSid, pathChannelSid, type); } diff --git a/src/main/java/com/twilio/rest/chat/v2/service/user/UserBinding.java b/src/main/java/com/twilio/rest/chat/v2/service/user/UserBinding.java index f95fefa538..183db9c103 100644 --- a/src/main/java/com/twilio/rest/chat/v2/service/user/UserBinding.java +++ b/src/main/java/com/twilio/rest/chat/v2/service/user/UserBinding.java @@ -115,7 +115,7 @@ public static UserBinding fromJson( private final String identity; private final String userSid; private final String credentialSid; - private final UserBinding.BindingType bindingType; + private final BindingType bindingType; private final List messageTypes; private final URI url; @@ -130,7 +130,7 @@ private UserBinding( @JsonProperty("identity") final String identity, @JsonProperty("user_sid") final String userSid, @JsonProperty("credential_sid") final String credentialSid, - @JsonProperty("binding_type") final UserBinding.BindingType bindingType, + @JsonProperty("binding_type") final BindingType bindingType, @JsonProperty("message_types") final List messageTypes, @JsonProperty("url") final URI url ) { @@ -184,7 +184,7 @@ public final String getCredentialSid() { return this.credentialSid; } - public final UserBinding.BindingType getBindingType() { + public final BindingType getBindingType() { return this.bindingType; } diff --git a/src/main/java/com/twilio/rest/chat/v2/service/user/UserChannel.java b/src/main/java/com/twilio/rest/chat/v2/service/user/UserChannel.java index ebe37d60ac..3dc09e5aa2 100644 --- a/src/main/java/com/twilio/rest/chat/v2/service/user/UserChannel.java +++ b/src/main/java/com/twilio/rest/chat/v2/service/user/UserChannel.java @@ -130,12 +130,12 @@ public static UserChannel fromJson( private final String channelSid; private final String userSid; private final String memberSid; - private final UserChannel.ChannelStatus status; + private final ChannelStatus status; private final Integer lastConsumedMessageIndex; private final Integer unreadMessagesCount; private final Map links; private final URI url; - private final UserChannel.NotificationLevel notificationLevel; + private final NotificationLevel notificationLevel; @JsonCreator private UserChannel( @@ -144,7 +144,7 @@ private UserChannel( @JsonProperty("channel_sid") final String channelSid, @JsonProperty("user_sid") final String userSid, @JsonProperty("member_sid") final String memberSid, - @JsonProperty("status") final UserChannel.ChannelStatus status, + @JsonProperty("status") final ChannelStatus status, @JsonProperty( "last_consumed_message_index" ) final Integer lastConsumedMessageIndex, @@ -155,7 +155,7 @@ private UserChannel( @JsonProperty("url") final URI url, @JsonProperty( "notification_level" - ) final UserChannel.NotificationLevel notificationLevel + ) final NotificationLevel notificationLevel ) { this.accountSid = accountSid; this.serviceSid = serviceSid; @@ -190,7 +190,7 @@ public final String getMemberSid() { return this.memberSid; } - public final UserChannel.ChannelStatus getStatus() { + public final ChannelStatus getStatus() { return this.status; } @@ -210,7 +210,7 @@ public final URI getUrl() { return this.url; } - public final UserChannel.NotificationLevel getNotificationLevel() { + public final NotificationLevel getNotificationLevel() { return this.notificationLevel; } diff --git a/src/main/java/com/twilio/rest/chat/v3/Channel.java b/src/main/java/com/twilio/rest/chat/v3/Channel.java index a46f618735..b606cf5123 100644 --- a/src/main/java/com/twilio/rest/chat/v3/Channel.java +++ b/src/main/java/com/twilio/rest/chat/v3/Channel.java @@ -95,7 +95,7 @@ public static Channel fromJson( private final String friendlyName; private final String uniqueName; private final String attributes; - private final Channel.ChannelType type; + private final ChannelType type; private final ZonedDateTime dateCreated; private final ZonedDateTime dateUpdated; private final String createdBy; @@ -112,7 +112,7 @@ private Channel( @JsonProperty("friendly_name") final String friendlyName, @JsonProperty("unique_name") final String uniqueName, @JsonProperty("attributes") final String attributes, - @JsonProperty("type") final Channel.ChannelType type, + @JsonProperty("type") final ChannelType type, @JsonProperty("date_created") final String dateCreated, @JsonProperty("date_updated") final String dateUpdated, @JsonProperty("created_by") final String createdBy, @@ -161,7 +161,7 @@ public final String getAttributes() { return this.attributes; } - public final Channel.ChannelType getType() { + public final ChannelType getType() { return this.type; } diff --git a/src/main/java/com/twilio/rest/content/v1/Content.java b/src/main/java/com/twilio/rest/content/v1/Content.java index addc44ae73..15b9fb92e2 100644 --- a/src/main/java/com/twilio/rest/content/v1/Content.java +++ b/src/main/java/com/twilio/rest/content/v1/Content.java @@ -942,7 +942,7 @@ public static ContentCreateRequest fromJson( } public static ContentCreator creator( - final Content.ContentCreateRequest contentCreateRequest + final ContentCreateRequest contentCreateRequest ) { return new ContentCreator(contentCreateRequest); } diff --git a/src/main/java/com/twilio/rest/content/v1/content/ApprovalCreate.java b/src/main/java/com/twilio/rest/content/v1/content/ApprovalCreate.java index aff2efdaf5..f8856de11a 100644 --- a/src/main/java/com/twilio/rest/content/v1/content/ApprovalCreate.java +++ b/src/main/java/com/twilio/rest/content/v1/content/ApprovalCreate.java @@ -72,7 +72,7 @@ public static ContentApprovalRequest fromJson( public static ApprovalCreateCreator creator( final String pathContentSid, - final ApprovalCreate.ContentApprovalRequest contentApprovalRequest + final ContentApprovalRequest contentApprovalRequest ) { return new ApprovalCreateCreator( pathContentSid, diff --git a/src/main/java/com/twilio/rest/conversations/v1/AddressConfiguration.java b/src/main/java/com/twilio/rest/conversations/v1/AddressConfiguration.java index e621325249..2aac078a95 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/AddressConfiguration.java +++ b/src/main/java/com/twilio/rest/conversations/v1/AddressConfiguration.java @@ -42,7 +42,7 @@ public class AddressConfiguration extends Resource { private static final long serialVersionUID = 162346024858734L; public static AddressConfigurationCreator creator( - final AddressConfiguration.Type type, + final Type type, final String address ) { return new AddressConfigurationCreator(type, address); @@ -246,19 +246,13 @@ public static AutoCreationType forValue(final String value) { } } - public enum Type { - SMS("sms"), - WHATSAPP("whatsapp"), - MESSENGER("messenger"), - GBM("gbm"), - EMAIL("email"), - RCS("rcs"), - APPLE("apple"), - CHAT("chat"); + public enum Method { + GET("get"), + POST("post"); private final String value; - private Type(final String value) { + private Method(final String value) { this.value = value; } @@ -267,18 +261,24 @@ public String toString() { } @JsonCreator - public static Type forValue(final String value) { - return Promoter.enumFromString(value, Type.values()); + public static Method forValue(final String value) { + return Promoter.enumFromString(value, Method.values()); } } - public enum Method { - GET("GET"), - POST("POST"); + public enum Type { + SMS("sms"), + WHATSAPP("whatsapp"), + MESSENGER("messenger"), + GBM("gbm"), + EMAIL("email"), + RCS("rcs"), + APPLE("apple"), + CHAT("chat"); private final String value; - private Method(final String value) { + private Type(final String value) { this.value = value; } @@ -287,8 +287,8 @@ public String toString() { } @JsonCreator - public static Method forValue(final String value) { - return Promoter.enumFromString(value, Method.values()); + public static Type forValue(final String value) { + return Promoter.enumFromString(value, Type.values()); } } } diff --git a/src/main/java/com/twilio/rest/conversations/v1/Conversation.java b/src/main/java/com/twilio/rest/conversations/v1/Conversation.java index dc54e2affc..652dbc936b 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/Conversation.java +++ b/src/main/java/com/twilio/rest/conversations/v1/Conversation.java @@ -111,7 +111,7 @@ public static Conversation fromJson( private final String friendlyName; private final String uniqueName; private final String attributes; - private final Conversation.State state; + private final State state; private final ZonedDateTime dateCreated; private final ZonedDateTime dateUpdated; private final Map timers; @@ -128,7 +128,7 @@ private Conversation( @JsonProperty("friendly_name") final String friendlyName, @JsonProperty("unique_name") final String uniqueName, @JsonProperty("attributes") final String attributes, - @JsonProperty("state") final Conversation.State state, + @JsonProperty("state") final State state, @JsonProperty("date_created") final String dateCreated, @JsonProperty("date_updated") final String dateUpdated, @JsonProperty("timers") final Map timers, @@ -180,7 +180,7 @@ public final String getAttributes() { return this.attributes; } - public final Conversation.State getState() { + public final State getState() { return this.state; } diff --git a/src/main/java/com/twilio/rest/conversations/v1/ConversationWithParticipants.java b/src/main/java/com/twilio/rest/conversations/v1/ConversationWithParticipants.java index ac73b9afa2..26439f0d4f 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/ConversationWithParticipants.java +++ b/src/main/java/com/twilio/rest/conversations/v1/ConversationWithParticipants.java @@ -101,7 +101,7 @@ public static ConversationWithParticipants fromJson( private final String friendlyName; private final String uniqueName; private final String attributes; - private final ConversationWithParticipants.State state; + private final State state; private final ZonedDateTime dateCreated; private final ZonedDateTime dateUpdated; private final Map timers; @@ -118,7 +118,7 @@ private ConversationWithParticipants( @JsonProperty("friendly_name") final String friendlyName, @JsonProperty("unique_name") final String uniqueName, @JsonProperty("attributes") final String attributes, - @JsonProperty("state") final ConversationWithParticipants.State state, + @JsonProperty("state") final State state, @JsonProperty("date_created") final String dateCreated, @JsonProperty("date_updated") final String dateUpdated, @JsonProperty("timers") final Map timers, @@ -170,7 +170,7 @@ public final String getAttributes() { return this.attributes; } - public final ConversationWithParticipants.State getState() { + public final State getState() { return this.state; } diff --git a/src/main/java/com/twilio/rest/conversations/v1/Credential.java b/src/main/java/com/twilio/rest/conversations/v1/Credential.java index 9b3cc9b62d..5d22d8174e 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/Credential.java +++ b/src/main/java/com/twilio/rest/conversations/v1/Credential.java @@ -39,7 +39,7 @@ public class Credential extends Resource { private static final long serialVersionUID = 265726674321801L; - public static CredentialCreator creator(final Credential.PushType type) { + public static CredentialCreator creator(final PushType type) { return new CredentialCreator(type); } @@ -105,7 +105,7 @@ public static Credential fromJson( private final String sid; private final String accountSid; private final String friendlyName; - private final Credential.PushType type; + private final PushType type; private final String sandbox; private final ZonedDateTime dateCreated; private final ZonedDateTime dateUpdated; @@ -116,7 +116,7 @@ private Credential( @JsonProperty("sid") final String sid, @JsonProperty("account_sid") final String accountSid, @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("type") final Credential.PushType type, + @JsonProperty("type") final PushType type, @JsonProperty("sandbox") final String sandbox, @JsonProperty("date_created") final String dateCreated, @JsonProperty("date_updated") final String dateUpdated, @@ -144,7 +144,7 @@ public final String getFriendlyName() { return this.friendlyName; } - public final Credential.PushType getType() { + public final PushType getType() { return this.type; } diff --git a/src/main/java/com/twilio/rest/conversations/v1/ParticipantConversation.java b/src/main/java/com/twilio/rest/conversations/v1/ParticipantConversation.java index 49b97fb0c4..e6dd3cfc82 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/ParticipantConversation.java +++ b/src/main/java/com/twilio/rest/conversations/v1/ParticipantConversation.java @@ -100,7 +100,7 @@ public static ParticipantConversation fromJson( private final ZonedDateTime conversationDateCreated; private final ZonedDateTime conversationDateUpdated; private final String conversationCreatedBy; - private final ParticipantConversation.State conversationState; + private final State conversationState; private final Map conversationTimers; private final Map links; @@ -134,9 +134,7 @@ private ParticipantConversation( @JsonProperty( "conversation_created_by" ) final String conversationCreatedBy, - @JsonProperty( - "conversation_state" - ) final ParticipantConversation.State conversationState, + @JsonProperty("conversation_state") final State conversationState, @JsonProperty("conversation_timers") final Map< String, Object @@ -215,7 +213,7 @@ public final String getConversationCreatedBy() { return this.conversationCreatedBy; } - public final ParticipantConversation.State getConversationState() { + public final State getConversationState() { return this.conversationState; } diff --git a/src/main/java/com/twilio/rest/conversations/v1/Role.java b/src/main/java/com/twilio/rest/conversations/v1/Role.java index 96ca04b94e..c20cf35b53 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/Role.java +++ b/src/main/java/com/twilio/rest/conversations/v1/Role.java @@ -42,7 +42,7 @@ public class Role extends Resource { public static RoleCreator creator( final String friendlyName, - final Role.RoleType type, + final RoleType type, final List permission ) { return new RoleCreator(friendlyName, type, permission); @@ -114,7 +114,7 @@ public static Role fromJson( private final String accountSid; private final String chatServiceSid; private final String friendlyName; - private final Role.RoleType type; + private final RoleType type; private final List permissions; private final ZonedDateTime dateCreated; private final ZonedDateTime dateUpdated; @@ -126,7 +126,7 @@ private Role( @JsonProperty("account_sid") final String accountSid, @JsonProperty("chat_service_sid") final String chatServiceSid, @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("type") final Role.RoleType type, + @JsonProperty("type") final RoleType type, @JsonProperty("permissions") final List permissions, @JsonProperty("date_created") final String dateCreated, @JsonProperty("date_updated") final String dateUpdated, @@ -159,7 +159,7 @@ public final String getFriendlyName() { return this.friendlyName; } - public final Role.RoleType getType() { + public final RoleType getType() { return this.type; } diff --git a/src/main/java/com/twilio/rest/conversations/v1/configuration/Webhook.java b/src/main/java/com/twilio/rest/conversations/v1/configuration/Webhook.java index 485c684771..7633382178 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/configuration/Webhook.java +++ b/src/main/java/com/twilio/rest/conversations/v1/configuration/Webhook.java @@ -90,21 +90,21 @@ public static Webhook fromJson( } private final String accountSid; - private final Webhook.Method method; + private final Method method; private final List filters; private final String preWebhookUrl; private final String postWebhookUrl; - private final Webhook.Target target; + private final Target target; private final URI url; @JsonCreator private Webhook( @JsonProperty("account_sid") final String accountSid, - @JsonProperty("method") final Webhook.Method method, + @JsonProperty("method") final Method method, @JsonProperty("filters") final List filters, @JsonProperty("pre_webhook_url") final String preWebhookUrl, @JsonProperty("post_webhook_url") final String postWebhookUrl, - @JsonProperty("target") final Webhook.Target target, + @JsonProperty("target") final Target target, @JsonProperty("url") final URI url ) { this.accountSid = accountSid; @@ -120,7 +120,7 @@ public final String getAccountSid() { return this.accountSid; } - public final Webhook.Method getMethod() { + public final Method getMethod() { return this.method; } @@ -136,7 +136,7 @@ public final String getPostWebhookUrl() { return this.postWebhookUrl; } - public final Webhook.Target getTarget() { + public final Target getTarget() { return this.target; } diff --git a/src/main/java/com/twilio/rest/conversations/v1/conversation/Webhook.java b/src/main/java/com/twilio/rest/conversations/v1/conversation/Webhook.java index f6da62268d..25b7ac3b9a 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/conversation/Webhook.java +++ b/src/main/java/com/twilio/rest/conversations/v1/conversation/Webhook.java @@ -43,7 +43,7 @@ public class Webhook extends Resource { public static WebhookCreator creator( final String pathConversationSid, - final Webhook.Target target + final Target target ) { return new WebhookCreator(pathConversationSid, target); } @@ -238,8 +238,8 @@ public static Target forValue(final String value) { } public enum Method { - GET("GET"), - POST("POST"); + GET("get"), + POST("post"); private final String value; diff --git a/src/main/java/com/twilio/rest/conversations/v1/conversation/message/DeliveryReceipt.java b/src/main/java/com/twilio/rest/conversations/v1/conversation/message/DeliveryReceipt.java index 5e5098d0a9..b65ea7716d 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/conversation/message/DeliveryReceipt.java +++ b/src/main/java/com/twilio/rest/conversations/v1/conversation/message/DeliveryReceipt.java @@ -107,7 +107,7 @@ public static DeliveryReceipt fromJson( private final String messageSid; private final String channelMessageSid; private final String participantSid; - private final DeliveryReceipt.DeliveryStatus status; + private final DeliveryStatus status; private final Integer errorCode; private final ZonedDateTime dateCreated; private final ZonedDateTime dateUpdated; @@ -121,7 +121,7 @@ private DeliveryReceipt( @JsonProperty("message_sid") final String messageSid, @JsonProperty("channel_message_sid") final String channelMessageSid, @JsonProperty("participant_sid") final String participantSid, - @JsonProperty("status") final DeliveryReceipt.DeliveryStatus status, + @JsonProperty("status") final DeliveryStatus status, @JsonProperty("error_code") final Integer errorCode, @JsonProperty("date_created") final String dateCreated, @JsonProperty("date_updated") final String dateUpdated, @@ -164,7 +164,7 @@ public final String getParticipantSid() { return this.participantSid; } - public final DeliveryReceipt.DeliveryStatus getStatus() { + public final DeliveryStatus getStatus() { return this.status; } diff --git a/src/main/java/com/twilio/rest/conversations/v1/service/Binding.java b/src/main/java/com/twilio/rest/conversations/v1/service/Binding.java index 0c10c7165f..dd66e34198 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/service/Binding.java +++ b/src/main/java/com/twilio/rest/conversations/v1/service/Binding.java @@ -109,7 +109,7 @@ public static Binding fromJson( private final ZonedDateTime dateUpdated; private final String endpoint; private final String identity; - private final Binding.BindingType bindingType; + private final BindingType bindingType; private final List messageTypes; private final URI url; @@ -123,7 +123,7 @@ private Binding( @JsonProperty("date_updated") final String dateUpdated, @JsonProperty("endpoint") final String endpoint, @JsonProperty("identity") final String identity, - @JsonProperty("binding_type") final Binding.BindingType bindingType, + @JsonProperty("binding_type") final BindingType bindingType, @JsonProperty("message_types") final List messageTypes, @JsonProperty("url") final URI url ) { @@ -172,7 +172,7 @@ public final String getIdentity() { return this.identity; } - public final Binding.BindingType getBindingType() { + public final BindingType getBindingType() { return this.bindingType; } diff --git a/src/main/java/com/twilio/rest/conversations/v1/service/Conversation.java b/src/main/java/com/twilio/rest/conversations/v1/service/Conversation.java index 181767e7e6..f4aed3b123 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/service/Conversation.java +++ b/src/main/java/com/twilio/rest/conversations/v1/service/Conversation.java @@ -120,7 +120,7 @@ public static Conversation fromJson( private final String friendlyName; private final String uniqueName; private final String attributes; - private final Conversation.State state; + private final State state; private final ZonedDateTime dateCreated; private final ZonedDateTime dateUpdated; private final Map timers; @@ -137,7 +137,7 @@ private Conversation( @JsonProperty("friendly_name") final String friendlyName, @JsonProperty("unique_name") final String uniqueName, @JsonProperty("attributes") final String attributes, - @JsonProperty("state") final Conversation.State state, + @JsonProperty("state") final State state, @JsonProperty("date_created") final String dateCreated, @JsonProperty("date_updated") final String dateUpdated, @JsonProperty("timers") final Map timers, @@ -189,7 +189,7 @@ public final String getAttributes() { return this.attributes; } - public final Conversation.State getState() { + public final State getState() { return this.state; } diff --git a/src/main/java/com/twilio/rest/conversations/v1/service/ConversationWithParticipants.java b/src/main/java/com/twilio/rest/conversations/v1/service/ConversationWithParticipants.java index 939f0389d7..50554a0254 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/service/ConversationWithParticipants.java +++ b/src/main/java/com/twilio/rest/conversations/v1/service/ConversationWithParticipants.java @@ -103,7 +103,7 @@ public static ConversationWithParticipants fromJson( private final String friendlyName; private final String uniqueName; private final String attributes; - private final ConversationWithParticipants.State state; + private final State state; private final ZonedDateTime dateCreated; private final ZonedDateTime dateUpdated; private final Map timers; @@ -120,7 +120,7 @@ private ConversationWithParticipants( @JsonProperty("friendly_name") final String friendlyName, @JsonProperty("unique_name") final String uniqueName, @JsonProperty("attributes") final String attributes, - @JsonProperty("state") final ConversationWithParticipants.State state, + @JsonProperty("state") final State state, @JsonProperty("date_created") final String dateCreated, @JsonProperty("date_updated") final String dateUpdated, @JsonProperty("timers") final Map timers, @@ -172,7 +172,7 @@ public final String getAttributes() { return this.attributes; } - public final ConversationWithParticipants.State getState() { + public final State getState() { return this.state; } diff --git a/src/main/java/com/twilio/rest/conversations/v1/service/ParticipantConversation.java b/src/main/java/com/twilio/rest/conversations/v1/service/ParticipantConversation.java index 7ee5b2860d..8949265dc2 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/service/ParticipantConversation.java +++ b/src/main/java/com/twilio/rest/conversations/v1/service/ParticipantConversation.java @@ -102,7 +102,7 @@ public static ParticipantConversation fromJson( private final ZonedDateTime conversationDateCreated; private final ZonedDateTime conversationDateUpdated; private final String conversationCreatedBy; - private final ParticipantConversation.State conversationState; + private final State conversationState; private final Map conversationTimers; private final Map links; @@ -136,9 +136,7 @@ private ParticipantConversation( @JsonProperty( "conversation_created_by" ) final String conversationCreatedBy, - @JsonProperty( - "conversation_state" - ) final ParticipantConversation.State conversationState, + @JsonProperty("conversation_state") final State conversationState, @JsonProperty("conversation_timers") final Map< String, Object @@ -217,7 +215,7 @@ public final String getConversationCreatedBy() { return this.conversationCreatedBy; } - public final ParticipantConversation.State getConversationState() { + public final State getConversationState() { return this.conversationState; } diff --git a/src/main/java/com/twilio/rest/conversations/v1/service/Role.java b/src/main/java/com/twilio/rest/conversations/v1/service/Role.java index 43c80476c7..31e0a6501c 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/service/Role.java +++ b/src/main/java/com/twilio/rest/conversations/v1/service/Role.java @@ -43,7 +43,7 @@ public class Role extends Resource { public static RoleCreator creator( final String pathChatServiceSid, final String friendlyName, - final Role.RoleType type, + final RoleType type, final List permission ) { return new RoleCreator( @@ -127,7 +127,7 @@ public static Role fromJson( private final String accountSid; private final String chatServiceSid; private final String friendlyName; - private final Role.RoleType type; + private final RoleType type; private final List permissions; private final ZonedDateTime dateCreated; private final ZonedDateTime dateUpdated; @@ -139,7 +139,7 @@ private Role( @JsonProperty("account_sid") final String accountSid, @JsonProperty("chat_service_sid") final String chatServiceSid, @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("type") final Role.RoleType type, + @JsonProperty("type") final RoleType type, @JsonProperty("permissions") final List permissions, @JsonProperty("date_created") final String dateCreated, @JsonProperty("date_updated") final String dateUpdated, @@ -172,7 +172,7 @@ public final String getFriendlyName() { return this.friendlyName; } - public final Role.RoleType getType() { + public final RoleType getType() { return this.type; } diff --git a/src/main/java/com/twilio/rest/conversations/v1/service/configuration/Webhook.java b/src/main/java/com/twilio/rest/conversations/v1/service/configuration/Webhook.java index 9947722db0..a9965ee61f 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/service/configuration/Webhook.java +++ b/src/main/java/com/twilio/rest/conversations/v1/service/configuration/Webhook.java @@ -94,7 +94,7 @@ public static Webhook fromJson( private final URI preWebhookUrl; private final URI postWebhookUrl; private final List filters; - private final Webhook.Method method; + private final Method method; private final URI url; @JsonCreator @@ -104,7 +104,7 @@ private Webhook( @JsonProperty("pre_webhook_url") final URI preWebhookUrl, @JsonProperty("post_webhook_url") final URI postWebhookUrl, @JsonProperty("filters") final List filters, - @JsonProperty("method") final Webhook.Method method, + @JsonProperty("method") final Method method, @JsonProperty("url") final URI url ) { this.accountSid = accountSid; @@ -136,7 +136,7 @@ public final List getFilters() { return this.filters; } - public final Webhook.Method getMethod() { + public final Method getMethod() { return this.method; } diff --git a/src/main/java/com/twilio/rest/conversations/v1/service/conversation/Webhook.java b/src/main/java/com/twilio/rest/conversations/v1/service/conversation/Webhook.java index dfaee4587f..f60058cb16 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/service/conversation/Webhook.java +++ b/src/main/java/com/twilio/rest/conversations/v1/service/conversation/Webhook.java @@ -44,7 +44,7 @@ public class Webhook extends Resource { public static WebhookCreator creator( final String pathChatServiceSid, final String pathConversationSid, - final Webhook.Target target + final Target target ) { return new WebhookCreator( pathChatServiceSid, @@ -270,8 +270,8 @@ public static Target forValue(final String value) { } public enum Method { - GET("GET"), - POST("POST"); + GET("get"), + POST("post"); private final String value; diff --git a/src/main/java/com/twilio/rest/conversations/v1/service/conversation/message/DeliveryReceipt.java b/src/main/java/com/twilio/rest/conversations/v1/service/conversation/message/DeliveryReceipt.java index f3a9dd829d..da0e2d35ee 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/service/conversation/message/DeliveryReceipt.java +++ b/src/main/java/com/twilio/rest/conversations/v1/service/conversation/message/DeliveryReceipt.java @@ -115,7 +115,7 @@ public static DeliveryReceipt fromJson( private final String sid; private final String channelMessageSid; private final String participantSid; - private final DeliveryReceipt.DeliveryStatus status; + private final DeliveryStatus status; private final Integer errorCode; private final ZonedDateTime dateCreated; private final ZonedDateTime dateUpdated; @@ -130,7 +130,7 @@ private DeliveryReceipt( @JsonProperty("sid") final String sid, @JsonProperty("channel_message_sid") final String channelMessageSid, @JsonProperty("participant_sid") final String participantSid, - @JsonProperty("status") final DeliveryReceipt.DeliveryStatus status, + @JsonProperty("status") final DeliveryStatus status, @JsonProperty("error_code") final Integer errorCode, @JsonProperty("date_created") final String dateCreated, @JsonProperty("date_updated") final String dateUpdated, @@ -178,7 +178,7 @@ public final String getParticipantSid() { return this.participantSid; } - public final DeliveryReceipt.DeliveryStatus getStatus() { + public final DeliveryStatus getStatus() { return this.status; } diff --git a/src/main/java/com/twilio/rest/conversations/v1/service/user/UserConversation.java b/src/main/java/com/twilio/rest/conversations/v1/service/user/UserConversation.java index 555ae5a2c6..42aecbd226 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/service/user/UserConversation.java +++ b/src/main/java/com/twilio/rest/conversations/v1/service/user/UserConversation.java @@ -135,13 +135,13 @@ public static UserConversation fromJson( private final String participantSid; private final String userSid; private final String friendlyName; - private final UserConversation.State conversationState; + private final State conversationState; private final Map timers; private final String attributes; private final ZonedDateTime dateCreated; private final ZonedDateTime dateUpdated; private final String createdBy; - private final UserConversation.NotificationLevel notificationLevel; + private final NotificationLevel notificationLevel; private final String uniqueName; private final URI url; private final Map links; @@ -160,9 +160,7 @@ private UserConversation( @JsonProperty("participant_sid") final String participantSid, @JsonProperty("user_sid") final String userSid, @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty( - "conversation_state" - ) final UserConversation.State conversationState, + @JsonProperty("conversation_state") final State conversationState, @JsonProperty("timers") final Map timers, @JsonProperty("attributes") final String attributes, @JsonProperty("date_created") final String dateCreated, @@ -170,7 +168,7 @@ private UserConversation( @JsonProperty("created_by") final String createdBy, @JsonProperty( "notification_level" - ) final UserConversation.NotificationLevel notificationLevel, + ) final NotificationLevel notificationLevel, @JsonProperty("unique_name") final String uniqueName, @JsonProperty("url") final URI url, @JsonProperty("links") final Map links @@ -227,7 +225,7 @@ public final String getFriendlyName() { return this.friendlyName; } - public final UserConversation.State getConversationState() { + public final State getConversationState() { return this.conversationState; } @@ -251,7 +249,7 @@ public final String getCreatedBy() { return this.createdBy; } - public final UserConversation.NotificationLevel getNotificationLevel() { + public final NotificationLevel getNotificationLevel() { return this.notificationLevel; } diff --git a/src/main/java/com/twilio/rest/conversations/v1/user/UserConversation.java b/src/main/java/com/twilio/rest/conversations/v1/user/UserConversation.java index 2b21907430..58fc49a1d0 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/user/UserConversation.java +++ b/src/main/java/com/twilio/rest/conversations/v1/user/UserConversation.java @@ -117,13 +117,13 @@ public static UserConversation fromJson( private final String participantSid; private final String userSid; private final String friendlyName; - private final UserConversation.State conversationState; + private final State conversationState; private final Map timers; private final String attributes; private final ZonedDateTime dateCreated; private final ZonedDateTime dateUpdated; private final String createdBy; - private final UserConversation.NotificationLevel notificationLevel; + private final NotificationLevel notificationLevel; private final String uniqueName; private final URI url; private final Map links; @@ -142,9 +142,7 @@ private UserConversation( @JsonProperty("participant_sid") final String participantSid, @JsonProperty("user_sid") final String userSid, @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty( - "conversation_state" - ) final UserConversation.State conversationState, + @JsonProperty("conversation_state") final State conversationState, @JsonProperty("timers") final Map timers, @JsonProperty("attributes") final String attributes, @JsonProperty("date_created") final String dateCreated, @@ -152,7 +150,7 @@ private UserConversation( @JsonProperty("created_by") final String createdBy, @JsonProperty( "notification_level" - ) final UserConversation.NotificationLevel notificationLevel, + ) final NotificationLevel notificationLevel, @JsonProperty("unique_name") final String uniqueName, @JsonProperty("url") final URI url, @JsonProperty("links") final Map links @@ -209,7 +207,7 @@ public final String getFriendlyName() { return this.friendlyName; } - public final UserConversation.State getConversationState() { + public final State getConversationState() { return this.conversationState; } @@ -233,7 +231,7 @@ public final String getCreatedBy() { return this.createdBy; } - public final UserConversation.NotificationLevel getNotificationLevel() { + public final NotificationLevel getNotificationLevel() { return this.notificationLevel; } diff --git a/src/main/java/com/twilio/rest/events/v1/Sink.java b/src/main/java/com/twilio/rest/events/v1/Sink.java index 1a0f0eb112..1d8a20eb62 100644 --- a/src/main/java/com/twilio/rest/events/v1/Sink.java +++ b/src/main/java/com/twilio/rest/events/v1/Sink.java @@ -43,8 +43,8 @@ public class Sink extends Resource { public static SinkCreator creator( final String description, - final Map sinkConfiguration, - final Sink.SinkType sinkType + final Object sinkConfiguration, + final SinkType sinkType ) { return new SinkCreator(description, sinkConfiguration, sinkType); } @@ -116,8 +116,8 @@ public static Sink fromJson( private final String description; private final String sid; private final Map sinkConfiguration; - private final Sink.SinkType sinkType; - private final Sink.Status status; + private final SinkType sinkType; + private final Status status; private final URI url; private final Map links; @@ -131,8 +131,8 @@ private Sink( String, Object > sinkConfiguration, - @JsonProperty("sink_type") final Sink.SinkType sinkType, - @JsonProperty("status") final Sink.Status status, + @JsonProperty("sink_type") final SinkType sinkType, + @JsonProperty("status") final Status status, @JsonProperty("url") final URI url, @JsonProperty("links") final Map links ) { @@ -167,11 +167,11 @@ public final Map getSinkConfiguration() { return this.sinkConfiguration; } - public final Sink.SinkType getSinkType() { + public final SinkType getSinkType() { return this.sinkType; } - public final Sink.Status getStatus() { + public final Status getStatus() { return this.status; } diff --git a/src/main/java/com/twilio/rest/events/v1/SinkCreator.java b/src/main/java/com/twilio/rest/events/v1/SinkCreator.java index 781066e4cd..632c1d9aec 100644 --- a/src/main/java/com/twilio/rest/events/v1/SinkCreator.java +++ b/src/main/java/com/twilio/rest/events/v1/SinkCreator.java @@ -26,18 +26,16 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -import java.util.Map; -import java.util.Map; public class SinkCreator extends Creator { private String description; - private Map sinkConfiguration; + private Object sinkConfiguration; private Sink.SinkType sinkType; public SinkCreator( final String description, - final Map sinkConfiguration, + final Object sinkConfiguration, final Sink.SinkType sinkType ) { this.description = description; @@ -50,9 +48,7 @@ public SinkCreator setDescription(final String description) { return this; } - public SinkCreator setSinkConfiguration( - final Map sinkConfiguration - ) { + public SinkCreator setSinkConfiguration(final Object sinkConfiguration) { this.sinkConfiguration = sinkConfiguration; return this; } @@ -114,7 +110,7 @@ private void addPostParams(final Request request) { if (sinkConfiguration != null) { request.addPostParam( "SinkConfiguration", - Converter.mapToJson(sinkConfiguration) + Converter.objectToJson(sinkConfiguration) ); } if (sinkType != null) { diff --git a/src/main/java/com/twilio/rest/events/v1/Subscription.java b/src/main/java/com/twilio/rest/events/v1/Subscription.java index 0a37de2b4a..123ccdbbfc 100644 --- a/src/main/java/com/twilio/rest/events/v1/Subscription.java +++ b/src/main/java/com/twilio/rest/events/v1/Subscription.java @@ -44,7 +44,7 @@ public class Subscription extends Resource { public static SubscriptionCreator creator( final String description, final String sinkSid, - final List> types + final List types ) { return new SubscriptionCreator(description, sinkSid, types); } diff --git a/src/main/java/com/twilio/rest/events/v1/SubscriptionCreator.java b/src/main/java/com/twilio/rest/events/v1/SubscriptionCreator.java index 449e4aa7cd..e82e798efa 100644 --- a/src/main/java/com/twilio/rest/events/v1/SubscriptionCreator.java +++ b/src/main/java/com/twilio/rest/events/v1/SubscriptionCreator.java @@ -16,8 +16,6 @@ import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; -import com.twilio.converter.Converter; -import com.twilio.converter.Converter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; @@ -29,19 +27,17 @@ import com.twilio.rest.Domains; import java.util.List; import java.util.List; -import java.util.Map; -import java.util.Map; public class SubscriptionCreator extends Creator { private String description; private String sinkSid; - private List> types; + private List types; public SubscriptionCreator( final String description, final String sinkSid, - final List> types + final List types ) { this.description = description; this.sinkSid = sinkSid; @@ -58,12 +54,12 @@ public SubscriptionCreator setSinkSid(final String sinkSid) { return this; } - public SubscriptionCreator setTypes(final List> types) { + public SubscriptionCreator setTypes(final List types) { this.types = types; return this; } - public SubscriptionCreator setTypes(final Map types) { + public SubscriptionCreator setTypes(final Object types) { return setTypes(Promoter.listOfOne(types)); } @@ -119,8 +115,8 @@ private void addPostParams(final Request request) { request.addPostParam("SinkSid", sinkSid); } if (types != null) { - for (Map prop : types) { - request.addPostParam("Types", Converter.mapToJson(prop)); + for (Object prop : types) { + request.addPostParam("Types", prop.toString()); } } } diff --git a/src/main/java/com/twilio/rest/flexapi/v1/Configuration.java b/src/main/java/com/twilio/rest/flexapi/v1/Configuration.java index 79e780fa58..42346f69ce 100644 --- a/src/main/java/com/twilio/rest/flexapi/v1/Configuration.java +++ b/src/main/java/com/twilio/rest/flexapi/v1/Configuration.java @@ -110,7 +110,7 @@ public static String toJson(Object object, ObjectMapper mapper) { private final ZonedDateTime dateCreated; private final ZonedDateTime dateUpdated; private final Map attributes; - private final Configuration.Status status; + private final Status status; private final String taskrouterWorkspaceSid; private final String taskrouterTargetWorkflowSid; private final String taskrouterTargetTaskqueueSid; @@ -162,7 +162,7 @@ private Configuration( @JsonProperty("date_created") final String dateCreated, @JsonProperty("date_updated") final String dateUpdated, @JsonProperty("attributes") final Map attributes, - @JsonProperty("status") final Configuration.Status status, + @JsonProperty("status") final Status status, @JsonProperty( "taskrouter_workspace_sid" ) final String taskrouterWorkspaceSid, @@ -343,7 +343,7 @@ public final Map getAttributes() { return this.attributes; } - public final Configuration.Status getStatus() { + public final Status getStatus() { return this.status; } diff --git a/src/main/java/com/twilio/rest/flexapi/v1/FlexFlow.java b/src/main/java/com/twilio/rest/flexapi/v1/FlexFlow.java index ecfe3be905..ef505f09b5 100644 --- a/src/main/java/com/twilio/rest/flexapi/v1/FlexFlow.java +++ b/src/main/java/com/twilio/rest/flexapi/v1/FlexFlow.java @@ -44,7 +44,7 @@ public class FlexFlow extends Resource { public static FlexFlowCreator creator( final String friendlyName, final String chatServiceSid, - final FlexFlow.ChannelType channelType + final ChannelType channelType ) { return new FlexFlowCreator(friendlyName, chatServiceSid, channelType); } @@ -114,10 +114,10 @@ public static FlexFlow fromJson( private final String sid; private final String friendlyName; private final String chatServiceSid; - private final FlexFlow.ChannelType channelType; + private final ChannelType channelType; private final String contactIdentity; private final Boolean enabled; - private final FlexFlow.IntegrationType integrationType; + private final IntegrationType integrationType; private final Map integration; private final Boolean longLived; private final Boolean janitorEnabled; @@ -131,12 +131,10 @@ private FlexFlow( @JsonProperty("sid") final String sid, @JsonProperty("friendly_name") final String friendlyName, @JsonProperty("chat_service_sid") final String chatServiceSid, - @JsonProperty("channel_type") final FlexFlow.ChannelType channelType, + @JsonProperty("channel_type") final ChannelType channelType, @JsonProperty("contact_identity") final String contactIdentity, @JsonProperty("enabled") final Boolean enabled, - @JsonProperty( - "integration_type" - ) final FlexFlow.IntegrationType integrationType, + @JsonProperty("integration_type") final IntegrationType integrationType, @JsonProperty("integration") final Map integration, @JsonProperty("long_lived") final Boolean longLived, @JsonProperty("janitor_enabled") final Boolean janitorEnabled, @@ -182,7 +180,7 @@ public final String getChatServiceSid() { return this.chatServiceSid; } - public final FlexFlow.ChannelType getChannelType() { + public final ChannelType getChannelType() { return this.channelType; } @@ -194,7 +192,7 @@ public final Boolean getEnabled() { return this.enabled; } - public final FlexFlow.IntegrationType getIntegrationType() { + public final IntegrationType getIntegrationType() { return this.integrationType; } diff --git a/src/main/java/com/twilio/rest/flexapi/v1/Interaction.java b/src/main/java/com/twilio/rest/flexapi/v1/Interaction.java index 9bce2d74ec..99af3da8ff 100644 --- a/src/main/java/com/twilio/rest/flexapi/v1/Interaction.java +++ b/src/main/java/com/twilio/rest/flexapi/v1/Interaction.java @@ -38,9 +38,7 @@ public class Interaction extends Resource { private static final long serialVersionUID = 256485735361091L; - public static InteractionCreator creator( - final Map channel - ) { + public static InteractionCreator creator(final Object channel) { return new InteractionCreator(channel); } diff --git a/src/main/java/com/twilio/rest/flexapi/v1/InteractionCreator.java b/src/main/java/com/twilio/rest/flexapi/v1/InteractionCreator.java index fa70c4a23e..4ac64c4b4a 100644 --- a/src/main/java/com/twilio/rest/flexapi/v1/InteractionCreator.java +++ b/src/main/java/com/twilio/rest/flexapi/v1/InteractionCreator.java @@ -26,26 +26,24 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -import java.util.Map; -import java.util.Map; public class InteractionCreator extends Creator { - private Map channel; - private Map routing; + private Object channel; + private Object routing; private String interactionContextSid; private String webhookTtid; - public InteractionCreator(final Map channel) { + public InteractionCreator(final Object channel) { this.channel = channel; } - public InteractionCreator setChannel(final Map channel) { + public InteractionCreator setChannel(final Object channel) { this.channel = channel; return this; } - public InteractionCreator setRouting(final Map routing) { + public InteractionCreator setRouting(final Object routing) { this.routing = routing; return this; } @@ -102,10 +100,10 @@ public Interaction create(final TwilioRestClient client) { private void addPostParams(final Request request) { if (channel != null) { - request.addPostParam("Channel", Converter.mapToJson(channel)); + request.addPostParam("Channel", Converter.objectToJson(channel)); } if (routing != null) { - request.addPostParam("Routing", Converter.mapToJson(routing)); + request.addPostParam("Routing", Converter.objectToJson(routing)); } if (interactionContextSid != null) { request.addPostParam( diff --git a/src/main/java/com/twilio/rest/flexapi/v1/PluginConfigurationCreator.java b/src/main/java/com/twilio/rest/flexapi/v1/PluginConfigurationCreator.java index 0450fd0ae1..d55ca90f44 100644 --- a/src/main/java/com/twilio/rest/flexapi/v1/PluginConfigurationCreator.java +++ b/src/main/java/com/twilio/rest/flexapi/v1/PluginConfigurationCreator.java @@ -16,8 +16,6 @@ import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; -import com.twilio.converter.Converter; -import com.twilio.converter.Converter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; @@ -29,14 +27,12 @@ import com.twilio.rest.Domains; import java.util.List; import java.util.List; -import java.util.Map; -import java.util.Map; public class PluginConfigurationCreator extends Creator { private String name; private String flexMetadata; - private List> plugins; + private List plugins; private String description; public PluginConfigurationCreator(final String name) { @@ -55,16 +51,12 @@ public PluginConfigurationCreator setFlexMetadata( return this; } - public PluginConfigurationCreator setPlugins( - final List> plugins - ) { + public PluginConfigurationCreator setPlugins(final List plugins) { this.plugins = plugins; return this; } - public PluginConfigurationCreator setPlugins( - final Map plugins - ) { + public PluginConfigurationCreator setPlugins(final Object plugins) { return setPlugins(Promoter.listOfOne(plugins)); } @@ -117,8 +109,8 @@ private void addPostParams(final Request request) { request.addPostParam("Name", name); } if (plugins != null) { - for (Map prop : plugins) { - request.addPostParam("Plugins", Converter.mapToJson(prop)); + for (Object prop : plugins) { + request.addPostParam("Plugins", prop.toString()); } } if (description != null) { diff --git a/src/main/java/com/twilio/rest/flexapi/v1/ProvisioningStatus.java b/src/main/java/com/twilio/rest/flexapi/v1/ProvisioningStatus.java index 48fd242415..4d04e64e6a 100644 --- a/src/main/java/com/twilio/rest/flexapi/v1/ProvisioningStatus.java +++ b/src/main/java/com/twilio/rest/flexapi/v1/ProvisioningStatus.java @@ -84,19 +84,19 @@ public static ProvisioningStatus fromJson( } } - private final ProvisioningStatus.Status status; + private final Status status; private final URI url; @JsonCreator private ProvisioningStatus( - @JsonProperty("status") final ProvisioningStatus.Status status, + @JsonProperty("status") final Status status, @JsonProperty("url") final URI url ) { this.status = status; this.url = url; } - public final ProvisioningStatus.Status getStatus() { + public final Status getStatus() { return this.status; } diff --git a/src/main/java/com/twilio/rest/flexapi/v1/interaction/InteractionChannel.java b/src/main/java/com/twilio/rest/flexapi/v1/interaction/InteractionChannel.java index 9c1d778e34..628600a80e 100644 --- a/src/main/java/com/twilio/rest/flexapi/v1/interaction/InteractionChannel.java +++ b/src/main/java/com/twilio/rest/flexapi/v1/interaction/InteractionChannel.java @@ -55,7 +55,7 @@ public static InteractionChannelReader reader( public static InteractionChannelUpdater updater( final String pathInteractionSid, final String pathSid, - final InteractionChannel.UpdateChannelStatus status + final UpdateChannelStatus status ) { return new InteractionChannelUpdater( pathInteractionSid, @@ -109,8 +109,8 @@ public static InteractionChannel fromJson( private final String sid; private final String interactionSid; - private final InteractionChannel.Type type; - private final InteractionChannel.ChannelStatus status; + private final Type type; + private final ChannelStatus status; private final Integer errorCode; private final String errorMessage; private final URI url; @@ -120,8 +120,8 @@ public static InteractionChannel fromJson( private InteractionChannel( @JsonProperty("sid") final String sid, @JsonProperty("interaction_sid") final String interactionSid, - @JsonProperty("type") final InteractionChannel.Type type, - @JsonProperty("status") final InteractionChannel.ChannelStatus status, + @JsonProperty("type") final Type type, + @JsonProperty("status") final ChannelStatus status, @JsonProperty("error_code") final Integer errorCode, @JsonProperty("error_message") final String errorMessage, @JsonProperty("url") final URI url, @@ -145,11 +145,11 @@ public final String getInteractionSid() { return this.interactionSid; } - public final InteractionChannel.Type getType() { + public final Type getType() { return this.type; } - public final InteractionChannel.ChannelStatus getStatus() { + public final ChannelStatus getStatus() { return this.status; } diff --git a/src/main/java/com/twilio/rest/flexapi/v1/interaction/InteractionChannelUpdater.java b/src/main/java/com/twilio/rest/flexapi/v1/interaction/InteractionChannelUpdater.java index 22a50f6d76..3c61717b83 100644 --- a/src/main/java/com/twilio/rest/flexapi/v1/interaction/InteractionChannelUpdater.java +++ b/src/main/java/com/twilio/rest/flexapi/v1/interaction/InteractionChannelUpdater.java @@ -25,14 +25,13 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -import java.util.Map; public class InteractionChannelUpdater extends Updater { private String pathInteractionSid; private String pathSid; private InteractionChannel.UpdateChannelStatus status; - private Map routing; + private Object routing; public InteractionChannelUpdater( final String pathInteractionSid, @@ -51,9 +50,7 @@ public InteractionChannelUpdater setStatus( return this; } - public InteractionChannelUpdater setRouting( - final Map routing - ) { + public InteractionChannelUpdater setRouting(final Object routing) { this.routing = routing; return this; } @@ -107,7 +104,7 @@ private void addPostParams(final Request request) { request.addPostParam("Status", status.toString()); } if (routing != null) { - request.addPostParam("Routing", Converter.mapToJson(routing)); + request.addPostParam("Routing", Converter.objectToJson(routing)); } } } diff --git a/src/main/java/com/twilio/rest/flexapi/v1/interaction/interactionchannel/InteractionChannelInvite.java b/src/main/java/com/twilio/rest/flexapi/v1/interaction/interactionchannel/InteractionChannelInvite.java index 6a9e79717b..da656b886a 100644 --- a/src/main/java/com/twilio/rest/flexapi/v1/interaction/interactionchannel/InteractionChannelInvite.java +++ b/src/main/java/com/twilio/rest/flexapi/v1/interaction/interactionchannel/InteractionChannelInvite.java @@ -41,7 +41,7 @@ public class InteractionChannelInvite extends Resource { public static InteractionChannelInviteCreator creator( final String pathInteractionSid, final String pathChannelSid, - final Map routing + final Object routing ) { return new InteractionChannelInviteCreator( pathInteractionSid, diff --git a/src/main/java/com/twilio/rest/flexapi/v1/interaction/interactionchannel/InteractionChannelInviteCreator.java b/src/main/java/com/twilio/rest/flexapi/v1/interaction/interactionchannel/InteractionChannelInviteCreator.java index 94643ed2dd..89dd3e12be 100644 --- a/src/main/java/com/twilio/rest/flexapi/v1/interaction/interactionchannel/InteractionChannelInviteCreator.java +++ b/src/main/java/com/twilio/rest/flexapi/v1/interaction/interactionchannel/InteractionChannelInviteCreator.java @@ -26,29 +26,25 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -import java.util.Map; -import java.util.Map; public class InteractionChannelInviteCreator extends Creator { private String pathInteractionSid; private String pathChannelSid; - private Map routing; + private Object routing; public InteractionChannelInviteCreator( final String pathInteractionSid, final String pathChannelSid, - final Map routing + final Object routing ) { this.pathInteractionSid = pathInteractionSid; this.pathChannelSid = pathChannelSid; this.routing = routing; } - public InteractionChannelInviteCreator setRouting( - final Map routing - ) { + public InteractionChannelInviteCreator setRouting(final Object routing) { this.routing = routing; return this; } @@ -104,7 +100,7 @@ public InteractionChannelInvite create(final TwilioRestClient client) { private void addPostParams(final Request request) { if (routing != null) { - request.addPostParam("Routing", Converter.mapToJson(routing)); + request.addPostParam("Routing", Converter.objectToJson(routing)); } } } diff --git a/src/main/java/com/twilio/rest/flexapi/v1/interaction/interactionchannel/InteractionChannelParticipant.java b/src/main/java/com/twilio/rest/flexapi/v1/interaction/interactionchannel/InteractionChannelParticipant.java index 390638a66e..d23c9ae21d 100644 --- a/src/main/java/com/twilio/rest/flexapi/v1/interaction/interactionchannel/InteractionChannelParticipant.java +++ b/src/main/java/com/twilio/rest/flexapi/v1/interaction/interactionchannel/InteractionChannelParticipant.java @@ -42,8 +42,8 @@ public class InteractionChannelParticipant extends Resource { public static InteractionChannelParticipantCreator creator( final String pathInteractionSid, final String pathChannelSid, - final InteractionChannelParticipant.Type type, - final Map mediaProperties + final Type type, + final Object mediaProperties ) { return new InteractionChannelParticipantCreator( pathInteractionSid, @@ -67,7 +67,7 @@ public static InteractionChannelParticipantUpdater updater( final String pathInteractionSid, final String pathChannelSid, final String pathSid, - final InteractionChannelParticipant.Status status + final Status status ) { return new InteractionChannelParticipantUpdater( pathInteractionSid, @@ -127,7 +127,7 @@ public static InteractionChannelParticipant fromJson( } private final String sid; - private final InteractionChannelParticipant.Type type; + private final Type type; private final String interactionSid; private final String channelSid; private final URI url; @@ -136,7 +136,7 @@ public static InteractionChannelParticipant fromJson( @JsonCreator private InteractionChannelParticipant( @JsonProperty("sid") final String sid, - @JsonProperty("type") final InteractionChannelParticipant.Type type, + @JsonProperty("type") final Type type, @JsonProperty("interaction_sid") final String interactionSid, @JsonProperty("channel_sid") final String channelSid, @JsonProperty("url") final URI url, @@ -157,7 +157,7 @@ public final String getSid() { return this.sid; } - public final InteractionChannelParticipant.Type getType() { + public final Type getType() { return this.type; } diff --git a/src/main/java/com/twilio/rest/flexapi/v1/interaction/interactionchannel/InteractionChannelParticipantCreator.java b/src/main/java/com/twilio/rest/flexapi/v1/interaction/interactionchannel/InteractionChannelParticipantCreator.java index 587a591060..0de36280bf 100644 --- a/src/main/java/com/twilio/rest/flexapi/v1/interaction/interactionchannel/InteractionChannelParticipantCreator.java +++ b/src/main/java/com/twilio/rest/flexapi/v1/interaction/interactionchannel/InteractionChannelParticipantCreator.java @@ -26,8 +26,6 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -import java.util.Map; -import java.util.Map; public class InteractionChannelParticipantCreator extends Creator { @@ -35,14 +33,14 @@ public class InteractionChannelParticipantCreator private String pathInteractionSid; private String pathChannelSid; private InteractionChannelParticipant.Type type; - private Map mediaProperties; - private Map routingProperties; + private Object mediaProperties; + private Object routingProperties; public InteractionChannelParticipantCreator( final String pathInteractionSid, final String pathChannelSid, final InteractionChannelParticipant.Type type, - final Map mediaProperties + final Object mediaProperties ) { this.pathInteractionSid = pathInteractionSid; this.pathChannelSid = pathChannelSid; @@ -58,14 +56,14 @@ public InteractionChannelParticipantCreator setType( } public InteractionChannelParticipantCreator setMediaProperties( - final Map mediaProperties + final Object mediaProperties ) { this.mediaProperties = mediaProperties; return this; } public InteractionChannelParticipantCreator setRoutingProperties( - final Map routingProperties + final Object routingProperties ) { this.routingProperties = routingProperties; return this; @@ -132,13 +130,13 @@ private void addPostParams(final Request request) { if (mediaProperties != null) { request.addPostParam( "MediaProperties", - Converter.mapToJson(mediaProperties) + Converter.objectToJson(mediaProperties) ); } if (routingProperties != null) { request.addPostParam( "RoutingProperties", - Converter.mapToJson(routingProperties) + Converter.objectToJson(routingProperties) ); } } diff --git a/src/main/java/com/twilio/rest/flexapi/v1/interaction/interactionchannel/InteractionTransfer.java b/src/main/java/com/twilio/rest/flexapi/v1/interaction/interactionchannel/InteractionTransfer.java index 40779ee7de..7541c81831 100644 --- a/src/main/java/com/twilio/rest/flexapi/v1/interaction/interactionchannel/InteractionTransfer.java +++ b/src/main/java/com/twilio/rest/flexapi/v1/interaction/interactionchannel/InteractionTransfer.java @@ -135,8 +135,8 @@ public static String toJson(Object object, ObjectMapper mapper) { private final String interactionSid; private final String channelSid; private final String executionSid; - private final InteractionTransfer.TransferType type; - private final InteractionTransfer.TransferStatus status; + private final TransferType type; + private final TransferStatus status; private final String from; private final String to; private final String noteSid; @@ -153,8 +153,8 @@ private InteractionTransfer( @JsonProperty("interaction_sid") final String interactionSid, @JsonProperty("channel_sid") final String channelSid, @JsonProperty("execution_sid") final String executionSid, - @JsonProperty("type") final InteractionTransfer.TransferType type, - @JsonProperty("status") final InteractionTransfer.TransferStatus status, + @JsonProperty("type") final TransferType type, + @JsonProperty("status") final TransferStatus status, @JsonProperty("from") final String from, @JsonProperty("to") final String to, @JsonProperty("note_sid") final String noteSid, @@ -204,11 +204,11 @@ public final String getExecutionSid() { return this.executionSid; } - public final InteractionTransfer.TransferType getType() { + public final TransferType getType() { return this.type; } - public final InteractionTransfer.TransferStatus getStatus() { + public final TransferStatus getStatus() { return this.status; } diff --git a/src/main/java/com/twilio/rest/frontlineapi/v1/User.java b/src/main/java/com/twilio/rest/frontlineapi/v1/User.java index 3534892247..6bc81d1212 100644 --- a/src/main/java/com/twilio/rest/frontlineapi/v1/User.java +++ b/src/main/java/com/twilio/rest/frontlineapi/v1/User.java @@ -92,7 +92,7 @@ public static User fromJson( private final String identity; private final String friendlyName; private final String avatar; - private final User.StateType state; + private final StateType state; private final Boolean isAvailable; private final URI url; @@ -102,7 +102,7 @@ private User( @JsonProperty("identity") final String identity, @JsonProperty("friendly_name") final String friendlyName, @JsonProperty("avatar") final String avatar, - @JsonProperty("state") final User.StateType state, + @JsonProperty("state") final StateType state, @JsonProperty("is_available") final Boolean isAvailable, @JsonProperty("url") final URI url ) { @@ -131,7 +131,7 @@ public final String getAvatar() { return this.avatar; } - public final User.StateType getState() { + public final StateType getState() { return this.state; } diff --git a/src/main/java/com/twilio/rest/insights/v1/CallSummaries.java b/src/main/java/com/twilio/rest/insights/v1/CallSummaries.java index 9741233555..2c9a77afed 100644 --- a/src/main/java/com/twilio/rest/insights/v1/CallSummaries.java +++ b/src/main/java/com/twilio/rest/insights/v1/CallSummaries.java @@ -91,10 +91,10 @@ public static CallSummaries fromJson( private final String accountSid; private final String callSid; - private final CallSummaries.AnsweredBy answeredBy; - private final CallSummaries.CallType callType; - private final CallSummaries.CallState callState; - private final CallSummaries.ProcessingState processingState; + private final AnsweredBy answeredBy; + private final CallType callType; + private final CallState callState; + private final ProcessingState processingState; private final ZonedDateTime createdTime; private final ZonedDateTime startTime; private final ZonedDateTime endTime; @@ -117,12 +117,10 @@ public static CallSummaries fromJson( private CallSummaries( @JsonProperty("account_sid") final String accountSid, @JsonProperty("call_sid") final String callSid, - @JsonProperty("answered_by") final CallSummaries.AnsweredBy answeredBy, - @JsonProperty("call_type") final CallSummaries.CallType callType, - @JsonProperty("call_state") final CallSummaries.CallState callState, - @JsonProperty( - "processing_state" - ) final CallSummaries.ProcessingState processingState, + @JsonProperty("answered_by") final AnsweredBy answeredBy, + @JsonProperty("call_type") final CallType callType, + @JsonProperty("call_state") final CallState callState, + @JsonProperty("processing_state") final ProcessingState processingState, @JsonProperty("created_time") final String createdTime, @JsonProperty("start_time") final String startTime, @JsonProperty("end_time") final String endTime, @@ -174,19 +172,19 @@ public final String getCallSid() { return this.callSid; } - public final CallSummaries.AnsweredBy getAnsweredBy() { + public final AnsweredBy getAnsweredBy() { return this.answeredBy; } - public final CallSummaries.CallType getCallType() { + public final CallType getCallType() { return this.callType; } - public final CallSummaries.CallState getCallState() { + public final CallState getCallState() { return this.callState; } - public final CallSummaries.ProcessingState getProcessingState() { + public final ProcessingState getProcessingState() { return this.processingState; } diff --git a/src/main/java/com/twilio/rest/insights/v1/Conference.java b/src/main/java/com/twilio/rest/insights/v1/Conference.java index c6a41efe28..7a3e57b142 100644 --- a/src/main/java/com/twilio/rest/insights/v1/Conference.java +++ b/src/main/java/com/twilio/rest/insights/v1/Conference.java @@ -101,19 +101,19 @@ public static Conference fromJson( private final ZonedDateTime endTime; private final Integer durationSeconds; private final Integer connectDurationSeconds; - private final Conference.ConferenceStatus status; + private final ConferenceStatus status; private final Integer maxParticipants; private final Integer maxConcurrentParticipants; private final Integer uniqueParticipants; - private final Conference.ConferenceEndReason endReason; + private final ConferenceEndReason endReason; private final String endedBy; - private final Conference.Region mixerRegion; - private final Conference.Region mixerRegionRequested; + private final Region mixerRegion; + private final Region mixerRegionRequested; private final Boolean recordingEnabled; private final Map detectedIssues; - private final List tags; + private final List tags; private final Map tagInfo; - private final Conference.ProcessingState processingState; + private final ProcessingState processingState; private final URI url; private final Map links; @@ -129,30 +129,26 @@ private Conference( @JsonProperty( "connect_duration_seconds" ) final Integer connectDurationSeconds, - @JsonProperty("status") final Conference.ConferenceStatus status, + @JsonProperty("status") final ConferenceStatus status, @JsonProperty("max_participants") final Integer maxParticipants, @JsonProperty( "max_concurrent_participants" ) final Integer maxConcurrentParticipants, @JsonProperty("unique_participants") final Integer uniqueParticipants, - @JsonProperty( - "end_reason" - ) final Conference.ConferenceEndReason endReason, + @JsonProperty("end_reason") final ConferenceEndReason endReason, @JsonProperty("ended_by") final String endedBy, - @JsonProperty("mixer_region") final Conference.Region mixerRegion, + @JsonProperty("mixer_region") final Region mixerRegion, @JsonProperty( "mixer_region_requested" - ) final Conference.Region mixerRegionRequested, + ) final Region mixerRegionRequested, @JsonProperty("recording_enabled") final Boolean recordingEnabled, @JsonProperty("detected_issues") final Map< String, Object > detectedIssues, - @JsonProperty("tags") final List tags, + @JsonProperty("tags") final List tags, @JsonProperty("tag_info") final Map tagInfo, - @JsonProperty( - "processing_state" - ) final Conference.ProcessingState processingState, + @JsonProperty("processing_state") final ProcessingState processingState, @JsonProperty("url") final URI url, @JsonProperty("links") final Map links ) { @@ -213,7 +209,7 @@ public final Integer getConnectDurationSeconds() { return this.connectDurationSeconds; } - public final Conference.ConferenceStatus getStatus() { + public final ConferenceStatus getStatus() { return this.status; } @@ -229,7 +225,7 @@ public final Integer getUniqueParticipants() { return this.uniqueParticipants; } - public final Conference.ConferenceEndReason getEndReason() { + public final ConferenceEndReason getEndReason() { return this.endReason; } @@ -237,11 +233,11 @@ public final String getEndedBy() { return this.endedBy; } - public final Conference.Region getMixerRegion() { + public final Region getMixerRegion() { return this.mixerRegion; } - public final Conference.Region getMixerRegionRequested() { + public final Region getMixerRegionRequested() { return this.mixerRegionRequested; } @@ -253,7 +249,7 @@ public final Map getDetectedIssues() { return this.detectedIssues; } - public final List getTags() { + public final List getTags() { return this.tags; } @@ -261,7 +257,7 @@ public final Map getTagInfo() { return this.tagInfo; } - public final Conference.ProcessingState getProcessingState() { + public final ProcessingState getProcessingState() { return this.processingState; } diff --git a/src/main/java/com/twilio/rest/insights/v1/Room.java b/src/main/java/com/twilio/rest/insights/v1/Room.java index 32a1fb2ece..e3ad533bec 100644 --- a/src/main/java/com/twilio/rest/insights/v1/Room.java +++ b/src/main/java/com/twilio/rest/insights/v1/Room.java @@ -99,25 +99,25 @@ public static Room fromJson( private final String roomName; private final ZonedDateTime createTime; private final ZonedDateTime endTime; - private final Room.RoomType roomType; - private final Room.RoomStatus roomStatus; + private final RoomType roomType; + private final RoomStatus roomStatus; private final URI statusCallback; private final HttpMethod statusCallbackMethod; - private final Room.CreatedMethod createdMethod; - private final Room.EndReason endReason; + private final CreatedMethod createdMethod; + private final EndReason endReason; private final Integer maxParticipants; private final Integer uniqueParticipants; private final Integer uniqueParticipantIdentities; private final Integer concurrentParticipants; private final Integer maxConcurrentParticipants; - private final List codecs; - private final Room.TwilioRealm mediaRegion; + private final List codecs; + private final TwilioRealm mediaRegion; private final Long durationSec; private final Long totalParticipantDurationSec; private final Long totalRecordingDurationSec; - private final Room.ProcessingState processingState; + private final ProcessingState processingState; private final Boolean recordingEnabled; - private final Room.EdgeLocation edgeLocation; + private final EdgeLocation edgeLocation; private final URI url; private final Map links; @@ -128,14 +128,14 @@ private Room( @JsonProperty("room_name") final String roomName, @JsonProperty("create_time") final String createTime, @JsonProperty("end_time") final String endTime, - @JsonProperty("room_type") final Room.RoomType roomType, - @JsonProperty("room_status") final Room.RoomStatus roomStatus, + @JsonProperty("room_type") final RoomType roomType, + @JsonProperty("room_status") final RoomStatus roomStatus, @JsonProperty("status_callback") final URI statusCallback, @JsonProperty( "status_callback_method" ) final HttpMethod statusCallbackMethod, - @JsonProperty("created_method") final Room.CreatedMethod createdMethod, - @JsonProperty("end_reason") final Room.EndReason endReason, + @JsonProperty("created_method") final CreatedMethod createdMethod, + @JsonProperty("end_reason") final EndReason endReason, @JsonProperty("max_participants") final Integer maxParticipants, @JsonProperty("unique_participants") final Integer uniqueParticipants, @JsonProperty( @@ -147,8 +147,8 @@ private Room( @JsonProperty( "max_concurrent_participants" ) final Integer maxConcurrentParticipants, - @JsonProperty("codecs") final List codecs, - @JsonProperty("media_region") final Room.TwilioRealm mediaRegion, + @JsonProperty("codecs") final List codecs, + @JsonProperty("media_region") final TwilioRealm mediaRegion, @JsonProperty("duration_sec") final Long durationSec, @JsonProperty( "total_participant_duration_sec" @@ -156,11 +156,9 @@ private Room( @JsonProperty( "total_recording_duration_sec" ) final Long totalRecordingDurationSec, - @JsonProperty( - "processing_state" - ) final Room.ProcessingState processingState, + @JsonProperty("processing_state") final ProcessingState processingState, @JsonProperty("recording_enabled") final Boolean recordingEnabled, - @JsonProperty("edge_location") final Room.EdgeLocation edgeLocation, + @JsonProperty("edge_location") final EdgeLocation edgeLocation, @JsonProperty("url") final URI url, @JsonProperty("links") final Map links ) { @@ -212,11 +210,11 @@ public final ZonedDateTime getEndTime() { return this.endTime; } - public final Room.RoomType getRoomType() { + public final RoomType getRoomType() { return this.roomType; } - public final Room.RoomStatus getRoomStatus() { + public final RoomStatus getRoomStatus() { return this.roomStatus; } @@ -228,11 +226,11 @@ public final HttpMethod getStatusCallbackMethod() { return this.statusCallbackMethod; } - public final Room.CreatedMethod getCreatedMethod() { + public final CreatedMethod getCreatedMethod() { return this.createdMethod; } - public final Room.EndReason getEndReason() { + public final EndReason getEndReason() { return this.endReason; } @@ -256,11 +254,11 @@ public final Integer getMaxConcurrentParticipants() { return this.maxConcurrentParticipants; } - public final List getCodecs() { + public final List getCodecs() { return this.codecs; } - public final Room.TwilioRealm getMediaRegion() { + public final TwilioRealm getMediaRegion() { return this.mediaRegion; } @@ -276,7 +274,7 @@ public final Long getTotalRecordingDurationSec() { return this.totalRecordingDurationSec; } - public final Room.ProcessingState getProcessingState() { + public final ProcessingState getProcessingState() { return this.processingState; } @@ -284,7 +282,7 @@ public final Boolean getRecordingEnabled() { return this.recordingEnabled; } - public final Room.EdgeLocation getEdgeLocation() { + public final EdgeLocation getEdgeLocation() { return this.edgeLocation; } diff --git a/src/main/java/com/twilio/rest/insights/v1/call/Annotation.java b/src/main/java/com/twilio/rest/insights/v1/call/Annotation.java index 0821e30210..0bb36cd0a0 100644 --- a/src/main/java/com/twilio/rest/insights/v1/call/Annotation.java +++ b/src/main/java/com/twilio/rest/insights/v1/call/Annotation.java @@ -91,8 +91,8 @@ public static Annotation fromJson( private final String callSid; private final String accountSid; - private final Annotation.AnsweredBy answeredBy; - private final Annotation.ConnectivityIssue connectivityIssue; + private final AnsweredBy answeredBy; + private final ConnectivityIssue connectivityIssue; private final List qualityIssues; private final Boolean spam; private final Integer callScore; @@ -104,10 +104,10 @@ public static Annotation fromJson( private Annotation( @JsonProperty("call_sid") final String callSid, @JsonProperty("account_sid") final String accountSid, - @JsonProperty("answered_by") final Annotation.AnsweredBy answeredBy, + @JsonProperty("answered_by") final AnsweredBy answeredBy, @JsonProperty( "connectivity_issue" - ) final Annotation.ConnectivityIssue connectivityIssue, + ) final ConnectivityIssue connectivityIssue, @JsonProperty("quality_issues") final List qualityIssues, @JsonProperty("spam") final Boolean spam, @JsonProperty("call_score") final Integer callScore, @@ -135,11 +135,11 @@ public final String getAccountSid() { return this.accountSid; } - public final Annotation.AnsweredBy getAnsweredBy() { + public final AnsweredBy getAnsweredBy() { return this.answeredBy; } - public final Annotation.ConnectivityIssue getConnectivityIssue() { + public final ConnectivityIssue getConnectivityIssue() { return this.connectivityIssue; } diff --git a/src/main/java/com/twilio/rest/insights/v1/call/CallSummary.java b/src/main/java/com/twilio/rest/insights/v1/call/CallSummary.java index ae8c1be46a..68ec399227 100644 --- a/src/main/java/com/twilio/rest/insights/v1/call/CallSummary.java +++ b/src/main/java/com/twilio/rest/insights/v1/call/CallSummary.java @@ -91,10 +91,10 @@ public static CallSummary fromJson( private final String accountSid; private final String callSid; - private final CallSummary.CallType callType; - private final CallSummary.CallState callState; - private final CallSummary.AnsweredBy answeredBy; - private final CallSummary.ProcessingState processingState; + private final CallType callType; + private final CallState callState; + private final AnsweredBy answeredBy; + private final ProcessingState processingState; private final ZonedDateTime createdTime; private final ZonedDateTime startTime; private final ZonedDateTime endTime; @@ -117,12 +117,10 @@ public static CallSummary fromJson( private CallSummary( @JsonProperty("account_sid") final String accountSid, @JsonProperty("call_sid") final String callSid, - @JsonProperty("call_type") final CallSummary.CallType callType, - @JsonProperty("call_state") final CallSummary.CallState callState, - @JsonProperty("answered_by") final CallSummary.AnsweredBy answeredBy, - @JsonProperty( - "processing_state" - ) final CallSummary.ProcessingState processingState, + @JsonProperty("call_type") final CallType callType, + @JsonProperty("call_state") final CallState callState, + @JsonProperty("answered_by") final AnsweredBy answeredBy, + @JsonProperty("processing_state") final ProcessingState processingState, @JsonProperty("created_time") final String createdTime, @JsonProperty("start_time") final String startTime, @JsonProperty("end_time") final String endTime, @@ -174,19 +172,19 @@ public final String getCallSid() { return this.callSid; } - public final CallSummary.CallType getCallType() { + public final CallType getCallType() { return this.callType; } - public final CallSummary.CallState getCallState() { + public final CallState getCallState() { return this.callState; } - public final CallSummary.AnsweredBy getAnsweredBy() { + public final AnsweredBy getAnsweredBy() { return this.answeredBy; } - public final CallSummary.ProcessingState getProcessingState() { + public final ProcessingState getProcessingState() { return this.processingState; } diff --git a/src/main/java/com/twilio/rest/insights/v1/call/Event.java b/src/main/java/com/twilio/rest/insights/v1/call/Event.java index 3d5803e58c..72db3a8646 100644 --- a/src/main/java/com/twilio/rest/insights/v1/call/Event.java +++ b/src/main/java/com/twilio/rest/insights/v1/call/Event.java @@ -88,9 +88,9 @@ public static Event fromJson( private final String timestamp; private final String callSid; private final String accountSid; - private final Event.TwilioEdge edge; + private final TwilioEdge edge; private final String group; - private final Event.Level level; + private final Level level; private final String name; private final Map carrierEdge; private final Map sipEdge; @@ -102,9 +102,9 @@ private Event( @JsonProperty("timestamp") final String timestamp, @JsonProperty("call_sid") final String callSid, @JsonProperty("account_sid") final String accountSid, - @JsonProperty("edge") final Event.TwilioEdge edge, + @JsonProperty("edge") final TwilioEdge edge, @JsonProperty("group") final String group, - @JsonProperty("level") final Event.Level level, + @JsonProperty("level") final Level level, @JsonProperty("name") final String name, @JsonProperty("carrier_edge") final Map carrierEdge, @JsonProperty("sip_edge") final Map sipEdge, @@ -136,7 +136,7 @@ public final String getAccountSid() { return this.accountSid; } - public final Event.TwilioEdge getEdge() { + public final TwilioEdge getEdge() { return this.edge; } @@ -144,7 +144,7 @@ public final String getGroup() { return this.group; } - public final Event.Level getLevel() { + public final Level getLevel() { return this.level; } diff --git a/src/main/java/com/twilio/rest/insights/v1/call/Metric.java b/src/main/java/com/twilio/rest/insights/v1/call/Metric.java index c5bc8315e8..e09bf425a6 100644 --- a/src/main/java/com/twilio/rest/insights/v1/call/Metric.java +++ b/src/main/java/com/twilio/rest/insights/v1/call/Metric.java @@ -88,8 +88,8 @@ public static Metric fromJson( private final String timestamp; private final String callSid; private final String accountSid; - private final Metric.TwilioEdge edge; - private final Metric.StreamDirection direction; + private final TwilioEdge edge; + private final StreamDirection direction; private final Map carrierEdge; private final Map sipEdge; private final Map sdkEdge; @@ -100,8 +100,8 @@ private Metric( @JsonProperty("timestamp") final String timestamp, @JsonProperty("call_sid") final String callSid, @JsonProperty("account_sid") final String accountSid, - @JsonProperty("edge") final Metric.TwilioEdge edge, - @JsonProperty("direction") final Metric.StreamDirection direction, + @JsonProperty("edge") final TwilioEdge edge, + @JsonProperty("direction") final StreamDirection direction, @JsonProperty("carrier_edge") final Map carrierEdge, @JsonProperty("sip_edge") final Map sipEdge, @JsonProperty("sdk_edge") final Map sdkEdge, @@ -130,11 +130,11 @@ public final String getAccountSid() { return this.accountSid; } - public final Metric.TwilioEdge getEdge() { + public final TwilioEdge getEdge() { return this.edge; } - public final Metric.StreamDirection getDirection() { + public final StreamDirection getDirection() { return this.direction; } diff --git a/src/main/java/com/twilio/rest/insights/v1/conference/ConferenceParticipant.java b/src/main/java/com/twilio/rest/insights/v1/conference/ConferenceParticipant.java index d62a3c56fd..b5996e37a3 100644 --- a/src/main/java/com/twilio/rest/insights/v1/conference/ConferenceParticipant.java +++ b/src/main/java/com/twilio/rest/insights/v1/conference/ConferenceParticipant.java @@ -106,10 +106,10 @@ public static ConferenceParticipant fromJson( private final String conferenceSid; private final String callSid; private final String accountSid; - private final ConferenceParticipant.CallDirection callDirection; + private final CallDirection callDirection; private final String from; private final String to; - private final ConferenceParticipant.CallStatus callStatus; + private final CallStatus callStatus; private final String countryCode; private final Boolean isModerator; private final ZonedDateTime joinTime; @@ -117,13 +117,13 @@ public static ConferenceParticipant fromJson( private final Integer durationSeconds; private final Integer outboundQueueLength; private final Integer outboundTimeInQueue; - private final ConferenceParticipant.JitterBufferSize jitterBufferSize; + private final JitterBufferSize jitterBufferSize; private final Boolean isCoach; private final List coachedParticipants; - private final ConferenceParticipant.Region participantRegion; - private final ConferenceParticipant.Region conferenceRegion; - private final ConferenceParticipant.CallType callType; - private final ConferenceParticipant.ProcessingState processingState; + private final Region participantRegion; + private final Region conferenceRegion; + private final CallType callType; + private final ProcessingState processingState; private final Map properties; private final Map events; private final Map metrics; @@ -136,14 +136,10 @@ private ConferenceParticipant( @JsonProperty("conference_sid") final String conferenceSid, @JsonProperty("call_sid") final String callSid, @JsonProperty("account_sid") final String accountSid, - @JsonProperty( - "call_direction" - ) final ConferenceParticipant.CallDirection callDirection, + @JsonProperty("call_direction") final CallDirection callDirection, @JsonProperty("from") final String from, @JsonProperty("to") final String to, - @JsonProperty( - "call_status" - ) final ConferenceParticipant.CallStatus callStatus, + @JsonProperty("call_status") final CallStatus callStatus, @JsonProperty("country_code") final String countryCode, @JsonProperty("is_moderator") final Boolean isModerator, @JsonProperty("join_time") final String joinTime, @@ -157,23 +153,15 @@ private ConferenceParticipant( ) final Integer outboundTimeInQueue, @JsonProperty( "jitter_buffer_size" - ) final ConferenceParticipant.JitterBufferSize jitterBufferSize, + ) final JitterBufferSize jitterBufferSize, @JsonProperty("is_coach") final Boolean isCoach, @JsonProperty("coached_participants") final List< String > coachedParticipants, - @JsonProperty( - "participant_region" - ) final ConferenceParticipant.Region participantRegion, - @JsonProperty( - "conference_region" - ) final ConferenceParticipant.Region conferenceRegion, - @JsonProperty( - "call_type" - ) final ConferenceParticipant.CallType callType, - @JsonProperty( - "processing_state" - ) final ConferenceParticipant.ProcessingState processingState, + @JsonProperty("participant_region") final Region participantRegion, + @JsonProperty("conference_region") final Region conferenceRegion, + @JsonProperty("call_type") final CallType callType, + @JsonProperty("processing_state") final ProcessingState processingState, @JsonProperty("properties") final Map properties, @JsonProperty("events") final Map events, @JsonProperty("metrics") final Map metrics, @@ -228,7 +216,7 @@ public final String getAccountSid() { return this.accountSid; } - public final ConferenceParticipant.CallDirection getCallDirection() { + public final CallDirection getCallDirection() { return this.callDirection; } @@ -240,7 +228,7 @@ public final String getTo() { return this.to; } - public final ConferenceParticipant.CallStatus getCallStatus() { + public final CallStatus getCallStatus() { return this.callStatus; } @@ -272,7 +260,7 @@ public final Integer getOutboundTimeInQueue() { return this.outboundTimeInQueue; } - public final ConferenceParticipant.JitterBufferSize getJitterBufferSize() { + public final JitterBufferSize getJitterBufferSize() { return this.jitterBufferSize; } @@ -284,19 +272,19 @@ public final List getCoachedParticipants() { return this.coachedParticipants; } - public final ConferenceParticipant.Region getParticipantRegion() { + public final Region getParticipantRegion() { return this.participantRegion; } - public final ConferenceParticipant.Region getConferenceRegion() { + public final Region getConferenceRegion() { return this.conferenceRegion; } - public final ConferenceParticipant.CallType getCallType() { + public final CallType getCallType() { return this.callType; } - public final ConferenceParticipant.ProcessingState getProcessingState() { + public final ProcessingState getProcessingState() { return this.processingState; } diff --git a/src/main/java/com/twilio/rest/insights/v1/room/Participant.java b/src/main/java/com/twilio/rest/insights/v1/room/Participant.java index db0b8b2325..bef00bd135 100644 --- a/src/main/java/com/twilio/rest/insights/v1/room/Participant.java +++ b/src/main/java/com/twilio/rest/insights/v1/room/Participant.java @@ -103,14 +103,14 @@ public static Participant fromJson( private final Long durationSec; private final String accountSid; private final String roomSid; - private final Participant.RoomStatus status; - private final List codecs; + private final RoomStatus status; + private final List codecs; private final String endReason; private final Integer errorCode; private final String errorCodeUrl; - private final Participant.TwilioRealm mediaRegion; + private final TwilioRealm mediaRegion; private final Map properties; - private final Participant.EdgeLocation edgeLocation; + private final EdgeLocation edgeLocation; private final Map publisherInfo; private final URI url; @@ -123,16 +123,14 @@ private Participant( @JsonProperty("duration_sec") final Long durationSec, @JsonProperty("account_sid") final String accountSid, @JsonProperty("room_sid") final String roomSid, - @JsonProperty("status") final Participant.RoomStatus status, - @JsonProperty("codecs") final List codecs, + @JsonProperty("status") final RoomStatus status, + @JsonProperty("codecs") final List codecs, @JsonProperty("end_reason") final String endReason, @JsonProperty("error_code") final Integer errorCode, @JsonProperty("error_code_url") final String errorCodeUrl, - @JsonProperty("media_region") final Participant.TwilioRealm mediaRegion, + @JsonProperty("media_region") final TwilioRealm mediaRegion, @JsonProperty("properties") final Map properties, - @JsonProperty( - "edge_location" - ) final Participant.EdgeLocation edgeLocation, + @JsonProperty("edge_location") final EdgeLocation edgeLocation, @JsonProperty("publisher_info") final Map publisherInfo, @JsonProperty("url") final URI url ) { @@ -183,11 +181,11 @@ public final String getRoomSid() { return this.roomSid; } - public final Participant.RoomStatus getStatus() { + public final RoomStatus getStatus() { return this.status; } - public final List getCodecs() { + public final List getCodecs() { return this.codecs; } @@ -203,7 +201,7 @@ public final String getErrorCodeUrl() { return this.errorCodeUrl; } - public final Participant.TwilioRealm getMediaRegion() { + public final TwilioRealm getMediaRegion() { return this.mediaRegion; } @@ -211,7 +209,7 @@ public final Map getProperties() { return this.properties; } - public final Participant.EdgeLocation getEdgeLocation() { + public final EdgeLocation getEdgeLocation() { return this.edgeLocation; } diff --git a/src/main/java/com/twilio/rest/intelligence/v2/CustomOperator.java b/src/main/java/com/twilio/rest/intelligence/v2/CustomOperator.java index fa1df6c2b0..ca2d94f285 100644 --- a/src/main/java/com/twilio/rest/intelligence/v2/CustomOperator.java +++ b/src/main/java/com/twilio/rest/intelligence/v2/CustomOperator.java @@ -44,7 +44,7 @@ public class CustomOperator extends Resource { public static CustomOperatorCreator creator( final String friendlyName, final String operatorType, - final Map config + final Object config ) { return new CustomOperatorCreator(friendlyName, operatorType, config); } @@ -64,7 +64,7 @@ public static CustomOperatorReader reader() { public static CustomOperatorUpdater updater( final String pathSid, final String friendlyName, - final Map config + final Object config ) { return new CustomOperatorUpdater(pathSid, friendlyName, config); } @@ -119,7 +119,7 @@ public static CustomOperator fromJson( private final String author; private final String operatorType; private final Integer version; - private final CustomOperator.Availability availability; + private final Availability availability; private final Map config; private final ZonedDateTime dateCreated; private final ZonedDateTime dateUpdated; @@ -134,9 +134,7 @@ private CustomOperator( @JsonProperty("author") final String author, @JsonProperty("operator_type") final String operatorType, @JsonProperty("version") final Integer version, - @JsonProperty( - "availability" - ) final CustomOperator.Availability availability, + @JsonProperty("availability") final Availability availability, @JsonProperty("config") final Map config, @JsonProperty("date_created") final String dateCreated, @JsonProperty("date_updated") final String dateUpdated, @@ -184,7 +182,7 @@ public final Integer getVersion() { return this.version; } - public final CustomOperator.Availability getAvailability() { + public final Availability getAvailability() { return this.availability; } diff --git a/src/main/java/com/twilio/rest/intelligence/v2/CustomOperatorCreator.java b/src/main/java/com/twilio/rest/intelligence/v2/CustomOperatorCreator.java index 1f8707d982..85535d3191 100644 --- a/src/main/java/com/twilio/rest/intelligence/v2/CustomOperatorCreator.java +++ b/src/main/java/com/twilio/rest/intelligence/v2/CustomOperatorCreator.java @@ -26,19 +26,17 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -import java.util.Map; -import java.util.Map; public class CustomOperatorCreator extends Creator { private String friendlyName; private String operatorType; - private Map config; + private Object config; public CustomOperatorCreator( final String friendlyName, final String operatorType, - final Map config + final Object config ) { this.friendlyName = friendlyName; this.operatorType = operatorType; @@ -55,7 +53,7 @@ public CustomOperatorCreator setOperatorType(final String operatorType) { return this; } - public CustomOperatorCreator setConfig(final Map config) { + public CustomOperatorCreator setConfig(final Object config) { this.config = config; return this; } @@ -116,7 +114,7 @@ private void addPostParams(final Request request) { request.addPostParam("OperatorType", operatorType); } if (config != null) { - request.addPostParam("Config", Converter.mapToJson(config)); + request.addPostParam("Config", Converter.objectToJson(config)); } } } diff --git a/src/main/java/com/twilio/rest/intelligence/v2/CustomOperatorUpdater.java b/src/main/java/com/twilio/rest/intelligence/v2/CustomOperatorUpdater.java index 45dbf98813..73c396b60d 100644 --- a/src/main/java/com/twilio/rest/intelligence/v2/CustomOperatorUpdater.java +++ b/src/main/java/com/twilio/rest/intelligence/v2/CustomOperatorUpdater.java @@ -25,19 +25,18 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -import java.util.Map; public class CustomOperatorUpdater extends Updater { private String pathSid; private String friendlyName; - private Map config; + private Object config; private String ifMatch; public CustomOperatorUpdater( final String pathSid, final String friendlyName, - final Map config + final Object config ) { this.pathSid = pathSid; this.friendlyName = friendlyName; @@ -49,7 +48,7 @@ public CustomOperatorUpdater setFriendlyName(final String friendlyName) { return this; } - public CustomOperatorUpdater setConfig(final Map config) { + public CustomOperatorUpdater setConfig(final Object config) { this.config = config; return this; } @@ -109,7 +108,7 @@ private void addPostParams(final Request request) { request.addPostParam("FriendlyName", friendlyName); } if (config != null) { - request.addPostParam("Config", Converter.mapToJson(config)); + request.addPostParam("Config", Converter.objectToJson(config)); } } diff --git a/src/main/java/com/twilio/rest/intelligence/v2/Operator.java b/src/main/java/com/twilio/rest/intelligence/v2/Operator.java index a9c425c153..d5d656a4ed 100644 --- a/src/main/java/com/twilio/rest/intelligence/v2/Operator.java +++ b/src/main/java/com/twilio/rest/intelligence/v2/Operator.java @@ -99,7 +99,7 @@ public static Operator fromJson( private final String author; private final String operatorType; private final Integer version; - private final Operator.Availability availability; + private final Availability availability; private final Map config; private final ZonedDateTime dateCreated; private final ZonedDateTime dateUpdated; @@ -114,7 +114,7 @@ private Operator( @JsonProperty("author") final String author, @JsonProperty("operator_type") final String operatorType, @JsonProperty("version") final Integer version, - @JsonProperty("availability") final Operator.Availability availability, + @JsonProperty("availability") final Availability availability, @JsonProperty("config") final Map config, @JsonProperty("date_created") final String dateCreated, @JsonProperty("date_updated") final String dateUpdated, @@ -162,7 +162,7 @@ public final Integer getVersion() { return this.version; } - public final Operator.Availability getAvailability() { + public final Availability getAvailability() { return this.availability; } diff --git a/src/main/java/com/twilio/rest/intelligence/v2/OperatorType.java b/src/main/java/com/twilio/rest/intelligence/v2/OperatorType.java index 566ab5cb66..03d6717137 100644 --- a/src/main/java/com/twilio/rest/intelligence/v2/OperatorType.java +++ b/src/main/java/com/twilio/rest/intelligence/v2/OperatorType.java @@ -98,10 +98,10 @@ public static OperatorType fromJson( private final String friendlyName; private final String description; private final URI docsLink; - private final OperatorType.OutputType outputType; + private final OutputType outputType; private final List supportedLanguages; - private final OperatorType.Provider provider; - private final OperatorType.Availability availability; + private final Provider provider; + private final Availability availability; private final Boolean configurable; private final Map configSchema; private final ZonedDateTime dateCreated; @@ -115,14 +115,12 @@ private OperatorType( @JsonProperty("friendly_name") final String friendlyName, @JsonProperty("description") final String description, @JsonProperty("docs_link") final URI docsLink, - @JsonProperty("output_type") final OperatorType.OutputType outputType, + @JsonProperty("output_type") final OutputType outputType, @JsonProperty("supported_languages") final List< String > supportedLanguages, - @JsonProperty("provider") final OperatorType.Provider provider, - @JsonProperty( - "availability" - ) final OperatorType.Availability availability, + @JsonProperty("provider") final Provider provider, + @JsonProperty("availability") final Availability availability, @JsonProperty("configurable") final Boolean configurable, @JsonProperty("config_schema") final Map configSchema, @JsonProperty("date_created") final String dateCreated, @@ -165,7 +163,7 @@ public final URI getDocsLink() { return this.docsLink; } - public final OperatorType.OutputType getOutputType() { + public final OutputType getOutputType() { return this.outputType; } @@ -173,11 +171,11 @@ public final List getSupportedLanguages() { return this.supportedLanguages; } - public final OperatorType.Provider getProvider() { + public final Provider getProvider() { return this.provider; } - public final OperatorType.Availability getAvailability() { + public final Availability getAvailability() { return this.availability; } diff --git a/src/main/java/com/twilio/rest/intelligence/v2/PrebuiltOperator.java b/src/main/java/com/twilio/rest/intelligence/v2/PrebuiltOperator.java index c9b414a546..9d2fc4e69c 100644 --- a/src/main/java/com/twilio/rest/intelligence/v2/PrebuiltOperator.java +++ b/src/main/java/com/twilio/rest/intelligence/v2/PrebuiltOperator.java @@ -99,7 +99,7 @@ public static PrebuiltOperator fromJson( private final String author; private final String operatorType; private final Integer version; - private final PrebuiltOperator.Availability availability; + private final Availability availability; private final Map config; private final ZonedDateTime dateCreated; private final ZonedDateTime dateUpdated; @@ -114,9 +114,7 @@ private PrebuiltOperator( @JsonProperty("author") final String author, @JsonProperty("operator_type") final String operatorType, @JsonProperty("version") final Integer version, - @JsonProperty( - "availability" - ) final PrebuiltOperator.Availability availability, + @JsonProperty("availability") final Availability availability, @JsonProperty("config") final Map config, @JsonProperty("date_created") final String dateCreated, @JsonProperty("date_updated") final String dateUpdated, @@ -164,7 +162,7 @@ public final Integer getVersion() { return this.version; } - public final PrebuiltOperator.Availability getAvailability() { + public final Availability getAvailability() { return this.availability; } diff --git a/src/main/java/com/twilio/rest/intelligence/v2/Service.java b/src/main/java/com/twilio/rest/intelligence/v2/Service.java index 6a14108124..b72a89dcaa 100644 --- a/src/main/java/com/twilio/rest/intelligence/v2/Service.java +++ b/src/main/java/com/twilio/rest/intelligence/v2/Service.java @@ -117,7 +117,7 @@ public static Service fromJson( private final String uniqueName; private final URI url; private final String webhookUrl; - private final Service.HttpMethod webhookHttpMethod; + private final HttpMethod webhookHttpMethod; private final List readOnlyAttachedOperatorSids; private final Integer version; @@ -136,9 +136,7 @@ private Service( @JsonProperty("unique_name") final String uniqueName, @JsonProperty("url") final URI url, @JsonProperty("webhook_url") final String webhookUrl, - @JsonProperty( - "webhook_http_method" - ) final Service.HttpMethod webhookHttpMethod, + @JsonProperty("webhook_http_method") final HttpMethod webhookHttpMethod, @JsonProperty("read_only_attached_operator_sids") final List< String > readOnlyAttachedOperatorSids, @@ -214,7 +212,7 @@ public final String getWebhookUrl() { return this.webhookUrl; } - public final Service.HttpMethod getWebhookHttpMethod() { + public final HttpMethod getWebhookHttpMethod() { return this.webhookHttpMethod; } diff --git a/src/main/java/com/twilio/rest/intelligence/v2/Transcript.java b/src/main/java/com/twilio/rest/intelligence/v2/Transcript.java index fa0fddb1df..5ef033357a 100644 --- a/src/main/java/com/twilio/rest/intelligence/v2/Transcript.java +++ b/src/main/java/com/twilio/rest/intelligence/v2/Transcript.java @@ -43,7 +43,7 @@ public class Transcript extends Resource { public static TranscriptCreator creator( final String serviceSid, - final Map channel + final Object channel ) { return new TranscriptCreator(serviceSid, channel); } @@ -108,7 +108,7 @@ public static Transcript fromJson( private final String sid; private final ZonedDateTime dateCreated; private final ZonedDateTime dateUpdated; - private final Transcript.Status status; + private final Status status; private final Map channel; private final Boolean dataLogging; private final String languageCode; @@ -126,7 +126,7 @@ private Transcript( @JsonProperty("sid") final String sid, @JsonProperty("date_created") final String dateCreated, @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("status") final Transcript.Status status, + @JsonProperty("status") final Status status, @JsonProperty("channel") final Map channel, @JsonProperty("data_logging") final Boolean dataLogging, @JsonProperty("language_code") final String languageCode, @@ -175,7 +175,7 @@ public final ZonedDateTime getDateUpdated() { return this.dateUpdated; } - public final Transcript.Status getStatus() { + public final Status getStatus() { return this.status; } diff --git a/src/main/java/com/twilio/rest/intelligence/v2/TranscriptCreator.java b/src/main/java/com/twilio/rest/intelligence/v2/TranscriptCreator.java index 8ab04ae15c..7a9249f442 100644 --- a/src/main/java/com/twilio/rest/intelligence/v2/TranscriptCreator.java +++ b/src/main/java/com/twilio/rest/intelligence/v2/TranscriptCreator.java @@ -27,20 +27,15 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; import java.time.ZonedDateTime; -import java.util.Map; -import java.util.Map; public class TranscriptCreator extends Creator { private String serviceSid; - private Map channel; + private Object channel; private String customerKey; private ZonedDateTime mediaStartTime; - public TranscriptCreator( - final String serviceSid, - final Map channel - ) { + public TranscriptCreator(final String serviceSid, final Object channel) { this.serviceSid = serviceSid; this.channel = channel; } @@ -50,7 +45,7 @@ public TranscriptCreator setServiceSid(final String serviceSid) { return this; } - public TranscriptCreator setChannel(final Map channel) { + public TranscriptCreator setChannel(final Object channel) { this.channel = channel; return this; } @@ -112,7 +107,7 @@ private void addPostParams(final Request request) { request.addPostParam("ServiceSid", serviceSid); } if (channel != null) { - request.addPostParam("Channel", Converter.mapToJson(channel)); + request.addPostParam("Channel", Converter.objectToJson(channel)); } if (customerKey != null) { request.addPostParam("CustomerKey", customerKey); diff --git a/src/main/java/com/twilio/rest/intelligence/v2/transcript/OperatorResult.java b/src/main/java/com/twilio/rest/intelligence/v2/transcript/OperatorResult.java index 8e734ee75a..6ceb37f984 100644 --- a/src/main/java/com/twilio/rest/intelligence/v2/transcript/OperatorResult.java +++ b/src/main/java/com/twilio/rest/intelligence/v2/transcript/OperatorResult.java @@ -95,7 +95,7 @@ public static OperatorResult fromJson( } } - private final OperatorResult.OperatorType operatorType; + private final OperatorType operatorType; private final String name; private final String operatorSid; private final Boolean extractMatch; @@ -114,9 +114,7 @@ public static OperatorResult fromJson( @JsonCreator private OperatorResult( - @JsonProperty( - "operator_type" - ) final OperatorResult.OperatorType operatorType, + @JsonProperty("operator_type") final OperatorType operatorType, @JsonProperty("name") final String name, @JsonProperty("operator_sid") final String operatorSid, @JsonProperty("extract_match") final Boolean extractMatch, @@ -164,7 +162,7 @@ private OperatorResult( this.url = url; } - public final OperatorResult.OperatorType getOperatorType() { + public final OperatorType getOperatorType() { return this.operatorType; } diff --git a/src/main/java/com/twilio/rest/ipmessaging/v1/Credential.java b/src/main/java/com/twilio/rest/ipmessaging/v1/Credential.java index c18921f709..00a5ede142 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v1/Credential.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v1/Credential.java @@ -39,7 +39,7 @@ public class Credential extends Resource { private static final long serialVersionUID = 161183169234848L; - public static CredentialCreator creator(final Credential.PushService type) { + public static CredentialCreator creator(final PushService type) { return new CredentialCreator(type); } @@ -105,7 +105,7 @@ public static Credential fromJson( private final String sid; private final String accountSid; private final String friendlyName; - private final Credential.PushService type; + private final PushService type; private final String sandbox; private final ZonedDateTime dateCreated; private final ZonedDateTime dateUpdated; @@ -116,7 +116,7 @@ private Credential( @JsonProperty("sid") final String sid, @JsonProperty("account_sid") final String accountSid, @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("type") final Credential.PushService type, + @JsonProperty("type") final PushService type, @JsonProperty("sandbox") final String sandbox, @JsonProperty("date_created") final String dateCreated, @JsonProperty("date_updated") final String dateUpdated, @@ -144,7 +144,7 @@ public final String getFriendlyName() { return this.friendlyName; } - public final Credential.PushService getType() { + public final PushService getType() { return this.type; } diff --git a/src/main/java/com/twilio/rest/ipmessaging/v1/service/Channel.java b/src/main/java/com/twilio/rest/ipmessaging/v1/service/Channel.java index 716231236c..3e872e729e 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v1/service/Channel.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v1/service/Channel.java @@ -119,7 +119,7 @@ public static Channel fromJson( private final String friendlyName; private final String uniqueName; private final String attributes; - private final Channel.ChannelType type; + private final ChannelType type; private final ZonedDateTime dateCreated; private final ZonedDateTime dateUpdated; private final String createdBy; @@ -136,7 +136,7 @@ private Channel( @JsonProperty("friendly_name") final String friendlyName, @JsonProperty("unique_name") final String uniqueName, @JsonProperty("attributes") final String attributes, - @JsonProperty("type") final Channel.ChannelType type, + @JsonProperty("type") final ChannelType type, @JsonProperty("date_created") final String dateCreated, @JsonProperty("date_updated") final String dateUpdated, @JsonProperty("created_by") final String createdBy, @@ -185,7 +185,7 @@ public final String getAttributes() { return this.attributes; } - public final Channel.ChannelType getType() { + public final ChannelType getType() { return this.type; } diff --git a/src/main/java/com/twilio/rest/ipmessaging/v1/service/Role.java b/src/main/java/com/twilio/rest/ipmessaging/v1/service/Role.java index 85ffef93d3..cca17cdc8e 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v1/service/Role.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v1/service/Role.java @@ -43,7 +43,7 @@ public class Role extends Resource { public static RoleCreator creator( final String pathServiceSid, final String friendlyName, - final Role.RoleType type, + final RoleType type, final List permission ) { return new RoleCreator(pathServiceSid, friendlyName, type, permission); @@ -122,7 +122,7 @@ public static Role fromJson( private final String accountSid; private final String serviceSid; private final String friendlyName; - private final Role.RoleType type; + private final RoleType type; private final List permissions; private final ZonedDateTime dateCreated; private final ZonedDateTime dateUpdated; @@ -134,7 +134,7 @@ private Role( @JsonProperty("account_sid") final String accountSid, @JsonProperty("service_sid") final String serviceSid, @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("type") final Role.RoleType type, + @JsonProperty("type") final RoleType type, @JsonProperty("permissions") final List permissions, @JsonProperty("date_created") final String dateCreated, @JsonProperty("date_updated") final String dateUpdated, @@ -167,7 +167,7 @@ public final String getFriendlyName() { return this.friendlyName; } - public final Role.RoleType getType() { + public final RoleType getType() { return this.type; } diff --git a/src/main/java/com/twilio/rest/ipmessaging/v1/service/user/UserChannel.java b/src/main/java/com/twilio/rest/ipmessaging/v1/service/user/UserChannel.java index 05ee6541e0..1aed0d0471 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v1/service/user/UserChannel.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v1/service/user/UserChannel.java @@ -92,7 +92,7 @@ public static UserChannel fromJson( private final String serviceSid; private final String channelSid; private final String memberSid; - private final UserChannel.ChannelStatus status; + private final ChannelStatus status; private final Integer lastConsumedMessageIndex; private final Integer unreadMessagesCount; private final Map links; @@ -103,7 +103,7 @@ private UserChannel( @JsonProperty("service_sid") final String serviceSid, @JsonProperty("channel_sid") final String channelSid, @JsonProperty("member_sid") final String memberSid, - @JsonProperty("status") final UserChannel.ChannelStatus status, + @JsonProperty("status") final ChannelStatus status, @JsonProperty( "last_consumed_message_index" ) final Integer lastConsumedMessageIndex, @@ -138,7 +138,7 @@ public final String getMemberSid() { return this.memberSid; } - public final UserChannel.ChannelStatus getStatus() { + public final ChannelStatus getStatus() { return this.status; } diff --git a/src/main/java/com/twilio/rest/ipmessaging/v2/Credential.java b/src/main/java/com/twilio/rest/ipmessaging/v2/Credential.java index 9f6267c773..f7beefe431 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v2/Credential.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v2/Credential.java @@ -39,7 +39,7 @@ public class Credential extends Resource { private static final long serialVersionUID = 161183169234848L; - public static CredentialCreator creator(final Credential.PushService type) { + public static CredentialCreator creator(final PushService type) { return new CredentialCreator(type); } @@ -105,7 +105,7 @@ public static Credential fromJson( private final String sid; private final String accountSid; private final String friendlyName; - private final Credential.PushService type; + private final PushService type; private final String sandbox; private final ZonedDateTime dateCreated; private final ZonedDateTime dateUpdated; @@ -116,7 +116,7 @@ private Credential( @JsonProperty("sid") final String sid, @JsonProperty("account_sid") final String accountSid, @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("type") final Credential.PushService type, + @JsonProperty("type") final PushService type, @JsonProperty("sandbox") final String sandbox, @JsonProperty("date_created") final String dateCreated, @JsonProperty("date_updated") final String dateUpdated, @@ -144,7 +144,7 @@ public final String getFriendlyName() { return this.friendlyName; } - public final Credential.PushService getType() { + public final PushService getType() { return this.type; } diff --git a/src/main/java/com/twilio/rest/ipmessaging/v2/service/Binding.java b/src/main/java/com/twilio/rest/ipmessaging/v2/service/Binding.java index 3004b0a963..fecd63144c 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v2/service/Binding.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v2/service/Binding.java @@ -111,7 +111,7 @@ public static Binding fromJson( private final String endpoint; private final String identity; private final String credentialSid; - private final Binding.BindingType bindingType; + private final BindingType bindingType; private final List messageTypes; private final URI url; private final Map links; @@ -126,7 +126,7 @@ private Binding( @JsonProperty("endpoint") final String endpoint, @JsonProperty("identity") final String identity, @JsonProperty("credential_sid") final String credentialSid, - @JsonProperty("binding_type") final Binding.BindingType bindingType, + @JsonProperty("binding_type") final BindingType bindingType, @JsonProperty("message_types") final List messageTypes, @JsonProperty("url") final URI url, @JsonProperty("links") final Map links @@ -177,7 +177,7 @@ public final String getCredentialSid() { return this.credentialSid; } - public final Binding.BindingType getBindingType() { + public final BindingType getBindingType() { return this.bindingType; } diff --git a/src/main/java/com/twilio/rest/ipmessaging/v2/service/Channel.java b/src/main/java/com/twilio/rest/ipmessaging/v2/service/Channel.java index 19ae5463c6..8b738c76e5 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v2/service/Channel.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v2/service/Channel.java @@ -119,7 +119,7 @@ public static Channel fromJson( private final String friendlyName; private final String uniqueName; private final String attributes; - private final Channel.ChannelType type; + private final ChannelType type; private final ZonedDateTime dateCreated; private final ZonedDateTime dateUpdated; private final String createdBy; @@ -136,7 +136,7 @@ private Channel( @JsonProperty("friendly_name") final String friendlyName, @JsonProperty("unique_name") final String uniqueName, @JsonProperty("attributes") final String attributes, - @JsonProperty("type") final Channel.ChannelType type, + @JsonProperty("type") final ChannelType type, @JsonProperty("date_created") final String dateCreated, @JsonProperty("date_updated") final String dateUpdated, @JsonProperty("created_by") final String createdBy, @@ -185,7 +185,7 @@ public final String getAttributes() { return this.attributes; } - public final Channel.ChannelType getType() { + public final ChannelType getType() { return this.type; } diff --git a/src/main/java/com/twilio/rest/ipmessaging/v2/service/Role.java b/src/main/java/com/twilio/rest/ipmessaging/v2/service/Role.java index 3f44c5de6f..b36d8e3ae7 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v2/service/Role.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v2/service/Role.java @@ -43,7 +43,7 @@ public class Role extends Resource { public static RoleCreator creator( final String pathServiceSid, final String friendlyName, - final Role.RoleType type, + final RoleType type, final List permission ) { return new RoleCreator(pathServiceSid, friendlyName, type, permission); @@ -122,7 +122,7 @@ public static Role fromJson( private final String accountSid; private final String serviceSid; private final String friendlyName; - private final Role.RoleType type; + private final RoleType type; private final List permissions; private final ZonedDateTime dateCreated; private final ZonedDateTime dateUpdated; @@ -134,7 +134,7 @@ private Role( @JsonProperty("account_sid") final String accountSid, @JsonProperty("service_sid") final String serviceSid, @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("type") final Role.RoleType type, + @JsonProperty("type") final RoleType type, @JsonProperty("permissions") final List permissions, @JsonProperty("date_created") final String dateCreated, @JsonProperty("date_updated") final String dateUpdated, @@ -167,7 +167,7 @@ public final String getFriendlyName() { return this.friendlyName; } - public final Role.RoleType getType() { + public final RoleType getType() { return this.type; } diff --git a/src/main/java/com/twilio/rest/ipmessaging/v2/service/channel/Webhook.java b/src/main/java/com/twilio/rest/ipmessaging/v2/service/channel/Webhook.java index e4202e4268..8674cc57fc 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v2/service/channel/Webhook.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v2/service/channel/Webhook.java @@ -44,7 +44,7 @@ public class Webhook extends Resource { public static WebhookCreator creator( final String pathServiceSid, final String pathChannelSid, - final Webhook.Type type + final Type type ) { return new WebhookCreator(pathServiceSid, pathChannelSid, type); } diff --git a/src/main/java/com/twilio/rest/ipmessaging/v2/service/user/UserBinding.java b/src/main/java/com/twilio/rest/ipmessaging/v2/service/user/UserBinding.java index e43512d118..a9ccdfface 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v2/service/user/UserBinding.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v2/service/user/UserBinding.java @@ -115,7 +115,7 @@ public static UserBinding fromJson( private final String identity; private final String userSid; private final String credentialSid; - private final UserBinding.BindingType bindingType; + private final BindingType bindingType; private final List messageTypes; private final URI url; @@ -130,7 +130,7 @@ private UserBinding( @JsonProperty("identity") final String identity, @JsonProperty("user_sid") final String userSid, @JsonProperty("credential_sid") final String credentialSid, - @JsonProperty("binding_type") final UserBinding.BindingType bindingType, + @JsonProperty("binding_type") final BindingType bindingType, @JsonProperty("message_types") final List messageTypes, @JsonProperty("url") final URI url ) { @@ -184,7 +184,7 @@ public final String getCredentialSid() { return this.credentialSid; } - public final UserBinding.BindingType getBindingType() { + public final BindingType getBindingType() { return this.bindingType; } diff --git a/src/main/java/com/twilio/rest/ipmessaging/v2/service/user/UserChannel.java b/src/main/java/com/twilio/rest/ipmessaging/v2/service/user/UserChannel.java index 780eca1a29..5b8761e478 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v2/service/user/UserChannel.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v2/service/user/UserChannel.java @@ -130,12 +130,12 @@ public static UserChannel fromJson( private final String channelSid; private final String userSid; private final String memberSid; - private final UserChannel.ChannelStatus status; + private final ChannelStatus status; private final Integer lastConsumedMessageIndex; private final Integer unreadMessagesCount; private final Map links; private final URI url; - private final UserChannel.NotificationLevel notificationLevel; + private final NotificationLevel notificationLevel; @JsonCreator private UserChannel( @@ -144,7 +144,7 @@ private UserChannel( @JsonProperty("channel_sid") final String channelSid, @JsonProperty("user_sid") final String userSid, @JsonProperty("member_sid") final String memberSid, - @JsonProperty("status") final UserChannel.ChannelStatus status, + @JsonProperty("status") final ChannelStatus status, @JsonProperty( "last_consumed_message_index" ) final Integer lastConsumedMessageIndex, @@ -155,7 +155,7 @@ private UserChannel( @JsonProperty("url") final URI url, @JsonProperty( "notification_level" - ) final UserChannel.NotificationLevel notificationLevel + ) final NotificationLevel notificationLevel ) { this.accountSid = accountSid; this.serviceSid = serviceSid; @@ -190,7 +190,7 @@ public final String getMemberSid() { return this.memberSid; } - public final UserChannel.ChannelStatus getStatus() { + public final ChannelStatus getStatus() { return this.status; } @@ -210,7 +210,7 @@ public final URI getUrl() { return this.url; } - public final UserChannel.NotificationLevel getNotificationLevel() { + public final NotificationLevel getNotificationLevel() { return this.notificationLevel; } diff --git a/src/main/java/com/twilio/rest/knowledge/v1/Knowledge.java b/src/main/java/com/twilio/rest/knowledge/v1/Knowledge.java index a2a7a572e3..4e6b69d6a9 100644 --- a/src/main/java/com/twilio/rest/knowledge/v1/Knowledge.java +++ b/src/main/java/com/twilio/rest/knowledge/v1/Knowledge.java @@ -23,7 +23,6 @@ import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; -import com.twilio.converter.Converter; import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; @@ -71,10 +70,6 @@ public static class KnowledgeV1ServiceCreatePolicyRequest { @Setter private Object policyDetails; - public String getPolicyDetails() { - return Converter.objectToJson(policyDetails); - } - @JsonInclude(JsonInclude.Include.NON_EMPTY) @JsonProperty("type") @Getter @@ -107,10 +102,6 @@ public static class KnowledgeV1ServiceCreateKnowledgeRequest { @Setter private Map knowledgeSourceDetails; - public String getKnowledgeSourceDetails() { - return Converter.mapToJson(knowledgeSourceDetails); - } - @JsonInclude(JsonInclude.Include.NON_EMPTY) @JsonProperty("name") @Getter @@ -135,7 +126,13 @@ public String getKnowledgeSourceDetails() { @Setter private String embeddingModel; - public KnowledgeV1ServiceCreateKnowledgeRequest() {} + public KnowledgeV1ServiceCreateKnowledgeRequest( + final String name, + final String type + ) { + this.name = name; + this.type = type; + } public static KnowledgeV1ServiceCreateKnowledgeRequest fromJson( String jsonString, @@ -163,10 +160,6 @@ public static class KnowledgeV1ServiceUpdateKnowledgeRequest { @Setter private Map knowledgeSourceDetails; - public String getKnowledgeSourceDetails() { - return Converter.mapToJson(knowledgeSourceDetails); - } - @JsonInclude(JsonInclude.Include.NON_EMPTY) @JsonProperty("name") @Getter @@ -205,7 +198,7 @@ public static KnowledgeV1ServiceUpdateKnowledgeRequest fromJson( } public static KnowledgeCreator creator( - final Knowledge.KnowledgeV1ServiceCreateKnowledgeRequest knowledgeV1ServiceCreateKnowledgeRequest + final KnowledgeV1ServiceCreateKnowledgeRequest knowledgeV1ServiceCreateKnowledgeRequest ) { return new KnowledgeCreator(knowledgeV1ServiceCreateKnowledgeRequest); } diff --git a/src/main/java/com/twilio/rest/lookups/v2/PhoneNumber.java b/src/main/java/com/twilio/rest/lookups/v2/PhoneNumber.java index 0bed3d57d4..4b25a770ee 100644 --- a/src/main/java/com/twilio/rest/lookups/v2/PhoneNumber.java +++ b/src/main/java/com/twilio/rest/lookups/v2/PhoneNumber.java @@ -92,7 +92,7 @@ public static PhoneNumber fromJson( private final com.twilio.type.PhoneNumber phoneNumber; private final String nationalFormat; private final Boolean valid; - private final List validationErrors; + private final List validationErrors; private final Map callerName; private final Map simSwap; private final Map callForwarding; @@ -115,7 +115,7 @@ private PhoneNumber( @JsonProperty("national_format") final String nationalFormat, @JsonProperty("valid") final Boolean valid, @JsonProperty("validation_errors") final List< - PhoneNumber.ValidationError + ValidationError > validationErrors, @JsonProperty("caller_name") final Map callerName, @JsonProperty("sim_swap") final Map simSwap, @@ -183,7 +183,7 @@ public final Boolean getValid() { return this.valid; } - public final List getValidationErrors() { + public final List getValidationErrors() { return this.validationErrors; } diff --git a/src/main/java/com/twilio/rest/marketplace/v1/ReferralConversion.java b/src/main/java/com/twilio/rest/marketplace/v1/ReferralConversion.java index 2981e42916..4210a1e21c 100644 --- a/src/main/java/com/twilio/rest/marketplace/v1/ReferralConversion.java +++ b/src/main/java/com/twilio/rest/marketplace/v1/ReferralConversion.java @@ -62,7 +62,7 @@ public static CreateReferralConversionRequest fromJson( } public static ReferralConversionCreator creator( - final ReferralConversion.CreateReferralConversionRequest createReferralConversionRequest + final CreateReferralConversionRequest createReferralConversionRequest ) { return new ReferralConversionCreator(createReferralConversionRequest); } diff --git a/src/main/java/com/twilio/rest/marketplace/v1/installedaddon/InstalledAddOnUsage.java b/src/main/java/com/twilio/rest/marketplace/v1/installedaddon/InstalledAddOnUsage.java index 26949939ae..02d957a065 100644 --- a/src/main/java/com/twilio/rest/marketplace/v1/installedaddon/InstalledAddOnUsage.java +++ b/src/main/java/com/twilio/rest/marketplace/v1/installedaddon/InstalledAddOnUsage.java @@ -111,7 +111,7 @@ public static MarketplaceV1InstalledAddOnInstalledAddOnUsage fromJson( public static InstalledAddOnUsageCreator creator( final String pathInstalledAddOnSid, - final InstalledAddOnUsage.MarketplaceV1InstalledAddOnInstalledAddOnUsage marketplaceV1InstalledAddOnInstalledAddOnUsage + final MarketplaceV1InstalledAddOnInstalledAddOnUsage marketplaceV1InstalledAddOnInstalledAddOnUsage ) { return new InstalledAddOnUsageCreator( pathInstalledAddOnSid, diff --git a/src/main/java/com/twilio/rest/messaging/v1/BrandRegistration.java b/src/main/java/com/twilio/rest/messaging/v1/BrandRegistration.java index 1f04545099..a485f926b2 100644 --- a/src/main/java/com/twilio/rest/messaging/v1/BrandRegistration.java +++ b/src/main/java/com/twilio/rest/messaging/v1/BrandRegistration.java @@ -114,14 +114,14 @@ public static BrandRegistration fromJson( private final ZonedDateTime dateCreated; private final ZonedDateTime dateUpdated; private final String brandType; - private final BrandRegistration.Status status; + private final Status status; private final String tcrId; private final String failureReason; private final List> errors; private final URI url; private final Integer brandScore; - private final List brandFeedback; - private final BrandRegistration.IdentityStatus identityStatus; + private final List brandFeedback; + private final IdentityStatus identityStatus; private final Boolean russell3000; private final Boolean governmentEntity; private final String taxExemptStatus; @@ -142,18 +142,14 @@ private BrandRegistration( @JsonProperty("date_created") final String dateCreated, @JsonProperty("date_updated") final String dateUpdated, @JsonProperty("brand_type") final String brandType, - @JsonProperty("status") final BrandRegistration.Status status, + @JsonProperty("status") final Status status, @JsonProperty("tcr_id") final String tcrId, @JsonProperty("failure_reason") final String failureReason, @JsonProperty("errors") final List> errors, @JsonProperty("url") final URI url, @JsonProperty("brand_score") final Integer brandScore, - @JsonProperty("brand_feedback") final List< - BrandRegistration.BrandFeedback - > brandFeedback, - @JsonProperty( - "identity_status" - ) final BrandRegistration.IdentityStatus identityStatus, + @JsonProperty("brand_feedback") final List brandFeedback, + @JsonProperty("identity_status") final IdentityStatus identityStatus, @JsonProperty("russell3000") final Boolean russell3000, @JsonProperty("government_entity") final Boolean governmentEntity, @JsonProperty("tax_exempt_status") final String taxExemptStatus, @@ -214,7 +210,7 @@ public final String getBrandType() { return this.brandType; } - public final BrandRegistration.Status getStatus() { + public final Status getStatus() { return this.status; } @@ -238,11 +234,11 @@ public final Integer getBrandScore() { return this.brandScore; } - public final List getBrandFeedback() { + public final List getBrandFeedback() { return this.brandFeedback; } - public final BrandRegistration.IdentityStatus getIdentityStatus() { + public final IdentityStatus getIdentityStatus() { return this.identityStatus; } diff --git a/src/main/java/com/twilio/rest/messaging/v1/Service.java b/src/main/java/com/twilio/rest/messaging/v1/Service.java index 3775bf4572..9d320105f4 100644 --- a/src/main/java/com/twilio/rest/messaging/v1/Service.java +++ b/src/main/java/com/twilio/rest/messaging/v1/Service.java @@ -118,7 +118,7 @@ public static Service fromJson( private final Boolean stickySender; private final Boolean mmsConverter; private final Boolean smartEncoding; - private final Service.ScanMessageContent scanMessageContent; + private final ScanMessageContent scanMessageContent; private final Boolean fallbackToLongCode; private final Boolean areaCodeGeomatch; private final Boolean synchronousValidation; @@ -146,7 +146,7 @@ private Service( @JsonProperty("smart_encoding") final Boolean smartEncoding, @JsonProperty( "scan_message_content" - ) final Service.ScanMessageContent scanMessageContent, + ) final ScanMessageContent scanMessageContent, @JsonProperty("fallback_to_long_code") final Boolean fallbackToLongCode, @JsonProperty("area_code_geomatch") final Boolean areaCodeGeomatch, @JsonProperty( @@ -240,7 +240,7 @@ public final Boolean getSmartEncoding() { return this.smartEncoding; } - public final Service.ScanMessageContent getScanMessageContent() { + public final ScanMessageContent getScanMessageContent() { return this.scanMessageContent; } diff --git a/src/main/java/com/twilio/rest/messaging/v1/TollfreeVerification.java b/src/main/java/com/twilio/rest/messaging/v1/TollfreeVerification.java index da3ddb6f84..2a189ab49f 100644 --- a/src/main/java/com/twilio/rest/messaging/v1/TollfreeVerification.java +++ b/src/main/java/com/twilio/rest/messaging/v1/TollfreeVerification.java @@ -50,7 +50,7 @@ public static TollfreeVerificationCreator creator( final String useCaseSummary, final String productionMessageSample, final List optInImageUrls, - final TollfreeVerification.OptInType optInType, + final OptInType optInType, final String messageVolume, final String tollfreePhoneNumberSid ) { @@ -151,11 +151,11 @@ public static TollfreeVerification fromJson( private final String useCaseSummary; private final String productionMessageSample; private final List optInImageUrls; - private final TollfreeVerification.OptInType optInType; + private final OptInType optInType; private final String messageVolume; private final String additionalInformation; private final String tollfreePhoneNumberSid; - private final TollfreeVerification.Status status; + private final Status status; private final URI url; private final String rejectionReason; private final Integer errorCode; @@ -209,9 +209,7 @@ private TollfreeVerification( "production_message_sample" ) final String productionMessageSample, @JsonProperty("opt_in_image_urls") final List optInImageUrls, - @JsonProperty( - "opt_in_type" - ) final TollfreeVerification.OptInType optInType, + @JsonProperty("opt_in_type") final OptInType optInType, @JsonProperty("message_volume") final String messageVolume, @JsonProperty( "additional_information" @@ -219,7 +217,7 @@ private TollfreeVerification( @JsonProperty( "tollfree_phone_number_sid" ) final String tollfreePhoneNumberSid, - @JsonProperty("status") final TollfreeVerification.Status status, + @JsonProperty("status") final Status status, @JsonProperty("url") final URI url, @JsonProperty("rejection_reason") final String rejectionReason, @JsonProperty("error_code") final Integer errorCode, @@ -367,7 +365,7 @@ public final List getOptInImageUrls() { return this.optInImageUrls; } - public final TollfreeVerification.OptInType getOptInType() { + public final OptInType getOptInType() { return this.optInType; } @@ -383,7 +381,7 @@ public final String getTollfreePhoneNumberSid() { return this.tollfreePhoneNumberSid; } - public final TollfreeVerification.Status getStatus() { + public final Status getStatus() { return this.status; } diff --git a/src/main/java/com/twilio/rest/messaging/v1/brandregistration/BrandVetting.java b/src/main/java/com/twilio/rest/messaging/v1/brandregistration/BrandVetting.java index 7d7f8526b5..8c284bbaf7 100644 --- a/src/main/java/com/twilio/rest/messaging/v1/brandregistration/BrandVetting.java +++ b/src/main/java/com/twilio/rest/messaging/v1/brandregistration/BrandVetting.java @@ -41,7 +41,7 @@ public class BrandVetting extends Resource { public static BrandVettingCreator creator( final String pathBrandSid, - final BrandVetting.VettingProvider vettingProvider + final VettingProvider vettingProvider ) { return new BrandVettingCreator(pathBrandSid, vettingProvider); } @@ -108,7 +108,7 @@ public static BrandVetting fromJson( private final String vettingId; private final String vettingClass; private final String vettingStatus; - private final BrandVetting.VettingProvider vettingProvider; + private final VettingProvider vettingProvider; private final URI url; @JsonCreator @@ -121,9 +121,7 @@ private BrandVetting( @JsonProperty("vetting_id") final String vettingId, @JsonProperty("vetting_class") final String vettingClass, @JsonProperty("vetting_status") final String vettingStatus, - @JsonProperty( - "vetting_provider" - ) final BrandVetting.VettingProvider vettingProvider, + @JsonProperty("vetting_provider") final VettingProvider vettingProvider, @JsonProperty("url") final URI url ) { this.accountSid = accountSid; @@ -170,7 +168,7 @@ public final String getVettingStatus() { return this.vettingStatus; } - public final BrandVetting.VettingProvider getVettingProvider() { + public final VettingProvider getVettingProvider() { return this.vettingProvider; } diff --git a/src/main/java/com/twilio/rest/messaging/v2/ChannelsSender.java b/src/main/java/com/twilio/rest/messaging/v2/ChannelsSender.java index 0560e1d4ce..c2650d66d0 100644 --- a/src/main/java/com/twilio/rest/messaging/v2/ChannelsSender.java +++ b/src/main/java/com/twilio/rest/messaging/v2/ChannelsSender.java @@ -23,7 +23,6 @@ import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; -import com.twilio.converter.Converter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; @@ -41,7 +40,7 @@ @ToString public class ChannelsSender extends Resource { - private static final long serialVersionUID = 42075077215889L; + private static final long serialVersionUID = 103954331986266L; @ToString public static class MessagingV2ChannelsSenderConfiguration { @@ -164,10 +163,6 @@ public static class MessagingV2ChannelsSenderProfile { @Setter private Object emails; - public String getEmails() { - return Converter.objectToJson(emails); - } - @JsonInclude(JsonInclude.Include.NON_EMPTY) @JsonProperty("logo_url") @Getter @@ -186,10 +181,6 @@ public String getEmails() { @Setter private Object websites; - public String getWebsites() { - return Converter.objectToJson(websites); - } - public static MessagingV2ChannelsSenderProfile fromJson( String jsonString, ObjectMapper mapper @@ -228,7 +219,9 @@ public static class MessagingV2ChannelsSenderRequestsCreate { @Setter private MessagingV2ChannelsSenderProfile profile; - public MessagingV2ChannelsSenderRequestsCreate() {} + public MessagingV2ChannelsSenderRequestsCreate(final String senderId) { + this.senderId = senderId; + } public static MessagingV2ChannelsSenderRequestsCreate fromJson( String jsonString, @@ -275,6 +268,120 @@ public static MessagingV2ChannelsSenderRequestsUpdate fromJson( } } + @ToString + public static class MessagingV2ChannelsSenderProfileResponseEmails { + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("email") + @Getter + @Setter + private String email; + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("label") + @Getter + @Setter + private String label; + + public static MessagingV2ChannelsSenderProfileResponseEmails fromJson( + String jsonString, + ObjectMapper mapper + ) throws IOException { + return mapper.readValue( + jsonString, + MessagingV2ChannelsSenderProfileResponseEmails.class + ); + } + } + + @ToString + public static class MessagingV2ChannelsSenderProfileResponseWebsites { + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("website") + @Getter + @Setter + private String website; + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("label") + @Getter + @Setter + private String label; + + public static MessagingV2ChannelsSenderProfileResponseWebsites fromJson( + String jsonString, + ObjectMapper mapper + ) throws IOException { + return mapper.readValue( + jsonString, + MessagingV2ChannelsSenderProfileResponseWebsites.class + ); + } + } + + @ToString + public static class MessagingV2ChannelsSenderProfileResponse { + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("name") + @Getter + @Setter + private String name; + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("about") + @Getter + @Setter + private String about; + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("address") + @Getter + @Setter + private String address; + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("description") + @Getter + @Setter + private String description; + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("emails") + @Getter + @Setter + private List emails; + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("logo_url") + @Getter + @Setter + private String logoUrl; + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("vertical") + @Getter + @Setter + private String vertical; + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("websites") + @Getter + @Setter + private List websites; + + public static MessagingV2ChannelsSenderProfileResponse fromJson( + String jsonString, + ObjectMapper mapper + ) throws IOException { + return mapper.readValue( + jsonString, + MessagingV2ChannelsSenderProfileResponse.class + ); + } + } + @ToString public static class MessagingV2ChannelsSenderProperties { @@ -334,7 +441,7 @@ public static MessagingV2ChannelsSenderOfflineReasonsItems fromJson( } public static ChannelsSenderCreator creator( - final ChannelsSender.MessagingV2ChannelsSenderRequestsCreate messagingV2ChannelsSenderRequestsCreate + final MessagingV2ChannelsSenderRequestsCreate messagingV2ChannelsSenderRequestsCreate ) { return new ChannelsSenderCreator( messagingV2ChannelsSenderRequestsCreate @@ -413,11 +520,11 @@ public static String toJson(Object object, ObjectMapper mapper) { } private final String sid; - private final ChannelsSender.Status status; + private final Status status; private final String senderId; private final MessagingV2ChannelsSenderConfiguration configuration; private final MessagingV2ChannelsSenderWebhook webhook; - private final MessagingV2ChannelsSenderProfile profile; + private final MessagingV2ChannelsSenderProfileResponse profile; private final MessagingV2ChannelsSenderProperties properties; private final List< MessagingV2ChannelsSenderOfflineReasonsItems @@ -427,13 +534,15 @@ public static String toJson(Object object, ObjectMapper mapper) { @JsonCreator private ChannelsSender( @JsonProperty("sid") final String sid, - @JsonProperty("status") final ChannelsSender.Status status, + @JsonProperty("status") final Status status, @JsonProperty("sender_id") final String senderId, @JsonProperty( "configuration" ) final MessagingV2ChannelsSenderConfiguration configuration, @JsonProperty("webhook") final MessagingV2ChannelsSenderWebhook webhook, - @JsonProperty("profile") final MessagingV2ChannelsSenderProfile profile, + @JsonProperty( + "profile" + ) final MessagingV2ChannelsSenderProfileResponse profile, @JsonProperty( "properties" ) final MessagingV2ChannelsSenderProperties properties, @@ -457,7 +566,7 @@ public final String getSid() { return this.sid; } - public final ChannelsSender.Status getStatus() { + public final Status getStatus() { return this.status; } @@ -473,7 +582,7 @@ public final MessagingV2ChannelsSenderWebhook getWebhook() { return this.webhook; } - public final MessagingV2ChannelsSenderProfile getProfile() { + public final MessagingV2ChannelsSenderProfileResponse getProfile() { return this.profile; } diff --git a/src/main/java/com/twilio/rest/notify/v1/Credential.java b/src/main/java/com/twilio/rest/notify/v1/Credential.java index 316599eb29..26d2e47199 100644 --- a/src/main/java/com/twilio/rest/notify/v1/Credential.java +++ b/src/main/java/com/twilio/rest/notify/v1/Credential.java @@ -39,7 +39,7 @@ public class Credential extends Resource { private static final long serialVersionUID = 161183169234848L; - public static CredentialCreator creator(final Credential.PushService type) { + public static CredentialCreator creator(final PushService type) { return new CredentialCreator(type); } @@ -105,7 +105,7 @@ public static Credential fromJson( private final String sid; private final String accountSid; private final String friendlyName; - private final Credential.PushService type; + private final PushService type; private final String sandbox; private final ZonedDateTime dateCreated; private final ZonedDateTime dateUpdated; @@ -116,7 +116,7 @@ private Credential( @JsonProperty("sid") final String sid, @JsonProperty("account_sid") final String accountSid, @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("type") final Credential.PushService type, + @JsonProperty("type") final PushService type, @JsonProperty("sandbox") final String sandbox, @JsonProperty("date_created") final String dateCreated, @JsonProperty("date_updated") final String dateUpdated, @@ -144,7 +144,7 @@ public final String getFriendlyName() { return this.friendlyName; } - public final Credential.PushService getType() { + public final PushService getType() { return this.type; } diff --git a/src/main/java/com/twilio/rest/notify/v1/service/Binding.java b/src/main/java/com/twilio/rest/notify/v1/service/Binding.java index a61e6c16e0..e5d9cf47db 100644 --- a/src/main/java/com/twilio/rest/notify/v1/service/Binding.java +++ b/src/main/java/com/twilio/rest/notify/v1/service/Binding.java @@ -45,7 +45,7 @@ public class Binding extends Resource { public static BindingCreator creator( final String pathServiceSid, final String identity, - final Binding.BindingType bindingType, + final BindingType bindingType, final String address ) { return new BindingCreator( diff --git a/src/main/java/com/twilio/rest/notify/v1/service/Notification.java b/src/main/java/com/twilio/rest/notify/v1/service/Notification.java index 432641c6cb..2fd78f20f6 100644 --- a/src/main/java/com/twilio/rest/notify/v1/service/Notification.java +++ b/src/main/java/com/twilio/rest/notify/v1/service/Notification.java @@ -95,7 +95,7 @@ public static Notification fromJson( private final List identities; private final List tags; private final List segments; - private final Notification.Priority priority; + private final Priority priority; private final Integer ttl; private final String title; private final String body; @@ -118,7 +118,7 @@ private Notification( @JsonProperty("identities") final List identities, @JsonProperty("tags") final List tags, @JsonProperty("segments") final List segments, - @JsonProperty("priority") final Notification.Priority priority, + @JsonProperty("priority") final Priority priority, @JsonProperty("ttl") final Integer ttl, @JsonProperty("title") final String title, @JsonProperty("body") final String body, @@ -185,7 +185,7 @@ public final List getSegments() { return this.segments; } - public final Notification.Priority getPriority() { + public final Priority getPriority() { return this.priority; } diff --git a/src/main/java/com/twilio/rest/notify/v1/service/NotificationCreator.java b/src/main/java/com/twilio/rest/notify/v1/service/NotificationCreator.java index c1debefd56..249e0f9685 100644 --- a/src/main/java/com/twilio/rest/notify/v1/service/NotificationCreator.java +++ b/src/main/java/com/twilio/rest/notify/v1/service/NotificationCreator.java @@ -29,8 +29,6 @@ import com.twilio.rest.Domains; import java.util.List; import java.util.List; -import java.util.Map; -import java.util.Map; public class NotificationCreator extends Creator { @@ -41,14 +39,14 @@ public class NotificationCreator extends Creator { private String title; private String sound; private String action; - private Map data; - private Map apn; - private Map gcm; - private Map sms; - private Map facebookMessenger; - private Map fcm; + private Object data; + private Object apn; + private Object gcm; + private Object sms; + private Object facebookMessenger; + private Object fcm; private List segment; - private Map alexa; + private Object alexa; private List toBinding; private String deliveryCallbackUrl; private List identity; @@ -90,34 +88,34 @@ public NotificationCreator setAction(final String action) { return this; } - public NotificationCreator setData(final Map data) { + public NotificationCreator setData(final Object data) { this.data = data; return this; } - public NotificationCreator setApn(final Map apn) { + public NotificationCreator setApn(final Object apn) { this.apn = apn; return this; } - public NotificationCreator setGcm(final Map gcm) { + public NotificationCreator setGcm(final Object gcm) { this.gcm = gcm; return this; } - public NotificationCreator setSms(final Map sms) { + public NotificationCreator setSms(final Object sms) { this.sms = sms; return this; } public NotificationCreator setFacebookMessenger( - final Map facebookMessenger + final Object facebookMessenger ) { this.facebookMessenger = facebookMessenger; return this; } - public NotificationCreator setFcm(final Map fcm) { + public NotificationCreator setFcm(final Object fcm) { this.fcm = fcm; return this; } @@ -131,7 +129,7 @@ public NotificationCreator setSegment(final String segment) { return setSegment(Promoter.listOfOne(segment)); } - public NotificationCreator setAlexa(final Map alexa) { + public NotificationCreator setAlexa(final Object alexa) { this.alexa = alexa; return this; } @@ -232,25 +230,25 @@ private void addPostParams(final Request request) { request.addPostParam("Action", action); } if (data != null) { - request.addPostParam("Data", Converter.mapToJson(data)); + request.addPostParam("Data", Converter.objectToJson(data)); } if (apn != null) { - request.addPostParam("Apn", Converter.mapToJson(apn)); + request.addPostParam("Apn", Converter.objectToJson(apn)); } if (gcm != null) { - request.addPostParam("Gcm", Converter.mapToJson(gcm)); + request.addPostParam("Gcm", Converter.objectToJson(gcm)); } if (sms != null) { - request.addPostParam("Sms", Converter.mapToJson(sms)); + request.addPostParam("Sms", Converter.objectToJson(sms)); } if (facebookMessenger != null) { request.addPostParam( "FacebookMessenger", - Converter.mapToJson(facebookMessenger) + Converter.objectToJson(facebookMessenger) ); } if (fcm != null) { - request.addPostParam("Fcm", Converter.mapToJson(fcm)); + request.addPostParam("Fcm", Converter.objectToJson(fcm)); } if (segment != null) { for (String prop : segment) { @@ -258,7 +256,7 @@ private void addPostParams(final Request request) { } } if (alexa != null) { - request.addPostParam("Alexa", Converter.mapToJson(alexa)); + request.addPostParam("Alexa", Converter.objectToJson(alexa)); } if (toBinding != null) { for (String prop : toBinding) { diff --git a/src/main/java/com/twilio/rest/numbers/v1/PortingPortability.java b/src/main/java/com/twilio/rest/numbers/v1/PortingPortability.java index f047290739..1559a8f88f 100644 --- a/src/main/java/com/twilio/rest/numbers/v1/PortingPortability.java +++ b/src/main/java/com/twilio/rest/numbers/v1/PortingPortability.java @@ -92,7 +92,7 @@ public static PortingPortability fromJson( private final Boolean pinAndAccountNumberRequired; private final String notPortableReason; private final Integer notPortableReasonCode; - private final PortingPortability.NumberType numberType; + private final NumberType numberType; private final String country; private final URI url; @@ -110,9 +110,7 @@ private PortingPortability( @JsonProperty( "not_portable_reason_code" ) final Integer notPortableReasonCode, - @JsonProperty( - "number_type" - ) final PortingPortability.NumberType numberType, + @JsonProperty("number_type") final NumberType numberType, @JsonProperty("country") final String country, @JsonProperty("url") final URI url ) { @@ -151,7 +149,7 @@ public final Integer getNotPortableReasonCode() { return this.notPortableReasonCode; } - public final PortingPortability.NumberType getNumberType() { + public final NumberType getNumberType() { return this.numberType; } diff --git a/src/main/java/com/twilio/rest/numbers/v1/PortingPortabilityFetcher.java b/src/main/java/com/twilio/rest/numbers/v1/PortingPortabilityFetcher.java index eedc6e5dc1..3eec9d2bbe 100644 --- a/src/main/java/com/twilio/rest/numbers/v1/PortingPortabilityFetcher.java +++ b/src/main/java/com/twilio/rest/numbers/v1/PortingPortabilityFetcher.java @@ -56,7 +56,7 @@ public PortingPortability fetch(final TwilioRestClient client) { path = path.replace( "{" + "PhoneNumber" + "}", - this.pathPhoneNumber.encode("utf-8") + this.pathPhoneNumber.toString() ); Request request = new Request( diff --git a/src/main/java/com/twilio/rest/numbers/v1/PortingWebhookConfigurationDelete.java b/src/main/java/com/twilio/rest/numbers/v1/PortingWebhookConfigurationDelete.java index cec172e3a1..40d6a5d8e9 100644 --- a/src/main/java/com/twilio/rest/numbers/v1/PortingWebhookConfigurationDelete.java +++ b/src/main/java/com/twilio/rest/numbers/v1/PortingWebhookConfigurationDelete.java @@ -35,7 +35,7 @@ public class PortingWebhookConfigurationDelete extends Resource { private static final long serialVersionUID = 0L; public static PortingWebhookConfigurationDeleteDeleter deleter( - final PortingWebhookConfigurationDelete.WebhookType webhookType + final WebhookType webhookType ) { return new PortingWebhookConfigurationDeleteDeleter(webhookType); } diff --git a/src/main/java/com/twilio/rest/numbers/v2/AuthorizationDocument.java b/src/main/java/com/twilio/rest/numbers/v2/AuthorizationDocument.java index 0c3aa64569..e46f361687 100644 --- a/src/main/java/com/twilio/rest/numbers/v2/AuthorizationDocument.java +++ b/src/main/java/com/twilio/rest/numbers/v2/AuthorizationDocument.java @@ -113,7 +113,7 @@ public static AuthorizationDocument fromJson( private final String sid; private final String addressSid; - private final AuthorizationDocument.Status status; + private final Status status; private final String email; private final List ccEmails; private final ZonedDateTime dateCreated; @@ -125,7 +125,7 @@ public static AuthorizationDocument fromJson( private AuthorizationDocument( @JsonProperty("sid") final String sid, @JsonProperty("address_sid") final String addressSid, - @JsonProperty("status") final AuthorizationDocument.Status status, + @JsonProperty("status") final Status status, @JsonProperty("email") final String email, @JsonProperty("cc_emails") final List ccEmails, @JsonProperty("date_created") final String dateCreated, @@ -152,7 +152,7 @@ public final String getAddressSid() { return this.addressSid; } - public final AuthorizationDocument.Status getStatus() { + public final Status getStatus() { return this.status; } diff --git a/src/main/java/com/twilio/rest/numbers/v2/AuthorizationDocumentCreator.java b/src/main/java/com/twilio/rest/numbers/v2/AuthorizationDocumentCreator.java index fded505c8a..3e9f6c5dd8 100644 --- a/src/main/java/com/twilio/rest/numbers/v2/AuthorizationDocumentCreator.java +++ b/src/main/java/com/twilio/rest/numbers/v2/AuthorizationDocumentCreator.java @@ -118,7 +118,7 @@ public AuthorizationDocument create(final TwilioRestClient client) { path = path.replace( "{" + "ContactPhoneNumber" + "}", - this.contactPhoneNumber.encode("utf-8") + this.contactPhoneNumber.toString() ); path = path.replace( diff --git a/src/main/java/com/twilio/rest/numbers/v2/BulkHostedNumberOrder.java b/src/main/java/com/twilio/rest/numbers/v2/BulkHostedNumberOrder.java index d491067489..a4d6136a15 100644 --- a/src/main/java/com/twilio/rest/numbers/v2/BulkHostedNumberOrder.java +++ b/src/main/java/com/twilio/rest/numbers/v2/BulkHostedNumberOrder.java @@ -109,7 +109,7 @@ public static String toJson(Object object, ObjectMapper mapper) { } private final String bulkHostingSid; - private final BulkHostedNumberOrder.RequestStatus requestStatus; + private final RequestStatus requestStatus; private final String friendlyName; private final String notificationEmail; private final ZonedDateTime dateCreated; @@ -121,9 +121,7 @@ public static String toJson(Object object, ObjectMapper mapper) { @JsonCreator private BulkHostedNumberOrder( @JsonProperty("bulk_hosting_sid") final String bulkHostingSid, - @JsonProperty( - "request_status" - ) final BulkHostedNumberOrder.RequestStatus requestStatus, + @JsonProperty("request_status") final RequestStatus requestStatus, @JsonProperty("friendly_name") final String friendlyName, @JsonProperty("notification_email") final String notificationEmail, @JsonProperty("date_created") final String dateCreated, @@ -148,7 +146,7 @@ public final String getBulkHostingSid() { return this.bulkHostingSid; } - public final BulkHostedNumberOrder.RequestStatus getRequestStatus() { + public final RequestStatus getRequestStatus() { return this.requestStatus; } diff --git a/src/main/java/com/twilio/rest/numbers/v2/BundleClone.java b/src/main/java/com/twilio/rest/numbers/v2/BundleClone.java index 8462b057d5..8f4376dfe5 100644 --- a/src/main/java/com/twilio/rest/numbers/v2/BundleClone.java +++ b/src/main/java/com/twilio/rest/numbers/v2/BundleClone.java @@ -93,7 +93,7 @@ public static BundleClone fromJson( private final String accountSid; private final String regulationSid; private final String friendlyName; - private final BundleClone.Status status; + private final Status status; private final ZonedDateTime validUntil; private final String email; private final URI statusCallback; @@ -107,7 +107,7 @@ private BundleClone( @JsonProperty("account_sid") final String accountSid, @JsonProperty("regulation_sid") final String regulationSid, @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("status") final BundleClone.Status status, + @JsonProperty("status") final Status status, @JsonProperty("valid_until") final String validUntil, @JsonProperty("email") final String email, @JsonProperty("status_callback") final URI statusCallback, @@ -144,7 +144,7 @@ public final String getFriendlyName() { return this.friendlyName; } - public final BundleClone.Status getStatus() { + public final Status getStatus() { return this.status; } diff --git a/src/main/java/com/twilio/rest/numbers/v2/HostedNumberOrder.java b/src/main/java/com/twilio/rest/numbers/v2/HostedNumberOrder.java index 6363d99966..4b6531f726 100644 --- a/src/main/java/com/twilio/rest/numbers/v2/HostedNumberOrder.java +++ b/src/main/java/com/twilio/rest/numbers/v2/HostedNumberOrder.java @@ -69,7 +69,7 @@ public static HostedNumberOrderReader reader() { public static HostedNumberOrderUpdater updater( final String pathSid, - final HostedNumberOrder.Status status + final Status status ) { return new HostedNumberOrderUpdater(pathSid, status); } @@ -125,7 +125,7 @@ public static HostedNumberOrder fromJson( private final com.twilio.type.PhoneNumber phoneNumber; private final PhoneNumberCapabilities capabilities; private final String friendlyName; - private final HostedNumberOrder.Status status; + private final Status status; private final String failureReason; private final ZonedDateTime dateCreated; private final ZonedDateTime dateUpdated; @@ -141,7 +141,7 @@ public static HostedNumberOrder fromJson( private final Integer verificationCallDelay; private final String verificationCallExtension; private final String verificationCode; - private final HostedNumberOrder.VerificationType verificationType; + private final VerificationType verificationType; @JsonCreator private HostedNumberOrder( @@ -159,7 +159,7 @@ private HostedNumberOrder( "capabilities" ) final PhoneNumberCapabilities capabilities, @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("status") final HostedNumberOrder.Status status, + @JsonProperty("status") final Status status, @JsonProperty("failure_reason") final String failureReason, @JsonProperty("date_created") final String dateCreated, @JsonProperty("date_updated") final String dateUpdated, @@ -189,7 +189,7 @@ private HostedNumberOrder( @JsonProperty("verification_code") final String verificationCode, @JsonProperty( "verification_type" - ) final HostedNumberOrder.VerificationType verificationType + ) final VerificationType verificationType ) { this.sid = sid; this.accountSid = accountSid; @@ -250,7 +250,7 @@ public final String getFriendlyName() { return this.friendlyName; } - public final HostedNumberOrder.Status getStatus() { + public final Status getStatus() { return this.status; } @@ -314,7 +314,7 @@ public final String getVerificationCode() { return this.verificationCode; } - public final HostedNumberOrder.VerificationType getVerificationType() { + public final VerificationType getVerificationType() { return this.verificationType; } diff --git a/src/main/java/com/twilio/rest/numbers/v2/HostedNumberOrderCreator.java b/src/main/java/com/twilio/rest/numbers/v2/HostedNumberOrderCreator.java index 7de5551daf..1345e5ce8a 100644 --- a/src/main/java/com/twilio/rest/numbers/v2/HostedNumberOrderCreator.java +++ b/src/main/java/com/twilio/rest/numbers/v2/HostedNumberOrderCreator.java @@ -196,12 +196,12 @@ public HostedNumberOrder create(final TwilioRestClient client) { path = path.replace( "{" + "PhoneNumber" + "}", - this.phoneNumber.encode("utf-8") + this.phoneNumber.toString() ); path = path.replace( "{" + "ContactPhoneNumber" + "}", - this.contactPhoneNumber.encode("utf-8") + this.contactPhoneNumber.toString() ); path = path.replace("{" + "AddressSid" + "}", this.addressSid.toString()); diff --git a/src/main/java/com/twilio/rest/numbers/v2/authorizationdocument/DependentHostedNumberOrder.java b/src/main/java/com/twilio/rest/numbers/v2/authorizationdocument/DependentHostedNumberOrder.java index 01b4345f77..c27f699fe5 100644 --- a/src/main/java/com/twilio/rest/numbers/v2/authorizationdocument/DependentHostedNumberOrder.java +++ b/src/main/java/com/twilio/rest/numbers/v2/authorizationdocument/DependentHostedNumberOrder.java @@ -105,7 +105,7 @@ public static DependentHostedNumberOrder fromJson( private final com.twilio.type.PhoneNumber phoneNumber; private final PhoneNumberCapabilities capabilities; private final String friendlyName; - private final DependentHostedNumberOrder.Status status; + private final Status status; private final String failureReason; private final ZonedDateTime dateCreated; private final ZonedDateTime dateUpdated; @@ -134,7 +134,7 @@ private DependentHostedNumberOrder( "capabilities" ) final PhoneNumberCapabilities capabilities, @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("status") final DependentHostedNumberOrder.Status status, + @JsonProperty("status") final Status status, @JsonProperty("failure_reason") final String failureReason, @JsonProperty("date_created") final String dateCreated, @JsonProperty("date_updated") final String dateUpdated, @@ -205,7 +205,7 @@ public final String getFriendlyName() { return this.friendlyName; } - public final DependentHostedNumberOrder.Status getStatus() { + public final Status getStatus() { return this.status; } diff --git a/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/Bundle.java b/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/Bundle.java index 9371ac3164..1245b44248 100644 --- a/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/Bundle.java +++ b/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/Bundle.java @@ -111,7 +111,7 @@ public static Bundle fromJson( private final String accountSid; private final String regulationSid; private final String friendlyName; - private final Bundle.Status status; + private final Status status; private final ZonedDateTime validUntil; private final String email; private final URI statusCallback; @@ -126,7 +126,7 @@ private Bundle( @JsonProperty("account_sid") final String accountSid, @JsonProperty("regulation_sid") final String regulationSid, @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("status") final Bundle.Status status, + @JsonProperty("status") final Status status, @JsonProperty("valid_until") final String validUntil, @JsonProperty("email") final String email, @JsonProperty("status_callback") final URI statusCallback, @@ -165,7 +165,7 @@ public final String getFriendlyName() { return this.friendlyName; } - public final Bundle.Status getStatus() { + public final Status getStatus() { return this.status; } diff --git a/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/EndUser.java b/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/EndUser.java index 6bfd90c4ab..57f8bc63d6 100644 --- a/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/EndUser.java +++ b/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/EndUser.java @@ -43,7 +43,7 @@ public class EndUser extends Resource { public static EndUserCreator creator( final String friendlyName, - final EndUser.Type type + final Type type ) { return new EndUserCreator(friendlyName, type); } @@ -110,7 +110,7 @@ public static EndUser fromJson( private final String sid; private final String accountSid; private final String friendlyName; - private final EndUser.Type type; + private final Type type; private final Map attributes; private final ZonedDateTime dateCreated; private final ZonedDateTime dateUpdated; @@ -121,7 +121,7 @@ private EndUser( @JsonProperty("sid") final String sid, @JsonProperty("account_sid") final String accountSid, @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("type") final EndUser.Type type, + @JsonProperty("type") final Type type, @JsonProperty("attributes") final Map attributes, @JsonProperty("date_created") final String dateCreated, @JsonProperty("date_updated") final String dateUpdated, @@ -149,7 +149,7 @@ public final String getFriendlyName() { return this.friendlyName; } - public final EndUser.Type getType() { + public final Type getType() { return this.type; } diff --git a/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/EndUserCreator.java b/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/EndUserCreator.java index 52ac79162d..9f301c0623 100644 --- a/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/EndUserCreator.java +++ b/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/EndUserCreator.java @@ -26,14 +26,12 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -import java.util.Map; -import java.util.Map; public class EndUserCreator extends Creator { private String friendlyName; private EndUser.Type type; - private Map attributes; + private Object attributes; public EndUserCreator(final String friendlyName, final EndUser.Type type) { this.friendlyName = friendlyName; @@ -50,7 +48,7 @@ public EndUserCreator setType(final EndUser.Type type) { return this; } - public EndUserCreator setAttributes(final Map attributes) { + public EndUserCreator setAttributes(final Object attributes) { this.attributes = attributes; return this; } @@ -103,7 +101,10 @@ private void addPostParams(final Request request) { request.addPostParam("Type", type.toString()); } if (attributes != null) { - request.addPostParam("Attributes", Converter.mapToJson(attributes)); + request.addPostParam( + "Attributes", + Converter.objectToJson(attributes) + ); } } } diff --git a/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/EndUserUpdater.java b/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/EndUserUpdater.java index 0abd35a726..189bd34787 100644 --- a/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/EndUserUpdater.java +++ b/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/EndUserUpdater.java @@ -25,13 +25,12 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -import java.util.Map; public class EndUserUpdater extends Updater { private String pathSid; private String friendlyName; - private Map attributes; + private Object attributes; public EndUserUpdater(final String pathSid) { this.pathSid = pathSid; @@ -42,7 +41,7 @@ public EndUserUpdater setFriendlyName(final String friendlyName) { return this; } - public EndUserUpdater setAttributes(final Map attributes) { + public EndUserUpdater setAttributes(final Object attributes) { this.attributes = attributes; return this; } @@ -87,7 +86,10 @@ private void addPostParams(final Request request) { request.addPostParam("FriendlyName", friendlyName); } if (attributes != null) { - request.addPostParam("Attributes", Converter.mapToJson(attributes)); + request.addPostParam( + "Attributes", + Converter.objectToJson(attributes) + ); } } } diff --git a/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/Regulation.java b/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/Regulation.java index 5c89d54944..16fdea60d1 100644 --- a/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/Regulation.java +++ b/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/Regulation.java @@ -94,7 +94,7 @@ public static Regulation fromJson( private final String friendlyName; private final String isoCountry; private final String numberType; - private final Regulation.EndUserType endUserType; + private final EndUserType endUserType; private final Map requirements; private final URI url; @@ -104,7 +104,7 @@ private Regulation( @JsonProperty("friendly_name") final String friendlyName, @JsonProperty("iso_country") final String isoCountry, @JsonProperty("number_type") final String numberType, - @JsonProperty("end_user_type") final Regulation.EndUserType endUserType, + @JsonProperty("end_user_type") final EndUserType endUserType, @JsonProperty("requirements") final Map requirements, @JsonProperty("url") final URI url ) { @@ -133,7 +133,7 @@ public final String getNumberType() { return this.numberType; } - public final Regulation.EndUserType getEndUserType() { + public final EndUserType getEndUserType() { return this.endUserType; } diff --git a/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/SupportingDocument.java b/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/SupportingDocument.java index 50135af80f..7562f95557 100644 --- a/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/SupportingDocument.java +++ b/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/SupportingDocument.java @@ -112,7 +112,7 @@ public static SupportingDocument fromJson( private final String accountSid; private final String friendlyName; private final String mimeType; - private final SupportingDocument.Status status; + private final Status status; private final String failureReason; private final List> errors; private final String type; @@ -127,7 +127,7 @@ private SupportingDocument( @JsonProperty("account_sid") final String accountSid, @JsonProperty("friendly_name") final String friendlyName, @JsonProperty("mime_type") final String mimeType, - @JsonProperty("status") final SupportingDocument.Status status, + @JsonProperty("status") final Status status, @JsonProperty("failure_reason") final String failureReason, @JsonProperty("errors") final List> errors, @JsonProperty("type") final String type, @@ -166,7 +166,7 @@ public final String getMimeType() { return this.mimeType; } - public final SupportingDocument.Status getStatus() { + public final Status getStatus() { return this.status; } diff --git a/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/SupportingDocumentCreator.java b/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/SupportingDocumentCreator.java index 61701ee5a0..9c53a94eb5 100644 --- a/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/SupportingDocumentCreator.java +++ b/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/SupportingDocumentCreator.java @@ -26,14 +26,12 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -import java.util.Map; -import java.util.Map; public class SupportingDocumentCreator extends Creator { private String friendlyName; private String type; - private Map attributes; + private Object attributes; public SupportingDocumentCreator( final String friendlyName, @@ -55,9 +53,7 @@ public SupportingDocumentCreator setType(final String type) { return this; } - public SupportingDocumentCreator setAttributes( - final Map attributes - ) { + public SupportingDocumentCreator setAttributes(final Object attributes) { this.attributes = attributes; return this; } @@ -113,7 +109,10 @@ private void addPostParams(final Request request) { request.addPostParam("Type", type); } if (attributes != null) { - request.addPostParam("Attributes", Converter.mapToJson(attributes)); + request.addPostParam( + "Attributes", + Converter.objectToJson(attributes) + ); } } } diff --git a/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/SupportingDocumentUpdater.java b/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/SupportingDocumentUpdater.java index 9e8edb947e..4a243f5fc5 100644 --- a/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/SupportingDocumentUpdater.java +++ b/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/SupportingDocumentUpdater.java @@ -25,13 +25,12 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -import java.util.Map; public class SupportingDocumentUpdater extends Updater { private String pathSid; private String friendlyName; - private Map attributes; + private Object attributes; public SupportingDocumentUpdater(final String pathSid) { this.pathSid = pathSid; @@ -44,9 +43,7 @@ public SupportingDocumentUpdater setFriendlyName( return this; } - public SupportingDocumentUpdater setAttributes( - final Map attributes - ) { + public SupportingDocumentUpdater setAttributes(final Object attributes) { this.attributes = attributes; return this; } @@ -94,7 +91,10 @@ private void addPostParams(final Request request) { request.addPostParam("FriendlyName", friendlyName); } if (attributes != null) { - request.addPostParam("Attributes", Converter.mapToJson(attributes)); + request.addPostParam( + "Attributes", + Converter.objectToJson(attributes) + ); } } } diff --git a/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/bundle/BundleCopy.java b/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/bundle/BundleCopy.java index 04ac0cb803..f769beb1da 100644 --- a/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/bundle/BundleCopy.java +++ b/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/bundle/BundleCopy.java @@ -94,7 +94,7 @@ public static BundleCopy fromJson( private final String accountSid; private final String regulationSid; private final String friendlyName; - private final BundleCopy.Status status; + private final Status status; private final ZonedDateTime validUntil; private final String email; private final URI statusCallback; @@ -107,7 +107,7 @@ private BundleCopy( @JsonProperty("account_sid") final String accountSid, @JsonProperty("regulation_sid") final String regulationSid, @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("status") final BundleCopy.Status status, + @JsonProperty("status") final Status status, @JsonProperty("valid_until") final String validUntil, @JsonProperty("email") final String email, @JsonProperty("status_callback") final URI statusCallback, @@ -142,7 +142,7 @@ public final String getFriendlyName() { return this.friendlyName; } - public final BundleCopy.Status getStatus() { + public final Status getStatus() { return this.status; } diff --git a/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/bundle/Evaluation.java b/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/bundle/Evaluation.java index 669f216872..4cd6b14db5 100644 --- a/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/bundle/Evaluation.java +++ b/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/bundle/Evaluation.java @@ -104,7 +104,7 @@ public static Evaluation fromJson( private final String accountSid; private final String regulationSid; private final String bundleSid; - private final Evaluation.Status status; + private final Status status; private final List> results; private final ZonedDateTime dateCreated; private final URI url; @@ -115,7 +115,7 @@ private Evaluation( @JsonProperty("account_sid") final String accountSid, @JsonProperty("regulation_sid") final String regulationSid, @JsonProperty("bundle_sid") final String bundleSid, - @JsonProperty("status") final Evaluation.Status status, + @JsonProperty("status") final Status status, @JsonProperty("results") final List> results, @JsonProperty("date_created") final String dateCreated, @JsonProperty("url") final URI url @@ -146,7 +146,7 @@ public final String getBundleSid() { return this.bundleSid; } - public final Evaluation.Status getStatus() { + public final Status getStatus() { return this.status; } diff --git a/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/bundle/ReplaceItems.java b/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/bundle/ReplaceItems.java index 9af6e75dac..77fec453f4 100644 --- a/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/bundle/ReplaceItems.java +++ b/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/bundle/ReplaceItems.java @@ -93,7 +93,7 @@ public static ReplaceItems fromJson( private final String accountSid; private final String regulationSid; private final String friendlyName; - private final ReplaceItems.Status status; + private final Status status; private final ZonedDateTime validUntil; private final String email; private final URI statusCallback; @@ -106,7 +106,7 @@ private ReplaceItems( @JsonProperty("account_sid") final String accountSid, @JsonProperty("regulation_sid") final String regulationSid, @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("status") final ReplaceItems.Status status, + @JsonProperty("status") final Status status, @JsonProperty("valid_until") final String validUntil, @JsonProperty("email") final String email, @JsonProperty("status_callback") final URI statusCallback, @@ -141,7 +141,7 @@ public final String getFriendlyName() { return this.friendlyName; } - public final ReplaceItems.Status getStatus() { + public final Status getStatus() { return this.status; } diff --git a/src/main/java/com/twilio/rest/preview/hostedNumbers/AuthorizationDocument.java b/src/main/java/com/twilio/rest/preview/hostedNumbers/AuthorizationDocument.java index 9bb552cfaf..7370fc631f 100644 --- a/src/main/java/com/twilio/rest/preview/hostedNumbers/AuthorizationDocument.java +++ b/src/main/java/com/twilio/rest/preview/hostedNumbers/AuthorizationDocument.java @@ -115,7 +115,7 @@ public static AuthorizationDocument fromJson( private final String sid; private final String addressSid; - private final AuthorizationDocument.Status status; + private final Status status; private final String email; private final List ccEmails; private final ZonedDateTime dateCreated; @@ -127,7 +127,7 @@ public static AuthorizationDocument fromJson( private AuthorizationDocument( @JsonProperty("sid") final String sid, @JsonProperty("address_sid") final String addressSid, - @JsonProperty("status") final AuthorizationDocument.Status status, + @JsonProperty("status") final Status status, @JsonProperty("email") final String email, @JsonProperty("cc_emails") final List ccEmails, @JsonProperty("date_created") final String dateCreated, @@ -154,7 +154,7 @@ public final String getAddressSid() { return this.addressSid; } - public final AuthorizationDocument.Status getStatus() { + public final Status getStatus() { return this.status; } diff --git a/src/main/java/com/twilio/rest/preview/hostedNumbers/HostedNumberOrder.java b/src/main/java/com/twilio/rest/preview/hostedNumbers/HostedNumberOrder.java index 1accd8a6ea..d3b6e61791 100644 --- a/src/main/java/com/twilio/rest/preview/hostedNumbers/HostedNumberOrder.java +++ b/src/main/java/com/twilio/rest/preview/hostedNumbers/HostedNumberOrder.java @@ -116,7 +116,7 @@ public static HostedNumberOrder fromJson( private final PhoneNumberCapabilities capabilities; private final String friendlyName; private final String uniqueName; - private final HostedNumberOrder.Status status; + private final Status status; private final String failureReason; private final ZonedDateTime dateCreated; private final ZonedDateTime dateUpdated; @@ -124,7 +124,7 @@ public static HostedNumberOrder fromJson( private final String email; private final List ccEmails; private final URI url; - private final HostedNumberOrder.VerificationType verificationType; + private final VerificationType verificationType; private final String verificationDocumentSid; private final String extension; private final Integer callDelay; @@ -148,7 +148,7 @@ private HostedNumberOrder( ) final PhoneNumberCapabilities capabilities, @JsonProperty("friendly_name") final String friendlyName, @JsonProperty("unique_name") final String uniqueName, - @JsonProperty("status") final HostedNumberOrder.Status status, + @JsonProperty("status") final Status status, @JsonProperty("failure_reason") final String failureReason, @JsonProperty("date_created") final String dateCreated, @JsonProperty("date_updated") final String dateUpdated, @@ -160,7 +160,7 @@ private HostedNumberOrder( @JsonProperty("url") final URI url, @JsonProperty( "verification_type" - ) final HostedNumberOrder.VerificationType verificationType, + ) final VerificationType verificationType, @JsonProperty( "verification_document_sid" ) final String verificationDocumentSid, @@ -232,7 +232,7 @@ public final String getUniqueName() { return this.uniqueName; } - public final HostedNumberOrder.Status getStatus() { + public final Status getStatus() { return this.status; } @@ -264,7 +264,7 @@ public final URI getUrl() { return this.url; } - public final HostedNumberOrder.VerificationType getVerificationType() { + public final VerificationType getVerificationType() { return this.verificationType; } diff --git a/src/main/java/com/twilio/rest/preview/hostedNumbers/HostedNumberOrderCreator.java b/src/main/java/com/twilio/rest/preview/hostedNumbers/HostedNumberOrderCreator.java index 4f48c3128b..927eba9f60 100644 --- a/src/main/java/com/twilio/rest/preview/hostedNumbers/HostedNumberOrderCreator.java +++ b/src/main/java/com/twilio/rest/preview/hostedNumbers/HostedNumberOrderCreator.java @@ -192,7 +192,7 @@ public HostedNumberOrder create(final TwilioRestClient client) { path = path.replace( "{" + "PhoneNumber" + "}", - this.phoneNumber.encode("utf-8") + this.phoneNumber.toString() ); path = path.replace( diff --git a/src/main/java/com/twilio/rest/preview/hostedNumbers/authorizationdocument/DependentHostedNumberOrder.java b/src/main/java/com/twilio/rest/preview/hostedNumbers/authorizationdocument/DependentHostedNumberOrder.java index a568b081d8..2ca263c614 100644 --- a/src/main/java/com/twilio/rest/preview/hostedNumbers/authorizationdocument/DependentHostedNumberOrder.java +++ b/src/main/java/com/twilio/rest/preview/hostedNumbers/authorizationdocument/DependentHostedNumberOrder.java @@ -104,14 +104,14 @@ public static DependentHostedNumberOrder fromJson( private final PhoneNumberCapabilities capabilities; private final String friendlyName; private final String uniqueName; - private final DependentHostedNumberOrder.Status status; + private final Status status; private final String failureReason; private final ZonedDateTime dateCreated; private final ZonedDateTime dateUpdated; private final Integer verificationAttempts; private final String email; private final List ccEmails; - private final DependentHostedNumberOrder.VerificationType verificationType; + private final VerificationType verificationType; private final String verificationDocumentSid; private final String extension; private final Integer callDelay; @@ -135,7 +135,7 @@ private DependentHostedNumberOrder( ) final PhoneNumberCapabilities capabilities, @JsonProperty("friendly_name") final String friendlyName, @JsonProperty("unique_name") final String uniqueName, - @JsonProperty("status") final DependentHostedNumberOrder.Status status, + @JsonProperty("status") final Status status, @JsonProperty("failure_reason") final String failureReason, @JsonProperty("date_created") final String dateCreated, @JsonProperty("date_updated") final String dateUpdated, @@ -146,7 +146,7 @@ private DependentHostedNumberOrder( @JsonProperty("cc_emails") final List ccEmails, @JsonProperty( "verification_type" - ) final DependentHostedNumberOrder.VerificationType verificationType, + ) final VerificationType verificationType, @JsonProperty( "verification_document_sid" ) final String verificationDocumentSid, @@ -217,7 +217,7 @@ public final String getUniqueName() { return this.uniqueName; } - public final DependentHostedNumberOrder.Status getStatus() { + public final Status getStatus() { return this.status; } @@ -245,7 +245,7 @@ public final List getCcEmails() { return this.ccEmails; } - public final DependentHostedNumberOrder.VerificationType getVerificationType() { + public final VerificationType getVerificationType() { return this.verificationType; } diff --git a/src/main/java/com/twilio/rest/preview/marketplace/InstalledAddOnCreator.java b/src/main/java/com/twilio/rest/preview/marketplace/InstalledAddOnCreator.java index 881b0d804c..21254453bc 100644 --- a/src/main/java/com/twilio/rest/preview/marketplace/InstalledAddOnCreator.java +++ b/src/main/java/com/twilio/rest/preview/marketplace/InstalledAddOnCreator.java @@ -26,14 +26,12 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -import java.util.Map; -import java.util.Map; public class InstalledAddOnCreator extends Creator { private String availableAddOnSid; private Boolean acceptTermsOfService; - private Map configuration; + private Object configuration; private String uniqueName; public InstalledAddOnCreator( @@ -58,9 +56,7 @@ public InstalledAddOnCreator setAcceptTermsOfService( return this; } - public InstalledAddOnCreator setConfiguration( - final Map configuration - ) { + public InstalledAddOnCreator setConfiguration(final Object configuration) { this.configuration = configuration; return this; } @@ -130,7 +126,7 @@ private void addPostParams(final Request request) { if (configuration != null) { request.addPostParam( "Configuration", - Converter.mapToJson(configuration) + Converter.objectToJson(configuration) ); } if (uniqueName != null) { diff --git a/src/main/java/com/twilio/rest/preview/marketplace/InstalledAddOnUpdater.java b/src/main/java/com/twilio/rest/preview/marketplace/InstalledAddOnUpdater.java index 72748e7594..bb4dc1e55b 100644 --- a/src/main/java/com/twilio/rest/preview/marketplace/InstalledAddOnUpdater.java +++ b/src/main/java/com/twilio/rest/preview/marketplace/InstalledAddOnUpdater.java @@ -25,21 +25,18 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -import java.util.Map; public class InstalledAddOnUpdater extends Updater { private String pathSid; - private Map configuration; + private Object configuration; private String uniqueName; public InstalledAddOnUpdater(final String pathSid) { this.pathSid = pathSid; } - public InstalledAddOnUpdater setConfiguration( - final Map configuration - ) { + public InstalledAddOnUpdater setConfiguration(final Object configuration) { this.configuration = configuration; return this; } @@ -91,7 +88,7 @@ private void addPostParams(final Request request) { if (configuration != null) { request.addPostParam( "Configuration", - Converter.mapToJson(configuration) + Converter.objectToJson(configuration) ); } if (uniqueName != null) { diff --git a/src/main/java/com/twilio/rest/previewiam/organizations/Account.java b/src/main/java/com/twilio/rest/previewiam/organizations/Account.java index 388b31fa34..5186823e23 100644 --- a/src/main/java/com/twilio/rest/previewiam/organizations/Account.java +++ b/src/main/java/com/twilio/rest/previewiam/organizations/Account.java @@ -94,7 +94,7 @@ public static Account fromJson( private final String accountSid; private final String friendlyName; - private final Account.StatusEnum status; + private final StatusEnum status; private final String ownerSid; private final ZonedDateTime dateCreated; @@ -102,7 +102,7 @@ public static Account fromJson( private Account( @JsonProperty("account_sid") final String accountSid, @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("status") final Account.StatusEnum status, + @JsonProperty("status") final StatusEnum status, @JsonProperty("owner_sid") final String ownerSid, @JsonProperty("date_created") final String dateCreated ) { @@ -121,7 +121,7 @@ public final String getFriendlyName() { return this.friendlyName; } - public final Account.StatusEnum getStatus() { + public final StatusEnum getStatus() { return this.status; } diff --git a/src/main/java/com/twilio/rest/previewiam/organizations/RoleAssignment.java b/src/main/java/com/twilio/rest/previewiam/organizations/RoleAssignment.java index 875068a004..f02a6ad8fa 100644 --- a/src/main/java/com/twilio/rest/previewiam/organizations/RoleAssignment.java +++ b/src/main/java/com/twilio/rest/previewiam/organizations/RoleAssignment.java @@ -83,7 +83,7 @@ public static PublicApiCreateRoleAssignmentRequest fromJson( public static RoleAssignmentCreator creator( final String pathOrganizationSid, - final RoleAssignment.PublicApiCreateRoleAssignmentRequest publicApiCreateRoleAssignmentRequest + final PublicApiCreateRoleAssignmentRequest publicApiCreateRoleAssignmentRequest ) { return new RoleAssignmentCreator( pathOrganizationSid, diff --git a/src/main/java/com/twilio/rest/previewiam/organizations/User.java b/src/main/java/com/twilio/rest/previewiam/organizations/User.java index 2e3a501701..923872e3e5 100644 --- a/src/main/java/com/twilio/rest/previewiam/organizations/User.java +++ b/src/main/java/com/twilio/rest/previewiam/organizations/User.java @@ -213,7 +213,7 @@ public static ScimUser fromJson(String jsonString, ObjectMapper mapper) public static UserCreator creator( final String pathOrganizationSid, - final User.ScimUser scimUser + final ScimUser scimUser ) { return new UserCreator(pathOrganizationSid, scimUser); } @@ -239,7 +239,7 @@ public static UserReader reader(final String pathOrganizationSid) { public static UserUpdater updater( final String pathOrganizationSid, final String pathUserSid, - final User.ScimUser scimUser + final ScimUser scimUser ) { return new UserUpdater(pathOrganizationSid, pathUserSid, scimUser); } diff --git a/src/main/java/com/twilio/rest/pricing/v1/messaging/Country.java b/src/main/java/com/twilio/rest/pricing/v1/messaging/Country.java index b94e824fc8..80882ed263 100644 --- a/src/main/java/com/twilio/rest/pricing/v1/messaging/Country.java +++ b/src/main/java/com/twilio/rest/pricing/v1/messaging/Country.java @@ -111,7 +111,7 @@ private Country( InboundSmsPrice > inboundSmsPrices, @JsonProperty("price_unit") @JsonDeserialize( - using = com.twilio.converter.CurrencyDeserializer.class + using = CurrencyDeserializer.class ) final Currency priceUnit, @JsonProperty("url") final URI url ) { diff --git a/src/main/java/com/twilio/rest/pricing/v1/phonenumber/Country.java b/src/main/java/com/twilio/rest/pricing/v1/phonenumber/Country.java index b7460493df..8c3d1a112f 100644 --- a/src/main/java/com/twilio/rest/pricing/v1/phonenumber/Country.java +++ b/src/main/java/com/twilio/rest/pricing/v1/phonenumber/Country.java @@ -106,7 +106,7 @@ private Country( PhoneNumberPrice > phoneNumberPrices, @JsonProperty("price_unit") @JsonDeserialize( - using = com.twilio.converter.CurrencyDeserializer.class + using = CurrencyDeserializer.class ) final Currency priceUnit, @JsonProperty("url") final URI url ) { diff --git a/src/main/java/com/twilio/rest/pricing/v1/voice/Country.java b/src/main/java/com/twilio/rest/pricing/v1/voice/Country.java index 766b5a0ced..571bdc47f3 100644 --- a/src/main/java/com/twilio/rest/pricing/v1/voice/Country.java +++ b/src/main/java/com/twilio/rest/pricing/v1/voice/Country.java @@ -111,7 +111,7 @@ private Country( InboundCallPrice > inboundCallPrices, @JsonProperty("price_unit") @JsonDeserialize( - using = com.twilio.converter.CurrencyDeserializer.class + using = CurrencyDeserializer.class ) final Currency priceUnit, @JsonProperty("url") final URI url ) { diff --git a/src/main/java/com/twilio/rest/pricing/v1/voice/Number.java b/src/main/java/com/twilio/rest/pricing/v1/voice/Number.java index 84501022ef..c3554827ba 100644 --- a/src/main/java/com/twilio/rest/pricing/v1/voice/Number.java +++ b/src/main/java/com/twilio/rest/pricing/v1/voice/Number.java @@ -110,7 +110,7 @@ private Number( "inbound_call_price" ) final InboundCallPrice inboundCallPrice, @JsonProperty("price_unit") @JsonDeserialize( - using = com.twilio.converter.CurrencyDeserializer.class + using = CurrencyDeserializer.class ) final Currency priceUnit, @JsonProperty("url") final URI url ) { diff --git a/src/main/java/com/twilio/rest/pricing/v1/voice/NumberFetcher.java b/src/main/java/com/twilio/rest/pricing/v1/voice/NumberFetcher.java index 4b3b9a50fd..ff3d62d4e3 100644 --- a/src/main/java/com/twilio/rest/pricing/v1/voice/NumberFetcher.java +++ b/src/main/java/com/twilio/rest/pricing/v1/voice/NumberFetcher.java @@ -37,8 +37,7 @@ public NumberFetcher(final com.twilio.type.PhoneNumber pathNumber) { public Number fetch(final TwilioRestClient client) { String path = "/v1/Voice/Numbers/{Number}"; - path = - path.replace("{" + "Number" + "}", this.pathNumber.encode("utf-8")); + path = path.replace("{" + "Number" + "}", this.pathNumber.toString()); Request request = new Request( HttpMethod.GET, diff --git a/src/main/java/com/twilio/rest/pricing/v2/Country.java b/src/main/java/com/twilio/rest/pricing/v2/Country.java index a95ebb6743..337a60e819 100644 --- a/src/main/java/com/twilio/rest/pricing/v2/Country.java +++ b/src/main/java/com/twilio/rest/pricing/v2/Country.java @@ -111,7 +111,7 @@ private Country( InboundCallPrice > originatingCallPrices, @JsonProperty("price_unit") @JsonDeserialize( - using = com.twilio.converter.CurrencyDeserializer.class + using = CurrencyDeserializer.class ) final Currency priceUnit, @JsonProperty("url") final URI url ) { diff --git a/src/main/java/com/twilio/rest/pricing/v2/Number.java b/src/main/java/com/twilio/rest/pricing/v2/Number.java index 3d8c0f89fe..f23418faf6 100644 --- a/src/main/java/com/twilio/rest/pricing/v2/Number.java +++ b/src/main/java/com/twilio/rest/pricing/v2/Number.java @@ -117,7 +117,7 @@ private Number( "originating_call_price" ) final InboundCallPrice originatingCallPrice, @JsonProperty("price_unit") @JsonDeserialize( - using = com.twilio.converter.CurrencyDeserializer.class + using = CurrencyDeserializer.class ) final Currency priceUnit, @JsonProperty("url") final URI url ) { diff --git a/src/main/java/com/twilio/rest/pricing/v2/NumberFetcher.java b/src/main/java/com/twilio/rest/pricing/v2/NumberFetcher.java index b433b097a0..e41c589818 100644 --- a/src/main/java/com/twilio/rest/pricing/v2/NumberFetcher.java +++ b/src/main/java/com/twilio/rest/pricing/v2/NumberFetcher.java @@ -57,7 +57,7 @@ public Number fetch(final TwilioRestClient client) { path = path.replace( "{" + "DestinationNumber" + "}", - this.pathDestinationNumber.encode("utf-8") + this.pathDestinationNumber.toString() ); Request request = new Request( diff --git a/src/main/java/com/twilio/rest/pricing/v2/voice/Country.java b/src/main/java/com/twilio/rest/pricing/v2/voice/Country.java index 18a482f54f..678cc56bda 100644 --- a/src/main/java/com/twilio/rest/pricing/v2/voice/Country.java +++ b/src/main/java/com/twilio/rest/pricing/v2/voice/Country.java @@ -111,7 +111,7 @@ private Country( InboundCallPrice > inboundCallPrices, @JsonProperty("price_unit") @JsonDeserialize( - using = com.twilio.converter.CurrencyDeserializer.class + using = CurrencyDeserializer.class ) final Currency priceUnit, @JsonProperty("url") final URI url ) { diff --git a/src/main/java/com/twilio/rest/pricing/v2/voice/Number.java b/src/main/java/com/twilio/rest/pricing/v2/voice/Number.java index cb87bffd51..c34fd46796 100644 --- a/src/main/java/com/twilio/rest/pricing/v2/voice/Number.java +++ b/src/main/java/com/twilio/rest/pricing/v2/voice/Number.java @@ -117,7 +117,7 @@ private Number( "inbound_call_price" ) final InboundCallPrice inboundCallPrice, @JsonProperty("price_unit") @JsonDeserialize( - using = com.twilio.converter.CurrencyDeserializer.class + using = CurrencyDeserializer.class ) final Currency priceUnit, @JsonProperty("url") final URI url ) { diff --git a/src/main/java/com/twilio/rest/pricing/v2/voice/NumberFetcher.java b/src/main/java/com/twilio/rest/pricing/v2/voice/NumberFetcher.java index a0285c5f44..806d653a7b 100644 --- a/src/main/java/com/twilio/rest/pricing/v2/voice/NumberFetcher.java +++ b/src/main/java/com/twilio/rest/pricing/v2/voice/NumberFetcher.java @@ -57,7 +57,7 @@ public Number fetch(final TwilioRestClient client) { path = path.replace( "{" + "DestinationNumber" + "}", - this.pathDestinationNumber.encode("utf-8") + this.pathDestinationNumber.toString() ); Request request = new Request( diff --git a/src/main/java/com/twilio/rest/proxy/v1/Service.java b/src/main/java/com/twilio/rest/proxy/v1/Service.java index 65eb5245f6..58fe5e69af 100644 --- a/src/main/java/com/twilio/rest/proxy/v1/Service.java +++ b/src/main/java/com/twilio/rest/proxy/v1/Service.java @@ -110,8 +110,8 @@ public static Service fromJson( private final String chatInstanceSid; private final URI callbackUrl; private final Integer defaultTtl; - private final Service.NumberSelectionBehavior numberSelectionBehavior; - private final Service.GeoMatchLevel geoMatchLevel; + private final NumberSelectionBehavior numberSelectionBehavior; + private final GeoMatchLevel geoMatchLevel; private final URI interceptCallbackUrl; private final URI outOfSessionCallbackUrl; private final ZonedDateTime dateCreated; @@ -129,10 +129,8 @@ private Service( @JsonProperty("default_ttl") final Integer defaultTtl, @JsonProperty( "number_selection_behavior" - ) final Service.NumberSelectionBehavior numberSelectionBehavior, - @JsonProperty( - "geo_match_level" - ) final Service.GeoMatchLevel geoMatchLevel, + ) final NumberSelectionBehavior numberSelectionBehavior, + @JsonProperty("geo_match_level") final GeoMatchLevel geoMatchLevel, @JsonProperty("intercept_callback_url") final URI interceptCallbackUrl, @JsonProperty( "out_of_session_callback_url" @@ -182,11 +180,11 @@ public final Integer getDefaultTtl() { return this.defaultTtl; } - public final Service.NumberSelectionBehavior getNumberSelectionBehavior() { + public final NumberSelectionBehavior getNumberSelectionBehavior() { return this.numberSelectionBehavior; } - public final Service.GeoMatchLevel getGeoMatchLevel() { + public final GeoMatchLevel getGeoMatchLevel() { return this.geoMatchLevel; } diff --git a/src/main/java/com/twilio/rest/proxy/v1/service/Session.java b/src/main/java/com/twilio/rest/proxy/v1/service/Session.java index 2c8db7c6ad..07b22595d9 100644 --- a/src/main/java/com/twilio/rest/proxy/v1/service/Session.java +++ b/src/main/java/com/twilio/rest/proxy/v1/service/Session.java @@ -121,10 +121,10 @@ public static Session fromJson( private final ZonedDateTime dateLastInteraction; private final ZonedDateTime dateExpiry; private final String uniqueName; - private final Session.Status status; + private final Status status; private final String closedReason; private final Integer ttl; - private final Session.Mode mode; + private final Mode mode; private final ZonedDateTime dateCreated; private final ZonedDateTime dateUpdated; private final URI url; @@ -140,10 +140,10 @@ private Session( @JsonProperty("date_last_interaction") final String dateLastInteraction, @JsonProperty("date_expiry") final String dateExpiry, @JsonProperty("unique_name") final String uniqueName, - @JsonProperty("status") final Session.Status status, + @JsonProperty("status") final Status status, @JsonProperty("closed_reason") final String closedReason, @JsonProperty("ttl") final Integer ttl, - @JsonProperty("mode") final Session.Mode mode, + @JsonProperty("mode") final Mode mode, @JsonProperty("date_created") final String dateCreated, @JsonProperty("date_updated") final String dateUpdated, @JsonProperty("url") final URI url, @@ -200,7 +200,7 @@ public final String getUniqueName() { return this.uniqueName; } - public final Session.Status getStatus() { + public final Status getStatus() { return this.status; } @@ -212,7 +212,7 @@ public final Integer getTtl() { return this.ttl; } - public final Session.Mode getMode() { + public final Mode getMode() { return this.mode; } diff --git a/src/main/java/com/twilio/rest/proxy/v1/service/SessionCreator.java b/src/main/java/com/twilio/rest/proxy/v1/service/SessionCreator.java index 988ff069e6..7cabf721a5 100644 --- a/src/main/java/com/twilio/rest/proxy/v1/service/SessionCreator.java +++ b/src/main/java/com/twilio/rest/proxy/v1/service/SessionCreator.java @@ -16,8 +16,6 @@ import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; -import com.twilio.converter.Converter; -import com.twilio.converter.Converter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; @@ -30,8 +28,6 @@ import java.time.ZonedDateTime; import java.util.List; import java.util.List; -import java.util.Map; -import java.util.Map; public class SessionCreator extends Creator { @@ -41,7 +37,7 @@ public class SessionCreator extends Creator { private Integer ttl; private Session.Mode mode; private Session.Status status; - private List> participants; + private List participants; public SessionCreator(final String pathServiceSid) { this.pathServiceSid = pathServiceSid; @@ -72,16 +68,12 @@ public SessionCreator setStatus(final Session.Status status) { return this; } - public SessionCreator setParticipants( - final List> participants - ) { + public SessionCreator setParticipants(final List participants) { this.participants = participants; return this; } - public SessionCreator setParticipants( - final Map participants - ) { + public SessionCreator setParticipants(final Object participants) { return setParticipants(Promoter.listOfOne(participants)); } @@ -144,8 +136,8 @@ private void addPostParams(final Request request) { request.addPostParam("Status", status.toString()); } if (participants != null) { - for (Map prop : participants) { - request.addPostParam("Participants", Converter.mapToJson(prop)); + for (Object prop : participants) { + request.addPostParam("Participants", prop.toString()); } } } diff --git a/src/main/java/com/twilio/rest/proxy/v1/service/session/Interaction.java b/src/main/java/com/twilio/rest/proxy/v1/service/session/Interaction.java index 9167ddc0a9..67ee90770a 100644 --- a/src/main/java/com/twilio/rest/proxy/v1/service/session/Interaction.java +++ b/src/main/java/com/twilio/rest/proxy/v1/service/session/Interaction.java @@ -110,15 +110,15 @@ public static Interaction fromJson( private final String serviceSid; private final String accountSid; private final String data; - private final Interaction.Type type; + private final Type type; private final String inboundParticipantSid; private final String inboundResourceSid; - private final Interaction.ResourceStatus inboundResourceStatus; + private final ResourceStatus inboundResourceStatus; private final String inboundResourceType; private final URI inboundResourceUrl; private final String outboundParticipantSid; private final String outboundResourceSid; - private final Interaction.ResourceStatus outboundResourceStatus; + private final ResourceStatus outboundResourceStatus; private final String outboundResourceType; private final URI outboundResourceUrl; private final ZonedDateTime dateCreated; @@ -132,14 +132,14 @@ private Interaction( @JsonProperty("service_sid") final String serviceSid, @JsonProperty("account_sid") final String accountSid, @JsonProperty("data") final String data, - @JsonProperty("type") final Interaction.Type type, + @JsonProperty("type") final Type type, @JsonProperty( "inbound_participant_sid" ) final String inboundParticipantSid, @JsonProperty("inbound_resource_sid") final String inboundResourceSid, @JsonProperty( "inbound_resource_status" - ) final Interaction.ResourceStatus inboundResourceStatus, + ) final ResourceStatus inboundResourceStatus, @JsonProperty("inbound_resource_type") final String inboundResourceType, @JsonProperty("inbound_resource_url") final URI inboundResourceUrl, @JsonProperty( @@ -148,7 +148,7 @@ private Interaction( @JsonProperty("outbound_resource_sid") final String outboundResourceSid, @JsonProperty( "outbound_resource_status" - ) final Interaction.ResourceStatus outboundResourceStatus, + ) final ResourceStatus outboundResourceStatus, @JsonProperty( "outbound_resource_type" ) final String outboundResourceType, @@ -198,7 +198,7 @@ public final String getData() { return this.data; } - public final Interaction.Type getType() { + public final Type getType() { return this.type; } @@ -210,7 +210,7 @@ public final String getInboundResourceSid() { return this.inboundResourceSid; } - public final Interaction.ResourceStatus getInboundResourceStatus() { + public final ResourceStatus getInboundResourceStatus() { return this.inboundResourceStatus; } @@ -230,7 +230,7 @@ public final String getOutboundResourceSid() { return this.outboundResourceSid; } - public final Interaction.ResourceStatus getOutboundResourceStatus() { + public final ResourceStatus getOutboundResourceStatus() { return this.outboundResourceStatus; } diff --git a/src/main/java/com/twilio/rest/proxy/v1/service/session/participant/MessageInteraction.java b/src/main/java/com/twilio/rest/proxy/v1/service/session/participant/MessageInteraction.java index 2cc5764aa6..fffb740206 100644 --- a/src/main/java/com/twilio/rest/proxy/v1/service/session/participant/MessageInteraction.java +++ b/src/main/java/com/twilio/rest/proxy/v1/service/session/participant/MessageInteraction.java @@ -142,16 +142,16 @@ public static MessageInteraction fromJson( private final String serviceSid; private final String accountSid; private final String data; - private final MessageInteraction.Type type; + private final Type type; private final String participantSid; private final String inboundParticipantSid; private final String inboundResourceSid; - private final MessageInteraction.ResourceStatus inboundResourceStatus; + private final ResourceStatus inboundResourceStatus; private final String inboundResourceType; private final URI inboundResourceUrl; private final String outboundParticipantSid; private final String outboundResourceSid; - private final MessageInteraction.ResourceStatus outboundResourceStatus; + private final ResourceStatus outboundResourceStatus; private final String outboundResourceType; private final URI outboundResourceUrl; private final ZonedDateTime dateCreated; @@ -165,7 +165,7 @@ private MessageInteraction( @JsonProperty("service_sid") final String serviceSid, @JsonProperty("account_sid") final String accountSid, @JsonProperty("data") final String data, - @JsonProperty("type") final MessageInteraction.Type type, + @JsonProperty("type") final Type type, @JsonProperty("participant_sid") final String participantSid, @JsonProperty( "inbound_participant_sid" @@ -173,7 +173,7 @@ private MessageInteraction( @JsonProperty("inbound_resource_sid") final String inboundResourceSid, @JsonProperty( "inbound_resource_status" - ) final MessageInteraction.ResourceStatus inboundResourceStatus, + ) final ResourceStatus inboundResourceStatus, @JsonProperty("inbound_resource_type") final String inboundResourceType, @JsonProperty("inbound_resource_url") final URI inboundResourceUrl, @JsonProperty( @@ -182,7 +182,7 @@ private MessageInteraction( @JsonProperty("outbound_resource_sid") final String outboundResourceSid, @JsonProperty( "outbound_resource_status" - ) final MessageInteraction.ResourceStatus outboundResourceStatus, + ) final ResourceStatus outboundResourceStatus, @JsonProperty( "outbound_resource_type" ) final String outboundResourceType, @@ -233,7 +233,7 @@ public final String getData() { return this.data; } - public final MessageInteraction.Type getType() { + public final Type getType() { return this.type; } @@ -249,7 +249,7 @@ public final String getInboundResourceSid() { return this.inboundResourceSid; } - public final MessageInteraction.ResourceStatus getInboundResourceStatus() { + public final ResourceStatus getInboundResourceStatus() { return this.inboundResourceStatus; } @@ -269,7 +269,7 @@ public final String getOutboundResourceSid() { return this.outboundResourceSid; } - public final MessageInteraction.ResourceStatus getOutboundResourceStatus() { + public final ResourceStatus getOutboundResourceStatus() { return this.outboundResourceStatus; } diff --git a/src/main/java/com/twilio/rest/serverless/v1/service/Build.java b/src/main/java/com/twilio/rest/serverless/v1/service/Build.java index 30dfe72cf9..aefb0ce32d 100644 --- a/src/main/java/com/twilio/rest/serverless/v1/service/Build.java +++ b/src/main/java/com/twilio/rest/serverless/v1/service/Build.java @@ -110,11 +110,11 @@ public static Build fromJson( private final String sid; private final String accountSid; private final String serviceSid; - private final Build.Status status; + private final Status status; private final List> assetVersions; private final List> functionVersions; private final List> dependencies; - private final Build.Runtime runtime; + private final Runtime runtime; private final ZonedDateTime dateCreated; private final ZonedDateTime dateUpdated; private final URI url; @@ -125,7 +125,7 @@ private Build( @JsonProperty("sid") final String sid, @JsonProperty("account_sid") final String accountSid, @JsonProperty("service_sid") final String serviceSid, - @JsonProperty("status") final Build.Status status, + @JsonProperty("status") final Status status, @JsonProperty("asset_versions") final List< Map > assetVersions, @@ -135,7 +135,7 @@ private Build( @JsonProperty("dependencies") final List< Map > dependencies, - @JsonProperty("runtime") final Build.Runtime runtime, + @JsonProperty("runtime") final Runtime runtime, @JsonProperty("date_created") final String dateCreated, @JsonProperty("date_updated") final String dateUpdated, @JsonProperty("url") final URI url, @@ -167,7 +167,7 @@ public final String getServiceSid() { return this.serviceSid; } - public final Build.Status getStatus() { + public final Status getStatus() { return this.status; } @@ -183,7 +183,7 @@ public final List> getDependencies() { return this.dependencies; } - public final Build.Runtime getRuntime() { + public final Runtime getRuntime() { return this.runtime; } diff --git a/src/main/java/com/twilio/rest/serverless/v1/service/asset/AssetVersion.java b/src/main/java/com/twilio/rest/serverless/v1/service/asset/AssetVersion.java index a8cc25e5b0..42be38212b 100644 --- a/src/main/java/com/twilio/rest/serverless/v1/service/asset/AssetVersion.java +++ b/src/main/java/com/twilio/rest/serverless/v1/service/asset/AssetVersion.java @@ -102,7 +102,7 @@ public static AssetVersion fromJson( private final String serviceSid; private final String assetSid; private final String path; - private final AssetVersion.Visibility visibility; + private final Visibility visibility; private final ZonedDateTime dateCreated; private final URI url; @@ -113,7 +113,7 @@ private AssetVersion( @JsonProperty("service_sid") final String serviceSid, @JsonProperty("asset_sid") final String assetSid, @JsonProperty("path") final String path, - @JsonProperty("visibility") final AssetVersion.Visibility visibility, + @JsonProperty("visibility") final Visibility visibility, @JsonProperty("date_created") final String dateCreated, @JsonProperty("url") final URI url ) { @@ -147,7 +147,7 @@ public final String getPath() { return this.path; } - public final AssetVersion.Visibility getVisibility() { + public final Visibility getVisibility() { return this.visibility; } diff --git a/src/main/java/com/twilio/rest/serverless/v1/service/build/BuildStatus.java b/src/main/java/com/twilio/rest/serverless/v1/service/build/BuildStatus.java index f00e9175cb..583fcb0fab 100644 --- a/src/main/java/com/twilio/rest/serverless/v1/service/build/BuildStatus.java +++ b/src/main/java/com/twilio/rest/serverless/v1/service/build/BuildStatus.java @@ -90,7 +90,7 @@ public static BuildStatus fromJson( private final String sid; private final String accountSid; private final String serviceSid; - private final BuildStatus.Status status; + private final Status status; private final URI url; @JsonCreator @@ -98,7 +98,7 @@ private BuildStatus( @JsonProperty("sid") final String sid, @JsonProperty("account_sid") final String accountSid, @JsonProperty("service_sid") final String serviceSid, - @JsonProperty("status") final BuildStatus.Status status, + @JsonProperty("status") final Status status, @JsonProperty("url") final URI url ) { this.sid = sid; @@ -120,7 +120,7 @@ public final String getServiceSid() { return this.serviceSid; } - public final BuildStatus.Status getStatus() { + public final Status getStatus() { return this.status; } diff --git a/src/main/java/com/twilio/rest/serverless/v1/service/environment/Log.java b/src/main/java/com/twilio/rest/serverless/v1/service/environment/Log.java index f1a225ac49..72abb9f912 100644 --- a/src/main/java/com/twilio/rest/serverless/v1/service/environment/Log.java +++ b/src/main/java/com/twilio/rest/serverless/v1/service/environment/Log.java @@ -22,7 +22,6 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.converter.DateConverter; -import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import java.io.IOException; @@ -37,7 +36,7 @@ @ToString public class Log extends Resource { - private static final long serialVersionUID = 129897058125132L; + private static final long serialVersionUID = 41290346867159L; public static LogFetcher fetcher( final String pathServiceSid, @@ -105,7 +104,7 @@ public static Log fromJson( private final String deploymentSid; private final String functionSid; private final String requestSid; - private final Log.Level level; + private final String level; private final String message; private final ZonedDateTime dateCreated; private final URI url; @@ -120,7 +119,7 @@ private Log( @JsonProperty("deployment_sid") final String deploymentSid, @JsonProperty("function_sid") final String functionSid, @JsonProperty("request_sid") final String requestSid, - @JsonProperty("level") final Log.Level level, + @JsonProperty("level") final String level, @JsonProperty("message") final String message, @JsonProperty("date_created") final String dateCreated, @JsonProperty("url") final URI url @@ -171,7 +170,7 @@ public final String getRequestSid() { return this.requestSid; } - public final Log.Level getLevel() { + public final String getLevel() { return this.level; } @@ -232,25 +231,4 @@ public int hashCode() { url ); } - - public enum Level { - INFO("info"), - WARN("warn"), - ERROR("error"); - - private final String value; - - private Level(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static Level forValue(final String value) { - return Promoter.enumFromString(value, Level.values()); - } - } } diff --git a/src/main/java/com/twilio/rest/serverless/v1/service/function/FunctionVersion.java b/src/main/java/com/twilio/rest/serverless/v1/service/function/FunctionVersion.java index af9004b2c4..46b6d6388f 100644 --- a/src/main/java/com/twilio/rest/serverless/v1/service/function/FunctionVersion.java +++ b/src/main/java/com/twilio/rest/serverless/v1/service/function/FunctionVersion.java @@ -108,7 +108,7 @@ public static FunctionVersion fromJson( private final String serviceSid; private final String functionSid; private final String path; - private final FunctionVersion.Visibility visibility; + private final Visibility visibility; private final ZonedDateTime dateCreated; private final URI url; private final Map links; @@ -120,7 +120,7 @@ private FunctionVersion( @JsonProperty("service_sid") final String serviceSid, @JsonProperty("function_sid") final String functionSid, @JsonProperty("path") final String path, - @JsonProperty("visibility") final FunctionVersion.Visibility visibility, + @JsonProperty("visibility") final Visibility visibility, @JsonProperty("date_created") final String dateCreated, @JsonProperty("url") final URI url, @JsonProperty("links") final Map links @@ -156,7 +156,7 @@ public final String getPath() { return this.path; } - public final FunctionVersion.Visibility getVisibility() { + public final Visibility getVisibility() { return this.visibility; } diff --git a/src/main/java/com/twilio/rest/studio/v1/Flow.java b/src/main/java/com/twilio/rest/studio/v1/Flow.java index e54921d904..6a84d3a01b 100644 --- a/src/main/java/com/twilio/rest/studio/v1/Flow.java +++ b/src/main/java/com/twilio/rest/studio/v1/Flow.java @@ -99,7 +99,7 @@ public static Flow fromJson( private final String sid; private final String accountSid; private final String friendlyName; - private final Flow.Status status; + private final Status status; private final Integer version; private final ZonedDateTime dateCreated; private final ZonedDateTime dateUpdated; @@ -111,7 +111,7 @@ private Flow( @JsonProperty("sid") final String sid, @JsonProperty("account_sid") final String accountSid, @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("status") final Flow.Status status, + @JsonProperty("status") final Status status, @JsonProperty("version") final Integer version, @JsonProperty("date_created") final String dateCreated, @JsonProperty("date_updated") final String dateUpdated, @@ -141,7 +141,7 @@ public final String getFriendlyName() { return this.friendlyName; } - public final Flow.Status getStatus() { + public final Status getStatus() { return this.status; } diff --git a/src/main/java/com/twilio/rest/studio/v1/flow/Engagement.java b/src/main/java/com/twilio/rest/studio/v1/flow/Engagement.java index 1b5c29b55b..99e517ac68 100644 --- a/src/main/java/com/twilio/rest/studio/v1/flow/Engagement.java +++ b/src/main/java/com/twilio/rest/studio/v1/flow/Engagement.java @@ -116,7 +116,7 @@ public static Engagement fromJson( private final String contactSid; private final String contactChannelAddress; private final Map context; - private final Engagement.Status status; + private final Status status; private final ZonedDateTime dateCreated; private final ZonedDateTime dateUpdated; private final URI url; @@ -132,7 +132,7 @@ private Engagement( "contact_channel_address" ) final String contactChannelAddress, @JsonProperty("context") final Map context, - @JsonProperty("status") final Engagement.Status status, + @JsonProperty("status") final Status status, @JsonProperty("date_created") final String dateCreated, @JsonProperty("date_updated") final String dateUpdated, @JsonProperty("url") final URI url, @@ -175,7 +175,7 @@ public final Map getContext() { return this.context; } - public final Engagement.Status getStatus() { + public final Status getStatus() { return this.status; } diff --git a/src/main/java/com/twilio/rest/studio/v1/flow/EngagementCreator.java b/src/main/java/com/twilio/rest/studio/v1/flow/EngagementCreator.java index cbd788a972..65b09c1a3c 100644 --- a/src/main/java/com/twilio/rest/studio/v1/flow/EngagementCreator.java +++ b/src/main/java/com/twilio/rest/studio/v1/flow/EngagementCreator.java @@ -27,15 +27,13 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -import java.util.Map; -import java.util.Map; public class EngagementCreator extends Creator { private String pathFlowSid; private com.twilio.type.PhoneNumber to; private com.twilio.type.PhoneNumber from; - private Map parameters; + private Object parameters; public EngagementCreator( final String pathFlowSid, @@ -65,9 +63,7 @@ public EngagementCreator setFrom(final String from) { return setFrom(Promoter.phoneNumberFromString(from)); } - public EngagementCreator setParameters( - final Map parameters - ) { + public EngagementCreator setParameters(final Object parameters) { this.parameters = parameters; return this; } @@ -77,8 +73,8 @@ public Engagement create(final TwilioRestClient client) { String path = "/v1/Flows/{FlowSid}/Engagements"; path = path.replace("{" + "FlowSid" + "}", this.pathFlowSid.toString()); - path = path.replace("{" + "To" + "}", this.to.encode("utf-8")); - path = path.replace("{" + "From" + "}", this.from.encode("utf-8")); + path = path.replace("{" + "To" + "}", this.to.toString()); + path = path.replace("{" + "From" + "}", this.from.toString()); Request request = new Request( HttpMethod.POST, @@ -120,7 +116,10 @@ private void addPostParams(final Request request) { request.addPostParam("From", from.toString()); } if (parameters != null) { - request.addPostParam("Parameters", Converter.mapToJson(parameters)); + request.addPostParam( + "Parameters", + Converter.objectToJson(parameters) + ); } } } diff --git a/src/main/java/com/twilio/rest/studio/v1/flow/Execution.java b/src/main/java/com/twilio/rest/studio/v1/flow/Execution.java index 7806f0e36d..a79863d930 100644 --- a/src/main/java/com/twilio/rest/studio/v1/flow/Execution.java +++ b/src/main/java/com/twilio/rest/studio/v1/flow/Execution.java @@ -70,7 +70,7 @@ public static ExecutionReader reader(final String pathFlowSid) { public static ExecutionUpdater updater( final String pathFlowSid, final String pathSid, - final Execution.Status status + final Status status ) { return new ExecutionUpdater(pathFlowSid, pathSid, status); } @@ -124,7 +124,7 @@ public static Execution fromJson( private final String contactSid; private final String contactChannelAddress; private final Map context; - private final Execution.Status status; + private final Status status; private final ZonedDateTime dateCreated; private final ZonedDateTime dateUpdated; private final URI url; @@ -140,7 +140,7 @@ private Execution( "contact_channel_address" ) final String contactChannelAddress, @JsonProperty("context") final Map context, - @JsonProperty("status") final Execution.Status status, + @JsonProperty("status") final Status status, @JsonProperty("date_created") final String dateCreated, @JsonProperty("date_updated") final String dateUpdated, @JsonProperty("url") final URI url, @@ -183,7 +183,7 @@ public final Map getContext() { return this.context; } - public final Execution.Status getStatus() { + public final Status getStatus() { return this.status; } diff --git a/src/main/java/com/twilio/rest/studio/v1/flow/ExecutionCreator.java b/src/main/java/com/twilio/rest/studio/v1/flow/ExecutionCreator.java index 89c8f288e0..bdc96dd0a3 100644 --- a/src/main/java/com/twilio/rest/studio/v1/flow/ExecutionCreator.java +++ b/src/main/java/com/twilio/rest/studio/v1/flow/ExecutionCreator.java @@ -27,15 +27,13 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -import java.util.Map; -import java.util.Map; public class ExecutionCreator extends Creator { private String pathFlowSid; private com.twilio.type.PhoneNumber to; private com.twilio.type.PhoneNumber from; - private Map parameters; + private Object parameters; public ExecutionCreator( final String pathFlowSid, @@ -65,9 +63,7 @@ public ExecutionCreator setFrom(final String from) { return setFrom(Promoter.phoneNumberFromString(from)); } - public ExecutionCreator setParameters( - final Map parameters - ) { + public ExecutionCreator setParameters(final Object parameters) { this.parameters = parameters; return this; } @@ -77,8 +73,8 @@ public Execution create(final TwilioRestClient client) { String path = "/v1/Flows/{FlowSid}/Executions"; path = path.replace("{" + "FlowSid" + "}", this.pathFlowSid.toString()); - path = path.replace("{" + "To" + "}", this.to.encode("utf-8")); - path = path.replace("{" + "From" + "}", this.from.encode("utf-8")); + path = path.replace("{" + "To" + "}", this.to.toString()); + path = path.replace("{" + "From" + "}", this.from.toString()); Request request = new Request( HttpMethod.POST, @@ -120,7 +116,10 @@ private void addPostParams(final Request request) { request.addPostParam("From", from.toString()); } if (parameters != null) { - request.addPostParam("Parameters", Converter.mapToJson(parameters)); + request.addPostParam( + "Parameters", + Converter.objectToJson(parameters) + ); } } } diff --git a/src/main/java/com/twilio/rest/studio/v2/Flow.java b/src/main/java/com/twilio/rest/studio/v2/Flow.java index f4f9f13fbf..7677d433dd 100644 --- a/src/main/java/com/twilio/rest/studio/v2/Flow.java +++ b/src/main/java/com/twilio/rest/studio/v2/Flow.java @@ -44,8 +44,8 @@ public class Flow extends Resource { public static FlowCreator creator( final String friendlyName, - final Flow.Status status, - final Map definition + final Status status, + final Object definition ) { return new FlowCreator(friendlyName, status, definition); } @@ -64,7 +64,7 @@ public static FlowReader reader() { public static FlowUpdater updater( final String pathSid, - final Flow.Status status + final Status status ) { return new FlowUpdater(pathSid, status); } @@ -116,7 +116,7 @@ public static Flow fromJson( private final String accountSid; private final String friendlyName; private final Map definition; - private final Flow.Status status; + private final Status status; private final Integer revision; private final String commitMessage; private final Boolean valid; @@ -134,7 +134,7 @@ private Flow( @JsonProperty("account_sid") final String accountSid, @JsonProperty("friendly_name") final String friendlyName, @JsonProperty("definition") final Map definition, - @JsonProperty("status") final Flow.Status status, + @JsonProperty("status") final Status status, @JsonProperty("revision") final Integer revision, @JsonProperty("commit_message") final String commitMessage, @JsonProperty("valid") final Boolean valid, @@ -179,7 +179,7 @@ public final Map getDefinition() { return this.definition; } - public final Flow.Status getStatus() { + public final Status getStatus() { return this.status; } diff --git a/src/main/java/com/twilio/rest/studio/v2/FlowCreator.java b/src/main/java/com/twilio/rest/studio/v2/FlowCreator.java index 3834351da1..9ae445c987 100644 --- a/src/main/java/com/twilio/rest/studio/v2/FlowCreator.java +++ b/src/main/java/com/twilio/rest/studio/v2/FlowCreator.java @@ -26,20 +26,18 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -import java.util.Map; -import java.util.Map; public class FlowCreator extends Creator { private String friendlyName; private Flow.Status status; - private Map definition; + private Object definition; private String commitMessage; public FlowCreator( final String friendlyName, final Flow.Status status, - final Map definition + final Object definition ) { this.friendlyName = friendlyName; this.status = status; @@ -56,7 +54,7 @@ public FlowCreator setStatus(final Flow.Status status) { return this; } - public FlowCreator setDefinition(final Map definition) { + public FlowCreator setDefinition(final Object definition) { this.definition = definition; return this; } @@ -116,7 +114,10 @@ private void addPostParams(final Request request) { request.addPostParam("Status", status.toString()); } if (definition != null) { - request.addPostParam("Definition", Converter.mapToJson(definition)); + request.addPostParam( + "Definition", + Converter.objectToJson(definition) + ); } if (commitMessage != null) { request.addPostParam("CommitMessage", commitMessage); diff --git a/src/main/java/com/twilio/rest/studio/v2/FlowUpdater.java b/src/main/java/com/twilio/rest/studio/v2/FlowUpdater.java index 981e21f24e..6d625f2a21 100644 --- a/src/main/java/com/twilio/rest/studio/v2/FlowUpdater.java +++ b/src/main/java/com/twilio/rest/studio/v2/FlowUpdater.java @@ -25,14 +25,13 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -import java.util.Map; public class FlowUpdater extends Updater { private String pathSid; private Flow.Status status; private String friendlyName; - private Map definition; + private Object definition; private String commitMessage; public FlowUpdater(final String pathSid, final Flow.Status status) { @@ -50,7 +49,7 @@ public FlowUpdater setFriendlyName(final String friendlyName) { return this; } - public FlowUpdater setDefinition(final Map definition) { + public FlowUpdater setDefinition(final Object definition) { this.definition = definition; return this; } @@ -104,7 +103,10 @@ private void addPostParams(final Request request) { request.addPostParam("FriendlyName", friendlyName); } if (definition != null) { - request.addPostParam("Definition", Converter.mapToJson(definition)); + request.addPostParam( + "Definition", + Converter.objectToJson(definition) + ); } if (commitMessage != null) { request.addPostParam("CommitMessage", commitMessage); diff --git a/src/main/java/com/twilio/rest/studio/v2/FlowValidate.java b/src/main/java/com/twilio/rest/studio/v2/FlowValidate.java index f3a156394a..1024e89519 100644 --- a/src/main/java/com/twilio/rest/studio/v2/FlowValidate.java +++ b/src/main/java/com/twilio/rest/studio/v2/FlowValidate.java @@ -26,8 +26,6 @@ import com.twilio.exception.ApiException; import java.io.IOException; import java.io.InputStream; -import java.util.Map; -import java.util.Map; import java.util.Objects; import lombok.ToString; import lombok.ToString; @@ -40,8 +38,8 @@ public class FlowValidate extends Resource { public static FlowValidateUpdater updater( final String friendlyName, - final FlowValidate.Status status, - final Map definition + final Status status, + final Object definition ) { return new FlowValidateUpdater(friendlyName, status, definition); } diff --git a/src/main/java/com/twilio/rest/studio/v2/FlowValidateUpdater.java b/src/main/java/com/twilio/rest/studio/v2/FlowValidateUpdater.java index 7c97916960..954245fd2a 100644 --- a/src/main/java/com/twilio/rest/studio/v2/FlowValidateUpdater.java +++ b/src/main/java/com/twilio/rest/studio/v2/FlowValidateUpdater.java @@ -25,19 +25,18 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -import java.util.Map; public class FlowValidateUpdater extends Updater { private String friendlyName; private FlowValidate.Status status; - private Map definition; + private Object definition; private String commitMessage; public FlowValidateUpdater( final String friendlyName, final FlowValidate.Status status, - final Map definition + final Object definition ) { this.friendlyName = friendlyName; this.status = status; @@ -54,9 +53,7 @@ public FlowValidateUpdater setStatus(final FlowValidate.Status status) { return this; } - public FlowValidateUpdater setDefinition( - final Map definition - ) { + public FlowValidateUpdater setDefinition(final Object definition) { this.definition = definition; return this; } @@ -119,7 +116,10 @@ private void addPostParams(final Request request) { request.addPostParam("Status", status.toString()); } if (definition != null) { - request.addPostParam("Definition", Converter.mapToJson(definition)); + request.addPostParam( + "Definition", + Converter.objectToJson(definition) + ); } if (commitMessage != null) { request.addPostParam("CommitMessage", commitMessage); diff --git a/src/main/java/com/twilio/rest/studio/v2/flow/Execution.java b/src/main/java/com/twilio/rest/studio/v2/flow/Execution.java index a39e679402..be8fa736c7 100644 --- a/src/main/java/com/twilio/rest/studio/v2/flow/Execution.java +++ b/src/main/java/com/twilio/rest/studio/v2/flow/Execution.java @@ -70,7 +70,7 @@ public static ExecutionReader reader(final String pathFlowSid) { public static ExecutionUpdater updater( final String pathFlowSid, final String pathSid, - final Execution.Status status + final Status status ) { return new ExecutionUpdater(pathFlowSid, pathSid, status); } @@ -123,7 +123,7 @@ public static Execution fromJson( private final String flowSid; private final String contactChannelAddress; private final Map context; - private final Execution.Status status; + private final Status status; private final ZonedDateTime dateCreated; private final ZonedDateTime dateUpdated; private final URI url; @@ -138,7 +138,7 @@ private Execution( "contact_channel_address" ) final String contactChannelAddress, @JsonProperty("context") final Map context, - @JsonProperty("status") final Execution.Status status, + @JsonProperty("status") final Status status, @JsonProperty("date_created") final String dateCreated, @JsonProperty("date_updated") final String dateUpdated, @JsonProperty("url") final URI url, @@ -176,7 +176,7 @@ public final Map getContext() { return this.context; } - public final Execution.Status getStatus() { + public final Status getStatus() { return this.status; } diff --git a/src/main/java/com/twilio/rest/studio/v2/flow/ExecutionCreator.java b/src/main/java/com/twilio/rest/studio/v2/flow/ExecutionCreator.java index df3d5c1245..df95407644 100644 --- a/src/main/java/com/twilio/rest/studio/v2/flow/ExecutionCreator.java +++ b/src/main/java/com/twilio/rest/studio/v2/flow/ExecutionCreator.java @@ -27,15 +27,13 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -import java.util.Map; -import java.util.Map; public class ExecutionCreator extends Creator { private String pathFlowSid; private com.twilio.type.PhoneNumber to; private com.twilio.type.PhoneNumber from; - private Map parameters; + private Object parameters; public ExecutionCreator( final String pathFlowSid, @@ -65,9 +63,7 @@ public ExecutionCreator setFrom(final String from) { return setFrom(Promoter.phoneNumberFromString(from)); } - public ExecutionCreator setParameters( - final Map parameters - ) { + public ExecutionCreator setParameters(final Object parameters) { this.parameters = parameters; return this; } @@ -77,8 +73,8 @@ public Execution create(final TwilioRestClient client) { String path = "/v2/Flows/{FlowSid}/Executions"; path = path.replace("{" + "FlowSid" + "}", this.pathFlowSid.toString()); - path = path.replace("{" + "To" + "}", this.to.encode("utf-8")); - path = path.replace("{" + "From" + "}", this.from.encode("utf-8")); + path = path.replace("{" + "To" + "}", this.to.toString()); + path = path.replace("{" + "From" + "}", this.from.toString()); Request request = new Request( HttpMethod.POST, @@ -120,7 +116,10 @@ private void addPostParams(final Request request) { request.addPostParam("From", from.toString()); } if (parameters != null) { - request.addPostParam("Parameters", Converter.mapToJson(parameters)); + request.addPostParam( + "Parameters", + Converter.objectToJson(parameters) + ); } } } diff --git a/src/main/java/com/twilio/rest/studio/v2/flow/FlowRevision.java b/src/main/java/com/twilio/rest/studio/v2/flow/FlowRevision.java index c92a4d7238..852a110e87 100644 --- a/src/main/java/com/twilio/rest/studio/v2/flow/FlowRevision.java +++ b/src/main/java/com/twilio/rest/studio/v2/flow/FlowRevision.java @@ -100,7 +100,7 @@ public static FlowRevision fromJson( private final String accountSid; private final String friendlyName; private final Map definition; - private final FlowRevision.Status status; + private final Status status; private final Integer revision; private final String commitMessage; private final Boolean valid; @@ -115,7 +115,7 @@ private FlowRevision( @JsonProperty("account_sid") final String accountSid, @JsonProperty("friendly_name") final String friendlyName, @JsonProperty("definition") final Map definition, - @JsonProperty("status") final FlowRevision.Status status, + @JsonProperty("status") final Status status, @JsonProperty("revision") final Integer revision, @JsonProperty("commit_message") final String commitMessage, @JsonProperty("valid") final Boolean valid, @@ -154,7 +154,7 @@ public final Map getDefinition() { return this.definition; } - public final FlowRevision.Status getStatus() { + public final Status getStatus() { return this.status; } diff --git a/src/main/java/com/twilio/rest/supersim/v1/EsimProfile.java b/src/main/java/com/twilio/rest/supersim/v1/EsimProfile.java index 5d3e1b08eb..311216484a 100644 --- a/src/main/java/com/twilio/rest/supersim/v1/EsimProfile.java +++ b/src/main/java/com/twilio/rest/supersim/v1/EsimProfile.java @@ -98,7 +98,7 @@ public static EsimProfile fromJson( private final String accountSid; private final String iccid; private final String simSid; - private final EsimProfile.Status status; + private final Status status; private final String eid; private final URI smdpPlusAddress; private final String matchingId; @@ -115,7 +115,7 @@ private EsimProfile( @JsonProperty("account_sid") final String accountSid, @JsonProperty("iccid") final String iccid, @JsonProperty("sim_sid") final String simSid, - @JsonProperty("status") final EsimProfile.Status status, + @JsonProperty("status") final Status status, @JsonProperty("eid") final String eid, @JsonProperty("smdp_plus_address") final URI smdpPlusAddress, @JsonProperty("matching_id") final String matchingId, @@ -158,7 +158,7 @@ public final String getSimSid() { return this.simSid; } - public final EsimProfile.Status getStatus() { + public final Status getStatus() { return this.status; } diff --git a/src/main/java/com/twilio/rest/supersim/v1/Fleet.java b/src/main/java/com/twilio/rest/supersim/v1/Fleet.java index 19c54502b2..2b9adfe683 100644 --- a/src/main/java/com/twilio/rest/supersim/v1/Fleet.java +++ b/src/main/java/com/twilio/rest/supersim/v1/Fleet.java @@ -107,7 +107,7 @@ public static Fleet fromJson( private final URI url; private final Boolean dataEnabled; private final Integer dataLimit; - private final Fleet.DataMetering dataMetering; + private final DataMetering dataMetering; private final Boolean smsCommandsEnabled; private final URI smsCommandsUrl; private final HttpMethod smsCommandsMethod; @@ -125,7 +125,7 @@ private Fleet( @JsonProperty("url") final URI url, @JsonProperty("data_enabled") final Boolean dataEnabled, @JsonProperty("data_limit") final Integer dataLimit, - @JsonProperty("data_metering") final Fleet.DataMetering dataMetering, + @JsonProperty("data_metering") final DataMetering dataMetering, @JsonProperty("sms_commands_enabled") final Boolean smsCommandsEnabled, @JsonProperty("sms_commands_url") final URI smsCommandsUrl, @JsonProperty("sms_commands_method") final HttpMethod smsCommandsMethod, @@ -184,7 +184,7 @@ public final Integer getDataLimit() { return this.dataLimit; } - public final Fleet.DataMetering getDataMetering() { + public final DataMetering getDataMetering() { return this.dataMetering; } diff --git a/src/main/java/com/twilio/rest/supersim/v1/IpCommand.java b/src/main/java/com/twilio/rest/supersim/v1/IpCommand.java index da34f019a3..aedeae6f5e 100644 --- a/src/main/java/com/twilio/rest/supersim/v1/IpCommand.java +++ b/src/main/java/com/twilio/rest/supersim/v1/IpCommand.java @@ -102,11 +102,11 @@ public static IpCommand fromJson( private final String accountSid; private final String simSid; private final String simIccid; - private final IpCommand.Status status; - private final IpCommand.Direction direction; + private final Status status; + private final Direction direction; private final String deviceIp; private final Integer devicePort; - private final IpCommand.PayloadType payloadType; + private final PayloadType payloadType; private final String payload; private final ZonedDateTime dateCreated; private final ZonedDateTime dateUpdated; @@ -118,11 +118,11 @@ private IpCommand( @JsonProperty("account_sid") final String accountSid, @JsonProperty("sim_sid") final String simSid, @JsonProperty("sim_iccid") final String simIccid, - @JsonProperty("status") final IpCommand.Status status, - @JsonProperty("direction") final IpCommand.Direction direction, + @JsonProperty("status") final Status status, + @JsonProperty("direction") final Direction direction, @JsonProperty("device_ip") final String deviceIp, @JsonProperty("device_port") final Integer devicePort, - @JsonProperty("payload_type") final IpCommand.PayloadType payloadType, + @JsonProperty("payload_type") final PayloadType payloadType, @JsonProperty("payload") final String payload, @JsonProperty("date_created") final String dateCreated, @JsonProperty("date_updated") final String dateUpdated, @@ -159,11 +159,11 @@ public final String getSimIccid() { return this.simIccid; } - public final IpCommand.Status getStatus() { + public final Status getStatus() { return this.status; } - public final IpCommand.Direction getDirection() { + public final Direction getDirection() { return this.direction; } @@ -175,7 +175,7 @@ public final Integer getDevicePort() { return this.devicePort; } - public final IpCommand.PayloadType getPayloadType() { + public final PayloadType getPayloadType() { return this.payloadType; } diff --git a/src/main/java/com/twilio/rest/supersim/v1/SettingsUpdate.java b/src/main/java/com/twilio/rest/supersim/v1/SettingsUpdate.java index 4d3dbc2f17..05a18f96f5 100644 --- a/src/main/java/com/twilio/rest/supersim/v1/SettingsUpdate.java +++ b/src/main/java/com/twilio/rest/supersim/v1/SettingsUpdate.java @@ -91,7 +91,7 @@ public static SettingsUpdate fromJson( private final String sid; private final String iccid; private final String simSid; - private final SettingsUpdate.Status status; + private final Status status; private final List> packages; private final ZonedDateTime dateCompleted; private final ZonedDateTime dateCreated; @@ -102,7 +102,7 @@ private SettingsUpdate( @JsonProperty("sid") final String sid, @JsonProperty("iccid") final String iccid, @JsonProperty("sim_sid") final String simSid, - @JsonProperty("status") final SettingsUpdate.Status status, + @JsonProperty("status") final Status status, @JsonProperty("packages") final List> packages, @JsonProperty("date_completed") final String dateCompleted, @JsonProperty("date_created") final String dateCreated, @@ -131,7 +131,7 @@ public final String getSimSid() { return this.simSid; } - public final SettingsUpdate.Status getStatus() { + public final Status getStatus() { return this.status; } diff --git a/src/main/java/com/twilio/rest/supersim/v1/Sim.java b/src/main/java/com/twilio/rest/supersim/v1/Sim.java index 072e1815fb..2829cf05ba 100644 --- a/src/main/java/com/twilio/rest/supersim/v1/Sim.java +++ b/src/main/java/com/twilio/rest/supersim/v1/Sim.java @@ -107,7 +107,7 @@ public static Sim fromJson( private final String uniqueName; private final String accountSid; private final String iccid; - private final Sim.Status status; + private final Status status; private final String fleetSid; private final ZonedDateTime dateCreated; private final ZonedDateTime dateUpdated; @@ -120,7 +120,7 @@ private Sim( @JsonProperty("unique_name") final String uniqueName, @JsonProperty("account_sid") final String accountSid, @JsonProperty("iccid") final String iccid, - @JsonProperty("status") final Sim.Status status, + @JsonProperty("status") final Status status, @JsonProperty("fleet_sid") final String fleetSid, @JsonProperty("date_created") final String dateCreated, @JsonProperty("date_updated") final String dateUpdated, @@ -155,7 +155,7 @@ public final String getIccid() { return this.iccid; } - public final Sim.Status getStatus() { + public final Status getStatus() { return this.status; } diff --git a/src/main/java/com/twilio/rest/supersim/v1/SmsCommand.java b/src/main/java/com/twilio/rest/supersim/v1/SmsCommand.java index ab1c698aa7..6e22dd0e57 100644 --- a/src/main/java/com/twilio/rest/supersim/v1/SmsCommand.java +++ b/src/main/java/com/twilio/rest/supersim/v1/SmsCommand.java @@ -101,8 +101,8 @@ public static SmsCommand fromJson( private final String accountSid; private final String simSid; private final String payload; - private final SmsCommand.Status status; - private final SmsCommand.Direction direction; + private final Status status; + private final Direction direction; private final ZonedDateTime dateCreated; private final ZonedDateTime dateUpdated; private final URI url; @@ -113,8 +113,8 @@ private SmsCommand( @JsonProperty("account_sid") final String accountSid, @JsonProperty("sim_sid") final String simSid, @JsonProperty("payload") final String payload, - @JsonProperty("status") final SmsCommand.Status status, - @JsonProperty("direction") final SmsCommand.Direction direction, + @JsonProperty("status") final Status status, + @JsonProperty("direction") final Direction direction, @JsonProperty("date_created") final String dateCreated, @JsonProperty("date_updated") final String dateUpdated, @JsonProperty("url") final URI url @@ -146,11 +146,11 @@ public final String getPayload() { return this.payload; } - public final SmsCommand.Status getStatus() { + public final Status getStatus() { return this.status; } - public final SmsCommand.Direction getDirection() { + public final Direction getDirection() { return this.direction; } diff --git a/src/main/java/com/twilio/rest/supersim/v1/UsageRecord.java b/src/main/java/com/twilio/rest/supersim/v1/UsageRecord.java index 2b7510e170..dd18ce4249 100644 --- a/src/main/java/com/twilio/rest/supersim/v1/UsageRecord.java +++ b/src/main/java/com/twilio/rest/supersim/v1/UsageRecord.java @@ -114,7 +114,7 @@ private UsageRecord( @JsonProperty("data_total") final Long dataTotal, @JsonProperty("data_total_billed") final BigDecimal dataTotalBilled, @JsonProperty("billed_unit") @JsonDeserialize( - using = com.twilio.converter.CurrencyDeserializer.class + using = CurrencyDeserializer.class ) final Currency billedUnit ) { this.accountSid = accountSid; diff --git a/src/main/java/com/twilio/rest/supersim/v1/sim/BillingPeriod.java b/src/main/java/com/twilio/rest/supersim/v1/sim/BillingPeriod.java index d73822c5b7..2cd6b48046 100644 --- a/src/main/java/com/twilio/rest/supersim/v1/sim/BillingPeriod.java +++ b/src/main/java/com/twilio/rest/supersim/v1/sim/BillingPeriod.java @@ -90,7 +90,7 @@ public static BillingPeriod fromJson( private final String simSid; private final ZonedDateTime startTime; private final ZonedDateTime endTime; - private final BillingPeriod.BpType periodType; + private final BpType periodType; private final ZonedDateTime dateCreated; private final ZonedDateTime dateUpdated; @@ -101,7 +101,7 @@ private BillingPeriod( @JsonProperty("sim_sid") final String simSid, @JsonProperty("start_time") final String startTime, @JsonProperty("end_time") final String endTime, - @JsonProperty("period_type") final BillingPeriod.BpType periodType, + @JsonProperty("period_type") final BpType periodType, @JsonProperty("date_created") final String dateCreated, @JsonProperty("date_updated") final String dateUpdated ) { @@ -135,7 +135,7 @@ public final ZonedDateTime getEndTime() { return this.endTime; } - public final BillingPeriod.BpType getPeriodType() { + public final BpType getPeriodType() { return this.periodType; } diff --git a/src/main/java/com/twilio/rest/supersim/v1/sim/SimIpAddress.java b/src/main/java/com/twilio/rest/supersim/v1/sim/SimIpAddress.java index 2983f71ba4..88f3361ac7 100644 --- a/src/main/java/com/twilio/rest/supersim/v1/sim/SimIpAddress.java +++ b/src/main/java/com/twilio/rest/supersim/v1/sim/SimIpAddress.java @@ -84,14 +84,14 @@ public static SimIpAddress fromJson( } private final String ipAddress; - private final SimIpAddress.IpAddressVersion ipAddressVersion; + private final IpAddressVersion ipAddressVersion; @JsonCreator private SimIpAddress( @JsonProperty("ip_address") final String ipAddress, @JsonProperty( "ip_address_version" - ) final SimIpAddress.IpAddressVersion ipAddressVersion + ) final IpAddressVersion ipAddressVersion ) { this.ipAddress = ipAddress; this.ipAddressVersion = ipAddressVersion; @@ -101,7 +101,7 @@ public final String getIpAddress() { return this.ipAddress; } - public final SimIpAddress.IpAddressVersion getIpAddressVersion() { + public final IpAddressVersion getIpAddressVersion() { return this.ipAddressVersion; } diff --git a/src/main/java/com/twilio/rest/sync/v1/service/DocumentCreator.java b/src/main/java/com/twilio/rest/sync/v1/service/DocumentCreator.java index 9b5eca36b7..3ad46deab0 100644 --- a/src/main/java/com/twilio/rest/sync/v1/service/DocumentCreator.java +++ b/src/main/java/com/twilio/rest/sync/v1/service/DocumentCreator.java @@ -26,14 +26,12 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -import java.util.Map; -import java.util.Map; public class DocumentCreator extends Creator { private String pathServiceSid; private String uniqueName; - private Map data; + private Object data; private Integer ttl; public DocumentCreator(final String pathServiceSid) { @@ -45,7 +43,7 @@ public DocumentCreator setUniqueName(final String uniqueName) { return this; } - public DocumentCreator setData(final Map data) { + public DocumentCreator setData(final Object data) { this.data = data; return this; } @@ -102,7 +100,7 @@ private void addPostParams(final Request request) { request.addPostParam("UniqueName", uniqueName); } if (data != null) { - request.addPostParam("Data", Converter.mapToJson(data)); + request.addPostParam("Data", Converter.objectToJson(data)); } if (ttl != null) { request.addPostParam("Ttl", ttl.toString()); diff --git a/src/main/java/com/twilio/rest/sync/v1/service/DocumentUpdater.java b/src/main/java/com/twilio/rest/sync/v1/service/DocumentUpdater.java index 1561d4c8a2..8c4bb058d5 100644 --- a/src/main/java/com/twilio/rest/sync/v1/service/DocumentUpdater.java +++ b/src/main/java/com/twilio/rest/sync/v1/service/DocumentUpdater.java @@ -25,14 +25,13 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -import java.util.Map; public class DocumentUpdater extends Updater { private String pathServiceSid; private String pathSid; private String ifMatch; - private Map data; + private Object data; private Integer ttl; public DocumentUpdater(final String pathServiceSid, final String pathSid) { @@ -45,7 +44,7 @@ public DocumentUpdater setIfMatch(final String ifMatch) { return this; } - public DocumentUpdater setData(final Map data) { + public DocumentUpdater setData(final Object data) { this.data = data; return this; } @@ -101,7 +100,7 @@ public Document update(final TwilioRestClient client) { private void addPostParams(final Request request) { if (data != null) { - request.addPostParam("Data", Converter.mapToJson(data)); + request.addPostParam("Data", Converter.objectToJson(data)); } if (ttl != null) { request.addPostParam("Ttl", ttl.toString()); diff --git a/src/main/java/com/twilio/rest/sync/v1/service/synclist/SyncListItem.java b/src/main/java/com/twilio/rest/sync/v1/service/synclist/SyncListItem.java index c0d70df086..00bbcafebd 100644 --- a/src/main/java/com/twilio/rest/sync/v1/service/synclist/SyncListItem.java +++ b/src/main/java/com/twilio/rest/sync/v1/service/synclist/SyncListItem.java @@ -44,7 +44,7 @@ public class SyncListItem extends Resource { public static SyncListItemCreator creator( final String pathServiceSid, final String pathListSid, - final Map data + final Object data ) { return new SyncListItemCreator(pathServiceSid, pathListSid, data); } diff --git a/src/main/java/com/twilio/rest/sync/v1/service/synclist/SyncListItemCreator.java b/src/main/java/com/twilio/rest/sync/v1/service/synclist/SyncListItemCreator.java index 2af4101ee6..4d8ac8f192 100644 --- a/src/main/java/com/twilio/rest/sync/v1/service/synclist/SyncListItemCreator.java +++ b/src/main/java/com/twilio/rest/sync/v1/service/synclist/SyncListItemCreator.java @@ -26,14 +26,12 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -import java.util.Map; -import java.util.Map; public class SyncListItemCreator extends Creator { private String pathServiceSid; private String pathListSid; - private Map data; + private Object data; private Integer ttl; private Integer itemTtl; private Integer collectionTtl; @@ -41,14 +39,14 @@ public class SyncListItemCreator extends Creator { public SyncListItemCreator( final String pathServiceSid, final String pathListSid, - final Map data + final Object data ) { this.pathServiceSid = pathServiceSid; this.pathListSid = pathListSid; this.data = data; } - public SyncListItemCreator setData(final Map data) { + public SyncListItemCreator setData(final Object data) { this.data = data; return this; } @@ -114,7 +112,7 @@ public SyncListItem create(final TwilioRestClient client) { private void addPostParams(final Request request) { if (data != null) { - request.addPostParam("Data", Converter.mapToJson(data)); + request.addPostParam("Data", Converter.objectToJson(data)); } if (ttl != null) { request.addPostParam("Ttl", ttl.toString()); diff --git a/src/main/java/com/twilio/rest/sync/v1/service/synclist/SyncListItemUpdater.java b/src/main/java/com/twilio/rest/sync/v1/service/synclist/SyncListItemUpdater.java index df538d9384..24dde562ca 100644 --- a/src/main/java/com/twilio/rest/sync/v1/service/synclist/SyncListItemUpdater.java +++ b/src/main/java/com/twilio/rest/sync/v1/service/synclist/SyncListItemUpdater.java @@ -25,7 +25,6 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -import java.util.Map; public class SyncListItemUpdater extends Updater { @@ -33,7 +32,7 @@ public class SyncListItemUpdater extends Updater { private String pathListSid; private Integer pathIndex; private String ifMatch; - private Map data; + private Object data; private Integer ttl; private Integer itemTtl; private Integer collectionTtl; @@ -53,7 +52,7 @@ public SyncListItemUpdater setIfMatch(final String ifMatch) { return this; } - public SyncListItemUpdater setData(final Map data) { + public SyncListItemUpdater setData(final Object data) { this.data = data; return this; } @@ -120,7 +119,7 @@ public SyncListItem update(final TwilioRestClient client) { private void addPostParams(final Request request) { if (data != null) { - request.addPostParam("Data", Converter.mapToJson(data)); + request.addPostParam("Data", Converter.objectToJson(data)); } if (ttl != null) { request.addPostParam("Ttl", ttl.toString()); diff --git a/src/main/java/com/twilio/rest/sync/v1/service/syncmap/SyncMapItem.java b/src/main/java/com/twilio/rest/sync/v1/service/syncmap/SyncMapItem.java index e2c25935cf..f134d6fb0c 100644 --- a/src/main/java/com/twilio/rest/sync/v1/service/syncmap/SyncMapItem.java +++ b/src/main/java/com/twilio/rest/sync/v1/service/syncmap/SyncMapItem.java @@ -45,7 +45,7 @@ public static SyncMapItemCreator creator( final String pathServiceSid, final String pathMapSid, final String key, - final Map data + final Object data ) { return new SyncMapItemCreator(pathServiceSid, pathMapSid, key, data); } diff --git a/src/main/java/com/twilio/rest/sync/v1/service/syncmap/SyncMapItemCreator.java b/src/main/java/com/twilio/rest/sync/v1/service/syncmap/SyncMapItemCreator.java index 095e615ca2..c85bdbfeb9 100644 --- a/src/main/java/com/twilio/rest/sync/v1/service/syncmap/SyncMapItemCreator.java +++ b/src/main/java/com/twilio/rest/sync/v1/service/syncmap/SyncMapItemCreator.java @@ -26,15 +26,13 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -import java.util.Map; -import java.util.Map; public class SyncMapItemCreator extends Creator { private String pathServiceSid; private String pathMapSid; private String key; - private Map data; + private Object data; private Integer ttl; private Integer itemTtl; private Integer collectionTtl; @@ -43,7 +41,7 @@ public SyncMapItemCreator( final String pathServiceSid, final String pathMapSid, final String key, - final Map data + final Object data ) { this.pathServiceSid = pathServiceSid; this.pathMapSid = pathMapSid; @@ -56,7 +54,7 @@ public SyncMapItemCreator setKey(final String key) { return this; } - public SyncMapItemCreator setData(final Map data) { + public SyncMapItemCreator setData(final Object data) { this.data = data; return this; } @@ -126,7 +124,7 @@ private void addPostParams(final Request request) { request.addPostParam("Key", key); } if (data != null) { - request.addPostParam("Data", Converter.mapToJson(data)); + request.addPostParam("Data", Converter.objectToJson(data)); } if (ttl != null) { request.addPostParam("Ttl", ttl.toString()); diff --git a/src/main/java/com/twilio/rest/sync/v1/service/syncmap/SyncMapItemUpdater.java b/src/main/java/com/twilio/rest/sync/v1/service/syncmap/SyncMapItemUpdater.java index f9cb5af292..b0b1a151c0 100644 --- a/src/main/java/com/twilio/rest/sync/v1/service/syncmap/SyncMapItemUpdater.java +++ b/src/main/java/com/twilio/rest/sync/v1/service/syncmap/SyncMapItemUpdater.java @@ -25,7 +25,6 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -import java.util.Map; public class SyncMapItemUpdater extends Updater { @@ -33,7 +32,7 @@ public class SyncMapItemUpdater extends Updater { private String pathMapSid; private String pathKey; private String ifMatch; - private Map data; + private Object data; private Integer ttl; private Integer itemTtl; private Integer collectionTtl; @@ -53,7 +52,7 @@ public SyncMapItemUpdater setIfMatch(final String ifMatch) { return this; } - public SyncMapItemUpdater setData(final Map data) { + public SyncMapItemUpdater setData(final Object data) { this.data = data; return this; } @@ -120,7 +119,7 @@ public SyncMapItem update(final TwilioRestClient client) { private void addPostParams(final Request request) { if (data != null) { - request.addPostParam("Data", Converter.mapToJson(data)); + request.addPostParam("Data", Converter.objectToJson(data)); } if (ttl != null) { request.addPostParam("Ttl", ttl.toString()); diff --git a/src/main/java/com/twilio/rest/sync/v1/service/syncstream/StreamMessage.java b/src/main/java/com/twilio/rest/sync/v1/service/syncstream/StreamMessage.java index 7191f3acc2..b787e9d5a1 100644 --- a/src/main/java/com/twilio/rest/sync/v1/service/syncstream/StreamMessage.java +++ b/src/main/java/com/twilio/rest/sync/v1/service/syncstream/StreamMessage.java @@ -40,7 +40,7 @@ public class StreamMessage extends Resource { public static StreamMessageCreator creator( final String pathServiceSid, final String pathStreamSid, - final Map data + final Object data ) { return new StreamMessageCreator(pathServiceSid, pathStreamSid, data); } diff --git a/src/main/java/com/twilio/rest/sync/v1/service/syncstream/StreamMessageCreator.java b/src/main/java/com/twilio/rest/sync/v1/service/syncstream/StreamMessageCreator.java index 5739a6e69d..015002f303 100644 --- a/src/main/java/com/twilio/rest/sync/v1/service/syncstream/StreamMessageCreator.java +++ b/src/main/java/com/twilio/rest/sync/v1/service/syncstream/StreamMessageCreator.java @@ -26,26 +26,24 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -import java.util.Map; -import java.util.Map; public class StreamMessageCreator extends Creator { private String pathServiceSid; private String pathStreamSid; - private Map data; + private Object data; public StreamMessageCreator( final String pathServiceSid, final String pathStreamSid, - final Map data + final Object data ) { this.pathServiceSid = pathServiceSid; this.pathStreamSid = pathStreamSid; this.data = data; } - public StreamMessageCreator setData(final Map data) { + public StreamMessageCreator setData(final Object data) { this.data = data; return this; } @@ -100,7 +98,7 @@ public StreamMessage create(final TwilioRestClient client) { private void addPostParams(final Request request) { if (data != null) { - request.addPostParam("Data", Converter.mapToJson(data)); + request.addPostParam("Data", Converter.objectToJson(data)); } } } diff --git a/src/main/java/com/twilio/rest/taskrouter/v1/Workspace.java b/src/main/java/com/twilio/rest/taskrouter/v1/Workspace.java index 4ab41a8013..9d2660f685 100644 --- a/src/main/java/com/twilio/rest/taskrouter/v1/Workspace.java +++ b/src/main/java/com/twilio/rest/taskrouter/v1/Workspace.java @@ -116,7 +116,7 @@ public static Workspace fromJson( private final String sid; private final String timeoutActivityName; private final String timeoutActivitySid; - private final Workspace.QueueOrder prioritizeQueueOrder; + private final QueueOrder prioritizeQueueOrder; private final URI url; private final Map links; @@ -136,7 +136,7 @@ private Workspace( @JsonProperty("timeout_activity_sid") final String timeoutActivitySid, @JsonProperty( "prioritize_queue_order" - ) final Workspace.QueueOrder prioritizeQueueOrder, + ) final QueueOrder prioritizeQueueOrder, @JsonProperty("url") final URI url, @JsonProperty("links") final Map links ) { @@ -205,7 +205,7 @@ public final String getTimeoutActivitySid() { return this.timeoutActivitySid; } - public final Workspace.QueueOrder getPrioritizeQueueOrder() { + public final QueueOrder getPrioritizeQueueOrder() { return this.prioritizeQueueOrder; } diff --git a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/Task.java b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/Task.java index 5179bf0053..09f55e1d04 100644 --- a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/Task.java +++ b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/Task.java @@ -115,7 +115,7 @@ public static Task fromJson( private final String accountSid; private final Integer age; - private final Task.Status assignmentStatus; + private final Status assignmentStatus; private final String attributes; private final String addons; private final ZonedDateTime dateCreated; @@ -142,7 +142,7 @@ public static Task fromJson( private Task( @JsonProperty("account_sid") final String accountSid, @JsonProperty("age") final Integer age, - @JsonProperty("assignment_status") final Task.Status assignmentStatus, + @JsonProperty("assignment_status") final Status assignmentStatus, @JsonProperty("attributes") final String attributes, @JsonProperty("addons") final String addons, @JsonProperty("date_created") final String dateCreated, @@ -209,7 +209,7 @@ public final Integer getAge() { return this.age; } - public final Task.Status getAssignmentStatus() { + public final Status getAssignmentStatus() { return this.assignmentStatus; } diff --git a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/TaskQueue.java b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/TaskQueue.java index 15f1dfabef..28550cc4ce 100644 --- a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/TaskQueue.java +++ b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/TaskQueue.java @@ -127,7 +127,7 @@ public static TaskQueue fromJson( private final String reservationActivityName; private final String sid; private final String targetWorkers; - private final TaskQueue.TaskOrder taskOrder; + private final TaskOrder taskOrder; private final URI url; private final String workspaceSid; private final Map links; @@ -153,7 +153,7 @@ private TaskQueue( ) final String reservationActivityName, @JsonProperty("sid") final String sid, @JsonProperty("target_workers") final String targetWorkers, - @JsonProperty("task_order") final TaskQueue.TaskOrder taskOrder, + @JsonProperty("task_order") final TaskOrder taskOrder, @JsonProperty("url") final URI url, @JsonProperty("workspace_sid") final String workspaceSid, @JsonProperty("links") final Map links @@ -219,7 +219,7 @@ public final String getTargetWorkers() { return this.targetWorkers; } - public final TaskQueue.TaskOrder getTaskOrder() { + public final TaskOrder getTaskOrder() { return this.taskOrder; } diff --git a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/task/Reservation.java b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/task/Reservation.java index e3755218cc..14ae6d69c9 100644 --- a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/task/Reservation.java +++ b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/task/Reservation.java @@ -110,7 +110,7 @@ public static Reservation fromJson( private final String accountSid; private final ZonedDateTime dateCreated; private final ZonedDateTime dateUpdated; - private final Reservation.Status reservationStatus; + private final Status reservationStatus; private final String sid; private final String taskSid; private final String workerName; @@ -124,9 +124,7 @@ private Reservation( @JsonProperty("account_sid") final String accountSid, @JsonProperty("date_created") final String dateCreated, @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty( - "reservation_status" - ) final Reservation.Status reservationStatus, + @JsonProperty("reservation_status") final Status reservationStatus, @JsonProperty("sid") final String sid, @JsonProperty("task_sid") final String taskSid, @JsonProperty("worker_name") final String workerName, @@ -160,7 +158,7 @@ public final ZonedDateTime getDateUpdated() { return this.dateUpdated; } - public final Reservation.Status getReservationStatus() { + public final Status getReservationStatus() { return this.reservationStatus; } diff --git a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/worker/Reservation.java b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/worker/Reservation.java index 3c6c7d48d6..89c4a7f9d4 100644 --- a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/worker/Reservation.java +++ b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/worker/Reservation.java @@ -110,7 +110,7 @@ public static Reservation fromJson( private final String accountSid; private final ZonedDateTime dateCreated; private final ZonedDateTime dateUpdated; - private final Reservation.Status reservationStatus; + private final Status reservationStatus; private final String sid; private final String taskSid; private final String workerName; @@ -124,9 +124,7 @@ private Reservation( @JsonProperty("account_sid") final String accountSid, @JsonProperty("date_created") final String dateCreated, @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty( - "reservation_status" - ) final Reservation.Status reservationStatus, + @JsonProperty("reservation_status") final Status reservationStatus, @JsonProperty("sid") final String sid, @JsonProperty("task_sid") final String taskSid, @JsonProperty("worker_name") final String workerName, @@ -160,7 +158,7 @@ public final ZonedDateTime getDateUpdated() { return this.dateUpdated; } - public final Reservation.Status getReservationStatus() { + public final Status getReservationStatus() { return this.reservationStatus; } diff --git a/src/main/java/com/twilio/rest/trunking/v1/Trunk.java b/src/main/java/com/twilio/rest/trunking/v1/Trunk.java index 2d77f12579..48919cb239 100644 --- a/src/main/java/com/twilio/rest/trunking/v1/Trunk.java +++ b/src/main/java/com/twilio/rest/trunking/v1/Trunk.java @@ -113,8 +113,8 @@ public static Trunk fromJson( private final String friendlyName; private final Boolean secure; private final Map recording; - private final Trunk.TransferSetting transferMode; - private final Trunk.TransferCallerId transferCallerId; + private final TransferSetting transferMode; + private final TransferCallerId transferCallerId; private final Boolean cnamLookupEnabled; private final String authType; private final List authTypeSet; @@ -135,10 +135,10 @@ private Trunk( @JsonProperty("friendly_name") final String friendlyName, @JsonProperty("secure") final Boolean secure, @JsonProperty("recording") final Map recording, - @JsonProperty("transfer_mode") final Trunk.TransferSetting transferMode, + @JsonProperty("transfer_mode") final TransferSetting transferMode, @JsonProperty( "transfer_caller_id" - ) final Trunk.TransferCallerId transferCallerId, + ) final TransferCallerId transferCallerId, @JsonProperty("cnam_lookup_enabled") final Boolean cnamLookupEnabled, @JsonProperty("auth_type") final String authType, @JsonProperty("auth_type_set") final List authTypeSet, @@ -195,11 +195,11 @@ public final Map getRecording() { return this.recording; } - public final Trunk.TransferSetting getTransferMode() { + public final TransferSetting getTransferMode() { return this.transferMode; } - public final Trunk.TransferCallerId getTransferCallerId() { + public final TransferCallerId getTransferCallerId() { return this.transferCallerId; } diff --git a/src/main/java/com/twilio/rest/trunking/v1/trunk/PhoneNumber.java b/src/main/java/com/twilio/rest/trunking/v1/trunk/PhoneNumber.java index 733b18311c..beef3087ff 100644 --- a/src/main/java/com/twilio/rest/trunking/v1/trunk/PhoneNumber.java +++ b/src/main/java/com/twilio/rest/trunking/v1/trunk/PhoneNumber.java @@ -111,7 +111,7 @@ public static PhoneNumber fromJson( } private final String accountSid; - private final PhoneNumber.AddressRequirement addressRequirements; + private final AddressRequirement addressRequirements; private final String apiVersion; private final Boolean beta; private final Map capabilities; @@ -142,7 +142,7 @@ private PhoneNumber( @JsonProperty("account_sid") final String accountSid, @JsonProperty( "address_requirements" - ) final PhoneNumber.AddressRequirement addressRequirements, + ) final AddressRequirement addressRequirements, @JsonProperty("api_version") final String apiVersion, @JsonProperty("beta") final Boolean beta, @JsonProperty("capabilities") final Map capabilities, @@ -208,7 +208,7 @@ public final String getAccountSid() { return this.accountSid; } - public final PhoneNumber.AddressRequirement getAddressRequirements() { + public final AddressRequirement getAddressRequirements() { return this.addressRequirements; } diff --git a/src/main/java/com/twilio/rest/trunking/v1/trunk/Recording.java b/src/main/java/com/twilio/rest/trunking/v1/trunk/Recording.java index 022e65d0b9..709ccb95c9 100644 --- a/src/main/java/com/twilio/rest/trunking/v1/trunk/Recording.java +++ b/src/main/java/com/twilio/rest/trunking/v1/trunk/Recording.java @@ -87,23 +87,23 @@ public static Recording fromJson( } } - private final Recording.RecordingMode mode; - private final Recording.RecordingTrim trim; + private final RecordingMode mode; + private final RecordingTrim trim; @JsonCreator private Recording( - @JsonProperty("mode") final Recording.RecordingMode mode, - @JsonProperty("trim") final Recording.RecordingTrim trim + @JsonProperty("mode") final RecordingMode mode, + @JsonProperty("trim") final RecordingTrim trim ) { this.mode = mode; this.trim = trim; } - public final Recording.RecordingMode getMode() { + public final RecordingMode getMode() { return this.mode; } - public final Recording.RecordingTrim getTrim() { + public final RecordingTrim getTrim() { return this.trim; } diff --git a/src/main/java/com/twilio/rest/trusthub/v1/ComplianceRegistrationInquiries.java b/src/main/java/com/twilio/rest/trusthub/v1/ComplianceRegistrationInquiries.java index b633de24f7..76a614b6e0 100644 --- a/src/main/java/com/twilio/rest/trusthub/v1/ComplianceRegistrationInquiries.java +++ b/src/main/java/com/twilio/rest/trusthub/v1/ComplianceRegistrationInquiries.java @@ -38,8 +38,8 @@ public class ComplianceRegistrationInquiries extends Resource { private static final long serialVersionUID = 153862952025802L; public static ComplianceRegistrationInquiriesCreator creator( - final ComplianceRegistrationInquiries.EndUserType endUserType, - final ComplianceRegistrationInquiries.PhoneNumberType phoneNumberType + final EndUserType endUserType, + final PhoneNumberType phoneNumberType ) { return new ComplianceRegistrationInquiriesCreator( endUserType, diff --git a/src/main/java/com/twilio/rest/trusthub/v1/ComplianceTollfreeInquiriesCreator.java b/src/main/java/com/twilio/rest/trusthub/v1/ComplianceTollfreeInquiriesCreator.java index 35cf959970..a4413dc4c8 100644 --- a/src/main/java/com/twilio/rest/trusthub/v1/ComplianceTollfreeInquiriesCreator.java +++ b/src/main/java/com/twilio/rest/trusthub/v1/ComplianceTollfreeInquiriesCreator.java @@ -259,7 +259,7 @@ public ComplianceTollfreeInquiries create(final TwilioRestClient client) { path = path.replace( "{" + "TollfreePhoneNumber" + "}", - this.tollfreePhoneNumber.encode("utf-8") + this.tollfreePhoneNumber.toString() ); path = path.replace( diff --git a/src/main/java/com/twilio/rest/trusthub/v1/CustomerProfiles.java b/src/main/java/com/twilio/rest/trusthub/v1/CustomerProfiles.java index 9217f2067b..7225389bcd 100644 --- a/src/main/java/com/twilio/rest/trusthub/v1/CustomerProfiles.java +++ b/src/main/java/com/twilio/rest/trusthub/v1/CustomerProfiles.java @@ -113,7 +113,7 @@ public static CustomerProfiles fromJson( private final String accountSid; private final String policySid; private final String friendlyName; - private final CustomerProfiles.Status status; + private final Status status; private final ZonedDateTime validUntil; private final String email; private final URI statusCallback; @@ -129,7 +129,7 @@ private CustomerProfiles( @JsonProperty("account_sid") final String accountSid, @JsonProperty("policy_sid") final String policySid, @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("status") final CustomerProfiles.Status status, + @JsonProperty("status") final Status status, @JsonProperty("valid_until") final String validUntil, @JsonProperty("email") final String email, @JsonProperty("status_callback") final URI statusCallback, @@ -170,7 +170,7 @@ public final String getFriendlyName() { return this.friendlyName; } - public final CustomerProfiles.Status getStatus() { + public final Status getStatus() { return this.status; } diff --git a/src/main/java/com/twilio/rest/trusthub/v1/EndUserCreator.java b/src/main/java/com/twilio/rest/trusthub/v1/EndUserCreator.java index 0be75ae9a4..aaddaa97f9 100644 --- a/src/main/java/com/twilio/rest/trusthub/v1/EndUserCreator.java +++ b/src/main/java/com/twilio/rest/trusthub/v1/EndUserCreator.java @@ -26,14 +26,12 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -import java.util.Map; -import java.util.Map; public class EndUserCreator extends Creator { private String friendlyName; private String type; - private Map attributes; + private Object attributes; public EndUserCreator(final String friendlyName, final String type) { this.friendlyName = friendlyName; @@ -50,7 +48,7 @@ public EndUserCreator setType(final String type) { return this; } - public EndUserCreator setAttributes(final Map attributes) { + public EndUserCreator setAttributes(final Object attributes) { this.attributes = attributes; return this; } @@ -103,7 +101,10 @@ private void addPostParams(final Request request) { request.addPostParam("Type", type); } if (attributes != null) { - request.addPostParam("Attributes", Converter.mapToJson(attributes)); + request.addPostParam( + "Attributes", + Converter.objectToJson(attributes) + ); } } } diff --git a/src/main/java/com/twilio/rest/trusthub/v1/EndUserUpdater.java b/src/main/java/com/twilio/rest/trusthub/v1/EndUserUpdater.java index 39e4de9753..479a4a4ed9 100644 --- a/src/main/java/com/twilio/rest/trusthub/v1/EndUserUpdater.java +++ b/src/main/java/com/twilio/rest/trusthub/v1/EndUserUpdater.java @@ -25,13 +25,12 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -import java.util.Map; public class EndUserUpdater extends Updater { private String pathSid; private String friendlyName; - private Map attributes; + private Object attributes; public EndUserUpdater(final String pathSid) { this.pathSid = pathSid; @@ -42,7 +41,7 @@ public EndUserUpdater setFriendlyName(final String friendlyName) { return this; } - public EndUserUpdater setAttributes(final Map attributes) { + public EndUserUpdater setAttributes(final Object attributes) { this.attributes = attributes; return this; } @@ -87,7 +86,10 @@ private void addPostParams(final Request request) { request.addPostParam("FriendlyName", friendlyName); } if (attributes != null) { - request.addPostParam("Attributes", Converter.mapToJson(attributes)); + request.addPostParam( + "Attributes", + Converter.objectToJson(attributes) + ); } } } diff --git a/src/main/java/com/twilio/rest/trusthub/v1/SupportingDocument.java b/src/main/java/com/twilio/rest/trusthub/v1/SupportingDocument.java index fcb0e31305..e9c68d404c 100644 --- a/src/main/java/com/twilio/rest/trusthub/v1/SupportingDocument.java +++ b/src/main/java/com/twilio/rest/trusthub/v1/SupportingDocument.java @@ -111,7 +111,7 @@ public static SupportingDocument fromJson( private final String accountSid; private final String friendlyName; private final String mimeType; - private final SupportingDocument.Status status; + private final Status status; private final String type; private final Map attributes; private final ZonedDateTime dateCreated; @@ -124,7 +124,7 @@ private SupportingDocument( @JsonProperty("account_sid") final String accountSid, @JsonProperty("friendly_name") final String friendlyName, @JsonProperty("mime_type") final String mimeType, - @JsonProperty("status") final SupportingDocument.Status status, + @JsonProperty("status") final Status status, @JsonProperty("type") final String type, @JsonProperty("attributes") final Map attributes, @JsonProperty("date_created") final String dateCreated, @@ -159,7 +159,7 @@ public final String getMimeType() { return this.mimeType; } - public final SupportingDocument.Status getStatus() { + public final Status getStatus() { return this.status; } diff --git a/src/main/java/com/twilio/rest/trusthub/v1/SupportingDocumentCreator.java b/src/main/java/com/twilio/rest/trusthub/v1/SupportingDocumentCreator.java index 6b509fe88f..53f68a08d7 100644 --- a/src/main/java/com/twilio/rest/trusthub/v1/SupportingDocumentCreator.java +++ b/src/main/java/com/twilio/rest/trusthub/v1/SupportingDocumentCreator.java @@ -26,14 +26,12 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -import java.util.Map; -import java.util.Map; public class SupportingDocumentCreator extends Creator { private String friendlyName; private String type; - private Map attributes; + private Object attributes; public SupportingDocumentCreator( final String friendlyName, @@ -55,9 +53,7 @@ public SupportingDocumentCreator setType(final String type) { return this; } - public SupportingDocumentCreator setAttributes( - final Map attributes - ) { + public SupportingDocumentCreator setAttributes(final Object attributes) { this.attributes = attributes; return this; } @@ -113,7 +109,10 @@ private void addPostParams(final Request request) { request.addPostParam("Type", type); } if (attributes != null) { - request.addPostParam("Attributes", Converter.mapToJson(attributes)); + request.addPostParam( + "Attributes", + Converter.objectToJson(attributes) + ); } } } diff --git a/src/main/java/com/twilio/rest/trusthub/v1/SupportingDocumentUpdater.java b/src/main/java/com/twilio/rest/trusthub/v1/SupportingDocumentUpdater.java index 099d6f7077..ec523a8f85 100644 --- a/src/main/java/com/twilio/rest/trusthub/v1/SupportingDocumentUpdater.java +++ b/src/main/java/com/twilio/rest/trusthub/v1/SupportingDocumentUpdater.java @@ -25,13 +25,12 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -import java.util.Map; public class SupportingDocumentUpdater extends Updater { private String pathSid; private String friendlyName; - private Map attributes; + private Object attributes; public SupportingDocumentUpdater(final String pathSid) { this.pathSid = pathSid; @@ -44,9 +43,7 @@ public SupportingDocumentUpdater setFriendlyName( return this; } - public SupportingDocumentUpdater setAttributes( - final Map attributes - ) { + public SupportingDocumentUpdater setAttributes(final Object attributes) { this.attributes = attributes; return this; } @@ -94,7 +91,10 @@ private void addPostParams(final Request request) { request.addPostParam("FriendlyName", friendlyName); } if (attributes != null) { - request.addPostParam("Attributes", Converter.mapToJson(attributes)); + request.addPostParam( + "Attributes", + Converter.objectToJson(attributes) + ); } } } diff --git a/src/main/java/com/twilio/rest/trusthub/v1/TrustProducts.java b/src/main/java/com/twilio/rest/trusthub/v1/TrustProducts.java index a1be16ed7e..97afa46975 100644 --- a/src/main/java/com/twilio/rest/trusthub/v1/TrustProducts.java +++ b/src/main/java/com/twilio/rest/trusthub/v1/TrustProducts.java @@ -113,7 +113,7 @@ public static TrustProducts fromJson( private final String accountSid; private final String policySid; private final String friendlyName; - private final TrustProducts.Status status; + private final Status status; private final ZonedDateTime validUntil; private final String email; private final URI statusCallback; @@ -129,7 +129,7 @@ private TrustProducts( @JsonProperty("account_sid") final String accountSid, @JsonProperty("policy_sid") final String policySid, @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("status") final TrustProducts.Status status, + @JsonProperty("status") final Status status, @JsonProperty("valid_until") final String validUntil, @JsonProperty("email") final String email, @JsonProperty("status_callback") final URI statusCallback, @@ -170,7 +170,7 @@ public final String getFriendlyName() { return this.friendlyName; } - public final TrustProducts.Status getStatus() { + public final Status getStatus() { return this.status; } diff --git a/src/main/java/com/twilio/rest/trusthub/v1/customerprofiles/CustomerProfilesEvaluations.java b/src/main/java/com/twilio/rest/trusthub/v1/customerprofiles/CustomerProfilesEvaluations.java index 27d0116ac0..04af325a8b 100644 --- a/src/main/java/com/twilio/rest/trusthub/v1/customerprofiles/CustomerProfilesEvaluations.java +++ b/src/main/java/com/twilio/rest/trusthub/v1/customerprofiles/CustomerProfilesEvaluations.java @@ -121,7 +121,7 @@ public static CustomerProfilesEvaluations fromJson( private final String accountSid; private final String policySid; private final String customerProfileSid; - private final CustomerProfilesEvaluations.Status status; + private final Status status; private final List> results; private final ZonedDateTime dateCreated; private final URI url; @@ -132,7 +132,7 @@ private CustomerProfilesEvaluations( @JsonProperty("account_sid") final String accountSid, @JsonProperty("policy_sid") final String policySid, @JsonProperty("customer_profile_sid") final String customerProfileSid, - @JsonProperty("status") final CustomerProfilesEvaluations.Status status, + @JsonProperty("status") final Status status, @JsonProperty("results") final List> results, @JsonProperty("date_created") final String dateCreated, @JsonProperty("url") final URI url @@ -163,7 +163,7 @@ public final String getCustomerProfileSid() { return this.customerProfileSid; } - public final CustomerProfilesEvaluations.Status getStatus() { + public final Status getStatus() { return this.status; } diff --git a/src/main/java/com/twilio/rest/trusthub/v1/trustproducts/TrustProductsEvaluations.java b/src/main/java/com/twilio/rest/trusthub/v1/trustproducts/TrustProductsEvaluations.java index c2aee8cf6b..9c10b40232 100644 --- a/src/main/java/com/twilio/rest/trusthub/v1/trustproducts/TrustProductsEvaluations.java +++ b/src/main/java/com/twilio/rest/trusthub/v1/trustproducts/TrustProductsEvaluations.java @@ -115,7 +115,7 @@ public static TrustProductsEvaluations fromJson( private final String accountSid; private final String policySid; private final String trustProductSid; - private final TrustProductsEvaluations.Status status; + private final Status status; private final List> results; private final ZonedDateTime dateCreated; private final URI url; @@ -126,7 +126,7 @@ private TrustProductsEvaluations( @JsonProperty("account_sid") final String accountSid, @JsonProperty("policy_sid") final String policySid, @JsonProperty("trust_product_sid") final String trustProductSid, - @JsonProperty("status") final TrustProductsEvaluations.Status status, + @JsonProperty("status") final Status status, @JsonProperty("results") final List> results, @JsonProperty("date_created") final String dateCreated, @JsonProperty("url") final URI url @@ -157,7 +157,7 @@ public final String getTrustProductSid() { return this.trustProductSid; } - public final TrustProductsEvaluations.Status getStatus() { + public final Status getStatus() { return this.status; } diff --git a/src/main/java/com/twilio/rest/verify/v2/Form.java b/src/main/java/com/twilio/rest/verify/v2/Form.java index c6f82158f9..0511a234b7 100644 --- a/src/main/java/com/twilio/rest/verify/v2/Form.java +++ b/src/main/java/com/twilio/rest/verify/v2/Form.java @@ -39,7 +39,7 @@ public class Form extends Resource { private static final long serialVersionUID = 202517967097226L; - public static FormFetcher fetcher(final Form.FormTypes formType) { + public static FormFetcher fetcher(final FormTypes formType) { return new FormFetcher(formType); } @@ -86,14 +86,14 @@ public static Form fromJson( } } - private final Form.FormTypes formType; + private final FormTypes formType; private final Map forms; private final Map formMeta; private final URI url; @JsonCreator private Form( - @JsonProperty("form_type") final Form.FormTypes formType, + @JsonProperty("form_type") final FormTypes formType, @JsonProperty("forms") final Map forms, @JsonProperty("form_meta") final Map formMeta, @JsonProperty("url") final URI url @@ -104,7 +104,7 @@ private Form( this.url = url; } - public final Form.FormTypes getFormType() { + public final FormTypes getFormType() { return this.formType; } diff --git a/src/main/java/com/twilio/rest/verify/v2/VerificationAttempt.java b/src/main/java/com/twilio/rest/verify/v2/VerificationAttempt.java index 9058afe690..de89169b16 100644 --- a/src/main/java/com/twilio/rest/verify/v2/VerificationAttempt.java +++ b/src/main/java/com/twilio/rest/verify/v2/VerificationAttempt.java @@ -98,8 +98,8 @@ public static VerificationAttempt fromJson( private final String verificationSid; private final ZonedDateTime dateCreated; private final ZonedDateTime dateUpdated; - private final VerificationAttempt.ConversionStatus conversionStatus; - private final VerificationAttempt.Channels channel; + private final ConversionStatus conversionStatus; + private final Channels channel; private final Map price; private final Map channelData; private final URI url; @@ -114,8 +114,8 @@ private VerificationAttempt( @JsonProperty("date_updated") final String dateUpdated, @JsonProperty( "conversion_status" - ) final VerificationAttempt.ConversionStatus conversionStatus, - @JsonProperty("channel") final VerificationAttempt.Channels channel, + ) final ConversionStatus conversionStatus, + @JsonProperty("channel") final Channels channel, @JsonProperty("price") final Map price, @JsonProperty("channel_data") final Map channelData, @JsonProperty("url") final URI url @@ -157,11 +157,11 @@ public final ZonedDateTime getDateUpdated() { return this.dateUpdated; } - public final VerificationAttempt.ConversionStatus getConversionStatus() { + public final ConversionStatus getConversionStatus() { return this.conversionStatus; } - public final VerificationAttempt.Channels getChannel() { + public final Channels getChannel() { return this.channel; } diff --git a/src/main/java/com/twilio/rest/verify/v2/service/AccessToken.java b/src/main/java/com/twilio/rest/verify/v2/service/AccessToken.java index e8ed33b57d..64f406878e 100644 --- a/src/main/java/com/twilio/rest/verify/v2/service/AccessToken.java +++ b/src/main/java/com/twilio/rest/verify/v2/service/AccessToken.java @@ -42,7 +42,7 @@ public class AccessToken extends Resource { public static AccessTokenCreator creator( final String pathServiceSid, final String identity, - final AccessToken.FactorTypes factorType + final FactorTypes factorType ) { return new AccessTokenCreator(pathServiceSid, identity, factorType); } @@ -101,7 +101,7 @@ public static AccessToken fromJson( private final String accountSid; private final String serviceSid; private final String entityIdentity; - private final AccessToken.FactorTypes factorType; + private final FactorTypes factorType; private final String factorFriendlyName; private final String token; private final URI url; @@ -114,7 +114,7 @@ private AccessToken( @JsonProperty("account_sid") final String accountSid, @JsonProperty("service_sid") final String serviceSid, @JsonProperty("entity_identity") final String entityIdentity, - @JsonProperty("factor_type") final AccessToken.FactorTypes factorType, + @JsonProperty("factor_type") final FactorTypes factorType, @JsonProperty("factor_friendly_name") final String factorFriendlyName, @JsonProperty("token") final String token, @JsonProperty("url") final URI url, @@ -149,7 +149,7 @@ public final String getEntityIdentity() { return this.entityIdentity; } - public final AccessToken.FactorTypes getFactorType() { + public final FactorTypes getFactorType() { return this.factorType; } diff --git a/src/main/java/com/twilio/rest/verify/v2/service/Verification.java b/src/main/java/com/twilio/rest/verify/v2/service/Verification.java index 913b0b4db9..c46be724eb 100644 --- a/src/main/java/com/twilio/rest/verify/v2/service/Verification.java +++ b/src/main/java/com/twilio/rest/verify/v2/service/Verification.java @@ -60,7 +60,7 @@ public static VerificationFetcher fetcher( public static VerificationUpdater updater( final String pathServiceSid, final String pathSid, - final Verification.Status status + final Status status ) { return new VerificationUpdater(pathServiceSid, pathSid, status); } @@ -112,7 +112,7 @@ public static Verification fromJson( private final String serviceSid; private final String accountSid; private final String to; - private final Verification.Channel channel; + private final Channel channel; private final String status; private final Boolean valid; private final Map lookup; @@ -130,7 +130,7 @@ private Verification( @JsonProperty("service_sid") final String serviceSid, @JsonProperty("account_sid") final String accountSid, @JsonProperty("to") final String to, - @JsonProperty("channel") final Verification.Channel channel, + @JsonProperty("channel") final Channel channel, @JsonProperty("status") final String status, @JsonProperty("valid") final Boolean valid, @JsonProperty("lookup") final Map lookup, @@ -177,7 +177,7 @@ public final String getTo() { return this.to; } - public final Verification.Channel getChannel() { + public final Channel getChannel() { return this.channel; } diff --git a/src/main/java/com/twilio/rest/verify/v2/service/VerificationCheck.java b/src/main/java/com/twilio/rest/verify/v2/service/VerificationCheck.java index 303b066dae..938c708c7e 100644 --- a/src/main/java/com/twilio/rest/verify/v2/service/VerificationCheck.java +++ b/src/main/java/com/twilio/rest/verify/v2/service/VerificationCheck.java @@ -94,7 +94,7 @@ public static VerificationCheck fromJson( private final String serviceSid; private final String accountSid; private final String to; - private final VerificationCheck.Channel channel; + private final Channel channel; private final String status; private final Boolean valid; private final String amount; @@ -109,7 +109,7 @@ private VerificationCheck( @JsonProperty("service_sid") final String serviceSid, @JsonProperty("account_sid") final String accountSid, @JsonProperty("to") final String to, - @JsonProperty("channel") final VerificationCheck.Channel channel, + @JsonProperty("channel") final Channel channel, @JsonProperty("status") final String status, @JsonProperty("valid") final Boolean valid, @JsonProperty("amount") final String amount, @@ -150,7 +150,7 @@ public final String getTo() { return this.to; } - public final VerificationCheck.Channel getChannel() { + public final Channel getChannel() { return this.channel; } diff --git a/src/main/java/com/twilio/rest/verify/v2/service/VerificationCreator.java b/src/main/java/com/twilio/rest/verify/v2/service/VerificationCreator.java index d6f592d7db..2e88faa3f9 100644 --- a/src/main/java/com/twilio/rest/verify/v2/service/VerificationCreator.java +++ b/src/main/java/com/twilio/rest/verify/v2/service/VerificationCreator.java @@ -26,8 +26,6 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -import java.util.Map; -import java.util.Map; public class VerificationCreator extends Creator { @@ -41,8 +39,8 @@ public class VerificationCreator extends Creator { private String customCode; private String amount; private String payee; - private Map rateLimits; - private Map channelConfiguration; + private Object rateLimits; + private Object channelConfiguration; private String appHash; private String templateSid; private String templateCustomSubstitutions; @@ -108,15 +106,13 @@ public VerificationCreator setPayee(final String payee) { return this; } - public VerificationCreator setRateLimits( - final Map rateLimits - ) { + public VerificationCreator setRateLimits(final Object rateLimits) { this.rateLimits = rateLimits; return this; } public VerificationCreator setChannelConfiguration( - final Map channelConfiguration + final Object channelConfiguration ) { this.channelConfiguration = channelConfiguration; return this; @@ -236,12 +232,15 @@ private void addPostParams(final Request request) { request.addPostParam("Payee", payee); } if (rateLimits != null) { - request.addPostParam("RateLimits", Converter.mapToJson(rateLimits)); + request.addPostParam( + "RateLimits", + Converter.objectToJson(rateLimits) + ); } if (channelConfiguration != null) { request.addPostParam( "ChannelConfiguration", - Converter.mapToJson(channelConfiguration) + Converter.objectToJson(channelConfiguration) ); } if (appHash != null) { diff --git a/src/main/java/com/twilio/rest/verify/v2/service/Webhook.java b/src/main/java/com/twilio/rest/verify/v2/service/Webhook.java index 16a7742d11..1ac1c6672d 100644 --- a/src/main/java/com/twilio/rest/verify/v2/service/Webhook.java +++ b/src/main/java/com/twilio/rest/verify/v2/service/Webhook.java @@ -127,10 +127,10 @@ public static Webhook fromJson( private final String accountSid; private final String friendlyName; private final List eventTypes; - private final Webhook.Status status; - private final Webhook.Version version; + private final Status status; + private final Version version; private final URI webhookUrl; - private final Webhook.Methods webhookMethod; + private final Methods webhookMethod; private final ZonedDateTime dateCreated; private final ZonedDateTime dateUpdated; private final URI url; @@ -142,10 +142,10 @@ private Webhook( @JsonProperty("account_sid") final String accountSid, @JsonProperty("friendly_name") final String friendlyName, @JsonProperty("event_types") final List eventTypes, - @JsonProperty("status") final Webhook.Status status, - @JsonProperty("version") final Webhook.Version version, + @JsonProperty("status") final Status status, + @JsonProperty("version") final Version version, @JsonProperty("webhook_url") final URI webhookUrl, - @JsonProperty("webhook_method") final Webhook.Methods webhookMethod, + @JsonProperty("webhook_method") final Methods webhookMethod, @JsonProperty("date_created") final String dateCreated, @JsonProperty("date_updated") final String dateUpdated, @JsonProperty("url") final URI url @@ -184,11 +184,11 @@ public final List getEventTypes() { return this.eventTypes; } - public final Webhook.Status getStatus() { + public final Status getStatus() { return this.status; } - public final Webhook.Version getVersion() { + public final Version getVersion() { return this.version; } @@ -196,7 +196,7 @@ public final URI getWebhookUrl() { return this.webhookUrl; } - public final Webhook.Methods getWebhookMethod() { + public final Methods getWebhookMethod() { return this.webhookMethod; } diff --git a/src/main/java/com/twilio/rest/verify/v2/service/entity/Challenge.java b/src/main/java/com/twilio/rest/verify/v2/service/entity/Challenge.java index 0d62df7622..448f620207 100644 --- a/src/main/java/com/twilio/rest/verify/v2/service/entity/Challenge.java +++ b/src/main/java/com/twilio/rest/verify/v2/service/entity/Challenge.java @@ -125,12 +125,12 @@ public static Challenge fromJson( private final ZonedDateTime dateUpdated; private final ZonedDateTime dateResponded; private final ZonedDateTime expirationDate; - private final Challenge.ChallengeStatuses status; - private final Challenge.ChallengeReasons respondedReason; + private final ChallengeStatuses status; + private final ChallengeReasons respondedReason; private final Map details; private final Map hiddenDetails; private final Map metadata; - private final Challenge.FactorTypes factorType; + private final FactorTypes factorType; private final URI url; private final Map links; @@ -146,14 +146,14 @@ private Challenge( @JsonProperty("date_updated") final String dateUpdated, @JsonProperty("date_responded") final String dateResponded, @JsonProperty("expiration_date") final String expirationDate, - @JsonProperty("status") final Challenge.ChallengeStatuses status, + @JsonProperty("status") final ChallengeStatuses status, @JsonProperty( "responded_reason" - ) final Challenge.ChallengeReasons respondedReason, + ) final ChallengeReasons respondedReason, @JsonProperty("details") final Map details, @JsonProperty("hidden_details") final Map hiddenDetails, @JsonProperty("metadata") final Map metadata, - @JsonProperty("factor_type") final Challenge.FactorTypes factorType, + @JsonProperty("factor_type") final FactorTypes factorType, @JsonProperty("url") final URI url, @JsonProperty("links") final Map links ) { @@ -219,11 +219,11 @@ public final ZonedDateTime getExpirationDate() { return this.expirationDate; } - public final Challenge.ChallengeStatuses getStatus() { + public final ChallengeStatuses getStatus() { return this.status; } - public final Challenge.ChallengeReasons getRespondedReason() { + public final ChallengeReasons getRespondedReason() { return this.respondedReason; } @@ -239,7 +239,7 @@ public final Map getMetadata() { return this.metadata; } - public final Challenge.FactorTypes getFactorType() { + public final FactorTypes getFactorType() { return this.factorType; } diff --git a/src/main/java/com/twilio/rest/verify/v2/service/entity/ChallengeCreator.java b/src/main/java/com/twilio/rest/verify/v2/service/entity/ChallengeCreator.java index 5f014a389f..7db4865e5c 100644 --- a/src/main/java/com/twilio/rest/verify/v2/service/entity/ChallengeCreator.java +++ b/src/main/java/com/twilio/rest/verify/v2/service/entity/ChallengeCreator.java @@ -30,8 +30,6 @@ import java.time.ZonedDateTime; import java.util.List; import java.util.List; -import java.util.Map; -import java.util.Map; public class ChallengeCreator extends Creator { @@ -40,8 +38,8 @@ public class ChallengeCreator extends Creator { private String factorSid; private ZonedDateTime expirationDate; private String detailsMessage; - private List> detailsFields; - private Map hiddenDetails; + private List detailsFields; + private Object hiddenDetails; private String authPayload; public ChallengeCreator( @@ -71,22 +69,16 @@ public ChallengeCreator setDetailsMessage(final String detailsMessage) { return this; } - public ChallengeCreator setDetailsFields( - final List> detailsFields - ) { + public ChallengeCreator setDetailsFields(final List detailsFields) { this.detailsFields = detailsFields; return this; } - public ChallengeCreator setDetailsFields( - final Map detailsFields - ) { + public ChallengeCreator setDetailsFields(final Object detailsFields) { return setDetailsFields(Promoter.listOfOne(detailsFields)); } - public ChallengeCreator setHiddenDetails( - final Map hiddenDetails - ) { + public ChallengeCreator setHiddenDetails(final Object hiddenDetails) { this.hiddenDetails = hiddenDetails; return this; } @@ -156,17 +148,14 @@ private void addPostParams(final Request request) { request.addPostParam("Details.Message", detailsMessage); } if (detailsFields != null) { - for (Map prop : detailsFields) { - request.addPostParam( - "Details.Fields", - Converter.mapToJson(prop) - ); + for (Object prop : detailsFields) { + request.addPostParam("Details.Fields", prop.toString()); } } if (hiddenDetails != null) { request.addPostParam( "HiddenDetails", - Converter.mapToJson(hiddenDetails) + Converter.objectToJson(hiddenDetails) ); } if (authPayload != null) { diff --git a/src/main/java/com/twilio/rest/verify/v2/service/entity/ChallengeUpdater.java b/src/main/java/com/twilio/rest/verify/v2/service/entity/ChallengeUpdater.java index 3b7fda6ef9..9870c326cc 100644 --- a/src/main/java/com/twilio/rest/verify/v2/service/entity/ChallengeUpdater.java +++ b/src/main/java/com/twilio/rest/verify/v2/service/entity/ChallengeUpdater.java @@ -25,7 +25,6 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -import java.util.Map; public class ChallengeUpdater extends Updater { @@ -33,7 +32,7 @@ public class ChallengeUpdater extends Updater { private String pathIdentity; private String pathSid; private String authPayload; - private Map metadata; + private Object metadata; public ChallengeUpdater( final String pathServiceSid, @@ -50,7 +49,7 @@ public ChallengeUpdater setAuthPayload(final String authPayload) { return this; } - public ChallengeUpdater setMetadata(final Map metadata) { + public ChallengeUpdater setMetadata(final Object metadata) { this.metadata = metadata; return this; } @@ -106,7 +105,7 @@ private void addPostParams(final Request request) { request.addPostParam("AuthPayload", authPayload); } if (metadata != null) { - request.addPostParam("Metadata", Converter.mapToJson(metadata)); + request.addPostParam("Metadata", Converter.objectToJson(metadata)); } } } diff --git a/src/main/java/com/twilio/rest/verify/v2/service/entity/Factor.java b/src/main/java/com/twilio/rest/verify/v2/service/entity/Factor.java index edeafe8f4e..ba24c6e972 100644 --- a/src/main/java/com/twilio/rest/verify/v2/service/entity/Factor.java +++ b/src/main/java/com/twilio/rest/verify/v2/service/entity/Factor.java @@ -123,8 +123,8 @@ public static Factor fromJson( private final ZonedDateTime dateCreated; private final ZonedDateTime dateUpdated; private final String friendlyName; - private final Factor.FactorStatuses status; - private final Factor.FactorTypes factorType; + private final FactorStatuses status; + private final FactorTypes factorType; private final Map config; private final Map metadata; private final URI url; @@ -139,8 +139,8 @@ private Factor( @JsonProperty("date_created") final String dateCreated, @JsonProperty("date_updated") final String dateUpdated, @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("status") final Factor.FactorStatuses status, - @JsonProperty("factor_type") final Factor.FactorTypes factorType, + @JsonProperty("status") final FactorStatuses status, + @JsonProperty("factor_type") final FactorTypes factorType, @JsonProperty("config") final Map config, @JsonProperty("metadata") final Map metadata, @JsonProperty("url") final URI url @@ -192,11 +192,11 @@ public final String getFriendlyName() { return this.friendlyName; } - public final Factor.FactorStatuses getStatus() { + public final FactorStatuses getStatus() { return this.status; } - public final Factor.FactorTypes getFactorType() { + public final FactorTypes getFactorType() { return this.factorType; } diff --git a/src/main/java/com/twilio/rest/verify/v2/service/entity/NewFactor.java b/src/main/java/com/twilio/rest/verify/v2/service/entity/NewFactor.java index 308d23c721..b5b249668f 100644 --- a/src/main/java/com/twilio/rest/verify/v2/service/entity/NewFactor.java +++ b/src/main/java/com/twilio/rest/verify/v2/service/entity/NewFactor.java @@ -45,7 +45,7 @@ public static NewFactorCreator creator( final String pathServiceSid, final String pathIdentity, final String friendlyName, - final NewFactor.FactorTypes factorType + final FactorTypes factorType ) { return new NewFactorCreator( pathServiceSid, @@ -107,8 +107,8 @@ public static NewFactor fromJson( private final ZonedDateTime dateCreated; private final ZonedDateTime dateUpdated; private final String friendlyName; - private final NewFactor.FactorStatuses status; - private final NewFactor.FactorTypes factorType; + private final FactorStatuses status; + private final FactorTypes factorType; private final Map config; private final Map metadata; private final URI url; @@ -124,8 +124,8 @@ private NewFactor( @JsonProperty("date_created") final String dateCreated, @JsonProperty("date_updated") final String dateUpdated, @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("status") final NewFactor.FactorStatuses status, - @JsonProperty("factor_type") final NewFactor.FactorTypes factorType, + @JsonProperty("status") final FactorStatuses status, + @JsonProperty("factor_type") final FactorTypes factorType, @JsonProperty("config") final Map config, @JsonProperty("metadata") final Map metadata, @JsonProperty("url") final URI url @@ -182,11 +182,11 @@ public final String getFriendlyName() { return this.friendlyName; } - public final NewFactor.FactorStatuses getStatus() { + public final FactorStatuses getStatus() { return this.status; } - public final NewFactor.FactorTypes getFactorType() { + public final FactorTypes getFactorType() { return this.factorType; } diff --git a/src/main/java/com/twilio/rest/verify/v2/service/entity/NewFactorCreator.java b/src/main/java/com/twilio/rest/verify/v2/service/entity/NewFactorCreator.java index 3221e50770..6f4e2f5409 100644 --- a/src/main/java/com/twilio/rest/verify/v2/service/entity/NewFactorCreator.java +++ b/src/main/java/com/twilio/rest/verify/v2/service/entity/NewFactorCreator.java @@ -26,8 +26,6 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -import java.util.Map; -import java.util.Map; public class NewFactorCreator extends Creator { @@ -46,7 +44,7 @@ public class NewFactorCreator extends Creator { private Integer configSkew; private Integer configCodeLength; private NewFactor.TotpAlgorithms configAlg; - private Map metadata; + private Object metadata; public NewFactorCreator( final String pathServiceSid, @@ -135,7 +133,7 @@ public NewFactorCreator setConfigAlg( return this; } - public NewFactorCreator setMetadata(final Map metadata) { + public NewFactorCreator setMetadata(final Object metadata) { this.metadata = metadata; return this; } @@ -241,7 +239,7 @@ private void addPostParams(final Request request) { request.addPostParam("Config.Alg", configAlg.toString()); } if (metadata != null) { - request.addPostParam("Metadata", Converter.mapToJson(metadata)); + request.addPostParam("Metadata", Converter.objectToJson(metadata)); } } } diff --git a/src/main/java/com/twilio/rest/video/v1/Composition.java b/src/main/java/com/twilio/rest/video/v1/Composition.java index c58d12e102..cdb8c529ea 100644 --- a/src/main/java/com/twilio/rest/video/v1/Composition.java +++ b/src/main/java/com/twilio/rest/video/v1/Composition.java @@ -103,7 +103,7 @@ public static Composition fromJson( } private final String accountSid; - private final Composition.Status status; + private final Status status; private final ZonedDateTime dateCreated; private final ZonedDateTime dateCompleted; private final ZonedDateTime dateDeleted; @@ -114,7 +114,7 @@ public static Composition fromJson( private final Map videoLayout; private final String resolution; private final Boolean trim; - private final Composition.Format format; + private final Format format; private final Integer bitrate; private final Long size; private final Integer duration; @@ -127,7 +127,7 @@ public static Composition fromJson( @JsonCreator private Composition( @JsonProperty("account_sid") final String accountSid, - @JsonProperty("status") final Composition.Status status, + @JsonProperty("status") final Status status, @JsonProperty("date_created") final String dateCreated, @JsonProperty("date_completed") final String dateCompleted, @JsonProperty("date_deleted") final String dateDeleted, @@ -140,7 +140,7 @@ private Composition( @JsonProperty("video_layout") final Map videoLayout, @JsonProperty("resolution") final String resolution, @JsonProperty("trim") final Boolean trim, - @JsonProperty("format") final Composition.Format format, + @JsonProperty("format") final Format format, @JsonProperty("bitrate") final Integer bitrate, @JsonProperty("size") final Long size, @JsonProperty("duration") final Integer duration, @@ -182,7 +182,7 @@ public final String getAccountSid() { return this.accountSid; } - public final Composition.Status getStatus() { + public final Status getStatus() { return this.status; } @@ -226,7 +226,7 @@ public final Boolean getTrim() { return this.trim; } - public final Composition.Format getFormat() { + public final Format getFormat() { return this.format; } diff --git a/src/main/java/com/twilio/rest/video/v1/CompositionHook.java b/src/main/java/com/twilio/rest/video/v1/CompositionHook.java index 4c28fa2a64..c311f937ea 100644 --- a/src/main/java/com/twilio/rest/video/v1/CompositionHook.java +++ b/src/main/java/com/twilio/rest/video/v1/CompositionHook.java @@ -120,7 +120,7 @@ public static CompositionHook fromJson( private final Map videoLayout; private final String resolution; private final Boolean trim; - private final CompositionHook.Format format; + private final Format format; private final URI statusCallback; private final HttpMethod statusCallbackMethod; private final URI url; @@ -140,7 +140,7 @@ private CompositionHook( @JsonProperty("video_layout") final Map videoLayout, @JsonProperty("resolution") final String resolution, @JsonProperty("trim") final Boolean trim, - @JsonProperty("format") final CompositionHook.Format format, + @JsonProperty("format") final Format format, @JsonProperty("status_callback") final URI statusCallback, @JsonProperty( "status_callback_method" @@ -208,7 +208,7 @@ public final Boolean getTrim() { return this.trim; } - public final CompositionHook.Format getFormat() { + public final Format getFormat() { return this.format; } diff --git a/src/main/java/com/twilio/rest/video/v1/Recording.java b/src/main/java/com/twilio/rest/video/v1/Recording.java index 4f21119419..8c7e6debb8 100644 --- a/src/main/java/com/twilio/rest/video/v1/Recording.java +++ b/src/main/java/com/twilio/rest/video/v1/Recording.java @@ -98,16 +98,16 @@ public static Recording fromJson( } private final String accountSid; - private final Recording.Status status; + private final Status status; private final ZonedDateTime dateCreated; private final String sid; private final String sourceSid; private final Long size; private final URI url; - private final Recording.Type type; + private final Type type; private final Integer duration; - private final Recording.Format containerFormat; - private final Recording.Codec codec; + private final Format containerFormat; + private final Codec codec; private final Map groupingSids; private final String trackName; private final Long offset; @@ -119,18 +119,16 @@ public static Recording fromJson( @JsonCreator private Recording( @JsonProperty("account_sid") final String accountSid, - @JsonProperty("status") final Recording.Status status, + @JsonProperty("status") final Status status, @JsonProperty("date_created") final String dateCreated, @JsonProperty("sid") final String sid, @JsonProperty("source_sid") final String sourceSid, @JsonProperty("size") final Long size, @JsonProperty("url") final URI url, - @JsonProperty("type") final Recording.Type type, + @JsonProperty("type") final Type type, @JsonProperty("duration") final Integer duration, - @JsonProperty( - "container_format" - ) final Recording.Format containerFormat, - @JsonProperty("codec") final Recording.Codec codec, + @JsonProperty("container_format") final Format containerFormat, + @JsonProperty("codec") final Codec codec, @JsonProperty("grouping_sids") final Map groupingSids, @JsonProperty("track_name") final String trackName, @JsonProperty("offset") final Long offset, @@ -167,7 +165,7 @@ public final String getAccountSid() { return this.accountSid; } - public final Recording.Status getStatus() { + public final Status getStatus() { return this.status; } @@ -191,7 +189,7 @@ public final URI getUrl() { return this.url; } - public final Recording.Type getType() { + public final Type getType() { return this.type; } @@ -199,11 +197,11 @@ public final Integer getDuration() { return this.duration; } - public final Recording.Format getContainerFormat() { + public final Format getContainerFormat() { return this.containerFormat; } - public final Recording.Codec getCodec() { + public final Codec getCodec() { return this.codec; } diff --git a/src/main/java/com/twilio/rest/video/v1/Room.java b/src/main/java/com/twilio/rest/video/v1/Room.java index 77a513b610..3ed9520d58 100644 --- a/src/main/java/com/twilio/rest/video/v1/Room.java +++ b/src/main/java/com/twilio/rest/video/v1/Room.java @@ -57,7 +57,7 @@ public static RoomReader reader() { public static RoomUpdater updater( final String pathSid, - final Room.RoomStatus status + final RoomStatus status ) { return new RoomUpdater(pathSid, status); } @@ -106,7 +106,7 @@ public static Room fromJson( } private final String sid; - private final Room.RoomStatus status; + private final RoomStatus status; private final ZonedDateTime dateCreated; private final ZonedDateTime dateUpdated; private final String accountSid; @@ -116,12 +116,12 @@ public static Room fromJson( private final HttpMethod statusCallbackMethod; private final ZonedDateTime endTime; private final Integer duration; - private final Room.RoomType type; + private final RoomType type; private final Integer maxParticipants; private final Integer maxParticipantDuration; private final Integer maxConcurrentPublishedTracks; private final Boolean recordParticipantsOnConnect; - private final List videoCodecs; + private final List videoCodecs; private final String mediaRegion; private final Boolean audioOnly; private final Integer emptyRoomTimeout; @@ -133,7 +133,7 @@ public static Room fromJson( @JsonCreator private Room( @JsonProperty("sid") final String sid, - @JsonProperty("status") final Room.RoomStatus status, + @JsonProperty("status") final RoomStatus status, @JsonProperty("date_created") final String dateCreated, @JsonProperty("date_updated") final String dateUpdated, @JsonProperty("account_sid") final String accountSid, @@ -145,7 +145,7 @@ private Room( ) final HttpMethod statusCallbackMethod, @JsonProperty("end_time") final String endTime, @JsonProperty("duration") final Integer duration, - @JsonProperty("type") final Room.RoomType type, + @JsonProperty("type") final RoomType type, @JsonProperty("max_participants") final Integer maxParticipants, @JsonProperty( "max_participant_duration" @@ -156,7 +156,7 @@ private Room( @JsonProperty( "record_participants_on_connect" ) final Boolean recordParticipantsOnConnect, - @JsonProperty("video_codecs") final List videoCodecs, + @JsonProperty("video_codecs") final List videoCodecs, @JsonProperty("media_region") final String mediaRegion, @JsonProperty("audio_only") final Boolean audioOnly, @JsonProperty("empty_room_timeout") final Integer emptyRoomTimeout, @@ -195,7 +195,7 @@ public final String getSid() { return this.sid; } - public final Room.RoomStatus getStatus() { + public final RoomStatus getStatus() { return this.status; } @@ -235,7 +235,7 @@ public final Integer getDuration() { return this.duration; } - public final Room.RoomType getType() { + public final RoomType getType() { return this.type; } @@ -255,7 +255,7 @@ public final Boolean getRecordParticipantsOnConnect() { return this.recordParticipantsOnConnect; } - public final List getVideoCodecs() { + public final List getVideoCodecs() { return this.videoCodecs; } diff --git a/src/main/java/com/twilio/rest/video/v1/room/Participant.java b/src/main/java/com/twilio/rest/video/v1/room/Participant.java index e424615a76..83a9ab8d84 100644 --- a/src/main/java/com/twilio/rest/video/v1/room/Participant.java +++ b/src/main/java/com/twilio/rest/video/v1/room/Participant.java @@ -105,7 +105,7 @@ public static Participant fromJson( private final String sid; private final String roomSid; private final String accountSid; - private final Participant.Status status; + private final Status status; private final String identity; private final ZonedDateTime dateCreated; private final ZonedDateTime dateUpdated; @@ -120,7 +120,7 @@ private Participant( @JsonProperty("sid") final String sid, @JsonProperty("room_sid") final String roomSid, @JsonProperty("account_sid") final String accountSid, - @JsonProperty("status") final Participant.Status status, + @JsonProperty("status") final Status status, @JsonProperty("identity") final String identity, @JsonProperty("date_created") final String dateCreated, @JsonProperty("date_updated") final String dateUpdated, @@ -156,7 +156,7 @@ public final String getAccountSid() { return this.accountSid; } - public final Participant.Status getStatus() { + public final Status getStatus() { return this.status; } diff --git a/src/main/java/com/twilio/rest/video/v1/room/RoomRecording.java b/src/main/java/com/twilio/rest/video/v1/room/RoomRecording.java index 7a37f4e2ad..506eaea365 100644 --- a/src/main/java/com/twilio/rest/video/v1/room/RoomRecording.java +++ b/src/main/java/com/twilio/rest/video/v1/room/RoomRecording.java @@ -103,16 +103,16 @@ public static RoomRecording fromJson( } private final String accountSid; - private final RoomRecording.Status status; + private final Status status; private final ZonedDateTime dateCreated; private final String sid; private final String sourceSid; private final Long size; private final URI url; - private final RoomRecording.Type type; + private final Type type; private final Integer duration; - private final RoomRecording.Format containerFormat; - private final RoomRecording.Codec codec; + private final Format containerFormat; + private final Codec codec; private final Map groupingSids; private final String trackName; private final Long offset; @@ -123,18 +123,16 @@ public static RoomRecording fromJson( @JsonCreator private RoomRecording( @JsonProperty("account_sid") final String accountSid, - @JsonProperty("status") final RoomRecording.Status status, + @JsonProperty("status") final Status status, @JsonProperty("date_created") final String dateCreated, @JsonProperty("sid") final String sid, @JsonProperty("source_sid") final String sourceSid, @JsonProperty("size") final Long size, @JsonProperty("url") final URI url, - @JsonProperty("type") final RoomRecording.Type type, + @JsonProperty("type") final Type type, @JsonProperty("duration") final Integer duration, - @JsonProperty( - "container_format" - ) final RoomRecording.Format containerFormat, - @JsonProperty("codec") final RoomRecording.Codec codec, + @JsonProperty("container_format") final Format containerFormat, + @JsonProperty("codec") final Codec codec, @JsonProperty("grouping_sids") final Map groupingSids, @JsonProperty("track_name") final String trackName, @JsonProperty("offset") final Long offset, @@ -167,7 +165,7 @@ public final String getAccountSid() { return this.accountSid; } - public final RoomRecording.Status getStatus() { + public final Status getStatus() { return this.status; } @@ -191,7 +189,7 @@ public final URI getUrl() { return this.url; } - public final RoomRecording.Type getType() { + public final Type getType() { return this.type; } @@ -199,11 +197,11 @@ public final Integer getDuration() { return this.duration; } - public final RoomRecording.Format getContainerFormat() { + public final Format getContainerFormat() { return this.containerFormat; } - public final RoomRecording.Codec getCodec() { + public final Codec getCodec() { return this.codec; } diff --git a/src/main/java/com/twilio/rest/video/v1/room/participant/Anonymize.java b/src/main/java/com/twilio/rest/video/v1/room/participant/Anonymize.java index 13cd56e05e..898d66175f 100644 --- a/src/main/java/com/twilio/rest/video/v1/room/participant/Anonymize.java +++ b/src/main/java/com/twilio/rest/video/v1/room/participant/Anonymize.java @@ -92,7 +92,7 @@ public static Anonymize fromJson( private final String sid; private final String roomSid; private final String accountSid; - private final Anonymize.Status status; + private final Status status; private final String identity; private final ZonedDateTime dateCreated; private final ZonedDateTime dateUpdated; @@ -106,7 +106,7 @@ private Anonymize( @JsonProperty("sid") final String sid, @JsonProperty("room_sid") final String roomSid, @JsonProperty("account_sid") final String accountSid, - @JsonProperty("status") final Anonymize.Status status, + @JsonProperty("status") final Status status, @JsonProperty("identity") final String identity, @JsonProperty("date_created") final String dateCreated, @JsonProperty("date_updated") final String dateUpdated, @@ -140,7 +140,7 @@ public final String getAccountSid() { return this.accountSid; } - public final Anonymize.Status getStatus() { + public final Status getStatus() { return this.status; } diff --git a/src/main/java/com/twilio/rest/video/v1/room/participant/PublishedTrack.java b/src/main/java/com/twilio/rest/video/v1/room/participant/PublishedTrack.java index 38798ef161..d48e5ad022 100644 --- a/src/main/java/com/twilio/rest/video/v1/room/participant/PublishedTrack.java +++ b/src/main/java/com/twilio/rest/video/v1/room/participant/PublishedTrack.java @@ -108,7 +108,7 @@ public static PublishedTrack fromJson( private final ZonedDateTime dateCreated; private final ZonedDateTime dateUpdated; private final Boolean enabled; - private final PublishedTrack.Kind kind; + private final Kind kind; private final URI url; @JsonCreator @@ -120,7 +120,7 @@ private PublishedTrack( @JsonProperty("date_created") final String dateCreated, @JsonProperty("date_updated") final String dateUpdated, @JsonProperty("enabled") final Boolean enabled, - @JsonProperty("kind") final PublishedTrack.Kind kind, + @JsonProperty("kind") final Kind kind, @JsonProperty("url") final URI url ) { this.sid = sid; @@ -162,7 +162,7 @@ public final Boolean getEnabled() { return this.enabled; } - public final PublishedTrack.Kind getKind() { + public final Kind getKind() { return this.kind; } diff --git a/src/main/java/com/twilio/rest/video/v1/room/participant/SubscribedTrack.java b/src/main/java/com/twilio/rest/video/v1/room/participant/SubscribedTrack.java index d31de8e3c5..23c88fbcc7 100644 --- a/src/main/java/com/twilio/rest/video/v1/room/participant/SubscribedTrack.java +++ b/src/main/java/com/twilio/rest/video/v1/room/participant/SubscribedTrack.java @@ -109,7 +109,7 @@ public static SubscribedTrack fromJson( private final ZonedDateTime dateCreated; private final ZonedDateTime dateUpdated; private final Boolean enabled; - private final SubscribedTrack.Kind kind; + private final Kind kind; private final URI url; @JsonCreator @@ -122,7 +122,7 @@ private SubscribedTrack( @JsonProperty("date_created") final String dateCreated, @JsonProperty("date_updated") final String dateUpdated, @JsonProperty("enabled") final Boolean enabled, - @JsonProperty("kind") final SubscribedTrack.Kind kind, + @JsonProperty("kind") final Kind kind, @JsonProperty("url") final URI url ) { this.sid = sid; @@ -169,7 +169,7 @@ public final Boolean getEnabled() { return this.enabled; } - public final SubscribedTrack.Kind getKind() { + public final Kind getKind() { return this.kind; } diff --git a/src/main/java/com/twilio/rest/wireless/v1/Command.java b/src/main/java/com/twilio/rest/wireless/v1/Command.java index e1c79cb63b..bd545d7403 100644 --- a/src/main/java/com/twilio/rest/wireless/v1/Command.java +++ b/src/main/java/com/twilio/rest/wireless/v1/Command.java @@ -102,11 +102,11 @@ public static Command fromJson( private final String accountSid; private final String simSid; private final String command; - private final Command.CommandMode commandMode; - private final Command.Transport transport; + private final CommandMode commandMode; + private final Transport transport; private final Boolean deliveryReceiptRequested; - private final Command.Status status; - private final Command.Direction direction; + private final Status status; + private final Direction direction; private final ZonedDateTime dateCreated; private final ZonedDateTime dateUpdated; private final URI url; @@ -117,13 +117,13 @@ private Command( @JsonProperty("account_sid") final String accountSid, @JsonProperty("sim_sid") final String simSid, @JsonProperty("command") final String command, - @JsonProperty("command_mode") final Command.CommandMode commandMode, - @JsonProperty("transport") final Command.Transport transport, + @JsonProperty("command_mode") final CommandMode commandMode, + @JsonProperty("transport") final Transport transport, @JsonProperty( "delivery_receipt_requested" ) final Boolean deliveryReceiptRequested, - @JsonProperty("status") final Command.Status status, - @JsonProperty("direction") final Command.Direction direction, + @JsonProperty("status") final Status status, + @JsonProperty("direction") final Direction direction, @JsonProperty("date_created") final String dateCreated, @JsonProperty("date_updated") final String dateUpdated, @JsonProperty("url") final URI url @@ -158,11 +158,11 @@ public final String getCommand() { return this.command; } - public final Command.CommandMode getCommandMode() { + public final CommandMode getCommandMode() { return this.commandMode; } - public final Command.Transport getTransport() { + public final Transport getTransport() { return this.transport; } @@ -170,11 +170,11 @@ public final Boolean getDeliveryReceiptRequested() { return this.deliveryReceiptRequested; } - public final Command.Status getStatus() { + public final Status getStatus() { return this.status; } - public final Command.Direction getDirection() { + public final Direction getDirection() { return this.direction; } diff --git a/src/main/java/com/twilio/rest/wireless/v1/Sim.java b/src/main/java/com/twilio/rest/wireless/v1/Sim.java index ccfd84da74..6410f6d200 100644 --- a/src/main/java/com/twilio/rest/wireless/v1/Sim.java +++ b/src/main/java/com/twilio/rest/wireless/v1/Sim.java @@ -108,8 +108,8 @@ public static Sim fromJson( private final String friendlyName; private final String iccid; private final String eId; - private final Sim.Status status; - private final Sim.ResetStatus resetStatus; + private final Status status; + private final ResetStatus resetStatus; private final URI commandsCallbackUrl; private final HttpMethod commandsCallbackMethod; private final HttpMethod smsFallbackMethod; @@ -135,8 +135,8 @@ private Sim( @JsonProperty("friendly_name") final String friendlyName, @JsonProperty("iccid") final String iccid, @JsonProperty("e_id") final String eId, - @JsonProperty("status") final Sim.Status status, - @JsonProperty("reset_status") final Sim.ResetStatus resetStatus, + @JsonProperty("status") final Status status, + @JsonProperty("reset_status") final ResetStatus resetStatus, @JsonProperty("commands_callback_url") final URI commandsCallbackUrl, @JsonProperty( "commands_callback_method" @@ -211,11 +211,11 @@ public final String getEId() { return this.eId; } - public final Sim.Status getStatus() { + public final Status getStatus() { return this.status; } - public final Sim.ResetStatus getResetStatus() { + public final ResetStatus getResetStatus() { return this.resetStatus; } diff --git a/src/test/java/com/twilio/ClusterTest.java b/src/test/java/com/twilio/ClusterTest.java index 328609a1c5..48e0fc3f39 100644 --- a/src/test/java/com/twilio/ClusterTest.java +++ b/src/test/java/com/twilio/ClusterTest.java @@ -38,7 +38,7 @@ public class ClusterTest { String clientSecret; String messageSid; TwilioRestClient customRestClient; - + String accountSid; @Before @@ -57,11 +57,11 @@ public void setUp() { orgsClientSecret = System.getenv("TWILIO_ORGS_CLIENT_SECRET"); organisationSid = System.getenv("TWILIO_ORG_SID"); TwilioOrgsTokenAuth.init(grantType, orgsClientId, orgsClientSecret); - + clientId = System.getenv("TWILIO_CLIENT_ID"); clientSecret = System.getenv("TWILIO_CLIENT_SECRET"); messageSid = System.getenv("TWILIO_MESSAGE_SID"); - + // CustomHttpClient customRestClient = new TwilioRestClient.Builder(apiKey, secret).accountSid(accountSid).httpClient(new CustomHttpClient()).build(); } @@ -117,7 +117,7 @@ public void testListParams() { sinkConfiguration.put("destination", "http://example.org/webhook"); sinkConfiguration.put("method", "post"); sinkConfiguration.put("batch_events",false); - List> types = new ArrayList<>(); + List types = new ArrayList<>(); Map types1 = new HashMap<>(); Map types2 = new HashMap<>(); types1.put("type", "com.twilio.messaging.message.delivered"); @@ -175,7 +175,7 @@ public void testMultiPartFormData() { // @Test // public void testPublicOAuthFetchMessage() { // Twilio.init(new ClientCredentialProvider(clientId, clientSecret), accountSid); -// // Fetching an existing message; if this test fails, the SID might be deleted, +// // Fetching an existing message; if this test fails, the SID might be deleted, // // in that case, change TWILIO_MESSAGE_SID in twilio-java repo env variables // Message message = Message.fetcher(messageSid).fetch(); // assertNotNull(message); From e3483556029cf4ee206b48d7e4127b3b750a24de Mon Sep 17 00:00:00 2001 From: Shubham Date: Wed, 2 Jul 2025 20:54:35 +0530 Subject: [PATCH 02/32] chore: Handle List serialization (#874) * fix: use Object for types instead of Map * fix: use Object for anyType * fix: use Object for anyType * fix: handle array of objects correctly * fix: add converter import statement --- .../com/twilio/rest/accounts/v1/BulkConsentsCreator.java | 3 ++- .../com/twilio/rest/accounts/v1/BulkContactsCreator.java | 3 ++- .../java/com/twilio/rest/events/v1/SubscriptionCreator.java | 3 ++- .../twilio/rest/flexapi/v1/PluginConfigurationCreator.java | 3 ++- .../com/twilio/rest/proxy/v1/service/SessionCreator.java | 6 +++++- .../rest/verify/v2/service/entity/ChallengeCreator.java | 5 ++++- 6 files changed, 17 insertions(+), 6 deletions(-) diff --git a/src/main/java/com/twilio/rest/accounts/v1/BulkConsentsCreator.java b/src/main/java/com/twilio/rest/accounts/v1/BulkConsentsCreator.java index ad5acc7da5..b472c75f67 100644 --- a/src/main/java/com/twilio/rest/accounts/v1/BulkConsentsCreator.java +++ b/src/main/java/com/twilio/rest/accounts/v1/BulkConsentsCreator.java @@ -15,6 +15,7 @@ package com.twilio.rest.accounts.v1; import com.twilio.base.Creator; +import com.twilio.converter.Converter; import com.twilio.constant.EnumConstants; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; @@ -86,7 +87,7 @@ public BulkConsents create(final TwilioRestClient client) { private void addPostParams(final Request request) { if (items != null) { for (Object prop : items) { - request.addPostParam("Items", prop.toString()); + request.addPostParam("Items", Converter.objectToJson(prop)); } } } diff --git a/src/main/java/com/twilio/rest/accounts/v1/BulkContactsCreator.java b/src/main/java/com/twilio/rest/accounts/v1/BulkContactsCreator.java index 2939c5c60d..abbd29d480 100644 --- a/src/main/java/com/twilio/rest/accounts/v1/BulkContactsCreator.java +++ b/src/main/java/com/twilio/rest/accounts/v1/BulkContactsCreator.java @@ -16,6 +16,7 @@ import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.converter.Converter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; @@ -86,7 +87,7 @@ public BulkContacts create(final TwilioRestClient client) { private void addPostParams(final Request request) { if (items != null) { for (Object prop : items) { - request.addPostParam("Items", prop.toString()); + request.addPostParam("Items", Converter.objectToJson(prop)); } } } diff --git a/src/main/java/com/twilio/rest/events/v1/SubscriptionCreator.java b/src/main/java/com/twilio/rest/events/v1/SubscriptionCreator.java index e82e798efa..fd9b3c97e5 100644 --- a/src/main/java/com/twilio/rest/events/v1/SubscriptionCreator.java +++ b/src/main/java/com/twilio/rest/events/v1/SubscriptionCreator.java @@ -15,6 +15,7 @@ package com.twilio.rest.events.v1; import com.twilio.base.Creator; +import com.twilio.converter.Converter; import com.twilio.constant.EnumConstants; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; @@ -116,7 +117,7 @@ private void addPostParams(final Request request) { } if (types != null) { for (Object prop : types) { - request.addPostParam("Types", prop.toString()); + request.addPostParam("Types", Converter.objectToJson(prop)); } } } diff --git a/src/main/java/com/twilio/rest/flexapi/v1/PluginConfigurationCreator.java b/src/main/java/com/twilio/rest/flexapi/v1/PluginConfigurationCreator.java index d55ca90f44..19dbfd4fee 100644 --- a/src/main/java/com/twilio/rest/flexapi/v1/PluginConfigurationCreator.java +++ b/src/main/java/com/twilio/rest/flexapi/v1/PluginConfigurationCreator.java @@ -16,6 +16,7 @@ import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.converter.Converter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; @@ -110,7 +111,7 @@ private void addPostParams(final Request request) { } if (plugins != null) { for (Object prop : plugins) { - request.addPostParam("Plugins", prop.toString()); + request.addPostParam("Plugins", Converter.objectToJson(prop)); } } if (description != null) { diff --git a/src/main/java/com/twilio/rest/proxy/v1/service/SessionCreator.java b/src/main/java/com/twilio/rest/proxy/v1/service/SessionCreator.java index 7cabf721a5..8a936a5902 100644 --- a/src/main/java/com/twilio/rest/proxy/v1/service/SessionCreator.java +++ b/src/main/java/com/twilio/rest/proxy/v1/service/SessionCreator.java @@ -15,6 +15,7 @@ package com.twilio.rest.proxy.v1.service; import com.twilio.base.Creator; +import com.twilio.converter.Converter; import com.twilio.constant.EnumConstants; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; @@ -137,7 +138,10 @@ private void addPostParams(final Request request) { } if (participants != null) { for (Object prop : participants) { - request.addPostParam("Participants", prop.toString()); + request.addPostParam( + "Participants", + Converter.objectToJson(prop) + ); } } } diff --git a/src/main/java/com/twilio/rest/verify/v2/service/entity/ChallengeCreator.java b/src/main/java/com/twilio/rest/verify/v2/service/entity/ChallengeCreator.java index 7db4865e5c..366f518740 100644 --- a/src/main/java/com/twilio/rest/verify/v2/service/entity/ChallengeCreator.java +++ b/src/main/java/com/twilio/rest/verify/v2/service/entity/ChallengeCreator.java @@ -149,7 +149,10 @@ private void addPostParams(final Request request) { } if (detailsFields != null) { for (Object prop : detailsFields) { - request.addPostParam("Details.Fields", prop.toString()); + request.addPostParam( + "Details.Fields", + Converter.objectToJson(prop) + ); } } if (hiddenDetails != null) { From b7375942080fa06d00e905ddf5b1d7b08057b924 Mon Sep 17 00:00:00 2001 From: Shubham Date: Thu, 3 Jul 2025 12:23:09 +0530 Subject: [PATCH 03/32] chore: prepare for RC release (#875) --- CHANGES.md | 4 ++++ README.md | 4 ++-- pom.xml | 4 ++-- src/main/java/com/twilio/Twilio.java | 8 ++++---- 4 files changed, 12 insertions(+), 8 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index 2a4a510039..22a5fd150c 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,6 +1,10 @@ twilio-java changelog ===================== +[2025-07-03] Version 11.0.0-rc.0 +-------------------------------- +- Release Candidate prep + [2025-06-12] Version 10.9.2 --------------------------- **Library - Chore** diff --git a/README.md b/README.md index dbd9f1c804..e498ca964c 100644 --- a/README.md +++ b/README.md @@ -62,7 +62,7 @@ Use the following dependency in your project to grab via Maven: com.twilio.sdk twilio - 10.X.X + 11.X.X-rc.x compile ``` @@ -70,7 +70,7 @@ Use the following dependency in your project to grab via Maven: or Gradle: ```groovy -implementation "com.twilio.sdk:twilio:10.X.X" +implementation "com.twilio.sdk:twilio:11.X.X-rc.x" ``` If you want to compile it yourself, here's how: diff --git a/pom.xml b/pom.xml index 69033e805e..ccd11db341 100644 --- a/pom.xml +++ b/pom.xml @@ -5,7 +5,7 @@ twilio jar twilio - 10.9.2 + 11.0.0-rc.0 Twilio Java Helper Library https://www.twilio.com @@ -490,4 +490,4 @@ - \ No newline at end of file + diff --git a/src/main/java/com/twilio/Twilio.java b/src/main/java/com/twilio/Twilio.java index 7ed3da168a..b2827de8f3 100644 --- a/src/main/java/com/twilio/Twilio.java +++ b/src/main/java/com/twilio/Twilio.java @@ -24,7 +24,7 @@ */ public class Twilio { - public static final String VERSION = "10.9.2"; + public static final String VERSION = "11.0.0-rc.0"; public static final String JAVA_VERSION = System.getProperty("java.version"); public static final String OS_NAME = System.getProperty("os.name"); public static final String OS_ARCH = System.getProperty("os.arch"); @@ -37,7 +37,7 @@ public class Twilio { private static String edge = System.getenv("TWILIO_EDGE"); private static volatile TwilioRestClient restClient; private static volatile ExecutorService executorService; - + private static CredentialProvider credentialProvider; private Twilio() { @@ -85,7 +85,7 @@ private static void setCredentialProvider(final CredentialProvider credentialPro if (credentialProvider == null) { throw new AuthenticationException("Credential Provider can not be null"); } - + if (!credentialProvider.equals(Twilio.credentialProvider)) { Twilio.invalidate(); } @@ -315,7 +315,7 @@ private static void invalidate() { private static void invalidateOAuthCreds() { Twilio.credentialProvider = null; } - + private static void invalidateBasicCreds() { Twilio.username = null; Twilio.password = null; From 953e73e599fdcf5d197fb95e873c0929d1fe2bd0 Mon Sep 17 00:00:00 2001 From: Twilio Date: Thu, 3 Jul 2025 09:38:52 +0000 Subject: [PATCH 04/32] [Librarian] Regenerated @ d122b05026327019e18cb5763c557a68138cc2c8 0e8634d10afc0145e18ccb8d90598b642b67ad87 --- CHANGES.md | 29 + src/main/java/com/twilio/Domains.java | 2 - .../rest/accounts/v1/BulkConsentsCreator.java | 3 +- .../rest/accounts/v1/BulkContactsCreator.java | 1 + .../com/twilio/rest/api/v2010/Account.java | 12 +- .../v2010/account/AuthorizedConnectApp.java | 8 +- .../twilio/rest/api/v2010/account/Call.java | 8 +- .../rest/api/v2010/account/Conference.java | 12 +- .../rest/api/v2010/account/ConnectApp.java | 8 +- .../v2010/account/IncomingPhoneNumber.java | 26 +- .../rest/api/v2010/account/Message.java | 14 +- .../rest/api/v2010/account/Recording.java | 12 +- .../rest/api/v2010/account/Transcription.java | 8 +- .../account/address/DependentPhoneNumber.java | 14 +- .../api/v2010/account/call/Recording.java | 18 +- .../rest/api/v2010/account/call/Siprec.java | 10 +- .../rest/api/v2010/account/call/Stream.java | 10 +- .../api/v2010/account/call/Transcription.java | 10 +- .../v2010/account/conference/Participant.java | 6 +- .../v2010/account/conference/Recording.java | 18 +- .../account/incomingphonenumber/Local.java | 26 +- .../account/incomingphonenumber/Mobile.java | 26 +- .../account/incomingphonenumber/TollFree.java | 26 +- .../api/v2010/account/message/Feedback.java | 6 +- .../v2010/account/recording/AddOnResult.java | 6 +- .../account/recording/Transcription.java | 8 +- .../rest/api/v2010/account/usage/Record.java | 8 +- .../rest/api/v2010/account/usage/Trigger.java | 24 +- .../v2010/account/usage/record/AllTime.java | 8 +- .../api/v2010/account/usage/record/Daily.java | 8 +- .../v2010/account/usage/record/LastMonth.java | 8 +- .../v2010/account/usage/record/Monthly.java | 8 +- .../v2010/account/usage/record/ThisMonth.java | 8 +- .../api/v2010/account/usage/record/Today.java | 8 +- .../v2010/account/usage/record/Yearly.java | 8 +- .../v2010/account/usage/record/Yesterday.java | 8 +- .../twilio/rest/assistants/v1/Assistant.java | 2 +- .../twilio/rest/assistants/v1/Knowledge.java | 2 +- .../com/twilio/rest/assistants/v1/Tool.java | 2 +- .../assistants/v1/assistant/Feedback.java | 2 +- .../rest/assistants/v1/assistant/Message.java | 2 +- .../com/twilio/rest/chat/v1/Credential.java | 8 +- .../twilio/rest/chat/v1/service/Channel.java | 6 +- .../com/twilio/rest/chat/v1/service/Role.java | 8 +- .../chat/v1/service/user/UserChannel.java | 6 +- .../com/twilio/rest/chat/v2/Credential.java | 8 +- .../twilio/rest/chat/v2/service/Binding.java | 6 +- .../twilio/rest/chat/v2/service/Channel.java | 6 +- .../com/twilio/rest/chat/v2/service/Role.java | 8 +- .../rest/chat/v2/service/channel/Webhook.java | 2 +- .../chat/v2/service/user/UserBinding.java | 6 +- .../chat/v2/service/user/UserChannel.java | 12 +- .../java/com/twilio/rest/chat/v3/Channel.java | 6 +- .../com/twilio/rest/content/v1/Content.java | 2 +- .../content/v1/content/ApprovalCreate.java | 2 +- .../v1/AddressConfiguration.java | 2 +- .../rest/conversations/v1/Conversation.java | 6 +- .../v1/ConversationWithParticipants.java | 6 +- .../rest/conversations/v1/Credential.java | 8 +- .../v1/ParticipantConversation.java | 8 +- .../twilio/rest/conversations/v1/Role.java | 8 +- .../v1/configuration/Webhook.java | 12 +- .../v1/conversation/Webhook.java | 2 +- .../conversation/message/DeliveryReceipt.java | 6 +- .../conversations/v1/service/Binding.java | 6 +- .../v1/service/Conversation.java | 6 +- .../service/ConversationWithParticipants.java | 6 +- .../v1/service/ParticipantConversation.java | 8 +- .../rest/conversations/v1/service/Role.java | 8 +- .../v1/service/configuration/Webhook.java | 6 +- .../v1/service/conversation/Webhook.java | 2 +- .../conversation/message/DeliveryReceipt.java | 6 +- .../v1/service/user/UserConversation.java | 14 +- .../v1/user/UserConversation.java | 14 +- .../java/com/twilio/rest/events/v1/Sink.java | 14 +- .../rest/events/v1/SubscriptionCreator.java | 3 +- .../twilio/rest/flexapi/v1/Configuration.java | 6 +- .../com/twilio/rest/flexapi/v1/FlexFlow.java | 16 +- .../v1/PluginConfigurationCreator.java | 1 + .../rest/flexapi/v1/ProvisioningStatus.java | 6 +- .../v1/interaction/InteractionChannel.java | 14 +- .../InteractionChannelParticipant.java | 10 +- .../InteractionTransfer.java | 12 +- .../com/twilio/rest/frontlineapi/v1/User.java | 6 +- .../rest/insights/v1/CallSummaries.java | 26 +- .../twilio/rest/insights/v1/Conference.java | 40 +- .../com/twilio/rest/insights/v1/Room.java | 50 +- .../rest/insights/v1/call/Annotation.java | 12 +- .../rest/insights/v1/call/CallSummary.java | 26 +- .../twilio/rest/insights/v1/call/Event.java | 12 +- .../twilio/rest/insights/v1/call/Metric.java | 12 +- .../v1/conference/ConferenceParticipant.java | 54 +- .../rest/insights/v1/room/Participant.java | 26 +- .../rest/intelligence/v2/CustomOperator.java | 8 +- .../twilio/rest/intelligence/v2/Operator.java | 6 +- .../rest/intelligence/v2/OperatorType.java | 20 +- .../intelligence/v2/PrebuiltOperator.java | 8 +- .../twilio/rest/intelligence/v2/Service.java | 8 +- .../rest/intelligence/v2/Transcript.java | 6 +- .../v2/transcript/OperatorResult.java | 8 +- .../rest/ipmessaging/v1/Credential.java | 8 +- .../rest/ipmessaging/v1/service/Channel.java | 6 +- .../rest/ipmessaging/v1/service/Role.java | 8 +- .../v1/service/user/UserChannel.java | 6 +- .../rest/ipmessaging/v2/Credential.java | 8 +- .../rest/ipmessaging/v2/service/Binding.java | 6 +- .../rest/ipmessaging/v2/service/Channel.java | 6 +- .../rest/ipmessaging/v2/service/Role.java | 8 +- .../v2/service/channel/Webhook.java | 2 +- .../v2/service/user/UserBinding.java | 6 +- .../v2/service/user/UserChannel.java | 12 +- .../twilio/rest/knowledge/v1/Knowledge.java | 409 --------- .../rest/knowledge/v1/KnowledgeDeleter.java | 69 -- .../rest/knowledge/v1/KnowledgeFetcher.java | 73 -- .../rest/knowledge/v1/KnowledgeReader.java | 144 ---- .../rest/knowledge/v1/knowledge/Chunk.java | 161 ---- .../knowledge/v1/knowledge/ChunkReader.java | 139 --- .../v1/knowledge/KnowledgeStatus.java | 145 ---- .../v1/knowledge/KnowledgeStatusFetcher.java | 73 -- .../com/twilio/rest/lookups/v2/Bucket.java | 209 +++++ .../v2/BucketDeleter.java} | 23 +- .../v2/BucketFetcher.java} | 27 +- .../v2/BucketUpdater.java} | 54 +- .../rest/lookups/v2/LookupOverride.java | 337 ++++++++ .../v2/LookupOverrideCreator.java} | 48 +- .../v2/LookupOverrideDeleter.java} | 32 +- .../v2/LookupOverrideFetcher.java} | 36 +- .../v2/LookupOverrideUpdater.java} | 50 +- .../twilio/rest/lookups/v2/PhoneNumber.java | 6 +- .../com/twilio/rest/lookups/v2/Query.java | 799 ++++++++++++++++++ .../v2/QueryCreator.java} | 54 +- .../v2/RateLimit.java} | 120 +-- .../v2/RateLimitFetcher.java} | 49 +- .../marketplace/v1/ReferralConversion.java | 2 +- .../installedaddon/InstalledAddOnUsage.java | 2 +- .../rest/messaging/v1/BrandRegistration.java | 22 +- .../com/twilio/rest/messaging/v1/Service.java | 6 +- .../messaging/v1/TollfreeVerification.java | 16 +- .../v1/brandregistration/BrandVetting.java | 10 +- .../rest/messaging/v2/ChannelsSender.java | 8 +- .../rest/microvisor/v1/AccountConfig.java | 168 ---- .../microvisor/v1/AccountConfigCreator.java | 95 --- .../microvisor/v1/AccountConfigFetcher.java | 73 -- .../microvisor/v1/AccountConfigReader.java | 135 --- .../rest/microvisor/v1/AccountSecret.java | 160 ---- .../microvisor/v1/AccountSecretCreator.java | 95 --- .../microvisor/v1/AccountSecretDeleter.java | 69 -- .../microvisor/v1/AccountSecretReader.java | 135 --- .../com/twilio/rest/microvisor/v1/App.java | 197 ----- .../twilio/rest/microvisor/v1/AppDeleter.java | 69 -- .../twilio/rest/microvisor/v1/AppFetcher.java | 70 -- .../twilio/rest/microvisor/v1/AppReader.java | 135 --- .../com/twilio/rest/microvisor/v1/Device.java | 206 ----- .../rest/microvisor/v1/DeviceUpdater.java | 109 --- .../microvisor/v1/app/AppManifestFetcher.java | 73 -- .../microvisor/v1/device/DeviceConfig.java | 184 ---- .../v1/device/DeviceConfigCreator.java | 106 --- .../v1/device/DeviceConfigReader.java | 143 ---- .../v1/device/DeviceConfigUpdater.java | 98 --- .../microvisor/v1/device/DeviceSecret.java | 176 ---- .../v1/device/DeviceSecretCreator.java | 106 --- .../v1/device/DeviceSecretFetcher.java | 83 -- .../v1/device/DeviceSecretReader.java | 143 ---- .../v1/device/DeviceSecretUpdater.java | 98 --- .../com/twilio/rest/notify/v1/Credential.java | 8 +- .../rest/notify/v1/service/Binding.java | 2 +- .../rest/notify/v1/service/Notification.java | 6 +- .../rest/numbers/v1/PortingPortability.java | 8 +- .../v1/PortingWebhookConfigurationDelete.java | 2 +- ...okConfigurationFetch.java => Webhook.java} | 33 +- ...nFetchFetcher.java => WebhookFetcher.java} | 16 +- .../numbers/v2/AuthorizationDocument.java | 6 +- .../numbers/v2/BulkHostedNumberOrder.java | 8 +- .../twilio/rest/numbers/v2/BundleClone.java | 6 +- .../rest/numbers/v2/HostedNumberOrder.java | 14 +- .../DependentHostedNumberOrder.java | 6 +- .../v2/regulatorycompliance/Bundle.java | 6 +- .../v2/regulatorycompliance/EndUser.java | 8 +- .../v2/regulatorycompliance/Regulation.java | 6 +- .../SupportingDocument.java | 6 +- .../bundle/BundleCopy.java | 6 +- .../bundle/Evaluation.java | 6 +- .../bundle/ReplaceItems.java | 6 +- .../hostedNumbers/AuthorizationDocument.java | 6 +- .../hostedNumbers/HostedNumberOrder.java | 12 +- .../DependentHostedNumberOrder.java | 12 +- .../previewiam/organizations/Account.java | 6 +- .../organizations/RoleAssignment.java | 2 +- .../rest/previewiam/organizations/User.java | 4 +- .../rest/pricing/v1/messaging/Country.java | 2 +- .../rest/pricing/v1/phonenumber/Country.java | 2 +- .../twilio/rest/pricing/v1/voice/Country.java | 2 +- .../twilio/rest/pricing/v1/voice/Number.java | 2 +- .../com/twilio/rest/pricing/v2/Country.java | 2 +- .../com/twilio/rest/pricing/v2/Number.java | 2 +- .../twilio/rest/pricing/v2/voice/Country.java | 2 +- .../twilio/rest/pricing/v2/voice/Number.java | 2 +- .../com/twilio/rest/proxy/v1/Service.java | 14 +- .../twilio/rest/proxy/v1/service/Session.java | 12 +- .../rest/proxy/v1/service/SessionCreator.java | 3 +- .../rest/proxy/v1/service/ShortCode.java | 236 ------ .../proxy/v1/service/ShortCodeDeleter.java | 76 -- .../proxy/v1/service/ShortCodeReader.java | 143 ---- .../proxy/v1/service/ShortCodeUpdater.java | 92 -- .../proxy/v1/service/session/Interaction.java | 18 +- .../participant/MessageInteraction.java | 18 +- .../rest/serverless/v1/service/Build.java | 12 +- .../v1/service/asset/AssetVersion.java | 6 +- .../v1/service/build/BuildStatus.java | 6 +- .../v1/service/function/FunctionVersion.java | 6 +- .../java/com/twilio/rest/studio/v1/Flow.java | 6 +- .../rest/studio/v1/flow/Engagement.java | 6 +- .../twilio/rest/studio/v1/flow/Execution.java | 8 +- .../java/com/twilio/rest/studio/v2/Flow.java | 10 +- .../twilio/rest/studio/v2/FlowValidate.java | 2 +- .../twilio/rest/studio/v2/flow/Execution.java | 8 +- .../rest/studio/v2/flow/FlowRevision.java | 6 +- .../twilio/rest/supersim/v1/EsimProfile.java | 6 +- .../com/twilio/rest/supersim/v1/Fleet.java | 6 +- .../twilio/rest/supersim/v1/IpCommand.java | 18 +- .../rest/supersim/v1/SettingsUpdate.java | 6 +- .../java/com/twilio/rest/supersim/v1/Sim.java | 6 +- .../twilio/rest/supersim/v1/SmsCommand.java | 12 +- .../twilio/rest/supersim/v1/UsageRecord.java | 2 +- .../rest/supersim/v1/sim/BillingPeriod.java | 6 +- .../rest/supersim/v1/sim/SimIpAddress.java | 6 +- .../rest/sync/v1/service/DocumentCreator.java | 8 +- .../rest/sync/v1/service/DocumentUpdater.java | 7 +- .../v1/service/synclist/SyncListItem.java | 2 +- .../service/synclist/SyncListItemCreator.java | 10 +- .../service/synclist/SyncListItemUpdater.java | 7 +- .../sync/v1/service/syncmap/SyncMapItem.java | 2 +- .../service/syncmap/SyncMapItemCreator.java | 10 +- .../service/syncmap/SyncMapItemUpdater.java | 7 +- .../v1/service/syncstream/StreamMessage.java | 2 +- .../syncstream/StreamMessageCreator.java | 10 +- .../twilio/rest/taskrouter/v1/Workspace.java | 6 +- .../rest/taskrouter/v1/workspace/Task.java | 6 +- .../taskrouter/v1/workspace/TaskQueue.java | 6 +- .../v1/workspace/task/Reservation.java | 8 +- .../v1/workspace/worker/Reservation.java | 8 +- .../com/twilio/rest/trunking/v1/Trunk.java | 25 +- .../rest/trunking/v1/trunk/PhoneNumber.java | 6 +- .../rest/trunking/v1/trunk/Recording.java | 12 +- .../v1/ComplianceRegistrationInquiries.java | 4 +- .../rest/trusthub/v1/CustomerProfiles.java | 6 +- .../rest/trusthub/v1/SupportingDocument.java | 6 +- .../rest/trusthub/v1/TrustProducts.java | 6 +- .../CustomerProfilesEvaluations.java | 6 +- .../TrustProductsEvaluations.java | 6 +- .../java/com/twilio/rest/verify/v2/Form.java | 8 +- .../rest/verify/v2/VerificationAttempt.java | 15 +- .../v2/VerificationAttemptsSummary.java | 3 +- .../rest/verify/v2/service/AccessToken.java | 8 +- .../rest/verify/v2/service/Verification.java | 8 +- .../verify/v2/service/VerificationCheck.java | 6 +- .../rest/verify/v2/service/Webhook.java | 18 +- .../verify/v2/service/entity/Challenge.java | 18 +- .../rest/verify/v2/service/entity/Factor.java | 12 +- .../verify/v2/service/entity/NewFactor.java | 14 +- .../com/twilio/rest/video/v1/Composition.java | 12 +- .../twilio/rest/video/v1/CompositionHook.java | 6 +- .../com/twilio/rest/video/v1/Recording.java | 26 +- .../java/com/twilio/rest/video/v1/Room.java | 20 +- .../rest/video/v1/room/Participant.java | 6 +- .../rest/video/v1/room/RoomRecording.java | 26 +- .../rest/video/v1/room/Transcriptions.java | 255 ++++++ .../v1/room/TranscriptionsCreator.java} | 49 +- .../v1/room/TranscriptionsFetcher.java} | 30 +- .../v1/room/TranscriptionsReader.java} | 44 +- .../v1/room/TranscriptionsUpdater.java} | 42 +- .../video/v1/room/participant/Anonymize.java | 6 +- .../v1/room/participant/PublishedTrack.java | 6 +- .../v1/room/participant/SubscribedTrack.java | 6 +- .../com/twilio/rest/wireless/v1/Command.java | 24 +- .../java/com/twilio/rest/wireless/v1/Sim.java | 12 +- .../java/com/twilio/twiml/voice/Dial.java | 9 + .../java/com/twilio/twiml/voice/WhatsApp.java | 299 +++++++ .../java/com/twilio/twiml/voice/DialTest.java | 18 + .../com/twilio/twiml/voice/WhatsAppTest.java | 54 ++ 280 files changed, 3437 insertions(+), 5960 deletions(-) delete mode 100644 src/main/java/com/twilio/rest/knowledge/v1/Knowledge.java delete mode 100644 src/main/java/com/twilio/rest/knowledge/v1/KnowledgeDeleter.java delete mode 100644 src/main/java/com/twilio/rest/knowledge/v1/KnowledgeFetcher.java delete mode 100644 src/main/java/com/twilio/rest/knowledge/v1/KnowledgeReader.java delete mode 100644 src/main/java/com/twilio/rest/knowledge/v1/knowledge/Chunk.java delete mode 100644 src/main/java/com/twilio/rest/knowledge/v1/knowledge/ChunkReader.java delete mode 100644 src/main/java/com/twilio/rest/knowledge/v1/knowledge/KnowledgeStatus.java delete mode 100644 src/main/java/com/twilio/rest/knowledge/v1/knowledge/KnowledgeStatusFetcher.java create mode 100644 src/main/java/com/twilio/rest/lookups/v2/Bucket.java rename src/main/java/com/twilio/rest/{microvisor/v1/AccountConfigDeleter.java => lookups/v2/BucketDeleter.java} (73%) rename src/main/java/com/twilio/rest/{microvisor/v1/DeviceFetcher.java => lookups/v2/BucketFetcher.java} (69%) rename src/main/java/com/twilio/rest/{microvisor/v1/AccountConfigUpdater.java => lookups/v2/BucketUpdater.java} (53%) create mode 100644 src/main/java/com/twilio/rest/lookups/v2/LookupOverride.java rename src/main/java/com/twilio/rest/{knowledge/v1/KnowledgeCreator.java => lookups/v2/LookupOverrideCreator.java} (61%) rename src/main/java/com/twilio/rest/{microvisor/v1/device/DeviceConfigDeleter.java => lookups/v2/LookupOverrideDeleter.java} (71%) rename src/main/java/com/twilio/rest/{microvisor/v1/device/DeviceConfigFetcher.java => lookups/v2/LookupOverrideFetcher.java} (68%) rename src/main/java/com/twilio/rest/{knowledge/v1/KnowledgeUpdater.java => lookups/v2/LookupOverrideUpdater.java} (63%) create mode 100644 src/main/java/com/twilio/rest/lookups/v2/Query.java rename src/main/java/com/twilio/rest/{microvisor/v1/device/DeviceSecretDeleter.java => lookups/v2/QueryCreator.java} (58%) rename src/main/java/com/twilio/rest/{microvisor/v1/app/AppManifest.java => lookups/v2/RateLimit.java} (52%) rename src/main/java/com/twilio/rest/{proxy/v1/service/ShortCodeFetcher.java => lookups/v2/RateLimitFetcher.java} (65%) delete mode 100644 src/main/java/com/twilio/rest/microvisor/v1/AccountConfig.java delete mode 100644 src/main/java/com/twilio/rest/microvisor/v1/AccountConfigCreator.java delete mode 100644 src/main/java/com/twilio/rest/microvisor/v1/AccountConfigFetcher.java delete mode 100644 src/main/java/com/twilio/rest/microvisor/v1/AccountConfigReader.java delete mode 100644 src/main/java/com/twilio/rest/microvisor/v1/AccountSecret.java delete mode 100644 src/main/java/com/twilio/rest/microvisor/v1/AccountSecretCreator.java delete mode 100644 src/main/java/com/twilio/rest/microvisor/v1/AccountSecretDeleter.java delete mode 100644 src/main/java/com/twilio/rest/microvisor/v1/AccountSecretReader.java delete mode 100644 src/main/java/com/twilio/rest/microvisor/v1/App.java delete mode 100644 src/main/java/com/twilio/rest/microvisor/v1/AppDeleter.java delete mode 100644 src/main/java/com/twilio/rest/microvisor/v1/AppFetcher.java delete mode 100644 src/main/java/com/twilio/rest/microvisor/v1/AppReader.java delete mode 100644 src/main/java/com/twilio/rest/microvisor/v1/Device.java delete mode 100644 src/main/java/com/twilio/rest/microvisor/v1/DeviceUpdater.java delete mode 100644 src/main/java/com/twilio/rest/microvisor/v1/app/AppManifestFetcher.java delete mode 100644 src/main/java/com/twilio/rest/microvisor/v1/device/DeviceConfig.java delete mode 100644 src/main/java/com/twilio/rest/microvisor/v1/device/DeviceConfigCreator.java delete mode 100644 src/main/java/com/twilio/rest/microvisor/v1/device/DeviceConfigReader.java delete mode 100644 src/main/java/com/twilio/rest/microvisor/v1/device/DeviceConfigUpdater.java delete mode 100644 src/main/java/com/twilio/rest/microvisor/v1/device/DeviceSecret.java delete mode 100644 src/main/java/com/twilio/rest/microvisor/v1/device/DeviceSecretCreator.java delete mode 100644 src/main/java/com/twilio/rest/microvisor/v1/device/DeviceSecretFetcher.java delete mode 100644 src/main/java/com/twilio/rest/microvisor/v1/device/DeviceSecretReader.java delete mode 100644 src/main/java/com/twilio/rest/microvisor/v1/device/DeviceSecretUpdater.java rename src/main/java/com/twilio/rest/numbers/v1/{PortingWebhookConfigurationFetch.java => Webhook.java} (82%) rename src/main/java/com/twilio/rest/numbers/v1/{PortingWebhookConfigurationFetchFetcher.java => WebhookFetcher.java} (79%) delete mode 100644 src/main/java/com/twilio/rest/proxy/v1/service/ShortCode.java delete mode 100644 src/main/java/com/twilio/rest/proxy/v1/service/ShortCodeDeleter.java delete mode 100644 src/main/java/com/twilio/rest/proxy/v1/service/ShortCodeReader.java delete mode 100644 src/main/java/com/twilio/rest/proxy/v1/service/ShortCodeUpdater.java create mode 100644 src/main/java/com/twilio/rest/video/v1/room/Transcriptions.java rename src/main/java/com/twilio/rest/{proxy/v1/service/ShortCodeCreator.java => video/v1/room/TranscriptionsCreator.java} (63%) rename src/main/java/com/twilio/rest/{microvisor/v1/AccountSecretFetcher.java => video/v1/room/TranscriptionsFetcher.java} (69%) rename src/main/java/com/twilio/rest/{microvisor/v1/DeviceReader.java => video/v1/room/TranscriptionsReader.java} (72%) rename src/main/java/com/twilio/rest/{microvisor/v1/AccountSecretUpdater.java => video/v1/room/TranscriptionsUpdater.java} (64%) create mode 100644 src/main/java/com/twilio/twiml/voice/WhatsApp.java create mode 100644 src/test/java/com/twilio/twiml/voice/WhatsAppTest.java diff --git a/CHANGES.md b/CHANGES.md index 22a5fd150c..9ef65ffab7 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,6 +1,35 @@ twilio-java changelog ===================== +[2025-07-03] Version 11.0.0-rc.1 +-------------------------------- +**Library - Chore** +- [PR #875](https://github.com/twilio/twilio-java/pull/875): prepare for RC release. Thanks to [@tiwarishubham635](https://github.com/tiwarishubham635)! +- [PR #874](https://github.com/twilio/twilio-java/pull/874): Handle List serialization. Thanks to [@tiwarishubham635](https://github.com/tiwarishubham635)! +- [PR #873](https://github.com/twilio/twilio-java/pull/873): use Object for anyType. Thanks to [@tiwarishubham635](https://github.com/tiwarishubham635)! + +**Bulkexports** +- Changed the type of 'details' field to be a list of objects instead of a single object + +**Conversations** +- Updates to `method` casing for ConfgurationAddress, ConversationScopedWebhook, and ServiceConversationScopedWebhook for RestProxy compatibility + +**Proxy** +- remove shortcodes resource as its no longer used + +**Serverless** +- Change log field level from type `ienum` to `string` in Logs api + +**Taskrouter** +- Remove `URL-encoded` from attributes param definition in tasks + +**Trunking** +- Added `symmetric_rtp_enabled` property on Trunks. + +**Twiml** +- Add support for `` noun under `` verb + + [2025-07-03] Version 11.0.0-rc.0 -------------------------------- - Release Candidate prep diff --git a/src/main/java/com/twilio/Domains.java b/src/main/java/com/twilio/Domains.java index 956b8080b9..2baa605f57 100644 --- a/src/main/java/com/twilio/Domains.java +++ b/src/main/java/com/twilio/Domains.java @@ -26,11 +26,9 @@ public enum Domains { INSIGHTS("insights"), INTELLIGENCE("intelligence"), IPMESSAGING("ip-messaging"), - KNOWLEDGE("knowledge"), LOOKUPS("lookups"), MARKETPLACE("marketplace"), MESSAGING("messaging"), - MICROVISOR("microvisor"), MONITOR("monitor"), NOTIFY("notify"), NUMBERS("numbers"), diff --git a/src/main/java/com/twilio/rest/accounts/v1/BulkConsentsCreator.java b/src/main/java/com/twilio/rest/accounts/v1/BulkConsentsCreator.java index b472c75f67..1155c9fd32 100644 --- a/src/main/java/com/twilio/rest/accounts/v1/BulkConsentsCreator.java +++ b/src/main/java/com/twilio/rest/accounts/v1/BulkConsentsCreator.java @@ -15,8 +15,9 @@ package com.twilio.rest.accounts.v1; import com.twilio.base.Creator; -import com.twilio.converter.Converter; import com.twilio.constant.EnumConstants; +import com.twilio.converter.Converter; +import com.twilio.converter.Converter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; diff --git a/src/main/java/com/twilio/rest/accounts/v1/BulkContactsCreator.java b/src/main/java/com/twilio/rest/accounts/v1/BulkContactsCreator.java index abbd29d480..7dc970c184 100644 --- a/src/main/java/com/twilio/rest/accounts/v1/BulkContactsCreator.java +++ b/src/main/java/com/twilio/rest/accounts/v1/BulkContactsCreator.java @@ -17,6 +17,7 @@ import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; import com.twilio.converter.Converter; +import com.twilio.converter.Converter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; diff --git a/src/main/java/com/twilio/rest/api/v2010/Account.java b/src/main/java/com/twilio/rest/api/v2010/Account.java index 814acb9477..7ab47a5b18 100644 --- a/src/main/java/com/twilio/rest/api/v2010/Account.java +++ b/src/main/java/com/twilio/rest/api/v2010/Account.java @@ -113,9 +113,9 @@ public static Account fromJson( private final String friendlyName; private final String ownerAccountSid; private final String sid; - private final Status status; + private final Account.Status status; private final Map subresourceUris; - private final Type type; + private final Account.Type type; private final String uri; @JsonCreator @@ -126,12 +126,12 @@ private Account( @JsonProperty("friendly_name") final String friendlyName, @JsonProperty("owner_account_sid") final String ownerAccountSid, @JsonProperty("sid") final String sid, - @JsonProperty("status") final Status status, + @JsonProperty("status") final Account.Status status, @JsonProperty("subresource_uris") final Map< String, String > subresourceUris, - @JsonProperty("type") final Type type, + @JsonProperty("type") final Account.Type type, @JsonProperty("uri") final String uri ) { this.authToken = authToken; @@ -170,7 +170,7 @@ public final String getSid() { return this.sid; } - public final Status getStatus() { + public final Account.Status getStatus() { return this.status; } @@ -178,7 +178,7 @@ public final Map getSubresourceUris() { return this.subresourceUris; } - public final Type getType() { + public final Account.Type getType() { return this.type; } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/AuthorizedConnectApp.java b/src/main/java/com/twilio/rest/api/v2010/account/AuthorizedConnectApp.java index a58a35511e..f7e1d9f67f 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/AuthorizedConnectApp.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/AuthorizedConnectApp.java @@ -113,7 +113,7 @@ public static AuthorizedConnectApp fromJson( private final String connectAppFriendlyName; private final URI connectAppHomepageUrl; private final String connectAppSid; - private final List permissions; + private final List permissions; private final String uri; @JsonCreator @@ -132,7 +132,9 @@ private AuthorizedConnectApp( "connect_app_homepage_url" ) final URI connectAppHomepageUrl, @JsonProperty("connect_app_sid") final String connectAppSid, - @JsonProperty("permissions") final List permissions, + @JsonProperty("permissions") final List< + AuthorizedConnectApp.Permission + > permissions, @JsonProperty("uri") final String uri ) { this.accountSid = accountSid; @@ -169,7 +171,7 @@ public final String getConnectAppSid() { return this.connectAppSid; } - public final List getPermissions() { + public final List getPermissions() { return this.permissions; } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/Call.java b/src/main/java/com/twilio/rest/api/v2010/account/Call.java index 59e9b2a099..8eaf7c203d 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/Call.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/Call.java @@ -189,7 +189,7 @@ public static Call fromJson( private final String from; private final String fromFormatted; private final String phoneNumberSid; - private final Status status; + private final Call.Status status; private final ZonedDateTime startTime; private final ZonedDateTime endTime; private final String duration; @@ -218,13 +218,13 @@ private Call( @JsonProperty("from") final String from, @JsonProperty("from_formatted") final String fromFormatted, @JsonProperty("phone_number_sid") final String phoneNumberSid, - @JsonProperty("status") final Status status, + @JsonProperty("status") final Call.Status status, @JsonProperty("start_time") final String startTime, @JsonProperty("end_time") final String endTime, @JsonProperty("duration") final String duration, @JsonProperty("price") final String price, @JsonProperty("price_unit") @JsonDeserialize( - using = CurrencyDeserializer.class + using = com.twilio.converter.CurrencyDeserializer.class ) final Currency priceUnit, @JsonProperty("direction") final String direction, @JsonProperty("answered_by") final String answeredBy, @@ -308,7 +308,7 @@ public final String getPhoneNumberSid() { return this.phoneNumberSid; } - public final Status getStatus() { + public final Call.Status getStatus() { return this.status; } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/Conference.java b/src/main/java/com/twilio/rest/api/v2010/account/Conference.java index a35e39b51c..bcb13ce3df 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/Conference.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/Conference.java @@ -120,10 +120,10 @@ public static Conference fromJson( private final String friendlyName; private final String region; private final String sid; - private final Status status; + private final Conference.Status status; private final String uri; private final Map subresourceUris; - private final ReasonConferenceEnded reasonConferenceEnded; + private final Conference.ReasonConferenceEnded reasonConferenceEnded; private final String callSidEndingConference; @JsonCreator @@ -135,7 +135,7 @@ private Conference( @JsonProperty("friendly_name") final String friendlyName, @JsonProperty("region") final String region, @JsonProperty("sid") final String sid, - @JsonProperty("status") final Status status, + @JsonProperty("status") final Conference.Status status, @JsonProperty("uri") final String uri, @JsonProperty("subresource_uris") final Map< String, @@ -143,7 +143,7 @@ private Conference( > subresourceUris, @JsonProperty( "reason_conference_ended" - ) final ReasonConferenceEnded reasonConferenceEnded, + ) final Conference.ReasonConferenceEnded reasonConferenceEnded, @JsonProperty( "call_sid_ending_conference" ) final String callSidEndingConference @@ -190,7 +190,7 @@ public final String getSid() { return this.sid; } - public final Status getStatus() { + public final Conference.Status getStatus() { return this.status; } @@ -202,7 +202,7 @@ public final Map getSubresourceUris() { return this.subresourceUris; } - public final ReasonConferenceEnded getReasonConferenceEnded() { + public final Conference.ReasonConferenceEnded getReasonConferenceEnded() { return this.reasonConferenceEnded; } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/ConnectApp.java b/src/main/java/com/twilio/rest/api/v2010/account/ConnectApp.java index da84d010e6..64e5e6198c 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/ConnectApp.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/ConnectApp.java @@ -131,7 +131,7 @@ public static ConnectApp fromJson( private final String description; private final String friendlyName; private final URI homepageUrl; - private final List permissions; + private final List permissions; private final String sid; private final String uri; @@ -149,7 +149,9 @@ private ConnectApp( @JsonProperty("description") final String description, @JsonProperty("friendly_name") final String friendlyName, @JsonProperty("homepage_url") final URI homepageUrl, - @JsonProperty("permissions") final List permissions, + @JsonProperty("permissions") final List< + ConnectApp.Permission + > permissions, @JsonProperty("sid") final String sid, @JsonProperty("uri") final String uri ) { @@ -198,7 +200,7 @@ public final URI getHomepageUrl() { return this.homepageUrl; } - public final List getPermissions() { + public final List getPermissions() { return this.permissions; } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/IncomingPhoneNumber.java b/src/main/java/com/twilio/rest/api/v2010/account/IncomingPhoneNumber.java index f59bdac73f..6c202374e5 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/IncomingPhoneNumber.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/IncomingPhoneNumber.java @@ -153,7 +153,7 @@ public static IncomingPhoneNumber fromJson( private final String accountSid; private final String addressSid; - private final AddressRequirement addressRequirements; + private final IncomingPhoneNumber.AddressRequirement addressRequirements; private final String apiVersion; private final Boolean beta; private final PhoneNumberCapabilities capabilities; @@ -173,16 +173,16 @@ public static IncomingPhoneNumber fromJson( private final HttpMethod statusCallbackMethod; private final String trunkSid; private final String uri; - private final VoiceReceiveMode voiceReceiveMode; + private final IncomingPhoneNumber.VoiceReceiveMode voiceReceiveMode; private final String voiceApplicationSid; private final Boolean voiceCallerIdLookup; private final HttpMethod voiceFallbackMethod; private final URI voiceFallbackUrl; private final HttpMethod voiceMethod; private final URI voiceUrl; - private final EmergencyStatus emergencyStatus; + private final IncomingPhoneNumber.EmergencyStatus emergencyStatus; private final String emergencyAddressSid; - private final EmergencyAddressStatus emergencyAddressStatus; + private final IncomingPhoneNumber.EmergencyAddressStatus emergencyAddressStatus; private final String bundleSid; private final String status; @@ -192,7 +192,7 @@ private IncomingPhoneNumber( @JsonProperty("address_sid") final String addressSid, @JsonProperty( "address_requirements" - ) final AddressRequirement addressRequirements, + ) final IncomingPhoneNumber.AddressRequirement addressRequirements, @JsonProperty("api_version") final String apiVersion, @JsonProperty("beta") final Boolean beta, @JsonProperty( @@ -220,7 +220,7 @@ private IncomingPhoneNumber( @JsonProperty("uri") final String uri, @JsonProperty( "voice_receive_mode" - ) final VoiceReceiveMode voiceReceiveMode, + ) final IncomingPhoneNumber.VoiceReceiveMode voiceReceiveMode, @JsonProperty("voice_application_sid") final String voiceApplicationSid, @JsonProperty( "voice_caller_id_lookup" @@ -231,11 +231,13 @@ private IncomingPhoneNumber( @JsonProperty("voice_fallback_url") final URI voiceFallbackUrl, @JsonProperty("voice_method") final HttpMethod voiceMethod, @JsonProperty("voice_url") final URI voiceUrl, - @JsonProperty("emergency_status") final EmergencyStatus emergencyStatus, + @JsonProperty( + "emergency_status" + ) final IncomingPhoneNumber.EmergencyStatus emergencyStatus, @JsonProperty("emergency_address_sid") final String emergencyAddressSid, @JsonProperty( "emergency_address_status" - ) final EmergencyAddressStatus emergencyAddressStatus, + ) final IncomingPhoneNumber.EmergencyAddressStatus emergencyAddressStatus, @JsonProperty("bundle_sid") final String bundleSid, @JsonProperty("status") final String status ) { @@ -283,7 +285,7 @@ public final String getAddressSid() { return this.addressSid; } - public final AddressRequirement getAddressRequirements() { + public final IncomingPhoneNumber.AddressRequirement getAddressRequirements() { return this.addressRequirements; } @@ -363,7 +365,7 @@ public final String getUri() { return this.uri; } - public final VoiceReceiveMode getVoiceReceiveMode() { + public final IncomingPhoneNumber.VoiceReceiveMode getVoiceReceiveMode() { return this.voiceReceiveMode; } @@ -391,7 +393,7 @@ public final URI getVoiceUrl() { return this.voiceUrl; } - public final EmergencyStatus getEmergencyStatus() { + public final IncomingPhoneNumber.EmergencyStatus getEmergencyStatus() { return this.emergencyStatus; } @@ -399,7 +401,7 @@ public final String getEmergencyAddressSid() { return this.emergencyAddressSid; } - public final EmergencyAddressStatus getEmergencyAddressStatus() { + public final IncomingPhoneNumber.EmergencyAddressStatus getEmergencyAddressStatus() { return this.emergencyAddressStatus; } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/Message.java b/src/main/java/com/twilio/rest/api/v2010/account/Message.java index dce011b3df..548b52b068 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/Message.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/Message.java @@ -209,7 +209,7 @@ public static Message fromJson( private final String body; private final String numSegments; - private final Direction direction; + private final Message.Direction direction; private final com.twilio.type.PhoneNumber from; private final String to; private final ZonedDateTime dateUpdated; @@ -218,7 +218,7 @@ public static Message fromJson( private final String uri; private final String accountSid; private final String numMedia; - private final Status status; + private final Message.Status status; private final String messagingServiceSid; private final String sid; private final ZonedDateTime dateSent; @@ -232,7 +232,7 @@ public static Message fromJson( private Message( @JsonProperty("body") final String body, @JsonProperty("num_segments") final String numSegments, - @JsonProperty("direction") final Direction direction, + @JsonProperty("direction") final Message.Direction direction, @JsonProperty("from") final com.twilio.type.PhoneNumber from, @JsonProperty("to") final String to, @JsonProperty("date_updated") final String dateUpdated, @@ -241,14 +241,14 @@ private Message( @JsonProperty("uri") final String uri, @JsonProperty("account_sid") final String accountSid, @JsonProperty("num_media") final String numMedia, - @JsonProperty("status") final Status status, + @JsonProperty("status") final Message.Status status, @JsonProperty("messaging_service_sid") final String messagingServiceSid, @JsonProperty("sid") final String sid, @JsonProperty("date_sent") final String dateSent, @JsonProperty("date_created") final String dateCreated, @JsonProperty("error_code") final Integer errorCode, @JsonProperty("price_unit") @JsonDeserialize( - using = CurrencyDeserializer.class + using = com.twilio.converter.CurrencyDeserializer.class ) final Currency priceUnit, @JsonProperty("api_version") final String apiVersion, @JsonProperty("subresource_uris") final Map< @@ -286,7 +286,7 @@ public final String getNumSegments() { return this.numSegments; } - public final Direction getDirection() { + public final Message.Direction getDirection() { return this.direction; } @@ -322,7 +322,7 @@ public final String getNumMedia() { return this.numMedia; } - public final Status getStatus() { + public final Message.Status getStatus() { return this.status; } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/Recording.java b/src/main/java/com/twilio/rest/api/v2010/account/Recording.java index e36eee0d13..88e79667f7 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/Recording.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/Recording.java @@ -125,9 +125,9 @@ public static Recording fromJson( private final String sid; private final String price; private final String priceUnit; - private final Status status; + private final Recording.Status status; private final Integer channels; - private final Source source; + private final Recording.Source source; private final Integer errorCode; private final String uri; private final Map encryptionDetails; @@ -147,9 +147,9 @@ private Recording( @JsonProperty("sid") final String sid, @JsonProperty("price") final String price, @JsonProperty("price_unit") final String priceUnit, - @JsonProperty("status") final Status status, + @JsonProperty("status") final Recording.Status status, @JsonProperty("channels") final Integer channels, - @JsonProperty("source") final Source source, + @JsonProperty("source") final Recording.Source source, @JsonProperty("error_code") final Integer errorCode, @JsonProperty("uri") final String uri, @JsonProperty("encryption_details") final Map< @@ -227,7 +227,7 @@ public final String getPriceUnit() { return this.priceUnit; } - public final Status getStatus() { + public final Recording.Status getStatus() { return this.status; } @@ -235,7 +235,7 @@ public final Integer getChannels() { return this.channels; } - public final Source getSource() { + public final Recording.Source getSource() { return this.source; } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/Transcription.java b/src/main/java/com/twilio/rest/api/v2010/account/Transcription.java index e801e42350..a9525ed472 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/Transcription.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/Transcription.java @@ -124,7 +124,7 @@ public static Transcription fromJson( private final Currency priceUnit; private final String recordingSid; private final String sid; - private final Status status; + private final Transcription.Status status; private final String transcriptionText; private final String type; private final String uri; @@ -138,11 +138,11 @@ private Transcription( @JsonProperty("duration") final String duration, @JsonProperty("price") final BigDecimal price, @JsonProperty("price_unit") @JsonDeserialize( - using = CurrencyDeserializer.class + using = com.twilio.converter.CurrencyDeserializer.class ) final Currency priceUnit, @JsonProperty("recording_sid") final String recordingSid, @JsonProperty("sid") final String sid, - @JsonProperty("status") final Status status, + @JsonProperty("status") final Transcription.Status status, @JsonProperty("transcription_text") final String transcriptionText, @JsonProperty("type") final String type, @JsonProperty("uri") final String uri @@ -198,7 +198,7 @@ public final String getSid() { return this.sid; } - public final Status getStatus() { + public final Transcription.Status getStatus() { return this.status; } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/address/DependentPhoneNumber.java b/src/main/java/com/twilio/rest/api/v2010/account/address/DependentPhoneNumber.java index ff8e7f4f78..3c65422d55 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/address/DependentPhoneNumber.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/address/DependentPhoneNumber.java @@ -113,7 +113,7 @@ public static DependentPhoneNumber fromJson( private final URI smsFallbackUrl; private final HttpMethod smsMethod; private final URI smsUrl; - private final AddressRequirement addressRequirements; + private final DependentPhoneNumber.AddressRequirement addressRequirements; private final Map capabilities; private final URI statusCallback; private final HttpMethod statusCallbackMethod; @@ -121,7 +121,7 @@ public static DependentPhoneNumber fromJson( private final String smsApplicationSid; private final String voiceApplicationSid; private final String trunkSid; - private final EmergencyStatus emergencyStatus; + private final DependentPhoneNumber.EmergencyStatus emergencyStatus; private final String emergencyAddressSid; private final String uri; @@ -150,7 +150,7 @@ private DependentPhoneNumber( @JsonProperty("sms_url") final URI smsUrl, @JsonProperty( "address_requirements" - ) final AddressRequirement addressRequirements, + ) final DependentPhoneNumber.AddressRequirement addressRequirements, @JsonProperty("capabilities") final Map capabilities, @JsonProperty("status_callback") final URI statusCallback, @JsonProperty( @@ -160,7 +160,9 @@ private DependentPhoneNumber( @JsonProperty("sms_application_sid") final String smsApplicationSid, @JsonProperty("voice_application_sid") final String voiceApplicationSid, @JsonProperty("trunk_sid") final String trunkSid, - @JsonProperty("emergency_status") final EmergencyStatus emergencyStatus, + @JsonProperty( + "emergency_status" + ) final DependentPhoneNumber.EmergencyStatus emergencyStatus, @JsonProperty("emergency_address_sid") final String emergencyAddressSid, @JsonProperty("uri") final String uri ) { @@ -252,7 +254,7 @@ public final URI getSmsUrl() { return this.smsUrl; } - public final AddressRequirement getAddressRequirements() { + public final DependentPhoneNumber.AddressRequirement getAddressRequirements() { return this.addressRequirements; } @@ -284,7 +286,7 @@ public final String getTrunkSid() { return this.trunkSid; } - public final EmergencyStatus getEmergencyStatus() { + public final DependentPhoneNumber.EmergencyStatus getEmergencyStatus() { return this.emergencyStatus; } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/call/Recording.java b/src/main/java/com/twilio/rest/api/v2010/account/call/Recording.java index 23d275246f..12054b2b44 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/call/Recording.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/call/Recording.java @@ -99,7 +99,7 @@ public static RecordingReader reader( public static RecordingUpdater updater( final String pathCallSid, final String pathSid, - final Status status + final Recording.Status status ) { return new RecordingUpdater(pathCallSid, pathSid, status); } @@ -108,7 +108,7 @@ public static RecordingUpdater updater( final String pathAccountSid, final String pathCallSid, final String pathSid, - final Status status + final Recording.Status status ) { return new RecordingUpdater( pathAccountSid, @@ -174,9 +174,9 @@ public static Recording fromJson( private final String uri; private final Map encryptionDetails; private final Currency priceUnit; - private final Status status; + private final Recording.Status status; private final Integer channels; - private final Source source; + private final Recording.Source source; private final Integer errorCode; private final String track; @@ -198,11 +198,11 @@ private Recording( Object > encryptionDetails, @JsonProperty("price_unit") @JsonDeserialize( - using = CurrencyDeserializer.class + using = com.twilio.converter.CurrencyDeserializer.class ) final Currency priceUnit, - @JsonProperty("status") final Status status, + @JsonProperty("status") final Recording.Status status, @JsonProperty("channels") final Integer channels, - @JsonProperty("source") final Source source, + @JsonProperty("source") final Recording.Source source, @JsonProperty("error_code") final Integer errorCode, @JsonProperty("track") final String track ) { @@ -278,7 +278,7 @@ public final Currency getPriceUnit() { return this.priceUnit; } - public final Status getStatus() { + public final Recording.Status getStatus() { return this.status; } @@ -286,7 +286,7 @@ public final Integer getChannels() { return this.channels; } - public final Source getSource() { + public final Recording.Source getSource() { return this.source; } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/call/Siprec.java b/src/main/java/com/twilio/rest/api/v2010/account/call/Siprec.java index 87912457a3..376b870d65 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/call/Siprec.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/call/Siprec.java @@ -52,7 +52,7 @@ public static SiprecCreator creator( public static SiprecUpdater updater( final String pathCallSid, final String pathSid, - final UpdateStatus status + final Siprec.UpdateStatus status ) { return new SiprecUpdater(pathCallSid, pathSid, status); } @@ -61,7 +61,7 @@ public static SiprecUpdater updater( final String pathAccountSid, final String pathCallSid, final String pathSid, - final UpdateStatus status + final Siprec.UpdateStatus status ) { return new SiprecUpdater(pathAccountSid, pathCallSid, pathSid, status); } @@ -113,7 +113,7 @@ public static Siprec fromJson( private final String accountSid; private final String callSid; private final String name; - private final Status status; + private final Siprec.Status status; private final ZonedDateTime dateUpdated; private final String uri; @@ -123,7 +123,7 @@ private Siprec( @JsonProperty("account_sid") final String accountSid, @JsonProperty("call_sid") final String callSid, @JsonProperty("name") final String name, - @JsonProperty("status") final Status status, + @JsonProperty("status") final Siprec.Status status, @JsonProperty("date_updated") final String dateUpdated, @JsonProperty("uri") final String uri ) { @@ -152,7 +152,7 @@ public final String getName() { return this.name; } - public final Status getStatus() { + public final Siprec.Status getStatus() { return this.status; } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/call/Stream.java b/src/main/java/com/twilio/rest/api/v2010/account/call/Stream.java index 6fcf583011..c646360c75 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/call/Stream.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/call/Stream.java @@ -57,7 +57,7 @@ public static StreamCreator creator( public static StreamUpdater updater( final String pathCallSid, final String pathSid, - final UpdateStatus status + final Stream.UpdateStatus status ) { return new StreamUpdater(pathCallSid, pathSid, status); } @@ -66,7 +66,7 @@ public static StreamUpdater updater( final String pathAccountSid, final String pathCallSid, final String pathSid, - final UpdateStatus status + final Stream.UpdateStatus status ) { return new StreamUpdater(pathAccountSid, pathCallSid, pathSid, status); } @@ -118,7 +118,7 @@ public static Stream fromJson( private final String accountSid; private final String callSid; private final String name; - private final Status status; + private final Stream.Status status; private final ZonedDateTime dateUpdated; private final String uri; @@ -128,7 +128,7 @@ private Stream( @JsonProperty("account_sid") final String accountSid, @JsonProperty("call_sid") final String callSid, @JsonProperty("name") final String name, - @JsonProperty("status") final Status status, + @JsonProperty("status") final Stream.Status status, @JsonProperty("date_updated") final String dateUpdated, @JsonProperty("uri") final String uri ) { @@ -157,7 +157,7 @@ public final String getName() { return this.name; } - public final Status getStatus() { + public final Stream.Status getStatus() { return this.status; } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/call/Transcription.java b/src/main/java/com/twilio/rest/api/v2010/account/call/Transcription.java index e7aec1241e..1f1083335a 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/call/Transcription.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/call/Transcription.java @@ -52,7 +52,7 @@ public static TranscriptionCreator creator( public static TranscriptionUpdater updater( final String pathCallSid, final String pathSid, - final UpdateStatus status + final Transcription.UpdateStatus status ) { return new TranscriptionUpdater(pathCallSid, pathSid, status); } @@ -61,7 +61,7 @@ public static TranscriptionUpdater updater( final String pathAccountSid, final String pathCallSid, final String pathSid, - final UpdateStatus status + final Transcription.UpdateStatus status ) { return new TranscriptionUpdater( pathAccountSid, @@ -118,7 +118,7 @@ public static Transcription fromJson( private final String accountSid; private final String callSid; private final String name; - private final Status status; + private final Transcription.Status status; private final ZonedDateTime dateUpdated; private final String uri; @@ -128,7 +128,7 @@ private Transcription( @JsonProperty("account_sid") final String accountSid, @JsonProperty("call_sid") final String callSid, @JsonProperty("name") final String name, - @JsonProperty("status") final Status status, + @JsonProperty("status") final Transcription.Status status, @JsonProperty("date_updated") final String dateUpdated, @JsonProperty("uri") final String uri ) { @@ -157,7 +157,7 @@ public final String getName() { return this.name; } - public final Status getStatus() { + public final Transcription.Status getStatus() { return this.status; } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/conference/Participant.java b/src/main/java/com/twilio/rest/api/v2010/account/conference/Participant.java index f386803124..1eb8a9218a 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/conference/Participant.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/conference/Participant.java @@ -183,7 +183,7 @@ public static Participant fromJson( private final Boolean muted; private final Boolean hold; private final Boolean startConferenceOnEnter; - private final Status status; + private final Participant.Status status; private final String queueTime; private final String uri; @@ -205,7 +205,7 @@ private Participant( @JsonProperty( "start_conference_on_enter" ) final Boolean startConferenceOnEnter, - @JsonProperty("status") final Status status, + @JsonProperty("status") final Participant.Status status, @JsonProperty("queue_time") final String queueTime, @JsonProperty("uri") final String uri ) { @@ -274,7 +274,7 @@ public final Boolean getStartConferenceOnEnter() { return this.startConferenceOnEnter; } - public final Status getStatus() { + public final Participant.Status getStatus() { return this.status; } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/conference/Recording.java b/src/main/java/com/twilio/rest/api/v2010/account/conference/Recording.java index cb19e56da8..0a4e1b2876 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/conference/Recording.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/conference/Recording.java @@ -87,7 +87,7 @@ public static RecordingReader reader( public static RecordingUpdater updater( final String pathConferenceSid, final String pathSid, - final Status status + final Recording.Status status ) { return new RecordingUpdater(pathConferenceSid, pathSid, status); } @@ -96,7 +96,7 @@ public static RecordingUpdater updater( final String pathAccountSid, final String pathConferenceSid, final String pathSid, - final Status status + final Recording.Status status ) { return new RecordingUpdater( pathAccountSid, @@ -160,9 +160,9 @@ public static Recording fromJson( private final String sid; private final String price; private final Currency priceUnit; - private final Status status; + private final Recording.Status status; private final Integer channels; - private final Source source; + private final Recording.Source source; private final Integer errorCode; private final Map encryptionDetails; private final String uri; @@ -180,11 +180,11 @@ private Recording( @JsonProperty("sid") final String sid, @JsonProperty("price") final String price, @JsonProperty("price_unit") @JsonDeserialize( - using = CurrencyDeserializer.class + using = com.twilio.converter.CurrencyDeserializer.class ) final Currency priceUnit, - @JsonProperty("status") final Status status, + @JsonProperty("status") final Recording.Status status, @JsonProperty("channels") final Integer channels, - @JsonProperty("source") final Source source, + @JsonProperty("source") final Recording.Source source, @JsonProperty("error_code") final Integer errorCode, @JsonProperty("encryption_details") final Map< String, @@ -255,7 +255,7 @@ public final Currency getPriceUnit() { return this.priceUnit; } - public final Status getStatus() { + public final Recording.Status getStatus() { return this.status; } @@ -263,7 +263,7 @@ public final Integer getChannels() { return this.channels; } - public final Source getSource() { + public final Recording.Source getSource() { return this.source; } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/incomingphonenumber/Local.java b/src/main/java/com/twilio/rest/api/v2010/account/incomingphonenumber/Local.java index cb3531a74c..801ff7fc75 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/incomingphonenumber/Local.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/incomingphonenumber/Local.java @@ -107,7 +107,7 @@ public static Local fromJson( private final String accountSid; private final String addressSid; - private final AddressRequirement addressRequirements; + private final Local.AddressRequirement addressRequirements; private final String apiVersion; private final Boolean beta; private final PhoneNumberCapabilities capabilities; @@ -127,16 +127,16 @@ public static Local fromJson( private final HttpMethod statusCallbackMethod; private final String trunkSid; private final String uri; - private final VoiceReceiveMode voiceReceiveMode; + private final Local.VoiceReceiveMode voiceReceiveMode; private final String voiceApplicationSid; private final Boolean voiceCallerIdLookup; private final HttpMethod voiceFallbackMethod; private final URI voiceFallbackUrl; private final HttpMethod voiceMethod; private final URI voiceUrl; - private final EmergencyStatus emergencyStatus; + private final Local.EmergencyStatus emergencyStatus; private final String emergencyAddressSid; - private final EmergencyAddressStatus emergencyAddressStatus; + private final Local.EmergencyAddressStatus emergencyAddressStatus; private final String bundleSid; private final String status; @@ -146,7 +146,7 @@ private Local( @JsonProperty("address_sid") final String addressSid, @JsonProperty( "address_requirements" - ) final AddressRequirement addressRequirements, + ) final Local.AddressRequirement addressRequirements, @JsonProperty("api_version") final String apiVersion, @JsonProperty("beta") final Boolean beta, @JsonProperty( @@ -174,7 +174,7 @@ private Local( @JsonProperty("uri") final String uri, @JsonProperty( "voice_receive_mode" - ) final VoiceReceiveMode voiceReceiveMode, + ) final Local.VoiceReceiveMode voiceReceiveMode, @JsonProperty("voice_application_sid") final String voiceApplicationSid, @JsonProperty( "voice_caller_id_lookup" @@ -185,11 +185,13 @@ private Local( @JsonProperty("voice_fallback_url") final URI voiceFallbackUrl, @JsonProperty("voice_method") final HttpMethod voiceMethod, @JsonProperty("voice_url") final URI voiceUrl, - @JsonProperty("emergency_status") final EmergencyStatus emergencyStatus, + @JsonProperty( + "emergency_status" + ) final Local.EmergencyStatus emergencyStatus, @JsonProperty("emergency_address_sid") final String emergencyAddressSid, @JsonProperty( "emergency_address_status" - ) final EmergencyAddressStatus emergencyAddressStatus, + ) final Local.EmergencyAddressStatus emergencyAddressStatus, @JsonProperty("bundle_sid") final String bundleSid, @JsonProperty("status") final String status ) { @@ -237,7 +239,7 @@ public final String getAddressSid() { return this.addressSid; } - public final AddressRequirement getAddressRequirements() { + public final Local.AddressRequirement getAddressRequirements() { return this.addressRequirements; } @@ -317,7 +319,7 @@ public final String getUri() { return this.uri; } - public final VoiceReceiveMode getVoiceReceiveMode() { + public final Local.VoiceReceiveMode getVoiceReceiveMode() { return this.voiceReceiveMode; } @@ -345,7 +347,7 @@ public final URI getVoiceUrl() { return this.voiceUrl; } - public final EmergencyStatus getEmergencyStatus() { + public final Local.EmergencyStatus getEmergencyStatus() { return this.emergencyStatus; } @@ -353,7 +355,7 @@ public final String getEmergencyAddressSid() { return this.emergencyAddressSid; } - public final EmergencyAddressStatus getEmergencyAddressStatus() { + public final Local.EmergencyAddressStatus getEmergencyAddressStatus() { return this.emergencyAddressStatus; } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/incomingphonenumber/Mobile.java b/src/main/java/com/twilio/rest/api/v2010/account/incomingphonenumber/Mobile.java index 78bdb0710f..62c6156f9e 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/incomingphonenumber/Mobile.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/incomingphonenumber/Mobile.java @@ -107,7 +107,7 @@ public static Mobile fromJson( private final String accountSid; private final String addressSid; - private final AddressRequirement addressRequirements; + private final Mobile.AddressRequirement addressRequirements; private final String apiVersion; private final Boolean beta; private final PhoneNumberCapabilities capabilities; @@ -127,16 +127,16 @@ public static Mobile fromJson( private final HttpMethod statusCallbackMethod; private final String trunkSid; private final String uri; - private final VoiceReceiveMode voiceReceiveMode; + private final Mobile.VoiceReceiveMode voiceReceiveMode; private final String voiceApplicationSid; private final Boolean voiceCallerIdLookup; private final HttpMethod voiceFallbackMethod; private final URI voiceFallbackUrl; private final HttpMethod voiceMethod; private final URI voiceUrl; - private final EmergencyStatus emergencyStatus; + private final Mobile.EmergencyStatus emergencyStatus; private final String emergencyAddressSid; - private final EmergencyAddressStatus emergencyAddressStatus; + private final Mobile.EmergencyAddressStatus emergencyAddressStatus; private final String bundleSid; private final String status; @@ -146,7 +146,7 @@ private Mobile( @JsonProperty("address_sid") final String addressSid, @JsonProperty( "address_requirements" - ) final AddressRequirement addressRequirements, + ) final Mobile.AddressRequirement addressRequirements, @JsonProperty("api_version") final String apiVersion, @JsonProperty("beta") final Boolean beta, @JsonProperty( @@ -174,7 +174,7 @@ private Mobile( @JsonProperty("uri") final String uri, @JsonProperty( "voice_receive_mode" - ) final VoiceReceiveMode voiceReceiveMode, + ) final Mobile.VoiceReceiveMode voiceReceiveMode, @JsonProperty("voice_application_sid") final String voiceApplicationSid, @JsonProperty( "voice_caller_id_lookup" @@ -185,11 +185,13 @@ private Mobile( @JsonProperty("voice_fallback_url") final URI voiceFallbackUrl, @JsonProperty("voice_method") final HttpMethod voiceMethod, @JsonProperty("voice_url") final URI voiceUrl, - @JsonProperty("emergency_status") final EmergencyStatus emergencyStatus, + @JsonProperty( + "emergency_status" + ) final Mobile.EmergencyStatus emergencyStatus, @JsonProperty("emergency_address_sid") final String emergencyAddressSid, @JsonProperty( "emergency_address_status" - ) final EmergencyAddressStatus emergencyAddressStatus, + ) final Mobile.EmergencyAddressStatus emergencyAddressStatus, @JsonProperty("bundle_sid") final String bundleSid, @JsonProperty("status") final String status ) { @@ -237,7 +239,7 @@ public final String getAddressSid() { return this.addressSid; } - public final AddressRequirement getAddressRequirements() { + public final Mobile.AddressRequirement getAddressRequirements() { return this.addressRequirements; } @@ -317,7 +319,7 @@ public final String getUri() { return this.uri; } - public final VoiceReceiveMode getVoiceReceiveMode() { + public final Mobile.VoiceReceiveMode getVoiceReceiveMode() { return this.voiceReceiveMode; } @@ -345,7 +347,7 @@ public final URI getVoiceUrl() { return this.voiceUrl; } - public final EmergencyStatus getEmergencyStatus() { + public final Mobile.EmergencyStatus getEmergencyStatus() { return this.emergencyStatus; } @@ -353,7 +355,7 @@ public final String getEmergencyAddressSid() { return this.emergencyAddressSid; } - public final EmergencyAddressStatus getEmergencyAddressStatus() { + public final Mobile.EmergencyAddressStatus getEmergencyAddressStatus() { return this.emergencyAddressStatus; } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/incomingphonenumber/TollFree.java b/src/main/java/com/twilio/rest/api/v2010/account/incomingphonenumber/TollFree.java index af9f39055a..4e1e3cf74c 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/incomingphonenumber/TollFree.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/incomingphonenumber/TollFree.java @@ -107,7 +107,7 @@ public static TollFree fromJson( private final String accountSid; private final String addressSid; - private final AddressRequirement addressRequirements; + private final TollFree.AddressRequirement addressRequirements; private final String apiVersion; private final Boolean beta; private final PhoneNumberCapabilities capabilities; @@ -127,16 +127,16 @@ public static TollFree fromJson( private final HttpMethod statusCallbackMethod; private final String trunkSid; private final String uri; - private final VoiceReceiveMode voiceReceiveMode; + private final TollFree.VoiceReceiveMode voiceReceiveMode; private final String voiceApplicationSid; private final Boolean voiceCallerIdLookup; private final HttpMethod voiceFallbackMethod; private final URI voiceFallbackUrl; private final HttpMethod voiceMethod; private final URI voiceUrl; - private final EmergencyStatus emergencyStatus; + private final TollFree.EmergencyStatus emergencyStatus; private final String emergencyAddressSid; - private final EmergencyAddressStatus emergencyAddressStatus; + private final TollFree.EmergencyAddressStatus emergencyAddressStatus; private final String bundleSid; private final String status; @@ -146,7 +146,7 @@ private TollFree( @JsonProperty("address_sid") final String addressSid, @JsonProperty( "address_requirements" - ) final AddressRequirement addressRequirements, + ) final TollFree.AddressRequirement addressRequirements, @JsonProperty("api_version") final String apiVersion, @JsonProperty("beta") final Boolean beta, @JsonProperty( @@ -174,7 +174,7 @@ private TollFree( @JsonProperty("uri") final String uri, @JsonProperty( "voice_receive_mode" - ) final VoiceReceiveMode voiceReceiveMode, + ) final TollFree.VoiceReceiveMode voiceReceiveMode, @JsonProperty("voice_application_sid") final String voiceApplicationSid, @JsonProperty( "voice_caller_id_lookup" @@ -185,11 +185,13 @@ private TollFree( @JsonProperty("voice_fallback_url") final URI voiceFallbackUrl, @JsonProperty("voice_method") final HttpMethod voiceMethod, @JsonProperty("voice_url") final URI voiceUrl, - @JsonProperty("emergency_status") final EmergencyStatus emergencyStatus, + @JsonProperty( + "emergency_status" + ) final TollFree.EmergencyStatus emergencyStatus, @JsonProperty("emergency_address_sid") final String emergencyAddressSid, @JsonProperty( "emergency_address_status" - ) final EmergencyAddressStatus emergencyAddressStatus, + ) final TollFree.EmergencyAddressStatus emergencyAddressStatus, @JsonProperty("bundle_sid") final String bundleSid, @JsonProperty("status") final String status ) { @@ -237,7 +239,7 @@ public final String getAddressSid() { return this.addressSid; } - public final AddressRequirement getAddressRequirements() { + public final TollFree.AddressRequirement getAddressRequirements() { return this.addressRequirements; } @@ -317,7 +319,7 @@ public final String getUri() { return this.uri; } - public final VoiceReceiveMode getVoiceReceiveMode() { + public final TollFree.VoiceReceiveMode getVoiceReceiveMode() { return this.voiceReceiveMode; } @@ -345,7 +347,7 @@ public final URI getVoiceUrl() { return this.voiceUrl; } - public final EmergencyStatus getEmergencyStatus() { + public final TollFree.EmergencyStatus getEmergencyStatus() { return this.emergencyStatus; } @@ -353,7 +355,7 @@ public final String getEmergencyAddressSid() { return this.emergencyAddressSid; } - public final EmergencyAddressStatus getEmergencyAddressStatus() { + public final TollFree.EmergencyAddressStatus getEmergencyAddressStatus() { return this.emergencyAddressStatus; } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/message/Feedback.java b/src/main/java/com/twilio/rest/api/v2010/account/message/Feedback.java index 86601603c3..66db8761d3 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/message/Feedback.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/message/Feedback.java @@ -94,7 +94,7 @@ public static Feedback fromJson( private final String accountSid; private final String messageSid; - private final Outcome outcome; + private final Feedback.Outcome outcome; private final ZonedDateTime dateCreated; private final ZonedDateTime dateUpdated; private final String uri; @@ -103,7 +103,7 @@ public static Feedback fromJson( private Feedback( @JsonProperty("account_sid") final String accountSid, @JsonProperty("message_sid") final String messageSid, - @JsonProperty("outcome") final Outcome outcome, + @JsonProperty("outcome") final Feedback.Outcome outcome, @JsonProperty("date_created") final String dateCreated, @JsonProperty("date_updated") final String dateUpdated, @JsonProperty("uri") final String uri @@ -124,7 +124,7 @@ public final String getMessageSid() { return this.messageSid; } - public final Outcome getOutcome() { + public final Feedback.Outcome getOutcome() { return this.outcome; } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/recording/AddOnResult.java b/src/main/java/com/twilio/rest/api/v2010/account/recording/AddOnResult.java index 42b02433c7..c20e30dcb0 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/recording/AddOnResult.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/recording/AddOnResult.java @@ -134,7 +134,7 @@ public static AddOnResult fromJson( private final String sid; private final String accountSid; - private final Status status; + private final AddOnResult.Status status; private final String addOnSid; private final String addOnConfigurationSid; private final ZonedDateTime dateCreated; @@ -147,7 +147,7 @@ public static AddOnResult fromJson( private AddOnResult( @JsonProperty("sid") final String sid, @JsonProperty("account_sid") final String accountSid, - @JsonProperty("status") final Status status, + @JsonProperty("status") final AddOnResult.Status status, @JsonProperty("add_on_sid") final String addOnSid, @JsonProperty( "add_on_configuration_sid" @@ -182,7 +182,7 @@ public final String getAccountSid() { return this.accountSid; } - public final Status getStatus() { + public final AddOnResult.Status getStatus() { return this.status; } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/recording/Transcription.java b/src/main/java/com/twilio/rest/api/v2010/account/recording/Transcription.java index ba9df4ae95..c265b98c28 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/recording/Transcription.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/recording/Transcription.java @@ -143,7 +143,7 @@ public static Transcription fromJson( private final Currency priceUnit; private final String recordingSid; private final String sid; - private final Status status; + private final Transcription.Status status; private final String transcriptionText; private final String type; private final String uri; @@ -157,11 +157,11 @@ private Transcription( @JsonProperty("duration") final String duration, @JsonProperty("price") final BigDecimal price, @JsonProperty("price_unit") @JsonDeserialize( - using = CurrencyDeserializer.class + using = com.twilio.converter.CurrencyDeserializer.class ) final Currency priceUnit, @JsonProperty("recording_sid") final String recordingSid, @JsonProperty("sid") final String sid, - @JsonProperty("status") final Status status, + @JsonProperty("status") final Transcription.Status status, @JsonProperty("transcription_text") final String transcriptionText, @JsonProperty("type") final String type, @JsonProperty("uri") final String uri @@ -217,7 +217,7 @@ public final String getSid() { return this.sid; } - public final Status getStatus() { + public final Transcription.Status getStatus() { return this.status; } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/usage/Record.java b/src/main/java/com/twilio/rest/api/v2010/account/usage/Record.java index de6b0f6a44..5c05e36626 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/usage/Record.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/usage/Record.java @@ -98,7 +98,7 @@ public static Record fromJson( private final String accountSid; private final String apiVersion; private final String asOf; - private final Category category; + private final Record.Category category; private final String count; private final String countUnit; private final String description; @@ -116,14 +116,14 @@ private Record( @JsonProperty("account_sid") final String accountSid, @JsonProperty("api_version") final String apiVersion, @JsonProperty("as_of") final String asOf, - @JsonProperty("category") final Category category, + @JsonProperty("category") final Record.Category category, @JsonProperty("count") final String count, @JsonProperty("count_unit") final String countUnit, @JsonProperty("description") final String description, @JsonProperty("end_date") final String endDate, @JsonProperty("price") final BigDecimal price, @JsonProperty("price_unit") @JsonDeserialize( - using = CurrencyDeserializer.class + using = com.twilio.converter.CurrencyDeserializer.class ) final Currency priceUnit, @JsonProperty("start_date") final String startDate, @JsonProperty("subresource_uris") final Map< @@ -163,7 +163,7 @@ public final String getAsOf() { return this.asOf; } - public final Category getCategory() { + public final Record.Category getCategory() { return this.category; } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/usage/Trigger.java b/src/main/java/com/twilio/rest/api/v2010/account/usage/Trigger.java index 287dcf8236..e18017d6e6 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/usage/Trigger.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/usage/Trigger.java @@ -43,7 +43,7 @@ public class Trigger extends Resource { public static TriggerCreator creator( final URI callbackUrl, final String triggerValue, - final UsageCategory usageCategory + final Trigger.UsageCategory usageCategory ) { return new TriggerCreator(callbackUrl, triggerValue, usageCategory); } @@ -52,7 +52,7 @@ public static TriggerCreator creator( final String pathAccountSid, final URI callbackUrl, final String triggerValue, - final UsageCategory usageCategory + final Trigger.UsageCategory usageCategory ) { return new TriggerCreator( pathAccountSid, @@ -155,12 +155,12 @@ public static Trigger fromJson( private final ZonedDateTime dateFired; private final ZonedDateTime dateUpdated; private final String friendlyName; - private final Recurring recurring; + private final Trigger.Recurring recurring; private final String sid; - private final TriggerField triggerBy; + private final Trigger.TriggerField triggerBy; private final String triggerValue; private final String uri; - private final UsageCategory usageCategory; + private final Trigger.UsageCategory usageCategory; private final String usageRecordUri; @JsonCreator @@ -174,12 +174,14 @@ private Trigger( @JsonProperty("date_fired") final String dateFired, @JsonProperty("date_updated") final String dateUpdated, @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("recurring") final Recurring recurring, + @JsonProperty("recurring") final Trigger.Recurring recurring, @JsonProperty("sid") final String sid, - @JsonProperty("trigger_by") final TriggerField triggerBy, + @JsonProperty("trigger_by") final Trigger.TriggerField triggerBy, @JsonProperty("trigger_value") final String triggerValue, @JsonProperty("uri") final String uri, - @JsonProperty("usage_category") final UsageCategory usageCategory, + @JsonProperty( + "usage_category" + ) final Trigger.UsageCategory usageCategory, @JsonProperty("usage_record_uri") final String usageRecordUri ) { this.accountSid = accountSid; @@ -236,7 +238,7 @@ public final String getFriendlyName() { return this.friendlyName; } - public final Recurring getRecurring() { + public final Trigger.Recurring getRecurring() { return this.recurring; } @@ -244,7 +246,7 @@ public final String getSid() { return this.sid; } - public final TriggerField getTriggerBy() { + public final Trigger.TriggerField getTriggerBy() { return this.triggerBy; } @@ -256,7 +258,7 @@ public final String getUri() { return this.uri; } - public final UsageCategory getUsageCategory() { + public final Trigger.UsageCategory getUsageCategory() { return this.usageCategory; } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/usage/record/AllTime.java b/src/main/java/com/twilio/rest/api/v2010/account/usage/record/AllTime.java index 576f6ddd09..2e5e8e1938 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/usage/record/AllTime.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/usage/record/AllTime.java @@ -98,7 +98,7 @@ public static AllTime fromJson( private final String accountSid; private final String apiVersion; private final String asOf; - private final Category category; + private final AllTime.Category category; private final String count; private final String countUnit; private final String description; @@ -116,14 +116,14 @@ private AllTime( @JsonProperty("account_sid") final String accountSid, @JsonProperty("api_version") final String apiVersion, @JsonProperty("as_of") final String asOf, - @JsonProperty("category") final Category category, + @JsonProperty("category") final AllTime.Category category, @JsonProperty("count") final String count, @JsonProperty("count_unit") final String countUnit, @JsonProperty("description") final String description, @JsonProperty("end_date") final String endDate, @JsonProperty("price") final BigDecimal price, @JsonProperty("price_unit") @JsonDeserialize( - using = CurrencyDeserializer.class + using = com.twilio.converter.CurrencyDeserializer.class ) final Currency priceUnit, @JsonProperty("start_date") final String startDate, @JsonProperty("subresource_uris") final Map< @@ -163,7 +163,7 @@ public final String getAsOf() { return this.asOf; } - public final Category getCategory() { + public final AllTime.Category getCategory() { return this.category; } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/usage/record/Daily.java b/src/main/java/com/twilio/rest/api/v2010/account/usage/record/Daily.java index 22c683d023..c562e8b219 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/usage/record/Daily.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/usage/record/Daily.java @@ -98,7 +98,7 @@ public static Daily fromJson( private final String accountSid; private final String apiVersion; private final String asOf; - private final Category category; + private final Daily.Category category; private final String count; private final String countUnit; private final String description; @@ -116,14 +116,14 @@ private Daily( @JsonProperty("account_sid") final String accountSid, @JsonProperty("api_version") final String apiVersion, @JsonProperty("as_of") final String asOf, - @JsonProperty("category") final Category category, + @JsonProperty("category") final Daily.Category category, @JsonProperty("count") final String count, @JsonProperty("count_unit") final String countUnit, @JsonProperty("description") final String description, @JsonProperty("end_date") final String endDate, @JsonProperty("price") final BigDecimal price, @JsonProperty("price_unit") @JsonDeserialize( - using = CurrencyDeserializer.class + using = com.twilio.converter.CurrencyDeserializer.class ) final Currency priceUnit, @JsonProperty("start_date") final String startDate, @JsonProperty("subresource_uris") final Map< @@ -163,7 +163,7 @@ public final String getAsOf() { return this.asOf; } - public final Category getCategory() { + public final Daily.Category getCategory() { return this.category; } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/usage/record/LastMonth.java b/src/main/java/com/twilio/rest/api/v2010/account/usage/record/LastMonth.java index fcbf30024c..471a20a4d8 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/usage/record/LastMonth.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/usage/record/LastMonth.java @@ -98,7 +98,7 @@ public static LastMonth fromJson( private final String accountSid; private final String apiVersion; private final String asOf; - private final Category category; + private final LastMonth.Category category; private final String count; private final String countUnit; private final String description; @@ -116,14 +116,14 @@ private LastMonth( @JsonProperty("account_sid") final String accountSid, @JsonProperty("api_version") final String apiVersion, @JsonProperty("as_of") final String asOf, - @JsonProperty("category") final Category category, + @JsonProperty("category") final LastMonth.Category category, @JsonProperty("count") final String count, @JsonProperty("count_unit") final String countUnit, @JsonProperty("description") final String description, @JsonProperty("end_date") final String endDate, @JsonProperty("price") final BigDecimal price, @JsonProperty("price_unit") @JsonDeserialize( - using = CurrencyDeserializer.class + using = com.twilio.converter.CurrencyDeserializer.class ) final Currency priceUnit, @JsonProperty("start_date") final String startDate, @JsonProperty("subresource_uris") final Map< @@ -163,7 +163,7 @@ public final String getAsOf() { return this.asOf; } - public final Category getCategory() { + public final LastMonth.Category getCategory() { return this.category; } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/usage/record/Monthly.java b/src/main/java/com/twilio/rest/api/v2010/account/usage/record/Monthly.java index 64b1070365..315837e39e 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/usage/record/Monthly.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/usage/record/Monthly.java @@ -98,7 +98,7 @@ public static Monthly fromJson( private final String accountSid; private final String apiVersion; private final String asOf; - private final Category category; + private final Monthly.Category category; private final String count; private final String countUnit; private final String description; @@ -116,14 +116,14 @@ private Monthly( @JsonProperty("account_sid") final String accountSid, @JsonProperty("api_version") final String apiVersion, @JsonProperty("as_of") final String asOf, - @JsonProperty("category") final Category category, + @JsonProperty("category") final Monthly.Category category, @JsonProperty("count") final String count, @JsonProperty("count_unit") final String countUnit, @JsonProperty("description") final String description, @JsonProperty("end_date") final String endDate, @JsonProperty("price") final BigDecimal price, @JsonProperty("price_unit") @JsonDeserialize( - using = CurrencyDeserializer.class + using = com.twilio.converter.CurrencyDeserializer.class ) final Currency priceUnit, @JsonProperty("start_date") final String startDate, @JsonProperty("subresource_uris") final Map< @@ -163,7 +163,7 @@ public final String getAsOf() { return this.asOf; } - public final Category getCategory() { + public final Monthly.Category getCategory() { return this.category; } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/usage/record/ThisMonth.java b/src/main/java/com/twilio/rest/api/v2010/account/usage/record/ThisMonth.java index f545f03970..f0799a55f9 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/usage/record/ThisMonth.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/usage/record/ThisMonth.java @@ -98,7 +98,7 @@ public static ThisMonth fromJson( private final String accountSid; private final String apiVersion; private final String asOf; - private final Category category; + private final ThisMonth.Category category; private final String count; private final String countUnit; private final String description; @@ -116,14 +116,14 @@ private ThisMonth( @JsonProperty("account_sid") final String accountSid, @JsonProperty("api_version") final String apiVersion, @JsonProperty("as_of") final String asOf, - @JsonProperty("category") final Category category, + @JsonProperty("category") final ThisMonth.Category category, @JsonProperty("count") final String count, @JsonProperty("count_unit") final String countUnit, @JsonProperty("description") final String description, @JsonProperty("end_date") final String endDate, @JsonProperty("price") final BigDecimal price, @JsonProperty("price_unit") @JsonDeserialize( - using = CurrencyDeserializer.class + using = com.twilio.converter.CurrencyDeserializer.class ) final Currency priceUnit, @JsonProperty("start_date") final String startDate, @JsonProperty("subresource_uris") final Map< @@ -163,7 +163,7 @@ public final String getAsOf() { return this.asOf; } - public final Category getCategory() { + public final ThisMonth.Category getCategory() { return this.category; } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/usage/record/Today.java b/src/main/java/com/twilio/rest/api/v2010/account/usage/record/Today.java index 09fced5595..38c0f84024 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/usage/record/Today.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/usage/record/Today.java @@ -98,7 +98,7 @@ public static Today fromJson( private final String accountSid; private final String apiVersion; private final String asOf; - private final Category category; + private final Today.Category category; private final String count; private final String countUnit; private final String description; @@ -116,14 +116,14 @@ private Today( @JsonProperty("account_sid") final String accountSid, @JsonProperty("api_version") final String apiVersion, @JsonProperty("as_of") final String asOf, - @JsonProperty("category") final Category category, + @JsonProperty("category") final Today.Category category, @JsonProperty("count") final String count, @JsonProperty("count_unit") final String countUnit, @JsonProperty("description") final String description, @JsonProperty("end_date") final String endDate, @JsonProperty("price") final BigDecimal price, @JsonProperty("price_unit") @JsonDeserialize( - using = CurrencyDeserializer.class + using = com.twilio.converter.CurrencyDeserializer.class ) final Currency priceUnit, @JsonProperty("start_date") final String startDate, @JsonProperty("subresource_uris") final Map< @@ -163,7 +163,7 @@ public final String getAsOf() { return this.asOf; } - public final Category getCategory() { + public final Today.Category getCategory() { return this.category; } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/usage/record/Yearly.java b/src/main/java/com/twilio/rest/api/v2010/account/usage/record/Yearly.java index c55164426b..bc447957ac 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/usage/record/Yearly.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/usage/record/Yearly.java @@ -98,7 +98,7 @@ public static Yearly fromJson( private final String accountSid; private final String apiVersion; private final String asOf; - private final Category category; + private final Yearly.Category category; private final String count; private final String countUnit; private final String description; @@ -116,14 +116,14 @@ private Yearly( @JsonProperty("account_sid") final String accountSid, @JsonProperty("api_version") final String apiVersion, @JsonProperty("as_of") final String asOf, - @JsonProperty("category") final Category category, + @JsonProperty("category") final Yearly.Category category, @JsonProperty("count") final String count, @JsonProperty("count_unit") final String countUnit, @JsonProperty("description") final String description, @JsonProperty("end_date") final String endDate, @JsonProperty("price") final BigDecimal price, @JsonProperty("price_unit") @JsonDeserialize( - using = CurrencyDeserializer.class + using = com.twilio.converter.CurrencyDeserializer.class ) final Currency priceUnit, @JsonProperty("start_date") final String startDate, @JsonProperty("subresource_uris") final Map< @@ -163,7 +163,7 @@ public final String getAsOf() { return this.asOf; } - public final Category getCategory() { + public final Yearly.Category getCategory() { return this.category; } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/usage/record/Yesterday.java b/src/main/java/com/twilio/rest/api/v2010/account/usage/record/Yesterday.java index d908600933..f271504c4b 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/usage/record/Yesterday.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/usage/record/Yesterday.java @@ -98,7 +98,7 @@ public static Yesterday fromJson( private final String accountSid; private final String apiVersion; private final String asOf; - private final Category category; + private final Yesterday.Category category; private final String count; private final String countUnit; private final String description; @@ -116,14 +116,14 @@ private Yesterday( @JsonProperty("account_sid") final String accountSid, @JsonProperty("api_version") final String apiVersion, @JsonProperty("as_of") final String asOf, - @JsonProperty("category") final Category category, + @JsonProperty("category") final Yesterday.Category category, @JsonProperty("count") final String count, @JsonProperty("count_unit") final String countUnit, @JsonProperty("description") final String description, @JsonProperty("end_date") final String endDate, @JsonProperty("price") final BigDecimal price, @JsonProperty("price_unit") @JsonDeserialize( - using = CurrencyDeserializer.class + using = com.twilio.converter.CurrencyDeserializer.class ) final Currency priceUnit, @JsonProperty("start_date") final String startDate, @JsonProperty("subresource_uris") final Map< @@ -163,7 +163,7 @@ public final String getAsOf() { return this.asOf; } - public final Category getCategory() { + public final Yesterday.Category getCategory() { return this.category; } diff --git a/src/main/java/com/twilio/rest/assistants/v1/Assistant.java b/src/main/java/com/twilio/rest/assistants/v1/Assistant.java index ac3ca71dda..0c4ed48947 100644 --- a/src/main/java/com/twilio/rest/assistants/v1/Assistant.java +++ b/src/main/java/com/twilio/rest/assistants/v1/Assistant.java @@ -370,7 +370,7 @@ public static AssistantsV1ServiceTool fromJson( } public static AssistantCreator creator( - final AssistantsV1ServiceCreateAssistantRequest assistantsV1ServiceCreateAssistantRequest + final Assistant.AssistantsV1ServiceCreateAssistantRequest assistantsV1ServiceCreateAssistantRequest ) { return new AssistantCreator(assistantsV1ServiceCreateAssistantRequest); } diff --git a/src/main/java/com/twilio/rest/assistants/v1/Knowledge.java b/src/main/java/com/twilio/rest/assistants/v1/Knowledge.java index b412f115bb..a899609713 100644 --- a/src/main/java/com/twilio/rest/assistants/v1/Knowledge.java +++ b/src/main/java/com/twilio/rest/assistants/v1/Knowledge.java @@ -204,7 +204,7 @@ public static AssistantsV1ServiceUpdateKnowledgeRequest fromJson( } public static KnowledgeCreator creator( - final AssistantsV1ServiceCreateKnowledgeRequest assistantsV1ServiceCreateKnowledgeRequest + final Knowledge.AssistantsV1ServiceCreateKnowledgeRequest assistantsV1ServiceCreateKnowledgeRequest ) { return new KnowledgeCreator(assistantsV1ServiceCreateKnowledgeRequest); } diff --git a/src/main/java/com/twilio/rest/assistants/v1/Tool.java b/src/main/java/com/twilio/rest/assistants/v1/Tool.java index 2f9b5aacb0..48770ad6a1 100644 --- a/src/main/java/com/twilio/rest/assistants/v1/Tool.java +++ b/src/main/java/com/twilio/rest/assistants/v1/Tool.java @@ -289,7 +289,7 @@ public static AssistantsV1ServicePolicy fromJson( } public static ToolCreator creator( - final AssistantsV1ServiceCreateToolRequest assistantsV1ServiceCreateToolRequest + final Tool.AssistantsV1ServiceCreateToolRequest assistantsV1ServiceCreateToolRequest ) { return new ToolCreator(assistantsV1ServiceCreateToolRequest); } diff --git a/src/main/java/com/twilio/rest/assistants/v1/assistant/Feedback.java b/src/main/java/com/twilio/rest/assistants/v1/assistant/Feedback.java index 57cb442b4a..c607c9c472 100644 --- a/src/main/java/com/twilio/rest/assistants/v1/assistant/Feedback.java +++ b/src/main/java/com/twilio/rest/assistants/v1/assistant/Feedback.java @@ -87,7 +87,7 @@ public static AssistantsV1ServiceCreateFeedbackRequest fromJson( public static FeedbackCreator creator( final String pathId, - final AssistantsV1ServiceCreateFeedbackRequest assistantsV1ServiceCreateFeedbackRequest + final Feedback.AssistantsV1ServiceCreateFeedbackRequest assistantsV1ServiceCreateFeedbackRequest ) { return new FeedbackCreator( pathId, diff --git a/src/main/java/com/twilio/rest/assistants/v1/assistant/Message.java b/src/main/java/com/twilio/rest/assistants/v1/assistant/Message.java index b2922bd6e9..3891e48b3e 100644 --- a/src/main/java/com/twilio/rest/assistants/v1/assistant/Message.java +++ b/src/main/java/com/twilio/rest/assistants/v1/assistant/Message.java @@ -93,7 +93,7 @@ public static AssistantsV1ServiceAssistantSendMessageRequest fromJson( public static MessageCreator creator( final String pathId, - final AssistantsV1ServiceAssistantSendMessageRequest assistantsV1ServiceAssistantSendMessageRequest + final Message.AssistantsV1ServiceAssistantSendMessageRequest assistantsV1ServiceAssistantSendMessageRequest ) { return new MessageCreator( pathId, diff --git a/src/main/java/com/twilio/rest/chat/v1/Credential.java b/src/main/java/com/twilio/rest/chat/v1/Credential.java index 8b91dfa3ef..270e61e3fe 100644 --- a/src/main/java/com/twilio/rest/chat/v1/Credential.java +++ b/src/main/java/com/twilio/rest/chat/v1/Credential.java @@ -39,7 +39,7 @@ public class Credential extends Resource { private static final long serialVersionUID = 161183169234848L; - public static CredentialCreator creator(final PushService type) { + public static CredentialCreator creator(final Credential.PushService type) { return new CredentialCreator(type); } @@ -105,7 +105,7 @@ public static Credential fromJson( private final String sid; private final String accountSid; private final String friendlyName; - private final PushService type; + private final Credential.PushService type; private final String sandbox; private final ZonedDateTime dateCreated; private final ZonedDateTime dateUpdated; @@ -116,7 +116,7 @@ private Credential( @JsonProperty("sid") final String sid, @JsonProperty("account_sid") final String accountSid, @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("type") final PushService type, + @JsonProperty("type") final Credential.PushService type, @JsonProperty("sandbox") final String sandbox, @JsonProperty("date_created") final String dateCreated, @JsonProperty("date_updated") final String dateUpdated, @@ -144,7 +144,7 @@ public final String getFriendlyName() { return this.friendlyName; } - public final PushService getType() { + public final Credential.PushService getType() { return this.type; } diff --git a/src/main/java/com/twilio/rest/chat/v1/service/Channel.java b/src/main/java/com/twilio/rest/chat/v1/service/Channel.java index 0b026f0db2..d8f46724b0 100644 --- a/src/main/java/com/twilio/rest/chat/v1/service/Channel.java +++ b/src/main/java/com/twilio/rest/chat/v1/service/Channel.java @@ -119,7 +119,7 @@ public static Channel fromJson( private final String friendlyName; private final String uniqueName; private final String attributes; - private final ChannelType type; + private final Channel.ChannelType type; private final ZonedDateTime dateCreated; private final ZonedDateTime dateUpdated; private final String createdBy; @@ -136,7 +136,7 @@ private Channel( @JsonProperty("friendly_name") final String friendlyName, @JsonProperty("unique_name") final String uniqueName, @JsonProperty("attributes") final String attributes, - @JsonProperty("type") final ChannelType type, + @JsonProperty("type") final Channel.ChannelType type, @JsonProperty("date_created") final String dateCreated, @JsonProperty("date_updated") final String dateUpdated, @JsonProperty("created_by") final String createdBy, @@ -185,7 +185,7 @@ public final String getAttributes() { return this.attributes; } - public final ChannelType getType() { + public final Channel.ChannelType getType() { return this.type; } diff --git a/src/main/java/com/twilio/rest/chat/v1/service/Role.java b/src/main/java/com/twilio/rest/chat/v1/service/Role.java index d2a44ff7dc..eaf3e01555 100644 --- a/src/main/java/com/twilio/rest/chat/v1/service/Role.java +++ b/src/main/java/com/twilio/rest/chat/v1/service/Role.java @@ -43,7 +43,7 @@ public class Role extends Resource { public static RoleCreator creator( final String pathServiceSid, final String friendlyName, - final RoleType type, + final Role.RoleType type, final List permission ) { return new RoleCreator(pathServiceSid, friendlyName, type, permission); @@ -122,7 +122,7 @@ public static Role fromJson( private final String accountSid; private final String serviceSid; private final String friendlyName; - private final RoleType type; + private final Role.RoleType type; private final List permissions; private final ZonedDateTime dateCreated; private final ZonedDateTime dateUpdated; @@ -134,7 +134,7 @@ private Role( @JsonProperty("account_sid") final String accountSid, @JsonProperty("service_sid") final String serviceSid, @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("type") final RoleType type, + @JsonProperty("type") final Role.RoleType type, @JsonProperty("permissions") final List permissions, @JsonProperty("date_created") final String dateCreated, @JsonProperty("date_updated") final String dateUpdated, @@ -167,7 +167,7 @@ public final String getFriendlyName() { return this.friendlyName; } - public final RoleType getType() { + public final Role.RoleType getType() { return this.type; } diff --git a/src/main/java/com/twilio/rest/chat/v1/service/user/UserChannel.java b/src/main/java/com/twilio/rest/chat/v1/service/user/UserChannel.java index 667c61e4eb..245f4d1b5d 100644 --- a/src/main/java/com/twilio/rest/chat/v1/service/user/UserChannel.java +++ b/src/main/java/com/twilio/rest/chat/v1/service/user/UserChannel.java @@ -92,7 +92,7 @@ public static UserChannel fromJson( private final String serviceSid; private final String channelSid; private final String memberSid; - private final ChannelStatus status; + private final UserChannel.ChannelStatus status; private final Integer lastConsumedMessageIndex; private final Integer unreadMessagesCount; private final Map links; @@ -103,7 +103,7 @@ private UserChannel( @JsonProperty("service_sid") final String serviceSid, @JsonProperty("channel_sid") final String channelSid, @JsonProperty("member_sid") final String memberSid, - @JsonProperty("status") final ChannelStatus status, + @JsonProperty("status") final UserChannel.ChannelStatus status, @JsonProperty( "last_consumed_message_index" ) final Integer lastConsumedMessageIndex, @@ -138,7 +138,7 @@ public final String getMemberSid() { return this.memberSid; } - public final ChannelStatus getStatus() { + public final UserChannel.ChannelStatus getStatus() { return this.status; } diff --git a/src/main/java/com/twilio/rest/chat/v2/Credential.java b/src/main/java/com/twilio/rest/chat/v2/Credential.java index 8be42a05aa..b02f30cb1e 100644 --- a/src/main/java/com/twilio/rest/chat/v2/Credential.java +++ b/src/main/java/com/twilio/rest/chat/v2/Credential.java @@ -39,7 +39,7 @@ public class Credential extends Resource { private static final long serialVersionUID = 161183169234848L; - public static CredentialCreator creator(final PushService type) { + public static CredentialCreator creator(final Credential.PushService type) { return new CredentialCreator(type); } @@ -105,7 +105,7 @@ public static Credential fromJson( private final String sid; private final String accountSid; private final String friendlyName; - private final PushService type; + private final Credential.PushService type; private final String sandbox; private final ZonedDateTime dateCreated; private final ZonedDateTime dateUpdated; @@ -116,7 +116,7 @@ private Credential( @JsonProperty("sid") final String sid, @JsonProperty("account_sid") final String accountSid, @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("type") final PushService type, + @JsonProperty("type") final Credential.PushService type, @JsonProperty("sandbox") final String sandbox, @JsonProperty("date_created") final String dateCreated, @JsonProperty("date_updated") final String dateUpdated, @@ -144,7 +144,7 @@ public final String getFriendlyName() { return this.friendlyName; } - public final PushService getType() { + public final Credential.PushService getType() { return this.type; } diff --git a/src/main/java/com/twilio/rest/chat/v2/service/Binding.java b/src/main/java/com/twilio/rest/chat/v2/service/Binding.java index 87b187143a..3ace8bfd8d 100644 --- a/src/main/java/com/twilio/rest/chat/v2/service/Binding.java +++ b/src/main/java/com/twilio/rest/chat/v2/service/Binding.java @@ -111,7 +111,7 @@ public static Binding fromJson( private final String endpoint; private final String identity; private final String credentialSid; - private final BindingType bindingType; + private final Binding.BindingType bindingType; private final List messageTypes; private final URI url; private final Map links; @@ -126,7 +126,7 @@ private Binding( @JsonProperty("endpoint") final String endpoint, @JsonProperty("identity") final String identity, @JsonProperty("credential_sid") final String credentialSid, - @JsonProperty("binding_type") final BindingType bindingType, + @JsonProperty("binding_type") final Binding.BindingType bindingType, @JsonProperty("message_types") final List messageTypes, @JsonProperty("url") final URI url, @JsonProperty("links") final Map links @@ -177,7 +177,7 @@ public final String getCredentialSid() { return this.credentialSid; } - public final BindingType getBindingType() { + public final Binding.BindingType getBindingType() { return this.bindingType; } diff --git a/src/main/java/com/twilio/rest/chat/v2/service/Channel.java b/src/main/java/com/twilio/rest/chat/v2/service/Channel.java index b4a9182d10..d950169893 100644 --- a/src/main/java/com/twilio/rest/chat/v2/service/Channel.java +++ b/src/main/java/com/twilio/rest/chat/v2/service/Channel.java @@ -119,7 +119,7 @@ public static Channel fromJson( private final String friendlyName; private final String uniqueName; private final String attributes; - private final ChannelType type; + private final Channel.ChannelType type; private final ZonedDateTime dateCreated; private final ZonedDateTime dateUpdated; private final String createdBy; @@ -136,7 +136,7 @@ private Channel( @JsonProperty("friendly_name") final String friendlyName, @JsonProperty("unique_name") final String uniqueName, @JsonProperty("attributes") final String attributes, - @JsonProperty("type") final ChannelType type, + @JsonProperty("type") final Channel.ChannelType type, @JsonProperty("date_created") final String dateCreated, @JsonProperty("date_updated") final String dateUpdated, @JsonProperty("created_by") final String createdBy, @@ -185,7 +185,7 @@ public final String getAttributes() { return this.attributes; } - public final ChannelType getType() { + public final Channel.ChannelType getType() { return this.type; } diff --git a/src/main/java/com/twilio/rest/chat/v2/service/Role.java b/src/main/java/com/twilio/rest/chat/v2/service/Role.java index b6dd5785ac..83550db69d 100644 --- a/src/main/java/com/twilio/rest/chat/v2/service/Role.java +++ b/src/main/java/com/twilio/rest/chat/v2/service/Role.java @@ -43,7 +43,7 @@ public class Role extends Resource { public static RoleCreator creator( final String pathServiceSid, final String friendlyName, - final RoleType type, + final Role.RoleType type, final List permission ) { return new RoleCreator(pathServiceSid, friendlyName, type, permission); @@ -122,7 +122,7 @@ public static Role fromJson( private final String accountSid; private final String serviceSid; private final String friendlyName; - private final RoleType type; + private final Role.RoleType type; private final List permissions; private final ZonedDateTime dateCreated; private final ZonedDateTime dateUpdated; @@ -134,7 +134,7 @@ private Role( @JsonProperty("account_sid") final String accountSid, @JsonProperty("service_sid") final String serviceSid, @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("type") final RoleType type, + @JsonProperty("type") final Role.RoleType type, @JsonProperty("permissions") final List permissions, @JsonProperty("date_created") final String dateCreated, @JsonProperty("date_updated") final String dateUpdated, @@ -167,7 +167,7 @@ public final String getFriendlyName() { return this.friendlyName; } - public final RoleType getType() { + public final Role.RoleType getType() { return this.type; } diff --git a/src/main/java/com/twilio/rest/chat/v2/service/channel/Webhook.java b/src/main/java/com/twilio/rest/chat/v2/service/channel/Webhook.java index b75b26253e..969a28cc11 100644 --- a/src/main/java/com/twilio/rest/chat/v2/service/channel/Webhook.java +++ b/src/main/java/com/twilio/rest/chat/v2/service/channel/Webhook.java @@ -44,7 +44,7 @@ public class Webhook extends Resource { public static WebhookCreator creator( final String pathServiceSid, final String pathChannelSid, - final Type type + final Webhook.Type type ) { return new WebhookCreator(pathServiceSid, pathChannelSid, type); } diff --git a/src/main/java/com/twilio/rest/chat/v2/service/user/UserBinding.java b/src/main/java/com/twilio/rest/chat/v2/service/user/UserBinding.java index 183db9c103..f95fefa538 100644 --- a/src/main/java/com/twilio/rest/chat/v2/service/user/UserBinding.java +++ b/src/main/java/com/twilio/rest/chat/v2/service/user/UserBinding.java @@ -115,7 +115,7 @@ public static UserBinding fromJson( private final String identity; private final String userSid; private final String credentialSid; - private final BindingType bindingType; + private final UserBinding.BindingType bindingType; private final List messageTypes; private final URI url; @@ -130,7 +130,7 @@ private UserBinding( @JsonProperty("identity") final String identity, @JsonProperty("user_sid") final String userSid, @JsonProperty("credential_sid") final String credentialSid, - @JsonProperty("binding_type") final BindingType bindingType, + @JsonProperty("binding_type") final UserBinding.BindingType bindingType, @JsonProperty("message_types") final List messageTypes, @JsonProperty("url") final URI url ) { @@ -184,7 +184,7 @@ public final String getCredentialSid() { return this.credentialSid; } - public final BindingType getBindingType() { + public final UserBinding.BindingType getBindingType() { return this.bindingType; } diff --git a/src/main/java/com/twilio/rest/chat/v2/service/user/UserChannel.java b/src/main/java/com/twilio/rest/chat/v2/service/user/UserChannel.java index 3dc09e5aa2..ebe37d60ac 100644 --- a/src/main/java/com/twilio/rest/chat/v2/service/user/UserChannel.java +++ b/src/main/java/com/twilio/rest/chat/v2/service/user/UserChannel.java @@ -130,12 +130,12 @@ public static UserChannel fromJson( private final String channelSid; private final String userSid; private final String memberSid; - private final ChannelStatus status; + private final UserChannel.ChannelStatus status; private final Integer lastConsumedMessageIndex; private final Integer unreadMessagesCount; private final Map links; private final URI url; - private final NotificationLevel notificationLevel; + private final UserChannel.NotificationLevel notificationLevel; @JsonCreator private UserChannel( @@ -144,7 +144,7 @@ private UserChannel( @JsonProperty("channel_sid") final String channelSid, @JsonProperty("user_sid") final String userSid, @JsonProperty("member_sid") final String memberSid, - @JsonProperty("status") final ChannelStatus status, + @JsonProperty("status") final UserChannel.ChannelStatus status, @JsonProperty( "last_consumed_message_index" ) final Integer lastConsumedMessageIndex, @@ -155,7 +155,7 @@ private UserChannel( @JsonProperty("url") final URI url, @JsonProperty( "notification_level" - ) final NotificationLevel notificationLevel + ) final UserChannel.NotificationLevel notificationLevel ) { this.accountSid = accountSid; this.serviceSid = serviceSid; @@ -190,7 +190,7 @@ public final String getMemberSid() { return this.memberSid; } - public final ChannelStatus getStatus() { + public final UserChannel.ChannelStatus getStatus() { return this.status; } @@ -210,7 +210,7 @@ public final URI getUrl() { return this.url; } - public final NotificationLevel getNotificationLevel() { + public final UserChannel.NotificationLevel getNotificationLevel() { return this.notificationLevel; } diff --git a/src/main/java/com/twilio/rest/chat/v3/Channel.java b/src/main/java/com/twilio/rest/chat/v3/Channel.java index b606cf5123..a46f618735 100644 --- a/src/main/java/com/twilio/rest/chat/v3/Channel.java +++ b/src/main/java/com/twilio/rest/chat/v3/Channel.java @@ -95,7 +95,7 @@ public static Channel fromJson( private final String friendlyName; private final String uniqueName; private final String attributes; - private final ChannelType type; + private final Channel.ChannelType type; private final ZonedDateTime dateCreated; private final ZonedDateTime dateUpdated; private final String createdBy; @@ -112,7 +112,7 @@ private Channel( @JsonProperty("friendly_name") final String friendlyName, @JsonProperty("unique_name") final String uniqueName, @JsonProperty("attributes") final String attributes, - @JsonProperty("type") final ChannelType type, + @JsonProperty("type") final Channel.ChannelType type, @JsonProperty("date_created") final String dateCreated, @JsonProperty("date_updated") final String dateUpdated, @JsonProperty("created_by") final String createdBy, @@ -161,7 +161,7 @@ public final String getAttributes() { return this.attributes; } - public final ChannelType getType() { + public final Channel.ChannelType getType() { return this.type; } diff --git a/src/main/java/com/twilio/rest/content/v1/Content.java b/src/main/java/com/twilio/rest/content/v1/Content.java index 15b9fb92e2..addc44ae73 100644 --- a/src/main/java/com/twilio/rest/content/v1/Content.java +++ b/src/main/java/com/twilio/rest/content/v1/Content.java @@ -942,7 +942,7 @@ public static ContentCreateRequest fromJson( } public static ContentCreator creator( - final ContentCreateRequest contentCreateRequest + final Content.ContentCreateRequest contentCreateRequest ) { return new ContentCreator(contentCreateRequest); } diff --git a/src/main/java/com/twilio/rest/content/v1/content/ApprovalCreate.java b/src/main/java/com/twilio/rest/content/v1/content/ApprovalCreate.java index f8856de11a..aff2efdaf5 100644 --- a/src/main/java/com/twilio/rest/content/v1/content/ApprovalCreate.java +++ b/src/main/java/com/twilio/rest/content/v1/content/ApprovalCreate.java @@ -72,7 +72,7 @@ public static ContentApprovalRequest fromJson( public static ApprovalCreateCreator creator( final String pathContentSid, - final ContentApprovalRequest contentApprovalRequest + final ApprovalCreate.ContentApprovalRequest contentApprovalRequest ) { return new ApprovalCreateCreator( pathContentSid, diff --git a/src/main/java/com/twilio/rest/conversations/v1/AddressConfiguration.java b/src/main/java/com/twilio/rest/conversations/v1/AddressConfiguration.java index 2aac078a95..b0b200cf5f 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/AddressConfiguration.java +++ b/src/main/java/com/twilio/rest/conversations/v1/AddressConfiguration.java @@ -42,7 +42,7 @@ public class AddressConfiguration extends Resource { private static final long serialVersionUID = 162346024858734L; public static AddressConfigurationCreator creator( - final Type type, + final AddressConfiguration.Type type, final String address ) { return new AddressConfigurationCreator(type, address); diff --git a/src/main/java/com/twilio/rest/conversations/v1/Conversation.java b/src/main/java/com/twilio/rest/conversations/v1/Conversation.java index 652dbc936b..dc54e2affc 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/Conversation.java +++ b/src/main/java/com/twilio/rest/conversations/v1/Conversation.java @@ -111,7 +111,7 @@ public static Conversation fromJson( private final String friendlyName; private final String uniqueName; private final String attributes; - private final State state; + private final Conversation.State state; private final ZonedDateTime dateCreated; private final ZonedDateTime dateUpdated; private final Map timers; @@ -128,7 +128,7 @@ private Conversation( @JsonProperty("friendly_name") final String friendlyName, @JsonProperty("unique_name") final String uniqueName, @JsonProperty("attributes") final String attributes, - @JsonProperty("state") final State state, + @JsonProperty("state") final Conversation.State state, @JsonProperty("date_created") final String dateCreated, @JsonProperty("date_updated") final String dateUpdated, @JsonProperty("timers") final Map timers, @@ -180,7 +180,7 @@ public final String getAttributes() { return this.attributes; } - public final State getState() { + public final Conversation.State getState() { return this.state; } diff --git a/src/main/java/com/twilio/rest/conversations/v1/ConversationWithParticipants.java b/src/main/java/com/twilio/rest/conversations/v1/ConversationWithParticipants.java index 26439f0d4f..ac73b9afa2 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/ConversationWithParticipants.java +++ b/src/main/java/com/twilio/rest/conversations/v1/ConversationWithParticipants.java @@ -101,7 +101,7 @@ public static ConversationWithParticipants fromJson( private final String friendlyName; private final String uniqueName; private final String attributes; - private final State state; + private final ConversationWithParticipants.State state; private final ZonedDateTime dateCreated; private final ZonedDateTime dateUpdated; private final Map timers; @@ -118,7 +118,7 @@ private ConversationWithParticipants( @JsonProperty("friendly_name") final String friendlyName, @JsonProperty("unique_name") final String uniqueName, @JsonProperty("attributes") final String attributes, - @JsonProperty("state") final State state, + @JsonProperty("state") final ConversationWithParticipants.State state, @JsonProperty("date_created") final String dateCreated, @JsonProperty("date_updated") final String dateUpdated, @JsonProperty("timers") final Map timers, @@ -170,7 +170,7 @@ public final String getAttributes() { return this.attributes; } - public final State getState() { + public final ConversationWithParticipants.State getState() { return this.state; } diff --git a/src/main/java/com/twilio/rest/conversations/v1/Credential.java b/src/main/java/com/twilio/rest/conversations/v1/Credential.java index 5d22d8174e..9b3cc9b62d 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/Credential.java +++ b/src/main/java/com/twilio/rest/conversations/v1/Credential.java @@ -39,7 +39,7 @@ public class Credential extends Resource { private static final long serialVersionUID = 265726674321801L; - public static CredentialCreator creator(final PushType type) { + public static CredentialCreator creator(final Credential.PushType type) { return new CredentialCreator(type); } @@ -105,7 +105,7 @@ public static Credential fromJson( private final String sid; private final String accountSid; private final String friendlyName; - private final PushType type; + private final Credential.PushType type; private final String sandbox; private final ZonedDateTime dateCreated; private final ZonedDateTime dateUpdated; @@ -116,7 +116,7 @@ private Credential( @JsonProperty("sid") final String sid, @JsonProperty("account_sid") final String accountSid, @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("type") final PushType type, + @JsonProperty("type") final Credential.PushType type, @JsonProperty("sandbox") final String sandbox, @JsonProperty("date_created") final String dateCreated, @JsonProperty("date_updated") final String dateUpdated, @@ -144,7 +144,7 @@ public final String getFriendlyName() { return this.friendlyName; } - public final PushType getType() { + public final Credential.PushType getType() { return this.type; } diff --git a/src/main/java/com/twilio/rest/conversations/v1/ParticipantConversation.java b/src/main/java/com/twilio/rest/conversations/v1/ParticipantConversation.java index e6dd3cfc82..49b97fb0c4 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/ParticipantConversation.java +++ b/src/main/java/com/twilio/rest/conversations/v1/ParticipantConversation.java @@ -100,7 +100,7 @@ public static ParticipantConversation fromJson( private final ZonedDateTime conversationDateCreated; private final ZonedDateTime conversationDateUpdated; private final String conversationCreatedBy; - private final State conversationState; + private final ParticipantConversation.State conversationState; private final Map conversationTimers; private final Map links; @@ -134,7 +134,9 @@ private ParticipantConversation( @JsonProperty( "conversation_created_by" ) final String conversationCreatedBy, - @JsonProperty("conversation_state") final State conversationState, + @JsonProperty( + "conversation_state" + ) final ParticipantConversation.State conversationState, @JsonProperty("conversation_timers") final Map< String, Object @@ -213,7 +215,7 @@ public final String getConversationCreatedBy() { return this.conversationCreatedBy; } - public final State getConversationState() { + public final ParticipantConversation.State getConversationState() { return this.conversationState; } diff --git a/src/main/java/com/twilio/rest/conversations/v1/Role.java b/src/main/java/com/twilio/rest/conversations/v1/Role.java index c20cf35b53..96ca04b94e 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/Role.java +++ b/src/main/java/com/twilio/rest/conversations/v1/Role.java @@ -42,7 +42,7 @@ public class Role extends Resource { public static RoleCreator creator( final String friendlyName, - final RoleType type, + final Role.RoleType type, final List permission ) { return new RoleCreator(friendlyName, type, permission); @@ -114,7 +114,7 @@ public static Role fromJson( private final String accountSid; private final String chatServiceSid; private final String friendlyName; - private final RoleType type; + private final Role.RoleType type; private final List permissions; private final ZonedDateTime dateCreated; private final ZonedDateTime dateUpdated; @@ -126,7 +126,7 @@ private Role( @JsonProperty("account_sid") final String accountSid, @JsonProperty("chat_service_sid") final String chatServiceSid, @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("type") final RoleType type, + @JsonProperty("type") final Role.RoleType type, @JsonProperty("permissions") final List permissions, @JsonProperty("date_created") final String dateCreated, @JsonProperty("date_updated") final String dateUpdated, @@ -159,7 +159,7 @@ public final String getFriendlyName() { return this.friendlyName; } - public final RoleType getType() { + public final Role.RoleType getType() { return this.type; } diff --git a/src/main/java/com/twilio/rest/conversations/v1/configuration/Webhook.java b/src/main/java/com/twilio/rest/conversations/v1/configuration/Webhook.java index 7633382178..485c684771 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/configuration/Webhook.java +++ b/src/main/java/com/twilio/rest/conversations/v1/configuration/Webhook.java @@ -90,21 +90,21 @@ public static Webhook fromJson( } private final String accountSid; - private final Method method; + private final Webhook.Method method; private final List filters; private final String preWebhookUrl; private final String postWebhookUrl; - private final Target target; + private final Webhook.Target target; private final URI url; @JsonCreator private Webhook( @JsonProperty("account_sid") final String accountSid, - @JsonProperty("method") final Method method, + @JsonProperty("method") final Webhook.Method method, @JsonProperty("filters") final List filters, @JsonProperty("pre_webhook_url") final String preWebhookUrl, @JsonProperty("post_webhook_url") final String postWebhookUrl, - @JsonProperty("target") final Target target, + @JsonProperty("target") final Webhook.Target target, @JsonProperty("url") final URI url ) { this.accountSid = accountSid; @@ -120,7 +120,7 @@ public final String getAccountSid() { return this.accountSid; } - public final Method getMethod() { + public final Webhook.Method getMethod() { return this.method; } @@ -136,7 +136,7 @@ public final String getPostWebhookUrl() { return this.postWebhookUrl; } - public final Target getTarget() { + public final Webhook.Target getTarget() { return this.target; } diff --git a/src/main/java/com/twilio/rest/conversations/v1/conversation/Webhook.java b/src/main/java/com/twilio/rest/conversations/v1/conversation/Webhook.java index 25b7ac3b9a..8bfea294d0 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/conversation/Webhook.java +++ b/src/main/java/com/twilio/rest/conversations/v1/conversation/Webhook.java @@ -43,7 +43,7 @@ public class Webhook extends Resource { public static WebhookCreator creator( final String pathConversationSid, - final Target target + final Webhook.Target target ) { return new WebhookCreator(pathConversationSid, target); } diff --git a/src/main/java/com/twilio/rest/conversations/v1/conversation/message/DeliveryReceipt.java b/src/main/java/com/twilio/rest/conversations/v1/conversation/message/DeliveryReceipt.java index b65ea7716d..5e5098d0a9 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/conversation/message/DeliveryReceipt.java +++ b/src/main/java/com/twilio/rest/conversations/v1/conversation/message/DeliveryReceipt.java @@ -107,7 +107,7 @@ public static DeliveryReceipt fromJson( private final String messageSid; private final String channelMessageSid; private final String participantSid; - private final DeliveryStatus status; + private final DeliveryReceipt.DeliveryStatus status; private final Integer errorCode; private final ZonedDateTime dateCreated; private final ZonedDateTime dateUpdated; @@ -121,7 +121,7 @@ private DeliveryReceipt( @JsonProperty("message_sid") final String messageSid, @JsonProperty("channel_message_sid") final String channelMessageSid, @JsonProperty("participant_sid") final String participantSid, - @JsonProperty("status") final DeliveryStatus status, + @JsonProperty("status") final DeliveryReceipt.DeliveryStatus status, @JsonProperty("error_code") final Integer errorCode, @JsonProperty("date_created") final String dateCreated, @JsonProperty("date_updated") final String dateUpdated, @@ -164,7 +164,7 @@ public final String getParticipantSid() { return this.participantSid; } - public final DeliveryStatus getStatus() { + public final DeliveryReceipt.DeliveryStatus getStatus() { return this.status; } diff --git a/src/main/java/com/twilio/rest/conversations/v1/service/Binding.java b/src/main/java/com/twilio/rest/conversations/v1/service/Binding.java index dd66e34198..0c10c7165f 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/service/Binding.java +++ b/src/main/java/com/twilio/rest/conversations/v1/service/Binding.java @@ -109,7 +109,7 @@ public static Binding fromJson( private final ZonedDateTime dateUpdated; private final String endpoint; private final String identity; - private final BindingType bindingType; + private final Binding.BindingType bindingType; private final List messageTypes; private final URI url; @@ -123,7 +123,7 @@ private Binding( @JsonProperty("date_updated") final String dateUpdated, @JsonProperty("endpoint") final String endpoint, @JsonProperty("identity") final String identity, - @JsonProperty("binding_type") final BindingType bindingType, + @JsonProperty("binding_type") final Binding.BindingType bindingType, @JsonProperty("message_types") final List messageTypes, @JsonProperty("url") final URI url ) { @@ -172,7 +172,7 @@ public final String getIdentity() { return this.identity; } - public final BindingType getBindingType() { + public final Binding.BindingType getBindingType() { return this.bindingType; } diff --git a/src/main/java/com/twilio/rest/conversations/v1/service/Conversation.java b/src/main/java/com/twilio/rest/conversations/v1/service/Conversation.java index f4aed3b123..181767e7e6 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/service/Conversation.java +++ b/src/main/java/com/twilio/rest/conversations/v1/service/Conversation.java @@ -120,7 +120,7 @@ public static Conversation fromJson( private final String friendlyName; private final String uniqueName; private final String attributes; - private final State state; + private final Conversation.State state; private final ZonedDateTime dateCreated; private final ZonedDateTime dateUpdated; private final Map timers; @@ -137,7 +137,7 @@ private Conversation( @JsonProperty("friendly_name") final String friendlyName, @JsonProperty("unique_name") final String uniqueName, @JsonProperty("attributes") final String attributes, - @JsonProperty("state") final State state, + @JsonProperty("state") final Conversation.State state, @JsonProperty("date_created") final String dateCreated, @JsonProperty("date_updated") final String dateUpdated, @JsonProperty("timers") final Map timers, @@ -189,7 +189,7 @@ public final String getAttributes() { return this.attributes; } - public final State getState() { + public final Conversation.State getState() { return this.state; } diff --git a/src/main/java/com/twilio/rest/conversations/v1/service/ConversationWithParticipants.java b/src/main/java/com/twilio/rest/conversations/v1/service/ConversationWithParticipants.java index 50554a0254..939f0389d7 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/service/ConversationWithParticipants.java +++ b/src/main/java/com/twilio/rest/conversations/v1/service/ConversationWithParticipants.java @@ -103,7 +103,7 @@ public static ConversationWithParticipants fromJson( private final String friendlyName; private final String uniqueName; private final String attributes; - private final State state; + private final ConversationWithParticipants.State state; private final ZonedDateTime dateCreated; private final ZonedDateTime dateUpdated; private final Map timers; @@ -120,7 +120,7 @@ private ConversationWithParticipants( @JsonProperty("friendly_name") final String friendlyName, @JsonProperty("unique_name") final String uniqueName, @JsonProperty("attributes") final String attributes, - @JsonProperty("state") final State state, + @JsonProperty("state") final ConversationWithParticipants.State state, @JsonProperty("date_created") final String dateCreated, @JsonProperty("date_updated") final String dateUpdated, @JsonProperty("timers") final Map timers, @@ -172,7 +172,7 @@ public final String getAttributes() { return this.attributes; } - public final State getState() { + public final ConversationWithParticipants.State getState() { return this.state; } diff --git a/src/main/java/com/twilio/rest/conversations/v1/service/ParticipantConversation.java b/src/main/java/com/twilio/rest/conversations/v1/service/ParticipantConversation.java index 8949265dc2..7ee5b2860d 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/service/ParticipantConversation.java +++ b/src/main/java/com/twilio/rest/conversations/v1/service/ParticipantConversation.java @@ -102,7 +102,7 @@ public static ParticipantConversation fromJson( private final ZonedDateTime conversationDateCreated; private final ZonedDateTime conversationDateUpdated; private final String conversationCreatedBy; - private final State conversationState; + private final ParticipantConversation.State conversationState; private final Map conversationTimers; private final Map links; @@ -136,7 +136,9 @@ private ParticipantConversation( @JsonProperty( "conversation_created_by" ) final String conversationCreatedBy, - @JsonProperty("conversation_state") final State conversationState, + @JsonProperty( + "conversation_state" + ) final ParticipantConversation.State conversationState, @JsonProperty("conversation_timers") final Map< String, Object @@ -215,7 +217,7 @@ public final String getConversationCreatedBy() { return this.conversationCreatedBy; } - public final State getConversationState() { + public final ParticipantConversation.State getConversationState() { return this.conversationState; } diff --git a/src/main/java/com/twilio/rest/conversations/v1/service/Role.java b/src/main/java/com/twilio/rest/conversations/v1/service/Role.java index 31e0a6501c..43c80476c7 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/service/Role.java +++ b/src/main/java/com/twilio/rest/conversations/v1/service/Role.java @@ -43,7 +43,7 @@ public class Role extends Resource { public static RoleCreator creator( final String pathChatServiceSid, final String friendlyName, - final RoleType type, + final Role.RoleType type, final List permission ) { return new RoleCreator( @@ -127,7 +127,7 @@ public static Role fromJson( private final String accountSid; private final String chatServiceSid; private final String friendlyName; - private final RoleType type; + private final Role.RoleType type; private final List permissions; private final ZonedDateTime dateCreated; private final ZonedDateTime dateUpdated; @@ -139,7 +139,7 @@ private Role( @JsonProperty("account_sid") final String accountSid, @JsonProperty("chat_service_sid") final String chatServiceSid, @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("type") final RoleType type, + @JsonProperty("type") final Role.RoleType type, @JsonProperty("permissions") final List permissions, @JsonProperty("date_created") final String dateCreated, @JsonProperty("date_updated") final String dateUpdated, @@ -172,7 +172,7 @@ public final String getFriendlyName() { return this.friendlyName; } - public final RoleType getType() { + public final Role.RoleType getType() { return this.type; } diff --git a/src/main/java/com/twilio/rest/conversations/v1/service/configuration/Webhook.java b/src/main/java/com/twilio/rest/conversations/v1/service/configuration/Webhook.java index a9965ee61f..9947722db0 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/service/configuration/Webhook.java +++ b/src/main/java/com/twilio/rest/conversations/v1/service/configuration/Webhook.java @@ -94,7 +94,7 @@ public static Webhook fromJson( private final URI preWebhookUrl; private final URI postWebhookUrl; private final List filters; - private final Method method; + private final Webhook.Method method; private final URI url; @JsonCreator @@ -104,7 +104,7 @@ private Webhook( @JsonProperty("pre_webhook_url") final URI preWebhookUrl, @JsonProperty("post_webhook_url") final URI postWebhookUrl, @JsonProperty("filters") final List filters, - @JsonProperty("method") final Method method, + @JsonProperty("method") final Webhook.Method method, @JsonProperty("url") final URI url ) { this.accountSid = accountSid; @@ -136,7 +136,7 @@ public final List getFilters() { return this.filters; } - public final Method getMethod() { + public final Webhook.Method getMethod() { return this.method; } diff --git a/src/main/java/com/twilio/rest/conversations/v1/service/conversation/Webhook.java b/src/main/java/com/twilio/rest/conversations/v1/service/conversation/Webhook.java index f60058cb16..3df7568adc 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/service/conversation/Webhook.java +++ b/src/main/java/com/twilio/rest/conversations/v1/service/conversation/Webhook.java @@ -44,7 +44,7 @@ public class Webhook extends Resource { public static WebhookCreator creator( final String pathChatServiceSid, final String pathConversationSid, - final Target target + final Webhook.Target target ) { return new WebhookCreator( pathChatServiceSid, diff --git a/src/main/java/com/twilio/rest/conversations/v1/service/conversation/message/DeliveryReceipt.java b/src/main/java/com/twilio/rest/conversations/v1/service/conversation/message/DeliveryReceipt.java index da0e2d35ee..f3a9dd829d 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/service/conversation/message/DeliveryReceipt.java +++ b/src/main/java/com/twilio/rest/conversations/v1/service/conversation/message/DeliveryReceipt.java @@ -115,7 +115,7 @@ public static DeliveryReceipt fromJson( private final String sid; private final String channelMessageSid; private final String participantSid; - private final DeliveryStatus status; + private final DeliveryReceipt.DeliveryStatus status; private final Integer errorCode; private final ZonedDateTime dateCreated; private final ZonedDateTime dateUpdated; @@ -130,7 +130,7 @@ private DeliveryReceipt( @JsonProperty("sid") final String sid, @JsonProperty("channel_message_sid") final String channelMessageSid, @JsonProperty("participant_sid") final String participantSid, - @JsonProperty("status") final DeliveryStatus status, + @JsonProperty("status") final DeliveryReceipt.DeliveryStatus status, @JsonProperty("error_code") final Integer errorCode, @JsonProperty("date_created") final String dateCreated, @JsonProperty("date_updated") final String dateUpdated, @@ -178,7 +178,7 @@ public final String getParticipantSid() { return this.participantSid; } - public final DeliveryStatus getStatus() { + public final DeliveryReceipt.DeliveryStatus getStatus() { return this.status; } diff --git a/src/main/java/com/twilio/rest/conversations/v1/service/user/UserConversation.java b/src/main/java/com/twilio/rest/conversations/v1/service/user/UserConversation.java index 42aecbd226..555ae5a2c6 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/service/user/UserConversation.java +++ b/src/main/java/com/twilio/rest/conversations/v1/service/user/UserConversation.java @@ -135,13 +135,13 @@ public static UserConversation fromJson( private final String participantSid; private final String userSid; private final String friendlyName; - private final State conversationState; + private final UserConversation.State conversationState; private final Map timers; private final String attributes; private final ZonedDateTime dateCreated; private final ZonedDateTime dateUpdated; private final String createdBy; - private final NotificationLevel notificationLevel; + private final UserConversation.NotificationLevel notificationLevel; private final String uniqueName; private final URI url; private final Map links; @@ -160,7 +160,9 @@ private UserConversation( @JsonProperty("participant_sid") final String participantSid, @JsonProperty("user_sid") final String userSid, @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("conversation_state") final State conversationState, + @JsonProperty( + "conversation_state" + ) final UserConversation.State conversationState, @JsonProperty("timers") final Map timers, @JsonProperty("attributes") final String attributes, @JsonProperty("date_created") final String dateCreated, @@ -168,7 +170,7 @@ private UserConversation( @JsonProperty("created_by") final String createdBy, @JsonProperty( "notification_level" - ) final NotificationLevel notificationLevel, + ) final UserConversation.NotificationLevel notificationLevel, @JsonProperty("unique_name") final String uniqueName, @JsonProperty("url") final URI url, @JsonProperty("links") final Map links @@ -225,7 +227,7 @@ public final String getFriendlyName() { return this.friendlyName; } - public final State getConversationState() { + public final UserConversation.State getConversationState() { return this.conversationState; } @@ -249,7 +251,7 @@ public final String getCreatedBy() { return this.createdBy; } - public final NotificationLevel getNotificationLevel() { + public final UserConversation.NotificationLevel getNotificationLevel() { return this.notificationLevel; } diff --git a/src/main/java/com/twilio/rest/conversations/v1/user/UserConversation.java b/src/main/java/com/twilio/rest/conversations/v1/user/UserConversation.java index 58fc49a1d0..2b21907430 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/user/UserConversation.java +++ b/src/main/java/com/twilio/rest/conversations/v1/user/UserConversation.java @@ -117,13 +117,13 @@ public static UserConversation fromJson( private final String participantSid; private final String userSid; private final String friendlyName; - private final State conversationState; + private final UserConversation.State conversationState; private final Map timers; private final String attributes; private final ZonedDateTime dateCreated; private final ZonedDateTime dateUpdated; private final String createdBy; - private final NotificationLevel notificationLevel; + private final UserConversation.NotificationLevel notificationLevel; private final String uniqueName; private final URI url; private final Map links; @@ -142,7 +142,9 @@ private UserConversation( @JsonProperty("participant_sid") final String participantSid, @JsonProperty("user_sid") final String userSid, @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("conversation_state") final State conversationState, + @JsonProperty( + "conversation_state" + ) final UserConversation.State conversationState, @JsonProperty("timers") final Map timers, @JsonProperty("attributes") final String attributes, @JsonProperty("date_created") final String dateCreated, @@ -150,7 +152,7 @@ private UserConversation( @JsonProperty("created_by") final String createdBy, @JsonProperty( "notification_level" - ) final NotificationLevel notificationLevel, + ) final UserConversation.NotificationLevel notificationLevel, @JsonProperty("unique_name") final String uniqueName, @JsonProperty("url") final URI url, @JsonProperty("links") final Map links @@ -207,7 +209,7 @@ public final String getFriendlyName() { return this.friendlyName; } - public final State getConversationState() { + public final UserConversation.State getConversationState() { return this.conversationState; } @@ -231,7 +233,7 @@ public final String getCreatedBy() { return this.createdBy; } - public final NotificationLevel getNotificationLevel() { + public final UserConversation.NotificationLevel getNotificationLevel() { return this.notificationLevel; } diff --git a/src/main/java/com/twilio/rest/events/v1/Sink.java b/src/main/java/com/twilio/rest/events/v1/Sink.java index 1d8a20eb62..8a5ea31e9c 100644 --- a/src/main/java/com/twilio/rest/events/v1/Sink.java +++ b/src/main/java/com/twilio/rest/events/v1/Sink.java @@ -44,7 +44,7 @@ public class Sink extends Resource { public static SinkCreator creator( final String description, final Object sinkConfiguration, - final SinkType sinkType + final Sink.SinkType sinkType ) { return new SinkCreator(description, sinkConfiguration, sinkType); } @@ -116,8 +116,8 @@ public static Sink fromJson( private final String description; private final String sid; private final Map sinkConfiguration; - private final SinkType sinkType; - private final Status status; + private final Sink.SinkType sinkType; + private final Sink.Status status; private final URI url; private final Map links; @@ -131,8 +131,8 @@ private Sink( String, Object > sinkConfiguration, - @JsonProperty("sink_type") final SinkType sinkType, - @JsonProperty("status") final Status status, + @JsonProperty("sink_type") final Sink.SinkType sinkType, + @JsonProperty("status") final Sink.Status status, @JsonProperty("url") final URI url, @JsonProperty("links") final Map links ) { @@ -167,11 +167,11 @@ public final Map getSinkConfiguration() { return this.sinkConfiguration; } - public final SinkType getSinkType() { + public final Sink.SinkType getSinkType() { return this.sinkType; } - public final Status getStatus() { + public final Sink.Status getStatus() { return this.status; } diff --git a/src/main/java/com/twilio/rest/events/v1/SubscriptionCreator.java b/src/main/java/com/twilio/rest/events/v1/SubscriptionCreator.java index fd9b3c97e5..32e9a37342 100644 --- a/src/main/java/com/twilio/rest/events/v1/SubscriptionCreator.java +++ b/src/main/java/com/twilio/rest/events/v1/SubscriptionCreator.java @@ -15,8 +15,9 @@ package com.twilio.rest.events.v1; import com.twilio.base.Creator; -import com.twilio.converter.Converter; import com.twilio.constant.EnumConstants; +import com.twilio.converter.Converter; +import com.twilio.converter.Converter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; diff --git a/src/main/java/com/twilio/rest/flexapi/v1/Configuration.java b/src/main/java/com/twilio/rest/flexapi/v1/Configuration.java index 42346f69ce..79e780fa58 100644 --- a/src/main/java/com/twilio/rest/flexapi/v1/Configuration.java +++ b/src/main/java/com/twilio/rest/flexapi/v1/Configuration.java @@ -110,7 +110,7 @@ public static String toJson(Object object, ObjectMapper mapper) { private final ZonedDateTime dateCreated; private final ZonedDateTime dateUpdated; private final Map attributes; - private final Status status; + private final Configuration.Status status; private final String taskrouterWorkspaceSid; private final String taskrouterTargetWorkflowSid; private final String taskrouterTargetTaskqueueSid; @@ -162,7 +162,7 @@ private Configuration( @JsonProperty("date_created") final String dateCreated, @JsonProperty("date_updated") final String dateUpdated, @JsonProperty("attributes") final Map attributes, - @JsonProperty("status") final Status status, + @JsonProperty("status") final Configuration.Status status, @JsonProperty( "taskrouter_workspace_sid" ) final String taskrouterWorkspaceSid, @@ -343,7 +343,7 @@ public final Map getAttributes() { return this.attributes; } - public final Status getStatus() { + public final Configuration.Status getStatus() { return this.status; } diff --git a/src/main/java/com/twilio/rest/flexapi/v1/FlexFlow.java b/src/main/java/com/twilio/rest/flexapi/v1/FlexFlow.java index ef505f09b5..ecfe3be905 100644 --- a/src/main/java/com/twilio/rest/flexapi/v1/FlexFlow.java +++ b/src/main/java/com/twilio/rest/flexapi/v1/FlexFlow.java @@ -44,7 +44,7 @@ public class FlexFlow extends Resource { public static FlexFlowCreator creator( final String friendlyName, final String chatServiceSid, - final ChannelType channelType + final FlexFlow.ChannelType channelType ) { return new FlexFlowCreator(friendlyName, chatServiceSid, channelType); } @@ -114,10 +114,10 @@ public static FlexFlow fromJson( private final String sid; private final String friendlyName; private final String chatServiceSid; - private final ChannelType channelType; + private final FlexFlow.ChannelType channelType; private final String contactIdentity; private final Boolean enabled; - private final IntegrationType integrationType; + private final FlexFlow.IntegrationType integrationType; private final Map integration; private final Boolean longLived; private final Boolean janitorEnabled; @@ -131,10 +131,12 @@ private FlexFlow( @JsonProperty("sid") final String sid, @JsonProperty("friendly_name") final String friendlyName, @JsonProperty("chat_service_sid") final String chatServiceSid, - @JsonProperty("channel_type") final ChannelType channelType, + @JsonProperty("channel_type") final FlexFlow.ChannelType channelType, @JsonProperty("contact_identity") final String contactIdentity, @JsonProperty("enabled") final Boolean enabled, - @JsonProperty("integration_type") final IntegrationType integrationType, + @JsonProperty( + "integration_type" + ) final FlexFlow.IntegrationType integrationType, @JsonProperty("integration") final Map integration, @JsonProperty("long_lived") final Boolean longLived, @JsonProperty("janitor_enabled") final Boolean janitorEnabled, @@ -180,7 +182,7 @@ public final String getChatServiceSid() { return this.chatServiceSid; } - public final ChannelType getChannelType() { + public final FlexFlow.ChannelType getChannelType() { return this.channelType; } @@ -192,7 +194,7 @@ public final Boolean getEnabled() { return this.enabled; } - public final IntegrationType getIntegrationType() { + public final FlexFlow.IntegrationType getIntegrationType() { return this.integrationType; } diff --git a/src/main/java/com/twilio/rest/flexapi/v1/PluginConfigurationCreator.java b/src/main/java/com/twilio/rest/flexapi/v1/PluginConfigurationCreator.java index 19dbfd4fee..3fc0e2b9d8 100644 --- a/src/main/java/com/twilio/rest/flexapi/v1/PluginConfigurationCreator.java +++ b/src/main/java/com/twilio/rest/flexapi/v1/PluginConfigurationCreator.java @@ -17,6 +17,7 @@ import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; import com.twilio.converter.Converter; +import com.twilio.converter.Converter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; diff --git a/src/main/java/com/twilio/rest/flexapi/v1/ProvisioningStatus.java b/src/main/java/com/twilio/rest/flexapi/v1/ProvisioningStatus.java index 4d04e64e6a..48fd242415 100644 --- a/src/main/java/com/twilio/rest/flexapi/v1/ProvisioningStatus.java +++ b/src/main/java/com/twilio/rest/flexapi/v1/ProvisioningStatus.java @@ -84,19 +84,19 @@ public static ProvisioningStatus fromJson( } } - private final Status status; + private final ProvisioningStatus.Status status; private final URI url; @JsonCreator private ProvisioningStatus( - @JsonProperty("status") final Status status, + @JsonProperty("status") final ProvisioningStatus.Status status, @JsonProperty("url") final URI url ) { this.status = status; this.url = url; } - public final Status getStatus() { + public final ProvisioningStatus.Status getStatus() { return this.status; } diff --git a/src/main/java/com/twilio/rest/flexapi/v1/interaction/InteractionChannel.java b/src/main/java/com/twilio/rest/flexapi/v1/interaction/InteractionChannel.java index 628600a80e..9c1d778e34 100644 --- a/src/main/java/com/twilio/rest/flexapi/v1/interaction/InteractionChannel.java +++ b/src/main/java/com/twilio/rest/flexapi/v1/interaction/InteractionChannel.java @@ -55,7 +55,7 @@ public static InteractionChannelReader reader( public static InteractionChannelUpdater updater( final String pathInteractionSid, final String pathSid, - final UpdateChannelStatus status + final InteractionChannel.UpdateChannelStatus status ) { return new InteractionChannelUpdater( pathInteractionSid, @@ -109,8 +109,8 @@ public static InteractionChannel fromJson( private final String sid; private final String interactionSid; - private final Type type; - private final ChannelStatus status; + private final InteractionChannel.Type type; + private final InteractionChannel.ChannelStatus status; private final Integer errorCode; private final String errorMessage; private final URI url; @@ -120,8 +120,8 @@ public static InteractionChannel fromJson( private InteractionChannel( @JsonProperty("sid") final String sid, @JsonProperty("interaction_sid") final String interactionSid, - @JsonProperty("type") final Type type, - @JsonProperty("status") final ChannelStatus status, + @JsonProperty("type") final InteractionChannel.Type type, + @JsonProperty("status") final InteractionChannel.ChannelStatus status, @JsonProperty("error_code") final Integer errorCode, @JsonProperty("error_message") final String errorMessage, @JsonProperty("url") final URI url, @@ -145,11 +145,11 @@ public final String getInteractionSid() { return this.interactionSid; } - public final Type getType() { + public final InteractionChannel.Type getType() { return this.type; } - public final ChannelStatus getStatus() { + public final InteractionChannel.ChannelStatus getStatus() { return this.status; } diff --git a/src/main/java/com/twilio/rest/flexapi/v1/interaction/interactionchannel/InteractionChannelParticipant.java b/src/main/java/com/twilio/rest/flexapi/v1/interaction/interactionchannel/InteractionChannelParticipant.java index d23c9ae21d..16c65ee470 100644 --- a/src/main/java/com/twilio/rest/flexapi/v1/interaction/interactionchannel/InteractionChannelParticipant.java +++ b/src/main/java/com/twilio/rest/flexapi/v1/interaction/interactionchannel/InteractionChannelParticipant.java @@ -42,7 +42,7 @@ public class InteractionChannelParticipant extends Resource { public static InteractionChannelParticipantCreator creator( final String pathInteractionSid, final String pathChannelSid, - final Type type, + final InteractionChannelParticipant.Type type, final Object mediaProperties ) { return new InteractionChannelParticipantCreator( @@ -67,7 +67,7 @@ public static InteractionChannelParticipantUpdater updater( final String pathInteractionSid, final String pathChannelSid, final String pathSid, - final Status status + final InteractionChannelParticipant.Status status ) { return new InteractionChannelParticipantUpdater( pathInteractionSid, @@ -127,7 +127,7 @@ public static InteractionChannelParticipant fromJson( } private final String sid; - private final Type type; + private final InteractionChannelParticipant.Type type; private final String interactionSid; private final String channelSid; private final URI url; @@ -136,7 +136,7 @@ public static InteractionChannelParticipant fromJson( @JsonCreator private InteractionChannelParticipant( @JsonProperty("sid") final String sid, - @JsonProperty("type") final Type type, + @JsonProperty("type") final InteractionChannelParticipant.Type type, @JsonProperty("interaction_sid") final String interactionSid, @JsonProperty("channel_sid") final String channelSid, @JsonProperty("url") final URI url, @@ -157,7 +157,7 @@ public final String getSid() { return this.sid; } - public final Type getType() { + public final InteractionChannelParticipant.Type getType() { return this.type; } diff --git a/src/main/java/com/twilio/rest/flexapi/v1/interaction/interactionchannel/InteractionTransfer.java b/src/main/java/com/twilio/rest/flexapi/v1/interaction/interactionchannel/InteractionTransfer.java index 7541c81831..40779ee7de 100644 --- a/src/main/java/com/twilio/rest/flexapi/v1/interaction/interactionchannel/InteractionTransfer.java +++ b/src/main/java/com/twilio/rest/flexapi/v1/interaction/interactionchannel/InteractionTransfer.java @@ -135,8 +135,8 @@ public static String toJson(Object object, ObjectMapper mapper) { private final String interactionSid; private final String channelSid; private final String executionSid; - private final TransferType type; - private final TransferStatus status; + private final InteractionTransfer.TransferType type; + private final InteractionTransfer.TransferStatus status; private final String from; private final String to; private final String noteSid; @@ -153,8 +153,8 @@ private InteractionTransfer( @JsonProperty("interaction_sid") final String interactionSid, @JsonProperty("channel_sid") final String channelSid, @JsonProperty("execution_sid") final String executionSid, - @JsonProperty("type") final TransferType type, - @JsonProperty("status") final TransferStatus status, + @JsonProperty("type") final InteractionTransfer.TransferType type, + @JsonProperty("status") final InteractionTransfer.TransferStatus status, @JsonProperty("from") final String from, @JsonProperty("to") final String to, @JsonProperty("note_sid") final String noteSid, @@ -204,11 +204,11 @@ public final String getExecutionSid() { return this.executionSid; } - public final TransferType getType() { + public final InteractionTransfer.TransferType getType() { return this.type; } - public final TransferStatus getStatus() { + public final InteractionTransfer.TransferStatus getStatus() { return this.status; } diff --git a/src/main/java/com/twilio/rest/frontlineapi/v1/User.java b/src/main/java/com/twilio/rest/frontlineapi/v1/User.java index 6bc81d1212..3534892247 100644 --- a/src/main/java/com/twilio/rest/frontlineapi/v1/User.java +++ b/src/main/java/com/twilio/rest/frontlineapi/v1/User.java @@ -92,7 +92,7 @@ public static User fromJson( private final String identity; private final String friendlyName; private final String avatar; - private final StateType state; + private final User.StateType state; private final Boolean isAvailable; private final URI url; @@ -102,7 +102,7 @@ private User( @JsonProperty("identity") final String identity, @JsonProperty("friendly_name") final String friendlyName, @JsonProperty("avatar") final String avatar, - @JsonProperty("state") final StateType state, + @JsonProperty("state") final User.StateType state, @JsonProperty("is_available") final Boolean isAvailable, @JsonProperty("url") final URI url ) { @@ -131,7 +131,7 @@ public final String getAvatar() { return this.avatar; } - public final StateType getState() { + public final User.StateType getState() { return this.state; } diff --git a/src/main/java/com/twilio/rest/insights/v1/CallSummaries.java b/src/main/java/com/twilio/rest/insights/v1/CallSummaries.java index 2c9a77afed..9741233555 100644 --- a/src/main/java/com/twilio/rest/insights/v1/CallSummaries.java +++ b/src/main/java/com/twilio/rest/insights/v1/CallSummaries.java @@ -91,10 +91,10 @@ public static CallSummaries fromJson( private final String accountSid; private final String callSid; - private final AnsweredBy answeredBy; - private final CallType callType; - private final CallState callState; - private final ProcessingState processingState; + private final CallSummaries.AnsweredBy answeredBy; + private final CallSummaries.CallType callType; + private final CallSummaries.CallState callState; + private final CallSummaries.ProcessingState processingState; private final ZonedDateTime createdTime; private final ZonedDateTime startTime; private final ZonedDateTime endTime; @@ -117,10 +117,12 @@ public static CallSummaries fromJson( private CallSummaries( @JsonProperty("account_sid") final String accountSid, @JsonProperty("call_sid") final String callSid, - @JsonProperty("answered_by") final AnsweredBy answeredBy, - @JsonProperty("call_type") final CallType callType, - @JsonProperty("call_state") final CallState callState, - @JsonProperty("processing_state") final ProcessingState processingState, + @JsonProperty("answered_by") final CallSummaries.AnsweredBy answeredBy, + @JsonProperty("call_type") final CallSummaries.CallType callType, + @JsonProperty("call_state") final CallSummaries.CallState callState, + @JsonProperty( + "processing_state" + ) final CallSummaries.ProcessingState processingState, @JsonProperty("created_time") final String createdTime, @JsonProperty("start_time") final String startTime, @JsonProperty("end_time") final String endTime, @@ -172,19 +174,19 @@ public final String getCallSid() { return this.callSid; } - public final AnsweredBy getAnsweredBy() { + public final CallSummaries.AnsweredBy getAnsweredBy() { return this.answeredBy; } - public final CallType getCallType() { + public final CallSummaries.CallType getCallType() { return this.callType; } - public final CallState getCallState() { + public final CallSummaries.CallState getCallState() { return this.callState; } - public final ProcessingState getProcessingState() { + public final CallSummaries.ProcessingState getProcessingState() { return this.processingState; } diff --git a/src/main/java/com/twilio/rest/insights/v1/Conference.java b/src/main/java/com/twilio/rest/insights/v1/Conference.java index 7a3e57b142..c6a41efe28 100644 --- a/src/main/java/com/twilio/rest/insights/v1/Conference.java +++ b/src/main/java/com/twilio/rest/insights/v1/Conference.java @@ -101,19 +101,19 @@ public static Conference fromJson( private final ZonedDateTime endTime; private final Integer durationSeconds; private final Integer connectDurationSeconds; - private final ConferenceStatus status; + private final Conference.ConferenceStatus status; private final Integer maxParticipants; private final Integer maxConcurrentParticipants; private final Integer uniqueParticipants; - private final ConferenceEndReason endReason; + private final Conference.ConferenceEndReason endReason; private final String endedBy; - private final Region mixerRegion; - private final Region mixerRegionRequested; + private final Conference.Region mixerRegion; + private final Conference.Region mixerRegionRequested; private final Boolean recordingEnabled; private final Map detectedIssues; - private final List tags; + private final List tags; private final Map tagInfo; - private final ProcessingState processingState; + private final Conference.ProcessingState processingState; private final URI url; private final Map links; @@ -129,26 +129,30 @@ private Conference( @JsonProperty( "connect_duration_seconds" ) final Integer connectDurationSeconds, - @JsonProperty("status") final ConferenceStatus status, + @JsonProperty("status") final Conference.ConferenceStatus status, @JsonProperty("max_participants") final Integer maxParticipants, @JsonProperty( "max_concurrent_participants" ) final Integer maxConcurrentParticipants, @JsonProperty("unique_participants") final Integer uniqueParticipants, - @JsonProperty("end_reason") final ConferenceEndReason endReason, + @JsonProperty( + "end_reason" + ) final Conference.ConferenceEndReason endReason, @JsonProperty("ended_by") final String endedBy, - @JsonProperty("mixer_region") final Region mixerRegion, + @JsonProperty("mixer_region") final Conference.Region mixerRegion, @JsonProperty( "mixer_region_requested" - ) final Region mixerRegionRequested, + ) final Conference.Region mixerRegionRequested, @JsonProperty("recording_enabled") final Boolean recordingEnabled, @JsonProperty("detected_issues") final Map< String, Object > detectedIssues, - @JsonProperty("tags") final List tags, + @JsonProperty("tags") final List tags, @JsonProperty("tag_info") final Map tagInfo, - @JsonProperty("processing_state") final ProcessingState processingState, + @JsonProperty( + "processing_state" + ) final Conference.ProcessingState processingState, @JsonProperty("url") final URI url, @JsonProperty("links") final Map links ) { @@ -209,7 +213,7 @@ public final Integer getConnectDurationSeconds() { return this.connectDurationSeconds; } - public final ConferenceStatus getStatus() { + public final Conference.ConferenceStatus getStatus() { return this.status; } @@ -225,7 +229,7 @@ public final Integer getUniqueParticipants() { return this.uniqueParticipants; } - public final ConferenceEndReason getEndReason() { + public final Conference.ConferenceEndReason getEndReason() { return this.endReason; } @@ -233,11 +237,11 @@ public final String getEndedBy() { return this.endedBy; } - public final Region getMixerRegion() { + public final Conference.Region getMixerRegion() { return this.mixerRegion; } - public final Region getMixerRegionRequested() { + public final Conference.Region getMixerRegionRequested() { return this.mixerRegionRequested; } @@ -249,7 +253,7 @@ public final Map getDetectedIssues() { return this.detectedIssues; } - public final List getTags() { + public final List getTags() { return this.tags; } @@ -257,7 +261,7 @@ public final Map getTagInfo() { return this.tagInfo; } - public final ProcessingState getProcessingState() { + public final Conference.ProcessingState getProcessingState() { return this.processingState; } diff --git a/src/main/java/com/twilio/rest/insights/v1/Room.java b/src/main/java/com/twilio/rest/insights/v1/Room.java index e3ad533bec..32a1fb2ece 100644 --- a/src/main/java/com/twilio/rest/insights/v1/Room.java +++ b/src/main/java/com/twilio/rest/insights/v1/Room.java @@ -99,25 +99,25 @@ public static Room fromJson( private final String roomName; private final ZonedDateTime createTime; private final ZonedDateTime endTime; - private final RoomType roomType; - private final RoomStatus roomStatus; + private final Room.RoomType roomType; + private final Room.RoomStatus roomStatus; private final URI statusCallback; private final HttpMethod statusCallbackMethod; - private final CreatedMethod createdMethod; - private final EndReason endReason; + private final Room.CreatedMethod createdMethod; + private final Room.EndReason endReason; private final Integer maxParticipants; private final Integer uniqueParticipants; private final Integer uniqueParticipantIdentities; private final Integer concurrentParticipants; private final Integer maxConcurrentParticipants; - private final List codecs; - private final TwilioRealm mediaRegion; + private final List codecs; + private final Room.TwilioRealm mediaRegion; private final Long durationSec; private final Long totalParticipantDurationSec; private final Long totalRecordingDurationSec; - private final ProcessingState processingState; + private final Room.ProcessingState processingState; private final Boolean recordingEnabled; - private final EdgeLocation edgeLocation; + private final Room.EdgeLocation edgeLocation; private final URI url; private final Map links; @@ -128,14 +128,14 @@ private Room( @JsonProperty("room_name") final String roomName, @JsonProperty("create_time") final String createTime, @JsonProperty("end_time") final String endTime, - @JsonProperty("room_type") final RoomType roomType, - @JsonProperty("room_status") final RoomStatus roomStatus, + @JsonProperty("room_type") final Room.RoomType roomType, + @JsonProperty("room_status") final Room.RoomStatus roomStatus, @JsonProperty("status_callback") final URI statusCallback, @JsonProperty( "status_callback_method" ) final HttpMethod statusCallbackMethod, - @JsonProperty("created_method") final CreatedMethod createdMethod, - @JsonProperty("end_reason") final EndReason endReason, + @JsonProperty("created_method") final Room.CreatedMethod createdMethod, + @JsonProperty("end_reason") final Room.EndReason endReason, @JsonProperty("max_participants") final Integer maxParticipants, @JsonProperty("unique_participants") final Integer uniqueParticipants, @JsonProperty( @@ -147,8 +147,8 @@ private Room( @JsonProperty( "max_concurrent_participants" ) final Integer maxConcurrentParticipants, - @JsonProperty("codecs") final List codecs, - @JsonProperty("media_region") final TwilioRealm mediaRegion, + @JsonProperty("codecs") final List codecs, + @JsonProperty("media_region") final Room.TwilioRealm mediaRegion, @JsonProperty("duration_sec") final Long durationSec, @JsonProperty( "total_participant_duration_sec" @@ -156,9 +156,11 @@ private Room( @JsonProperty( "total_recording_duration_sec" ) final Long totalRecordingDurationSec, - @JsonProperty("processing_state") final ProcessingState processingState, + @JsonProperty( + "processing_state" + ) final Room.ProcessingState processingState, @JsonProperty("recording_enabled") final Boolean recordingEnabled, - @JsonProperty("edge_location") final EdgeLocation edgeLocation, + @JsonProperty("edge_location") final Room.EdgeLocation edgeLocation, @JsonProperty("url") final URI url, @JsonProperty("links") final Map links ) { @@ -210,11 +212,11 @@ public final ZonedDateTime getEndTime() { return this.endTime; } - public final RoomType getRoomType() { + public final Room.RoomType getRoomType() { return this.roomType; } - public final RoomStatus getRoomStatus() { + public final Room.RoomStatus getRoomStatus() { return this.roomStatus; } @@ -226,11 +228,11 @@ public final HttpMethod getStatusCallbackMethod() { return this.statusCallbackMethod; } - public final CreatedMethod getCreatedMethod() { + public final Room.CreatedMethod getCreatedMethod() { return this.createdMethod; } - public final EndReason getEndReason() { + public final Room.EndReason getEndReason() { return this.endReason; } @@ -254,11 +256,11 @@ public final Integer getMaxConcurrentParticipants() { return this.maxConcurrentParticipants; } - public final List getCodecs() { + public final List getCodecs() { return this.codecs; } - public final TwilioRealm getMediaRegion() { + public final Room.TwilioRealm getMediaRegion() { return this.mediaRegion; } @@ -274,7 +276,7 @@ public final Long getTotalRecordingDurationSec() { return this.totalRecordingDurationSec; } - public final ProcessingState getProcessingState() { + public final Room.ProcessingState getProcessingState() { return this.processingState; } @@ -282,7 +284,7 @@ public final Boolean getRecordingEnabled() { return this.recordingEnabled; } - public final EdgeLocation getEdgeLocation() { + public final Room.EdgeLocation getEdgeLocation() { return this.edgeLocation; } diff --git a/src/main/java/com/twilio/rest/insights/v1/call/Annotation.java b/src/main/java/com/twilio/rest/insights/v1/call/Annotation.java index 0bb36cd0a0..0821e30210 100644 --- a/src/main/java/com/twilio/rest/insights/v1/call/Annotation.java +++ b/src/main/java/com/twilio/rest/insights/v1/call/Annotation.java @@ -91,8 +91,8 @@ public static Annotation fromJson( private final String callSid; private final String accountSid; - private final AnsweredBy answeredBy; - private final ConnectivityIssue connectivityIssue; + private final Annotation.AnsweredBy answeredBy; + private final Annotation.ConnectivityIssue connectivityIssue; private final List qualityIssues; private final Boolean spam; private final Integer callScore; @@ -104,10 +104,10 @@ public static Annotation fromJson( private Annotation( @JsonProperty("call_sid") final String callSid, @JsonProperty("account_sid") final String accountSid, - @JsonProperty("answered_by") final AnsweredBy answeredBy, + @JsonProperty("answered_by") final Annotation.AnsweredBy answeredBy, @JsonProperty( "connectivity_issue" - ) final ConnectivityIssue connectivityIssue, + ) final Annotation.ConnectivityIssue connectivityIssue, @JsonProperty("quality_issues") final List qualityIssues, @JsonProperty("spam") final Boolean spam, @JsonProperty("call_score") final Integer callScore, @@ -135,11 +135,11 @@ public final String getAccountSid() { return this.accountSid; } - public final AnsweredBy getAnsweredBy() { + public final Annotation.AnsweredBy getAnsweredBy() { return this.answeredBy; } - public final ConnectivityIssue getConnectivityIssue() { + public final Annotation.ConnectivityIssue getConnectivityIssue() { return this.connectivityIssue; } diff --git a/src/main/java/com/twilio/rest/insights/v1/call/CallSummary.java b/src/main/java/com/twilio/rest/insights/v1/call/CallSummary.java index 68ec399227..ae8c1be46a 100644 --- a/src/main/java/com/twilio/rest/insights/v1/call/CallSummary.java +++ b/src/main/java/com/twilio/rest/insights/v1/call/CallSummary.java @@ -91,10 +91,10 @@ public static CallSummary fromJson( private final String accountSid; private final String callSid; - private final CallType callType; - private final CallState callState; - private final AnsweredBy answeredBy; - private final ProcessingState processingState; + private final CallSummary.CallType callType; + private final CallSummary.CallState callState; + private final CallSummary.AnsweredBy answeredBy; + private final CallSummary.ProcessingState processingState; private final ZonedDateTime createdTime; private final ZonedDateTime startTime; private final ZonedDateTime endTime; @@ -117,10 +117,12 @@ public static CallSummary fromJson( private CallSummary( @JsonProperty("account_sid") final String accountSid, @JsonProperty("call_sid") final String callSid, - @JsonProperty("call_type") final CallType callType, - @JsonProperty("call_state") final CallState callState, - @JsonProperty("answered_by") final AnsweredBy answeredBy, - @JsonProperty("processing_state") final ProcessingState processingState, + @JsonProperty("call_type") final CallSummary.CallType callType, + @JsonProperty("call_state") final CallSummary.CallState callState, + @JsonProperty("answered_by") final CallSummary.AnsweredBy answeredBy, + @JsonProperty( + "processing_state" + ) final CallSummary.ProcessingState processingState, @JsonProperty("created_time") final String createdTime, @JsonProperty("start_time") final String startTime, @JsonProperty("end_time") final String endTime, @@ -172,19 +174,19 @@ public final String getCallSid() { return this.callSid; } - public final CallType getCallType() { + public final CallSummary.CallType getCallType() { return this.callType; } - public final CallState getCallState() { + public final CallSummary.CallState getCallState() { return this.callState; } - public final AnsweredBy getAnsweredBy() { + public final CallSummary.AnsweredBy getAnsweredBy() { return this.answeredBy; } - public final ProcessingState getProcessingState() { + public final CallSummary.ProcessingState getProcessingState() { return this.processingState; } diff --git a/src/main/java/com/twilio/rest/insights/v1/call/Event.java b/src/main/java/com/twilio/rest/insights/v1/call/Event.java index 72db3a8646..3d5803e58c 100644 --- a/src/main/java/com/twilio/rest/insights/v1/call/Event.java +++ b/src/main/java/com/twilio/rest/insights/v1/call/Event.java @@ -88,9 +88,9 @@ public static Event fromJson( private final String timestamp; private final String callSid; private final String accountSid; - private final TwilioEdge edge; + private final Event.TwilioEdge edge; private final String group; - private final Level level; + private final Event.Level level; private final String name; private final Map carrierEdge; private final Map sipEdge; @@ -102,9 +102,9 @@ private Event( @JsonProperty("timestamp") final String timestamp, @JsonProperty("call_sid") final String callSid, @JsonProperty("account_sid") final String accountSid, - @JsonProperty("edge") final TwilioEdge edge, + @JsonProperty("edge") final Event.TwilioEdge edge, @JsonProperty("group") final String group, - @JsonProperty("level") final Level level, + @JsonProperty("level") final Event.Level level, @JsonProperty("name") final String name, @JsonProperty("carrier_edge") final Map carrierEdge, @JsonProperty("sip_edge") final Map sipEdge, @@ -136,7 +136,7 @@ public final String getAccountSid() { return this.accountSid; } - public final TwilioEdge getEdge() { + public final Event.TwilioEdge getEdge() { return this.edge; } @@ -144,7 +144,7 @@ public final String getGroup() { return this.group; } - public final Level getLevel() { + public final Event.Level getLevel() { return this.level; } diff --git a/src/main/java/com/twilio/rest/insights/v1/call/Metric.java b/src/main/java/com/twilio/rest/insights/v1/call/Metric.java index e09bf425a6..c5bc8315e8 100644 --- a/src/main/java/com/twilio/rest/insights/v1/call/Metric.java +++ b/src/main/java/com/twilio/rest/insights/v1/call/Metric.java @@ -88,8 +88,8 @@ public static Metric fromJson( private final String timestamp; private final String callSid; private final String accountSid; - private final TwilioEdge edge; - private final StreamDirection direction; + private final Metric.TwilioEdge edge; + private final Metric.StreamDirection direction; private final Map carrierEdge; private final Map sipEdge; private final Map sdkEdge; @@ -100,8 +100,8 @@ private Metric( @JsonProperty("timestamp") final String timestamp, @JsonProperty("call_sid") final String callSid, @JsonProperty("account_sid") final String accountSid, - @JsonProperty("edge") final TwilioEdge edge, - @JsonProperty("direction") final StreamDirection direction, + @JsonProperty("edge") final Metric.TwilioEdge edge, + @JsonProperty("direction") final Metric.StreamDirection direction, @JsonProperty("carrier_edge") final Map carrierEdge, @JsonProperty("sip_edge") final Map sipEdge, @JsonProperty("sdk_edge") final Map sdkEdge, @@ -130,11 +130,11 @@ public final String getAccountSid() { return this.accountSid; } - public final TwilioEdge getEdge() { + public final Metric.TwilioEdge getEdge() { return this.edge; } - public final StreamDirection getDirection() { + public final Metric.StreamDirection getDirection() { return this.direction; } diff --git a/src/main/java/com/twilio/rest/insights/v1/conference/ConferenceParticipant.java b/src/main/java/com/twilio/rest/insights/v1/conference/ConferenceParticipant.java index b5996e37a3..d62a3c56fd 100644 --- a/src/main/java/com/twilio/rest/insights/v1/conference/ConferenceParticipant.java +++ b/src/main/java/com/twilio/rest/insights/v1/conference/ConferenceParticipant.java @@ -106,10 +106,10 @@ public static ConferenceParticipant fromJson( private final String conferenceSid; private final String callSid; private final String accountSid; - private final CallDirection callDirection; + private final ConferenceParticipant.CallDirection callDirection; private final String from; private final String to; - private final CallStatus callStatus; + private final ConferenceParticipant.CallStatus callStatus; private final String countryCode; private final Boolean isModerator; private final ZonedDateTime joinTime; @@ -117,13 +117,13 @@ public static ConferenceParticipant fromJson( private final Integer durationSeconds; private final Integer outboundQueueLength; private final Integer outboundTimeInQueue; - private final JitterBufferSize jitterBufferSize; + private final ConferenceParticipant.JitterBufferSize jitterBufferSize; private final Boolean isCoach; private final List coachedParticipants; - private final Region participantRegion; - private final Region conferenceRegion; - private final CallType callType; - private final ProcessingState processingState; + private final ConferenceParticipant.Region participantRegion; + private final ConferenceParticipant.Region conferenceRegion; + private final ConferenceParticipant.CallType callType; + private final ConferenceParticipant.ProcessingState processingState; private final Map properties; private final Map events; private final Map metrics; @@ -136,10 +136,14 @@ private ConferenceParticipant( @JsonProperty("conference_sid") final String conferenceSid, @JsonProperty("call_sid") final String callSid, @JsonProperty("account_sid") final String accountSid, - @JsonProperty("call_direction") final CallDirection callDirection, + @JsonProperty( + "call_direction" + ) final ConferenceParticipant.CallDirection callDirection, @JsonProperty("from") final String from, @JsonProperty("to") final String to, - @JsonProperty("call_status") final CallStatus callStatus, + @JsonProperty( + "call_status" + ) final ConferenceParticipant.CallStatus callStatus, @JsonProperty("country_code") final String countryCode, @JsonProperty("is_moderator") final Boolean isModerator, @JsonProperty("join_time") final String joinTime, @@ -153,15 +157,23 @@ private ConferenceParticipant( ) final Integer outboundTimeInQueue, @JsonProperty( "jitter_buffer_size" - ) final JitterBufferSize jitterBufferSize, + ) final ConferenceParticipant.JitterBufferSize jitterBufferSize, @JsonProperty("is_coach") final Boolean isCoach, @JsonProperty("coached_participants") final List< String > coachedParticipants, - @JsonProperty("participant_region") final Region participantRegion, - @JsonProperty("conference_region") final Region conferenceRegion, - @JsonProperty("call_type") final CallType callType, - @JsonProperty("processing_state") final ProcessingState processingState, + @JsonProperty( + "participant_region" + ) final ConferenceParticipant.Region participantRegion, + @JsonProperty( + "conference_region" + ) final ConferenceParticipant.Region conferenceRegion, + @JsonProperty( + "call_type" + ) final ConferenceParticipant.CallType callType, + @JsonProperty( + "processing_state" + ) final ConferenceParticipant.ProcessingState processingState, @JsonProperty("properties") final Map properties, @JsonProperty("events") final Map events, @JsonProperty("metrics") final Map metrics, @@ -216,7 +228,7 @@ public final String getAccountSid() { return this.accountSid; } - public final CallDirection getCallDirection() { + public final ConferenceParticipant.CallDirection getCallDirection() { return this.callDirection; } @@ -228,7 +240,7 @@ public final String getTo() { return this.to; } - public final CallStatus getCallStatus() { + public final ConferenceParticipant.CallStatus getCallStatus() { return this.callStatus; } @@ -260,7 +272,7 @@ public final Integer getOutboundTimeInQueue() { return this.outboundTimeInQueue; } - public final JitterBufferSize getJitterBufferSize() { + public final ConferenceParticipant.JitterBufferSize getJitterBufferSize() { return this.jitterBufferSize; } @@ -272,19 +284,19 @@ public final List getCoachedParticipants() { return this.coachedParticipants; } - public final Region getParticipantRegion() { + public final ConferenceParticipant.Region getParticipantRegion() { return this.participantRegion; } - public final Region getConferenceRegion() { + public final ConferenceParticipant.Region getConferenceRegion() { return this.conferenceRegion; } - public final CallType getCallType() { + public final ConferenceParticipant.CallType getCallType() { return this.callType; } - public final ProcessingState getProcessingState() { + public final ConferenceParticipant.ProcessingState getProcessingState() { return this.processingState; } diff --git a/src/main/java/com/twilio/rest/insights/v1/room/Participant.java b/src/main/java/com/twilio/rest/insights/v1/room/Participant.java index bef00bd135..db0b8b2325 100644 --- a/src/main/java/com/twilio/rest/insights/v1/room/Participant.java +++ b/src/main/java/com/twilio/rest/insights/v1/room/Participant.java @@ -103,14 +103,14 @@ public static Participant fromJson( private final Long durationSec; private final String accountSid; private final String roomSid; - private final RoomStatus status; - private final List codecs; + private final Participant.RoomStatus status; + private final List codecs; private final String endReason; private final Integer errorCode; private final String errorCodeUrl; - private final TwilioRealm mediaRegion; + private final Participant.TwilioRealm mediaRegion; private final Map properties; - private final EdgeLocation edgeLocation; + private final Participant.EdgeLocation edgeLocation; private final Map publisherInfo; private final URI url; @@ -123,14 +123,16 @@ private Participant( @JsonProperty("duration_sec") final Long durationSec, @JsonProperty("account_sid") final String accountSid, @JsonProperty("room_sid") final String roomSid, - @JsonProperty("status") final RoomStatus status, - @JsonProperty("codecs") final List codecs, + @JsonProperty("status") final Participant.RoomStatus status, + @JsonProperty("codecs") final List codecs, @JsonProperty("end_reason") final String endReason, @JsonProperty("error_code") final Integer errorCode, @JsonProperty("error_code_url") final String errorCodeUrl, - @JsonProperty("media_region") final TwilioRealm mediaRegion, + @JsonProperty("media_region") final Participant.TwilioRealm mediaRegion, @JsonProperty("properties") final Map properties, - @JsonProperty("edge_location") final EdgeLocation edgeLocation, + @JsonProperty( + "edge_location" + ) final Participant.EdgeLocation edgeLocation, @JsonProperty("publisher_info") final Map publisherInfo, @JsonProperty("url") final URI url ) { @@ -181,11 +183,11 @@ public final String getRoomSid() { return this.roomSid; } - public final RoomStatus getStatus() { + public final Participant.RoomStatus getStatus() { return this.status; } - public final List getCodecs() { + public final List getCodecs() { return this.codecs; } @@ -201,7 +203,7 @@ public final String getErrorCodeUrl() { return this.errorCodeUrl; } - public final TwilioRealm getMediaRegion() { + public final Participant.TwilioRealm getMediaRegion() { return this.mediaRegion; } @@ -209,7 +211,7 @@ public final Map getProperties() { return this.properties; } - public final EdgeLocation getEdgeLocation() { + public final Participant.EdgeLocation getEdgeLocation() { return this.edgeLocation; } diff --git a/src/main/java/com/twilio/rest/intelligence/v2/CustomOperator.java b/src/main/java/com/twilio/rest/intelligence/v2/CustomOperator.java index ca2d94f285..577770f332 100644 --- a/src/main/java/com/twilio/rest/intelligence/v2/CustomOperator.java +++ b/src/main/java/com/twilio/rest/intelligence/v2/CustomOperator.java @@ -119,7 +119,7 @@ public static CustomOperator fromJson( private final String author; private final String operatorType; private final Integer version; - private final Availability availability; + private final CustomOperator.Availability availability; private final Map config; private final ZonedDateTime dateCreated; private final ZonedDateTime dateUpdated; @@ -134,7 +134,9 @@ private CustomOperator( @JsonProperty("author") final String author, @JsonProperty("operator_type") final String operatorType, @JsonProperty("version") final Integer version, - @JsonProperty("availability") final Availability availability, + @JsonProperty( + "availability" + ) final CustomOperator.Availability availability, @JsonProperty("config") final Map config, @JsonProperty("date_created") final String dateCreated, @JsonProperty("date_updated") final String dateUpdated, @@ -182,7 +184,7 @@ public final Integer getVersion() { return this.version; } - public final Availability getAvailability() { + public final CustomOperator.Availability getAvailability() { return this.availability; } diff --git a/src/main/java/com/twilio/rest/intelligence/v2/Operator.java b/src/main/java/com/twilio/rest/intelligence/v2/Operator.java index d5d656a4ed..a9c425c153 100644 --- a/src/main/java/com/twilio/rest/intelligence/v2/Operator.java +++ b/src/main/java/com/twilio/rest/intelligence/v2/Operator.java @@ -99,7 +99,7 @@ public static Operator fromJson( private final String author; private final String operatorType; private final Integer version; - private final Availability availability; + private final Operator.Availability availability; private final Map config; private final ZonedDateTime dateCreated; private final ZonedDateTime dateUpdated; @@ -114,7 +114,7 @@ private Operator( @JsonProperty("author") final String author, @JsonProperty("operator_type") final String operatorType, @JsonProperty("version") final Integer version, - @JsonProperty("availability") final Availability availability, + @JsonProperty("availability") final Operator.Availability availability, @JsonProperty("config") final Map config, @JsonProperty("date_created") final String dateCreated, @JsonProperty("date_updated") final String dateUpdated, @@ -162,7 +162,7 @@ public final Integer getVersion() { return this.version; } - public final Availability getAvailability() { + public final Operator.Availability getAvailability() { return this.availability; } diff --git a/src/main/java/com/twilio/rest/intelligence/v2/OperatorType.java b/src/main/java/com/twilio/rest/intelligence/v2/OperatorType.java index 03d6717137..566ab5cb66 100644 --- a/src/main/java/com/twilio/rest/intelligence/v2/OperatorType.java +++ b/src/main/java/com/twilio/rest/intelligence/v2/OperatorType.java @@ -98,10 +98,10 @@ public static OperatorType fromJson( private final String friendlyName; private final String description; private final URI docsLink; - private final OutputType outputType; + private final OperatorType.OutputType outputType; private final List supportedLanguages; - private final Provider provider; - private final Availability availability; + private final OperatorType.Provider provider; + private final OperatorType.Availability availability; private final Boolean configurable; private final Map configSchema; private final ZonedDateTime dateCreated; @@ -115,12 +115,14 @@ private OperatorType( @JsonProperty("friendly_name") final String friendlyName, @JsonProperty("description") final String description, @JsonProperty("docs_link") final URI docsLink, - @JsonProperty("output_type") final OutputType outputType, + @JsonProperty("output_type") final OperatorType.OutputType outputType, @JsonProperty("supported_languages") final List< String > supportedLanguages, - @JsonProperty("provider") final Provider provider, - @JsonProperty("availability") final Availability availability, + @JsonProperty("provider") final OperatorType.Provider provider, + @JsonProperty( + "availability" + ) final OperatorType.Availability availability, @JsonProperty("configurable") final Boolean configurable, @JsonProperty("config_schema") final Map configSchema, @JsonProperty("date_created") final String dateCreated, @@ -163,7 +165,7 @@ public final URI getDocsLink() { return this.docsLink; } - public final OutputType getOutputType() { + public final OperatorType.OutputType getOutputType() { return this.outputType; } @@ -171,11 +173,11 @@ public final List getSupportedLanguages() { return this.supportedLanguages; } - public final Provider getProvider() { + public final OperatorType.Provider getProvider() { return this.provider; } - public final Availability getAvailability() { + public final OperatorType.Availability getAvailability() { return this.availability; } diff --git a/src/main/java/com/twilio/rest/intelligence/v2/PrebuiltOperator.java b/src/main/java/com/twilio/rest/intelligence/v2/PrebuiltOperator.java index 9d2fc4e69c..c9b414a546 100644 --- a/src/main/java/com/twilio/rest/intelligence/v2/PrebuiltOperator.java +++ b/src/main/java/com/twilio/rest/intelligence/v2/PrebuiltOperator.java @@ -99,7 +99,7 @@ public static PrebuiltOperator fromJson( private final String author; private final String operatorType; private final Integer version; - private final Availability availability; + private final PrebuiltOperator.Availability availability; private final Map config; private final ZonedDateTime dateCreated; private final ZonedDateTime dateUpdated; @@ -114,7 +114,9 @@ private PrebuiltOperator( @JsonProperty("author") final String author, @JsonProperty("operator_type") final String operatorType, @JsonProperty("version") final Integer version, - @JsonProperty("availability") final Availability availability, + @JsonProperty( + "availability" + ) final PrebuiltOperator.Availability availability, @JsonProperty("config") final Map config, @JsonProperty("date_created") final String dateCreated, @JsonProperty("date_updated") final String dateUpdated, @@ -162,7 +164,7 @@ public final Integer getVersion() { return this.version; } - public final Availability getAvailability() { + public final PrebuiltOperator.Availability getAvailability() { return this.availability; } diff --git a/src/main/java/com/twilio/rest/intelligence/v2/Service.java b/src/main/java/com/twilio/rest/intelligence/v2/Service.java index b72a89dcaa..6a14108124 100644 --- a/src/main/java/com/twilio/rest/intelligence/v2/Service.java +++ b/src/main/java/com/twilio/rest/intelligence/v2/Service.java @@ -117,7 +117,7 @@ public static Service fromJson( private final String uniqueName; private final URI url; private final String webhookUrl; - private final HttpMethod webhookHttpMethod; + private final Service.HttpMethod webhookHttpMethod; private final List readOnlyAttachedOperatorSids; private final Integer version; @@ -136,7 +136,9 @@ private Service( @JsonProperty("unique_name") final String uniqueName, @JsonProperty("url") final URI url, @JsonProperty("webhook_url") final String webhookUrl, - @JsonProperty("webhook_http_method") final HttpMethod webhookHttpMethod, + @JsonProperty( + "webhook_http_method" + ) final Service.HttpMethod webhookHttpMethod, @JsonProperty("read_only_attached_operator_sids") final List< String > readOnlyAttachedOperatorSids, @@ -212,7 +214,7 @@ public final String getWebhookUrl() { return this.webhookUrl; } - public final HttpMethod getWebhookHttpMethod() { + public final Service.HttpMethod getWebhookHttpMethod() { return this.webhookHttpMethod; } diff --git a/src/main/java/com/twilio/rest/intelligence/v2/Transcript.java b/src/main/java/com/twilio/rest/intelligence/v2/Transcript.java index 5ef033357a..0e19d311a1 100644 --- a/src/main/java/com/twilio/rest/intelligence/v2/Transcript.java +++ b/src/main/java/com/twilio/rest/intelligence/v2/Transcript.java @@ -108,7 +108,7 @@ public static Transcript fromJson( private final String sid; private final ZonedDateTime dateCreated; private final ZonedDateTime dateUpdated; - private final Status status; + private final Transcript.Status status; private final Map channel; private final Boolean dataLogging; private final String languageCode; @@ -126,7 +126,7 @@ private Transcript( @JsonProperty("sid") final String sid, @JsonProperty("date_created") final String dateCreated, @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("status") final Status status, + @JsonProperty("status") final Transcript.Status status, @JsonProperty("channel") final Map channel, @JsonProperty("data_logging") final Boolean dataLogging, @JsonProperty("language_code") final String languageCode, @@ -175,7 +175,7 @@ public final ZonedDateTime getDateUpdated() { return this.dateUpdated; } - public final Status getStatus() { + public final Transcript.Status getStatus() { return this.status; } diff --git a/src/main/java/com/twilio/rest/intelligence/v2/transcript/OperatorResult.java b/src/main/java/com/twilio/rest/intelligence/v2/transcript/OperatorResult.java index 6ceb37f984..8e734ee75a 100644 --- a/src/main/java/com/twilio/rest/intelligence/v2/transcript/OperatorResult.java +++ b/src/main/java/com/twilio/rest/intelligence/v2/transcript/OperatorResult.java @@ -95,7 +95,7 @@ public static OperatorResult fromJson( } } - private final OperatorType operatorType; + private final OperatorResult.OperatorType operatorType; private final String name; private final String operatorSid; private final Boolean extractMatch; @@ -114,7 +114,9 @@ public static OperatorResult fromJson( @JsonCreator private OperatorResult( - @JsonProperty("operator_type") final OperatorType operatorType, + @JsonProperty( + "operator_type" + ) final OperatorResult.OperatorType operatorType, @JsonProperty("name") final String name, @JsonProperty("operator_sid") final String operatorSid, @JsonProperty("extract_match") final Boolean extractMatch, @@ -162,7 +164,7 @@ private OperatorResult( this.url = url; } - public final OperatorType getOperatorType() { + public final OperatorResult.OperatorType getOperatorType() { return this.operatorType; } diff --git a/src/main/java/com/twilio/rest/ipmessaging/v1/Credential.java b/src/main/java/com/twilio/rest/ipmessaging/v1/Credential.java index 00a5ede142..c18921f709 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v1/Credential.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v1/Credential.java @@ -39,7 +39,7 @@ public class Credential extends Resource { private static final long serialVersionUID = 161183169234848L; - public static CredentialCreator creator(final PushService type) { + public static CredentialCreator creator(final Credential.PushService type) { return new CredentialCreator(type); } @@ -105,7 +105,7 @@ public static Credential fromJson( private final String sid; private final String accountSid; private final String friendlyName; - private final PushService type; + private final Credential.PushService type; private final String sandbox; private final ZonedDateTime dateCreated; private final ZonedDateTime dateUpdated; @@ -116,7 +116,7 @@ private Credential( @JsonProperty("sid") final String sid, @JsonProperty("account_sid") final String accountSid, @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("type") final PushService type, + @JsonProperty("type") final Credential.PushService type, @JsonProperty("sandbox") final String sandbox, @JsonProperty("date_created") final String dateCreated, @JsonProperty("date_updated") final String dateUpdated, @@ -144,7 +144,7 @@ public final String getFriendlyName() { return this.friendlyName; } - public final PushService getType() { + public final Credential.PushService getType() { return this.type; } diff --git a/src/main/java/com/twilio/rest/ipmessaging/v1/service/Channel.java b/src/main/java/com/twilio/rest/ipmessaging/v1/service/Channel.java index 3e872e729e..716231236c 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v1/service/Channel.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v1/service/Channel.java @@ -119,7 +119,7 @@ public static Channel fromJson( private final String friendlyName; private final String uniqueName; private final String attributes; - private final ChannelType type; + private final Channel.ChannelType type; private final ZonedDateTime dateCreated; private final ZonedDateTime dateUpdated; private final String createdBy; @@ -136,7 +136,7 @@ private Channel( @JsonProperty("friendly_name") final String friendlyName, @JsonProperty("unique_name") final String uniqueName, @JsonProperty("attributes") final String attributes, - @JsonProperty("type") final ChannelType type, + @JsonProperty("type") final Channel.ChannelType type, @JsonProperty("date_created") final String dateCreated, @JsonProperty("date_updated") final String dateUpdated, @JsonProperty("created_by") final String createdBy, @@ -185,7 +185,7 @@ public final String getAttributes() { return this.attributes; } - public final ChannelType getType() { + public final Channel.ChannelType getType() { return this.type; } diff --git a/src/main/java/com/twilio/rest/ipmessaging/v1/service/Role.java b/src/main/java/com/twilio/rest/ipmessaging/v1/service/Role.java index cca17cdc8e..85ffef93d3 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v1/service/Role.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v1/service/Role.java @@ -43,7 +43,7 @@ public class Role extends Resource { public static RoleCreator creator( final String pathServiceSid, final String friendlyName, - final RoleType type, + final Role.RoleType type, final List permission ) { return new RoleCreator(pathServiceSid, friendlyName, type, permission); @@ -122,7 +122,7 @@ public static Role fromJson( private final String accountSid; private final String serviceSid; private final String friendlyName; - private final RoleType type; + private final Role.RoleType type; private final List permissions; private final ZonedDateTime dateCreated; private final ZonedDateTime dateUpdated; @@ -134,7 +134,7 @@ private Role( @JsonProperty("account_sid") final String accountSid, @JsonProperty("service_sid") final String serviceSid, @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("type") final RoleType type, + @JsonProperty("type") final Role.RoleType type, @JsonProperty("permissions") final List permissions, @JsonProperty("date_created") final String dateCreated, @JsonProperty("date_updated") final String dateUpdated, @@ -167,7 +167,7 @@ public final String getFriendlyName() { return this.friendlyName; } - public final RoleType getType() { + public final Role.RoleType getType() { return this.type; } diff --git a/src/main/java/com/twilio/rest/ipmessaging/v1/service/user/UserChannel.java b/src/main/java/com/twilio/rest/ipmessaging/v1/service/user/UserChannel.java index 1aed0d0471..05ee6541e0 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v1/service/user/UserChannel.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v1/service/user/UserChannel.java @@ -92,7 +92,7 @@ public static UserChannel fromJson( private final String serviceSid; private final String channelSid; private final String memberSid; - private final ChannelStatus status; + private final UserChannel.ChannelStatus status; private final Integer lastConsumedMessageIndex; private final Integer unreadMessagesCount; private final Map links; @@ -103,7 +103,7 @@ private UserChannel( @JsonProperty("service_sid") final String serviceSid, @JsonProperty("channel_sid") final String channelSid, @JsonProperty("member_sid") final String memberSid, - @JsonProperty("status") final ChannelStatus status, + @JsonProperty("status") final UserChannel.ChannelStatus status, @JsonProperty( "last_consumed_message_index" ) final Integer lastConsumedMessageIndex, @@ -138,7 +138,7 @@ public final String getMemberSid() { return this.memberSid; } - public final ChannelStatus getStatus() { + public final UserChannel.ChannelStatus getStatus() { return this.status; } diff --git a/src/main/java/com/twilio/rest/ipmessaging/v2/Credential.java b/src/main/java/com/twilio/rest/ipmessaging/v2/Credential.java index f7beefe431..9f6267c773 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v2/Credential.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v2/Credential.java @@ -39,7 +39,7 @@ public class Credential extends Resource { private static final long serialVersionUID = 161183169234848L; - public static CredentialCreator creator(final PushService type) { + public static CredentialCreator creator(final Credential.PushService type) { return new CredentialCreator(type); } @@ -105,7 +105,7 @@ public static Credential fromJson( private final String sid; private final String accountSid; private final String friendlyName; - private final PushService type; + private final Credential.PushService type; private final String sandbox; private final ZonedDateTime dateCreated; private final ZonedDateTime dateUpdated; @@ -116,7 +116,7 @@ private Credential( @JsonProperty("sid") final String sid, @JsonProperty("account_sid") final String accountSid, @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("type") final PushService type, + @JsonProperty("type") final Credential.PushService type, @JsonProperty("sandbox") final String sandbox, @JsonProperty("date_created") final String dateCreated, @JsonProperty("date_updated") final String dateUpdated, @@ -144,7 +144,7 @@ public final String getFriendlyName() { return this.friendlyName; } - public final PushService getType() { + public final Credential.PushService getType() { return this.type; } diff --git a/src/main/java/com/twilio/rest/ipmessaging/v2/service/Binding.java b/src/main/java/com/twilio/rest/ipmessaging/v2/service/Binding.java index fecd63144c..3004b0a963 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v2/service/Binding.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v2/service/Binding.java @@ -111,7 +111,7 @@ public static Binding fromJson( private final String endpoint; private final String identity; private final String credentialSid; - private final BindingType bindingType; + private final Binding.BindingType bindingType; private final List messageTypes; private final URI url; private final Map links; @@ -126,7 +126,7 @@ private Binding( @JsonProperty("endpoint") final String endpoint, @JsonProperty("identity") final String identity, @JsonProperty("credential_sid") final String credentialSid, - @JsonProperty("binding_type") final BindingType bindingType, + @JsonProperty("binding_type") final Binding.BindingType bindingType, @JsonProperty("message_types") final List messageTypes, @JsonProperty("url") final URI url, @JsonProperty("links") final Map links @@ -177,7 +177,7 @@ public final String getCredentialSid() { return this.credentialSid; } - public final BindingType getBindingType() { + public final Binding.BindingType getBindingType() { return this.bindingType; } diff --git a/src/main/java/com/twilio/rest/ipmessaging/v2/service/Channel.java b/src/main/java/com/twilio/rest/ipmessaging/v2/service/Channel.java index 8b738c76e5..19ae5463c6 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v2/service/Channel.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v2/service/Channel.java @@ -119,7 +119,7 @@ public static Channel fromJson( private final String friendlyName; private final String uniqueName; private final String attributes; - private final ChannelType type; + private final Channel.ChannelType type; private final ZonedDateTime dateCreated; private final ZonedDateTime dateUpdated; private final String createdBy; @@ -136,7 +136,7 @@ private Channel( @JsonProperty("friendly_name") final String friendlyName, @JsonProperty("unique_name") final String uniqueName, @JsonProperty("attributes") final String attributes, - @JsonProperty("type") final ChannelType type, + @JsonProperty("type") final Channel.ChannelType type, @JsonProperty("date_created") final String dateCreated, @JsonProperty("date_updated") final String dateUpdated, @JsonProperty("created_by") final String createdBy, @@ -185,7 +185,7 @@ public final String getAttributes() { return this.attributes; } - public final ChannelType getType() { + public final Channel.ChannelType getType() { return this.type; } diff --git a/src/main/java/com/twilio/rest/ipmessaging/v2/service/Role.java b/src/main/java/com/twilio/rest/ipmessaging/v2/service/Role.java index b36d8e3ae7..3f44c5de6f 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v2/service/Role.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v2/service/Role.java @@ -43,7 +43,7 @@ public class Role extends Resource { public static RoleCreator creator( final String pathServiceSid, final String friendlyName, - final RoleType type, + final Role.RoleType type, final List permission ) { return new RoleCreator(pathServiceSid, friendlyName, type, permission); @@ -122,7 +122,7 @@ public static Role fromJson( private final String accountSid; private final String serviceSid; private final String friendlyName; - private final RoleType type; + private final Role.RoleType type; private final List permissions; private final ZonedDateTime dateCreated; private final ZonedDateTime dateUpdated; @@ -134,7 +134,7 @@ private Role( @JsonProperty("account_sid") final String accountSid, @JsonProperty("service_sid") final String serviceSid, @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("type") final RoleType type, + @JsonProperty("type") final Role.RoleType type, @JsonProperty("permissions") final List permissions, @JsonProperty("date_created") final String dateCreated, @JsonProperty("date_updated") final String dateUpdated, @@ -167,7 +167,7 @@ public final String getFriendlyName() { return this.friendlyName; } - public final RoleType getType() { + public final Role.RoleType getType() { return this.type; } diff --git a/src/main/java/com/twilio/rest/ipmessaging/v2/service/channel/Webhook.java b/src/main/java/com/twilio/rest/ipmessaging/v2/service/channel/Webhook.java index 8674cc57fc..e4202e4268 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v2/service/channel/Webhook.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v2/service/channel/Webhook.java @@ -44,7 +44,7 @@ public class Webhook extends Resource { public static WebhookCreator creator( final String pathServiceSid, final String pathChannelSid, - final Type type + final Webhook.Type type ) { return new WebhookCreator(pathServiceSid, pathChannelSid, type); } diff --git a/src/main/java/com/twilio/rest/ipmessaging/v2/service/user/UserBinding.java b/src/main/java/com/twilio/rest/ipmessaging/v2/service/user/UserBinding.java index a9ccdfface..e43512d118 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v2/service/user/UserBinding.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v2/service/user/UserBinding.java @@ -115,7 +115,7 @@ public static UserBinding fromJson( private final String identity; private final String userSid; private final String credentialSid; - private final BindingType bindingType; + private final UserBinding.BindingType bindingType; private final List messageTypes; private final URI url; @@ -130,7 +130,7 @@ private UserBinding( @JsonProperty("identity") final String identity, @JsonProperty("user_sid") final String userSid, @JsonProperty("credential_sid") final String credentialSid, - @JsonProperty("binding_type") final BindingType bindingType, + @JsonProperty("binding_type") final UserBinding.BindingType bindingType, @JsonProperty("message_types") final List messageTypes, @JsonProperty("url") final URI url ) { @@ -184,7 +184,7 @@ public final String getCredentialSid() { return this.credentialSid; } - public final BindingType getBindingType() { + public final UserBinding.BindingType getBindingType() { return this.bindingType; } diff --git a/src/main/java/com/twilio/rest/ipmessaging/v2/service/user/UserChannel.java b/src/main/java/com/twilio/rest/ipmessaging/v2/service/user/UserChannel.java index 5b8761e478..780eca1a29 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v2/service/user/UserChannel.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v2/service/user/UserChannel.java @@ -130,12 +130,12 @@ public static UserChannel fromJson( private final String channelSid; private final String userSid; private final String memberSid; - private final ChannelStatus status; + private final UserChannel.ChannelStatus status; private final Integer lastConsumedMessageIndex; private final Integer unreadMessagesCount; private final Map links; private final URI url; - private final NotificationLevel notificationLevel; + private final UserChannel.NotificationLevel notificationLevel; @JsonCreator private UserChannel( @@ -144,7 +144,7 @@ private UserChannel( @JsonProperty("channel_sid") final String channelSid, @JsonProperty("user_sid") final String userSid, @JsonProperty("member_sid") final String memberSid, - @JsonProperty("status") final ChannelStatus status, + @JsonProperty("status") final UserChannel.ChannelStatus status, @JsonProperty( "last_consumed_message_index" ) final Integer lastConsumedMessageIndex, @@ -155,7 +155,7 @@ private UserChannel( @JsonProperty("url") final URI url, @JsonProperty( "notification_level" - ) final NotificationLevel notificationLevel + ) final UserChannel.NotificationLevel notificationLevel ) { this.accountSid = accountSid; this.serviceSid = serviceSid; @@ -190,7 +190,7 @@ public final String getMemberSid() { return this.memberSid; } - public final ChannelStatus getStatus() { + public final UserChannel.ChannelStatus getStatus() { return this.status; } @@ -210,7 +210,7 @@ public final URI getUrl() { return this.url; } - public final NotificationLevel getNotificationLevel() { + public final UserChannel.NotificationLevel getNotificationLevel() { return this.notificationLevel; } diff --git a/src/main/java/com/twilio/rest/knowledge/v1/Knowledge.java b/src/main/java/com/twilio/rest/knowledge/v1/Knowledge.java deleted file mode 100644 index 4e6b69d6a9..0000000000 --- a/src/main/java/com/twilio/rest/knowledge/v1/Knowledge.java +++ /dev/null @@ -1,409 +0,0 @@ -/* - * This code was generated by - * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ - * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ - * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ - * - * Twilio - Knowledge - * This is the public Twilio REST API. - * - * NOTE: This class is auto generated by OpenAPI Generator. - * https://openapi-generator.tech - * Do not edit the class manually. - */ - -package com.twilio.rest.knowledge.v1; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.core.JsonParseException; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.JsonMappingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; -import com.twilio.exception.ApiConnectionException; -import com.twilio.exception.ApiException; -import java.io.IOException; -import java.io.InputStream; -import java.time.ZonedDateTime; -import java.util.Map; -import java.util.Map; -import java.util.Objects; -import lombok.Getter; -import lombok.Setter; -import lombok.ToString; -import lombok.ToString; - -@JsonIgnoreProperties(ignoreUnknown = true) -@ToString -public class Knowledge extends Resource { - - private static final long serialVersionUID = 142704301669097L; - - @ToString - public static class KnowledgeV1ServiceCreatePolicyRequest { - - @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("description") - @Getter - @Setter - private String description; - - @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("id") - @Getter - @Setter - private String id; - - @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("name") - @Getter - @Setter - private String name; - - @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("policy_details") - @Getter - @Setter - private Object policyDetails; - - @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("type") - @Getter - @Setter - private String type; - - public static KnowledgeV1ServiceCreatePolicyRequest fromJson( - String jsonString, - ObjectMapper mapper - ) throws IOException { - return mapper.readValue( - jsonString, - KnowledgeV1ServiceCreatePolicyRequest.class - ); - } - } - - @ToString - public static class KnowledgeV1ServiceCreateKnowledgeRequest { - - @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("description") - @Getter - @Setter - private String description; - - @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("knowledge_source_details") - @Getter - @Setter - private Map knowledgeSourceDetails; - - @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("name") - @Getter - @Setter - private String name; - - @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("policy") - @Getter - @Setter - private KnowledgeV1ServiceCreatePolicyRequest policy; - - @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("type") - @Getter - @Setter - private String type; - - @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("embedding_model") - @Getter - @Setter - private String embeddingModel; - - public KnowledgeV1ServiceCreateKnowledgeRequest( - final String name, - final String type - ) { - this.name = name; - this.type = type; - } - - public static KnowledgeV1ServiceCreateKnowledgeRequest fromJson( - String jsonString, - ObjectMapper mapper - ) throws IOException { - return mapper.readValue( - jsonString, - KnowledgeV1ServiceCreateKnowledgeRequest.class - ); - } - } - - @ToString - public static class KnowledgeV1ServiceUpdateKnowledgeRequest { - - @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("description") - @Getter - @Setter - private String description; - - @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("knowledge_source_details") - @Getter - @Setter - private Map knowledgeSourceDetails; - - @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("name") - @Getter - @Setter - private String name; - - @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("policy") - @Getter - @Setter - private KnowledgeV1ServiceCreatePolicyRequest policy; - - @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("type") - @Getter - @Setter - private String type; - - @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("embedding_model") - @Getter - @Setter - private String embeddingModel; - - public KnowledgeV1ServiceUpdateKnowledgeRequest() {} - - public static KnowledgeV1ServiceUpdateKnowledgeRequest fromJson( - String jsonString, - ObjectMapper mapper - ) throws IOException { - return mapper.readValue( - jsonString, - KnowledgeV1ServiceUpdateKnowledgeRequest.class - ); - } - } - - public static KnowledgeCreator creator( - final KnowledgeV1ServiceCreateKnowledgeRequest knowledgeV1ServiceCreateKnowledgeRequest - ) { - return new KnowledgeCreator(knowledgeV1ServiceCreateKnowledgeRequest); - } - - public static KnowledgeDeleter deleter(final String pathId) { - return new KnowledgeDeleter(pathId); - } - - public static KnowledgeFetcher fetcher(final String pathId) { - return new KnowledgeFetcher(pathId); - } - - public static KnowledgeReader reader() { - return new KnowledgeReader(); - } - - public static KnowledgeUpdater updater(final String pathId) { - return new KnowledgeUpdater(pathId); - } - - /** - * Converts a JSON String into a Knowledge object using the provided ObjectMapper. - * - * @param json Raw JSON String - * @param objectMapper Jackson ObjectMapper - * @return Knowledge object represented by the provided JSON - */ - public static Knowledge fromJson( - final String json, - final ObjectMapper objectMapper - ) { - // Convert all checked exceptions to Runtime - try { - return objectMapper.readValue(json, Knowledge.class); - } catch (final JsonMappingException | JsonParseException e) { - throw new ApiException(e.getMessage(), e); - } catch (final IOException e) { - throw new ApiConnectionException(e.getMessage(), e); - } - } - - /** - * Converts a JSON InputStream into a Knowledge object using the provided - * ObjectMapper. - * - * @param json Raw JSON InputStream - * @param objectMapper Jackson ObjectMapper - * @return Knowledge object represented by the provided JSON - */ - public static Knowledge fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { - // Convert all checked exceptions to Runtime - try { - return objectMapper.readValue(json, Knowledge.class); - } catch (final JsonMappingException | JsonParseException e) { - throw new ApiException(e.getMessage(), e); - } catch (final IOException e) { - throw new ApiConnectionException(e.getMessage(), e); - } - } - - public static String toJson(Object object, ObjectMapper mapper) { - try { - return mapper.writeValueAsString(object); - } catch (final JsonMappingException e) { - throw new ApiException(e.getMessage(), e); - } catch (JsonProcessingException e) { - throw new ApiException(e.getMessage(), e); - } catch (final IOException e) { - throw new ApiConnectionException(e.getMessage(), e); - } - } - - private final String description; - private final String id; - private final String accountSid; - private final Map knowledgeSourceDetails; - private final String name; - private final String status; - private final String type; - private final String url; - private final String embeddingModel; - private final ZonedDateTime dateCreated; - private final ZonedDateTime dateUpdated; - - @JsonCreator - private Knowledge( - @JsonProperty("description") final String description, - @JsonProperty("id") final String id, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("knowledge_source_details") final Map< - String, - Object - > knowledgeSourceDetails, - @JsonProperty("name") final String name, - @JsonProperty("status") final String status, - @JsonProperty("type") final String type, - @JsonProperty("url") final String url, - @JsonProperty("embedding_model") final String embeddingModel, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated - ) { - this.description = description; - this.id = id; - this.accountSid = accountSid; - this.knowledgeSourceDetails = knowledgeSourceDetails; - this.name = name; - this.status = status; - this.type = type; - this.url = url; - this.embeddingModel = embeddingModel; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); - } - - public final String getDescription() { - return this.description; - } - - public final String getId() { - return this.id; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final Map getKnowledgeSourceDetails() { - return this.knowledgeSourceDetails; - } - - public final String getName() { - return this.name; - } - - public final String getStatus() { - return this.status; - } - - public final String getType() { - return this.type; - } - - public final String getUrl() { - return this.url; - } - - public final String getEmbeddingModel() { - return this.embeddingModel; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - @Override - public boolean equals(final Object o) { - if (this == o) { - return true; - } - - if (o == null || getClass() != o.getClass()) { - return false; - } - - Knowledge other = (Knowledge) o; - - return ( - Objects.equals(description, other.description) && - Objects.equals(id, other.id) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals( - knowledgeSourceDetails, - other.knowledgeSourceDetails - ) && - Objects.equals(name, other.name) && - Objects.equals(status, other.status) && - Objects.equals(type, other.type) && - Objects.equals(url, other.url) && - Objects.equals(embeddingModel, other.embeddingModel) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) - ); - } - - @Override - public int hashCode() { - return Objects.hash( - description, - id, - accountSid, - knowledgeSourceDetails, - name, - status, - type, - url, - embeddingModel, - dateCreated, - dateUpdated - ); - } -} diff --git a/src/main/java/com/twilio/rest/knowledge/v1/KnowledgeDeleter.java b/src/main/java/com/twilio/rest/knowledge/v1/KnowledgeDeleter.java deleted file mode 100644 index 59804cdc4e..0000000000 --- a/src/main/java/com/twilio/rest/knowledge/v1/KnowledgeDeleter.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * This code was generated by - * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ - * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ - * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ - * - * Twilio - Knowledge - * This is the public Twilio REST API. - * - * NOTE: This class is auto generated by OpenAPI Generator. - * https://openapi-generator.tech - * Do not edit the class manually. - */ - -package com.twilio.rest.knowledge.v1; - -import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; -import com.twilio.exception.ApiConnectionException; -import com.twilio.exception.ApiException; -import com.twilio.exception.RestException; -import com.twilio.http.HttpMethod; -import com.twilio.http.Request; -import com.twilio.http.Response; -import com.twilio.http.TwilioRestClient; -import com.twilio.rest.Domains; - -public class KnowledgeDeleter extends Deleter { - - private String pathId; - - public KnowledgeDeleter(final String pathId) { - this.pathId = pathId; - } - - @Override - public boolean delete(final TwilioRestClient client) { - String path = "/v1/Knowledge/{id}"; - - path = path.replace("{" + "id" + "}", this.pathId.toString()); - - Request request = new Request( - HttpMethod.DELETE, - Domains.KNOWLEDGE.toString(), - path - ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); - Response response = client.request(request); - - if (response == null) { - throw new ApiConnectionException( - "Knowledge delete failed: Unable to connect to server" - ); - } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { - RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); - if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); - } - throw new ApiException(restException); - } - return response.getStatusCode() == 204; - } -} diff --git a/src/main/java/com/twilio/rest/knowledge/v1/KnowledgeFetcher.java b/src/main/java/com/twilio/rest/knowledge/v1/KnowledgeFetcher.java deleted file mode 100644 index 5e7aea48b0..0000000000 --- a/src/main/java/com/twilio/rest/knowledge/v1/KnowledgeFetcher.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * This code was generated by - * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ - * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ - * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ - * - * Twilio - Knowledge - * This is the public Twilio REST API. - * - * NOTE: This class is auto generated by OpenAPI Generator. - * https://openapi-generator.tech - * Do not edit the class manually. - */ - -package com.twilio.rest.knowledge.v1; - -import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; -import com.twilio.exception.ApiConnectionException; -import com.twilio.exception.ApiException; -import com.twilio.exception.RestException; -import com.twilio.http.HttpMethod; -import com.twilio.http.Request; -import com.twilio.http.Response; -import com.twilio.http.TwilioRestClient; -import com.twilio.rest.Domains; - -public class KnowledgeFetcher extends Fetcher { - - private String pathId; - - public KnowledgeFetcher(final String pathId) { - this.pathId = pathId; - } - - @Override - public Knowledge fetch(final TwilioRestClient client) { - String path = "/v1/Knowledge/{id}"; - - path = path.replace("{" + "id" + "}", this.pathId.toString()); - - Request request = new Request( - HttpMethod.GET, - Domains.KNOWLEDGE.toString(), - path - ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); - Response response = client.request(request); - - if (response == null) { - throw new ApiConnectionException( - "Knowledge fetch failed: Unable to connect to server" - ); - } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { - RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); - if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); - } - throw new ApiException(restException); - } - - return Knowledge.fromJson( - response.getStream(), - client.getObjectMapper() - ); - } -} diff --git a/src/main/java/com/twilio/rest/knowledge/v1/KnowledgeReader.java b/src/main/java/com/twilio/rest/knowledge/v1/KnowledgeReader.java deleted file mode 100644 index f0d8abd0f5..0000000000 --- a/src/main/java/com/twilio/rest/knowledge/v1/KnowledgeReader.java +++ /dev/null @@ -1,144 +0,0 @@ -/* - * This code was generated by - * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ - * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ - * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ - * - * Twilio - Knowledge - * This is the public Twilio REST API. - * - * NOTE: This class is auto generated by OpenAPI Generator. - * https://openapi-generator.tech - * Do not edit the class manually. - */ - -package com.twilio.rest.knowledge.v1; - -import com.twilio.base.Page; -import com.twilio.base.Reader; -import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; -import com.twilio.exception.ApiConnectionException; -import com.twilio.exception.ApiException; -import com.twilio.exception.RestException; -import com.twilio.http.HttpMethod; -import com.twilio.http.Request; -import com.twilio.http.Response; -import com.twilio.http.TwilioRestClient; -import com.twilio.rest.Domains; - -public class KnowledgeReader extends Reader { - - private Integer pageSize; - private String tags; - - public KnowledgeReader() {} - - public KnowledgeReader setPageSize(final Integer pageSize) { - this.pageSize = pageSize; - return this; - } - - public KnowledgeReader setTags(final String tags) { - this.tags = tags; - return this; - } - - @Override - public ResourceSet read(final TwilioRestClient client) { - return new ResourceSet<>(this, client, firstPage(client)); - } - - public Page firstPage(final TwilioRestClient client) { - String path = "/v1/Knowledge"; - - Request request = new Request( - HttpMethod.GET, - Domains.KNOWLEDGE.toString(), - path - ); - - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); - return pageForRequest(client, request); - } - - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { - Response response = client.request(request); - - if (response == null) { - throw new ApiConnectionException( - "Knowledge read failed: Unable to connect to server" - ); - } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { - RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); - if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); - } - throw new ApiException(restException); - } - - return Page.fromJson( - "knowledge", - response.getContent(), - Knowledge.class, - client.getObjectMapper() - ); - } - - @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.KNOWLEDGE.toString()) - ); - return pageForRequest(client, request); - } - - @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.KNOWLEDGE.toString()) - ); - return pageForRequest(client, request); - } - - @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { - Request request = new Request(HttpMethod.GET, targetUrl); - - return pageForRequest(client, request); - } - - private void addQueryParams(final Request request) { - if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); - } - if (tags != null) { - request.addQueryParam("Tags", tags); - } - - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } - } -} diff --git a/src/main/java/com/twilio/rest/knowledge/v1/knowledge/Chunk.java b/src/main/java/com/twilio/rest/knowledge/v1/knowledge/Chunk.java deleted file mode 100644 index b0336d7aa9..0000000000 --- a/src/main/java/com/twilio/rest/knowledge/v1/knowledge/Chunk.java +++ /dev/null @@ -1,161 +0,0 @@ -/* - * This code was generated by - * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ - * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ - * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ - * - * Twilio - Knowledge - * This is the public Twilio REST API. - * - * NOTE: This class is auto generated by OpenAPI Generator. - * https://openapi-generator.tech - * Do not edit the class manually. - */ - -package com.twilio.rest.knowledge.v1.knowledge; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.core.JsonParseException; -import com.fasterxml.jackson.databind.JsonMappingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; -import com.twilio.exception.ApiConnectionException; -import com.twilio.exception.ApiException; -import java.io.IOException; -import java.io.InputStream; -import java.time.ZonedDateTime; -import java.util.Map; -import java.util.Map; -import java.util.Objects; -import lombok.ToString; -import lombok.ToString; - -@JsonIgnoreProperties(ignoreUnknown = true) -@ToString -public class Chunk extends Resource { - - private static final long serialVersionUID = 152804488582909L; - - public static ChunkReader reader(final String pathId) { - return new ChunkReader(pathId); - } - - /** - * Converts a JSON String into a Chunk object using the provided ObjectMapper. - * - * @param json Raw JSON String - * @param objectMapper Jackson ObjectMapper - * @return Chunk object represented by the provided JSON - */ - public static Chunk fromJson( - final String json, - final ObjectMapper objectMapper - ) { - // Convert all checked exceptions to Runtime - try { - return objectMapper.readValue(json, Chunk.class); - } catch (final JsonMappingException | JsonParseException e) { - throw new ApiException(e.getMessage(), e); - } catch (final IOException e) { - throw new ApiConnectionException(e.getMessage(), e); - } - } - - /** - * Converts a JSON InputStream into a Chunk object using the provided - * ObjectMapper. - * - * @param json Raw JSON InputStream - * @param objectMapper Jackson ObjectMapper - * @return Chunk object represented by the provided JSON - */ - public static Chunk fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { - // Convert all checked exceptions to Runtime - try { - return objectMapper.readValue(json, Chunk.class); - } catch (final JsonMappingException | JsonParseException e) { - throw new ApiException(e.getMessage(), e); - } catch (final IOException e) { - throw new ApiConnectionException(e.getMessage(), e); - } - } - - private final String accountSid; - private final String content; - private final Map metadata; - private final ZonedDateTime dateCreated; - private final ZonedDateTime dateUpdated; - - @JsonCreator - private Chunk( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("content") final String content, - @JsonProperty("metadata") final Map metadata, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated - ) { - this.accountSid = accountSid; - this.content = content; - this.metadata = metadata; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getContent() { - return this.content; - } - - public final Map getMetadata() { - return this.metadata; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - @Override - public boolean equals(final Object o) { - if (this == o) { - return true; - } - - if (o == null || getClass() != o.getClass()) { - return false; - } - - Chunk other = (Chunk) o; - - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(content, other.content) && - Objects.equals(metadata, other.metadata) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) - ); - } - - @Override - public int hashCode() { - return Objects.hash( - accountSid, - content, - metadata, - dateCreated, - dateUpdated - ); - } -} diff --git a/src/main/java/com/twilio/rest/knowledge/v1/knowledge/ChunkReader.java b/src/main/java/com/twilio/rest/knowledge/v1/knowledge/ChunkReader.java deleted file mode 100644 index bceed7b7f8..0000000000 --- a/src/main/java/com/twilio/rest/knowledge/v1/knowledge/ChunkReader.java +++ /dev/null @@ -1,139 +0,0 @@ -/* - * This code was generated by - * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ - * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ - * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ - * - * Twilio - Knowledge - * This is the public Twilio REST API. - * - * NOTE: This class is auto generated by OpenAPI Generator. - * https://openapi-generator.tech - * Do not edit the class manually. - */ - -package com.twilio.rest.knowledge.v1.knowledge; - -import com.twilio.base.Page; -import com.twilio.base.Reader; -import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; -import com.twilio.exception.ApiConnectionException; -import com.twilio.exception.ApiException; -import com.twilio.exception.RestException; -import com.twilio.http.HttpMethod; -import com.twilio.http.Request; -import com.twilio.http.Response; -import com.twilio.http.TwilioRestClient; -import com.twilio.rest.Domains; - -public class ChunkReader extends Reader { - - private String pathId; - private Integer pageSize; - - public ChunkReader(final String pathId) { - this.pathId = pathId; - } - - public ChunkReader setPageSize(final Integer pageSize) { - this.pageSize = pageSize; - return this; - } - - @Override - public ResourceSet read(final TwilioRestClient client) { - return new ResourceSet<>(this, client, firstPage(client)); - } - - public Page firstPage(final TwilioRestClient client) { - String path = "/v1/Knowledge/{id}/Chunks"; - path = path.replace("{" + "id" + "}", this.pathId.toString()); - - Request request = new Request( - HttpMethod.GET, - Domains.KNOWLEDGE.toString(), - path - ); - - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); - return pageForRequest(client, request); - } - - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { - Response response = client.request(request); - - if (response == null) { - throw new ApiConnectionException( - "Chunk read failed: Unable to connect to server" - ); - } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { - RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); - if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); - } - throw new ApiException(restException); - } - - return Page.fromJson( - "chunks", - response.getContent(), - Chunk.class, - client.getObjectMapper() - ); - } - - @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.KNOWLEDGE.toString()) - ); - return pageForRequest(client, request); - } - - @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.KNOWLEDGE.toString()) - ); - return pageForRequest(client, request); - } - - @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { - Request request = new Request(HttpMethod.GET, targetUrl); - - return pageForRequest(client, request); - } - - private void addQueryParams(final Request request) { - if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); - } - - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } - } -} diff --git a/src/main/java/com/twilio/rest/knowledge/v1/knowledge/KnowledgeStatus.java b/src/main/java/com/twilio/rest/knowledge/v1/knowledge/KnowledgeStatus.java deleted file mode 100644 index ded378b2d8..0000000000 --- a/src/main/java/com/twilio/rest/knowledge/v1/knowledge/KnowledgeStatus.java +++ /dev/null @@ -1,145 +0,0 @@ -/* - * This code was generated by - * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ - * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ - * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ - * - * Twilio - Knowledge - * This is the public Twilio REST API. - * - * NOTE: This class is auto generated by OpenAPI Generator. - * https://openapi-generator.tech - * Do not edit the class manually. - */ - -package com.twilio.rest.knowledge.v1.knowledge; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.core.JsonParseException; -import com.fasterxml.jackson.databind.JsonMappingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; -import com.twilio.exception.ApiConnectionException; -import com.twilio.exception.ApiException; -import java.io.IOException; -import java.io.InputStream; -import java.time.ZonedDateTime; -import java.util.Objects; -import lombok.ToString; -import lombok.ToString; - -@JsonIgnoreProperties(ignoreUnknown = true) -@ToString -public class KnowledgeStatus extends Resource { - - private static final long serialVersionUID = 178959927465400L; - - public static KnowledgeStatusFetcher fetcher(final String pathId) { - return new KnowledgeStatusFetcher(pathId); - } - - /** - * Converts a JSON String into a KnowledgeStatus object using the provided ObjectMapper. - * - * @param json Raw JSON String - * @param objectMapper Jackson ObjectMapper - * @return KnowledgeStatus object represented by the provided JSON - */ - public static KnowledgeStatus fromJson( - final String json, - final ObjectMapper objectMapper - ) { - // Convert all checked exceptions to Runtime - try { - return objectMapper.readValue(json, KnowledgeStatus.class); - } catch (final JsonMappingException | JsonParseException e) { - throw new ApiException(e.getMessage(), e); - } catch (final IOException e) { - throw new ApiConnectionException(e.getMessage(), e); - } - } - - /** - * Converts a JSON InputStream into a KnowledgeStatus object using the provided - * ObjectMapper. - * - * @param json Raw JSON InputStream - * @param objectMapper Jackson ObjectMapper - * @return KnowledgeStatus object represented by the provided JSON - */ - public static KnowledgeStatus fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { - // Convert all checked exceptions to Runtime - try { - return objectMapper.readValue(json, KnowledgeStatus.class); - } catch (final JsonMappingException | JsonParseException e) { - throw new ApiException(e.getMessage(), e); - } catch (final IOException e) { - throw new ApiConnectionException(e.getMessage(), e); - } - } - - private final String accountSid; - private final String status; - private final String lastStatus; - private final ZonedDateTime dateUpdated; - - @JsonCreator - private KnowledgeStatus( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("status") final String status, - @JsonProperty("last_status") final String lastStatus, - @JsonProperty("date_updated") final String dateUpdated - ) { - this.accountSid = accountSid; - this.status = status; - this.lastStatus = lastStatus; - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getStatus() { - return this.status; - } - - public final String getLastStatus() { - return this.lastStatus; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - @Override - public boolean equals(final Object o) { - if (this == o) { - return true; - } - - if (o == null || getClass() != o.getClass()) { - return false; - } - - KnowledgeStatus other = (KnowledgeStatus) o; - - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(status, other.status) && - Objects.equals(lastStatus, other.lastStatus) && - Objects.equals(dateUpdated, other.dateUpdated) - ); - } - - @Override - public int hashCode() { - return Objects.hash(accountSid, status, lastStatus, dateUpdated); - } -} diff --git a/src/main/java/com/twilio/rest/knowledge/v1/knowledge/KnowledgeStatusFetcher.java b/src/main/java/com/twilio/rest/knowledge/v1/knowledge/KnowledgeStatusFetcher.java deleted file mode 100644 index 93c2e7bfb6..0000000000 --- a/src/main/java/com/twilio/rest/knowledge/v1/knowledge/KnowledgeStatusFetcher.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * This code was generated by - * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ - * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ - * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ - * - * Twilio - Knowledge - * This is the public Twilio REST API. - * - * NOTE: This class is auto generated by OpenAPI Generator. - * https://openapi-generator.tech - * Do not edit the class manually. - */ - -package com.twilio.rest.knowledge.v1.knowledge; - -import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; -import com.twilio.exception.ApiConnectionException; -import com.twilio.exception.ApiException; -import com.twilio.exception.RestException; -import com.twilio.http.HttpMethod; -import com.twilio.http.Request; -import com.twilio.http.Response; -import com.twilio.http.TwilioRestClient; -import com.twilio.rest.Domains; - -public class KnowledgeStatusFetcher extends Fetcher { - - private String pathId; - - public KnowledgeStatusFetcher(final String pathId) { - this.pathId = pathId; - } - - @Override - public KnowledgeStatus fetch(final TwilioRestClient client) { - String path = "/v1/Knowledge/{id}/Status"; - - path = path.replace("{" + "id" + "}", this.pathId.toString()); - - Request request = new Request( - HttpMethod.GET, - Domains.KNOWLEDGE.toString(), - path - ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); - Response response = client.request(request); - - if (response == null) { - throw new ApiConnectionException( - "KnowledgeStatus fetch failed: Unable to connect to server" - ); - } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { - RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); - if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); - } - throw new ApiException(restException); - } - - return KnowledgeStatus.fromJson( - response.getStream(), - client.getObjectMapper() - ); - } -} diff --git a/src/main/java/com/twilio/rest/lookups/v2/Bucket.java b/src/main/java/com/twilio/rest/lookups/v2/Bucket.java new file mode 100644 index 0000000000..221da7456a --- /dev/null +++ b/src/main/java/com/twilio/rest/lookups/v2/Bucket.java @@ -0,0 +1,209 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Lookups + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package com.twilio.rest.lookups.v2; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.twilio.base.Resource; +import com.twilio.exception.ApiConnectionException; +import com.twilio.exception.ApiException; +import java.io.IOException; +import java.io.InputStream; +import java.util.Objects; +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; +import lombok.ToString; + +@JsonIgnoreProperties(ignoreUnknown = true) +@ToString +public class Bucket extends Resource { + + private static final long serialVersionUID = 277677635778369L; + + @ToString + public static class RateLimitRequest { + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("limit") + @Getter + @Setter + private Integer limit; + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("ttl") + @Getter + @Setter + private Integer ttl; + + public RateLimitRequest() {} + + public static RateLimitRequest fromJson( + String jsonString, + ObjectMapper mapper + ) throws IOException { + return mapper.readValue(jsonString, RateLimitRequest.class); + } + } + + public static BucketDeleter deleter( + final String pathField, + final String pathBucket + ) { + return new BucketDeleter(pathField, pathBucket); + } + + public static BucketFetcher fetcher( + final String pathField, + final String pathBucket + ) { + return new BucketFetcher(pathField, pathBucket); + } + + public static BucketUpdater updater( + final String pathField, + final String pathBucket + ) { + return new BucketUpdater(pathField, pathBucket); + } + + /** + * Converts a JSON String into a Bucket object using the provided ObjectMapper. + * + * @param json Raw JSON String + * @param objectMapper Jackson ObjectMapper + * @return Bucket object represented by the provided JSON + */ + public static Bucket fromJson( + final String json, + final ObjectMapper objectMapper + ) { + // Convert all checked exceptions to Runtime + try { + return objectMapper.readValue(json, Bucket.class); + } catch (final JsonMappingException | JsonParseException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + /** + * Converts a JSON InputStream into a Bucket object using the provided + * ObjectMapper. + * + * @param json Raw JSON InputStream + * @param objectMapper Jackson ObjectMapper + * @return Bucket object represented by the provided JSON + */ + public static Bucket fromJson( + final InputStream json, + final ObjectMapper objectMapper + ) { + // Convert all checked exceptions to Runtime + try { + return objectMapper.readValue(json, Bucket.class); + } catch (final JsonMappingException | JsonParseException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + private final String field; + private final Integer limit; + private final String bucket; + private final String owner; + private final Integer ttl; + + @JsonCreator + private Bucket( + @JsonProperty("field") final String field, + @JsonProperty("limit") final Integer limit, + @JsonProperty("bucket") final String bucket, + @JsonProperty("owner") final String owner, + @JsonProperty("ttl") final Integer ttl + ) { + this.field = field; + this.limit = limit; + this.bucket = bucket; + this.owner = owner; + this.ttl = ttl; + } + + public final String getField() { + return this.field; + } + + public final Integer getLimit() { + return this.limit; + } + + public final String getBucket() { + return this.bucket; + } + + public final String getOwner() { + return this.owner; + } + + public final Integer getTtl() { + return this.ttl; + } + + @Override + public boolean equals(final Object o) { + if (this == o) { + return true; + } + + if (o == null || getClass() != o.getClass()) { + return false; + } + + Bucket other = (Bucket) o; + + return ( + Objects.equals(field, other.field) && + Objects.equals(limit, other.limit) && + Objects.equals(bucket, other.bucket) && + Objects.equals(owner, other.owner) && + Objects.equals(ttl, other.ttl) + ); + } + + @Override + public int hashCode() { + return Objects.hash(field, limit, bucket, owner, ttl); + } +} diff --git a/src/main/java/com/twilio/rest/microvisor/v1/AccountConfigDeleter.java b/src/main/java/com/twilio/rest/lookups/v2/BucketDeleter.java similarity index 73% rename from src/main/java/com/twilio/rest/microvisor/v1/AccountConfigDeleter.java rename to src/main/java/com/twilio/rest/lookups/v2/BucketDeleter.java index 9529bba7b5..511751bad2 100644 --- a/src/main/java/com/twilio/rest/microvisor/v1/AccountConfigDeleter.java +++ b/src/main/java/com/twilio/rest/lookups/v2/BucketDeleter.java @@ -4,7 +4,7 @@ * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ * - * Twilio - Microvisor + * Twilio - Lookups * This is the public Twilio REST API. * * NOTE: This class is auto generated by OpenAPI Generator. @@ -12,7 +12,7 @@ * Do not edit the class manually. */ -package com.twilio.rest.microvisor.v1; +package com.twilio.rest.lookups.v2; import com.twilio.base.Deleter; import com.twilio.constant.EnumConstants; @@ -25,23 +25,26 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class AccountConfigDeleter extends Deleter { +public class BucketDeleter extends Deleter { - private String pathKey; + private String pathField; + private String pathBucket; - public AccountConfigDeleter(final String pathKey) { - this.pathKey = pathKey; + public BucketDeleter(final String pathField, final String pathBucket) { + this.pathField = pathField; + this.pathBucket = pathBucket; } @Override public boolean delete(final TwilioRestClient client) { - String path = "/v1/Configs/{Key}"; + String path = "/v2/RateLimits/Fields/{Field}/Bucket/{Bucket}"; - path = path.replace("{" + "Key" + "}", this.pathKey.toString()); + path = path.replace("{" + "Field" + "}", this.pathField.toString()); + path = path.replace("{" + "Bucket" + "}", this.pathBucket.toString()); Request request = new Request( HttpMethod.DELETE, - Domains.MICROVISOR.toString(), + Domains.LOOKUPS.toString(), path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); @@ -49,7 +52,7 @@ public boolean delete(final TwilioRestClient client) { if (response == null) { throw new ApiConnectionException( - "AccountConfig delete failed: Unable to connect to server" + "Bucket delete failed: Unable to connect to server" ); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( diff --git a/src/main/java/com/twilio/rest/microvisor/v1/DeviceFetcher.java b/src/main/java/com/twilio/rest/lookups/v2/BucketFetcher.java similarity index 69% rename from src/main/java/com/twilio/rest/microvisor/v1/DeviceFetcher.java rename to src/main/java/com/twilio/rest/lookups/v2/BucketFetcher.java index 6192902ea2..c73c369da4 100644 --- a/src/main/java/com/twilio/rest/microvisor/v1/DeviceFetcher.java +++ b/src/main/java/com/twilio/rest/lookups/v2/BucketFetcher.java @@ -4,7 +4,7 @@ * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ * - * Twilio - Microvisor + * Twilio - Lookups * This is the public Twilio REST API. * * NOTE: This class is auto generated by OpenAPI Generator. @@ -12,7 +12,7 @@ * Do not edit the class manually. */ -package com.twilio.rest.microvisor.v1; +package com.twilio.rest.lookups.v2; import com.twilio.base.Fetcher; import com.twilio.constant.EnumConstants; @@ -25,23 +25,26 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class DeviceFetcher extends Fetcher { +public class BucketFetcher extends Fetcher { - private String pathSid; + private String pathField; + private String pathBucket; - public DeviceFetcher(final String pathSid) { - this.pathSid = pathSid; + public BucketFetcher(final String pathField, final String pathBucket) { + this.pathField = pathField; + this.pathBucket = pathBucket; } @Override - public Device fetch(final TwilioRestClient client) { - String path = "/v1/Devices/{Sid}"; + public Bucket fetch(final TwilioRestClient client) { + String path = "/v2/RateLimits/Fields/{Field}/Bucket/{Bucket}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Field" + "}", this.pathField.toString()); + path = path.replace("{" + "Bucket" + "}", this.pathBucket.toString()); Request request = new Request( HttpMethod.GET, - Domains.MICROVISOR.toString(), + Domains.LOOKUPS.toString(), path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); @@ -49,7 +52,7 @@ public Device fetch(final TwilioRestClient client) { if (response == null) { throw new ApiConnectionException( - "Device fetch failed: Unable to connect to server" + "Bucket fetch failed: Unable to connect to server" ); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( @@ -65,6 +68,6 @@ public Device fetch(final TwilioRestClient client) { throw new ApiException(restException); } - return Device.fromJson(response.getStream(), client.getObjectMapper()); + return Bucket.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/microvisor/v1/AccountConfigUpdater.java b/src/main/java/com/twilio/rest/lookups/v2/BucketUpdater.java similarity index 53% rename from src/main/java/com/twilio/rest/microvisor/v1/AccountConfigUpdater.java rename to src/main/java/com/twilio/rest/lookups/v2/BucketUpdater.java index 0c2c55a496..ebb98856f1 100644 --- a/src/main/java/com/twilio/rest/microvisor/v1/AccountConfigUpdater.java +++ b/src/main/java/com/twilio/rest/lookups/v2/BucketUpdater.java @@ -4,7 +4,7 @@ * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ * - * Twilio - Microvisor + * Twilio - Lookups * This is the public Twilio REST API. * * NOTE: This class is auto generated by OpenAPI Generator. @@ -12,8 +12,9 @@ * Do not edit the class manually. */ -package com.twilio.rest.microvisor.v1; +package com.twilio.rest.lookups.v2; +import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; @@ -25,39 +26,42 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class AccountConfigUpdater extends Updater { +public class BucketUpdater extends Updater { - private String pathKey; - private String value; + private String pathField; + private String pathBucket; + private Bucket.RateLimitRequest rateLimitRequest; - public AccountConfigUpdater(final String pathKey, final String value) { - this.pathKey = pathKey; - this.value = value; + public BucketUpdater(final String pathField, final String pathBucket) { + this.pathField = pathField; + this.pathBucket = pathBucket; } - public AccountConfigUpdater setValue(final String value) { - this.value = value; + public BucketUpdater setRateLimitRequest( + final Bucket.RateLimitRequest rateLimitRequest + ) { + this.rateLimitRequest = rateLimitRequest; return this; } @Override - public AccountConfig update(final TwilioRestClient client) { - String path = "/v1/Configs/{Key}"; + public Bucket update(final TwilioRestClient client) { + String path = "/v2/RateLimits/Fields/{Field}/Bucket/{Bucket}"; - path = path.replace("{" + "Key" + "}", this.pathKey.toString()); - path = path.replace("{" + "Value" + "}", this.value.toString()); + path = path.replace("{" + "Field" + "}", this.pathField.toString()); + path = path.replace("{" + "Bucket" + "}", this.pathBucket.toString()); Request request = new Request( - HttpMethod.POST, - Domains.MICROVISOR.toString(), + HttpMethod.PUT, + Domains.LOOKUPS.toString(), path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); - addPostParams(request); + request.setContentType(EnumConstants.ContentType.JSON); + addPostParams(request, client); Response response = client.request(request); if (response == null) { throw new ApiConnectionException( - "AccountConfig update failed: Unable to connect to server" + "Bucket update failed: Unable to connect to server" ); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( @@ -73,15 +77,13 @@ public AccountConfig update(final TwilioRestClient client) { throw new ApiException(restException); } - return AccountConfig.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Bucket.fromJson(response.getStream(), client.getObjectMapper()); } - private void addPostParams(final Request request) { - if (value != null) { - request.addPostParam("Value", value); + private void addPostParams(final Request request, TwilioRestClient client) { + ObjectMapper objectMapper = client.getObjectMapper(); + if (rateLimitRequest != null) { + request.setBody(Bucket.toJson(rateLimitRequest, objectMapper)); } } } diff --git a/src/main/java/com/twilio/rest/lookups/v2/LookupOverride.java b/src/main/java/com/twilio/rest/lookups/v2/LookupOverride.java new file mode 100644 index 0000000000..2762094bfa --- /dev/null +++ b/src/main/java/com/twilio/rest/lookups/v2/LookupOverride.java @@ -0,0 +1,337 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Lookups + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package com.twilio.rest.lookups.v2; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.twilio.base.Resource; +import com.twilio.converter.DateConverter; +import com.twilio.converter.Promoter; +import com.twilio.exception.ApiConnectionException; +import com.twilio.exception.ApiException; +import java.io.IOException; +import java.io.InputStream; +import java.time.ZonedDateTime; +import java.util.Objects; +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; +import lombok.ToString; + +@JsonIgnoreProperties(ignoreUnknown = true) +@ToString +public class LookupOverride extends Resource { + + private static final long serialVersionUID = 147188354779019L; + + @ToString + public static class OverridesRequest { + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("line_type") + @Getter + @Setter + private LineTypeEnum lineType; + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("reason") + @Getter + @Setter + private String reason; + + public OverridesRequest() {} + + public static OverridesRequest fromJson( + String jsonString, + ObjectMapper mapper + ) throws IOException { + return mapper.readValue(jsonString, OverridesRequest.class); + } + } + + public static LookupOverrideCreator creator( + final String pathField, + final String pathPhoneNumber + ) { + return new LookupOverrideCreator(pathField, pathPhoneNumber); + } + + public static LookupOverrideDeleter deleter( + final String pathField, + final String pathPhoneNumber + ) { + return new LookupOverrideDeleter(pathField, pathPhoneNumber); + } + + public static LookupOverrideFetcher fetcher( + final String pathField, + final String pathPhoneNumber + ) { + return new LookupOverrideFetcher(pathField, pathPhoneNumber); + } + + public static LookupOverrideUpdater updater( + final String pathField, + final String pathPhoneNumber + ) { + return new LookupOverrideUpdater(pathField, pathPhoneNumber); + } + + /** + * Converts a JSON String into a LookupOverride object using the provided ObjectMapper. + * + * @param json Raw JSON String + * @param objectMapper Jackson ObjectMapper + * @return LookupOverride object represented by the provided JSON + */ + public static LookupOverride fromJson( + final String json, + final ObjectMapper objectMapper + ) { + // Convert all checked exceptions to Runtime + try { + return objectMapper.readValue(json, LookupOverride.class); + } catch (final JsonMappingException | JsonParseException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + /** + * Converts a JSON InputStream into a LookupOverride object using the provided + * ObjectMapper. + * + * @param json Raw JSON InputStream + * @param objectMapper Jackson ObjectMapper + * @return LookupOverride object represented by the provided JSON + */ + public static LookupOverride fromJson( + final InputStream json, + final ObjectMapper objectMapper + ) { + // Convert all checked exceptions to Runtime + try { + return objectMapper.readValue(json, LookupOverride.class); + } catch (final JsonMappingException | JsonParseException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + private final String phoneNumber; + private final LookupOverride.OriginalLineTypeEnum originalLineType; + private final LookupOverride.OverriddenLineTypeEnum overriddenLineType; + private final String overrideReason; + private final ZonedDateTime overrideTimestamp; + private final String overriddenByAccountSid; + + @JsonCreator + private LookupOverride( + @JsonProperty("phone_number") final String phoneNumber, + @JsonProperty( + "original_line_type" + ) final LookupOverride.OriginalLineTypeEnum originalLineType, + @JsonProperty( + "overridden_line_type" + ) final LookupOverride.OverriddenLineTypeEnum overriddenLineType, + @JsonProperty("override_reason") final String overrideReason, + @JsonProperty("override_timestamp") final String overrideTimestamp, + @JsonProperty( + "overridden_by_account_sid" + ) final String overriddenByAccountSid + ) { + this.phoneNumber = phoneNumber; + this.originalLineType = originalLineType; + this.overriddenLineType = overriddenLineType; + this.overrideReason = overrideReason; + this.overrideTimestamp = + DateConverter.iso8601DateTimeFromString(overrideTimestamp); + this.overriddenByAccountSid = overriddenByAccountSid; + } + + public final String getPhoneNumber() { + return this.phoneNumber; + } + + public final LookupOverride.OriginalLineTypeEnum getOriginalLineType() { + return this.originalLineType; + } + + public final LookupOverride.OverriddenLineTypeEnum getOverriddenLineType() { + return this.overriddenLineType; + } + + public final String getOverrideReason() { + return this.overrideReason; + } + + public final ZonedDateTime getOverrideTimestamp() { + return this.overrideTimestamp; + } + + public final String getOverriddenByAccountSid() { + return this.overriddenByAccountSid; + } + + @Override + public boolean equals(final Object o) { + if (this == o) { + return true; + } + + if (o == null || getClass() != o.getClass()) { + return false; + } + + LookupOverride other = (LookupOverride) o; + + return ( + Objects.equals(phoneNumber, other.phoneNumber) && + Objects.equals(originalLineType, other.originalLineType) && + Objects.equals(overriddenLineType, other.overriddenLineType) && + Objects.equals(overrideReason, other.overrideReason) && + Objects.equals(overrideTimestamp, other.overrideTimestamp) && + Objects.equals(overriddenByAccountSid, other.overriddenByAccountSid) + ); + } + + @Override + public int hashCode() { + return Objects.hash( + phoneNumber, + originalLineType, + overriddenLineType, + overrideReason, + overrideTimestamp, + overriddenByAccountSid + ); + } + + public enum OriginalLineTypeEnum { + MOBILE("mobile"), + LANDLINE("landline"), + TOLLFREE("tollFree"), + FIXEDVOIP("fixedVoip"), + NONFIXEDVOIP("nonFixedVoip"), + PERSONAL("personal"), + PREMIUM("premium"), + VOICEMAIL("voicemail"), + SHAREDCOST("sharedCost"), + UAN("uan"), + PAGER("pager"), + UNKNOWN("unknown"); + + private final String value; + + private OriginalLineTypeEnum(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static OriginalLineTypeEnum forValue(final String value) { + return Promoter.enumFromString( + value, + OriginalLineTypeEnum.values() + ); + } + } + + public enum OverriddenLineTypeEnum { + MOBILE("mobile"), + LANDLINE("landline"), + TOLLFREE("tollFree"), + FIXEDVOIP("fixedVoip"), + NONFIXEDVOIP("nonFixedVoip"), + PERSONAL("personal"), + PREMIUM("premium"), + VOICEMAIL("voicemail"), + SHAREDCOST("sharedCost"), + UAN("uan"), + PAGER("pager"), + UNKNOWN("unknown"); + + private final String value; + + private OverriddenLineTypeEnum(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static OverriddenLineTypeEnum forValue(final String value) { + return Promoter.enumFromString( + value, + OverriddenLineTypeEnum.values() + ); + } + } + + public enum LineTypeEnum { + MOBILE("mobile"), + LANDLINE("landline"), + TOLLFREE("tollFree"), + FIXEDVOIP("fixedVoip"), + NONFIXEDVOIP("nonFixedVoip"), + PERSONAL("personal"), + PREMIUM("premium"), + VOICEMAIL("voicemail"), + SHAREDCOST("sharedCost"), + UAN("uan"), + PAGER("pager"), + UNKNOWN("unknown"); + + private final String value; + + private LineTypeEnum(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static LineTypeEnum forValue(final String value) { + return Promoter.enumFromString(value, LineTypeEnum.values()); + } + } +} diff --git a/src/main/java/com/twilio/rest/knowledge/v1/KnowledgeCreator.java b/src/main/java/com/twilio/rest/lookups/v2/LookupOverrideCreator.java similarity index 61% rename from src/main/java/com/twilio/rest/knowledge/v1/KnowledgeCreator.java rename to src/main/java/com/twilio/rest/lookups/v2/LookupOverrideCreator.java index 943ed52437..bdc0dc5304 100644 --- a/src/main/java/com/twilio/rest/knowledge/v1/KnowledgeCreator.java +++ b/src/main/java/com/twilio/rest/lookups/v2/LookupOverrideCreator.java @@ -4,7 +4,7 @@ * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ * - * Twilio - Knowledge + * Twilio - Lookups * This is the public Twilio REST API. * * NOTE: This class is auto generated by OpenAPI Generator. @@ -12,7 +12,7 @@ * Do not edit the class manually. */ -package com.twilio.rest.knowledge.v1; +package com.twilio.rest.lookups.v2; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Creator; @@ -26,38 +26,41 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class KnowledgeCreator extends Creator { +public class LookupOverrideCreator extends Creator { - private Knowledge.KnowledgeV1ServiceCreateKnowledgeRequest knowledgeV1ServiceCreateKnowledgeRequest; + private String pathField; + private String pathPhoneNumber; + private LookupOverride.OverridesRequest overridesRequest; - public KnowledgeCreator( - final Knowledge.KnowledgeV1ServiceCreateKnowledgeRequest knowledgeV1ServiceCreateKnowledgeRequest + public LookupOverrideCreator( + final String pathField, + final String pathPhoneNumber ) { - this.knowledgeV1ServiceCreateKnowledgeRequest = - knowledgeV1ServiceCreateKnowledgeRequest; + this.pathField = pathField; + this.pathPhoneNumber = pathPhoneNumber; } - public KnowledgeCreator setKnowledgeV1ServiceCreateKnowledgeRequest( - final Knowledge.KnowledgeV1ServiceCreateKnowledgeRequest knowledgeV1ServiceCreateKnowledgeRequest + public LookupOverrideCreator setOverridesRequest( + final LookupOverride.OverridesRequest overridesRequest ) { - this.knowledgeV1ServiceCreateKnowledgeRequest = - knowledgeV1ServiceCreateKnowledgeRequest; + this.overridesRequest = overridesRequest; return this; } @Override - public Knowledge create(final TwilioRestClient client) { - String path = "/v1/Knowledge"; + public LookupOverride create(final TwilioRestClient client) { + String path = "/v2/PhoneNumbers/{PhoneNumber}/Overrides/{Field}"; + path = path.replace("{" + "Field" + "}", this.pathField.toString()); path = path.replace( - "{" + "KnowledgeV1ServiceCreateKnowledgeRequest" + "}", - this.knowledgeV1ServiceCreateKnowledgeRequest.toString() + "{" + "PhoneNumber" + "}", + this.pathPhoneNumber.toString() ); Request request = new Request( HttpMethod.POST, - Domains.KNOWLEDGE.toString(), + Domains.LOOKUPS.toString(), path ); request.setContentType(EnumConstants.ContentType.JSON); @@ -65,7 +68,7 @@ public Knowledge create(final TwilioRestClient client) { Response response = client.request(request); if (response == null) { throw new ApiConnectionException( - "Knowledge creation failed: Unable to connect to server" + "LookupOverride creation failed: Unable to connect to server" ); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( @@ -81,7 +84,7 @@ public Knowledge create(final TwilioRestClient client) { throw new ApiException(restException); } - return Knowledge.fromJson( + return LookupOverride.fromJson( response.getStream(), client.getObjectMapper() ); @@ -89,12 +92,9 @@ public Knowledge create(final TwilioRestClient client) { private void addPostParams(final Request request, TwilioRestClient client) { ObjectMapper objectMapper = client.getObjectMapper(); - if (knowledgeV1ServiceCreateKnowledgeRequest != null) { + if (overridesRequest != null) { request.setBody( - Knowledge.toJson( - knowledgeV1ServiceCreateKnowledgeRequest, - objectMapper - ) + LookupOverride.toJson(overridesRequest, objectMapper) ); } } diff --git a/src/main/java/com/twilio/rest/microvisor/v1/device/DeviceConfigDeleter.java b/src/main/java/com/twilio/rest/lookups/v2/LookupOverrideDeleter.java similarity index 71% rename from src/main/java/com/twilio/rest/microvisor/v1/device/DeviceConfigDeleter.java rename to src/main/java/com/twilio/rest/lookups/v2/LookupOverrideDeleter.java index e471b64a72..7a13b9fcf0 100644 --- a/src/main/java/com/twilio/rest/microvisor/v1/device/DeviceConfigDeleter.java +++ b/src/main/java/com/twilio/rest/lookups/v2/LookupOverrideDeleter.java @@ -4,7 +4,7 @@ * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ * - * Twilio - Microvisor + * Twilio - Lookups * This is the public Twilio REST API. * * NOTE: This class is auto generated by OpenAPI Generator. @@ -12,7 +12,7 @@ * Do not edit the class manually. */ -package com.twilio.rest.microvisor.v1.device; +package com.twilio.rest.lookups.v2; import com.twilio.base.Deleter; import com.twilio.constant.EnumConstants; @@ -25,33 +25,33 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class DeviceConfigDeleter extends Deleter { +public class LookupOverrideDeleter extends Deleter { - private String pathDeviceSid; - private String pathKey; + private String pathField; + private String pathPhoneNumber; - public DeviceConfigDeleter( - final String pathDeviceSid, - final String pathKey + public LookupOverrideDeleter( + final String pathField, + final String pathPhoneNumber ) { - this.pathDeviceSid = pathDeviceSid; - this.pathKey = pathKey; + this.pathField = pathField; + this.pathPhoneNumber = pathPhoneNumber; } @Override public boolean delete(final TwilioRestClient client) { - String path = "/v1/Devices/{DeviceSid}/Configs/{Key}"; + String path = "/v2/PhoneNumbers/{PhoneNumber}/Overrides/{Field}"; + path = path.replace("{" + "Field" + "}", this.pathField.toString()); path = path.replace( - "{" + "DeviceSid" + "}", - this.pathDeviceSid.toString() + "{" + "PhoneNumber" + "}", + this.pathPhoneNumber.toString() ); - path = path.replace("{" + "Key" + "}", this.pathKey.toString()); Request request = new Request( HttpMethod.DELETE, - Domains.MICROVISOR.toString(), + Domains.LOOKUPS.toString(), path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); @@ -59,7 +59,7 @@ public boolean delete(final TwilioRestClient client) { if (response == null) { throw new ApiConnectionException( - "DeviceConfig delete failed: Unable to connect to server" + "LookupOverride delete failed: Unable to connect to server" ); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( diff --git a/src/main/java/com/twilio/rest/microvisor/v1/device/DeviceConfigFetcher.java b/src/main/java/com/twilio/rest/lookups/v2/LookupOverrideFetcher.java similarity index 68% rename from src/main/java/com/twilio/rest/microvisor/v1/device/DeviceConfigFetcher.java rename to src/main/java/com/twilio/rest/lookups/v2/LookupOverrideFetcher.java index 3b0d148d4a..f345b4a4e4 100644 --- a/src/main/java/com/twilio/rest/microvisor/v1/device/DeviceConfigFetcher.java +++ b/src/main/java/com/twilio/rest/lookups/v2/LookupOverrideFetcher.java @@ -4,7 +4,7 @@ * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ * - * Twilio - Microvisor + * Twilio - Lookups * This is the public Twilio REST API. * * NOTE: This class is auto generated by OpenAPI Generator. @@ -12,7 +12,7 @@ * Do not edit the class manually. */ -package com.twilio.rest.microvisor.v1.device; +package com.twilio.rest.lookups.v2; import com.twilio.base.Fetcher; import com.twilio.constant.EnumConstants; @@ -25,33 +25,33 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class DeviceConfigFetcher extends Fetcher { +public class LookupOverrideFetcher extends Fetcher { - private String pathDeviceSid; - private String pathKey; + private String pathField; + private String pathPhoneNumber; - public DeviceConfigFetcher( - final String pathDeviceSid, - final String pathKey + public LookupOverrideFetcher( + final String pathField, + final String pathPhoneNumber ) { - this.pathDeviceSid = pathDeviceSid; - this.pathKey = pathKey; + this.pathField = pathField; + this.pathPhoneNumber = pathPhoneNumber; } @Override - public DeviceConfig fetch(final TwilioRestClient client) { - String path = "/v1/Devices/{DeviceSid}/Configs/{Key}"; + public LookupOverride fetch(final TwilioRestClient client) { + String path = "/v2/PhoneNumbers/{PhoneNumber}/Overrides/{Field}"; + path = path.replace("{" + "Field" + "}", this.pathField.toString()); path = path.replace( - "{" + "DeviceSid" + "}", - this.pathDeviceSid.toString() + "{" + "PhoneNumber" + "}", + this.pathPhoneNumber.toString() ); - path = path.replace("{" + "Key" + "}", this.pathKey.toString()); Request request = new Request( HttpMethod.GET, - Domains.MICROVISOR.toString(), + Domains.LOOKUPS.toString(), path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); @@ -59,7 +59,7 @@ public DeviceConfig fetch(final TwilioRestClient client) { if (response == null) { throw new ApiConnectionException( - "DeviceConfig fetch failed: Unable to connect to server" + "LookupOverride fetch failed: Unable to connect to server" ); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( @@ -75,7 +75,7 @@ public DeviceConfig fetch(final TwilioRestClient client) { throw new ApiException(restException); } - return DeviceConfig.fromJson( + return LookupOverride.fromJson( response.getStream(), client.getObjectMapper() ); diff --git a/src/main/java/com/twilio/rest/knowledge/v1/KnowledgeUpdater.java b/src/main/java/com/twilio/rest/lookups/v2/LookupOverrideUpdater.java similarity index 63% rename from src/main/java/com/twilio/rest/knowledge/v1/KnowledgeUpdater.java rename to src/main/java/com/twilio/rest/lookups/v2/LookupOverrideUpdater.java index bfa6ca6ee5..5674e6110a 100644 --- a/src/main/java/com/twilio/rest/knowledge/v1/KnowledgeUpdater.java +++ b/src/main/java/com/twilio/rest/lookups/v2/LookupOverrideUpdater.java @@ -4,7 +4,7 @@ * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ * - * Twilio - Knowledge + * Twilio - Lookups * This is the public Twilio REST API. * * NOTE: This class is auto generated by OpenAPI Generator. @@ -12,7 +12,7 @@ * Do not edit the class manually. */ -package com.twilio.rest.knowledge.v1; +package com.twilio.rest.lookups.v2; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Updater; @@ -26,32 +26,41 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class KnowledgeUpdater extends Updater { +public class LookupOverrideUpdater extends Updater { - private String pathId; - private Knowledge.KnowledgeV1ServiceUpdateKnowledgeRequest knowledgeV1ServiceUpdateKnowledgeRequest; + private String pathField; + private String pathPhoneNumber; + private LookupOverride.OverridesRequest overridesRequest; - public KnowledgeUpdater(final String pathId) { - this.pathId = pathId; + public LookupOverrideUpdater( + final String pathField, + final String pathPhoneNumber + ) { + this.pathField = pathField; + this.pathPhoneNumber = pathPhoneNumber; } - public KnowledgeUpdater setKnowledgeV1ServiceUpdateKnowledgeRequest( - final Knowledge.KnowledgeV1ServiceUpdateKnowledgeRequest knowledgeV1ServiceUpdateKnowledgeRequest + public LookupOverrideUpdater setOverridesRequest( + final LookupOverride.OverridesRequest overridesRequest ) { - this.knowledgeV1ServiceUpdateKnowledgeRequest = - knowledgeV1ServiceUpdateKnowledgeRequest; + this.overridesRequest = overridesRequest; return this; } @Override - public Knowledge update(final TwilioRestClient client) { - String path = "/v1/Knowledge/{id}"; + public LookupOverride update(final TwilioRestClient client) { + String path = "/v2/PhoneNumbers/{PhoneNumber}/Overrides/{Field}"; - path = path.replace("{" + "id" + "}", this.pathId.toString()); + path = path.replace("{" + "Field" + "}", this.pathField.toString()); + path = + path.replace( + "{" + "PhoneNumber" + "}", + this.pathPhoneNumber.toString() + ); Request request = new Request( HttpMethod.PUT, - Domains.KNOWLEDGE.toString(), + Domains.LOOKUPS.toString(), path ); request.setContentType(EnumConstants.ContentType.JSON); @@ -59,7 +68,7 @@ public Knowledge update(final TwilioRestClient client) { Response response = client.request(request); if (response == null) { throw new ApiConnectionException( - "Knowledge update failed: Unable to connect to server" + "LookupOverride update failed: Unable to connect to server" ); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( @@ -75,7 +84,7 @@ public Knowledge update(final TwilioRestClient client) { throw new ApiException(restException); } - return Knowledge.fromJson( + return LookupOverride.fromJson( response.getStream(), client.getObjectMapper() ); @@ -83,12 +92,9 @@ public Knowledge update(final TwilioRestClient client) { private void addPostParams(final Request request, TwilioRestClient client) { ObjectMapper objectMapper = client.getObjectMapper(); - if (knowledgeV1ServiceUpdateKnowledgeRequest != null) { + if (overridesRequest != null) { request.setBody( - Knowledge.toJson( - knowledgeV1ServiceUpdateKnowledgeRequest, - objectMapper - ) + LookupOverride.toJson(overridesRequest, objectMapper) ); } } diff --git a/src/main/java/com/twilio/rest/lookups/v2/PhoneNumber.java b/src/main/java/com/twilio/rest/lookups/v2/PhoneNumber.java index 4b25a770ee..0bed3d57d4 100644 --- a/src/main/java/com/twilio/rest/lookups/v2/PhoneNumber.java +++ b/src/main/java/com/twilio/rest/lookups/v2/PhoneNumber.java @@ -92,7 +92,7 @@ public static PhoneNumber fromJson( private final com.twilio.type.PhoneNumber phoneNumber; private final String nationalFormat; private final Boolean valid; - private final List validationErrors; + private final List validationErrors; private final Map callerName; private final Map simSwap; private final Map callForwarding; @@ -115,7 +115,7 @@ private PhoneNumber( @JsonProperty("national_format") final String nationalFormat, @JsonProperty("valid") final Boolean valid, @JsonProperty("validation_errors") final List< - ValidationError + PhoneNumber.ValidationError > validationErrors, @JsonProperty("caller_name") final Map callerName, @JsonProperty("sim_swap") final Map simSwap, @@ -183,7 +183,7 @@ public final Boolean getValid() { return this.valid; } - public final List getValidationErrors() { + public final List getValidationErrors() { return this.validationErrors; } diff --git a/src/main/java/com/twilio/rest/lookups/v2/Query.java b/src/main/java/com/twilio/rest/lookups/v2/Query.java new file mode 100644 index 0000000000..14e8748259 --- /dev/null +++ b/src/main/java/com/twilio/rest/lookups/v2/Query.java @@ -0,0 +1,799 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Lookups + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package com.twilio.rest.lookups.v2; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.twilio.base.Resource; +import com.twilio.converter.Promoter; +import com.twilio.exception.ApiConnectionException; +import com.twilio.exception.ApiException; +import java.io.IOException; +import java.io.InputStream; +import java.time.ZonedDateTime; +import java.util.List; +import java.util.Objects; +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; +import lombok.ToString; + +@JsonIgnoreProperties(ignoreUnknown = true) +@ToString +public class Query extends Resource { + + private static final long serialVersionUID = 115616150775512L; + + @ToString + public static class IdentityMatchParameters { + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("first_name") + @Getter + @Setter + private String firstName; + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("last_name") + @Getter + @Setter + private String lastName; + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("address_line1") + @Getter + @Setter + private String addressLine1; + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("address_line2") + @Getter + @Setter + private String addressLine2; + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("city") + @Getter + @Setter + private String city; + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("state") + @Getter + @Setter + private String state; + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("postal_code") + @Getter + @Setter + private String postalCode; + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("address_country_code") + @Getter + @Setter + private String addressCountryCode; + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("national_id") + @Getter + @Setter + private String nationalId; + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("date_of_birth") + @Getter + @Setter + private String dateOfBirth; + + public static IdentityMatchParameters fromJson( + String jsonString, + ObjectMapper mapper + ) throws IOException { + return mapper.readValue(jsonString, IdentityMatchParameters.class); + } + } + + @ToString + public static class ReassignedNumberRequest { + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("last_verified_date") + @Getter + @Setter + private String lastVerifiedDate; + + public static ReassignedNumberRequest fromJson( + String jsonString, + ObjectMapper mapper + ) throws IOException { + return mapper.readValue(jsonString, ReassignedNumberRequest.class); + } + } + + @ToString + public static class SmsPumpingRiskParameters { + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("partner_sub_id") + @Getter + @Setter + private String partnerSubId; + + public static SmsPumpingRiskParameters fromJson( + String jsonString, + ObjectMapper mapper + ) throws IOException { + return mapper.readValue(jsonString, SmsPumpingRiskParameters.class); + } + } + + @ToString + public static class LookupRequestWithCorId { + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("correlation_id") + @Getter + @Setter + private String correlationId; + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("phone_number") + @Getter + @Setter + private String phoneNumber; + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("fields") + @Getter + @Setter + private List fields; + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("country_code") + @Getter + @Setter + private String countryCode; + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("identity_match") + @Getter + @Setter + private IdentityMatchParameters identityMatch; + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("reassigned_number") + @Getter + @Setter + private ReassignedNumberRequest reassignedNumber; + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("sms_pumping_risk") + @Getter + @Setter + private SmsPumpingRiskParameters smsPumpingRisk; + + public static LookupRequestWithCorId fromJson( + String jsonString, + ObjectMapper mapper + ) throws IOException { + return mapper.readValue(jsonString, LookupRequestWithCorId.class); + } + } + + @ToString + public static class LookupRequest1 { + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("phone_numbers") + @Getter + @Setter + private List phoneNumbers; + + public LookupRequest1() {} + + public static LookupRequest1 fromJson( + String jsonString, + ObjectMapper mapper + ) throws IOException { + return mapper.readValue(jsonString, LookupRequest1.class); + } + } + + @ToString + public static class CallerName { + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("caller_name") + @Getter + @Setter + private String callerName; + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("caller_type") + @Getter + @Setter + private String callerType; + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("error_code") + @Getter + @Setter + private Integer errorCode; + + public static CallerName fromJson( + String jsonString, + ObjectMapper mapper + ) throws IOException { + return mapper.readValue(jsonString, CallerName.class); + } + } + + @ToString + public static class LastSimSwap { + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("last_sim_swap_date") + @Getter + @Setter + private ZonedDateTime lastSimSwapDate; + + public String getLastSimSwapDate() { + return lastSimSwapDate.toInstant().toString(); + } + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("swapped_period") + @Getter + @Setter + private String swappedPeriod; + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("swapped_in_period") + @Getter + @Setter + private Boolean swappedInPeriod; + + public static LastSimSwap fromJson( + String jsonString, + ObjectMapper mapper + ) throws IOException { + return mapper.readValue(jsonString, LastSimSwap.class); + } + } + + @ToString + public static class SimSwap { + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("last_sim_swap") + @Getter + @Setter + private LastSimSwap lastSimSwap; + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("carrier_name") + @Getter + @Setter + private String carrierName; + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("mobile_country_code") + @Getter + @Setter + private String mobileCountryCode; + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("mobile_network_code") + @Getter + @Setter + private String mobileNetworkCode; + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("error_code") + @Getter + @Setter + private Integer errorCode; + + public static SimSwap fromJson(String jsonString, ObjectMapper mapper) + throws IOException { + return mapper.readValue(jsonString, SimSwap.class); + } + } + + @ToString + public static class CallForwarding { + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("call_forwarding_enabled") + @Getter + @Setter + private Boolean callForwardingEnabled; + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("error_code") + @Getter + @Setter + private Integer errorCode; + + public static CallForwarding fromJson( + String jsonString, + ObjectMapper mapper + ) throws IOException { + return mapper.readValue(jsonString, CallForwarding.class); + } + } + + @ToString + public static class LineTypeIntelligence { + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("type") + @Getter + @Setter + private String type; + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("carrier_name") + @Getter + @Setter + private String carrierName; + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("mobile_country_code") + @Getter + @Setter + private String mobileCountryCode; + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("mobile_network_code") + @Getter + @Setter + private String mobileNetworkCode; + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("error_code") + @Getter + @Setter + private Integer errorCode; + + public static LineTypeIntelligence fromJson( + String jsonString, + ObjectMapper mapper + ) throws IOException { + return mapper.readValue(jsonString, LineTypeIntelligence.class); + } + } + + @ToString + public static class LineStatus { + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("status") + @Getter + @Setter + private String status; + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("error_code") + @Getter + @Setter + private Integer errorCode; + + public static LineStatus fromJson( + String jsonString, + ObjectMapper mapper + ) throws IOException { + return mapper.readValue(jsonString, LineStatus.class); + } + } + + @ToString + public static class IdentityMatch { + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("first_name_match") + @Getter + @Setter + private String firstNameMatch; + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("last_name_match") + @Getter + @Setter + private String lastNameMatch; + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("address_line_match") + @Getter + @Setter + private String addressLineMatch; + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("city_match") + @Getter + @Setter + private String cityMatch; + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("state_match") + @Getter + @Setter + private String stateMatch; + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("postal_code_match") + @Getter + @Setter + private String postalCodeMatch; + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("country_code_match") + @Getter + @Setter + private String countryCodeMatch; + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("national_id_match") + @Getter + @Setter + private String nationalIdMatch; + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("date_of_birth_match") + @Getter + @Setter + private String dateOfBirthMatch; + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("summary_score") + @Getter + @Setter + private Integer summaryScore; + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("error_code") + @Getter + @Setter + private Integer errorCode; + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("error_message") + @Getter + @Setter + private String errorMessage; + + public static IdentityMatch fromJson( + String jsonString, + ObjectMapper mapper + ) throws IOException { + return mapper.readValue(jsonString, IdentityMatch.class); + } + } + + @ToString + public static class ReassignedNumberResponse { + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("last_verified_date") + @Getter + @Setter + private String lastVerifiedDate; + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("is_number_reassigned") + @Getter + @Setter + private String isNumberReassigned; + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("error_code") + @Getter + @Setter + private String errorCode; + + public static ReassignedNumberResponse fromJson( + String jsonString, + ObjectMapper mapper + ) throws IOException { + return mapper.readValue(jsonString, ReassignedNumberResponse.class); + } + } + + @ToString + public static class SmsPumpingRisk { + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("carrier_risk_category") + @Getter + @Setter + private String carrierRiskCategory; + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("number_blocked") + @Getter + @Setter + private Boolean numberBlocked; + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("number_blocked_date") + @Getter + @Setter + private ZonedDateTime numberBlockedDate; + + public String getNumberBlockedDate() { + return numberBlockedDate.toInstant().toString(); + } + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("number_blocked_last_3_months") + @Getter + @Setter + private Boolean numberBlockedLast3Months; + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("sms_pumping_risk_score") + @Getter + @Setter + private Integer smsPumpingRiskScore; + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("error_code") + @Getter + @Setter + private Integer errorCode; + + public static SmsPumpingRisk fromJson( + String jsonString, + ObjectMapper mapper + ) throws IOException { + return mapper.readValue(jsonString, SmsPumpingRisk.class); + } + } + + @ToString + public static class LookupResponseWithCorId { + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("correlation_id") + @Getter + @Setter + private String correlationId; + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("twilio_error_code") + @Getter + @Setter + private Integer twilioErrorCode; + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("calling_country_code") + @Getter + @Setter + private String callingCountryCode; + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("country_code") + @Getter + @Setter + private String countryCode; + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("phone_number") + @Getter + @Setter + private String phoneNumber; + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("national_format") + @Getter + @Setter + private String nationalFormat; + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("valid") + @Getter + @Setter + private Boolean valid; + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("validation_errors") + @Getter + @Setter + private List validationErrors; + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("caller_name") + @Getter + @Setter + private CallerName callerName; + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("sim_swap") + @Getter + @Setter + private SimSwap simSwap; + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("call_forwarding") + @Getter + @Setter + private CallForwarding callForwarding; + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("line_type_intelligence") + @Getter + @Setter + private LineTypeIntelligence lineTypeIntelligence; + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("line_status") + @Getter + @Setter + private LineStatus lineStatus; + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("identity_match") + @Getter + @Setter + private IdentityMatch identityMatch; + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("reassigned_number") + @Getter + @Setter + private ReassignedNumberResponse reassignedNumber; + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("sms_pumping_risk") + @Getter + @Setter + private SmsPumpingRisk smsPumpingRisk; + + public static LookupResponseWithCorId fromJson( + String jsonString, + ObjectMapper mapper + ) throws IOException { + return mapper.readValue(jsonString, LookupResponseWithCorId.class); + } + } + + public static QueryCreator creator() { + return new QueryCreator(); + } + + /** + * Converts a JSON String into a Query object using the provided ObjectMapper. + * + * @param json Raw JSON String + * @param objectMapper Jackson ObjectMapper + * @return Query object represented by the provided JSON + */ + public static Query fromJson( + final String json, + final ObjectMapper objectMapper + ) { + // Convert all checked exceptions to Runtime + try { + return objectMapper.readValue(json, Query.class); + } catch (final JsonMappingException | JsonParseException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + /** + * Converts a JSON InputStream into a Query object using the provided + * ObjectMapper. + * + * @param json Raw JSON InputStream + * @param objectMapper Jackson ObjectMapper + * @return Query object represented by the provided JSON + */ + public static Query fromJson( + final InputStream json, + final ObjectMapper objectMapper + ) { + // Convert all checked exceptions to Runtime + try { + return objectMapper.readValue(json, Query.class); + } catch (final JsonMappingException | JsonParseException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + private final List phoneNumbers; + + @JsonCreator + private Query( + @JsonProperty("phone_numbers") final List< + LookupResponseWithCorId + > phoneNumbers + ) { + this.phoneNumbers = phoneNumbers; + } + + public final List getPhoneNumbers() { + return this.phoneNumbers; + } + + @Override + public boolean equals(final Object o) { + if (this == o) { + return true; + } + + if (o == null || getClass() != o.getClass()) { + return false; + } + + Query other = (Query) o; + + return Objects.equals(phoneNumbers, other.phoneNumbers); + } + + @Override + public int hashCode() { + return Objects.hash(phoneNumbers); + } + + public enum FieldsEnum { + CALLER_NAME("caller_name"), + SIM_SWAP("sim_swap"), + CALL_FORWARDING("call_forwarding"), + LINE_TYPE_INTELLIGENCE("line_type_intelligence"), + LINE_STATUS("line_status"), + IDENTITY_MATCH("identity_match"), + REASSIGNED_NUMBER("reassigned_number"), + SMS_PUMPING_RISK("sms_pumping_risk"); + + private final String value; + + private FieldsEnum(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static FieldsEnum forValue(final String value) { + return Promoter.enumFromString(value, FieldsEnum.values()); + } + } +} diff --git a/src/main/java/com/twilio/rest/microvisor/v1/device/DeviceSecretDeleter.java b/src/main/java/com/twilio/rest/lookups/v2/QueryCreator.java similarity index 58% rename from src/main/java/com/twilio/rest/microvisor/v1/device/DeviceSecretDeleter.java rename to src/main/java/com/twilio/rest/lookups/v2/QueryCreator.java index 992f623f57..e7481c28d8 100644 --- a/src/main/java/com/twilio/rest/microvisor/v1/device/DeviceSecretDeleter.java +++ b/src/main/java/com/twilio/rest/lookups/v2/QueryCreator.java @@ -4,7 +4,7 @@ * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ * - * Twilio - Microvisor + * Twilio - Lookups * This is the public Twilio REST API. * * NOTE: This class is auto generated by OpenAPI Generator. @@ -12,9 +12,10 @@ * Do not edit the class manually. */ -package com.twilio.rest.microvisor.v1.device; +package com.twilio.rest.lookups.v2; -import com.twilio.base.Deleter; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; @@ -25,41 +26,34 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class DeviceSecretDeleter extends Deleter { +public class QueryCreator extends Creator { - private String pathDeviceSid; - private String pathKey; + private Query.LookupRequest1 lookupRequest1; - public DeviceSecretDeleter( - final String pathDeviceSid, - final String pathKey + public QueryCreator() {} + + public QueryCreator setLookupRequest1( + final Query.LookupRequest1 lookupRequest1 ) { - this.pathDeviceSid = pathDeviceSid; - this.pathKey = pathKey; + this.lookupRequest1 = lookupRequest1; + return this; } @Override - public boolean delete(final TwilioRestClient client) { - String path = "/v1/Devices/{DeviceSid}/Secrets/{Key}"; - - path = - path.replace( - "{" + "DeviceSid" + "}", - this.pathDeviceSid.toString() - ); - path = path.replace("{" + "Key" + "}", this.pathKey.toString()); + public Query create(final TwilioRestClient client) { + String path = "/v2/batch/query"; Request request = new Request( - HttpMethod.DELETE, - Domains.MICROVISOR.toString(), + HttpMethod.POST, + Domains.LOOKUPS.toString(), path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + request.setContentType(EnumConstants.ContentType.JSON); + addPostParams(request, client); Response response = client.request(request); - if (response == null) { throw new ApiConnectionException( - "DeviceSecret delete failed: Unable to connect to server" + "Query creation failed: Unable to connect to server" ); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( @@ -74,6 +68,14 @@ public boolean delete(final TwilioRestClient client) { } throw new ApiException(restException); } - return response.getStatusCode() == 204; + + return Query.fromJson(response.getStream(), client.getObjectMapper()); + } + + private void addPostParams(final Request request, TwilioRestClient client) { + ObjectMapper objectMapper = client.getObjectMapper(); + if (lookupRequest1 != null) { + request.setBody(Query.toJson(lookupRequest1, objectMapper)); + } } } diff --git a/src/main/java/com/twilio/rest/microvisor/v1/app/AppManifest.java b/src/main/java/com/twilio/rest/lookups/v2/RateLimit.java similarity index 52% rename from src/main/java/com/twilio/rest/microvisor/v1/app/AppManifest.java rename to src/main/java/com/twilio/rest/lookups/v2/RateLimit.java index 9beb04ce48..0551523fd0 100644 --- a/src/main/java/com/twilio/rest/microvisor/v1/app/AppManifest.java +++ b/src/main/java/com/twilio/rest/lookups/v2/RateLimit.java @@ -4,7 +4,7 @@ * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ * - * Twilio - Microvisor + * Twilio - Lookups * This is the public Twilio REST API. * * NOTE: This class is auto generated by OpenAPI Generator. @@ -12,10 +12,11 @@ * Do not edit the class manually. */ -package com.twilio.rest.microvisor.v1.app; +package com.twilio.rest.lookups.v2; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.JsonMappingException; @@ -25,35 +26,78 @@ import com.twilio.exception.ApiException; import java.io.IOException; import java.io.InputStream; -import java.net.URI; +import java.util.List; import java.util.Objects; +import lombok.Getter; +import lombok.Setter; import lombok.ToString; import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString -public class AppManifest extends Resource { - - private static final long serialVersionUID = 249809073531699L; +public class RateLimit extends Resource { + + private static final long serialVersionUID = 36869169584327L; + + @ToString + public static class RateLimitResponse { + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("field") + @Getter + @Setter + private String field; + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("limit") + @Getter + @Setter + private Integer limit; + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("bucket") + @Getter + @Setter + private String bucket; + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("owner") + @Getter + @Setter + private String owner; + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("ttl") + @Getter + @Setter + private Integer ttl; + + public static RateLimitResponse fromJson( + String jsonString, + ObjectMapper mapper + ) throws IOException { + return mapper.readValue(jsonString, RateLimitResponse.class); + } + } - public static AppManifestFetcher fetcher(final String pathAppSid) { - return new AppManifestFetcher(pathAppSid); + public static RateLimitFetcher fetcher() { + return new RateLimitFetcher(); } /** - * Converts a JSON String into a AppManifest object using the provided ObjectMapper. + * Converts a JSON String into a RateLimit object using the provided ObjectMapper. * * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper - * @return AppManifest object represented by the provided JSON + * @return RateLimit object represented by the provided JSON */ - public static AppManifest fromJson( + public static RateLimit fromJson( final String json, final ObjectMapper objectMapper ) { // Convert all checked exceptions to Runtime try { - return objectMapper.readValue(json, AppManifest.class); + return objectMapper.readValue(json, RateLimit.class); } catch (final JsonMappingException | JsonParseException e) { throw new ApiException(e.getMessage(), e); } catch (final IOException e) { @@ -62,20 +106,20 @@ public static AppManifest fromJson( } /** - * Converts a JSON InputStream into a AppManifest object using the provided + * Converts a JSON InputStream into a RateLimit object using the provided * ObjectMapper. * * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper - * @return AppManifest object represented by the provided JSON + * @return RateLimit object represented by the provided JSON */ - public static AppManifest fromJson( + public static RateLimit fromJson( final InputStream json, final ObjectMapper objectMapper ) { // Convert all checked exceptions to Runtime try { - return objectMapper.readValue(json, AppManifest.class); + return objectMapper.readValue(json, RateLimit.class); } catch (final JsonMappingException | JsonParseException e) { throw new ApiException(e.getMessage(), e); } catch (final IOException e) { @@ -83,38 +127,17 @@ public static AppManifest fromJson( } } - private final String appSid; - private final String hash; - private final String encodedBytes; - private final URI url; + private final List rateLimits; @JsonCreator - private AppManifest( - @JsonProperty("app_sid") final String appSid, - @JsonProperty("hash") final String hash, - @JsonProperty("encoded_bytes") final String encodedBytes, - @JsonProperty("url") final URI url + private RateLimit( + @JsonProperty("rate_limits") final List rateLimits ) { - this.appSid = appSid; - this.hash = hash; - this.encodedBytes = encodedBytes; - this.url = url; - } - - public final String getAppSid() { - return this.appSid; - } - - public final String getHash() { - return this.hash; - } - - public final String getEncodedBytes() { - return this.encodedBytes; + this.rateLimits = rateLimits; } - public final URI getUrl() { - return this.url; + public final List getRateLimits() { + return this.rateLimits; } @Override @@ -127,18 +150,13 @@ public boolean equals(final Object o) { return false; } - AppManifest other = (AppManifest) o; + RateLimit other = (RateLimit) o; - return ( - Objects.equals(appSid, other.appSid) && - Objects.equals(hash, other.hash) && - Objects.equals(encodedBytes, other.encodedBytes) && - Objects.equals(url, other.url) - ); + return Objects.equals(rateLimits, other.rateLimits); } @Override public int hashCode() { - return Objects.hash(appSid, hash, encodedBytes, url); + return Objects.hash(rateLimits); } } diff --git a/src/main/java/com/twilio/rest/proxy/v1/service/ShortCodeFetcher.java b/src/main/java/com/twilio/rest/lookups/v2/RateLimitFetcher.java similarity index 65% rename from src/main/java/com/twilio/rest/proxy/v1/service/ShortCodeFetcher.java rename to src/main/java/com/twilio/rest/lookups/v2/RateLimitFetcher.java index deeb66ca54..8d3e241b82 100644 --- a/src/main/java/com/twilio/rest/proxy/v1/service/ShortCodeFetcher.java +++ b/src/main/java/com/twilio/rest/lookups/v2/RateLimitFetcher.java @@ -4,7 +4,7 @@ * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ * - * Twilio - Proxy + * Twilio - Lookups * This is the public Twilio REST API. * * NOTE: This class is auto generated by OpenAPI Generator. @@ -12,10 +12,11 @@ * Do not edit the class manually. */ -package com.twilio.rest.proxy.v1.service; +package com.twilio.rest.lookups.v2; import com.twilio.base.Fetcher; import com.twilio.constant.EnumConstants; +import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -24,39 +25,39 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; +import java.util.List; -public class ShortCodeFetcher extends Fetcher { +public class RateLimitFetcher extends Fetcher { - private String pathServiceSid; - private String pathSid; + private List fields; - public ShortCodeFetcher(final String pathServiceSid, final String pathSid) { - this.pathServiceSid = pathServiceSid; - this.pathSid = pathSid; + public RateLimitFetcher() {} + + public RateLimitFetcher setFields(final List fields) { + this.fields = fields; + return this; } - @Override - public ShortCode fetch(final TwilioRestClient client) { - String path = "/v1/Services/{ServiceSid}/ShortCodes/{Sid}"; + public RateLimitFetcher setFields(final String fields) { + return setFields(Promoter.listOfOne(fields)); + } - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + @Override + public RateLimit fetch(final TwilioRestClient client) { + String path = "/v2/RateLimits"; Request request = new Request( HttpMethod.GET, - Domains.PROXY.toString(), + Domains.LOOKUPS.toString(), path ); + addQueryParams(request); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); Response response = client.request(request); if (response == null) { throw new ApiConnectionException( - "ShortCode fetch failed: Unable to connect to server" + "RateLimit fetch failed: Unable to connect to server" ); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( @@ -72,9 +73,17 @@ public ShortCode fetch(final TwilioRestClient client) { throw new ApiException(restException); } - return ShortCode.fromJson( + return RateLimit.fromJson( response.getStream(), client.getObjectMapper() ); } + + private void addQueryParams(final Request request) { + if (fields != null) { + for (String prop : fields) { + request.addQueryParam("Fields", prop); + } + } + } } diff --git a/src/main/java/com/twilio/rest/marketplace/v1/ReferralConversion.java b/src/main/java/com/twilio/rest/marketplace/v1/ReferralConversion.java index 4210a1e21c..2981e42916 100644 --- a/src/main/java/com/twilio/rest/marketplace/v1/ReferralConversion.java +++ b/src/main/java/com/twilio/rest/marketplace/v1/ReferralConversion.java @@ -62,7 +62,7 @@ public static CreateReferralConversionRequest fromJson( } public static ReferralConversionCreator creator( - final CreateReferralConversionRequest createReferralConversionRequest + final ReferralConversion.CreateReferralConversionRequest createReferralConversionRequest ) { return new ReferralConversionCreator(createReferralConversionRequest); } diff --git a/src/main/java/com/twilio/rest/marketplace/v1/installedaddon/InstalledAddOnUsage.java b/src/main/java/com/twilio/rest/marketplace/v1/installedaddon/InstalledAddOnUsage.java index 02d957a065..26949939ae 100644 --- a/src/main/java/com/twilio/rest/marketplace/v1/installedaddon/InstalledAddOnUsage.java +++ b/src/main/java/com/twilio/rest/marketplace/v1/installedaddon/InstalledAddOnUsage.java @@ -111,7 +111,7 @@ public static MarketplaceV1InstalledAddOnInstalledAddOnUsage fromJson( public static InstalledAddOnUsageCreator creator( final String pathInstalledAddOnSid, - final MarketplaceV1InstalledAddOnInstalledAddOnUsage marketplaceV1InstalledAddOnInstalledAddOnUsage + final InstalledAddOnUsage.MarketplaceV1InstalledAddOnInstalledAddOnUsage marketplaceV1InstalledAddOnInstalledAddOnUsage ) { return new InstalledAddOnUsageCreator( pathInstalledAddOnSid, diff --git a/src/main/java/com/twilio/rest/messaging/v1/BrandRegistration.java b/src/main/java/com/twilio/rest/messaging/v1/BrandRegistration.java index a485f926b2..1f04545099 100644 --- a/src/main/java/com/twilio/rest/messaging/v1/BrandRegistration.java +++ b/src/main/java/com/twilio/rest/messaging/v1/BrandRegistration.java @@ -114,14 +114,14 @@ public static BrandRegistration fromJson( private final ZonedDateTime dateCreated; private final ZonedDateTime dateUpdated; private final String brandType; - private final Status status; + private final BrandRegistration.Status status; private final String tcrId; private final String failureReason; private final List> errors; private final URI url; private final Integer brandScore; - private final List brandFeedback; - private final IdentityStatus identityStatus; + private final List brandFeedback; + private final BrandRegistration.IdentityStatus identityStatus; private final Boolean russell3000; private final Boolean governmentEntity; private final String taxExemptStatus; @@ -142,14 +142,18 @@ private BrandRegistration( @JsonProperty("date_created") final String dateCreated, @JsonProperty("date_updated") final String dateUpdated, @JsonProperty("brand_type") final String brandType, - @JsonProperty("status") final Status status, + @JsonProperty("status") final BrandRegistration.Status status, @JsonProperty("tcr_id") final String tcrId, @JsonProperty("failure_reason") final String failureReason, @JsonProperty("errors") final List> errors, @JsonProperty("url") final URI url, @JsonProperty("brand_score") final Integer brandScore, - @JsonProperty("brand_feedback") final List brandFeedback, - @JsonProperty("identity_status") final IdentityStatus identityStatus, + @JsonProperty("brand_feedback") final List< + BrandRegistration.BrandFeedback + > brandFeedback, + @JsonProperty( + "identity_status" + ) final BrandRegistration.IdentityStatus identityStatus, @JsonProperty("russell3000") final Boolean russell3000, @JsonProperty("government_entity") final Boolean governmentEntity, @JsonProperty("tax_exempt_status") final String taxExemptStatus, @@ -210,7 +214,7 @@ public final String getBrandType() { return this.brandType; } - public final Status getStatus() { + public final BrandRegistration.Status getStatus() { return this.status; } @@ -234,11 +238,11 @@ public final Integer getBrandScore() { return this.brandScore; } - public final List getBrandFeedback() { + public final List getBrandFeedback() { return this.brandFeedback; } - public final IdentityStatus getIdentityStatus() { + public final BrandRegistration.IdentityStatus getIdentityStatus() { return this.identityStatus; } diff --git a/src/main/java/com/twilio/rest/messaging/v1/Service.java b/src/main/java/com/twilio/rest/messaging/v1/Service.java index 9d320105f4..3775bf4572 100644 --- a/src/main/java/com/twilio/rest/messaging/v1/Service.java +++ b/src/main/java/com/twilio/rest/messaging/v1/Service.java @@ -118,7 +118,7 @@ public static Service fromJson( private final Boolean stickySender; private final Boolean mmsConverter; private final Boolean smartEncoding; - private final ScanMessageContent scanMessageContent; + private final Service.ScanMessageContent scanMessageContent; private final Boolean fallbackToLongCode; private final Boolean areaCodeGeomatch; private final Boolean synchronousValidation; @@ -146,7 +146,7 @@ private Service( @JsonProperty("smart_encoding") final Boolean smartEncoding, @JsonProperty( "scan_message_content" - ) final ScanMessageContent scanMessageContent, + ) final Service.ScanMessageContent scanMessageContent, @JsonProperty("fallback_to_long_code") final Boolean fallbackToLongCode, @JsonProperty("area_code_geomatch") final Boolean areaCodeGeomatch, @JsonProperty( @@ -240,7 +240,7 @@ public final Boolean getSmartEncoding() { return this.smartEncoding; } - public final ScanMessageContent getScanMessageContent() { + public final Service.ScanMessageContent getScanMessageContent() { return this.scanMessageContent; } diff --git a/src/main/java/com/twilio/rest/messaging/v1/TollfreeVerification.java b/src/main/java/com/twilio/rest/messaging/v1/TollfreeVerification.java index 2a189ab49f..da3ddb6f84 100644 --- a/src/main/java/com/twilio/rest/messaging/v1/TollfreeVerification.java +++ b/src/main/java/com/twilio/rest/messaging/v1/TollfreeVerification.java @@ -50,7 +50,7 @@ public static TollfreeVerificationCreator creator( final String useCaseSummary, final String productionMessageSample, final List optInImageUrls, - final OptInType optInType, + final TollfreeVerification.OptInType optInType, final String messageVolume, final String tollfreePhoneNumberSid ) { @@ -151,11 +151,11 @@ public static TollfreeVerification fromJson( private final String useCaseSummary; private final String productionMessageSample; private final List optInImageUrls; - private final OptInType optInType; + private final TollfreeVerification.OptInType optInType; private final String messageVolume; private final String additionalInformation; private final String tollfreePhoneNumberSid; - private final Status status; + private final TollfreeVerification.Status status; private final URI url; private final String rejectionReason; private final Integer errorCode; @@ -209,7 +209,9 @@ private TollfreeVerification( "production_message_sample" ) final String productionMessageSample, @JsonProperty("opt_in_image_urls") final List optInImageUrls, - @JsonProperty("opt_in_type") final OptInType optInType, + @JsonProperty( + "opt_in_type" + ) final TollfreeVerification.OptInType optInType, @JsonProperty("message_volume") final String messageVolume, @JsonProperty( "additional_information" @@ -217,7 +219,7 @@ private TollfreeVerification( @JsonProperty( "tollfree_phone_number_sid" ) final String tollfreePhoneNumberSid, - @JsonProperty("status") final Status status, + @JsonProperty("status") final TollfreeVerification.Status status, @JsonProperty("url") final URI url, @JsonProperty("rejection_reason") final String rejectionReason, @JsonProperty("error_code") final Integer errorCode, @@ -365,7 +367,7 @@ public final List getOptInImageUrls() { return this.optInImageUrls; } - public final OptInType getOptInType() { + public final TollfreeVerification.OptInType getOptInType() { return this.optInType; } @@ -381,7 +383,7 @@ public final String getTollfreePhoneNumberSid() { return this.tollfreePhoneNumberSid; } - public final Status getStatus() { + public final TollfreeVerification.Status getStatus() { return this.status; } diff --git a/src/main/java/com/twilio/rest/messaging/v1/brandregistration/BrandVetting.java b/src/main/java/com/twilio/rest/messaging/v1/brandregistration/BrandVetting.java index 8c284bbaf7..7d7f8526b5 100644 --- a/src/main/java/com/twilio/rest/messaging/v1/brandregistration/BrandVetting.java +++ b/src/main/java/com/twilio/rest/messaging/v1/brandregistration/BrandVetting.java @@ -41,7 +41,7 @@ public class BrandVetting extends Resource { public static BrandVettingCreator creator( final String pathBrandSid, - final VettingProvider vettingProvider + final BrandVetting.VettingProvider vettingProvider ) { return new BrandVettingCreator(pathBrandSid, vettingProvider); } @@ -108,7 +108,7 @@ public static BrandVetting fromJson( private final String vettingId; private final String vettingClass; private final String vettingStatus; - private final VettingProvider vettingProvider; + private final BrandVetting.VettingProvider vettingProvider; private final URI url; @JsonCreator @@ -121,7 +121,9 @@ private BrandVetting( @JsonProperty("vetting_id") final String vettingId, @JsonProperty("vetting_class") final String vettingClass, @JsonProperty("vetting_status") final String vettingStatus, - @JsonProperty("vetting_provider") final VettingProvider vettingProvider, + @JsonProperty( + "vetting_provider" + ) final BrandVetting.VettingProvider vettingProvider, @JsonProperty("url") final URI url ) { this.accountSid = accountSid; @@ -168,7 +170,7 @@ public final String getVettingStatus() { return this.vettingStatus; } - public final VettingProvider getVettingProvider() { + public final BrandVetting.VettingProvider getVettingProvider() { return this.vettingProvider; } diff --git a/src/main/java/com/twilio/rest/messaging/v2/ChannelsSender.java b/src/main/java/com/twilio/rest/messaging/v2/ChannelsSender.java index c2650d66d0..668b7a85cb 100644 --- a/src/main/java/com/twilio/rest/messaging/v2/ChannelsSender.java +++ b/src/main/java/com/twilio/rest/messaging/v2/ChannelsSender.java @@ -441,7 +441,7 @@ public static MessagingV2ChannelsSenderOfflineReasonsItems fromJson( } public static ChannelsSenderCreator creator( - final MessagingV2ChannelsSenderRequestsCreate messagingV2ChannelsSenderRequestsCreate + final ChannelsSender.MessagingV2ChannelsSenderRequestsCreate messagingV2ChannelsSenderRequestsCreate ) { return new ChannelsSenderCreator( messagingV2ChannelsSenderRequestsCreate @@ -520,7 +520,7 @@ public static String toJson(Object object, ObjectMapper mapper) { } private final String sid; - private final Status status; + private final ChannelsSender.Status status; private final String senderId; private final MessagingV2ChannelsSenderConfiguration configuration; private final MessagingV2ChannelsSenderWebhook webhook; @@ -534,7 +534,7 @@ public static String toJson(Object object, ObjectMapper mapper) { @JsonCreator private ChannelsSender( @JsonProperty("sid") final String sid, - @JsonProperty("status") final Status status, + @JsonProperty("status") final ChannelsSender.Status status, @JsonProperty("sender_id") final String senderId, @JsonProperty( "configuration" @@ -566,7 +566,7 @@ public final String getSid() { return this.sid; } - public final Status getStatus() { + public final ChannelsSender.Status getStatus() { return this.status; } diff --git a/src/main/java/com/twilio/rest/microvisor/v1/AccountConfig.java b/src/main/java/com/twilio/rest/microvisor/v1/AccountConfig.java deleted file mode 100644 index f51341b9ef..0000000000 --- a/src/main/java/com/twilio/rest/microvisor/v1/AccountConfig.java +++ /dev/null @@ -1,168 +0,0 @@ -/* - * This code was generated by - * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ - * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ - * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ - * - * Twilio - Microvisor - * This is the public Twilio REST API. - * - * NOTE: This class is auto generated by OpenAPI Generator. - * https://openapi-generator.tech - * Do not edit the class manually. - */ - -package com.twilio.rest.microvisor.v1; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.core.JsonParseException; -import com.fasterxml.jackson.databind.JsonMappingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; -import com.twilio.exception.ApiConnectionException; -import com.twilio.exception.ApiException; -import java.io.IOException; -import java.io.InputStream; -import java.net.URI; -import java.time.ZonedDateTime; -import java.util.Objects; -import lombok.ToString; -import lombok.ToString; - -@JsonIgnoreProperties(ignoreUnknown = true) -@ToString -public class AccountConfig extends Resource { - - private static final long serialVersionUID = 212393375904180L; - - public static AccountConfigCreator creator( - final String key, - final String value - ) { - return new AccountConfigCreator(key, value); - } - - public static AccountConfigDeleter deleter(final String pathKey) { - return new AccountConfigDeleter(pathKey); - } - - public static AccountConfigFetcher fetcher(final String pathKey) { - return new AccountConfigFetcher(pathKey); - } - - public static AccountConfigReader reader() { - return new AccountConfigReader(); - } - - public static AccountConfigUpdater updater( - final String pathKey, - final String value - ) { - return new AccountConfigUpdater(pathKey, value); - } - - /** - * Converts a JSON String into a AccountConfig object using the provided ObjectMapper. - * - * @param json Raw JSON String - * @param objectMapper Jackson ObjectMapper - * @return AccountConfig object represented by the provided JSON - */ - public static AccountConfig fromJson( - final String json, - final ObjectMapper objectMapper - ) { - // Convert all checked exceptions to Runtime - try { - return objectMapper.readValue(json, AccountConfig.class); - } catch (final JsonMappingException | JsonParseException e) { - throw new ApiException(e.getMessage(), e); - } catch (final IOException e) { - throw new ApiConnectionException(e.getMessage(), e); - } - } - - /** - * Converts a JSON InputStream into a AccountConfig object using the provided - * ObjectMapper. - * - * @param json Raw JSON InputStream - * @param objectMapper Jackson ObjectMapper - * @return AccountConfig object represented by the provided JSON - */ - public static AccountConfig fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { - // Convert all checked exceptions to Runtime - try { - return objectMapper.readValue(json, AccountConfig.class); - } catch (final JsonMappingException | JsonParseException e) { - throw new ApiException(e.getMessage(), e); - } catch (final IOException e) { - throw new ApiConnectionException(e.getMessage(), e); - } - } - - private final String key; - private final ZonedDateTime dateUpdated; - private final String value; - private final URI url; - - @JsonCreator - private AccountConfig( - @JsonProperty("key") final String key, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("value") final String value, - @JsonProperty("url") final URI url - ) { - this.key = key; - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); - this.value = value; - this.url = url; - } - - public final String getKey() { - return this.key; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final String getValue() { - return this.value; - } - - public final URI getUrl() { - return this.url; - } - - @Override - public boolean equals(final Object o) { - if (this == o) { - return true; - } - - if (o == null || getClass() != o.getClass()) { - return false; - } - - AccountConfig other = (AccountConfig) o; - - return ( - Objects.equals(key, other.key) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(value, other.value) && - Objects.equals(url, other.url) - ); - } - - @Override - public int hashCode() { - return Objects.hash(key, dateUpdated, value, url); - } -} diff --git a/src/main/java/com/twilio/rest/microvisor/v1/AccountConfigCreator.java b/src/main/java/com/twilio/rest/microvisor/v1/AccountConfigCreator.java deleted file mode 100644 index 7070bac8d9..0000000000 --- a/src/main/java/com/twilio/rest/microvisor/v1/AccountConfigCreator.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * This code was generated by - * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ - * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ - * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ - * - * Twilio - Microvisor - * This is the public Twilio REST API. - * - * NOTE: This class is auto generated by OpenAPI Generator. - * https://openapi-generator.tech - * Do not edit the class manually. - */ - -package com.twilio.rest.microvisor.v1; - -import com.twilio.base.Creator; -import com.twilio.constant.EnumConstants; -import com.twilio.exception.ApiConnectionException; -import com.twilio.exception.ApiException; -import com.twilio.exception.RestException; -import com.twilio.http.HttpMethod; -import com.twilio.http.Request; -import com.twilio.http.Response; -import com.twilio.http.TwilioRestClient; -import com.twilio.rest.Domains; - -public class AccountConfigCreator extends Creator { - - private String key; - private String value; - - public AccountConfigCreator(final String key, final String value) { - this.key = key; - this.value = value; - } - - public AccountConfigCreator setKey(final String key) { - this.key = key; - return this; - } - - public AccountConfigCreator setValue(final String value) { - this.value = value; - return this; - } - - @Override - public AccountConfig create(final TwilioRestClient client) { - String path = "/v1/Configs"; - - path = path.replace("{" + "Key" + "}", this.key.toString()); - path = path.replace("{" + "Value" + "}", this.value.toString()); - - Request request = new Request( - HttpMethod.POST, - Domains.MICROVISOR.toString(), - path - ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); - addPostParams(request); - Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "AccountConfig creation failed: Unable to connect to server" - ); - } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { - RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); - if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); - } - throw new ApiException(restException); - } - - return AccountConfig.fromJson( - response.getStream(), - client.getObjectMapper() - ); - } - - private void addPostParams(final Request request) { - if (key != null) { - request.addPostParam("Key", key); - } - if (value != null) { - request.addPostParam("Value", value); - } - } -} diff --git a/src/main/java/com/twilio/rest/microvisor/v1/AccountConfigFetcher.java b/src/main/java/com/twilio/rest/microvisor/v1/AccountConfigFetcher.java deleted file mode 100644 index 54949a068e..0000000000 --- a/src/main/java/com/twilio/rest/microvisor/v1/AccountConfigFetcher.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * This code was generated by - * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ - * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ - * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ - * - * Twilio - Microvisor - * This is the public Twilio REST API. - * - * NOTE: This class is auto generated by OpenAPI Generator. - * https://openapi-generator.tech - * Do not edit the class manually. - */ - -package com.twilio.rest.microvisor.v1; - -import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; -import com.twilio.exception.ApiConnectionException; -import com.twilio.exception.ApiException; -import com.twilio.exception.RestException; -import com.twilio.http.HttpMethod; -import com.twilio.http.Request; -import com.twilio.http.Response; -import com.twilio.http.TwilioRestClient; -import com.twilio.rest.Domains; - -public class AccountConfigFetcher extends Fetcher { - - private String pathKey; - - public AccountConfigFetcher(final String pathKey) { - this.pathKey = pathKey; - } - - @Override - public AccountConfig fetch(final TwilioRestClient client) { - String path = "/v1/Configs/{Key}"; - - path = path.replace("{" + "Key" + "}", this.pathKey.toString()); - - Request request = new Request( - HttpMethod.GET, - Domains.MICROVISOR.toString(), - path - ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); - Response response = client.request(request); - - if (response == null) { - throw new ApiConnectionException( - "AccountConfig fetch failed: Unable to connect to server" - ); - } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { - RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); - if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); - } - throw new ApiException(restException); - } - - return AccountConfig.fromJson( - response.getStream(), - client.getObjectMapper() - ); - } -} diff --git a/src/main/java/com/twilio/rest/microvisor/v1/AccountConfigReader.java b/src/main/java/com/twilio/rest/microvisor/v1/AccountConfigReader.java deleted file mode 100644 index 5e68b1b2bd..0000000000 --- a/src/main/java/com/twilio/rest/microvisor/v1/AccountConfigReader.java +++ /dev/null @@ -1,135 +0,0 @@ -/* - * This code was generated by - * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ - * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ - * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ - * - * Twilio - Microvisor - * This is the public Twilio REST API. - * - * NOTE: This class is auto generated by OpenAPI Generator. - * https://openapi-generator.tech - * Do not edit the class manually. - */ - -package com.twilio.rest.microvisor.v1; - -import com.twilio.base.Page; -import com.twilio.base.Reader; -import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; -import com.twilio.exception.ApiConnectionException; -import com.twilio.exception.ApiException; -import com.twilio.exception.RestException; -import com.twilio.http.HttpMethod; -import com.twilio.http.Request; -import com.twilio.http.Response; -import com.twilio.http.TwilioRestClient; -import com.twilio.rest.Domains; - -public class AccountConfigReader extends Reader { - - private Long pageSize; - - public AccountConfigReader() {} - - public AccountConfigReader setPageSize(final Long pageSize) { - this.pageSize = pageSize; - return this; - } - - @Override - public ResourceSet read(final TwilioRestClient client) { - return new ResourceSet<>(this, client, firstPage(client)); - } - - public Page firstPage(final TwilioRestClient client) { - String path = "/v1/Configs"; - - Request request = new Request( - HttpMethod.GET, - Domains.MICROVISOR.toString(), - path - ); - - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); - return pageForRequest(client, request); - } - - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { - Response response = client.request(request); - - if (response == null) { - throw new ApiConnectionException( - "AccountConfig read failed: Unable to connect to server" - ); - } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { - RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); - if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); - } - throw new ApiException(restException); - } - - return Page.fromJson( - "configs", - response.getContent(), - AccountConfig.class, - client.getObjectMapper() - ); - } - - @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.MICROVISOR.toString()) - ); - return pageForRequest(client, request); - } - - @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.MICROVISOR.toString()) - ); - return pageForRequest(client, request); - } - - @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { - Request request = new Request(HttpMethod.GET, targetUrl); - - return pageForRequest(client, request); - } - - private void addQueryParams(final Request request) { - if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); - } - - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } - } -} diff --git a/src/main/java/com/twilio/rest/microvisor/v1/AccountSecret.java b/src/main/java/com/twilio/rest/microvisor/v1/AccountSecret.java deleted file mode 100644 index 65fab57e56..0000000000 --- a/src/main/java/com/twilio/rest/microvisor/v1/AccountSecret.java +++ /dev/null @@ -1,160 +0,0 @@ -/* - * This code was generated by - * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ - * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ - * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ - * - * Twilio - Microvisor - * This is the public Twilio REST API. - * - * NOTE: This class is auto generated by OpenAPI Generator. - * https://openapi-generator.tech - * Do not edit the class manually. - */ - -package com.twilio.rest.microvisor.v1; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.core.JsonParseException; -import com.fasterxml.jackson.databind.JsonMappingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; -import com.twilio.exception.ApiConnectionException; -import com.twilio.exception.ApiException; -import java.io.IOException; -import java.io.InputStream; -import java.net.URI; -import java.time.ZonedDateTime; -import java.util.Objects; -import lombok.ToString; -import lombok.ToString; - -@JsonIgnoreProperties(ignoreUnknown = true) -@ToString -public class AccountSecret extends Resource { - - private static final long serialVersionUID = 245444757442788L; - - public static AccountSecretCreator creator( - final String key, - final String value - ) { - return new AccountSecretCreator(key, value); - } - - public static AccountSecretDeleter deleter(final String pathKey) { - return new AccountSecretDeleter(pathKey); - } - - public static AccountSecretFetcher fetcher(final String pathKey) { - return new AccountSecretFetcher(pathKey); - } - - public static AccountSecretReader reader() { - return new AccountSecretReader(); - } - - public static AccountSecretUpdater updater( - final String pathKey, - final String value - ) { - return new AccountSecretUpdater(pathKey, value); - } - - /** - * Converts a JSON String into a AccountSecret object using the provided ObjectMapper. - * - * @param json Raw JSON String - * @param objectMapper Jackson ObjectMapper - * @return AccountSecret object represented by the provided JSON - */ - public static AccountSecret fromJson( - final String json, - final ObjectMapper objectMapper - ) { - // Convert all checked exceptions to Runtime - try { - return objectMapper.readValue(json, AccountSecret.class); - } catch (final JsonMappingException | JsonParseException e) { - throw new ApiException(e.getMessage(), e); - } catch (final IOException e) { - throw new ApiConnectionException(e.getMessage(), e); - } - } - - /** - * Converts a JSON InputStream into a AccountSecret object using the provided - * ObjectMapper. - * - * @param json Raw JSON InputStream - * @param objectMapper Jackson ObjectMapper - * @return AccountSecret object represented by the provided JSON - */ - public static AccountSecret fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { - // Convert all checked exceptions to Runtime - try { - return objectMapper.readValue(json, AccountSecret.class); - } catch (final JsonMappingException | JsonParseException e) { - throw new ApiException(e.getMessage(), e); - } catch (final IOException e) { - throw new ApiConnectionException(e.getMessage(), e); - } - } - - private final String key; - private final ZonedDateTime dateRotated; - private final URI url; - - @JsonCreator - private AccountSecret( - @JsonProperty("key") final String key, - @JsonProperty("date_rotated") final String dateRotated, - @JsonProperty("url") final URI url - ) { - this.key = key; - this.dateRotated = DateConverter.iso8601DateTimeFromString(dateRotated); - this.url = url; - } - - public final String getKey() { - return this.key; - } - - public final ZonedDateTime getDateRotated() { - return this.dateRotated; - } - - public final URI getUrl() { - return this.url; - } - - @Override - public boolean equals(final Object o) { - if (this == o) { - return true; - } - - if (o == null || getClass() != o.getClass()) { - return false; - } - - AccountSecret other = (AccountSecret) o; - - return ( - Objects.equals(key, other.key) && - Objects.equals(dateRotated, other.dateRotated) && - Objects.equals(url, other.url) - ); - } - - @Override - public int hashCode() { - return Objects.hash(key, dateRotated, url); - } -} diff --git a/src/main/java/com/twilio/rest/microvisor/v1/AccountSecretCreator.java b/src/main/java/com/twilio/rest/microvisor/v1/AccountSecretCreator.java deleted file mode 100644 index 2652846681..0000000000 --- a/src/main/java/com/twilio/rest/microvisor/v1/AccountSecretCreator.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * This code was generated by - * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ - * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ - * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ - * - * Twilio - Microvisor - * This is the public Twilio REST API. - * - * NOTE: This class is auto generated by OpenAPI Generator. - * https://openapi-generator.tech - * Do not edit the class manually. - */ - -package com.twilio.rest.microvisor.v1; - -import com.twilio.base.Creator; -import com.twilio.constant.EnumConstants; -import com.twilio.exception.ApiConnectionException; -import com.twilio.exception.ApiException; -import com.twilio.exception.RestException; -import com.twilio.http.HttpMethod; -import com.twilio.http.Request; -import com.twilio.http.Response; -import com.twilio.http.TwilioRestClient; -import com.twilio.rest.Domains; - -public class AccountSecretCreator extends Creator { - - private String key; - private String value; - - public AccountSecretCreator(final String key, final String value) { - this.key = key; - this.value = value; - } - - public AccountSecretCreator setKey(final String key) { - this.key = key; - return this; - } - - public AccountSecretCreator setValue(final String value) { - this.value = value; - return this; - } - - @Override - public AccountSecret create(final TwilioRestClient client) { - String path = "/v1/Secrets"; - - path = path.replace("{" + "Key" + "}", this.key.toString()); - path = path.replace("{" + "Value" + "}", this.value.toString()); - - Request request = new Request( - HttpMethod.POST, - Domains.MICROVISOR.toString(), - path - ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); - addPostParams(request); - Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "AccountSecret creation failed: Unable to connect to server" - ); - } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { - RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); - if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); - } - throw new ApiException(restException); - } - - return AccountSecret.fromJson( - response.getStream(), - client.getObjectMapper() - ); - } - - private void addPostParams(final Request request) { - if (key != null) { - request.addPostParam("Key", key); - } - if (value != null) { - request.addPostParam("Value", value); - } - } -} diff --git a/src/main/java/com/twilio/rest/microvisor/v1/AccountSecretDeleter.java b/src/main/java/com/twilio/rest/microvisor/v1/AccountSecretDeleter.java deleted file mode 100644 index c427b71904..0000000000 --- a/src/main/java/com/twilio/rest/microvisor/v1/AccountSecretDeleter.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * This code was generated by - * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ - * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ - * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ - * - * Twilio - Microvisor - * This is the public Twilio REST API. - * - * NOTE: This class is auto generated by OpenAPI Generator. - * https://openapi-generator.tech - * Do not edit the class manually. - */ - -package com.twilio.rest.microvisor.v1; - -import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; -import com.twilio.exception.ApiConnectionException; -import com.twilio.exception.ApiException; -import com.twilio.exception.RestException; -import com.twilio.http.HttpMethod; -import com.twilio.http.Request; -import com.twilio.http.Response; -import com.twilio.http.TwilioRestClient; -import com.twilio.rest.Domains; - -public class AccountSecretDeleter extends Deleter { - - private String pathKey; - - public AccountSecretDeleter(final String pathKey) { - this.pathKey = pathKey; - } - - @Override - public boolean delete(final TwilioRestClient client) { - String path = "/v1/Secrets/{Key}"; - - path = path.replace("{" + "Key" + "}", this.pathKey.toString()); - - Request request = new Request( - HttpMethod.DELETE, - Domains.MICROVISOR.toString(), - path - ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); - Response response = client.request(request); - - if (response == null) { - throw new ApiConnectionException( - "AccountSecret delete failed: Unable to connect to server" - ); - } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { - RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); - if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); - } - throw new ApiException(restException); - } - return response.getStatusCode() == 204; - } -} diff --git a/src/main/java/com/twilio/rest/microvisor/v1/AccountSecretReader.java b/src/main/java/com/twilio/rest/microvisor/v1/AccountSecretReader.java deleted file mode 100644 index eeeccfb5f1..0000000000 --- a/src/main/java/com/twilio/rest/microvisor/v1/AccountSecretReader.java +++ /dev/null @@ -1,135 +0,0 @@ -/* - * This code was generated by - * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ - * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ - * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ - * - * Twilio - Microvisor - * This is the public Twilio REST API. - * - * NOTE: This class is auto generated by OpenAPI Generator. - * https://openapi-generator.tech - * Do not edit the class manually. - */ - -package com.twilio.rest.microvisor.v1; - -import com.twilio.base.Page; -import com.twilio.base.Reader; -import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; -import com.twilio.exception.ApiConnectionException; -import com.twilio.exception.ApiException; -import com.twilio.exception.RestException; -import com.twilio.http.HttpMethod; -import com.twilio.http.Request; -import com.twilio.http.Response; -import com.twilio.http.TwilioRestClient; -import com.twilio.rest.Domains; - -public class AccountSecretReader extends Reader { - - private Long pageSize; - - public AccountSecretReader() {} - - public AccountSecretReader setPageSize(final Long pageSize) { - this.pageSize = pageSize; - return this; - } - - @Override - public ResourceSet read(final TwilioRestClient client) { - return new ResourceSet<>(this, client, firstPage(client)); - } - - public Page firstPage(final TwilioRestClient client) { - String path = "/v1/Secrets"; - - Request request = new Request( - HttpMethod.GET, - Domains.MICROVISOR.toString(), - path - ); - - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); - return pageForRequest(client, request); - } - - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { - Response response = client.request(request); - - if (response == null) { - throw new ApiConnectionException( - "AccountSecret read failed: Unable to connect to server" - ); - } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { - RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); - if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); - } - throw new ApiException(restException); - } - - return Page.fromJson( - "secrets", - response.getContent(), - AccountSecret.class, - client.getObjectMapper() - ); - } - - @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.MICROVISOR.toString()) - ); - return pageForRequest(client, request); - } - - @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.MICROVISOR.toString()) - ); - return pageForRequest(client, request); - } - - @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { - Request request = new Request(HttpMethod.GET, targetUrl); - - return pageForRequest(client, request); - } - - private void addQueryParams(final Request request) { - if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); - } - - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } - } -} diff --git a/src/main/java/com/twilio/rest/microvisor/v1/App.java b/src/main/java/com/twilio/rest/microvisor/v1/App.java deleted file mode 100644 index 23827af572..0000000000 --- a/src/main/java/com/twilio/rest/microvisor/v1/App.java +++ /dev/null @@ -1,197 +0,0 @@ -/* - * This code was generated by - * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ - * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ - * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ - * - * Twilio - Microvisor - * This is the public Twilio REST API. - * - * NOTE: This class is auto generated by OpenAPI Generator. - * https://openapi-generator.tech - * Do not edit the class manually. - */ - -package com.twilio.rest.microvisor.v1; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.core.JsonParseException; -import com.fasterxml.jackson.databind.JsonMappingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; -import com.twilio.exception.ApiConnectionException; -import com.twilio.exception.ApiException; -import java.io.IOException; -import java.io.InputStream; -import java.net.URI; -import java.time.ZonedDateTime; -import java.util.Map; -import java.util.Map; -import java.util.Objects; -import lombok.ToString; -import lombok.ToString; - -@JsonIgnoreProperties(ignoreUnknown = true) -@ToString -public class App extends Resource { - - private static final long serialVersionUID = 223120562272974L; - - public static AppDeleter deleter(final String pathSid) { - return new AppDeleter(pathSid); - } - - public static AppFetcher fetcher(final String pathSid) { - return new AppFetcher(pathSid); - } - - public static AppReader reader() { - return new AppReader(); - } - - /** - * Converts a JSON String into a App object using the provided ObjectMapper. - * - * @param json Raw JSON String - * @param objectMapper Jackson ObjectMapper - * @return App object represented by the provided JSON - */ - public static App fromJson( - final String json, - final ObjectMapper objectMapper - ) { - // Convert all checked exceptions to Runtime - try { - return objectMapper.readValue(json, App.class); - } catch (final JsonMappingException | JsonParseException e) { - throw new ApiException(e.getMessage(), e); - } catch (final IOException e) { - throw new ApiConnectionException(e.getMessage(), e); - } - } - - /** - * Converts a JSON InputStream into a App object using the provided - * ObjectMapper. - * - * @param json Raw JSON InputStream - * @param objectMapper Jackson ObjectMapper - * @return App object represented by the provided JSON - */ - public static App fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { - // Convert all checked exceptions to Runtime - try { - return objectMapper.readValue(json, App.class); - } catch (final JsonMappingException | JsonParseException e) { - throw new ApiException(e.getMessage(), e); - } catch (final IOException e) { - throw new ApiConnectionException(e.getMessage(), e); - } - } - - private final String sid; - private final String accountSid; - private final String hash; - private final String uniqueName; - private final ZonedDateTime dateCreated; - private final ZonedDateTime dateUpdated; - private final URI url; - private final Map links; - - @JsonCreator - private App( - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("hash") final String hash, - @JsonProperty("unique_name") final String uniqueName, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("url") final URI url, - @JsonProperty("links") final Map links - ) { - this.sid = sid; - this.accountSid = accountSid; - this.hash = hash; - this.uniqueName = uniqueName; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); - this.url = url; - this.links = links; - } - - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getHash() { - return this.hash; - } - - public final String getUniqueName() { - return this.uniqueName; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final URI getUrl() { - return this.url; - } - - public final Map getLinks() { - return this.links; - } - - @Override - public boolean equals(final Object o) { - if (this == o) { - return true; - } - - if (o == null || getClass() != o.getClass()) { - return false; - } - - App other = (App) o; - - return ( - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(hash, other.hash) && - Objects.equals(uniqueName, other.uniqueName) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(url, other.url) && - Objects.equals(links, other.links) - ); - } - - @Override - public int hashCode() { - return Objects.hash( - sid, - accountSid, - hash, - uniqueName, - dateCreated, - dateUpdated, - url, - links - ); - } -} diff --git a/src/main/java/com/twilio/rest/microvisor/v1/AppDeleter.java b/src/main/java/com/twilio/rest/microvisor/v1/AppDeleter.java deleted file mode 100644 index ee834cbce9..0000000000 --- a/src/main/java/com/twilio/rest/microvisor/v1/AppDeleter.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * This code was generated by - * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ - * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ - * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ - * - * Twilio - Microvisor - * This is the public Twilio REST API. - * - * NOTE: This class is auto generated by OpenAPI Generator. - * https://openapi-generator.tech - * Do not edit the class manually. - */ - -package com.twilio.rest.microvisor.v1; - -import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; -import com.twilio.exception.ApiConnectionException; -import com.twilio.exception.ApiException; -import com.twilio.exception.RestException; -import com.twilio.http.HttpMethod; -import com.twilio.http.Request; -import com.twilio.http.Response; -import com.twilio.http.TwilioRestClient; -import com.twilio.rest.Domains; - -public class AppDeleter extends Deleter { - - private String pathSid; - - public AppDeleter(final String pathSid) { - this.pathSid = pathSid; - } - - @Override - public boolean delete(final TwilioRestClient client) { - String path = "/v1/Apps/{Sid}"; - - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); - - Request request = new Request( - HttpMethod.DELETE, - Domains.MICROVISOR.toString(), - path - ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); - Response response = client.request(request); - - if (response == null) { - throw new ApiConnectionException( - "App delete failed: Unable to connect to server" - ); - } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { - RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); - if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); - } - throw new ApiException(restException); - } - return response.getStatusCode() == 204; - } -} diff --git a/src/main/java/com/twilio/rest/microvisor/v1/AppFetcher.java b/src/main/java/com/twilio/rest/microvisor/v1/AppFetcher.java deleted file mode 100644 index e5f7fb789a..0000000000 --- a/src/main/java/com/twilio/rest/microvisor/v1/AppFetcher.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * This code was generated by - * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ - * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ - * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ - * - * Twilio - Microvisor - * This is the public Twilio REST API. - * - * NOTE: This class is auto generated by OpenAPI Generator. - * https://openapi-generator.tech - * Do not edit the class manually. - */ - -package com.twilio.rest.microvisor.v1; - -import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; -import com.twilio.exception.ApiConnectionException; -import com.twilio.exception.ApiException; -import com.twilio.exception.RestException; -import com.twilio.http.HttpMethod; -import com.twilio.http.Request; -import com.twilio.http.Response; -import com.twilio.http.TwilioRestClient; -import com.twilio.rest.Domains; - -public class AppFetcher extends Fetcher { - - private String pathSid; - - public AppFetcher(final String pathSid) { - this.pathSid = pathSid; - } - - @Override - public App fetch(final TwilioRestClient client) { - String path = "/v1/Apps/{Sid}"; - - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); - - Request request = new Request( - HttpMethod.GET, - Domains.MICROVISOR.toString(), - path - ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); - Response response = client.request(request); - - if (response == null) { - throw new ApiConnectionException( - "App fetch failed: Unable to connect to server" - ); - } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { - RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); - if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); - } - throw new ApiException(restException); - } - - return App.fromJson(response.getStream(), client.getObjectMapper()); - } -} diff --git a/src/main/java/com/twilio/rest/microvisor/v1/AppReader.java b/src/main/java/com/twilio/rest/microvisor/v1/AppReader.java deleted file mode 100644 index 2c0d0efdf5..0000000000 --- a/src/main/java/com/twilio/rest/microvisor/v1/AppReader.java +++ /dev/null @@ -1,135 +0,0 @@ -/* - * This code was generated by - * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ - * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ - * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ - * - * Twilio - Microvisor - * This is the public Twilio REST API. - * - * NOTE: This class is auto generated by OpenAPI Generator. - * https://openapi-generator.tech - * Do not edit the class manually. - */ - -package com.twilio.rest.microvisor.v1; - -import com.twilio.base.Page; -import com.twilio.base.Reader; -import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; -import com.twilio.exception.ApiConnectionException; -import com.twilio.exception.ApiException; -import com.twilio.exception.RestException; -import com.twilio.http.HttpMethod; -import com.twilio.http.Request; -import com.twilio.http.Response; -import com.twilio.http.TwilioRestClient; -import com.twilio.rest.Domains; - -public class AppReader extends Reader { - - private Long pageSize; - - public AppReader() {} - - public AppReader setPageSize(final Long pageSize) { - this.pageSize = pageSize; - return this; - } - - @Override - public ResourceSet read(final TwilioRestClient client) { - return new ResourceSet<>(this, client, firstPage(client)); - } - - public Page firstPage(final TwilioRestClient client) { - String path = "/v1/Apps"; - - Request request = new Request( - HttpMethod.GET, - Domains.MICROVISOR.toString(), - path - ); - - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); - return pageForRequest(client, request); - } - - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { - Response response = client.request(request); - - if (response == null) { - throw new ApiConnectionException( - "App read failed: Unable to connect to server" - ); - } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { - RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); - if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); - } - throw new ApiException(restException); - } - - return Page.fromJson( - "apps", - response.getContent(), - App.class, - client.getObjectMapper() - ); - } - - @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.MICROVISOR.toString()) - ); - return pageForRequest(client, request); - } - - @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.MICROVISOR.toString()) - ); - return pageForRequest(client, request); - } - - @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { - Request request = new Request(HttpMethod.GET, targetUrl); - - return pageForRequest(client, request); - } - - private void addQueryParams(final Request request) { - if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); - } - - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } - } -} diff --git a/src/main/java/com/twilio/rest/microvisor/v1/Device.java b/src/main/java/com/twilio/rest/microvisor/v1/Device.java deleted file mode 100644 index 6775341645..0000000000 --- a/src/main/java/com/twilio/rest/microvisor/v1/Device.java +++ /dev/null @@ -1,206 +0,0 @@ -/* - * This code was generated by - * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ - * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ - * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ - * - * Twilio - Microvisor - * This is the public Twilio REST API. - * - * NOTE: This class is auto generated by OpenAPI Generator. - * https://openapi-generator.tech - * Do not edit the class manually. - */ - -package com.twilio.rest.microvisor.v1; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.core.JsonParseException; -import com.fasterxml.jackson.databind.JsonMappingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; -import com.twilio.exception.ApiConnectionException; -import com.twilio.exception.ApiException; -import java.io.IOException; -import java.io.InputStream; -import java.net.URI; -import java.time.ZonedDateTime; -import java.util.Map; -import java.util.Map; -import java.util.Objects; -import lombok.ToString; -import lombok.ToString; - -@JsonIgnoreProperties(ignoreUnknown = true) -@ToString -public class Device extends Resource { - - private static final long serialVersionUID = 266652017538801L; - - public static DeviceFetcher fetcher(final String pathSid) { - return new DeviceFetcher(pathSid); - } - - public static DeviceReader reader() { - return new DeviceReader(); - } - - public static DeviceUpdater updater(final String pathSid) { - return new DeviceUpdater(pathSid); - } - - /** - * Converts a JSON String into a Device object using the provided ObjectMapper. - * - * @param json Raw JSON String - * @param objectMapper Jackson ObjectMapper - * @return Device object represented by the provided JSON - */ - public static Device fromJson( - final String json, - final ObjectMapper objectMapper - ) { - // Convert all checked exceptions to Runtime - try { - return objectMapper.readValue(json, Device.class); - } catch (final JsonMappingException | JsonParseException e) { - throw new ApiException(e.getMessage(), e); - } catch (final IOException e) { - throw new ApiConnectionException(e.getMessage(), e); - } - } - - /** - * Converts a JSON InputStream into a Device object using the provided - * ObjectMapper. - * - * @param json Raw JSON InputStream - * @param objectMapper Jackson ObjectMapper - * @return Device object represented by the provided JSON - */ - public static Device fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { - // Convert all checked exceptions to Runtime - try { - return objectMapper.readValue(json, Device.class); - } catch (final JsonMappingException | JsonParseException e) { - throw new ApiException(e.getMessage(), e); - } catch (final IOException e) { - throw new ApiConnectionException(e.getMessage(), e); - } - } - - private final String sid; - private final String uniqueName; - private final String accountSid; - private final Map app; - private final Map logging; - private final ZonedDateTime dateCreated; - private final ZonedDateTime dateUpdated; - private final URI url; - private final Map links; - - @JsonCreator - private Device( - @JsonProperty("sid") final String sid, - @JsonProperty("unique_name") final String uniqueName, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("app") final Map app, - @JsonProperty("logging") final Map logging, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("url") final URI url, - @JsonProperty("links") final Map links - ) { - this.sid = sid; - this.uniqueName = uniqueName; - this.accountSid = accountSid; - this.app = app; - this.logging = logging; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); - this.url = url; - this.links = links; - } - - public final String getSid() { - return this.sid; - } - - public final String getUniqueName() { - return this.uniqueName; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final Map getApp() { - return this.app; - } - - public final Map getLogging() { - return this.logging; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final URI getUrl() { - return this.url; - } - - public final Map getLinks() { - return this.links; - } - - @Override - public boolean equals(final Object o) { - if (this == o) { - return true; - } - - if (o == null || getClass() != o.getClass()) { - return false; - } - - Device other = (Device) o; - - return ( - Objects.equals(sid, other.sid) && - Objects.equals(uniqueName, other.uniqueName) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(app, other.app) && - Objects.equals(logging, other.logging) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(url, other.url) && - Objects.equals(links, other.links) - ); - } - - @Override - public int hashCode() { - return Objects.hash( - sid, - uniqueName, - accountSid, - app, - logging, - dateCreated, - dateUpdated, - url, - links - ); - } -} diff --git a/src/main/java/com/twilio/rest/microvisor/v1/DeviceUpdater.java b/src/main/java/com/twilio/rest/microvisor/v1/DeviceUpdater.java deleted file mode 100644 index 4c451aa3c0..0000000000 --- a/src/main/java/com/twilio/rest/microvisor/v1/DeviceUpdater.java +++ /dev/null @@ -1,109 +0,0 @@ -/* - * This code was generated by - * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ - * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ - * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ - * - * Twilio - Microvisor - * This is the public Twilio REST API. - * - * NOTE: This class is auto generated by OpenAPI Generator. - * https://openapi-generator.tech - * Do not edit the class manually. - */ - -package com.twilio.rest.microvisor.v1; - -import com.twilio.base.Updater; -import com.twilio.constant.EnumConstants; -import com.twilio.exception.ApiConnectionException; -import com.twilio.exception.ApiException; -import com.twilio.exception.RestException; -import com.twilio.http.HttpMethod; -import com.twilio.http.Request; -import com.twilio.http.Response; -import com.twilio.http.TwilioRestClient; -import com.twilio.rest.Domains; - -public class DeviceUpdater extends Updater { - - private String pathSid; - private String uniqueName; - private String targetApp; - private Boolean loggingEnabled; - private Boolean restartApp; - - public DeviceUpdater(final String pathSid) { - this.pathSid = pathSid; - } - - public DeviceUpdater setUniqueName(final String uniqueName) { - this.uniqueName = uniqueName; - return this; - } - - public DeviceUpdater setTargetApp(final String targetApp) { - this.targetApp = targetApp; - return this; - } - - public DeviceUpdater setLoggingEnabled(final Boolean loggingEnabled) { - this.loggingEnabled = loggingEnabled; - return this; - } - - public DeviceUpdater setRestartApp(final Boolean restartApp) { - this.restartApp = restartApp; - return this; - } - - @Override - public Device update(final TwilioRestClient client) { - String path = "/v1/Devices/{Sid}"; - - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); - - Request request = new Request( - HttpMethod.POST, - Domains.MICROVISOR.toString(), - path - ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); - addPostParams(request); - Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Device update failed: Unable to connect to server" - ); - } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { - RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); - if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); - } - throw new ApiException(restException); - } - - return Device.fromJson(response.getStream(), client.getObjectMapper()); - } - - private void addPostParams(final Request request) { - if (uniqueName != null) { - request.addPostParam("UniqueName", uniqueName); - } - if (targetApp != null) { - request.addPostParam("TargetApp", targetApp); - } - if (loggingEnabled != null) { - request.addPostParam("LoggingEnabled", loggingEnabled.toString()); - } - if (restartApp != null) { - request.addPostParam("RestartApp", restartApp.toString()); - } - } -} diff --git a/src/main/java/com/twilio/rest/microvisor/v1/app/AppManifestFetcher.java b/src/main/java/com/twilio/rest/microvisor/v1/app/AppManifestFetcher.java deleted file mode 100644 index 296b8d3a0a..0000000000 --- a/src/main/java/com/twilio/rest/microvisor/v1/app/AppManifestFetcher.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * This code was generated by - * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ - * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ - * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ - * - * Twilio - Microvisor - * This is the public Twilio REST API. - * - * NOTE: This class is auto generated by OpenAPI Generator. - * https://openapi-generator.tech - * Do not edit the class manually. - */ - -package com.twilio.rest.microvisor.v1.app; - -import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; -import com.twilio.exception.ApiConnectionException; -import com.twilio.exception.ApiException; -import com.twilio.exception.RestException; -import com.twilio.http.HttpMethod; -import com.twilio.http.Request; -import com.twilio.http.Response; -import com.twilio.http.TwilioRestClient; -import com.twilio.rest.Domains; - -public class AppManifestFetcher extends Fetcher { - - private String pathAppSid; - - public AppManifestFetcher(final String pathAppSid) { - this.pathAppSid = pathAppSid; - } - - @Override - public AppManifest fetch(final TwilioRestClient client) { - String path = "/v1/Apps/{AppSid}/Manifest"; - - path = path.replace("{" + "AppSid" + "}", this.pathAppSid.toString()); - - Request request = new Request( - HttpMethod.GET, - Domains.MICROVISOR.toString(), - path - ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); - Response response = client.request(request); - - if (response == null) { - throw new ApiConnectionException( - "AppManifest fetch failed: Unable to connect to server" - ); - } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { - RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); - if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); - } - throw new ApiException(restException); - } - - return AppManifest.fromJson( - response.getStream(), - client.getObjectMapper() - ); - } -} diff --git a/src/main/java/com/twilio/rest/microvisor/v1/device/DeviceConfig.java b/src/main/java/com/twilio/rest/microvisor/v1/device/DeviceConfig.java deleted file mode 100644 index 3574a6e773..0000000000 --- a/src/main/java/com/twilio/rest/microvisor/v1/device/DeviceConfig.java +++ /dev/null @@ -1,184 +0,0 @@ -/* - * This code was generated by - * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ - * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ - * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ - * - * Twilio - Microvisor - * This is the public Twilio REST API. - * - * NOTE: This class is auto generated by OpenAPI Generator. - * https://openapi-generator.tech - * Do not edit the class manually. - */ - -package com.twilio.rest.microvisor.v1.device; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.core.JsonParseException; -import com.fasterxml.jackson.databind.JsonMappingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; -import com.twilio.exception.ApiConnectionException; -import com.twilio.exception.ApiException; -import java.io.IOException; -import java.io.InputStream; -import java.net.URI; -import java.time.ZonedDateTime; -import java.util.Objects; -import lombok.ToString; -import lombok.ToString; - -@JsonIgnoreProperties(ignoreUnknown = true) -@ToString -public class DeviceConfig extends Resource { - - private static final long serialVersionUID = 4121523224128L; - - public static DeviceConfigCreator creator( - final String pathDeviceSid, - final String key, - final String value - ) { - return new DeviceConfigCreator(pathDeviceSid, key, value); - } - - public static DeviceConfigDeleter deleter( - final String pathDeviceSid, - final String pathKey - ) { - return new DeviceConfigDeleter(pathDeviceSid, pathKey); - } - - public static DeviceConfigFetcher fetcher( - final String pathDeviceSid, - final String pathKey - ) { - return new DeviceConfigFetcher(pathDeviceSid, pathKey); - } - - public static DeviceConfigReader reader(final String pathDeviceSid) { - return new DeviceConfigReader(pathDeviceSid); - } - - public static DeviceConfigUpdater updater( - final String pathDeviceSid, - final String pathKey, - final String value - ) { - return new DeviceConfigUpdater(pathDeviceSid, pathKey, value); - } - - /** - * Converts a JSON String into a DeviceConfig object using the provided ObjectMapper. - * - * @param json Raw JSON String - * @param objectMapper Jackson ObjectMapper - * @return DeviceConfig object represented by the provided JSON - */ - public static DeviceConfig fromJson( - final String json, - final ObjectMapper objectMapper - ) { - // Convert all checked exceptions to Runtime - try { - return objectMapper.readValue(json, DeviceConfig.class); - } catch (final JsonMappingException | JsonParseException e) { - throw new ApiException(e.getMessage(), e); - } catch (final IOException e) { - throw new ApiConnectionException(e.getMessage(), e); - } - } - - /** - * Converts a JSON InputStream into a DeviceConfig object using the provided - * ObjectMapper. - * - * @param json Raw JSON InputStream - * @param objectMapper Jackson ObjectMapper - * @return DeviceConfig object represented by the provided JSON - */ - public static DeviceConfig fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { - // Convert all checked exceptions to Runtime - try { - return objectMapper.readValue(json, DeviceConfig.class); - } catch (final JsonMappingException | JsonParseException e) { - throw new ApiException(e.getMessage(), e); - } catch (final IOException e) { - throw new ApiConnectionException(e.getMessage(), e); - } - } - - private final String deviceSid; - private final String key; - private final String value; - private final ZonedDateTime dateUpdated; - private final URI url; - - @JsonCreator - private DeviceConfig( - @JsonProperty("device_sid") final String deviceSid, - @JsonProperty("key") final String key, - @JsonProperty("value") final String value, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("url") final URI url - ) { - this.deviceSid = deviceSid; - this.key = key; - this.value = value; - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); - this.url = url; - } - - public final String getDeviceSid() { - return this.deviceSid; - } - - public final String getKey() { - return this.key; - } - - public final String getValue() { - return this.value; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final URI getUrl() { - return this.url; - } - - @Override - public boolean equals(final Object o) { - if (this == o) { - return true; - } - - if (o == null || getClass() != o.getClass()) { - return false; - } - - DeviceConfig other = (DeviceConfig) o; - - return ( - Objects.equals(deviceSid, other.deviceSid) && - Objects.equals(key, other.key) && - Objects.equals(value, other.value) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(url, other.url) - ); - } - - @Override - public int hashCode() { - return Objects.hash(deviceSid, key, value, dateUpdated, url); - } -} diff --git a/src/main/java/com/twilio/rest/microvisor/v1/device/DeviceConfigCreator.java b/src/main/java/com/twilio/rest/microvisor/v1/device/DeviceConfigCreator.java deleted file mode 100644 index badaac3ead..0000000000 --- a/src/main/java/com/twilio/rest/microvisor/v1/device/DeviceConfigCreator.java +++ /dev/null @@ -1,106 +0,0 @@ -/* - * This code was generated by - * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ - * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ - * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ - * - * Twilio - Microvisor - * This is the public Twilio REST API. - * - * NOTE: This class is auto generated by OpenAPI Generator. - * https://openapi-generator.tech - * Do not edit the class manually. - */ - -package com.twilio.rest.microvisor.v1.device; - -import com.twilio.base.Creator; -import com.twilio.constant.EnumConstants; -import com.twilio.exception.ApiConnectionException; -import com.twilio.exception.ApiException; -import com.twilio.exception.RestException; -import com.twilio.http.HttpMethod; -import com.twilio.http.Request; -import com.twilio.http.Response; -import com.twilio.http.TwilioRestClient; -import com.twilio.rest.Domains; - -public class DeviceConfigCreator extends Creator { - - private String pathDeviceSid; - private String key; - private String value; - - public DeviceConfigCreator( - final String pathDeviceSid, - final String key, - final String value - ) { - this.pathDeviceSid = pathDeviceSid; - this.key = key; - this.value = value; - } - - public DeviceConfigCreator setKey(final String key) { - this.key = key; - return this; - } - - public DeviceConfigCreator setValue(final String value) { - this.value = value; - return this; - } - - @Override - public DeviceConfig create(final TwilioRestClient client) { - String path = "/v1/Devices/{DeviceSid}/Configs"; - - path = - path.replace( - "{" + "DeviceSid" + "}", - this.pathDeviceSid.toString() - ); - path = path.replace("{" + "Key" + "}", this.key.toString()); - path = path.replace("{" + "Value" + "}", this.value.toString()); - - Request request = new Request( - HttpMethod.POST, - Domains.MICROVISOR.toString(), - path - ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); - addPostParams(request); - Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "DeviceConfig creation failed: Unable to connect to server" - ); - } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { - RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); - if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); - } - throw new ApiException(restException); - } - - return DeviceConfig.fromJson( - response.getStream(), - client.getObjectMapper() - ); - } - - private void addPostParams(final Request request) { - if (key != null) { - request.addPostParam("Key", key); - } - if (value != null) { - request.addPostParam("Value", value); - } - } -} diff --git a/src/main/java/com/twilio/rest/microvisor/v1/device/DeviceConfigReader.java b/src/main/java/com/twilio/rest/microvisor/v1/device/DeviceConfigReader.java deleted file mode 100644 index aa855c227d..0000000000 --- a/src/main/java/com/twilio/rest/microvisor/v1/device/DeviceConfigReader.java +++ /dev/null @@ -1,143 +0,0 @@ -/* - * This code was generated by - * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ - * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ - * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ - * - * Twilio - Microvisor - * This is the public Twilio REST API. - * - * NOTE: This class is auto generated by OpenAPI Generator. - * https://openapi-generator.tech - * Do not edit the class manually. - */ - -package com.twilio.rest.microvisor.v1.device; - -import com.twilio.base.Page; -import com.twilio.base.Reader; -import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; -import com.twilio.exception.ApiConnectionException; -import com.twilio.exception.ApiException; -import com.twilio.exception.RestException; -import com.twilio.http.HttpMethod; -import com.twilio.http.Request; -import com.twilio.http.Response; -import com.twilio.http.TwilioRestClient; -import com.twilio.rest.Domains; - -public class DeviceConfigReader extends Reader { - - private String pathDeviceSid; - private Long pageSize; - - public DeviceConfigReader(final String pathDeviceSid) { - this.pathDeviceSid = pathDeviceSid; - } - - public DeviceConfigReader setPageSize(final Long pageSize) { - this.pageSize = pageSize; - return this; - } - - @Override - public ResourceSet read(final TwilioRestClient client) { - return new ResourceSet<>(this, client, firstPage(client)); - } - - public Page firstPage(final TwilioRestClient client) { - String path = "/v1/Devices/{DeviceSid}/Configs"; - path = - path.replace( - "{" + "DeviceSid" + "}", - this.pathDeviceSid.toString() - ); - - Request request = new Request( - HttpMethod.GET, - Domains.MICROVISOR.toString(), - path - ); - - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); - return pageForRequest(client, request); - } - - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { - Response response = client.request(request); - - if (response == null) { - throw new ApiConnectionException( - "DeviceConfig read failed: Unable to connect to server" - ); - } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { - RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); - if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); - } - throw new ApiException(restException); - } - - return Page.fromJson( - "configs", - response.getContent(), - DeviceConfig.class, - client.getObjectMapper() - ); - } - - @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.MICROVISOR.toString()) - ); - return pageForRequest(client, request); - } - - @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.MICROVISOR.toString()) - ); - return pageForRequest(client, request); - } - - @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { - Request request = new Request(HttpMethod.GET, targetUrl); - - return pageForRequest(client, request); - } - - private void addQueryParams(final Request request) { - if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); - } - - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } - } -} diff --git a/src/main/java/com/twilio/rest/microvisor/v1/device/DeviceConfigUpdater.java b/src/main/java/com/twilio/rest/microvisor/v1/device/DeviceConfigUpdater.java deleted file mode 100644 index d2f55627e1..0000000000 --- a/src/main/java/com/twilio/rest/microvisor/v1/device/DeviceConfigUpdater.java +++ /dev/null @@ -1,98 +0,0 @@ -/* - * This code was generated by - * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ - * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ - * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ - * - * Twilio - Microvisor - * This is the public Twilio REST API. - * - * NOTE: This class is auto generated by OpenAPI Generator. - * https://openapi-generator.tech - * Do not edit the class manually. - */ - -package com.twilio.rest.microvisor.v1.device; - -import com.twilio.base.Updater; -import com.twilio.constant.EnumConstants; -import com.twilio.exception.ApiConnectionException; -import com.twilio.exception.ApiException; -import com.twilio.exception.RestException; -import com.twilio.http.HttpMethod; -import com.twilio.http.Request; -import com.twilio.http.Response; -import com.twilio.http.TwilioRestClient; -import com.twilio.rest.Domains; - -public class DeviceConfigUpdater extends Updater { - - private String pathDeviceSid; - private String pathKey; - private String value; - - public DeviceConfigUpdater( - final String pathDeviceSid, - final String pathKey, - final String value - ) { - this.pathDeviceSid = pathDeviceSid; - this.pathKey = pathKey; - this.value = value; - } - - public DeviceConfigUpdater setValue(final String value) { - this.value = value; - return this; - } - - @Override - public DeviceConfig update(final TwilioRestClient client) { - String path = "/v1/Devices/{DeviceSid}/Configs/{Key}"; - - path = - path.replace( - "{" + "DeviceSid" + "}", - this.pathDeviceSid.toString() - ); - path = path.replace("{" + "Key" + "}", this.pathKey.toString()); - path = path.replace("{" + "Value" + "}", this.value.toString()); - - Request request = new Request( - HttpMethod.POST, - Domains.MICROVISOR.toString(), - path - ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); - addPostParams(request); - Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "DeviceConfig update failed: Unable to connect to server" - ); - } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { - RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); - if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); - } - throw new ApiException(restException); - } - - return DeviceConfig.fromJson( - response.getStream(), - client.getObjectMapper() - ); - } - - private void addPostParams(final Request request) { - if (value != null) { - request.addPostParam("Value", value); - } - } -} diff --git a/src/main/java/com/twilio/rest/microvisor/v1/device/DeviceSecret.java b/src/main/java/com/twilio/rest/microvisor/v1/device/DeviceSecret.java deleted file mode 100644 index 36e7e8916a..0000000000 --- a/src/main/java/com/twilio/rest/microvisor/v1/device/DeviceSecret.java +++ /dev/null @@ -1,176 +0,0 @@ -/* - * This code was generated by - * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ - * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ - * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ - * - * Twilio - Microvisor - * This is the public Twilio REST API. - * - * NOTE: This class is auto generated by OpenAPI Generator. - * https://openapi-generator.tech - * Do not edit the class manually. - */ - -package com.twilio.rest.microvisor.v1.device; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.core.JsonParseException; -import com.fasterxml.jackson.databind.JsonMappingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; -import com.twilio.exception.ApiConnectionException; -import com.twilio.exception.ApiException; -import java.io.IOException; -import java.io.InputStream; -import java.net.URI; -import java.time.ZonedDateTime; -import java.util.Objects; -import lombok.ToString; -import lombok.ToString; - -@JsonIgnoreProperties(ignoreUnknown = true) -@ToString -public class DeviceSecret extends Resource { - - private static final long serialVersionUID = 4318157927104L; - - public static DeviceSecretCreator creator( - final String pathDeviceSid, - final String key, - final String value - ) { - return new DeviceSecretCreator(pathDeviceSid, key, value); - } - - public static DeviceSecretDeleter deleter( - final String pathDeviceSid, - final String pathKey - ) { - return new DeviceSecretDeleter(pathDeviceSid, pathKey); - } - - public static DeviceSecretFetcher fetcher( - final String pathDeviceSid, - final String pathKey - ) { - return new DeviceSecretFetcher(pathDeviceSid, pathKey); - } - - public static DeviceSecretReader reader(final String pathDeviceSid) { - return new DeviceSecretReader(pathDeviceSid); - } - - public static DeviceSecretUpdater updater( - final String pathDeviceSid, - final String pathKey, - final String value - ) { - return new DeviceSecretUpdater(pathDeviceSid, pathKey, value); - } - - /** - * Converts a JSON String into a DeviceSecret object using the provided ObjectMapper. - * - * @param json Raw JSON String - * @param objectMapper Jackson ObjectMapper - * @return DeviceSecret object represented by the provided JSON - */ - public static DeviceSecret fromJson( - final String json, - final ObjectMapper objectMapper - ) { - // Convert all checked exceptions to Runtime - try { - return objectMapper.readValue(json, DeviceSecret.class); - } catch (final JsonMappingException | JsonParseException e) { - throw new ApiException(e.getMessage(), e); - } catch (final IOException e) { - throw new ApiConnectionException(e.getMessage(), e); - } - } - - /** - * Converts a JSON InputStream into a DeviceSecret object using the provided - * ObjectMapper. - * - * @param json Raw JSON InputStream - * @param objectMapper Jackson ObjectMapper - * @return DeviceSecret object represented by the provided JSON - */ - public static DeviceSecret fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { - // Convert all checked exceptions to Runtime - try { - return objectMapper.readValue(json, DeviceSecret.class); - } catch (final JsonMappingException | JsonParseException e) { - throw new ApiException(e.getMessage(), e); - } catch (final IOException e) { - throw new ApiConnectionException(e.getMessage(), e); - } - } - - private final String deviceSid; - private final String key; - private final ZonedDateTime dateRotated; - private final URI url; - - @JsonCreator - private DeviceSecret( - @JsonProperty("device_sid") final String deviceSid, - @JsonProperty("key") final String key, - @JsonProperty("date_rotated") final String dateRotated, - @JsonProperty("url") final URI url - ) { - this.deviceSid = deviceSid; - this.key = key; - this.dateRotated = DateConverter.iso8601DateTimeFromString(dateRotated); - this.url = url; - } - - public final String getDeviceSid() { - return this.deviceSid; - } - - public final String getKey() { - return this.key; - } - - public final ZonedDateTime getDateRotated() { - return this.dateRotated; - } - - public final URI getUrl() { - return this.url; - } - - @Override - public boolean equals(final Object o) { - if (this == o) { - return true; - } - - if (o == null || getClass() != o.getClass()) { - return false; - } - - DeviceSecret other = (DeviceSecret) o; - - return ( - Objects.equals(deviceSid, other.deviceSid) && - Objects.equals(key, other.key) && - Objects.equals(dateRotated, other.dateRotated) && - Objects.equals(url, other.url) - ); - } - - @Override - public int hashCode() { - return Objects.hash(deviceSid, key, dateRotated, url); - } -} diff --git a/src/main/java/com/twilio/rest/microvisor/v1/device/DeviceSecretCreator.java b/src/main/java/com/twilio/rest/microvisor/v1/device/DeviceSecretCreator.java deleted file mode 100644 index 33e07b238c..0000000000 --- a/src/main/java/com/twilio/rest/microvisor/v1/device/DeviceSecretCreator.java +++ /dev/null @@ -1,106 +0,0 @@ -/* - * This code was generated by - * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ - * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ - * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ - * - * Twilio - Microvisor - * This is the public Twilio REST API. - * - * NOTE: This class is auto generated by OpenAPI Generator. - * https://openapi-generator.tech - * Do not edit the class manually. - */ - -package com.twilio.rest.microvisor.v1.device; - -import com.twilio.base.Creator; -import com.twilio.constant.EnumConstants; -import com.twilio.exception.ApiConnectionException; -import com.twilio.exception.ApiException; -import com.twilio.exception.RestException; -import com.twilio.http.HttpMethod; -import com.twilio.http.Request; -import com.twilio.http.Response; -import com.twilio.http.TwilioRestClient; -import com.twilio.rest.Domains; - -public class DeviceSecretCreator extends Creator { - - private String pathDeviceSid; - private String key; - private String value; - - public DeviceSecretCreator( - final String pathDeviceSid, - final String key, - final String value - ) { - this.pathDeviceSid = pathDeviceSid; - this.key = key; - this.value = value; - } - - public DeviceSecretCreator setKey(final String key) { - this.key = key; - return this; - } - - public DeviceSecretCreator setValue(final String value) { - this.value = value; - return this; - } - - @Override - public DeviceSecret create(final TwilioRestClient client) { - String path = "/v1/Devices/{DeviceSid}/Secrets"; - - path = - path.replace( - "{" + "DeviceSid" + "}", - this.pathDeviceSid.toString() - ); - path = path.replace("{" + "Key" + "}", this.key.toString()); - path = path.replace("{" + "Value" + "}", this.value.toString()); - - Request request = new Request( - HttpMethod.POST, - Domains.MICROVISOR.toString(), - path - ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); - addPostParams(request); - Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "DeviceSecret creation failed: Unable to connect to server" - ); - } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { - RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); - if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); - } - throw new ApiException(restException); - } - - return DeviceSecret.fromJson( - response.getStream(), - client.getObjectMapper() - ); - } - - private void addPostParams(final Request request) { - if (key != null) { - request.addPostParam("Key", key); - } - if (value != null) { - request.addPostParam("Value", value); - } - } -} diff --git a/src/main/java/com/twilio/rest/microvisor/v1/device/DeviceSecretFetcher.java b/src/main/java/com/twilio/rest/microvisor/v1/device/DeviceSecretFetcher.java deleted file mode 100644 index 363d966e83..0000000000 --- a/src/main/java/com/twilio/rest/microvisor/v1/device/DeviceSecretFetcher.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * This code was generated by - * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ - * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ - * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ - * - * Twilio - Microvisor - * This is the public Twilio REST API. - * - * NOTE: This class is auto generated by OpenAPI Generator. - * https://openapi-generator.tech - * Do not edit the class manually. - */ - -package com.twilio.rest.microvisor.v1.device; - -import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; -import com.twilio.exception.ApiConnectionException; -import com.twilio.exception.ApiException; -import com.twilio.exception.RestException; -import com.twilio.http.HttpMethod; -import com.twilio.http.Request; -import com.twilio.http.Response; -import com.twilio.http.TwilioRestClient; -import com.twilio.rest.Domains; - -public class DeviceSecretFetcher extends Fetcher { - - private String pathDeviceSid; - private String pathKey; - - public DeviceSecretFetcher( - final String pathDeviceSid, - final String pathKey - ) { - this.pathDeviceSid = pathDeviceSid; - this.pathKey = pathKey; - } - - @Override - public DeviceSecret fetch(final TwilioRestClient client) { - String path = "/v1/Devices/{DeviceSid}/Secrets/{Key}"; - - path = - path.replace( - "{" + "DeviceSid" + "}", - this.pathDeviceSid.toString() - ); - path = path.replace("{" + "Key" + "}", this.pathKey.toString()); - - Request request = new Request( - HttpMethod.GET, - Domains.MICROVISOR.toString(), - path - ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); - Response response = client.request(request); - - if (response == null) { - throw new ApiConnectionException( - "DeviceSecret fetch failed: Unable to connect to server" - ); - } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { - RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); - if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); - } - throw new ApiException(restException); - } - - return DeviceSecret.fromJson( - response.getStream(), - client.getObjectMapper() - ); - } -} diff --git a/src/main/java/com/twilio/rest/microvisor/v1/device/DeviceSecretReader.java b/src/main/java/com/twilio/rest/microvisor/v1/device/DeviceSecretReader.java deleted file mode 100644 index 4eb5e21ae8..0000000000 --- a/src/main/java/com/twilio/rest/microvisor/v1/device/DeviceSecretReader.java +++ /dev/null @@ -1,143 +0,0 @@ -/* - * This code was generated by - * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ - * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ - * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ - * - * Twilio - Microvisor - * This is the public Twilio REST API. - * - * NOTE: This class is auto generated by OpenAPI Generator. - * https://openapi-generator.tech - * Do not edit the class manually. - */ - -package com.twilio.rest.microvisor.v1.device; - -import com.twilio.base.Page; -import com.twilio.base.Reader; -import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; -import com.twilio.exception.ApiConnectionException; -import com.twilio.exception.ApiException; -import com.twilio.exception.RestException; -import com.twilio.http.HttpMethod; -import com.twilio.http.Request; -import com.twilio.http.Response; -import com.twilio.http.TwilioRestClient; -import com.twilio.rest.Domains; - -public class DeviceSecretReader extends Reader { - - private String pathDeviceSid; - private Long pageSize; - - public DeviceSecretReader(final String pathDeviceSid) { - this.pathDeviceSid = pathDeviceSid; - } - - public DeviceSecretReader setPageSize(final Long pageSize) { - this.pageSize = pageSize; - return this; - } - - @Override - public ResourceSet read(final TwilioRestClient client) { - return new ResourceSet<>(this, client, firstPage(client)); - } - - public Page firstPage(final TwilioRestClient client) { - String path = "/v1/Devices/{DeviceSid}/Secrets"; - path = - path.replace( - "{" + "DeviceSid" + "}", - this.pathDeviceSid.toString() - ); - - Request request = new Request( - HttpMethod.GET, - Domains.MICROVISOR.toString(), - path - ); - - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); - return pageForRequest(client, request); - } - - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { - Response response = client.request(request); - - if (response == null) { - throw new ApiConnectionException( - "DeviceSecret read failed: Unable to connect to server" - ); - } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { - RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); - if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); - } - throw new ApiException(restException); - } - - return Page.fromJson( - "secrets", - response.getContent(), - DeviceSecret.class, - client.getObjectMapper() - ); - } - - @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.MICROVISOR.toString()) - ); - return pageForRequest(client, request); - } - - @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.MICROVISOR.toString()) - ); - return pageForRequest(client, request); - } - - @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { - Request request = new Request(HttpMethod.GET, targetUrl); - - return pageForRequest(client, request); - } - - private void addQueryParams(final Request request) { - if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); - } - - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } - } -} diff --git a/src/main/java/com/twilio/rest/microvisor/v1/device/DeviceSecretUpdater.java b/src/main/java/com/twilio/rest/microvisor/v1/device/DeviceSecretUpdater.java deleted file mode 100644 index ec9105b461..0000000000 --- a/src/main/java/com/twilio/rest/microvisor/v1/device/DeviceSecretUpdater.java +++ /dev/null @@ -1,98 +0,0 @@ -/* - * This code was generated by - * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ - * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ - * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ - * - * Twilio - Microvisor - * This is the public Twilio REST API. - * - * NOTE: This class is auto generated by OpenAPI Generator. - * https://openapi-generator.tech - * Do not edit the class manually. - */ - -package com.twilio.rest.microvisor.v1.device; - -import com.twilio.base.Updater; -import com.twilio.constant.EnumConstants; -import com.twilio.exception.ApiConnectionException; -import com.twilio.exception.ApiException; -import com.twilio.exception.RestException; -import com.twilio.http.HttpMethod; -import com.twilio.http.Request; -import com.twilio.http.Response; -import com.twilio.http.TwilioRestClient; -import com.twilio.rest.Domains; - -public class DeviceSecretUpdater extends Updater { - - private String pathDeviceSid; - private String pathKey; - private String value; - - public DeviceSecretUpdater( - final String pathDeviceSid, - final String pathKey, - final String value - ) { - this.pathDeviceSid = pathDeviceSid; - this.pathKey = pathKey; - this.value = value; - } - - public DeviceSecretUpdater setValue(final String value) { - this.value = value; - return this; - } - - @Override - public DeviceSecret update(final TwilioRestClient client) { - String path = "/v1/Devices/{DeviceSid}/Secrets/{Key}"; - - path = - path.replace( - "{" + "DeviceSid" + "}", - this.pathDeviceSid.toString() - ); - path = path.replace("{" + "Key" + "}", this.pathKey.toString()); - path = path.replace("{" + "Value" + "}", this.value.toString()); - - Request request = new Request( - HttpMethod.POST, - Domains.MICROVISOR.toString(), - path - ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); - addPostParams(request); - Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "DeviceSecret update failed: Unable to connect to server" - ); - } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { - RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); - if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); - } - throw new ApiException(restException); - } - - return DeviceSecret.fromJson( - response.getStream(), - client.getObjectMapper() - ); - } - - private void addPostParams(final Request request) { - if (value != null) { - request.addPostParam("Value", value); - } - } -} diff --git a/src/main/java/com/twilio/rest/notify/v1/Credential.java b/src/main/java/com/twilio/rest/notify/v1/Credential.java index 26d2e47199..316599eb29 100644 --- a/src/main/java/com/twilio/rest/notify/v1/Credential.java +++ b/src/main/java/com/twilio/rest/notify/v1/Credential.java @@ -39,7 +39,7 @@ public class Credential extends Resource { private static final long serialVersionUID = 161183169234848L; - public static CredentialCreator creator(final PushService type) { + public static CredentialCreator creator(final Credential.PushService type) { return new CredentialCreator(type); } @@ -105,7 +105,7 @@ public static Credential fromJson( private final String sid; private final String accountSid; private final String friendlyName; - private final PushService type; + private final Credential.PushService type; private final String sandbox; private final ZonedDateTime dateCreated; private final ZonedDateTime dateUpdated; @@ -116,7 +116,7 @@ private Credential( @JsonProperty("sid") final String sid, @JsonProperty("account_sid") final String accountSid, @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("type") final PushService type, + @JsonProperty("type") final Credential.PushService type, @JsonProperty("sandbox") final String sandbox, @JsonProperty("date_created") final String dateCreated, @JsonProperty("date_updated") final String dateUpdated, @@ -144,7 +144,7 @@ public final String getFriendlyName() { return this.friendlyName; } - public final PushService getType() { + public final Credential.PushService getType() { return this.type; } diff --git a/src/main/java/com/twilio/rest/notify/v1/service/Binding.java b/src/main/java/com/twilio/rest/notify/v1/service/Binding.java index e5d9cf47db..a61e6c16e0 100644 --- a/src/main/java/com/twilio/rest/notify/v1/service/Binding.java +++ b/src/main/java/com/twilio/rest/notify/v1/service/Binding.java @@ -45,7 +45,7 @@ public class Binding extends Resource { public static BindingCreator creator( final String pathServiceSid, final String identity, - final BindingType bindingType, + final Binding.BindingType bindingType, final String address ) { return new BindingCreator( diff --git a/src/main/java/com/twilio/rest/notify/v1/service/Notification.java b/src/main/java/com/twilio/rest/notify/v1/service/Notification.java index 2fd78f20f6..432641c6cb 100644 --- a/src/main/java/com/twilio/rest/notify/v1/service/Notification.java +++ b/src/main/java/com/twilio/rest/notify/v1/service/Notification.java @@ -95,7 +95,7 @@ public static Notification fromJson( private final List identities; private final List tags; private final List segments; - private final Priority priority; + private final Notification.Priority priority; private final Integer ttl; private final String title; private final String body; @@ -118,7 +118,7 @@ private Notification( @JsonProperty("identities") final List identities, @JsonProperty("tags") final List tags, @JsonProperty("segments") final List segments, - @JsonProperty("priority") final Priority priority, + @JsonProperty("priority") final Notification.Priority priority, @JsonProperty("ttl") final Integer ttl, @JsonProperty("title") final String title, @JsonProperty("body") final String body, @@ -185,7 +185,7 @@ public final List getSegments() { return this.segments; } - public final Priority getPriority() { + public final Notification.Priority getPriority() { return this.priority; } diff --git a/src/main/java/com/twilio/rest/numbers/v1/PortingPortability.java b/src/main/java/com/twilio/rest/numbers/v1/PortingPortability.java index 1559a8f88f..f047290739 100644 --- a/src/main/java/com/twilio/rest/numbers/v1/PortingPortability.java +++ b/src/main/java/com/twilio/rest/numbers/v1/PortingPortability.java @@ -92,7 +92,7 @@ public static PortingPortability fromJson( private final Boolean pinAndAccountNumberRequired; private final String notPortableReason; private final Integer notPortableReasonCode; - private final NumberType numberType; + private final PortingPortability.NumberType numberType; private final String country; private final URI url; @@ -110,7 +110,9 @@ private PortingPortability( @JsonProperty( "not_portable_reason_code" ) final Integer notPortableReasonCode, - @JsonProperty("number_type") final NumberType numberType, + @JsonProperty( + "number_type" + ) final PortingPortability.NumberType numberType, @JsonProperty("country") final String country, @JsonProperty("url") final URI url ) { @@ -149,7 +151,7 @@ public final Integer getNotPortableReasonCode() { return this.notPortableReasonCode; } - public final NumberType getNumberType() { + public final PortingPortability.NumberType getNumberType() { return this.numberType; } diff --git a/src/main/java/com/twilio/rest/numbers/v1/PortingWebhookConfigurationDelete.java b/src/main/java/com/twilio/rest/numbers/v1/PortingWebhookConfigurationDelete.java index 40d6a5d8e9..cec172e3a1 100644 --- a/src/main/java/com/twilio/rest/numbers/v1/PortingWebhookConfigurationDelete.java +++ b/src/main/java/com/twilio/rest/numbers/v1/PortingWebhookConfigurationDelete.java @@ -35,7 +35,7 @@ public class PortingWebhookConfigurationDelete extends Resource { private static final long serialVersionUID = 0L; public static PortingWebhookConfigurationDeleteDeleter deleter( - final WebhookType webhookType + final PortingWebhookConfigurationDelete.WebhookType webhookType ) { return new PortingWebhookConfigurationDeleteDeleter(webhookType); } diff --git a/src/main/java/com/twilio/rest/numbers/v1/PortingWebhookConfigurationFetch.java b/src/main/java/com/twilio/rest/numbers/v1/Webhook.java similarity index 82% rename from src/main/java/com/twilio/rest/numbers/v1/PortingWebhookConfigurationFetch.java rename to src/main/java/com/twilio/rest/numbers/v1/Webhook.java index 53c0f02a23..6e9c6921dd 100644 --- a/src/main/java/com/twilio/rest/numbers/v1/PortingWebhookConfigurationFetch.java +++ b/src/main/java/com/twilio/rest/numbers/v1/Webhook.java @@ -35,31 +35,28 @@ @JsonIgnoreProperties(ignoreUnknown = true) @ToString -public class PortingWebhookConfigurationFetch extends Resource { +public class Webhook extends Resource { private static final long serialVersionUID = 270526030240961L; - public static PortingWebhookConfigurationFetchFetcher fetcher() { - return new PortingWebhookConfigurationFetchFetcher(); + public static WebhookFetcher fetcher() { + return new WebhookFetcher(); } /** - * Converts a JSON String into a PortingWebhookConfigurationFetch object using the provided ObjectMapper. + * Converts a JSON String into a Webhook object using the provided ObjectMapper. * * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper - * @return PortingWebhookConfigurationFetch object represented by the provided JSON + * @return Webhook object represented by the provided JSON */ - public static PortingWebhookConfigurationFetch fromJson( + public static Webhook fromJson( final String json, final ObjectMapper objectMapper ) { // Convert all checked exceptions to Runtime try { - return objectMapper.readValue( - json, - PortingWebhookConfigurationFetch.class - ); + return objectMapper.readValue(json, Webhook.class); } catch (final JsonMappingException | JsonParseException e) { throw new ApiException(e.getMessage(), e); } catch (final IOException e) { @@ -68,23 +65,20 @@ public static PortingWebhookConfigurationFetch fromJson( } /** - * Converts a JSON InputStream into a PortingWebhookConfigurationFetch object using the provided + * Converts a JSON InputStream into a Webhook object using the provided * ObjectMapper. * * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper - * @return PortingWebhookConfigurationFetch object represented by the provided JSON + * @return Webhook object represented by the provided JSON */ - public static PortingWebhookConfigurationFetch fromJson( + public static Webhook fromJson( final InputStream json, final ObjectMapper objectMapper ) { // Convert all checked exceptions to Runtime try { - return objectMapper.readValue( - json, - PortingWebhookConfigurationFetch.class - ); + return objectMapper.readValue(json, Webhook.class); } catch (final JsonMappingException | JsonParseException e) { throw new ApiException(e.getMessage(), e); } catch (final IOException e) { @@ -100,7 +94,7 @@ public static PortingWebhookConfigurationFetch fromJson( private final ZonedDateTime portOutTargetDateCreated; @JsonCreator - private PortingWebhookConfigurationFetch( + private Webhook( @JsonProperty("url") final URI url, @JsonProperty("port_in_target_url") final URI portInTargetUrl, @JsonProperty("port_out_target_url") final URI portOutTargetUrl, @@ -156,8 +150,7 @@ public boolean equals(final Object o) { return false; } - PortingWebhookConfigurationFetch other = - (PortingWebhookConfigurationFetch) o; + Webhook other = (Webhook) o; return ( Objects.equals(url, other.url) && diff --git a/src/main/java/com/twilio/rest/numbers/v1/PortingWebhookConfigurationFetchFetcher.java b/src/main/java/com/twilio/rest/numbers/v1/WebhookFetcher.java similarity index 79% rename from src/main/java/com/twilio/rest/numbers/v1/PortingWebhookConfigurationFetchFetcher.java rename to src/main/java/com/twilio/rest/numbers/v1/WebhookFetcher.java index 59d0dc599f..ccffc00624 100644 --- a/src/main/java/com/twilio/rest/numbers/v1/PortingWebhookConfigurationFetchFetcher.java +++ b/src/main/java/com/twilio/rest/numbers/v1/WebhookFetcher.java @@ -25,15 +25,12 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class PortingWebhookConfigurationFetchFetcher - extends Fetcher { +public class WebhookFetcher extends Fetcher { - public PortingWebhookConfigurationFetchFetcher() {} + public WebhookFetcher() {} @Override - public PortingWebhookConfigurationFetch fetch( - final TwilioRestClient client - ) { + public Webhook fetch(final TwilioRestClient client) { String path = "/v1/Porting/Configuration/Webhook"; Request request = new Request( @@ -46,7 +43,7 @@ public PortingWebhookConfigurationFetch fetch( if (response == null) { throw new ApiConnectionException( - "PortingWebhookConfigurationFetch fetch failed: Unable to connect to server" + "Webhook fetch failed: Unable to connect to server" ); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( @@ -62,9 +59,6 @@ public PortingWebhookConfigurationFetch fetch( throw new ApiException(restException); } - return PortingWebhookConfigurationFetch.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Webhook.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/numbers/v2/AuthorizationDocument.java b/src/main/java/com/twilio/rest/numbers/v2/AuthorizationDocument.java index e46f361687..0c3aa64569 100644 --- a/src/main/java/com/twilio/rest/numbers/v2/AuthorizationDocument.java +++ b/src/main/java/com/twilio/rest/numbers/v2/AuthorizationDocument.java @@ -113,7 +113,7 @@ public static AuthorizationDocument fromJson( private final String sid; private final String addressSid; - private final Status status; + private final AuthorizationDocument.Status status; private final String email; private final List ccEmails; private final ZonedDateTime dateCreated; @@ -125,7 +125,7 @@ public static AuthorizationDocument fromJson( private AuthorizationDocument( @JsonProperty("sid") final String sid, @JsonProperty("address_sid") final String addressSid, - @JsonProperty("status") final Status status, + @JsonProperty("status") final AuthorizationDocument.Status status, @JsonProperty("email") final String email, @JsonProperty("cc_emails") final List ccEmails, @JsonProperty("date_created") final String dateCreated, @@ -152,7 +152,7 @@ public final String getAddressSid() { return this.addressSid; } - public final Status getStatus() { + public final AuthorizationDocument.Status getStatus() { return this.status; } diff --git a/src/main/java/com/twilio/rest/numbers/v2/BulkHostedNumberOrder.java b/src/main/java/com/twilio/rest/numbers/v2/BulkHostedNumberOrder.java index a4d6136a15..d491067489 100644 --- a/src/main/java/com/twilio/rest/numbers/v2/BulkHostedNumberOrder.java +++ b/src/main/java/com/twilio/rest/numbers/v2/BulkHostedNumberOrder.java @@ -109,7 +109,7 @@ public static String toJson(Object object, ObjectMapper mapper) { } private final String bulkHostingSid; - private final RequestStatus requestStatus; + private final BulkHostedNumberOrder.RequestStatus requestStatus; private final String friendlyName; private final String notificationEmail; private final ZonedDateTime dateCreated; @@ -121,7 +121,9 @@ public static String toJson(Object object, ObjectMapper mapper) { @JsonCreator private BulkHostedNumberOrder( @JsonProperty("bulk_hosting_sid") final String bulkHostingSid, - @JsonProperty("request_status") final RequestStatus requestStatus, + @JsonProperty( + "request_status" + ) final BulkHostedNumberOrder.RequestStatus requestStatus, @JsonProperty("friendly_name") final String friendlyName, @JsonProperty("notification_email") final String notificationEmail, @JsonProperty("date_created") final String dateCreated, @@ -146,7 +148,7 @@ public final String getBulkHostingSid() { return this.bulkHostingSid; } - public final RequestStatus getRequestStatus() { + public final BulkHostedNumberOrder.RequestStatus getRequestStatus() { return this.requestStatus; } diff --git a/src/main/java/com/twilio/rest/numbers/v2/BundleClone.java b/src/main/java/com/twilio/rest/numbers/v2/BundleClone.java index 8f4376dfe5..8462b057d5 100644 --- a/src/main/java/com/twilio/rest/numbers/v2/BundleClone.java +++ b/src/main/java/com/twilio/rest/numbers/v2/BundleClone.java @@ -93,7 +93,7 @@ public static BundleClone fromJson( private final String accountSid; private final String regulationSid; private final String friendlyName; - private final Status status; + private final BundleClone.Status status; private final ZonedDateTime validUntil; private final String email; private final URI statusCallback; @@ -107,7 +107,7 @@ private BundleClone( @JsonProperty("account_sid") final String accountSid, @JsonProperty("regulation_sid") final String regulationSid, @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("status") final Status status, + @JsonProperty("status") final BundleClone.Status status, @JsonProperty("valid_until") final String validUntil, @JsonProperty("email") final String email, @JsonProperty("status_callback") final URI statusCallback, @@ -144,7 +144,7 @@ public final String getFriendlyName() { return this.friendlyName; } - public final Status getStatus() { + public final BundleClone.Status getStatus() { return this.status; } diff --git a/src/main/java/com/twilio/rest/numbers/v2/HostedNumberOrder.java b/src/main/java/com/twilio/rest/numbers/v2/HostedNumberOrder.java index 4b6531f726..6363d99966 100644 --- a/src/main/java/com/twilio/rest/numbers/v2/HostedNumberOrder.java +++ b/src/main/java/com/twilio/rest/numbers/v2/HostedNumberOrder.java @@ -69,7 +69,7 @@ public static HostedNumberOrderReader reader() { public static HostedNumberOrderUpdater updater( final String pathSid, - final Status status + final HostedNumberOrder.Status status ) { return new HostedNumberOrderUpdater(pathSid, status); } @@ -125,7 +125,7 @@ public static HostedNumberOrder fromJson( private final com.twilio.type.PhoneNumber phoneNumber; private final PhoneNumberCapabilities capabilities; private final String friendlyName; - private final Status status; + private final HostedNumberOrder.Status status; private final String failureReason; private final ZonedDateTime dateCreated; private final ZonedDateTime dateUpdated; @@ -141,7 +141,7 @@ public static HostedNumberOrder fromJson( private final Integer verificationCallDelay; private final String verificationCallExtension; private final String verificationCode; - private final VerificationType verificationType; + private final HostedNumberOrder.VerificationType verificationType; @JsonCreator private HostedNumberOrder( @@ -159,7 +159,7 @@ private HostedNumberOrder( "capabilities" ) final PhoneNumberCapabilities capabilities, @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("status") final Status status, + @JsonProperty("status") final HostedNumberOrder.Status status, @JsonProperty("failure_reason") final String failureReason, @JsonProperty("date_created") final String dateCreated, @JsonProperty("date_updated") final String dateUpdated, @@ -189,7 +189,7 @@ private HostedNumberOrder( @JsonProperty("verification_code") final String verificationCode, @JsonProperty( "verification_type" - ) final VerificationType verificationType + ) final HostedNumberOrder.VerificationType verificationType ) { this.sid = sid; this.accountSid = accountSid; @@ -250,7 +250,7 @@ public final String getFriendlyName() { return this.friendlyName; } - public final Status getStatus() { + public final HostedNumberOrder.Status getStatus() { return this.status; } @@ -314,7 +314,7 @@ public final String getVerificationCode() { return this.verificationCode; } - public final VerificationType getVerificationType() { + public final HostedNumberOrder.VerificationType getVerificationType() { return this.verificationType; } diff --git a/src/main/java/com/twilio/rest/numbers/v2/authorizationdocument/DependentHostedNumberOrder.java b/src/main/java/com/twilio/rest/numbers/v2/authorizationdocument/DependentHostedNumberOrder.java index c27f699fe5..01b4345f77 100644 --- a/src/main/java/com/twilio/rest/numbers/v2/authorizationdocument/DependentHostedNumberOrder.java +++ b/src/main/java/com/twilio/rest/numbers/v2/authorizationdocument/DependentHostedNumberOrder.java @@ -105,7 +105,7 @@ public static DependentHostedNumberOrder fromJson( private final com.twilio.type.PhoneNumber phoneNumber; private final PhoneNumberCapabilities capabilities; private final String friendlyName; - private final Status status; + private final DependentHostedNumberOrder.Status status; private final String failureReason; private final ZonedDateTime dateCreated; private final ZonedDateTime dateUpdated; @@ -134,7 +134,7 @@ private DependentHostedNumberOrder( "capabilities" ) final PhoneNumberCapabilities capabilities, @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("status") final Status status, + @JsonProperty("status") final DependentHostedNumberOrder.Status status, @JsonProperty("failure_reason") final String failureReason, @JsonProperty("date_created") final String dateCreated, @JsonProperty("date_updated") final String dateUpdated, @@ -205,7 +205,7 @@ public final String getFriendlyName() { return this.friendlyName; } - public final Status getStatus() { + public final DependentHostedNumberOrder.Status getStatus() { return this.status; } diff --git a/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/Bundle.java b/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/Bundle.java index 1245b44248..9371ac3164 100644 --- a/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/Bundle.java +++ b/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/Bundle.java @@ -111,7 +111,7 @@ public static Bundle fromJson( private final String accountSid; private final String regulationSid; private final String friendlyName; - private final Status status; + private final Bundle.Status status; private final ZonedDateTime validUntil; private final String email; private final URI statusCallback; @@ -126,7 +126,7 @@ private Bundle( @JsonProperty("account_sid") final String accountSid, @JsonProperty("regulation_sid") final String regulationSid, @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("status") final Status status, + @JsonProperty("status") final Bundle.Status status, @JsonProperty("valid_until") final String validUntil, @JsonProperty("email") final String email, @JsonProperty("status_callback") final URI statusCallback, @@ -165,7 +165,7 @@ public final String getFriendlyName() { return this.friendlyName; } - public final Status getStatus() { + public final Bundle.Status getStatus() { return this.status; } diff --git a/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/EndUser.java b/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/EndUser.java index 57f8bc63d6..6bfd90c4ab 100644 --- a/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/EndUser.java +++ b/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/EndUser.java @@ -43,7 +43,7 @@ public class EndUser extends Resource { public static EndUserCreator creator( final String friendlyName, - final Type type + final EndUser.Type type ) { return new EndUserCreator(friendlyName, type); } @@ -110,7 +110,7 @@ public static EndUser fromJson( private final String sid; private final String accountSid; private final String friendlyName; - private final Type type; + private final EndUser.Type type; private final Map attributes; private final ZonedDateTime dateCreated; private final ZonedDateTime dateUpdated; @@ -121,7 +121,7 @@ private EndUser( @JsonProperty("sid") final String sid, @JsonProperty("account_sid") final String accountSid, @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("type") final Type type, + @JsonProperty("type") final EndUser.Type type, @JsonProperty("attributes") final Map attributes, @JsonProperty("date_created") final String dateCreated, @JsonProperty("date_updated") final String dateUpdated, @@ -149,7 +149,7 @@ public final String getFriendlyName() { return this.friendlyName; } - public final Type getType() { + public final EndUser.Type getType() { return this.type; } diff --git a/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/Regulation.java b/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/Regulation.java index 16fdea60d1..5c89d54944 100644 --- a/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/Regulation.java +++ b/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/Regulation.java @@ -94,7 +94,7 @@ public static Regulation fromJson( private final String friendlyName; private final String isoCountry; private final String numberType; - private final EndUserType endUserType; + private final Regulation.EndUserType endUserType; private final Map requirements; private final URI url; @@ -104,7 +104,7 @@ private Regulation( @JsonProperty("friendly_name") final String friendlyName, @JsonProperty("iso_country") final String isoCountry, @JsonProperty("number_type") final String numberType, - @JsonProperty("end_user_type") final EndUserType endUserType, + @JsonProperty("end_user_type") final Regulation.EndUserType endUserType, @JsonProperty("requirements") final Map requirements, @JsonProperty("url") final URI url ) { @@ -133,7 +133,7 @@ public final String getNumberType() { return this.numberType; } - public final EndUserType getEndUserType() { + public final Regulation.EndUserType getEndUserType() { return this.endUserType; } diff --git a/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/SupportingDocument.java b/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/SupportingDocument.java index 7562f95557..50135af80f 100644 --- a/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/SupportingDocument.java +++ b/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/SupportingDocument.java @@ -112,7 +112,7 @@ public static SupportingDocument fromJson( private final String accountSid; private final String friendlyName; private final String mimeType; - private final Status status; + private final SupportingDocument.Status status; private final String failureReason; private final List> errors; private final String type; @@ -127,7 +127,7 @@ private SupportingDocument( @JsonProperty("account_sid") final String accountSid, @JsonProperty("friendly_name") final String friendlyName, @JsonProperty("mime_type") final String mimeType, - @JsonProperty("status") final Status status, + @JsonProperty("status") final SupportingDocument.Status status, @JsonProperty("failure_reason") final String failureReason, @JsonProperty("errors") final List> errors, @JsonProperty("type") final String type, @@ -166,7 +166,7 @@ public final String getMimeType() { return this.mimeType; } - public final Status getStatus() { + public final SupportingDocument.Status getStatus() { return this.status; } diff --git a/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/bundle/BundleCopy.java b/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/bundle/BundleCopy.java index f769beb1da..04ac0cb803 100644 --- a/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/bundle/BundleCopy.java +++ b/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/bundle/BundleCopy.java @@ -94,7 +94,7 @@ public static BundleCopy fromJson( private final String accountSid; private final String regulationSid; private final String friendlyName; - private final Status status; + private final BundleCopy.Status status; private final ZonedDateTime validUntil; private final String email; private final URI statusCallback; @@ -107,7 +107,7 @@ private BundleCopy( @JsonProperty("account_sid") final String accountSid, @JsonProperty("regulation_sid") final String regulationSid, @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("status") final Status status, + @JsonProperty("status") final BundleCopy.Status status, @JsonProperty("valid_until") final String validUntil, @JsonProperty("email") final String email, @JsonProperty("status_callback") final URI statusCallback, @@ -142,7 +142,7 @@ public final String getFriendlyName() { return this.friendlyName; } - public final Status getStatus() { + public final BundleCopy.Status getStatus() { return this.status; } diff --git a/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/bundle/Evaluation.java b/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/bundle/Evaluation.java index 4cd6b14db5..669f216872 100644 --- a/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/bundle/Evaluation.java +++ b/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/bundle/Evaluation.java @@ -104,7 +104,7 @@ public static Evaluation fromJson( private final String accountSid; private final String regulationSid; private final String bundleSid; - private final Status status; + private final Evaluation.Status status; private final List> results; private final ZonedDateTime dateCreated; private final URI url; @@ -115,7 +115,7 @@ private Evaluation( @JsonProperty("account_sid") final String accountSid, @JsonProperty("regulation_sid") final String regulationSid, @JsonProperty("bundle_sid") final String bundleSid, - @JsonProperty("status") final Status status, + @JsonProperty("status") final Evaluation.Status status, @JsonProperty("results") final List> results, @JsonProperty("date_created") final String dateCreated, @JsonProperty("url") final URI url @@ -146,7 +146,7 @@ public final String getBundleSid() { return this.bundleSid; } - public final Status getStatus() { + public final Evaluation.Status getStatus() { return this.status; } diff --git a/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/bundle/ReplaceItems.java b/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/bundle/ReplaceItems.java index 77fec453f4..9af6e75dac 100644 --- a/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/bundle/ReplaceItems.java +++ b/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/bundle/ReplaceItems.java @@ -93,7 +93,7 @@ public static ReplaceItems fromJson( private final String accountSid; private final String regulationSid; private final String friendlyName; - private final Status status; + private final ReplaceItems.Status status; private final ZonedDateTime validUntil; private final String email; private final URI statusCallback; @@ -106,7 +106,7 @@ private ReplaceItems( @JsonProperty("account_sid") final String accountSid, @JsonProperty("regulation_sid") final String regulationSid, @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("status") final Status status, + @JsonProperty("status") final ReplaceItems.Status status, @JsonProperty("valid_until") final String validUntil, @JsonProperty("email") final String email, @JsonProperty("status_callback") final URI statusCallback, @@ -141,7 +141,7 @@ public final String getFriendlyName() { return this.friendlyName; } - public final Status getStatus() { + public final ReplaceItems.Status getStatus() { return this.status; } diff --git a/src/main/java/com/twilio/rest/preview/hostedNumbers/AuthorizationDocument.java b/src/main/java/com/twilio/rest/preview/hostedNumbers/AuthorizationDocument.java index 7370fc631f..9bb552cfaf 100644 --- a/src/main/java/com/twilio/rest/preview/hostedNumbers/AuthorizationDocument.java +++ b/src/main/java/com/twilio/rest/preview/hostedNumbers/AuthorizationDocument.java @@ -115,7 +115,7 @@ public static AuthorizationDocument fromJson( private final String sid; private final String addressSid; - private final Status status; + private final AuthorizationDocument.Status status; private final String email; private final List ccEmails; private final ZonedDateTime dateCreated; @@ -127,7 +127,7 @@ public static AuthorizationDocument fromJson( private AuthorizationDocument( @JsonProperty("sid") final String sid, @JsonProperty("address_sid") final String addressSid, - @JsonProperty("status") final Status status, + @JsonProperty("status") final AuthorizationDocument.Status status, @JsonProperty("email") final String email, @JsonProperty("cc_emails") final List ccEmails, @JsonProperty("date_created") final String dateCreated, @@ -154,7 +154,7 @@ public final String getAddressSid() { return this.addressSid; } - public final Status getStatus() { + public final AuthorizationDocument.Status getStatus() { return this.status; } diff --git a/src/main/java/com/twilio/rest/preview/hostedNumbers/HostedNumberOrder.java b/src/main/java/com/twilio/rest/preview/hostedNumbers/HostedNumberOrder.java index d3b6e61791..1accd8a6ea 100644 --- a/src/main/java/com/twilio/rest/preview/hostedNumbers/HostedNumberOrder.java +++ b/src/main/java/com/twilio/rest/preview/hostedNumbers/HostedNumberOrder.java @@ -116,7 +116,7 @@ public static HostedNumberOrder fromJson( private final PhoneNumberCapabilities capabilities; private final String friendlyName; private final String uniqueName; - private final Status status; + private final HostedNumberOrder.Status status; private final String failureReason; private final ZonedDateTime dateCreated; private final ZonedDateTime dateUpdated; @@ -124,7 +124,7 @@ public static HostedNumberOrder fromJson( private final String email; private final List ccEmails; private final URI url; - private final VerificationType verificationType; + private final HostedNumberOrder.VerificationType verificationType; private final String verificationDocumentSid; private final String extension; private final Integer callDelay; @@ -148,7 +148,7 @@ private HostedNumberOrder( ) final PhoneNumberCapabilities capabilities, @JsonProperty("friendly_name") final String friendlyName, @JsonProperty("unique_name") final String uniqueName, - @JsonProperty("status") final Status status, + @JsonProperty("status") final HostedNumberOrder.Status status, @JsonProperty("failure_reason") final String failureReason, @JsonProperty("date_created") final String dateCreated, @JsonProperty("date_updated") final String dateUpdated, @@ -160,7 +160,7 @@ private HostedNumberOrder( @JsonProperty("url") final URI url, @JsonProperty( "verification_type" - ) final VerificationType verificationType, + ) final HostedNumberOrder.VerificationType verificationType, @JsonProperty( "verification_document_sid" ) final String verificationDocumentSid, @@ -232,7 +232,7 @@ public final String getUniqueName() { return this.uniqueName; } - public final Status getStatus() { + public final HostedNumberOrder.Status getStatus() { return this.status; } @@ -264,7 +264,7 @@ public final URI getUrl() { return this.url; } - public final VerificationType getVerificationType() { + public final HostedNumberOrder.VerificationType getVerificationType() { return this.verificationType; } diff --git a/src/main/java/com/twilio/rest/preview/hostedNumbers/authorizationdocument/DependentHostedNumberOrder.java b/src/main/java/com/twilio/rest/preview/hostedNumbers/authorizationdocument/DependentHostedNumberOrder.java index 2ca263c614..a568b081d8 100644 --- a/src/main/java/com/twilio/rest/preview/hostedNumbers/authorizationdocument/DependentHostedNumberOrder.java +++ b/src/main/java/com/twilio/rest/preview/hostedNumbers/authorizationdocument/DependentHostedNumberOrder.java @@ -104,14 +104,14 @@ public static DependentHostedNumberOrder fromJson( private final PhoneNumberCapabilities capabilities; private final String friendlyName; private final String uniqueName; - private final Status status; + private final DependentHostedNumberOrder.Status status; private final String failureReason; private final ZonedDateTime dateCreated; private final ZonedDateTime dateUpdated; private final Integer verificationAttempts; private final String email; private final List ccEmails; - private final VerificationType verificationType; + private final DependentHostedNumberOrder.VerificationType verificationType; private final String verificationDocumentSid; private final String extension; private final Integer callDelay; @@ -135,7 +135,7 @@ private DependentHostedNumberOrder( ) final PhoneNumberCapabilities capabilities, @JsonProperty("friendly_name") final String friendlyName, @JsonProperty("unique_name") final String uniqueName, - @JsonProperty("status") final Status status, + @JsonProperty("status") final DependentHostedNumberOrder.Status status, @JsonProperty("failure_reason") final String failureReason, @JsonProperty("date_created") final String dateCreated, @JsonProperty("date_updated") final String dateUpdated, @@ -146,7 +146,7 @@ private DependentHostedNumberOrder( @JsonProperty("cc_emails") final List ccEmails, @JsonProperty( "verification_type" - ) final VerificationType verificationType, + ) final DependentHostedNumberOrder.VerificationType verificationType, @JsonProperty( "verification_document_sid" ) final String verificationDocumentSid, @@ -217,7 +217,7 @@ public final String getUniqueName() { return this.uniqueName; } - public final Status getStatus() { + public final DependentHostedNumberOrder.Status getStatus() { return this.status; } @@ -245,7 +245,7 @@ public final List getCcEmails() { return this.ccEmails; } - public final VerificationType getVerificationType() { + public final DependentHostedNumberOrder.VerificationType getVerificationType() { return this.verificationType; } diff --git a/src/main/java/com/twilio/rest/previewiam/organizations/Account.java b/src/main/java/com/twilio/rest/previewiam/organizations/Account.java index 5186823e23..388b31fa34 100644 --- a/src/main/java/com/twilio/rest/previewiam/organizations/Account.java +++ b/src/main/java/com/twilio/rest/previewiam/organizations/Account.java @@ -94,7 +94,7 @@ public static Account fromJson( private final String accountSid; private final String friendlyName; - private final StatusEnum status; + private final Account.StatusEnum status; private final String ownerSid; private final ZonedDateTime dateCreated; @@ -102,7 +102,7 @@ public static Account fromJson( private Account( @JsonProperty("account_sid") final String accountSid, @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("status") final StatusEnum status, + @JsonProperty("status") final Account.StatusEnum status, @JsonProperty("owner_sid") final String ownerSid, @JsonProperty("date_created") final String dateCreated ) { @@ -121,7 +121,7 @@ public final String getFriendlyName() { return this.friendlyName; } - public final StatusEnum getStatus() { + public final Account.StatusEnum getStatus() { return this.status; } diff --git a/src/main/java/com/twilio/rest/previewiam/organizations/RoleAssignment.java b/src/main/java/com/twilio/rest/previewiam/organizations/RoleAssignment.java index f02a6ad8fa..875068a004 100644 --- a/src/main/java/com/twilio/rest/previewiam/organizations/RoleAssignment.java +++ b/src/main/java/com/twilio/rest/previewiam/organizations/RoleAssignment.java @@ -83,7 +83,7 @@ public static PublicApiCreateRoleAssignmentRequest fromJson( public static RoleAssignmentCreator creator( final String pathOrganizationSid, - final PublicApiCreateRoleAssignmentRequest publicApiCreateRoleAssignmentRequest + final RoleAssignment.PublicApiCreateRoleAssignmentRequest publicApiCreateRoleAssignmentRequest ) { return new RoleAssignmentCreator( pathOrganizationSid, diff --git a/src/main/java/com/twilio/rest/previewiam/organizations/User.java b/src/main/java/com/twilio/rest/previewiam/organizations/User.java index 923872e3e5..2e3a501701 100644 --- a/src/main/java/com/twilio/rest/previewiam/organizations/User.java +++ b/src/main/java/com/twilio/rest/previewiam/organizations/User.java @@ -213,7 +213,7 @@ public static ScimUser fromJson(String jsonString, ObjectMapper mapper) public static UserCreator creator( final String pathOrganizationSid, - final ScimUser scimUser + final User.ScimUser scimUser ) { return new UserCreator(pathOrganizationSid, scimUser); } @@ -239,7 +239,7 @@ public static UserReader reader(final String pathOrganizationSid) { public static UserUpdater updater( final String pathOrganizationSid, final String pathUserSid, - final ScimUser scimUser + final User.ScimUser scimUser ) { return new UserUpdater(pathOrganizationSid, pathUserSid, scimUser); } diff --git a/src/main/java/com/twilio/rest/pricing/v1/messaging/Country.java b/src/main/java/com/twilio/rest/pricing/v1/messaging/Country.java index 80882ed263..b94e824fc8 100644 --- a/src/main/java/com/twilio/rest/pricing/v1/messaging/Country.java +++ b/src/main/java/com/twilio/rest/pricing/v1/messaging/Country.java @@ -111,7 +111,7 @@ private Country( InboundSmsPrice > inboundSmsPrices, @JsonProperty("price_unit") @JsonDeserialize( - using = CurrencyDeserializer.class + using = com.twilio.converter.CurrencyDeserializer.class ) final Currency priceUnit, @JsonProperty("url") final URI url ) { diff --git a/src/main/java/com/twilio/rest/pricing/v1/phonenumber/Country.java b/src/main/java/com/twilio/rest/pricing/v1/phonenumber/Country.java index 8c3d1a112f..b7460493df 100644 --- a/src/main/java/com/twilio/rest/pricing/v1/phonenumber/Country.java +++ b/src/main/java/com/twilio/rest/pricing/v1/phonenumber/Country.java @@ -106,7 +106,7 @@ private Country( PhoneNumberPrice > phoneNumberPrices, @JsonProperty("price_unit") @JsonDeserialize( - using = CurrencyDeserializer.class + using = com.twilio.converter.CurrencyDeserializer.class ) final Currency priceUnit, @JsonProperty("url") final URI url ) { diff --git a/src/main/java/com/twilio/rest/pricing/v1/voice/Country.java b/src/main/java/com/twilio/rest/pricing/v1/voice/Country.java index 571bdc47f3..766b5a0ced 100644 --- a/src/main/java/com/twilio/rest/pricing/v1/voice/Country.java +++ b/src/main/java/com/twilio/rest/pricing/v1/voice/Country.java @@ -111,7 +111,7 @@ private Country( InboundCallPrice > inboundCallPrices, @JsonProperty("price_unit") @JsonDeserialize( - using = CurrencyDeserializer.class + using = com.twilio.converter.CurrencyDeserializer.class ) final Currency priceUnit, @JsonProperty("url") final URI url ) { diff --git a/src/main/java/com/twilio/rest/pricing/v1/voice/Number.java b/src/main/java/com/twilio/rest/pricing/v1/voice/Number.java index c3554827ba..84501022ef 100644 --- a/src/main/java/com/twilio/rest/pricing/v1/voice/Number.java +++ b/src/main/java/com/twilio/rest/pricing/v1/voice/Number.java @@ -110,7 +110,7 @@ private Number( "inbound_call_price" ) final InboundCallPrice inboundCallPrice, @JsonProperty("price_unit") @JsonDeserialize( - using = CurrencyDeserializer.class + using = com.twilio.converter.CurrencyDeserializer.class ) final Currency priceUnit, @JsonProperty("url") final URI url ) { diff --git a/src/main/java/com/twilio/rest/pricing/v2/Country.java b/src/main/java/com/twilio/rest/pricing/v2/Country.java index 337a60e819..a95ebb6743 100644 --- a/src/main/java/com/twilio/rest/pricing/v2/Country.java +++ b/src/main/java/com/twilio/rest/pricing/v2/Country.java @@ -111,7 +111,7 @@ private Country( InboundCallPrice > originatingCallPrices, @JsonProperty("price_unit") @JsonDeserialize( - using = CurrencyDeserializer.class + using = com.twilio.converter.CurrencyDeserializer.class ) final Currency priceUnit, @JsonProperty("url") final URI url ) { diff --git a/src/main/java/com/twilio/rest/pricing/v2/Number.java b/src/main/java/com/twilio/rest/pricing/v2/Number.java index f23418faf6..3d8c0f89fe 100644 --- a/src/main/java/com/twilio/rest/pricing/v2/Number.java +++ b/src/main/java/com/twilio/rest/pricing/v2/Number.java @@ -117,7 +117,7 @@ private Number( "originating_call_price" ) final InboundCallPrice originatingCallPrice, @JsonProperty("price_unit") @JsonDeserialize( - using = CurrencyDeserializer.class + using = com.twilio.converter.CurrencyDeserializer.class ) final Currency priceUnit, @JsonProperty("url") final URI url ) { diff --git a/src/main/java/com/twilio/rest/pricing/v2/voice/Country.java b/src/main/java/com/twilio/rest/pricing/v2/voice/Country.java index 678cc56bda..18a482f54f 100644 --- a/src/main/java/com/twilio/rest/pricing/v2/voice/Country.java +++ b/src/main/java/com/twilio/rest/pricing/v2/voice/Country.java @@ -111,7 +111,7 @@ private Country( InboundCallPrice > inboundCallPrices, @JsonProperty("price_unit") @JsonDeserialize( - using = CurrencyDeserializer.class + using = com.twilio.converter.CurrencyDeserializer.class ) final Currency priceUnit, @JsonProperty("url") final URI url ) { diff --git a/src/main/java/com/twilio/rest/pricing/v2/voice/Number.java b/src/main/java/com/twilio/rest/pricing/v2/voice/Number.java index c34fd46796..cb87bffd51 100644 --- a/src/main/java/com/twilio/rest/pricing/v2/voice/Number.java +++ b/src/main/java/com/twilio/rest/pricing/v2/voice/Number.java @@ -117,7 +117,7 @@ private Number( "inbound_call_price" ) final InboundCallPrice inboundCallPrice, @JsonProperty("price_unit") @JsonDeserialize( - using = CurrencyDeserializer.class + using = com.twilio.converter.CurrencyDeserializer.class ) final Currency priceUnit, @JsonProperty("url") final URI url ) { diff --git a/src/main/java/com/twilio/rest/proxy/v1/Service.java b/src/main/java/com/twilio/rest/proxy/v1/Service.java index 58fe5e69af..65eb5245f6 100644 --- a/src/main/java/com/twilio/rest/proxy/v1/Service.java +++ b/src/main/java/com/twilio/rest/proxy/v1/Service.java @@ -110,8 +110,8 @@ public static Service fromJson( private final String chatInstanceSid; private final URI callbackUrl; private final Integer defaultTtl; - private final NumberSelectionBehavior numberSelectionBehavior; - private final GeoMatchLevel geoMatchLevel; + private final Service.NumberSelectionBehavior numberSelectionBehavior; + private final Service.GeoMatchLevel geoMatchLevel; private final URI interceptCallbackUrl; private final URI outOfSessionCallbackUrl; private final ZonedDateTime dateCreated; @@ -129,8 +129,10 @@ private Service( @JsonProperty("default_ttl") final Integer defaultTtl, @JsonProperty( "number_selection_behavior" - ) final NumberSelectionBehavior numberSelectionBehavior, - @JsonProperty("geo_match_level") final GeoMatchLevel geoMatchLevel, + ) final Service.NumberSelectionBehavior numberSelectionBehavior, + @JsonProperty( + "geo_match_level" + ) final Service.GeoMatchLevel geoMatchLevel, @JsonProperty("intercept_callback_url") final URI interceptCallbackUrl, @JsonProperty( "out_of_session_callback_url" @@ -180,11 +182,11 @@ public final Integer getDefaultTtl() { return this.defaultTtl; } - public final NumberSelectionBehavior getNumberSelectionBehavior() { + public final Service.NumberSelectionBehavior getNumberSelectionBehavior() { return this.numberSelectionBehavior; } - public final GeoMatchLevel getGeoMatchLevel() { + public final Service.GeoMatchLevel getGeoMatchLevel() { return this.geoMatchLevel; } diff --git a/src/main/java/com/twilio/rest/proxy/v1/service/Session.java b/src/main/java/com/twilio/rest/proxy/v1/service/Session.java index 07b22595d9..2c8db7c6ad 100644 --- a/src/main/java/com/twilio/rest/proxy/v1/service/Session.java +++ b/src/main/java/com/twilio/rest/proxy/v1/service/Session.java @@ -121,10 +121,10 @@ public static Session fromJson( private final ZonedDateTime dateLastInteraction; private final ZonedDateTime dateExpiry; private final String uniqueName; - private final Status status; + private final Session.Status status; private final String closedReason; private final Integer ttl; - private final Mode mode; + private final Session.Mode mode; private final ZonedDateTime dateCreated; private final ZonedDateTime dateUpdated; private final URI url; @@ -140,10 +140,10 @@ private Session( @JsonProperty("date_last_interaction") final String dateLastInteraction, @JsonProperty("date_expiry") final String dateExpiry, @JsonProperty("unique_name") final String uniqueName, - @JsonProperty("status") final Status status, + @JsonProperty("status") final Session.Status status, @JsonProperty("closed_reason") final String closedReason, @JsonProperty("ttl") final Integer ttl, - @JsonProperty("mode") final Mode mode, + @JsonProperty("mode") final Session.Mode mode, @JsonProperty("date_created") final String dateCreated, @JsonProperty("date_updated") final String dateUpdated, @JsonProperty("url") final URI url, @@ -200,7 +200,7 @@ public final String getUniqueName() { return this.uniqueName; } - public final Status getStatus() { + public final Session.Status getStatus() { return this.status; } @@ -212,7 +212,7 @@ public final Integer getTtl() { return this.ttl; } - public final Mode getMode() { + public final Session.Mode getMode() { return this.mode; } diff --git a/src/main/java/com/twilio/rest/proxy/v1/service/SessionCreator.java b/src/main/java/com/twilio/rest/proxy/v1/service/SessionCreator.java index 8a936a5902..db40a233aa 100644 --- a/src/main/java/com/twilio/rest/proxy/v1/service/SessionCreator.java +++ b/src/main/java/com/twilio/rest/proxy/v1/service/SessionCreator.java @@ -15,8 +15,9 @@ package com.twilio.rest.proxy.v1.service; import com.twilio.base.Creator; -import com.twilio.converter.Converter; import com.twilio.constant.EnumConstants; +import com.twilio.converter.Converter; +import com.twilio.converter.Converter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; diff --git a/src/main/java/com/twilio/rest/proxy/v1/service/ShortCode.java b/src/main/java/com/twilio/rest/proxy/v1/service/ShortCode.java deleted file mode 100644 index f329ccddf9..0000000000 --- a/src/main/java/com/twilio/rest/proxy/v1/service/ShortCode.java +++ /dev/null @@ -1,236 +0,0 @@ -/* - * This code was generated by - * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ - * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ - * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ - * - * Twilio - Proxy - * This is the public Twilio REST API. - * - * NOTE: This class is auto generated by OpenAPI Generator. - * https://openapi-generator.tech - * Do not edit the class manually. - */ - -package com.twilio.rest.proxy.v1.service; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.core.JsonParseException; -import com.fasterxml.jackson.databind.JsonMappingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; -import com.twilio.exception.ApiConnectionException; -import com.twilio.exception.ApiException; -import com.twilio.type.PhoneNumberCapabilities; -import java.io.IOException; -import java.io.InputStream; -import java.net.URI; -import java.time.ZonedDateTime; -import java.util.Objects; -import lombok.ToString; -import lombok.ToString; - -@JsonIgnoreProperties(ignoreUnknown = true) -@ToString -public class ShortCode extends Resource { - - private static final long serialVersionUID = 222849980654127L; - - public static ShortCodeCreator creator( - final String pathServiceSid, - final String sid - ) { - return new ShortCodeCreator(pathServiceSid, sid); - } - - public static ShortCodeDeleter deleter( - final String pathServiceSid, - final String pathSid - ) { - return new ShortCodeDeleter(pathServiceSid, pathSid); - } - - public static ShortCodeFetcher fetcher( - final String pathServiceSid, - final String pathSid - ) { - return new ShortCodeFetcher(pathServiceSid, pathSid); - } - - public static ShortCodeReader reader(final String pathServiceSid) { - return new ShortCodeReader(pathServiceSid); - } - - public static ShortCodeUpdater updater( - final String pathServiceSid, - final String pathSid - ) { - return new ShortCodeUpdater(pathServiceSid, pathSid); - } - - /** - * Converts a JSON String into a ShortCode object using the provided ObjectMapper. - * - * @param json Raw JSON String - * @param objectMapper Jackson ObjectMapper - * @return ShortCode object represented by the provided JSON - */ - public static ShortCode fromJson( - final String json, - final ObjectMapper objectMapper - ) { - // Convert all checked exceptions to Runtime - try { - return objectMapper.readValue(json, ShortCode.class); - } catch (final JsonMappingException | JsonParseException e) { - throw new ApiException(e.getMessage(), e); - } catch (final IOException e) { - throw new ApiConnectionException(e.getMessage(), e); - } - } - - /** - * Converts a JSON InputStream into a ShortCode object using the provided - * ObjectMapper. - * - * @param json Raw JSON InputStream - * @param objectMapper Jackson ObjectMapper - * @return ShortCode object represented by the provided JSON - */ - public static ShortCode fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { - // Convert all checked exceptions to Runtime - try { - return objectMapper.readValue(json, ShortCode.class); - } catch (final JsonMappingException | JsonParseException e) { - throw new ApiException(e.getMessage(), e); - } catch (final IOException e) { - throw new ApiConnectionException(e.getMessage(), e); - } - } - - private final String sid; - private final String accountSid; - private final String serviceSid; - private final ZonedDateTime dateCreated; - private final ZonedDateTime dateUpdated; - private final String shortCode; - private final String isoCountry; - private final PhoneNumberCapabilities capabilities; - private final URI url; - private final Boolean isReserved; - - @JsonCreator - private ShortCode( - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("service_sid") final String serviceSid, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("short_code") final String shortCode, - @JsonProperty("iso_country") final String isoCountry, - @JsonProperty( - "capabilities" - ) final PhoneNumberCapabilities capabilities, - @JsonProperty("url") final URI url, - @JsonProperty("is_reserved") final Boolean isReserved - ) { - this.sid = sid; - this.accountSid = accountSid; - this.serviceSid = serviceSid; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); - this.shortCode = shortCode; - this.isoCountry = isoCountry; - this.capabilities = capabilities; - this.url = url; - this.isReserved = isReserved; - } - - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getServiceSid() { - return this.serviceSid; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final String getShortCode() { - return this.shortCode; - } - - public final String getIsoCountry() { - return this.isoCountry; - } - - public final PhoneNumberCapabilities getCapabilities() { - return this.capabilities; - } - - public final URI getUrl() { - return this.url; - } - - public final Boolean getIsReserved() { - return this.isReserved; - } - - @Override - public boolean equals(final Object o) { - if (this == o) { - return true; - } - - if (o == null || getClass() != o.getClass()) { - return false; - } - - ShortCode other = (ShortCode) o; - - return ( - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(serviceSid, other.serviceSid) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(shortCode, other.shortCode) && - Objects.equals(isoCountry, other.isoCountry) && - Objects.equals(capabilities, other.capabilities) && - Objects.equals(url, other.url) && - Objects.equals(isReserved, other.isReserved) - ); - } - - @Override - public int hashCode() { - return Objects.hash( - sid, - accountSid, - serviceSid, - dateCreated, - dateUpdated, - shortCode, - isoCountry, - capabilities, - url, - isReserved - ); - } -} diff --git a/src/main/java/com/twilio/rest/proxy/v1/service/ShortCodeDeleter.java b/src/main/java/com/twilio/rest/proxy/v1/service/ShortCodeDeleter.java deleted file mode 100644 index 488b8600c0..0000000000 --- a/src/main/java/com/twilio/rest/proxy/v1/service/ShortCodeDeleter.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * This code was generated by - * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ - * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ - * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ - * - * Twilio - Proxy - * This is the public Twilio REST API. - * - * NOTE: This class is auto generated by OpenAPI Generator. - * https://openapi-generator.tech - * Do not edit the class manually. - */ - -package com.twilio.rest.proxy.v1.service; - -import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; -import com.twilio.exception.ApiConnectionException; -import com.twilio.exception.ApiException; -import com.twilio.exception.RestException; -import com.twilio.http.HttpMethod; -import com.twilio.http.Request; -import com.twilio.http.Response; -import com.twilio.http.TwilioRestClient; -import com.twilio.rest.Domains; - -public class ShortCodeDeleter extends Deleter { - - private String pathServiceSid; - private String pathSid; - - public ShortCodeDeleter(final String pathServiceSid, final String pathSid) { - this.pathServiceSid = pathServiceSid; - this.pathSid = pathSid; - } - - @Override - public boolean delete(final TwilioRestClient client) { - String path = "/v1/Services/{ServiceSid}/ShortCodes/{Sid}"; - - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); - - Request request = new Request( - HttpMethod.DELETE, - Domains.PROXY.toString(), - path - ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); - Response response = client.request(request); - - if (response == null) { - throw new ApiConnectionException( - "ShortCode delete failed: Unable to connect to server" - ); - } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { - RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); - if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); - } - throw new ApiException(restException); - } - return response.getStatusCode() == 204; - } -} diff --git a/src/main/java/com/twilio/rest/proxy/v1/service/ShortCodeReader.java b/src/main/java/com/twilio/rest/proxy/v1/service/ShortCodeReader.java deleted file mode 100644 index 1a88f3707d..0000000000 --- a/src/main/java/com/twilio/rest/proxy/v1/service/ShortCodeReader.java +++ /dev/null @@ -1,143 +0,0 @@ -/* - * This code was generated by - * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ - * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ - * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ - * - * Twilio - Proxy - * This is the public Twilio REST API. - * - * NOTE: This class is auto generated by OpenAPI Generator. - * https://openapi-generator.tech - * Do not edit the class manually. - */ - -package com.twilio.rest.proxy.v1.service; - -import com.twilio.base.Page; -import com.twilio.base.Reader; -import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; -import com.twilio.exception.ApiConnectionException; -import com.twilio.exception.ApiException; -import com.twilio.exception.RestException; -import com.twilio.http.HttpMethod; -import com.twilio.http.Request; -import com.twilio.http.Response; -import com.twilio.http.TwilioRestClient; -import com.twilio.rest.Domains; - -public class ShortCodeReader extends Reader { - - private String pathServiceSid; - private Long pageSize; - - public ShortCodeReader(final String pathServiceSid) { - this.pathServiceSid = pathServiceSid; - } - - public ShortCodeReader setPageSize(final Long pageSize) { - this.pageSize = pageSize; - return this; - } - - @Override - public ResourceSet read(final TwilioRestClient client) { - return new ResourceSet<>(this, client, firstPage(client)); - } - - public Page firstPage(final TwilioRestClient client) { - String path = "/v1/Services/{ServiceSid}/ShortCodes"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - - Request request = new Request( - HttpMethod.GET, - Domains.PROXY.toString(), - path - ); - - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); - return pageForRequest(client, request); - } - - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { - Response response = client.request(request); - - if (response == null) { - throw new ApiConnectionException( - "ShortCode read failed: Unable to connect to server" - ); - } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { - RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); - if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); - } - throw new ApiException(restException); - } - - return Page.fromJson( - "short_codes", - response.getContent(), - ShortCode.class, - client.getObjectMapper() - ); - } - - @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.PROXY.toString()) - ); - return pageForRequest(client, request); - } - - @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.PROXY.toString()) - ); - return pageForRequest(client, request); - } - - @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { - Request request = new Request(HttpMethod.GET, targetUrl); - - return pageForRequest(client, request); - } - - private void addQueryParams(final Request request) { - if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); - } - - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } - } -} diff --git a/src/main/java/com/twilio/rest/proxy/v1/service/ShortCodeUpdater.java b/src/main/java/com/twilio/rest/proxy/v1/service/ShortCodeUpdater.java deleted file mode 100644 index 6672e14a7e..0000000000 --- a/src/main/java/com/twilio/rest/proxy/v1/service/ShortCodeUpdater.java +++ /dev/null @@ -1,92 +0,0 @@ -/* - * This code was generated by - * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ - * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ - * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ - * - * Twilio - Proxy - * This is the public Twilio REST API. - * - * NOTE: This class is auto generated by OpenAPI Generator. - * https://openapi-generator.tech - * Do not edit the class manually. - */ - -package com.twilio.rest.proxy.v1.service; - -import com.twilio.base.Updater; -import com.twilio.constant.EnumConstants; -import com.twilio.exception.ApiConnectionException; -import com.twilio.exception.ApiException; -import com.twilio.exception.RestException; -import com.twilio.http.HttpMethod; -import com.twilio.http.Request; -import com.twilio.http.Response; -import com.twilio.http.TwilioRestClient; -import com.twilio.rest.Domains; - -public class ShortCodeUpdater extends Updater { - - private String pathServiceSid; - private String pathSid; - private Boolean isReserved; - - public ShortCodeUpdater(final String pathServiceSid, final String pathSid) { - this.pathServiceSid = pathServiceSid; - this.pathSid = pathSid; - } - - public ShortCodeUpdater setIsReserved(final Boolean isReserved) { - this.isReserved = isReserved; - return this; - } - - @Override - public ShortCode update(final TwilioRestClient client) { - String path = "/v1/Services/{ServiceSid}/ShortCodes/{Sid}"; - - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); - - Request request = new Request( - HttpMethod.POST, - Domains.PROXY.toString(), - path - ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); - addPostParams(request); - Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "ShortCode update failed: Unable to connect to server" - ); - } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { - RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); - if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); - } - throw new ApiException(restException); - } - - return ShortCode.fromJson( - response.getStream(), - client.getObjectMapper() - ); - } - - private void addPostParams(final Request request) { - if (isReserved != null) { - request.addPostParam("IsReserved", isReserved.toString()); - } - } -} diff --git a/src/main/java/com/twilio/rest/proxy/v1/service/session/Interaction.java b/src/main/java/com/twilio/rest/proxy/v1/service/session/Interaction.java index 67ee90770a..9167ddc0a9 100644 --- a/src/main/java/com/twilio/rest/proxy/v1/service/session/Interaction.java +++ b/src/main/java/com/twilio/rest/proxy/v1/service/session/Interaction.java @@ -110,15 +110,15 @@ public static Interaction fromJson( private final String serviceSid; private final String accountSid; private final String data; - private final Type type; + private final Interaction.Type type; private final String inboundParticipantSid; private final String inboundResourceSid; - private final ResourceStatus inboundResourceStatus; + private final Interaction.ResourceStatus inboundResourceStatus; private final String inboundResourceType; private final URI inboundResourceUrl; private final String outboundParticipantSid; private final String outboundResourceSid; - private final ResourceStatus outboundResourceStatus; + private final Interaction.ResourceStatus outboundResourceStatus; private final String outboundResourceType; private final URI outboundResourceUrl; private final ZonedDateTime dateCreated; @@ -132,14 +132,14 @@ private Interaction( @JsonProperty("service_sid") final String serviceSid, @JsonProperty("account_sid") final String accountSid, @JsonProperty("data") final String data, - @JsonProperty("type") final Type type, + @JsonProperty("type") final Interaction.Type type, @JsonProperty( "inbound_participant_sid" ) final String inboundParticipantSid, @JsonProperty("inbound_resource_sid") final String inboundResourceSid, @JsonProperty( "inbound_resource_status" - ) final ResourceStatus inboundResourceStatus, + ) final Interaction.ResourceStatus inboundResourceStatus, @JsonProperty("inbound_resource_type") final String inboundResourceType, @JsonProperty("inbound_resource_url") final URI inboundResourceUrl, @JsonProperty( @@ -148,7 +148,7 @@ private Interaction( @JsonProperty("outbound_resource_sid") final String outboundResourceSid, @JsonProperty( "outbound_resource_status" - ) final ResourceStatus outboundResourceStatus, + ) final Interaction.ResourceStatus outboundResourceStatus, @JsonProperty( "outbound_resource_type" ) final String outboundResourceType, @@ -198,7 +198,7 @@ public final String getData() { return this.data; } - public final Type getType() { + public final Interaction.Type getType() { return this.type; } @@ -210,7 +210,7 @@ public final String getInboundResourceSid() { return this.inboundResourceSid; } - public final ResourceStatus getInboundResourceStatus() { + public final Interaction.ResourceStatus getInboundResourceStatus() { return this.inboundResourceStatus; } @@ -230,7 +230,7 @@ public final String getOutboundResourceSid() { return this.outboundResourceSid; } - public final ResourceStatus getOutboundResourceStatus() { + public final Interaction.ResourceStatus getOutboundResourceStatus() { return this.outboundResourceStatus; } diff --git a/src/main/java/com/twilio/rest/proxy/v1/service/session/participant/MessageInteraction.java b/src/main/java/com/twilio/rest/proxy/v1/service/session/participant/MessageInteraction.java index fffb740206..2cc5764aa6 100644 --- a/src/main/java/com/twilio/rest/proxy/v1/service/session/participant/MessageInteraction.java +++ b/src/main/java/com/twilio/rest/proxy/v1/service/session/participant/MessageInteraction.java @@ -142,16 +142,16 @@ public static MessageInteraction fromJson( private final String serviceSid; private final String accountSid; private final String data; - private final Type type; + private final MessageInteraction.Type type; private final String participantSid; private final String inboundParticipantSid; private final String inboundResourceSid; - private final ResourceStatus inboundResourceStatus; + private final MessageInteraction.ResourceStatus inboundResourceStatus; private final String inboundResourceType; private final URI inboundResourceUrl; private final String outboundParticipantSid; private final String outboundResourceSid; - private final ResourceStatus outboundResourceStatus; + private final MessageInteraction.ResourceStatus outboundResourceStatus; private final String outboundResourceType; private final URI outboundResourceUrl; private final ZonedDateTime dateCreated; @@ -165,7 +165,7 @@ private MessageInteraction( @JsonProperty("service_sid") final String serviceSid, @JsonProperty("account_sid") final String accountSid, @JsonProperty("data") final String data, - @JsonProperty("type") final Type type, + @JsonProperty("type") final MessageInteraction.Type type, @JsonProperty("participant_sid") final String participantSid, @JsonProperty( "inbound_participant_sid" @@ -173,7 +173,7 @@ private MessageInteraction( @JsonProperty("inbound_resource_sid") final String inboundResourceSid, @JsonProperty( "inbound_resource_status" - ) final ResourceStatus inboundResourceStatus, + ) final MessageInteraction.ResourceStatus inboundResourceStatus, @JsonProperty("inbound_resource_type") final String inboundResourceType, @JsonProperty("inbound_resource_url") final URI inboundResourceUrl, @JsonProperty( @@ -182,7 +182,7 @@ private MessageInteraction( @JsonProperty("outbound_resource_sid") final String outboundResourceSid, @JsonProperty( "outbound_resource_status" - ) final ResourceStatus outboundResourceStatus, + ) final MessageInteraction.ResourceStatus outboundResourceStatus, @JsonProperty( "outbound_resource_type" ) final String outboundResourceType, @@ -233,7 +233,7 @@ public final String getData() { return this.data; } - public final Type getType() { + public final MessageInteraction.Type getType() { return this.type; } @@ -249,7 +249,7 @@ public final String getInboundResourceSid() { return this.inboundResourceSid; } - public final ResourceStatus getInboundResourceStatus() { + public final MessageInteraction.ResourceStatus getInboundResourceStatus() { return this.inboundResourceStatus; } @@ -269,7 +269,7 @@ public final String getOutboundResourceSid() { return this.outboundResourceSid; } - public final ResourceStatus getOutboundResourceStatus() { + public final MessageInteraction.ResourceStatus getOutboundResourceStatus() { return this.outboundResourceStatus; } diff --git a/src/main/java/com/twilio/rest/serverless/v1/service/Build.java b/src/main/java/com/twilio/rest/serverless/v1/service/Build.java index aefb0ce32d..30dfe72cf9 100644 --- a/src/main/java/com/twilio/rest/serverless/v1/service/Build.java +++ b/src/main/java/com/twilio/rest/serverless/v1/service/Build.java @@ -110,11 +110,11 @@ public static Build fromJson( private final String sid; private final String accountSid; private final String serviceSid; - private final Status status; + private final Build.Status status; private final List> assetVersions; private final List> functionVersions; private final List> dependencies; - private final Runtime runtime; + private final Build.Runtime runtime; private final ZonedDateTime dateCreated; private final ZonedDateTime dateUpdated; private final URI url; @@ -125,7 +125,7 @@ private Build( @JsonProperty("sid") final String sid, @JsonProperty("account_sid") final String accountSid, @JsonProperty("service_sid") final String serviceSid, - @JsonProperty("status") final Status status, + @JsonProperty("status") final Build.Status status, @JsonProperty("asset_versions") final List< Map > assetVersions, @@ -135,7 +135,7 @@ private Build( @JsonProperty("dependencies") final List< Map > dependencies, - @JsonProperty("runtime") final Runtime runtime, + @JsonProperty("runtime") final Build.Runtime runtime, @JsonProperty("date_created") final String dateCreated, @JsonProperty("date_updated") final String dateUpdated, @JsonProperty("url") final URI url, @@ -167,7 +167,7 @@ public final String getServiceSid() { return this.serviceSid; } - public final Status getStatus() { + public final Build.Status getStatus() { return this.status; } @@ -183,7 +183,7 @@ public final List> getDependencies() { return this.dependencies; } - public final Runtime getRuntime() { + public final Build.Runtime getRuntime() { return this.runtime; } diff --git a/src/main/java/com/twilio/rest/serverless/v1/service/asset/AssetVersion.java b/src/main/java/com/twilio/rest/serverless/v1/service/asset/AssetVersion.java index 42be38212b..a8cc25e5b0 100644 --- a/src/main/java/com/twilio/rest/serverless/v1/service/asset/AssetVersion.java +++ b/src/main/java/com/twilio/rest/serverless/v1/service/asset/AssetVersion.java @@ -102,7 +102,7 @@ public static AssetVersion fromJson( private final String serviceSid; private final String assetSid; private final String path; - private final Visibility visibility; + private final AssetVersion.Visibility visibility; private final ZonedDateTime dateCreated; private final URI url; @@ -113,7 +113,7 @@ private AssetVersion( @JsonProperty("service_sid") final String serviceSid, @JsonProperty("asset_sid") final String assetSid, @JsonProperty("path") final String path, - @JsonProperty("visibility") final Visibility visibility, + @JsonProperty("visibility") final AssetVersion.Visibility visibility, @JsonProperty("date_created") final String dateCreated, @JsonProperty("url") final URI url ) { @@ -147,7 +147,7 @@ public final String getPath() { return this.path; } - public final Visibility getVisibility() { + public final AssetVersion.Visibility getVisibility() { return this.visibility; } diff --git a/src/main/java/com/twilio/rest/serverless/v1/service/build/BuildStatus.java b/src/main/java/com/twilio/rest/serverless/v1/service/build/BuildStatus.java index 583fcb0fab..f00e9175cb 100644 --- a/src/main/java/com/twilio/rest/serverless/v1/service/build/BuildStatus.java +++ b/src/main/java/com/twilio/rest/serverless/v1/service/build/BuildStatus.java @@ -90,7 +90,7 @@ public static BuildStatus fromJson( private final String sid; private final String accountSid; private final String serviceSid; - private final Status status; + private final BuildStatus.Status status; private final URI url; @JsonCreator @@ -98,7 +98,7 @@ private BuildStatus( @JsonProperty("sid") final String sid, @JsonProperty("account_sid") final String accountSid, @JsonProperty("service_sid") final String serviceSid, - @JsonProperty("status") final Status status, + @JsonProperty("status") final BuildStatus.Status status, @JsonProperty("url") final URI url ) { this.sid = sid; @@ -120,7 +120,7 @@ public final String getServiceSid() { return this.serviceSid; } - public final Status getStatus() { + public final BuildStatus.Status getStatus() { return this.status; } diff --git a/src/main/java/com/twilio/rest/serverless/v1/service/function/FunctionVersion.java b/src/main/java/com/twilio/rest/serverless/v1/service/function/FunctionVersion.java index 46b6d6388f..af9004b2c4 100644 --- a/src/main/java/com/twilio/rest/serverless/v1/service/function/FunctionVersion.java +++ b/src/main/java/com/twilio/rest/serverless/v1/service/function/FunctionVersion.java @@ -108,7 +108,7 @@ public static FunctionVersion fromJson( private final String serviceSid; private final String functionSid; private final String path; - private final Visibility visibility; + private final FunctionVersion.Visibility visibility; private final ZonedDateTime dateCreated; private final URI url; private final Map links; @@ -120,7 +120,7 @@ private FunctionVersion( @JsonProperty("service_sid") final String serviceSid, @JsonProperty("function_sid") final String functionSid, @JsonProperty("path") final String path, - @JsonProperty("visibility") final Visibility visibility, + @JsonProperty("visibility") final FunctionVersion.Visibility visibility, @JsonProperty("date_created") final String dateCreated, @JsonProperty("url") final URI url, @JsonProperty("links") final Map links @@ -156,7 +156,7 @@ public final String getPath() { return this.path; } - public final Visibility getVisibility() { + public final FunctionVersion.Visibility getVisibility() { return this.visibility; } diff --git a/src/main/java/com/twilio/rest/studio/v1/Flow.java b/src/main/java/com/twilio/rest/studio/v1/Flow.java index 6a84d3a01b..e54921d904 100644 --- a/src/main/java/com/twilio/rest/studio/v1/Flow.java +++ b/src/main/java/com/twilio/rest/studio/v1/Flow.java @@ -99,7 +99,7 @@ public static Flow fromJson( private final String sid; private final String accountSid; private final String friendlyName; - private final Status status; + private final Flow.Status status; private final Integer version; private final ZonedDateTime dateCreated; private final ZonedDateTime dateUpdated; @@ -111,7 +111,7 @@ private Flow( @JsonProperty("sid") final String sid, @JsonProperty("account_sid") final String accountSid, @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("status") final Status status, + @JsonProperty("status") final Flow.Status status, @JsonProperty("version") final Integer version, @JsonProperty("date_created") final String dateCreated, @JsonProperty("date_updated") final String dateUpdated, @@ -141,7 +141,7 @@ public final String getFriendlyName() { return this.friendlyName; } - public final Status getStatus() { + public final Flow.Status getStatus() { return this.status; } diff --git a/src/main/java/com/twilio/rest/studio/v1/flow/Engagement.java b/src/main/java/com/twilio/rest/studio/v1/flow/Engagement.java index 99e517ac68..1b5c29b55b 100644 --- a/src/main/java/com/twilio/rest/studio/v1/flow/Engagement.java +++ b/src/main/java/com/twilio/rest/studio/v1/flow/Engagement.java @@ -116,7 +116,7 @@ public static Engagement fromJson( private final String contactSid; private final String contactChannelAddress; private final Map context; - private final Status status; + private final Engagement.Status status; private final ZonedDateTime dateCreated; private final ZonedDateTime dateUpdated; private final URI url; @@ -132,7 +132,7 @@ private Engagement( "contact_channel_address" ) final String contactChannelAddress, @JsonProperty("context") final Map context, - @JsonProperty("status") final Status status, + @JsonProperty("status") final Engagement.Status status, @JsonProperty("date_created") final String dateCreated, @JsonProperty("date_updated") final String dateUpdated, @JsonProperty("url") final URI url, @@ -175,7 +175,7 @@ public final Map getContext() { return this.context; } - public final Status getStatus() { + public final Engagement.Status getStatus() { return this.status; } diff --git a/src/main/java/com/twilio/rest/studio/v1/flow/Execution.java b/src/main/java/com/twilio/rest/studio/v1/flow/Execution.java index a79863d930..7806f0e36d 100644 --- a/src/main/java/com/twilio/rest/studio/v1/flow/Execution.java +++ b/src/main/java/com/twilio/rest/studio/v1/flow/Execution.java @@ -70,7 +70,7 @@ public static ExecutionReader reader(final String pathFlowSid) { public static ExecutionUpdater updater( final String pathFlowSid, final String pathSid, - final Status status + final Execution.Status status ) { return new ExecutionUpdater(pathFlowSid, pathSid, status); } @@ -124,7 +124,7 @@ public static Execution fromJson( private final String contactSid; private final String contactChannelAddress; private final Map context; - private final Status status; + private final Execution.Status status; private final ZonedDateTime dateCreated; private final ZonedDateTime dateUpdated; private final URI url; @@ -140,7 +140,7 @@ private Execution( "contact_channel_address" ) final String contactChannelAddress, @JsonProperty("context") final Map context, - @JsonProperty("status") final Status status, + @JsonProperty("status") final Execution.Status status, @JsonProperty("date_created") final String dateCreated, @JsonProperty("date_updated") final String dateUpdated, @JsonProperty("url") final URI url, @@ -183,7 +183,7 @@ public final Map getContext() { return this.context; } - public final Status getStatus() { + public final Execution.Status getStatus() { return this.status; } diff --git a/src/main/java/com/twilio/rest/studio/v2/Flow.java b/src/main/java/com/twilio/rest/studio/v2/Flow.java index 7677d433dd..989e733f30 100644 --- a/src/main/java/com/twilio/rest/studio/v2/Flow.java +++ b/src/main/java/com/twilio/rest/studio/v2/Flow.java @@ -44,7 +44,7 @@ public class Flow extends Resource { public static FlowCreator creator( final String friendlyName, - final Status status, + final Flow.Status status, final Object definition ) { return new FlowCreator(friendlyName, status, definition); @@ -64,7 +64,7 @@ public static FlowReader reader() { public static FlowUpdater updater( final String pathSid, - final Status status + final Flow.Status status ) { return new FlowUpdater(pathSid, status); } @@ -116,7 +116,7 @@ public static Flow fromJson( private final String accountSid; private final String friendlyName; private final Map definition; - private final Status status; + private final Flow.Status status; private final Integer revision; private final String commitMessage; private final Boolean valid; @@ -134,7 +134,7 @@ private Flow( @JsonProperty("account_sid") final String accountSid, @JsonProperty("friendly_name") final String friendlyName, @JsonProperty("definition") final Map definition, - @JsonProperty("status") final Status status, + @JsonProperty("status") final Flow.Status status, @JsonProperty("revision") final Integer revision, @JsonProperty("commit_message") final String commitMessage, @JsonProperty("valid") final Boolean valid, @@ -179,7 +179,7 @@ public final Map getDefinition() { return this.definition; } - public final Status getStatus() { + public final Flow.Status getStatus() { return this.status; } diff --git a/src/main/java/com/twilio/rest/studio/v2/FlowValidate.java b/src/main/java/com/twilio/rest/studio/v2/FlowValidate.java index 1024e89519..6eba3f66e9 100644 --- a/src/main/java/com/twilio/rest/studio/v2/FlowValidate.java +++ b/src/main/java/com/twilio/rest/studio/v2/FlowValidate.java @@ -38,7 +38,7 @@ public class FlowValidate extends Resource { public static FlowValidateUpdater updater( final String friendlyName, - final Status status, + final FlowValidate.Status status, final Object definition ) { return new FlowValidateUpdater(friendlyName, status, definition); diff --git a/src/main/java/com/twilio/rest/studio/v2/flow/Execution.java b/src/main/java/com/twilio/rest/studio/v2/flow/Execution.java index be8fa736c7..a39e679402 100644 --- a/src/main/java/com/twilio/rest/studio/v2/flow/Execution.java +++ b/src/main/java/com/twilio/rest/studio/v2/flow/Execution.java @@ -70,7 +70,7 @@ public static ExecutionReader reader(final String pathFlowSid) { public static ExecutionUpdater updater( final String pathFlowSid, final String pathSid, - final Status status + final Execution.Status status ) { return new ExecutionUpdater(pathFlowSid, pathSid, status); } @@ -123,7 +123,7 @@ public static Execution fromJson( private final String flowSid; private final String contactChannelAddress; private final Map context; - private final Status status; + private final Execution.Status status; private final ZonedDateTime dateCreated; private final ZonedDateTime dateUpdated; private final URI url; @@ -138,7 +138,7 @@ private Execution( "contact_channel_address" ) final String contactChannelAddress, @JsonProperty("context") final Map context, - @JsonProperty("status") final Status status, + @JsonProperty("status") final Execution.Status status, @JsonProperty("date_created") final String dateCreated, @JsonProperty("date_updated") final String dateUpdated, @JsonProperty("url") final URI url, @@ -176,7 +176,7 @@ public final Map getContext() { return this.context; } - public final Status getStatus() { + public final Execution.Status getStatus() { return this.status; } diff --git a/src/main/java/com/twilio/rest/studio/v2/flow/FlowRevision.java b/src/main/java/com/twilio/rest/studio/v2/flow/FlowRevision.java index 852a110e87..c92a4d7238 100644 --- a/src/main/java/com/twilio/rest/studio/v2/flow/FlowRevision.java +++ b/src/main/java/com/twilio/rest/studio/v2/flow/FlowRevision.java @@ -100,7 +100,7 @@ public static FlowRevision fromJson( private final String accountSid; private final String friendlyName; private final Map definition; - private final Status status; + private final FlowRevision.Status status; private final Integer revision; private final String commitMessage; private final Boolean valid; @@ -115,7 +115,7 @@ private FlowRevision( @JsonProperty("account_sid") final String accountSid, @JsonProperty("friendly_name") final String friendlyName, @JsonProperty("definition") final Map definition, - @JsonProperty("status") final Status status, + @JsonProperty("status") final FlowRevision.Status status, @JsonProperty("revision") final Integer revision, @JsonProperty("commit_message") final String commitMessage, @JsonProperty("valid") final Boolean valid, @@ -154,7 +154,7 @@ public final Map getDefinition() { return this.definition; } - public final Status getStatus() { + public final FlowRevision.Status getStatus() { return this.status; } diff --git a/src/main/java/com/twilio/rest/supersim/v1/EsimProfile.java b/src/main/java/com/twilio/rest/supersim/v1/EsimProfile.java index 311216484a..5d3e1b08eb 100644 --- a/src/main/java/com/twilio/rest/supersim/v1/EsimProfile.java +++ b/src/main/java/com/twilio/rest/supersim/v1/EsimProfile.java @@ -98,7 +98,7 @@ public static EsimProfile fromJson( private final String accountSid; private final String iccid; private final String simSid; - private final Status status; + private final EsimProfile.Status status; private final String eid; private final URI smdpPlusAddress; private final String matchingId; @@ -115,7 +115,7 @@ private EsimProfile( @JsonProperty("account_sid") final String accountSid, @JsonProperty("iccid") final String iccid, @JsonProperty("sim_sid") final String simSid, - @JsonProperty("status") final Status status, + @JsonProperty("status") final EsimProfile.Status status, @JsonProperty("eid") final String eid, @JsonProperty("smdp_plus_address") final URI smdpPlusAddress, @JsonProperty("matching_id") final String matchingId, @@ -158,7 +158,7 @@ public final String getSimSid() { return this.simSid; } - public final Status getStatus() { + public final EsimProfile.Status getStatus() { return this.status; } diff --git a/src/main/java/com/twilio/rest/supersim/v1/Fleet.java b/src/main/java/com/twilio/rest/supersim/v1/Fleet.java index 2b9adfe683..19c54502b2 100644 --- a/src/main/java/com/twilio/rest/supersim/v1/Fleet.java +++ b/src/main/java/com/twilio/rest/supersim/v1/Fleet.java @@ -107,7 +107,7 @@ public static Fleet fromJson( private final URI url; private final Boolean dataEnabled; private final Integer dataLimit; - private final DataMetering dataMetering; + private final Fleet.DataMetering dataMetering; private final Boolean smsCommandsEnabled; private final URI smsCommandsUrl; private final HttpMethod smsCommandsMethod; @@ -125,7 +125,7 @@ private Fleet( @JsonProperty("url") final URI url, @JsonProperty("data_enabled") final Boolean dataEnabled, @JsonProperty("data_limit") final Integer dataLimit, - @JsonProperty("data_metering") final DataMetering dataMetering, + @JsonProperty("data_metering") final Fleet.DataMetering dataMetering, @JsonProperty("sms_commands_enabled") final Boolean smsCommandsEnabled, @JsonProperty("sms_commands_url") final URI smsCommandsUrl, @JsonProperty("sms_commands_method") final HttpMethod smsCommandsMethod, @@ -184,7 +184,7 @@ public final Integer getDataLimit() { return this.dataLimit; } - public final DataMetering getDataMetering() { + public final Fleet.DataMetering getDataMetering() { return this.dataMetering; } diff --git a/src/main/java/com/twilio/rest/supersim/v1/IpCommand.java b/src/main/java/com/twilio/rest/supersim/v1/IpCommand.java index aedeae6f5e..da34f019a3 100644 --- a/src/main/java/com/twilio/rest/supersim/v1/IpCommand.java +++ b/src/main/java/com/twilio/rest/supersim/v1/IpCommand.java @@ -102,11 +102,11 @@ public static IpCommand fromJson( private final String accountSid; private final String simSid; private final String simIccid; - private final Status status; - private final Direction direction; + private final IpCommand.Status status; + private final IpCommand.Direction direction; private final String deviceIp; private final Integer devicePort; - private final PayloadType payloadType; + private final IpCommand.PayloadType payloadType; private final String payload; private final ZonedDateTime dateCreated; private final ZonedDateTime dateUpdated; @@ -118,11 +118,11 @@ private IpCommand( @JsonProperty("account_sid") final String accountSid, @JsonProperty("sim_sid") final String simSid, @JsonProperty("sim_iccid") final String simIccid, - @JsonProperty("status") final Status status, - @JsonProperty("direction") final Direction direction, + @JsonProperty("status") final IpCommand.Status status, + @JsonProperty("direction") final IpCommand.Direction direction, @JsonProperty("device_ip") final String deviceIp, @JsonProperty("device_port") final Integer devicePort, - @JsonProperty("payload_type") final PayloadType payloadType, + @JsonProperty("payload_type") final IpCommand.PayloadType payloadType, @JsonProperty("payload") final String payload, @JsonProperty("date_created") final String dateCreated, @JsonProperty("date_updated") final String dateUpdated, @@ -159,11 +159,11 @@ public final String getSimIccid() { return this.simIccid; } - public final Status getStatus() { + public final IpCommand.Status getStatus() { return this.status; } - public final Direction getDirection() { + public final IpCommand.Direction getDirection() { return this.direction; } @@ -175,7 +175,7 @@ public final Integer getDevicePort() { return this.devicePort; } - public final PayloadType getPayloadType() { + public final IpCommand.PayloadType getPayloadType() { return this.payloadType; } diff --git a/src/main/java/com/twilio/rest/supersim/v1/SettingsUpdate.java b/src/main/java/com/twilio/rest/supersim/v1/SettingsUpdate.java index 05a18f96f5..4d3dbc2f17 100644 --- a/src/main/java/com/twilio/rest/supersim/v1/SettingsUpdate.java +++ b/src/main/java/com/twilio/rest/supersim/v1/SettingsUpdate.java @@ -91,7 +91,7 @@ public static SettingsUpdate fromJson( private final String sid; private final String iccid; private final String simSid; - private final Status status; + private final SettingsUpdate.Status status; private final List> packages; private final ZonedDateTime dateCompleted; private final ZonedDateTime dateCreated; @@ -102,7 +102,7 @@ private SettingsUpdate( @JsonProperty("sid") final String sid, @JsonProperty("iccid") final String iccid, @JsonProperty("sim_sid") final String simSid, - @JsonProperty("status") final Status status, + @JsonProperty("status") final SettingsUpdate.Status status, @JsonProperty("packages") final List> packages, @JsonProperty("date_completed") final String dateCompleted, @JsonProperty("date_created") final String dateCreated, @@ -131,7 +131,7 @@ public final String getSimSid() { return this.simSid; } - public final Status getStatus() { + public final SettingsUpdate.Status getStatus() { return this.status; } diff --git a/src/main/java/com/twilio/rest/supersim/v1/Sim.java b/src/main/java/com/twilio/rest/supersim/v1/Sim.java index 2829cf05ba..072e1815fb 100644 --- a/src/main/java/com/twilio/rest/supersim/v1/Sim.java +++ b/src/main/java/com/twilio/rest/supersim/v1/Sim.java @@ -107,7 +107,7 @@ public static Sim fromJson( private final String uniqueName; private final String accountSid; private final String iccid; - private final Status status; + private final Sim.Status status; private final String fleetSid; private final ZonedDateTime dateCreated; private final ZonedDateTime dateUpdated; @@ -120,7 +120,7 @@ private Sim( @JsonProperty("unique_name") final String uniqueName, @JsonProperty("account_sid") final String accountSid, @JsonProperty("iccid") final String iccid, - @JsonProperty("status") final Status status, + @JsonProperty("status") final Sim.Status status, @JsonProperty("fleet_sid") final String fleetSid, @JsonProperty("date_created") final String dateCreated, @JsonProperty("date_updated") final String dateUpdated, @@ -155,7 +155,7 @@ public final String getIccid() { return this.iccid; } - public final Status getStatus() { + public final Sim.Status getStatus() { return this.status; } diff --git a/src/main/java/com/twilio/rest/supersim/v1/SmsCommand.java b/src/main/java/com/twilio/rest/supersim/v1/SmsCommand.java index 6e22dd0e57..ab1c698aa7 100644 --- a/src/main/java/com/twilio/rest/supersim/v1/SmsCommand.java +++ b/src/main/java/com/twilio/rest/supersim/v1/SmsCommand.java @@ -101,8 +101,8 @@ public static SmsCommand fromJson( private final String accountSid; private final String simSid; private final String payload; - private final Status status; - private final Direction direction; + private final SmsCommand.Status status; + private final SmsCommand.Direction direction; private final ZonedDateTime dateCreated; private final ZonedDateTime dateUpdated; private final URI url; @@ -113,8 +113,8 @@ private SmsCommand( @JsonProperty("account_sid") final String accountSid, @JsonProperty("sim_sid") final String simSid, @JsonProperty("payload") final String payload, - @JsonProperty("status") final Status status, - @JsonProperty("direction") final Direction direction, + @JsonProperty("status") final SmsCommand.Status status, + @JsonProperty("direction") final SmsCommand.Direction direction, @JsonProperty("date_created") final String dateCreated, @JsonProperty("date_updated") final String dateUpdated, @JsonProperty("url") final URI url @@ -146,11 +146,11 @@ public final String getPayload() { return this.payload; } - public final Status getStatus() { + public final SmsCommand.Status getStatus() { return this.status; } - public final Direction getDirection() { + public final SmsCommand.Direction getDirection() { return this.direction; } diff --git a/src/main/java/com/twilio/rest/supersim/v1/UsageRecord.java b/src/main/java/com/twilio/rest/supersim/v1/UsageRecord.java index dd18ce4249..2b7510e170 100644 --- a/src/main/java/com/twilio/rest/supersim/v1/UsageRecord.java +++ b/src/main/java/com/twilio/rest/supersim/v1/UsageRecord.java @@ -114,7 +114,7 @@ private UsageRecord( @JsonProperty("data_total") final Long dataTotal, @JsonProperty("data_total_billed") final BigDecimal dataTotalBilled, @JsonProperty("billed_unit") @JsonDeserialize( - using = CurrencyDeserializer.class + using = com.twilio.converter.CurrencyDeserializer.class ) final Currency billedUnit ) { this.accountSid = accountSid; diff --git a/src/main/java/com/twilio/rest/supersim/v1/sim/BillingPeriod.java b/src/main/java/com/twilio/rest/supersim/v1/sim/BillingPeriod.java index 2cd6b48046..d73822c5b7 100644 --- a/src/main/java/com/twilio/rest/supersim/v1/sim/BillingPeriod.java +++ b/src/main/java/com/twilio/rest/supersim/v1/sim/BillingPeriod.java @@ -90,7 +90,7 @@ public static BillingPeriod fromJson( private final String simSid; private final ZonedDateTime startTime; private final ZonedDateTime endTime; - private final BpType periodType; + private final BillingPeriod.BpType periodType; private final ZonedDateTime dateCreated; private final ZonedDateTime dateUpdated; @@ -101,7 +101,7 @@ private BillingPeriod( @JsonProperty("sim_sid") final String simSid, @JsonProperty("start_time") final String startTime, @JsonProperty("end_time") final String endTime, - @JsonProperty("period_type") final BpType periodType, + @JsonProperty("period_type") final BillingPeriod.BpType periodType, @JsonProperty("date_created") final String dateCreated, @JsonProperty("date_updated") final String dateUpdated ) { @@ -135,7 +135,7 @@ public final ZonedDateTime getEndTime() { return this.endTime; } - public final BpType getPeriodType() { + public final BillingPeriod.BpType getPeriodType() { return this.periodType; } diff --git a/src/main/java/com/twilio/rest/supersim/v1/sim/SimIpAddress.java b/src/main/java/com/twilio/rest/supersim/v1/sim/SimIpAddress.java index 88f3361ac7..2983f71ba4 100644 --- a/src/main/java/com/twilio/rest/supersim/v1/sim/SimIpAddress.java +++ b/src/main/java/com/twilio/rest/supersim/v1/sim/SimIpAddress.java @@ -84,14 +84,14 @@ public static SimIpAddress fromJson( } private final String ipAddress; - private final IpAddressVersion ipAddressVersion; + private final SimIpAddress.IpAddressVersion ipAddressVersion; @JsonCreator private SimIpAddress( @JsonProperty("ip_address") final String ipAddress, @JsonProperty( "ip_address_version" - ) final IpAddressVersion ipAddressVersion + ) final SimIpAddress.IpAddressVersion ipAddressVersion ) { this.ipAddress = ipAddress; this.ipAddressVersion = ipAddressVersion; @@ -101,7 +101,7 @@ public final String getIpAddress() { return this.ipAddress; } - public final IpAddressVersion getIpAddressVersion() { + public final SimIpAddress.IpAddressVersion getIpAddressVersion() { return this.ipAddressVersion; } diff --git a/src/main/java/com/twilio/rest/sync/v1/service/DocumentCreator.java b/src/main/java/com/twilio/rest/sync/v1/service/DocumentCreator.java index 3ad46deab0..9b5eca36b7 100644 --- a/src/main/java/com/twilio/rest/sync/v1/service/DocumentCreator.java +++ b/src/main/java/com/twilio/rest/sync/v1/service/DocumentCreator.java @@ -26,12 +26,14 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; +import java.util.Map; +import java.util.Map; public class DocumentCreator extends Creator { private String pathServiceSid; private String uniqueName; - private Object data; + private Map data; private Integer ttl; public DocumentCreator(final String pathServiceSid) { @@ -43,7 +45,7 @@ public DocumentCreator setUniqueName(final String uniqueName) { return this; } - public DocumentCreator setData(final Object data) { + public DocumentCreator setData(final Map data) { this.data = data; return this; } @@ -100,7 +102,7 @@ private void addPostParams(final Request request) { request.addPostParam("UniqueName", uniqueName); } if (data != null) { - request.addPostParam("Data", Converter.objectToJson(data)); + request.addPostParam("Data", Converter.mapToJson(data)); } if (ttl != null) { request.addPostParam("Ttl", ttl.toString()); diff --git a/src/main/java/com/twilio/rest/sync/v1/service/DocumentUpdater.java b/src/main/java/com/twilio/rest/sync/v1/service/DocumentUpdater.java index 8c4bb058d5..1561d4c8a2 100644 --- a/src/main/java/com/twilio/rest/sync/v1/service/DocumentUpdater.java +++ b/src/main/java/com/twilio/rest/sync/v1/service/DocumentUpdater.java @@ -25,13 +25,14 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; +import java.util.Map; public class DocumentUpdater extends Updater { private String pathServiceSid; private String pathSid; private String ifMatch; - private Object data; + private Map data; private Integer ttl; public DocumentUpdater(final String pathServiceSid, final String pathSid) { @@ -44,7 +45,7 @@ public DocumentUpdater setIfMatch(final String ifMatch) { return this; } - public DocumentUpdater setData(final Object data) { + public DocumentUpdater setData(final Map data) { this.data = data; return this; } @@ -100,7 +101,7 @@ public Document update(final TwilioRestClient client) { private void addPostParams(final Request request) { if (data != null) { - request.addPostParam("Data", Converter.objectToJson(data)); + request.addPostParam("Data", Converter.mapToJson(data)); } if (ttl != null) { request.addPostParam("Ttl", ttl.toString()); diff --git a/src/main/java/com/twilio/rest/sync/v1/service/synclist/SyncListItem.java b/src/main/java/com/twilio/rest/sync/v1/service/synclist/SyncListItem.java index 00bbcafebd..c0d70df086 100644 --- a/src/main/java/com/twilio/rest/sync/v1/service/synclist/SyncListItem.java +++ b/src/main/java/com/twilio/rest/sync/v1/service/synclist/SyncListItem.java @@ -44,7 +44,7 @@ public class SyncListItem extends Resource { public static SyncListItemCreator creator( final String pathServiceSid, final String pathListSid, - final Object data + final Map data ) { return new SyncListItemCreator(pathServiceSid, pathListSid, data); } diff --git a/src/main/java/com/twilio/rest/sync/v1/service/synclist/SyncListItemCreator.java b/src/main/java/com/twilio/rest/sync/v1/service/synclist/SyncListItemCreator.java index 4d8ac8f192..2af4101ee6 100644 --- a/src/main/java/com/twilio/rest/sync/v1/service/synclist/SyncListItemCreator.java +++ b/src/main/java/com/twilio/rest/sync/v1/service/synclist/SyncListItemCreator.java @@ -26,12 +26,14 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; +import java.util.Map; +import java.util.Map; public class SyncListItemCreator extends Creator { private String pathServiceSid; private String pathListSid; - private Object data; + private Map data; private Integer ttl; private Integer itemTtl; private Integer collectionTtl; @@ -39,14 +41,14 @@ public class SyncListItemCreator extends Creator { public SyncListItemCreator( final String pathServiceSid, final String pathListSid, - final Object data + final Map data ) { this.pathServiceSid = pathServiceSid; this.pathListSid = pathListSid; this.data = data; } - public SyncListItemCreator setData(final Object data) { + public SyncListItemCreator setData(final Map data) { this.data = data; return this; } @@ -112,7 +114,7 @@ public SyncListItem create(final TwilioRestClient client) { private void addPostParams(final Request request) { if (data != null) { - request.addPostParam("Data", Converter.objectToJson(data)); + request.addPostParam("Data", Converter.mapToJson(data)); } if (ttl != null) { request.addPostParam("Ttl", ttl.toString()); diff --git a/src/main/java/com/twilio/rest/sync/v1/service/synclist/SyncListItemUpdater.java b/src/main/java/com/twilio/rest/sync/v1/service/synclist/SyncListItemUpdater.java index 24dde562ca..df538d9384 100644 --- a/src/main/java/com/twilio/rest/sync/v1/service/synclist/SyncListItemUpdater.java +++ b/src/main/java/com/twilio/rest/sync/v1/service/synclist/SyncListItemUpdater.java @@ -25,6 +25,7 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; +import java.util.Map; public class SyncListItemUpdater extends Updater { @@ -32,7 +33,7 @@ public class SyncListItemUpdater extends Updater { private String pathListSid; private Integer pathIndex; private String ifMatch; - private Object data; + private Map data; private Integer ttl; private Integer itemTtl; private Integer collectionTtl; @@ -52,7 +53,7 @@ public SyncListItemUpdater setIfMatch(final String ifMatch) { return this; } - public SyncListItemUpdater setData(final Object data) { + public SyncListItemUpdater setData(final Map data) { this.data = data; return this; } @@ -119,7 +120,7 @@ public SyncListItem update(final TwilioRestClient client) { private void addPostParams(final Request request) { if (data != null) { - request.addPostParam("Data", Converter.objectToJson(data)); + request.addPostParam("Data", Converter.mapToJson(data)); } if (ttl != null) { request.addPostParam("Ttl", ttl.toString()); diff --git a/src/main/java/com/twilio/rest/sync/v1/service/syncmap/SyncMapItem.java b/src/main/java/com/twilio/rest/sync/v1/service/syncmap/SyncMapItem.java index f134d6fb0c..e2c25935cf 100644 --- a/src/main/java/com/twilio/rest/sync/v1/service/syncmap/SyncMapItem.java +++ b/src/main/java/com/twilio/rest/sync/v1/service/syncmap/SyncMapItem.java @@ -45,7 +45,7 @@ public static SyncMapItemCreator creator( final String pathServiceSid, final String pathMapSid, final String key, - final Object data + final Map data ) { return new SyncMapItemCreator(pathServiceSid, pathMapSid, key, data); } diff --git a/src/main/java/com/twilio/rest/sync/v1/service/syncmap/SyncMapItemCreator.java b/src/main/java/com/twilio/rest/sync/v1/service/syncmap/SyncMapItemCreator.java index c85bdbfeb9..095e615ca2 100644 --- a/src/main/java/com/twilio/rest/sync/v1/service/syncmap/SyncMapItemCreator.java +++ b/src/main/java/com/twilio/rest/sync/v1/service/syncmap/SyncMapItemCreator.java @@ -26,13 +26,15 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; +import java.util.Map; +import java.util.Map; public class SyncMapItemCreator extends Creator { private String pathServiceSid; private String pathMapSid; private String key; - private Object data; + private Map data; private Integer ttl; private Integer itemTtl; private Integer collectionTtl; @@ -41,7 +43,7 @@ public SyncMapItemCreator( final String pathServiceSid, final String pathMapSid, final String key, - final Object data + final Map data ) { this.pathServiceSid = pathServiceSid; this.pathMapSid = pathMapSid; @@ -54,7 +56,7 @@ public SyncMapItemCreator setKey(final String key) { return this; } - public SyncMapItemCreator setData(final Object data) { + public SyncMapItemCreator setData(final Map data) { this.data = data; return this; } @@ -124,7 +126,7 @@ private void addPostParams(final Request request) { request.addPostParam("Key", key); } if (data != null) { - request.addPostParam("Data", Converter.objectToJson(data)); + request.addPostParam("Data", Converter.mapToJson(data)); } if (ttl != null) { request.addPostParam("Ttl", ttl.toString()); diff --git a/src/main/java/com/twilio/rest/sync/v1/service/syncmap/SyncMapItemUpdater.java b/src/main/java/com/twilio/rest/sync/v1/service/syncmap/SyncMapItemUpdater.java index b0b1a151c0..f9cb5af292 100644 --- a/src/main/java/com/twilio/rest/sync/v1/service/syncmap/SyncMapItemUpdater.java +++ b/src/main/java/com/twilio/rest/sync/v1/service/syncmap/SyncMapItemUpdater.java @@ -25,6 +25,7 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; +import java.util.Map; public class SyncMapItemUpdater extends Updater { @@ -32,7 +33,7 @@ public class SyncMapItemUpdater extends Updater { private String pathMapSid; private String pathKey; private String ifMatch; - private Object data; + private Map data; private Integer ttl; private Integer itemTtl; private Integer collectionTtl; @@ -52,7 +53,7 @@ public SyncMapItemUpdater setIfMatch(final String ifMatch) { return this; } - public SyncMapItemUpdater setData(final Object data) { + public SyncMapItemUpdater setData(final Map data) { this.data = data; return this; } @@ -119,7 +120,7 @@ public SyncMapItem update(final TwilioRestClient client) { private void addPostParams(final Request request) { if (data != null) { - request.addPostParam("Data", Converter.objectToJson(data)); + request.addPostParam("Data", Converter.mapToJson(data)); } if (ttl != null) { request.addPostParam("Ttl", ttl.toString()); diff --git a/src/main/java/com/twilio/rest/sync/v1/service/syncstream/StreamMessage.java b/src/main/java/com/twilio/rest/sync/v1/service/syncstream/StreamMessage.java index b787e9d5a1..7191f3acc2 100644 --- a/src/main/java/com/twilio/rest/sync/v1/service/syncstream/StreamMessage.java +++ b/src/main/java/com/twilio/rest/sync/v1/service/syncstream/StreamMessage.java @@ -40,7 +40,7 @@ public class StreamMessage extends Resource { public static StreamMessageCreator creator( final String pathServiceSid, final String pathStreamSid, - final Object data + final Map data ) { return new StreamMessageCreator(pathServiceSid, pathStreamSid, data); } diff --git a/src/main/java/com/twilio/rest/sync/v1/service/syncstream/StreamMessageCreator.java b/src/main/java/com/twilio/rest/sync/v1/service/syncstream/StreamMessageCreator.java index 015002f303..5739a6e69d 100644 --- a/src/main/java/com/twilio/rest/sync/v1/service/syncstream/StreamMessageCreator.java +++ b/src/main/java/com/twilio/rest/sync/v1/service/syncstream/StreamMessageCreator.java @@ -26,24 +26,26 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; +import java.util.Map; +import java.util.Map; public class StreamMessageCreator extends Creator { private String pathServiceSid; private String pathStreamSid; - private Object data; + private Map data; public StreamMessageCreator( final String pathServiceSid, final String pathStreamSid, - final Object data + final Map data ) { this.pathServiceSid = pathServiceSid; this.pathStreamSid = pathStreamSid; this.data = data; } - public StreamMessageCreator setData(final Object data) { + public StreamMessageCreator setData(final Map data) { this.data = data; return this; } @@ -98,7 +100,7 @@ public StreamMessage create(final TwilioRestClient client) { private void addPostParams(final Request request) { if (data != null) { - request.addPostParam("Data", Converter.objectToJson(data)); + request.addPostParam("Data", Converter.mapToJson(data)); } } } diff --git a/src/main/java/com/twilio/rest/taskrouter/v1/Workspace.java b/src/main/java/com/twilio/rest/taskrouter/v1/Workspace.java index 9d2660f685..4ab41a8013 100644 --- a/src/main/java/com/twilio/rest/taskrouter/v1/Workspace.java +++ b/src/main/java/com/twilio/rest/taskrouter/v1/Workspace.java @@ -116,7 +116,7 @@ public static Workspace fromJson( private final String sid; private final String timeoutActivityName; private final String timeoutActivitySid; - private final QueueOrder prioritizeQueueOrder; + private final Workspace.QueueOrder prioritizeQueueOrder; private final URI url; private final Map links; @@ -136,7 +136,7 @@ private Workspace( @JsonProperty("timeout_activity_sid") final String timeoutActivitySid, @JsonProperty( "prioritize_queue_order" - ) final QueueOrder prioritizeQueueOrder, + ) final Workspace.QueueOrder prioritizeQueueOrder, @JsonProperty("url") final URI url, @JsonProperty("links") final Map links ) { @@ -205,7 +205,7 @@ public final String getTimeoutActivitySid() { return this.timeoutActivitySid; } - public final QueueOrder getPrioritizeQueueOrder() { + public final Workspace.QueueOrder getPrioritizeQueueOrder() { return this.prioritizeQueueOrder; } diff --git a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/Task.java b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/Task.java index 09f55e1d04..5179bf0053 100644 --- a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/Task.java +++ b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/Task.java @@ -115,7 +115,7 @@ public static Task fromJson( private final String accountSid; private final Integer age; - private final Status assignmentStatus; + private final Task.Status assignmentStatus; private final String attributes; private final String addons; private final ZonedDateTime dateCreated; @@ -142,7 +142,7 @@ public static Task fromJson( private Task( @JsonProperty("account_sid") final String accountSid, @JsonProperty("age") final Integer age, - @JsonProperty("assignment_status") final Status assignmentStatus, + @JsonProperty("assignment_status") final Task.Status assignmentStatus, @JsonProperty("attributes") final String attributes, @JsonProperty("addons") final String addons, @JsonProperty("date_created") final String dateCreated, @@ -209,7 +209,7 @@ public final Integer getAge() { return this.age; } - public final Status getAssignmentStatus() { + public final Task.Status getAssignmentStatus() { return this.assignmentStatus; } diff --git a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/TaskQueue.java b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/TaskQueue.java index 28550cc4ce..15f1dfabef 100644 --- a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/TaskQueue.java +++ b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/TaskQueue.java @@ -127,7 +127,7 @@ public static TaskQueue fromJson( private final String reservationActivityName; private final String sid; private final String targetWorkers; - private final TaskOrder taskOrder; + private final TaskQueue.TaskOrder taskOrder; private final URI url; private final String workspaceSid; private final Map links; @@ -153,7 +153,7 @@ private TaskQueue( ) final String reservationActivityName, @JsonProperty("sid") final String sid, @JsonProperty("target_workers") final String targetWorkers, - @JsonProperty("task_order") final TaskOrder taskOrder, + @JsonProperty("task_order") final TaskQueue.TaskOrder taskOrder, @JsonProperty("url") final URI url, @JsonProperty("workspace_sid") final String workspaceSid, @JsonProperty("links") final Map links @@ -219,7 +219,7 @@ public final String getTargetWorkers() { return this.targetWorkers; } - public final TaskOrder getTaskOrder() { + public final TaskQueue.TaskOrder getTaskOrder() { return this.taskOrder; } diff --git a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/task/Reservation.java b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/task/Reservation.java index 14ae6d69c9..e3755218cc 100644 --- a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/task/Reservation.java +++ b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/task/Reservation.java @@ -110,7 +110,7 @@ public static Reservation fromJson( private final String accountSid; private final ZonedDateTime dateCreated; private final ZonedDateTime dateUpdated; - private final Status reservationStatus; + private final Reservation.Status reservationStatus; private final String sid; private final String taskSid; private final String workerName; @@ -124,7 +124,9 @@ private Reservation( @JsonProperty("account_sid") final String accountSid, @JsonProperty("date_created") final String dateCreated, @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("reservation_status") final Status reservationStatus, + @JsonProperty( + "reservation_status" + ) final Reservation.Status reservationStatus, @JsonProperty("sid") final String sid, @JsonProperty("task_sid") final String taskSid, @JsonProperty("worker_name") final String workerName, @@ -158,7 +160,7 @@ public final ZonedDateTime getDateUpdated() { return this.dateUpdated; } - public final Status getReservationStatus() { + public final Reservation.Status getReservationStatus() { return this.reservationStatus; } diff --git a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/worker/Reservation.java b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/worker/Reservation.java index 89c4a7f9d4..3c6c7d48d6 100644 --- a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/worker/Reservation.java +++ b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/worker/Reservation.java @@ -110,7 +110,7 @@ public static Reservation fromJson( private final String accountSid; private final ZonedDateTime dateCreated; private final ZonedDateTime dateUpdated; - private final Status reservationStatus; + private final Reservation.Status reservationStatus; private final String sid; private final String taskSid; private final String workerName; @@ -124,7 +124,9 @@ private Reservation( @JsonProperty("account_sid") final String accountSid, @JsonProperty("date_created") final String dateCreated, @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("reservation_status") final Status reservationStatus, + @JsonProperty( + "reservation_status" + ) final Reservation.Status reservationStatus, @JsonProperty("sid") final String sid, @JsonProperty("task_sid") final String taskSid, @JsonProperty("worker_name") final String workerName, @@ -158,7 +160,7 @@ public final ZonedDateTime getDateUpdated() { return this.dateUpdated; } - public final Status getReservationStatus() { + public final Reservation.Status getReservationStatus() { return this.reservationStatus; } diff --git a/src/main/java/com/twilio/rest/trunking/v1/Trunk.java b/src/main/java/com/twilio/rest/trunking/v1/Trunk.java index 48919cb239..6ddece0cab 100644 --- a/src/main/java/com/twilio/rest/trunking/v1/Trunk.java +++ b/src/main/java/com/twilio/rest/trunking/v1/Trunk.java @@ -41,7 +41,7 @@ @ToString public class Trunk extends Resource { - private static final long serialVersionUID = 225938897286327L; + private static final long serialVersionUID = 232204827569278L; public static TrunkCreator creator() { return new TrunkCreator(); @@ -113,10 +113,11 @@ public static Trunk fromJson( private final String friendlyName; private final Boolean secure; private final Map recording; - private final TransferSetting transferMode; - private final TransferCallerId transferCallerId; + private final Trunk.TransferSetting transferMode; + private final Trunk.TransferCallerId transferCallerId; private final Boolean cnamLookupEnabled; private final String authType; + private final Boolean symmetricRtpEnabled; private final List authTypeSet; private final ZonedDateTime dateCreated; private final ZonedDateTime dateUpdated; @@ -135,12 +136,15 @@ private Trunk( @JsonProperty("friendly_name") final String friendlyName, @JsonProperty("secure") final Boolean secure, @JsonProperty("recording") final Map recording, - @JsonProperty("transfer_mode") final TransferSetting transferMode, + @JsonProperty("transfer_mode") final Trunk.TransferSetting transferMode, @JsonProperty( "transfer_caller_id" - ) final TransferCallerId transferCallerId, + ) final Trunk.TransferCallerId transferCallerId, @JsonProperty("cnam_lookup_enabled") final Boolean cnamLookupEnabled, @JsonProperty("auth_type") final String authType, + @JsonProperty( + "symmetric_rtp_enabled" + ) final Boolean symmetricRtpEnabled, @JsonProperty("auth_type_set") final List authTypeSet, @JsonProperty("date_created") final String dateCreated, @JsonProperty("date_updated") final String dateUpdated, @@ -159,6 +163,7 @@ private Trunk( this.transferCallerId = transferCallerId; this.cnamLookupEnabled = cnamLookupEnabled; this.authType = authType; + this.symmetricRtpEnabled = symmetricRtpEnabled; this.authTypeSet = authTypeSet; this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); @@ -195,11 +200,11 @@ public final Map getRecording() { return this.recording; } - public final TransferSetting getTransferMode() { + public final Trunk.TransferSetting getTransferMode() { return this.transferMode; } - public final TransferCallerId getTransferCallerId() { + public final Trunk.TransferCallerId getTransferCallerId() { return this.transferCallerId; } @@ -211,6 +216,10 @@ public final String getAuthType() { return this.authType; } + public final Boolean getSymmetricRtpEnabled() { + return this.symmetricRtpEnabled; + } + public final List getAuthTypeSet() { return this.authTypeSet; } @@ -262,6 +271,7 @@ public boolean equals(final Object o) { Objects.equals(transferCallerId, other.transferCallerId) && Objects.equals(cnamLookupEnabled, other.cnamLookupEnabled) && Objects.equals(authType, other.authType) && + Objects.equals(symmetricRtpEnabled, other.symmetricRtpEnabled) && Objects.equals(authTypeSet, other.authTypeSet) && Objects.equals(dateCreated, other.dateCreated) && Objects.equals(dateUpdated, other.dateUpdated) && @@ -285,6 +295,7 @@ public int hashCode() { transferCallerId, cnamLookupEnabled, authType, + symmetricRtpEnabled, authTypeSet, dateCreated, dateUpdated, diff --git a/src/main/java/com/twilio/rest/trunking/v1/trunk/PhoneNumber.java b/src/main/java/com/twilio/rest/trunking/v1/trunk/PhoneNumber.java index beef3087ff..733b18311c 100644 --- a/src/main/java/com/twilio/rest/trunking/v1/trunk/PhoneNumber.java +++ b/src/main/java/com/twilio/rest/trunking/v1/trunk/PhoneNumber.java @@ -111,7 +111,7 @@ public static PhoneNumber fromJson( } private final String accountSid; - private final AddressRequirement addressRequirements; + private final PhoneNumber.AddressRequirement addressRequirements; private final String apiVersion; private final Boolean beta; private final Map capabilities; @@ -142,7 +142,7 @@ private PhoneNumber( @JsonProperty("account_sid") final String accountSid, @JsonProperty( "address_requirements" - ) final AddressRequirement addressRequirements, + ) final PhoneNumber.AddressRequirement addressRequirements, @JsonProperty("api_version") final String apiVersion, @JsonProperty("beta") final Boolean beta, @JsonProperty("capabilities") final Map capabilities, @@ -208,7 +208,7 @@ public final String getAccountSid() { return this.accountSid; } - public final AddressRequirement getAddressRequirements() { + public final PhoneNumber.AddressRequirement getAddressRequirements() { return this.addressRequirements; } diff --git a/src/main/java/com/twilio/rest/trunking/v1/trunk/Recording.java b/src/main/java/com/twilio/rest/trunking/v1/trunk/Recording.java index 709ccb95c9..022e65d0b9 100644 --- a/src/main/java/com/twilio/rest/trunking/v1/trunk/Recording.java +++ b/src/main/java/com/twilio/rest/trunking/v1/trunk/Recording.java @@ -87,23 +87,23 @@ public static Recording fromJson( } } - private final RecordingMode mode; - private final RecordingTrim trim; + private final Recording.RecordingMode mode; + private final Recording.RecordingTrim trim; @JsonCreator private Recording( - @JsonProperty("mode") final RecordingMode mode, - @JsonProperty("trim") final RecordingTrim trim + @JsonProperty("mode") final Recording.RecordingMode mode, + @JsonProperty("trim") final Recording.RecordingTrim trim ) { this.mode = mode; this.trim = trim; } - public final RecordingMode getMode() { + public final Recording.RecordingMode getMode() { return this.mode; } - public final RecordingTrim getTrim() { + public final Recording.RecordingTrim getTrim() { return this.trim; } diff --git a/src/main/java/com/twilio/rest/trusthub/v1/ComplianceRegistrationInquiries.java b/src/main/java/com/twilio/rest/trusthub/v1/ComplianceRegistrationInquiries.java index 76a614b6e0..b633de24f7 100644 --- a/src/main/java/com/twilio/rest/trusthub/v1/ComplianceRegistrationInquiries.java +++ b/src/main/java/com/twilio/rest/trusthub/v1/ComplianceRegistrationInquiries.java @@ -38,8 +38,8 @@ public class ComplianceRegistrationInquiries extends Resource { private static final long serialVersionUID = 153862952025802L; public static ComplianceRegistrationInquiriesCreator creator( - final EndUserType endUserType, - final PhoneNumberType phoneNumberType + final ComplianceRegistrationInquiries.EndUserType endUserType, + final ComplianceRegistrationInquiries.PhoneNumberType phoneNumberType ) { return new ComplianceRegistrationInquiriesCreator( endUserType, diff --git a/src/main/java/com/twilio/rest/trusthub/v1/CustomerProfiles.java b/src/main/java/com/twilio/rest/trusthub/v1/CustomerProfiles.java index 7225389bcd..9217f2067b 100644 --- a/src/main/java/com/twilio/rest/trusthub/v1/CustomerProfiles.java +++ b/src/main/java/com/twilio/rest/trusthub/v1/CustomerProfiles.java @@ -113,7 +113,7 @@ public static CustomerProfiles fromJson( private final String accountSid; private final String policySid; private final String friendlyName; - private final Status status; + private final CustomerProfiles.Status status; private final ZonedDateTime validUntil; private final String email; private final URI statusCallback; @@ -129,7 +129,7 @@ private CustomerProfiles( @JsonProperty("account_sid") final String accountSid, @JsonProperty("policy_sid") final String policySid, @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("status") final Status status, + @JsonProperty("status") final CustomerProfiles.Status status, @JsonProperty("valid_until") final String validUntil, @JsonProperty("email") final String email, @JsonProperty("status_callback") final URI statusCallback, @@ -170,7 +170,7 @@ public final String getFriendlyName() { return this.friendlyName; } - public final Status getStatus() { + public final CustomerProfiles.Status getStatus() { return this.status; } diff --git a/src/main/java/com/twilio/rest/trusthub/v1/SupportingDocument.java b/src/main/java/com/twilio/rest/trusthub/v1/SupportingDocument.java index e9c68d404c..fcb0e31305 100644 --- a/src/main/java/com/twilio/rest/trusthub/v1/SupportingDocument.java +++ b/src/main/java/com/twilio/rest/trusthub/v1/SupportingDocument.java @@ -111,7 +111,7 @@ public static SupportingDocument fromJson( private final String accountSid; private final String friendlyName; private final String mimeType; - private final Status status; + private final SupportingDocument.Status status; private final String type; private final Map attributes; private final ZonedDateTime dateCreated; @@ -124,7 +124,7 @@ private SupportingDocument( @JsonProperty("account_sid") final String accountSid, @JsonProperty("friendly_name") final String friendlyName, @JsonProperty("mime_type") final String mimeType, - @JsonProperty("status") final Status status, + @JsonProperty("status") final SupportingDocument.Status status, @JsonProperty("type") final String type, @JsonProperty("attributes") final Map attributes, @JsonProperty("date_created") final String dateCreated, @@ -159,7 +159,7 @@ public final String getMimeType() { return this.mimeType; } - public final Status getStatus() { + public final SupportingDocument.Status getStatus() { return this.status; } diff --git a/src/main/java/com/twilio/rest/trusthub/v1/TrustProducts.java b/src/main/java/com/twilio/rest/trusthub/v1/TrustProducts.java index 97afa46975..a1be16ed7e 100644 --- a/src/main/java/com/twilio/rest/trusthub/v1/TrustProducts.java +++ b/src/main/java/com/twilio/rest/trusthub/v1/TrustProducts.java @@ -113,7 +113,7 @@ public static TrustProducts fromJson( private final String accountSid; private final String policySid; private final String friendlyName; - private final Status status; + private final TrustProducts.Status status; private final ZonedDateTime validUntil; private final String email; private final URI statusCallback; @@ -129,7 +129,7 @@ private TrustProducts( @JsonProperty("account_sid") final String accountSid, @JsonProperty("policy_sid") final String policySid, @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("status") final Status status, + @JsonProperty("status") final TrustProducts.Status status, @JsonProperty("valid_until") final String validUntil, @JsonProperty("email") final String email, @JsonProperty("status_callback") final URI statusCallback, @@ -170,7 +170,7 @@ public final String getFriendlyName() { return this.friendlyName; } - public final Status getStatus() { + public final TrustProducts.Status getStatus() { return this.status; } diff --git a/src/main/java/com/twilio/rest/trusthub/v1/customerprofiles/CustomerProfilesEvaluations.java b/src/main/java/com/twilio/rest/trusthub/v1/customerprofiles/CustomerProfilesEvaluations.java index 04af325a8b..27d0116ac0 100644 --- a/src/main/java/com/twilio/rest/trusthub/v1/customerprofiles/CustomerProfilesEvaluations.java +++ b/src/main/java/com/twilio/rest/trusthub/v1/customerprofiles/CustomerProfilesEvaluations.java @@ -121,7 +121,7 @@ public static CustomerProfilesEvaluations fromJson( private final String accountSid; private final String policySid; private final String customerProfileSid; - private final Status status; + private final CustomerProfilesEvaluations.Status status; private final List> results; private final ZonedDateTime dateCreated; private final URI url; @@ -132,7 +132,7 @@ private CustomerProfilesEvaluations( @JsonProperty("account_sid") final String accountSid, @JsonProperty("policy_sid") final String policySid, @JsonProperty("customer_profile_sid") final String customerProfileSid, - @JsonProperty("status") final Status status, + @JsonProperty("status") final CustomerProfilesEvaluations.Status status, @JsonProperty("results") final List> results, @JsonProperty("date_created") final String dateCreated, @JsonProperty("url") final URI url @@ -163,7 +163,7 @@ public final String getCustomerProfileSid() { return this.customerProfileSid; } - public final Status getStatus() { + public final CustomerProfilesEvaluations.Status getStatus() { return this.status; } diff --git a/src/main/java/com/twilio/rest/trusthub/v1/trustproducts/TrustProductsEvaluations.java b/src/main/java/com/twilio/rest/trusthub/v1/trustproducts/TrustProductsEvaluations.java index 9c10b40232..c2aee8cf6b 100644 --- a/src/main/java/com/twilio/rest/trusthub/v1/trustproducts/TrustProductsEvaluations.java +++ b/src/main/java/com/twilio/rest/trusthub/v1/trustproducts/TrustProductsEvaluations.java @@ -115,7 +115,7 @@ public static TrustProductsEvaluations fromJson( private final String accountSid; private final String policySid; private final String trustProductSid; - private final Status status; + private final TrustProductsEvaluations.Status status; private final List> results; private final ZonedDateTime dateCreated; private final URI url; @@ -126,7 +126,7 @@ private TrustProductsEvaluations( @JsonProperty("account_sid") final String accountSid, @JsonProperty("policy_sid") final String policySid, @JsonProperty("trust_product_sid") final String trustProductSid, - @JsonProperty("status") final Status status, + @JsonProperty("status") final TrustProductsEvaluations.Status status, @JsonProperty("results") final List> results, @JsonProperty("date_created") final String dateCreated, @JsonProperty("url") final URI url @@ -157,7 +157,7 @@ public final String getTrustProductSid() { return this.trustProductSid; } - public final Status getStatus() { + public final TrustProductsEvaluations.Status getStatus() { return this.status; } diff --git a/src/main/java/com/twilio/rest/verify/v2/Form.java b/src/main/java/com/twilio/rest/verify/v2/Form.java index 0511a234b7..c6f82158f9 100644 --- a/src/main/java/com/twilio/rest/verify/v2/Form.java +++ b/src/main/java/com/twilio/rest/verify/v2/Form.java @@ -39,7 +39,7 @@ public class Form extends Resource { private static final long serialVersionUID = 202517967097226L; - public static FormFetcher fetcher(final FormTypes formType) { + public static FormFetcher fetcher(final Form.FormTypes formType) { return new FormFetcher(formType); } @@ -86,14 +86,14 @@ public static Form fromJson( } } - private final FormTypes formType; + private final Form.FormTypes formType; private final Map forms; private final Map formMeta; private final URI url; @JsonCreator private Form( - @JsonProperty("form_type") final FormTypes formType, + @JsonProperty("form_type") final Form.FormTypes formType, @JsonProperty("forms") final Map forms, @JsonProperty("form_meta") final Map formMeta, @JsonProperty("url") final URI url @@ -104,7 +104,7 @@ private Form( this.url = url; } - public final FormTypes getFormType() { + public final Form.FormTypes getFormType() { return this.formType; } diff --git a/src/main/java/com/twilio/rest/verify/v2/VerificationAttempt.java b/src/main/java/com/twilio/rest/verify/v2/VerificationAttempt.java index de89169b16..5fc710aaf4 100644 --- a/src/main/java/com/twilio/rest/verify/v2/VerificationAttempt.java +++ b/src/main/java/com/twilio/rest/verify/v2/VerificationAttempt.java @@ -98,8 +98,8 @@ public static VerificationAttempt fromJson( private final String verificationSid; private final ZonedDateTime dateCreated; private final ZonedDateTime dateUpdated; - private final ConversionStatus conversionStatus; - private final Channels channel; + private final VerificationAttempt.ConversionStatus conversionStatus; + private final VerificationAttempt.Channels channel; private final Map price; private final Map channelData; private final URI url; @@ -114,8 +114,8 @@ private VerificationAttempt( @JsonProperty("date_updated") final String dateUpdated, @JsonProperty( "conversion_status" - ) final ConversionStatus conversionStatus, - @JsonProperty("channel") final Channels channel, + ) final VerificationAttempt.ConversionStatus conversionStatus, + @JsonProperty("channel") final VerificationAttempt.Channels channel, @JsonProperty("price") final Map price, @JsonProperty("channel_data") final Map channelData, @JsonProperty("url") final URI url @@ -157,11 +157,11 @@ public final ZonedDateTime getDateUpdated() { return this.dateUpdated; } - public final ConversionStatus getConversionStatus() { + public final VerificationAttempt.ConversionStatus getConversionStatus() { return this.conversionStatus; } - public final Channels getChannel() { + public final VerificationAttempt.Channels getChannel() { return this.channel; } @@ -246,8 +246,7 @@ public enum Channels { CALL("call"), EMAIL("email"), WHATSAPP("whatsapp"), - RBM("rbm"), - SNA("sna"); + RBM("rbm"); private final String value; diff --git a/src/main/java/com/twilio/rest/verify/v2/VerificationAttemptsSummary.java b/src/main/java/com/twilio/rest/verify/v2/VerificationAttemptsSummary.java index 5566ca5174..925f76b700 100644 --- a/src/main/java/com/twilio/rest/verify/v2/VerificationAttemptsSummary.java +++ b/src/main/java/com/twilio/rest/verify/v2/VerificationAttemptsSummary.java @@ -172,7 +172,8 @@ public enum Channels { SMS("sms"), CALL("call"), EMAIL("email"), - WHATSAPP("whatsapp"); + WHATSAPP("whatsapp"), + RBM("rbm"); private final String value; diff --git a/src/main/java/com/twilio/rest/verify/v2/service/AccessToken.java b/src/main/java/com/twilio/rest/verify/v2/service/AccessToken.java index 64f406878e..e8ed33b57d 100644 --- a/src/main/java/com/twilio/rest/verify/v2/service/AccessToken.java +++ b/src/main/java/com/twilio/rest/verify/v2/service/AccessToken.java @@ -42,7 +42,7 @@ public class AccessToken extends Resource { public static AccessTokenCreator creator( final String pathServiceSid, final String identity, - final FactorTypes factorType + final AccessToken.FactorTypes factorType ) { return new AccessTokenCreator(pathServiceSid, identity, factorType); } @@ -101,7 +101,7 @@ public static AccessToken fromJson( private final String accountSid; private final String serviceSid; private final String entityIdentity; - private final FactorTypes factorType; + private final AccessToken.FactorTypes factorType; private final String factorFriendlyName; private final String token; private final URI url; @@ -114,7 +114,7 @@ private AccessToken( @JsonProperty("account_sid") final String accountSid, @JsonProperty("service_sid") final String serviceSid, @JsonProperty("entity_identity") final String entityIdentity, - @JsonProperty("factor_type") final FactorTypes factorType, + @JsonProperty("factor_type") final AccessToken.FactorTypes factorType, @JsonProperty("factor_friendly_name") final String factorFriendlyName, @JsonProperty("token") final String token, @JsonProperty("url") final URI url, @@ -149,7 +149,7 @@ public final String getEntityIdentity() { return this.entityIdentity; } - public final FactorTypes getFactorType() { + public final AccessToken.FactorTypes getFactorType() { return this.factorType; } diff --git a/src/main/java/com/twilio/rest/verify/v2/service/Verification.java b/src/main/java/com/twilio/rest/verify/v2/service/Verification.java index c46be724eb..913b0b4db9 100644 --- a/src/main/java/com/twilio/rest/verify/v2/service/Verification.java +++ b/src/main/java/com/twilio/rest/verify/v2/service/Verification.java @@ -60,7 +60,7 @@ public static VerificationFetcher fetcher( public static VerificationUpdater updater( final String pathServiceSid, final String pathSid, - final Status status + final Verification.Status status ) { return new VerificationUpdater(pathServiceSid, pathSid, status); } @@ -112,7 +112,7 @@ public static Verification fromJson( private final String serviceSid; private final String accountSid; private final String to; - private final Channel channel; + private final Verification.Channel channel; private final String status; private final Boolean valid; private final Map lookup; @@ -130,7 +130,7 @@ private Verification( @JsonProperty("service_sid") final String serviceSid, @JsonProperty("account_sid") final String accountSid, @JsonProperty("to") final String to, - @JsonProperty("channel") final Channel channel, + @JsonProperty("channel") final Verification.Channel channel, @JsonProperty("status") final String status, @JsonProperty("valid") final Boolean valid, @JsonProperty("lookup") final Map lookup, @@ -177,7 +177,7 @@ public final String getTo() { return this.to; } - public final Channel getChannel() { + public final Verification.Channel getChannel() { return this.channel; } diff --git a/src/main/java/com/twilio/rest/verify/v2/service/VerificationCheck.java b/src/main/java/com/twilio/rest/verify/v2/service/VerificationCheck.java index 938c708c7e..303b066dae 100644 --- a/src/main/java/com/twilio/rest/verify/v2/service/VerificationCheck.java +++ b/src/main/java/com/twilio/rest/verify/v2/service/VerificationCheck.java @@ -94,7 +94,7 @@ public static VerificationCheck fromJson( private final String serviceSid; private final String accountSid; private final String to; - private final Channel channel; + private final VerificationCheck.Channel channel; private final String status; private final Boolean valid; private final String amount; @@ -109,7 +109,7 @@ private VerificationCheck( @JsonProperty("service_sid") final String serviceSid, @JsonProperty("account_sid") final String accountSid, @JsonProperty("to") final String to, - @JsonProperty("channel") final Channel channel, + @JsonProperty("channel") final VerificationCheck.Channel channel, @JsonProperty("status") final String status, @JsonProperty("valid") final Boolean valid, @JsonProperty("amount") final String amount, @@ -150,7 +150,7 @@ public final String getTo() { return this.to; } - public final Channel getChannel() { + public final VerificationCheck.Channel getChannel() { return this.channel; } diff --git a/src/main/java/com/twilio/rest/verify/v2/service/Webhook.java b/src/main/java/com/twilio/rest/verify/v2/service/Webhook.java index 1ac1c6672d..16a7742d11 100644 --- a/src/main/java/com/twilio/rest/verify/v2/service/Webhook.java +++ b/src/main/java/com/twilio/rest/verify/v2/service/Webhook.java @@ -127,10 +127,10 @@ public static Webhook fromJson( private final String accountSid; private final String friendlyName; private final List eventTypes; - private final Status status; - private final Version version; + private final Webhook.Status status; + private final Webhook.Version version; private final URI webhookUrl; - private final Methods webhookMethod; + private final Webhook.Methods webhookMethod; private final ZonedDateTime dateCreated; private final ZonedDateTime dateUpdated; private final URI url; @@ -142,10 +142,10 @@ private Webhook( @JsonProperty("account_sid") final String accountSid, @JsonProperty("friendly_name") final String friendlyName, @JsonProperty("event_types") final List eventTypes, - @JsonProperty("status") final Status status, - @JsonProperty("version") final Version version, + @JsonProperty("status") final Webhook.Status status, + @JsonProperty("version") final Webhook.Version version, @JsonProperty("webhook_url") final URI webhookUrl, - @JsonProperty("webhook_method") final Methods webhookMethod, + @JsonProperty("webhook_method") final Webhook.Methods webhookMethod, @JsonProperty("date_created") final String dateCreated, @JsonProperty("date_updated") final String dateUpdated, @JsonProperty("url") final URI url @@ -184,11 +184,11 @@ public final List getEventTypes() { return this.eventTypes; } - public final Status getStatus() { + public final Webhook.Status getStatus() { return this.status; } - public final Version getVersion() { + public final Webhook.Version getVersion() { return this.version; } @@ -196,7 +196,7 @@ public final URI getWebhookUrl() { return this.webhookUrl; } - public final Methods getWebhookMethod() { + public final Webhook.Methods getWebhookMethod() { return this.webhookMethod; } diff --git a/src/main/java/com/twilio/rest/verify/v2/service/entity/Challenge.java b/src/main/java/com/twilio/rest/verify/v2/service/entity/Challenge.java index 448f620207..0d62df7622 100644 --- a/src/main/java/com/twilio/rest/verify/v2/service/entity/Challenge.java +++ b/src/main/java/com/twilio/rest/verify/v2/service/entity/Challenge.java @@ -125,12 +125,12 @@ public static Challenge fromJson( private final ZonedDateTime dateUpdated; private final ZonedDateTime dateResponded; private final ZonedDateTime expirationDate; - private final ChallengeStatuses status; - private final ChallengeReasons respondedReason; + private final Challenge.ChallengeStatuses status; + private final Challenge.ChallengeReasons respondedReason; private final Map details; private final Map hiddenDetails; private final Map metadata; - private final FactorTypes factorType; + private final Challenge.FactorTypes factorType; private final URI url; private final Map links; @@ -146,14 +146,14 @@ private Challenge( @JsonProperty("date_updated") final String dateUpdated, @JsonProperty("date_responded") final String dateResponded, @JsonProperty("expiration_date") final String expirationDate, - @JsonProperty("status") final ChallengeStatuses status, + @JsonProperty("status") final Challenge.ChallengeStatuses status, @JsonProperty( "responded_reason" - ) final ChallengeReasons respondedReason, + ) final Challenge.ChallengeReasons respondedReason, @JsonProperty("details") final Map details, @JsonProperty("hidden_details") final Map hiddenDetails, @JsonProperty("metadata") final Map metadata, - @JsonProperty("factor_type") final FactorTypes factorType, + @JsonProperty("factor_type") final Challenge.FactorTypes factorType, @JsonProperty("url") final URI url, @JsonProperty("links") final Map links ) { @@ -219,11 +219,11 @@ public final ZonedDateTime getExpirationDate() { return this.expirationDate; } - public final ChallengeStatuses getStatus() { + public final Challenge.ChallengeStatuses getStatus() { return this.status; } - public final ChallengeReasons getRespondedReason() { + public final Challenge.ChallengeReasons getRespondedReason() { return this.respondedReason; } @@ -239,7 +239,7 @@ public final Map getMetadata() { return this.metadata; } - public final FactorTypes getFactorType() { + public final Challenge.FactorTypes getFactorType() { return this.factorType; } diff --git a/src/main/java/com/twilio/rest/verify/v2/service/entity/Factor.java b/src/main/java/com/twilio/rest/verify/v2/service/entity/Factor.java index ba24c6e972..edeafe8f4e 100644 --- a/src/main/java/com/twilio/rest/verify/v2/service/entity/Factor.java +++ b/src/main/java/com/twilio/rest/verify/v2/service/entity/Factor.java @@ -123,8 +123,8 @@ public static Factor fromJson( private final ZonedDateTime dateCreated; private final ZonedDateTime dateUpdated; private final String friendlyName; - private final FactorStatuses status; - private final FactorTypes factorType; + private final Factor.FactorStatuses status; + private final Factor.FactorTypes factorType; private final Map config; private final Map metadata; private final URI url; @@ -139,8 +139,8 @@ private Factor( @JsonProperty("date_created") final String dateCreated, @JsonProperty("date_updated") final String dateUpdated, @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("status") final FactorStatuses status, - @JsonProperty("factor_type") final FactorTypes factorType, + @JsonProperty("status") final Factor.FactorStatuses status, + @JsonProperty("factor_type") final Factor.FactorTypes factorType, @JsonProperty("config") final Map config, @JsonProperty("metadata") final Map metadata, @JsonProperty("url") final URI url @@ -192,11 +192,11 @@ public final String getFriendlyName() { return this.friendlyName; } - public final FactorStatuses getStatus() { + public final Factor.FactorStatuses getStatus() { return this.status; } - public final FactorTypes getFactorType() { + public final Factor.FactorTypes getFactorType() { return this.factorType; } diff --git a/src/main/java/com/twilio/rest/verify/v2/service/entity/NewFactor.java b/src/main/java/com/twilio/rest/verify/v2/service/entity/NewFactor.java index b5b249668f..308d23c721 100644 --- a/src/main/java/com/twilio/rest/verify/v2/service/entity/NewFactor.java +++ b/src/main/java/com/twilio/rest/verify/v2/service/entity/NewFactor.java @@ -45,7 +45,7 @@ public static NewFactorCreator creator( final String pathServiceSid, final String pathIdentity, final String friendlyName, - final FactorTypes factorType + final NewFactor.FactorTypes factorType ) { return new NewFactorCreator( pathServiceSid, @@ -107,8 +107,8 @@ public static NewFactor fromJson( private final ZonedDateTime dateCreated; private final ZonedDateTime dateUpdated; private final String friendlyName; - private final FactorStatuses status; - private final FactorTypes factorType; + private final NewFactor.FactorStatuses status; + private final NewFactor.FactorTypes factorType; private final Map config; private final Map metadata; private final URI url; @@ -124,8 +124,8 @@ private NewFactor( @JsonProperty("date_created") final String dateCreated, @JsonProperty("date_updated") final String dateUpdated, @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("status") final FactorStatuses status, - @JsonProperty("factor_type") final FactorTypes factorType, + @JsonProperty("status") final NewFactor.FactorStatuses status, + @JsonProperty("factor_type") final NewFactor.FactorTypes factorType, @JsonProperty("config") final Map config, @JsonProperty("metadata") final Map metadata, @JsonProperty("url") final URI url @@ -182,11 +182,11 @@ public final String getFriendlyName() { return this.friendlyName; } - public final FactorStatuses getStatus() { + public final NewFactor.FactorStatuses getStatus() { return this.status; } - public final FactorTypes getFactorType() { + public final NewFactor.FactorTypes getFactorType() { return this.factorType; } diff --git a/src/main/java/com/twilio/rest/video/v1/Composition.java b/src/main/java/com/twilio/rest/video/v1/Composition.java index cdb8c529ea..c58d12e102 100644 --- a/src/main/java/com/twilio/rest/video/v1/Composition.java +++ b/src/main/java/com/twilio/rest/video/v1/Composition.java @@ -103,7 +103,7 @@ public static Composition fromJson( } private final String accountSid; - private final Status status; + private final Composition.Status status; private final ZonedDateTime dateCreated; private final ZonedDateTime dateCompleted; private final ZonedDateTime dateDeleted; @@ -114,7 +114,7 @@ public static Composition fromJson( private final Map videoLayout; private final String resolution; private final Boolean trim; - private final Format format; + private final Composition.Format format; private final Integer bitrate; private final Long size; private final Integer duration; @@ -127,7 +127,7 @@ public static Composition fromJson( @JsonCreator private Composition( @JsonProperty("account_sid") final String accountSid, - @JsonProperty("status") final Status status, + @JsonProperty("status") final Composition.Status status, @JsonProperty("date_created") final String dateCreated, @JsonProperty("date_completed") final String dateCompleted, @JsonProperty("date_deleted") final String dateDeleted, @@ -140,7 +140,7 @@ private Composition( @JsonProperty("video_layout") final Map videoLayout, @JsonProperty("resolution") final String resolution, @JsonProperty("trim") final Boolean trim, - @JsonProperty("format") final Format format, + @JsonProperty("format") final Composition.Format format, @JsonProperty("bitrate") final Integer bitrate, @JsonProperty("size") final Long size, @JsonProperty("duration") final Integer duration, @@ -182,7 +182,7 @@ public final String getAccountSid() { return this.accountSid; } - public final Status getStatus() { + public final Composition.Status getStatus() { return this.status; } @@ -226,7 +226,7 @@ public final Boolean getTrim() { return this.trim; } - public final Format getFormat() { + public final Composition.Format getFormat() { return this.format; } diff --git a/src/main/java/com/twilio/rest/video/v1/CompositionHook.java b/src/main/java/com/twilio/rest/video/v1/CompositionHook.java index c311f937ea..4c28fa2a64 100644 --- a/src/main/java/com/twilio/rest/video/v1/CompositionHook.java +++ b/src/main/java/com/twilio/rest/video/v1/CompositionHook.java @@ -120,7 +120,7 @@ public static CompositionHook fromJson( private final Map videoLayout; private final String resolution; private final Boolean trim; - private final Format format; + private final CompositionHook.Format format; private final URI statusCallback; private final HttpMethod statusCallbackMethod; private final URI url; @@ -140,7 +140,7 @@ private CompositionHook( @JsonProperty("video_layout") final Map videoLayout, @JsonProperty("resolution") final String resolution, @JsonProperty("trim") final Boolean trim, - @JsonProperty("format") final Format format, + @JsonProperty("format") final CompositionHook.Format format, @JsonProperty("status_callback") final URI statusCallback, @JsonProperty( "status_callback_method" @@ -208,7 +208,7 @@ public final Boolean getTrim() { return this.trim; } - public final Format getFormat() { + public final CompositionHook.Format getFormat() { return this.format; } diff --git a/src/main/java/com/twilio/rest/video/v1/Recording.java b/src/main/java/com/twilio/rest/video/v1/Recording.java index 8c7e6debb8..4f21119419 100644 --- a/src/main/java/com/twilio/rest/video/v1/Recording.java +++ b/src/main/java/com/twilio/rest/video/v1/Recording.java @@ -98,16 +98,16 @@ public static Recording fromJson( } private final String accountSid; - private final Status status; + private final Recording.Status status; private final ZonedDateTime dateCreated; private final String sid; private final String sourceSid; private final Long size; private final URI url; - private final Type type; + private final Recording.Type type; private final Integer duration; - private final Format containerFormat; - private final Codec codec; + private final Recording.Format containerFormat; + private final Recording.Codec codec; private final Map groupingSids; private final String trackName; private final Long offset; @@ -119,16 +119,18 @@ public static Recording fromJson( @JsonCreator private Recording( @JsonProperty("account_sid") final String accountSid, - @JsonProperty("status") final Status status, + @JsonProperty("status") final Recording.Status status, @JsonProperty("date_created") final String dateCreated, @JsonProperty("sid") final String sid, @JsonProperty("source_sid") final String sourceSid, @JsonProperty("size") final Long size, @JsonProperty("url") final URI url, - @JsonProperty("type") final Type type, + @JsonProperty("type") final Recording.Type type, @JsonProperty("duration") final Integer duration, - @JsonProperty("container_format") final Format containerFormat, - @JsonProperty("codec") final Codec codec, + @JsonProperty( + "container_format" + ) final Recording.Format containerFormat, + @JsonProperty("codec") final Recording.Codec codec, @JsonProperty("grouping_sids") final Map groupingSids, @JsonProperty("track_name") final String trackName, @JsonProperty("offset") final Long offset, @@ -165,7 +167,7 @@ public final String getAccountSid() { return this.accountSid; } - public final Status getStatus() { + public final Recording.Status getStatus() { return this.status; } @@ -189,7 +191,7 @@ public final URI getUrl() { return this.url; } - public final Type getType() { + public final Recording.Type getType() { return this.type; } @@ -197,11 +199,11 @@ public final Integer getDuration() { return this.duration; } - public final Format getContainerFormat() { + public final Recording.Format getContainerFormat() { return this.containerFormat; } - public final Codec getCodec() { + public final Recording.Codec getCodec() { return this.codec; } diff --git a/src/main/java/com/twilio/rest/video/v1/Room.java b/src/main/java/com/twilio/rest/video/v1/Room.java index 3ed9520d58..77a513b610 100644 --- a/src/main/java/com/twilio/rest/video/v1/Room.java +++ b/src/main/java/com/twilio/rest/video/v1/Room.java @@ -57,7 +57,7 @@ public static RoomReader reader() { public static RoomUpdater updater( final String pathSid, - final RoomStatus status + final Room.RoomStatus status ) { return new RoomUpdater(pathSid, status); } @@ -106,7 +106,7 @@ public static Room fromJson( } private final String sid; - private final RoomStatus status; + private final Room.RoomStatus status; private final ZonedDateTime dateCreated; private final ZonedDateTime dateUpdated; private final String accountSid; @@ -116,12 +116,12 @@ public static Room fromJson( private final HttpMethod statusCallbackMethod; private final ZonedDateTime endTime; private final Integer duration; - private final RoomType type; + private final Room.RoomType type; private final Integer maxParticipants; private final Integer maxParticipantDuration; private final Integer maxConcurrentPublishedTracks; private final Boolean recordParticipantsOnConnect; - private final List videoCodecs; + private final List videoCodecs; private final String mediaRegion; private final Boolean audioOnly; private final Integer emptyRoomTimeout; @@ -133,7 +133,7 @@ public static Room fromJson( @JsonCreator private Room( @JsonProperty("sid") final String sid, - @JsonProperty("status") final RoomStatus status, + @JsonProperty("status") final Room.RoomStatus status, @JsonProperty("date_created") final String dateCreated, @JsonProperty("date_updated") final String dateUpdated, @JsonProperty("account_sid") final String accountSid, @@ -145,7 +145,7 @@ private Room( ) final HttpMethod statusCallbackMethod, @JsonProperty("end_time") final String endTime, @JsonProperty("duration") final Integer duration, - @JsonProperty("type") final RoomType type, + @JsonProperty("type") final Room.RoomType type, @JsonProperty("max_participants") final Integer maxParticipants, @JsonProperty( "max_participant_duration" @@ -156,7 +156,7 @@ private Room( @JsonProperty( "record_participants_on_connect" ) final Boolean recordParticipantsOnConnect, - @JsonProperty("video_codecs") final List videoCodecs, + @JsonProperty("video_codecs") final List videoCodecs, @JsonProperty("media_region") final String mediaRegion, @JsonProperty("audio_only") final Boolean audioOnly, @JsonProperty("empty_room_timeout") final Integer emptyRoomTimeout, @@ -195,7 +195,7 @@ public final String getSid() { return this.sid; } - public final RoomStatus getStatus() { + public final Room.RoomStatus getStatus() { return this.status; } @@ -235,7 +235,7 @@ public final Integer getDuration() { return this.duration; } - public final RoomType getType() { + public final Room.RoomType getType() { return this.type; } @@ -255,7 +255,7 @@ public final Boolean getRecordParticipantsOnConnect() { return this.recordParticipantsOnConnect; } - public final List getVideoCodecs() { + public final List getVideoCodecs() { return this.videoCodecs; } diff --git a/src/main/java/com/twilio/rest/video/v1/room/Participant.java b/src/main/java/com/twilio/rest/video/v1/room/Participant.java index 83a9ab8d84..e424615a76 100644 --- a/src/main/java/com/twilio/rest/video/v1/room/Participant.java +++ b/src/main/java/com/twilio/rest/video/v1/room/Participant.java @@ -105,7 +105,7 @@ public static Participant fromJson( private final String sid; private final String roomSid; private final String accountSid; - private final Status status; + private final Participant.Status status; private final String identity; private final ZonedDateTime dateCreated; private final ZonedDateTime dateUpdated; @@ -120,7 +120,7 @@ private Participant( @JsonProperty("sid") final String sid, @JsonProperty("room_sid") final String roomSid, @JsonProperty("account_sid") final String accountSid, - @JsonProperty("status") final Status status, + @JsonProperty("status") final Participant.Status status, @JsonProperty("identity") final String identity, @JsonProperty("date_created") final String dateCreated, @JsonProperty("date_updated") final String dateUpdated, @@ -156,7 +156,7 @@ public final String getAccountSid() { return this.accountSid; } - public final Status getStatus() { + public final Participant.Status getStatus() { return this.status; } diff --git a/src/main/java/com/twilio/rest/video/v1/room/RoomRecording.java b/src/main/java/com/twilio/rest/video/v1/room/RoomRecording.java index 506eaea365..7a37f4e2ad 100644 --- a/src/main/java/com/twilio/rest/video/v1/room/RoomRecording.java +++ b/src/main/java/com/twilio/rest/video/v1/room/RoomRecording.java @@ -103,16 +103,16 @@ public static RoomRecording fromJson( } private final String accountSid; - private final Status status; + private final RoomRecording.Status status; private final ZonedDateTime dateCreated; private final String sid; private final String sourceSid; private final Long size; private final URI url; - private final Type type; + private final RoomRecording.Type type; private final Integer duration; - private final Format containerFormat; - private final Codec codec; + private final RoomRecording.Format containerFormat; + private final RoomRecording.Codec codec; private final Map groupingSids; private final String trackName; private final Long offset; @@ -123,16 +123,18 @@ public static RoomRecording fromJson( @JsonCreator private RoomRecording( @JsonProperty("account_sid") final String accountSid, - @JsonProperty("status") final Status status, + @JsonProperty("status") final RoomRecording.Status status, @JsonProperty("date_created") final String dateCreated, @JsonProperty("sid") final String sid, @JsonProperty("source_sid") final String sourceSid, @JsonProperty("size") final Long size, @JsonProperty("url") final URI url, - @JsonProperty("type") final Type type, + @JsonProperty("type") final RoomRecording.Type type, @JsonProperty("duration") final Integer duration, - @JsonProperty("container_format") final Format containerFormat, - @JsonProperty("codec") final Codec codec, + @JsonProperty( + "container_format" + ) final RoomRecording.Format containerFormat, + @JsonProperty("codec") final RoomRecording.Codec codec, @JsonProperty("grouping_sids") final Map groupingSids, @JsonProperty("track_name") final String trackName, @JsonProperty("offset") final Long offset, @@ -165,7 +167,7 @@ public final String getAccountSid() { return this.accountSid; } - public final Status getStatus() { + public final RoomRecording.Status getStatus() { return this.status; } @@ -189,7 +191,7 @@ public final URI getUrl() { return this.url; } - public final Type getType() { + public final RoomRecording.Type getType() { return this.type; } @@ -197,11 +199,11 @@ public final Integer getDuration() { return this.duration; } - public final Format getContainerFormat() { + public final RoomRecording.Format getContainerFormat() { return this.containerFormat; } - public final Codec getCodec() { + public final RoomRecording.Codec getCodec() { return this.codec; } diff --git a/src/main/java/com/twilio/rest/video/v1/room/Transcriptions.java b/src/main/java/com/twilio/rest/video/v1/room/Transcriptions.java new file mode 100644 index 0000000000..d5f741d671 --- /dev/null +++ b/src/main/java/com/twilio/rest/video/v1/room/Transcriptions.java @@ -0,0 +1,255 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Video + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package com.twilio.rest.video.v1.room; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.twilio.base.Resource; +import com.twilio.converter.DateConverter; +import com.twilio.converter.Promoter; +import com.twilio.exception.ApiConnectionException; +import com.twilio.exception.ApiException; +import java.io.IOException; +import java.io.InputStream; +import java.net.URI; +import java.time.ZonedDateTime; +import java.util.Objects; +import lombok.ToString; +import lombok.ToString; + +@JsonIgnoreProperties(ignoreUnknown = true) +@ToString +public class Transcriptions extends Resource { + + private static final long serialVersionUID = 265092932948237L; + + public static TranscriptionsCreator creator(final String pathRoomSid) { + return new TranscriptionsCreator(pathRoomSid); + } + + public static TranscriptionsFetcher fetcher( + final String pathRoomSid, + final String pathTtid + ) { + return new TranscriptionsFetcher(pathRoomSid, pathTtid); + } + + public static TranscriptionsReader reader(final String pathRoomSid) { + return new TranscriptionsReader(pathRoomSid); + } + + public static TranscriptionsUpdater updater( + final String pathRoomSid, + final String pathTtid + ) { + return new TranscriptionsUpdater(pathRoomSid, pathTtid); + } + + /** + * Converts a JSON String into a Transcriptions object using the provided ObjectMapper. + * + * @param json Raw JSON String + * @param objectMapper Jackson ObjectMapper + * @return Transcriptions object represented by the provided JSON + */ + public static Transcriptions fromJson( + final String json, + final ObjectMapper objectMapper + ) { + // Convert all checked exceptions to Runtime + try { + return objectMapper.readValue(json, Transcriptions.class); + } catch (final JsonMappingException | JsonParseException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + /** + * Converts a JSON InputStream into a Transcriptions object using the provided + * ObjectMapper. + * + * @param json Raw JSON InputStream + * @param objectMapper Jackson ObjectMapper + * @return Transcriptions object represented by the provided JSON + */ + public static Transcriptions fromJson( + final InputStream json, + final ObjectMapper objectMapper + ) { + // Convert all checked exceptions to Runtime + try { + return objectMapper.readValue(json, Transcriptions.class); + } catch (final JsonMappingException | JsonParseException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + private final String ttid; + private final String accountSid; + private final String roomSid; + private final Transcriptions.Status status; + private final String identity; + private final ZonedDateTime dateCreated; + private final ZonedDateTime dateUpdated; + private final ZonedDateTime startTime; + private final ZonedDateTime endTime; + private final Integer duration; + private final URI url; + + @JsonCreator + private Transcriptions( + @JsonProperty("ttid") final String ttid, + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("room_sid") final String roomSid, + @JsonProperty("status") final Transcriptions.Status status, + @JsonProperty("identity") final String identity, + @JsonProperty("date_created") final String dateCreated, + @JsonProperty("date_updated") final String dateUpdated, + @JsonProperty("start_time") final String startTime, + @JsonProperty("end_time") final String endTime, + @JsonProperty("duration") final Integer duration, + @JsonProperty("url") final URI url + ) { + this.ttid = ttid; + this.accountSid = accountSid; + this.roomSid = roomSid; + this.status = status; + this.identity = identity; + this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); + this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); + this.startTime = DateConverter.iso8601DateTimeFromString(startTime); + this.endTime = DateConverter.iso8601DateTimeFromString(endTime); + this.duration = duration; + this.url = url; + } + + public final String getTtid() { + return this.ttid; + } + + public final String getAccountSid() { + return this.accountSid; + } + + public final String getRoomSid() { + return this.roomSid; + } + + public final Transcriptions.Status getStatus() { + return this.status; + } + + public final String getIdentity() { + return this.identity; + } + + public final ZonedDateTime getDateCreated() { + return this.dateCreated; + } + + public final ZonedDateTime getDateUpdated() { + return this.dateUpdated; + } + + public final ZonedDateTime getStartTime() { + return this.startTime; + } + + public final ZonedDateTime getEndTime() { + return this.endTime; + } + + public final Integer getDuration() { + return this.duration; + } + + public final URI getUrl() { + return this.url; + } + + @Override + public boolean equals(final Object o) { + if (this == o) { + return true; + } + + if (o == null || getClass() != o.getClass()) { + return false; + } + + Transcriptions other = (Transcriptions) o; + + return ( + Objects.equals(ttid, other.ttid) && + Objects.equals(accountSid, other.accountSid) && + Objects.equals(roomSid, other.roomSid) && + Objects.equals(status, other.status) && + Objects.equals(identity, other.identity) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(startTime, other.startTime) && + Objects.equals(endTime, other.endTime) && + Objects.equals(duration, other.duration) && + Objects.equals(url, other.url) + ); + } + + @Override + public int hashCode() { + return Objects.hash( + ttid, + accountSid, + roomSid, + status, + identity, + dateCreated, + dateUpdated, + startTime, + endTime, + duration, + url + ); + } + + public enum Status { + CREATED("created"), + STARTED("started"), + STOPPED("stopped"), + FAILED("failed"); + + private final String value; + + private Status(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static Status forValue(final String value) { + return Promoter.enumFromString(value, Status.values()); + } + } +} diff --git a/src/main/java/com/twilio/rest/proxy/v1/service/ShortCodeCreator.java b/src/main/java/com/twilio/rest/video/v1/room/TranscriptionsCreator.java similarity index 63% rename from src/main/java/com/twilio/rest/proxy/v1/service/ShortCodeCreator.java rename to src/main/java/com/twilio/rest/video/v1/room/TranscriptionsCreator.java index 534da26b49..92947f94ea 100644 --- a/src/main/java/com/twilio/rest/proxy/v1/service/ShortCodeCreator.java +++ b/src/main/java/com/twilio/rest/video/v1/room/TranscriptionsCreator.java @@ -4,7 +4,7 @@ * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ * - * Twilio - Proxy + * Twilio - Video * This is the public Twilio REST API. * * NOTE: This class is auto generated by OpenAPI Generator. @@ -12,10 +12,12 @@ * Do not edit the class manually. */ -package com.twilio.rest.proxy.v1.service; +package com.twilio.rest.video.v1.room; import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.converter.Converter; +import com.twilio.converter.Converter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -24,36 +26,34 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; +import java.util.Map; +import java.util.Map; -public class ShortCodeCreator extends Creator { +public class TranscriptionsCreator extends Creator { - private String pathServiceSid; - private String sid; + private String pathRoomSid; + private Map configuration; - public ShortCodeCreator(final String pathServiceSid, final String sid) { - this.pathServiceSid = pathServiceSid; - this.sid = sid; + public TranscriptionsCreator(final String pathRoomSid) { + this.pathRoomSid = pathRoomSid; } - public ShortCodeCreator setSid(final String sid) { - this.sid = sid; + public TranscriptionsCreator setConfiguration( + final Map configuration + ) { + this.configuration = configuration; return this; } @Override - public ShortCode create(final TwilioRestClient client) { - String path = "/v1/Services/{ServiceSid}/ShortCodes"; + public Transcriptions create(final TwilioRestClient client) { + String path = "/v1/Rooms/{RoomSid}/Transcriptions"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.sid.toString()); + path = path.replace("{" + "RoomSid" + "}", this.pathRoomSid.toString()); Request request = new Request( HttpMethod.POST, - Domains.PROXY.toString(), + Domains.VIDEO.toString(), path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); @@ -61,7 +61,7 @@ public ShortCode create(final TwilioRestClient client) { Response response = client.request(request); if (response == null) { throw new ApiConnectionException( - "ShortCode creation failed: Unable to connect to server" + "Transcriptions creation failed: Unable to connect to server" ); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( @@ -77,15 +77,18 @@ public ShortCode create(final TwilioRestClient client) { throw new ApiException(restException); } - return ShortCode.fromJson( + return Transcriptions.fromJson( response.getStream(), client.getObjectMapper() ); } private void addPostParams(final Request request) { - if (sid != null) { - request.addPostParam("Sid", sid); + if (configuration != null) { + request.addPostParam( + "Configuration", + Converter.mapToJson(configuration) + ); } } } diff --git a/src/main/java/com/twilio/rest/microvisor/v1/AccountSecretFetcher.java b/src/main/java/com/twilio/rest/video/v1/room/TranscriptionsFetcher.java similarity index 69% rename from src/main/java/com/twilio/rest/microvisor/v1/AccountSecretFetcher.java rename to src/main/java/com/twilio/rest/video/v1/room/TranscriptionsFetcher.java index 78b58fca72..b1a311a59e 100644 --- a/src/main/java/com/twilio/rest/microvisor/v1/AccountSecretFetcher.java +++ b/src/main/java/com/twilio/rest/video/v1/room/TranscriptionsFetcher.java @@ -4,7 +4,7 @@ * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ * - * Twilio - Microvisor + * Twilio - Video * This is the public Twilio REST API. * * NOTE: This class is auto generated by OpenAPI Generator. @@ -12,7 +12,7 @@ * Do not edit the class manually. */ -package com.twilio.rest.microvisor.v1; +package com.twilio.rest.video.v1.room; import com.twilio.base.Fetcher; import com.twilio.constant.EnumConstants; @@ -25,23 +25,29 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class AccountSecretFetcher extends Fetcher { +public class TranscriptionsFetcher extends Fetcher { - private String pathKey; + private String pathRoomSid; + private String pathTtid; - public AccountSecretFetcher(final String pathKey) { - this.pathKey = pathKey; + public TranscriptionsFetcher( + final String pathRoomSid, + final String pathTtid + ) { + this.pathRoomSid = pathRoomSid; + this.pathTtid = pathTtid; } @Override - public AccountSecret fetch(final TwilioRestClient client) { - String path = "/v1/Secrets/{Key}"; + public Transcriptions fetch(final TwilioRestClient client) { + String path = "/v1/Rooms/{RoomSid}/Transcriptions/{Ttid}"; - path = path.replace("{" + "Key" + "}", this.pathKey.toString()); + path = path.replace("{" + "RoomSid" + "}", this.pathRoomSid.toString()); + path = path.replace("{" + "Ttid" + "}", this.pathTtid.toString()); Request request = new Request( HttpMethod.GET, - Domains.MICROVISOR.toString(), + Domains.VIDEO.toString(), path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); @@ -49,7 +55,7 @@ public AccountSecret fetch(final TwilioRestClient client) { if (response == null) { throw new ApiConnectionException( - "AccountSecret fetch failed: Unable to connect to server" + "Transcriptions fetch failed: Unable to connect to server" ); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( @@ -65,7 +71,7 @@ public AccountSecret fetch(final TwilioRestClient client) { throw new ApiException(restException); } - return AccountSecret.fromJson( + return Transcriptions.fromJson( response.getStream(), client.getObjectMapper() ); diff --git a/src/main/java/com/twilio/rest/microvisor/v1/DeviceReader.java b/src/main/java/com/twilio/rest/video/v1/room/TranscriptionsReader.java similarity index 72% rename from src/main/java/com/twilio/rest/microvisor/v1/DeviceReader.java rename to src/main/java/com/twilio/rest/video/v1/room/TranscriptionsReader.java index 28cec8e051..7cb0570421 100644 --- a/src/main/java/com/twilio/rest/microvisor/v1/DeviceReader.java +++ b/src/main/java/com/twilio/rest/video/v1/room/TranscriptionsReader.java @@ -4,7 +4,7 @@ * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ * - * Twilio - Microvisor + * Twilio - Video * This is the public Twilio REST API. * * NOTE: This class is auto generated by OpenAPI Generator. @@ -12,7 +12,7 @@ * Do not edit the class manually. */ -package com.twilio.rest.microvisor.v1; +package com.twilio.rest.video.v1.room; import com.twilio.base.Page; import com.twilio.base.Reader; @@ -27,28 +27,32 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class DeviceReader extends Reader { +public class TranscriptionsReader extends Reader { + private String pathRoomSid; private Long pageSize; - public DeviceReader() {} + public TranscriptionsReader(final String pathRoomSid) { + this.pathRoomSid = pathRoomSid; + } - public DeviceReader setPageSize(final Long pageSize) { + public TranscriptionsReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } @Override - public ResourceSet read(final TwilioRestClient client) { + public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } - public Page firstPage(final TwilioRestClient client) { - String path = "/v1/Devices"; + public Page firstPage(final TwilioRestClient client) { + String path = "/v1/Rooms/{RoomSid}/Transcriptions"; + path = path.replace("{" + "RoomSid" + "}", this.pathRoomSid.toString()); Request request = new Request( HttpMethod.GET, - Domains.MICROVISOR.toString(), + Domains.VIDEO.toString(), path ); @@ -57,7 +61,7 @@ public Page firstPage(final TwilioRestClient client) { return pageForRequest(client, request); } - private Page pageForRequest( + private Page pageForRequest( final TwilioRestClient client, final Request request ) { @@ -65,7 +69,7 @@ private Page pageForRequest( if (response == null) { throw new ApiConnectionException( - "Device read failed: Unable to connect to server" + "Transcriptions read failed: Unable to connect to server" ); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( @@ -82,39 +86,39 @@ private Page pageForRequest( } return Page.fromJson( - "devices", + "extensions", response.getContent(), - Device.class, + Transcriptions.class, client.getObjectMapper() ); } @Override - public Page previousPage( - final Page page, + public Page previousPage( + final Page page, final TwilioRestClient client ) { Request request = new Request( HttpMethod.GET, - page.getPreviousPageUrl(Domains.MICROVISOR.toString()) + page.getPreviousPageUrl(Domains.VIDEO.toString()) ); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, + public Page nextPage( + final Page page, final TwilioRestClient client ) { Request request = new Request( HttpMethod.GET, - page.getNextPageUrl(Domains.MICROVISOR.toString()) + page.getNextPageUrl(Domains.VIDEO.toString()) ); return pageForRequest(client, request); } @Override - public Page getPage( + public Page getPage( final String targetUrl, final TwilioRestClient client ) { diff --git a/src/main/java/com/twilio/rest/microvisor/v1/AccountSecretUpdater.java b/src/main/java/com/twilio/rest/video/v1/room/TranscriptionsUpdater.java similarity index 64% rename from src/main/java/com/twilio/rest/microvisor/v1/AccountSecretUpdater.java rename to src/main/java/com/twilio/rest/video/v1/room/TranscriptionsUpdater.java index fc4e3c61eb..ff6487e71d 100644 --- a/src/main/java/com/twilio/rest/microvisor/v1/AccountSecretUpdater.java +++ b/src/main/java/com/twilio/rest/video/v1/room/TranscriptionsUpdater.java @@ -4,7 +4,7 @@ * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ * - * Twilio - Microvisor + * Twilio - Video * This is the public Twilio REST API. * * NOTE: This class is auto generated by OpenAPI Generator. @@ -12,7 +12,7 @@ * Do not edit the class manually. */ -package com.twilio.rest.microvisor.v1; +package com.twilio.rest.video.v1.room; import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; @@ -25,31 +25,35 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class AccountSecretUpdater extends Updater { +public class TranscriptionsUpdater extends Updater { - private String pathKey; - private String value; + private String pathRoomSid; + private String pathTtid; + private Transcriptions.Status status; - public AccountSecretUpdater(final String pathKey, final String value) { - this.pathKey = pathKey; - this.value = value; + public TranscriptionsUpdater( + final String pathRoomSid, + final String pathTtid + ) { + this.pathRoomSid = pathRoomSid; + this.pathTtid = pathTtid; } - public AccountSecretUpdater setValue(final String value) { - this.value = value; + public TranscriptionsUpdater setStatus(final Transcriptions.Status status) { + this.status = status; return this; } @Override - public AccountSecret update(final TwilioRestClient client) { - String path = "/v1/Secrets/{Key}"; + public Transcriptions update(final TwilioRestClient client) { + String path = "/v1/Rooms/{RoomSid}/Transcriptions/{Ttid}"; - path = path.replace("{" + "Key" + "}", this.pathKey.toString()); - path = path.replace("{" + "Value" + "}", this.value.toString()); + path = path.replace("{" + "RoomSid" + "}", this.pathRoomSid.toString()); + path = path.replace("{" + "Ttid" + "}", this.pathTtid.toString()); Request request = new Request( HttpMethod.POST, - Domains.MICROVISOR.toString(), + Domains.VIDEO.toString(), path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); @@ -57,7 +61,7 @@ public AccountSecret update(final TwilioRestClient client) { Response response = client.request(request); if (response == null) { throw new ApiConnectionException( - "AccountSecret update failed: Unable to connect to server" + "Transcriptions update failed: Unable to connect to server" ); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( @@ -73,15 +77,15 @@ public AccountSecret update(final TwilioRestClient client) { throw new ApiException(restException); } - return AccountSecret.fromJson( + return Transcriptions.fromJson( response.getStream(), client.getObjectMapper() ); } private void addPostParams(final Request request) { - if (value != null) { - request.addPostParam("Value", value); + if (status != null) { + request.addPostParam("Status", status.toString()); } } } diff --git a/src/main/java/com/twilio/rest/video/v1/room/participant/Anonymize.java b/src/main/java/com/twilio/rest/video/v1/room/participant/Anonymize.java index 898d66175f..13cd56e05e 100644 --- a/src/main/java/com/twilio/rest/video/v1/room/participant/Anonymize.java +++ b/src/main/java/com/twilio/rest/video/v1/room/participant/Anonymize.java @@ -92,7 +92,7 @@ public static Anonymize fromJson( private final String sid; private final String roomSid; private final String accountSid; - private final Status status; + private final Anonymize.Status status; private final String identity; private final ZonedDateTime dateCreated; private final ZonedDateTime dateUpdated; @@ -106,7 +106,7 @@ private Anonymize( @JsonProperty("sid") final String sid, @JsonProperty("room_sid") final String roomSid, @JsonProperty("account_sid") final String accountSid, - @JsonProperty("status") final Status status, + @JsonProperty("status") final Anonymize.Status status, @JsonProperty("identity") final String identity, @JsonProperty("date_created") final String dateCreated, @JsonProperty("date_updated") final String dateUpdated, @@ -140,7 +140,7 @@ public final String getAccountSid() { return this.accountSid; } - public final Status getStatus() { + public final Anonymize.Status getStatus() { return this.status; } diff --git a/src/main/java/com/twilio/rest/video/v1/room/participant/PublishedTrack.java b/src/main/java/com/twilio/rest/video/v1/room/participant/PublishedTrack.java index d48e5ad022..38798ef161 100644 --- a/src/main/java/com/twilio/rest/video/v1/room/participant/PublishedTrack.java +++ b/src/main/java/com/twilio/rest/video/v1/room/participant/PublishedTrack.java @@ -108,7 +108,7 @@ public static PublishedTrack fromJson( private final ZonedDateTime dateCreated; private final ZonedDateTime dateUpdated; private final Boolean enabled; - private final Kind kind; + private final PublishedTrack.Kind kind; private final URI url; @JsonCreator @@ -120,7 +120,7 @@ private PublishedTrack( @JsonProperty("date_created") final String dateCreated, @JsonProperty("date_updated") final String dateUpdated, @JsonProperty("enabled") final Boolean enabled, - @JsonProperty("kind") final Kind kind, + @JsonProperty("kind") final PublishedTrack.Kind kind, @JsonProperty("url") final URI url ) { this.sid = sid; @@ -162,7 +162,7 @@ public final Boolean getEnabled() { return this.enabled; } - public final Kind getKind() { + public final PublishedTrack.Kind getKind() { return this.kind; } diff --git a/src/main/java/com/twilio/rest/video/v1/room/participant/SubscribedTrack.java b/src/main/java/com/twilio/rest/video/v1/room/participant/SubscribedTrack.java index 23c88fbcc7..d31de8e3c5 100644 --- a/src/main/java/com/twilio/rest/video/v1/room/participant/SubscribedTrack.java +++ b/src/main/java/com/twilio/rest/video/v1/room/participant/SubscribedTrack.java @@ -109,7 +109,7 @@ public static SubscribedTrack fromJson( private final ZonedDateTime dateCreated; private final ZonedDateTime dateUpdated; private final Boolean enabled; - private final Kind kind; + private final SubscribedTrack.Kind kind; private final URI url; @JsonCreator @@ -122,7 +122,7 @@ private SubscribedTrack( @JsonProperty("date_created") final String dateCreated, @JsonProperty("date_updated") final String dateUpdated, @JsonProperty("enabled") final Boolean enabled, - @JsonProperty("kind") final Kind kind, + @JsonProperty("kind") final SubscribedTrack.Kind kind, @JsonProperty("url") final URI url ) { this.sid = sid; @@ -169,7 +169,7 @@ public final Boolean getEnabled() { return this.enabled; } - public final Kind getKind() { + public final SubscribedTrack.Kind getKind() { return this.kind; } diff --git a/src/main/java/com/twilio/rest/wireless/v1/Command.java b/src/main/java/com/twilio/rest/wireless/v1/Command.java index bd545d7403..e1c79cb63b 100644 --- a/src/main/java/com/twilio/rest/wireless/v1/Command.java +++ b/src/main/java/com/twilio/rest/wireless/v1/Command.java @@ -102,11 +102,11 @@ public static Command fromJson( private final String accountSid; private final String simSid; private final String command; - private final CommandMode commandMode; - private final Transport transport; + private final Command.CommandMode commandMode; + private final Command.Transport transport; private final Boolean deliveryReceiptRequested; - private final Status status; - private final Direction direction; + private final Command.Status status; + private final Command.Direction direction; private final ZonedDateTime dateCreated; private final ZonedDateTime dateUpdated; private final URI url; @@ -117,13 +117,13 @@ private Command( @JsonProperty("account_sid") final String accountSid, @JsonProperty("sim_sid") final String simSid, @JsonProperty("command") final String command, - @JsonProperty("command_mode") final CommandMode commandMode, - @JsonProperty("transport") final Transport transport, + @JsonProperty("command_mode") final Command.CommandMode commandMode, + @JsonProperty("transport") final Command.Transport transport, @JsonProperty( "delivery_receipt_requested" ) final Boolean deliveryReceiptRequested, - @JsonProperty("status") final Status status, - @JsonProperty("direction") final Direction direction, + @JsonProperty("status") final Command.Status status, + @JsonProperty("direction") final Command.Direction direction, @JsonProperty("date_created") final String dateCreated, @JsonProperty("date_updated") final String dateUpdated, @JsonProperty("url") final URI url @@ -158,11 +158,11 @@ public final String getCommand() { return this.command; } - public final CommandMode getCommandMode() { + public final Command.CommandMode getCommandMode() { return this.commandMode; } - public final Transport getTransport() { + public final Command.Transport getTransport() { return this.transport; } @@ -170,11 +170,11 @@ public final Boolean getDeliveryReceiptRequested() { return this.deliveryReceiptRequested; } - public final Status getStatus() { + public final Command.Status getStatus() { return this.status; } - public final Direction getDirection() { + public final Command.Direction getDirection() { return this.direction; } diff --git a/src/main/java/com/twilio/rest/wireless/v1/Sim.java b/src/main/java/com/twilio/rest/wireless/v1/Sim.java index 6410f6d200..ccfd84da74 100644 --- a/src/main/java/com/twilio/rest/wireless/v1/Sim.java +++ b/src/main/java/com/twilio/rest/wireless/v1/Sim.java @@ -108,8 +108,8 @@ public static Sim fromJson( private final String friendlyName; private final String iccid; private final String eId; - private final Status status; - private final ResetStatus resetStatus; + private final Sim.Status status; + private final Sim.ResetStatus resetStatus; private final URI commandsCallbackUrl; private final HttpMethod commandsCallbackMethod; private final HttpMethod smsFallbackMethod; @@ -135,8 +135,8 @@ private Sim( @JsonProperty("friendly_name") final String friendlyName, @JsonProperty("iccid") final String iccid, @JsonProperty("e_id") final String eId, - @JsonProperty("status") final Status status, - @JsonProperty("reset_status") final ResetStatus resetStatus, + @JsonProperty("status") final Sim.Status status, + @JsonProperty("reset_status") final Sim.ResetStatus resetStatus, @JsonProperty("commands_callback_url") final URI commandsCallbackUrl, @JsonProperty( "commands_callback_method" @@ -211,11 +211,11 @@ public final String getEId() { return this.eId; } - public final Status getStatus() { + public final Sim.Status getStatus() { return this.status; } - public final ResetStatus getResetStatus() { + public final Sim.ResetStatus getResetStatus() { return this.resetStatus; } diff --git a/src/main/java/com/twilio/twiml/voice/Dial.java b/src/main/java/com/twilio/twiml/voice/Dial.java index 0314d5ec65..27eeda82c8 100644 --- a/src/main/java/com/twilio/twiml/voice/Dial.java +++ b/src/main/java/com/twilio/twiml/voice/Dial.java @@ -801,6 +801,15 @@ public Builder application(Application application) { return this; } + /** + * Add a child {@code } element + */ + @JacksonXmlProperty(isAttribute = false, localName = "WhatsApp") + public Builder whatsApp(WhatsApp whatsApp) { + this.children.add(whatsApp); + return this; + } + /** * Create and return resulting {@code } element */ diff --git a/src/main/java/com/twilio/twiml/voice/WhatsApp.java b/src/main/java/com/twilio/twiml/voice/WhatsApp.java new file mode 100644 index 0000000000..1556ead3c4 --- /dev/null +++ b/src/main/java/com/twilio/twiml/voice/WhatsApp.java @@ -0,0 +1,299 @@ +/** + * This code was generated by + * \ / _ _ _| _ _ + * | (_)\/(_)(_|\/| |(/_ v1.0.0 + * / / + */ + +package com.twilio.twiml.voice; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder; +import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty; +import com.twilio.converter.Promoter; +import com.twilio.http.HttpMethod; +import com.twilio.twiml.TwiML; +import com.twilio.twiml.TwiMLException; + +import java.net.URI; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +/** + * TwiML wrapper for {@code } + */ +@JsonDeserialize(builder = WhatsApp.Builder.class) +public class WhatsApp extends TwiML { + public enum Event { + INITIATED("initiated"), + RINGING("ringing"), + ANSWERED("answered"), + COMPLETED("completed"); + + private final String value; + + private Event(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + } + + private final URI url; + private final HttpMethod method; + private final List statusCallbackEvent; + private final URI statusCallback; + private final HttpMethod statusCallbackMethod; + private final com.twilio.type.PhoneNumber phoneNumber; + + /** + * For XML Serialization/Deserialization + */ + private WhatsApp() { + this(new Builder((com.twilio.type.PhoneNumber) null)); + } + + /** + * Create a new {@code } element + */ + private WhatsApp(Builder b) { + super("WhatsApp", b); + this.url = b.url; + this.method = b.method; + this.statusCallbackEvent = b.statusCallbackEvent; + this.statusCallback = b.statusCallback; + this.statusCallbackMethod = b.statusCallbackMethod; + this.phoneNumber = b.phoneNumber; + } + + /** + * The body of the TwiML element + * + * @return Element body as a string if present else null + */ + protected String getElementBody() { + return this.getPhoneNumber() == null ? null : this.getPhoneNumber().toString(); + } + + /** + * Attributes to set on the generated XML element + * + * @return A Map of attribute keys to values + */ + protected Map getElementAttributes() { + // Preserve order of attributes + Map attrs = new HashMap<>(); + + if (this.getUrl() != null) { + attrs.put("url", this.getUrl().toString()); + } + if (this.getMethod() != null) { + attrs.put("method", this.getMethod().toString()); + } + if (this.getStatusCallbackEvents() != null) { + attrs.put("statusCallbackEvent", this.getStatusCallbackEventsAsString()); + } + if (this.getStatusCallback() != null) { + attrs.put("statusCallback", this.getStatusCallback().toString()); + } + if (this.getStatusCallbackMethod() != null) { + attrs.put("statusCallbackMethod", this.getStatusCallbackMethod().toString()); + } + + return attrs; + } + + /** + * TwiML URL + * + * @return TwiML URL + */ + public URI getUrl() { + return url; + } + + /** + * TwiML URL Method + * + * @return TwiML URL Method + */ + public HttpMethod getMethod() { + return method; + } + + /** + * Events to trigger status callback + * + * @return Events to trigger status callback + */ + public List getStatusCallbackEvents() { + return statusCallbackEvent; + } + + protected String getStatusCallbackEventsAsString() { + StringBuilder sb = new StringBuilder(); + Iterator iter = this.getStatusCallbackEvents().iterator(); + while (iter.hasNext()) { + sb.append(iter.next().toString()); + if (iter.hasNext()) { + sb.append(" "); + } + } + return sb.toString(); + } + + /** + * Status Callback URL + * + * @return Status Callback URL + */ + public URI getStatusCallback() { + return statusCallback; + } + + /** + * Status Callback URL Method + * + * @return Status Callback URL Method + */ + public HttpMethod getStatusCallbackMethod() { + return statusCallbackMethod; + } + + /** + * WhatsApp Phone Number to dial + * + * @return WhatsApp Phone Number to dial + */ + public com.twilio.type.PhoneNumber getPhoneNumber() { + return phoneNumber; + } + + /** + * Create a new {@code } element + */ + @JsonPOJOBuilder(withPrefix = "") + public static class Builder extends TwiML.Builder { + /** + * Create and return a {@code } from an XML string + */ + public static Builder fromXml(final String xml) throws TwiMLException { + try { + return OBJECT_MAPPER.readValue(xml, Builder.class); + } catch (final JsonProcessingException jpe) { + throw new TwiMLException( + "Failed to deserialize a WhatsApp.Builder from the provided XML string: " + jpe.getMessage()); + } catch (final Exception e) { + throw new TwiMLException("Unhandled exception: " + e.getMessage()); + } + } + + private URI url; + private HttpMethod method; + private List statusCallbackEvent; + private URI statusCallback; + private HttpMethod statusCallbackMethod; + private com.twilio.type.PhoneNumber phoneNumber; + + /** + * Create a {@code } with phoneNumber + */ + public Builder(com.twilio.type.PhoneNumber phoneNumber) { + this.phoneNumber = phoneNumber; + } + + /** + * Create a {@code } with phoneNumber + */ + public Builder(String phoneNumber) { + this.phoneNumber = Promoter.phoneNumberFromString(phoneNumber); + } + + /** + * Create a {@code } (for XML deserialization) + */ + private Builder() { + } + + /** + * TwiML URL + */ + @JacksonXmlProperty(isAttribute = true, localName = "url") + public Builder url(URI url) { + this.url = url; + return this; + } + + /** + * TwiML URL + */ + public Builder url(String url) { + this.url = Promoter.uriFromString(url); + return this; + } + + /** + * TwiML URL Method + */ + @JacksonXmlProperty(isAttribute = true, localName = "method") + public Builder method(HttpMethod method) { + this.method = method; + return this; + } + + /** + * Events to trigger status callback + */ + @JacksonXmlProperty(isAttribute = true, localName = "statusCallbackEvent") + public Builder statusCallbackEvents(List statusCallbackEvent) { + this.statusCallbackEvent = statusCallbackEvent; + return this; + } + + /** + * Events to trigger status callback + */ + public Builder statusCallbackEvents(WhatsApp.Event statusCallbackEvent) { + this.statusCallbackEvent = Promoter.listOfOne(statusCallbackEvent); + return this; + } + + /** + * Status Callback URL + */ + @JacksonXmlProperty(isAttribute = true, localName = "statusCallback") + public Builder statusCallback(URI statusCallback) { + this.statusCallback = statusCallback; + return this; + } + + /** + * Status Callback URL + */ + public Builder statusCallback(String statusCallback) { + this.statusCallback = Promoter.uriFromString(statusCallback); + return this; + } + + /** + * Status Callback URL Method + */ + @JacksonXmlProperty(isAttribute = true, localName = "statusCallbackMethod") + public Builder statusCallbackMethod(HttpMethod statusCallbackMethod) { + this.statusCallbackMethod = statusCallbackMethod; + return this; + } + + /** + * Create and return resulting {@code } element + */ + public WhatsApp build() { + return new WhatsApp(this); + } + } +} \ No newline at end of file diff --git a/src/test/java/com/twilio/twiml/voice/DialTest.java b/src/test/java/com/twilio/twiml/voice/DialTest.java index df5e2d3b31..8d6da7c853 100644 --- a/src/test/java/com/twilio/twiml/voice/DialTest.java +++ b/src/test/java/com/twilio/twiml/voice/DialTest.java @@ -167,6 +167,14 @@ public void testElementWithChildren() { .copyParentTo(true) .build()); + builder.whatsApp(new WhatsApp.Builder(new com.twilio.type.PhoneNumber("+15017122661")) + .url(URI.create("https://example.com")) + .method(HttpMethod.GET) + .statusCallbackEvents(Promoter.listOfOne(WhatsApp.Event.INITIATED)) + .statusCallback(URI.create("https://example.com")) + .statusCallbackMethod(HttpMethod.GET) + .build()); + Dial elem = builder.build(); Assert.assertEquals( @@ -179,6 +187,7 @@ public void testElementWithChildren() { "DEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" + "https://example.com" + "application_sid" + + "+15017122661" + "", elem.toXml() ); @@ -379,6 +388,14 @@ public void testXmlChildrenDeserialization() { .copyParentTo(true) .build()); + builder.whatsApp(new WhatsApp.Builder(new com.twilio.type.PhoneNumber("+15017122661")) + .url(URI.create("https://example.com")) + .method(HttpMethod.GET) + .statusCallbackEvents(Promoter.listOfOne(WhatsApp.Event.INITIATED)) + .statusCallback(URI.create("https://example.com")) + .statusCallbackMethod(HttpMethod.GET) + .build()); + final Dial elem = builder.build(); Assert.assertEquals( @@ -390,6 +407,7 @@ public void testXmlChildrenDeserialization() { "DEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" + "https://example.com" + "application_sid" + + "+15017122661" + "").build().toXml(), elem.toXml() ); diff --git a/src/test/java/com/twilio/twiml/voice/WhatsAppTest.java b/src/test/java/com/twilio/twiml/voice/WhatsAppTest.java new file mode 100644 index 0000000000..4c6b47bfa1 --- /dev/null +++ b/src/test/java/com/twilio/twiml/voice/WhatsAppTest.java @@ -0,0 +1,54 @@ +/** + * This code was generated by + * \ / _ _ _| _ _ + * | (_)\/(_)(_|\/| |(/_ v1.0.0 + * / / + */ + +package com.twilio.twiml.voice; + +import com.twilio.converter.Promoter; +import com.twilio.http.HttpMethod; +import org.junit.Assert; +import org.junit.Test; + +import java.net.URI; +import java.util.List; + +/** + * Test class for {@link WhatsApp} + */ +public class WhatsAppTest { + @Test + public void testElementWithParams() { + WhatsApp elem = new WhatsApp.Builder(new com.twilio.type.PhoneNumber("+15017122661")) + .url(URI.create("https://example.com")) + .method(HttpMethod.GET) + .statusCallbackEvents(Promoter.listOfOne(WhatsApp.Event.INITIATED)) + .statusCallback(URI.create("https://example.com")) + .statusCallbackMethod(HttpMethod.GET) + .build(); + + Assert.assertEquals( + "" + + "+15017122661", + elem.toXml() + ); + } + + @Test + public void testXmlAttributesDeserialization() { + final WhatsApp elem = new WhatsApp.Builder(new com.twilio.type.PhoneNumber("+15017122661")) + .url(URI.create("https://example.com")) + .method(HttpMethod.GET) + .statusCallbackEvents(Promoter.listOfOne(WhatsApp.Event.INITIATED)) + .statusCallback(URI.create("https://example.com")) + .statusCallbackMethod(HttpMethod.GET) + .build(); + + Assert.assertEquals( + WhatsApp.Builder.fromXml("+15017122661").build().toXml(), + elem.toXml() + ); + } +} \ No newline at end of file From 04f1e083084ec3e9a10dc5b70474656b3c925c2c Mon Sep 17 00:00:00 2001 From: Twilio Date: Thu, 3 Jul 2025 09:41:54 +0000 Subject: [PATCH 05/32] Release 11.0.0-rc.1 --- pom.xml | 6 +++--- src/main/java/com/twilio/Twilio.java | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/pom.xml b/pom.xml index ccd11db341..c000ec13c2 100644 --- a/pom.xml +++ b/pom.xml @@ -5,7 +5,7 @@ twilio jar twilio - 11.0.0-rc.0 + 11.0.0-rc.1 Twilio Java Helper Library https://www.twilio.com @@ -19,7 +19,7 @@ git@github.com:twilio/twilio-java.git scm:git:git@github.com:twilio/twilio-java.git scm:git:git@github.com:twilio/twilio-java.git - 10.9.2 + 11.0.0-rc.1 @@ -490,4 +490,4 @@ - + \ No newline at end of file diff --git a/src/main/java/com/twilio/Twilio.java b/src/main/java/com/twilio/Twilio.java index b2827de8f3..1fb6a5f9b5 100644 --- a/src/main/java/com/twilio/Twilio.java +++ b/src/main/java/com/twilio/Twilio.java @@ -24,7 +24,7 @@ */ public class Twilio { - public static final String VERSION = "11.0.0-rc.0"; + public static final String VERSION = "11.0.0-rc.1"; public static final String JAVA_VERSION = System.getProperty("java.version"); public static final String OS_NAME = System.getProperty("os.name"); public static final String OS_ARCH = System.getProperty("os.arch"); From c469b61dd40c60d3c81e7dff439a2be95bed14c8 Mon Sep 17 00:00:00 2001 From: Twilio Date: Thu, 10 Jul 2025 11:47:40 +0000 Subject: [PATCH 06/32] [Librarian] Regenerated @ 39bbd47c92a659f8a7464cedcc75b92c7ba69773 f51169e3becf53bb375f9c7413aec0c78fe78fcc --- CHANGES.md | 6 ++++ .../rest/lookups/v2/LookupOverride.java | 30 ++++++++--------- ... => PortingWebhookConfigurationFetch.java} | 33 +++++++++++-------- ...tingWebhookConfigurationFetchFetcher.java} | 16 ++++++--- .../rest/sync/v1/service/DocumentCreator.java | 8 ++--- .../rest/sync/v1/service/DocumentUpdater.java | 7 ++-- .../v1/service/synclist/SyncListItem.java | 2 +- .../service/synclist/SyncListItemCreator.java | 10 +++--- .../service/synclist/SyncListItemUpdater.java | 7 ++-- .../sync/v1/service/syncmap/SyncMapItem.java | 2 +- .../service/syncmap/SyncMapItemCreator.java | 10 +++--- .../service/syncmap/SyncMapItemUpdater.java | 7 ++-- .../v1/service/syncstream/StreamMessage.java | 2 +- .../syncstream/StreamMessageCreator.java | 10 +++--- .../rest/video/v1/CompositionCreator.java | 10 ++---- .../rest/video/v1/CompositionHookCreator.java | 10 ++---- .../rest/video/v1/CompositionHookUpdater.java | 9 ++--- .../com/twilio/rest/video/v1/RoomCreator.java | 8 ++--- .../video/v1/room/RecordingRulesUpdater.java | 7 ++-- .../rest/video/v1/room/Transcriptions.java | 29 ++++++++-------- .../video/v1/room/TranscriptionsReader.java | 2 +- .../participant/SubscribeRulesUpdater.java | 7 ++-- 22 files changed, 113 insertions(+), 119 deletions(-) rename src/main/java/com/twilio/rest/numbers/v1/{Webhook.java => PortingWebhookConfigurationFetch.java} (82%) rename src/main/java/com/twilio/rest/numbers/v1/{WebhookFetcher.java => PortingWebhookConfigurationFetchFetcher.java} (79%) diff --git a/CHANGES.md b/CHANGES.md index 9ef65ffab7..46534c7b6d 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,6 +1,12 @@ twilio-java changelog ===================== +[2025-07-10] Version 11.0.0-rc.2 +-------------------------------- +**Flex** +- update team name for web_channel, webchat_init_token, webchat_refresh_token + + [2025-07-03] Version 11.0.0-rc.1 -------------------------------- **Library - Chore** diff --git a/src/main/java/com/twilio/rest/lookups/v2/LookupOverride.java b/src/main/java/com/twilio/rest/lookups/v2/LookupOverride.java index 2762094bfa..69b4c42558 100644 --- a/src/main/java/com/twilio/rest/lookups/v2/LookupOverride.java +++ b/src/main/java/com/twilio/rest/lookups/v2/LookupOverride.java @@ -239,7 +239,7 @@ public int hashCode() { ); } - public enum OriginalLineTypeEnum { + public enum OverriddenLineTypeEnum { MOBILE("mobile"), LANDLINE("landline"), TOLLFREE("tollFree"), @@ -255,7 +255,7 @@ public enum OriginalLineTypeEnum { private final String value; - private OriginalLineTypeEnum(final String value) { + private OverriddenLineTypeEnum(final String value) { this.value = value; } @@ -264,15 +264,15 @@ public String toString() { } @JsonCreator - public static OriginalLineTypeEnum forValue(final String value) { + public static OverriddenLineTypeEnum forValue(final String value) { return Promoter.enumFromString( value, - OriginalLineTypeEnum.values() + OverriddenLineTypeEnum.values() ); } } - public enum OverriddenLineTypeEnum { + public enum LineTypeEnum { MOBILE("mobile"), LANDLINE("landline"), TOLLFREE("tollFree"), @@ -288,7 +288,7 @@ public enum OverriddenLineTypeEnum { private final String value; - private OverriddenLineTypeEnum(final String value) { + private LineTypeEnum(final String value) { this.value = value; } @@ -297,15 +297,12 @@ public String toString() { } @JsonCreator - public static OverriddenLineTypeEnum forValue(final String value) { - return Promoter.enumFromString( - value, - OverriddenLineTypeEnum.values() - ); + public static LineTypeEnum forValue(final String value) { + return Promoter.enumFromString(value, LineTypeEnum.values()); } } - public enum LineTypeEnum { + public enum OriginalLineTypeEnum { MOBILE("mobile"), LANDLINE("landline"), TOLLFREE("tollFree"), @@ -321,7 +318,7 @@ public enum LineTypeEnum { private final String value; - private LineTypeEnum(final String value) { + private OriginalLineTypeEnum(final String value) { this.value = value; } @@ -330,8 +327,11 @@ public String toString() { } @JsonCreator - public static LineTypeEnum forValue(final String value) { - return Promoter.enumFromString(value, LineTypeEnum.values()); + public static OriginalLineTypeEnum forValue(final String value) { + return Promoter.enumFromString( + value, + OriginalLineTypeEnum.values() + ); } } } diff --git a/src/main/java/com/twilio/rest/numbers/v1/Webhook.java b/src/main/java/com/twilio/rest/numbers/v1/PortingWebhookConfigurationFetch.java similarity index 82% rename from src/main/java/com/twilio/rest/numbers/v1/Webhook.java rename to src/main/java/com/twilio/rest/numbers/v1/PortingWebhookConfigurationFetch.java index 6e9c6921dd..53c0f02a23 100644 --- a/src/main/java/com/twilio/rest/numbers/v1/Webhook.java +++ b/src/main/java/com/twilio/rest/numbers/v1/PortingWebhookConfigurationFetch.java @@ -35,28 +35,31 @@ @JsonIgnoreProperties(ignoreUnknown = true) @ToString -public class Webhook extends Resource { +public class PortingWebhookConfigurationFetch extends Resource { private static final long serialVersionUID = 270526030240961L; - public static WebhookFetcher fetcher() { - return new WebhookFetcher(); + public static PortingWebhookConfigurationFetchFetcher fetcher() { + return new PortingWebhookConfigurationFetchFetcher(); } /** - * Converts a JSON String into a Webhook object using the provided ObjectMapper. + * Converts a JSON String into a PortingWebhookConfigurationFetch object using the provided ObjectMapper. * * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper - * @return Webhook object represented by the provided JSON + * @return PortingWebhookConfigurationFetch object represented by the provided JSON */ - public static Webhook fromJson( + public static PortingWebhookConfigurationFetch fromJson( final String json, final ObjectMapper objectMapper ) { // Convert all checked exceptions to Runtime try { - return objectMapper.readValue(json, Webhook.class); + return objectMapper.readValue( + json, + PortingWebhookConfigurationFetch.class + ); } catch (final JsonMappingException | JsonParseException e) { throw new ApiException(e.getMessage(), e); } catch (final IOException e) { @@ -65,20 +68,23 @@ public static Webhook fromJson( } /** - * Converts a JSON InputStream into a Webhook object using the provided + * Converts a JSON InputStream into a PortingWebhookConfigurationFetch object using the provided * ObjectMapper. * * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper - * @return Webhook object represented by the provided JSON + * @return PortingWebhookConfigurationFetch object represented by the provided JSON */ - public static Webhook fromJson( + public static PortingWebhookConfigurationFetch fromJson( final InputStream json, final ObjectMapper objectMapper ) { // Convert all checked exceptions to Runtime try { - return objectMapper.readValue(json, Webhook.class); + return objectMapper.readValue( + json, + PortingWebhookConfigurationFetch.class + ); } catch (final JsonMappingException | JsonParseException e) { throw new ApiException(e.getMessage(), e); } catch (final IOException e) { @@ -94,7 +100,7 @@ public static Webhook fromJson( private final ZonedDateTime portOutTargetDateCreated; @JsonCreator - private Webhook( + private PortingWebhookConfigurationFetch( @JsonProperty("url") final URI url, @JsonProperty("port_in_target_url") final URI portInTargetUrl, @JsonProperty("port_out_target_url") final URI portOutTargetUrl, @@ -150,7 +156,8 @@ public boolean equals(final Object o) { return false; } - Webhook other = (Webhook) o; + PortingWebhookConfigurationFetch other = + (PortingWebhookConfigurationFetch) o; return ( Objects.equals(url, other.url) && diff --git a/src/main/java/com/twilio/rest/numbers/v1/WebhookFetcher.java b/src/main/java/com/twilio/rest/numbers/v1/PortingWebhookConfigurationFetchFetcher.java similarity index 79% rename from src/main/java/com/twilio/rest/numbers/v1/WebhookFetcher.java rename to src/main/java/com/twilio/rest/numbers/v1/PortingWebhookConfigurationFetchFetcher.java index ccffc00624..59d0dc599f 100644 --- a/src/main/java/com/twilio/rest/numbers/v1/WebhookFetcher.java +++ b/src/main/java/com/twilio/rest/numbers/v1/PortingWebhookConfigurationFetchFetcher.java @@ -25,12 +25,15 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class WebhookFetcher extends Fetcher { +public class PortingWebhookConfigurationFetchFetcher + extends Fetcher { - public WebhookFetcher() {} + public PortingWebhookConfigurationFetchFetcher() {} @Override - public Webhook fetch(final TwilioRestClient client) { + public PortingWebhookConfigurationFetch fetch( + final TwilioRestClient client + ) { String path = "/v1/Porting/Configuration/Webhook"; Request request = new Request( @@ -43,7 +46,7 @@ public Webhook fetch(final TwilioRestClient client) { if (response == null) { throw new ApiConnectionException( - "Webhook fetch failed: Unable to connect to server" + "PortingWebhookConfigurationFetch fetch failed: Unable to connect to server" ); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( @@ -59,6 +62,9 @@ public Webhook fetch(final TwilioRestClient client) { throw new ApiException(restException); } - return Webhook.fromJson(response.getStream(), client.getObjectMapper()); + return PortingWebhookConfigurationFetch.fromJson( + response.getStream(), + client.getObjectMapper() + ); } } diff --git a/src/main/java/com/twilio/rest/sync/v1/service/DocumentCreator.java b/src/main/java/com/twilio/rest/sync/v1/service/DocumentCreator.java index 9b5eca36b7..3ad46deab0 100644 --- a/src/main/java/com/twilio/rest/sync/v1/service/DocumentCreator.java +++ b/src/main/java/com/twilio/rest/sync/v1/service/DocumentCreator.java @@ -26,14 +26,12 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -import java.util.Map; -import java.util.Map; public class DocumentCreator extends Creator { private String pathServiceSid; private String uniqueName; - private Map data; + private Object data; private Integer ttl; public DocumentCreator(final String pathServiceSid) { @@ -45,7 +43,7 @@ public DocumentCreator setUniqueName(final String uniqueName) { return this; } - public DocumentCreator setData(final Map data) { + public DocumentCreator setData(final Object data) { this.data = data; return this; } @@ -102,7 +100,7 @@ private void addPostParams(final Request request) { request.addPostParam("UniqueName", uniqueName); } if (data != null) { - request.addPostParam("Data", Converter.mapToJson(data)); + request.addPostParam("Data", Converter.objectToJson(data)); } if (ttl != null) { request.addPostParam("Ttl", ttl.toString()); diff --git a/src/main/java/com/twilio/rest/sync/v1/service/DocumentUpdater.java b/src/main/java/com/twilio/rest/sync/v1/service/DocumentUpdater.java index 1561d4c8a2..8c4bb058d5 100644 --- a/src/main/java/com/twilio/rest/sync/v1/service/DocumentUpdater.java +++ b/src/main/java/com/twilio/rest/sync/v1/service/DocumentUpdater.java @@ -25,14 +25,13 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -import java.util.Map; public class DocumentUpdater extends Updater { private String pathServiceSid; private String pathSid; private String ifMatch; - private Map data; + private Object data; private Integer ttl; public DocumentUpdater(final String pathServiceSid, final String pathSid) { @@ -45,7 +44,7 @@ public DocumentUpdater setIfMatch(final String ifMatch) { return this; } - public DocumentUpdater setData(final Map data) { + public DocumentUpdater setData(final Object data) { this.data = data; return this; } @@ -101,7 +100,7 @@ public Document update(final TwilioRestClient client) { private void addPostParams(final Request request) { if (data != null) { - request.addPostParam("Data", Converter.mapToJson(data)); + request.addPostParam("Data", Converter.objectToJson(data)); } if (ttl != null) { request.addPostParam("Ttl", ttl.toString()); diff --git a/src/main/java/com/twilio/rest/sync/v1/service/synclist/SyncListItem.java b/src/main/java/com/twilio/rest/sync/v1/service/synclist/SyncListItem.java index c0d70df086..00bbcafebd 100644 --- a/src/main/java/com/twilio/rest/sync/v1/service/synclist/SyncListItem.java +++ b/src/main/java/com/twilio/rest/sync/v1/service/synclist/SyncListItem.java @@ -44,7 +44,7 @@ public class SyncListItem extends Resource { public static SyncListItemCreator creator( final String pathServiceSid, final String pathListSid, - final Map data + final Object data ) { return new SyncListItemCreator(pathServiceSid, pathListSid, data); } diff --git a/src/main/java/com/twilio/rest/sync/v1/service/synclist/SyncListItemCreator.java b/src/main/java/com/twilio/rest/sync/v1/service/synclist/SyncListItemCreator.java index 2af4101ee6..4d8ac8f192 100644 --- a/src/main/java/com/twilio/rest/sync/v1/service/synclist/SyncListItemCreator.java +++ b/src/main/java/com/twilio/rest/sync/v1/service/synclist/SyncListItemCreator.java @@ -26,14 +26,12 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -import java.util.Map; -import java.util.Map; public class SyncListItemCreator extends Creator { private String pathServiceSid; private String pathListSid; - private Map data; + private Object data; private Integer ttl; private Integer itemTtl; private Integer collectionTtl; @@ -41,14 +39,14 @@ public class SyncListItemCreator extends Creator { public SyncListItemCreator( final String pathServiceSid, final String pathListSid, - final Map data + final Object data ) { this.pathServiceSid = pathServiceSid; this.pathListSid = pathListSid; this.data = data; } - public SyncListItemCreator setData(final Map data) { + public SyncListItemCreator setData(final Object data) { this.data = data; return this; } @@ -114,7 +112,7 @@ public SyncListItem create(final TwilioRestClient client) { private void addPostParams(final Request request) { if (data != null) { - request.addPostParam("Data", Converter.mapToJson(data)); + request.addPostParam("Data", Converter.objectToJson(data)); } if (ttl != null) { request.addPostParam("Ttl", ttl.toString()); diff --git a/src/main/java/com/twilio/rest/sync/v1/service/synclist/SyncListItemUpdater.java b/src/main/java/com/twilio/rest/sync/v1/service/synclist/SyncListItemUpdater.java index df538d9384..24dde562ca 100644 --- a/src/main/java/com/twilio/rest/sync/v1/service/synclist/SyncListItemUpdater.java +++ b/src/main/java/com/twilio/rest/sync/v1/service/synclist/SyncListItemUpdater.java @@ -25,7 +25,6 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -import java.util.Map; public class SyncListItemUpdater extends Updater { @@ -33,7 +32,7 @@ public class SyncListItemUpdater extends Updater { private String pathListSid; private Integer pathIndex; private String ifMatch; - private Map data; + private Object data; private Integer ttl; private Integer itemTtl; private Integer collectionTtl; @@ -53,7 +52,7 @@ public SyncListItemUpdater setIfMatch(final String ifMatch) { return this; } - public SyncListItemUpdater setData(final Map data) { + public SyncListItemUpdater setData(final Object data) { this.data = data; return this; } @@ -120,7 +119,7 @@ public SyncListItem update(final TwilioRestClient client) { private void addPostParams(final Request request) { if (data != null) { - request.addPostParam("Data", Converter.mapToJson(data)); + request.addPostParam("Data", Converter.objectToJson(data)); } if (ttl != null) { request.addPostParam("Ttl", ttl.toString()); diff --git a/src/main/java/com/twilio/rest/sync/v1/service/syncmap/SyncMapItem.java b/src/main/java/com/twilio/rest/sync/v1/service/syncmap/SyncMapItem.java index e2c25935cf..f134d6fb0c 100644 --- a/src/main/java/com/twilio/rest/sync/v1/service/syncmap/SyncMapItem.java +++ b/src/main/java/com/twilio/rest/sync/v1/service/syncmap/SyncMapItem.java @@ -45,7 +45,7 @@ public static SyncMapItemCreator creator( final String pathServiceSid, final String pathMapSid, final String key, - final Map data + final Object data ) { return new SyncMapItemCreator(pathServiceSid, pathMapSid, key, data); } diff --git a/src/main/java/com/twilio/rest/sync/v1/service/syncmap/SyncMapItemCreator.java b/src/main/java/com/twilio/rest/sync/v1/service/syncmap/SyncMapItemCreator.java index 095e615ca2..c85bdbfeb9 100644 --- a/src/main/java/com/twilio/rest/sync/v1/service/syncmap/SyncMapItemCreator.java +++ b/src/main/java/com/twilio/rest/sync/v1/service/syncmap/SyncMapItemCreator.java @@ -26,15 +26,13 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -import java.util.Map; -import java.util.Map; public class SyncMapItemCreator extends Creator { private String pathServiceSid; private String pathMapSid; private String key; - private Map data; + private Object data; private Integer ttl; private Integer itemTtl; private Integer collectionTtl; @@ -43,7 +41,7 @@ public SyncMapItemCreator( final String pathServiceSid, final String pathMapSid, final String key, - final Map data + final Object data ) { this.pathServiceSid = pathServiceSid; this.pathMapSid = pathMapSid; @@ -56,7 +54,7 @@ public SyncMapItemCreator setKey(final String key) { return this; } - public SyncMapItemCreator setData(final Map data) { + public SyncMapItemCreator setData(final Object data) { this.data = data; return this; } @@ -126,7 +124,7 @@ private void addPostParams(final Request request) { request.addPostParam("Key", key); } if (data != null) { - request.addPostParam("Data", Converter.mapToJson(data)); + request.addPostParam("Data", Converter.objectToJson(data)); } if (ttl != null) { request.addPostParam("Ttl", ttl.toString()); diff --git a/src/main/java/com/twilio/rest/sync/v1/service/syncmap/SyncMapItemUpdater.java b/src/main/java/com/twilio/rest/sync/v1/service/syncmap/SyncMapItemUpdater.java index f9cb5af292..b0b1a151c0 100644 --- a/src/main/java/com/twilio/rest/sync/v1/service/syncmap/SyncMapItemUpdater.java +++ b/src/main/java/com/twilio/rest/sync/v1/service/syncmap/SyncMapItemUpdater.java @@ -25,7 +25,6 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -import java.util.Map; public class SyncMapItemUpdater extends Updater { @@ -33,7 +32,7 @@ public class SyncMapItemUpdater extends Updater { private String pathMapSid; private String pathKey; private String ifMatch; - private Map data; + private Object data; private Integer ttl; private Integer itemTtl; private Integer collectionTtl; @@ -53,7 +52,7 @@ public SyncMapItemUpdater setIfMatch(final String ifMatch) { return this; } - public SyncMapItemUpdater setData(final Map data) { + public SyncMapItemUpdater setData(final Object data) { this.data = data; return this; } @@ -120,7 +119,7 @@ public SyncMapItem update(final TwilioRestClient client) { private void addPostParams(final Request request) { if (data != null) { - request.addPostParam("Data", Converter.mapToJson(data)); + request.addPostParam("Data", Converter.objectToJson(data)); } if (ttl != null) { request.addPostParam("Ttl", ttl.toString()); diff --git a/src/main/java/com/twilio/rest/sync/v1/service/syncstream/StreamMessage.java b/src/main/java/com/twilio/rest/sync/v1/service/syncstream/StreamMessage.java index 7191f3acc2..b787e9d5a1 100644 --- a/src/main/java/com/twilio/rest/sync/v1/service/syncstream/StreamMessage.java +++ b/src/main/java/com/twilio/rest/sync/v1/service/syncstream/StreamMessage.java @@ -40,7 +40,7 @@ public class StreamMessage extends Resource { public static StreamMessageCreator creator( final String pathServiceSid, final String pathStreamSid, - final Map data + final Object data ) { return new StreamMessageCreator(pathServiceSid, pathStreamSid, data); } diff --git a/src/main/java/com/twilio/rest/sync/v1/service/syncstream/StreamMessageCreator.java b/src/main/java/com/twilio/rest/sync/v1/service/syncstream/StreamMessageCreator.java index 5739a6e69d..015002f303 100644 --- a/src/main/java/com/twilio/rest/sync/v1/service/syncstream/StreamMessageCreator.java +++ b/src/main/java/com/twilio/rest/sync/v1/service/syncstream/StreamMessageCreator.java @@ -26,26 +26,24 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -import java.util.Map; -import java.util.Map; public class StreamMessageCreator extends Creator { private String pathServiceSid; private String pathStreamSid; - private Map data; + private Object data; public StreamMessageCreator( final String pathServiceSid, final String pathStreamSid, - final Map data + final Object data ) { this.pathServiceSid = pathServiceSid; this.pathStreamSid = pathStreamSid; this.data = data; } - public StreamMessageCreator setData(final Map data) { + public StreamMessageCreator setData(final Object data) { this.data = data; return this; } @@ -100,7 +98,7 @@ public StreamMessage create(final TwilioRestClient client) { private void addPostParams(final Request request) { if (data != null) { - request.addPostParam("Data", Converter.mapToJson(data)); + request.addPostParam("Data", Converter.objectToJson(data)); } } } diff --git a/src/main/java/com/twilio/rest/video/v1/CompositionCreator.java b/src/main/java/com/twilio/rest/video/v1/CompositionCreator.java index 3c579d6781..f162cd921c 100644 --- a/src/main/java/com/twilio/rest/video/v1/CompositionCreator.java +++ b/src/main/java/com/twilio/rest/video/v1/CompositionCreator.java @@ -31,13 +31,11 @@ import java.net.URI; import java.util.List; import java.util.List; -import java.util.Map; -import java.util.Map; public class CompositionCreator extends Creator { private String roomSid; - private Map videoLayout; + private Object videoLayout; private List audioSources; private List audioSourcesExcluded; private String resolution; @@ -55,9 +53,7 @@ public CompositionCreator setRoomSid(final String roomSid) { return this; } - public CompositionCreator setVideoLayout( - final Map videoLayout - ) { + public CompositionCreator setVideoLayout(final Object videoLayout) { this.videoLayout = videoLayout; return this; } @@ -162,7 +158,7 @@ private void addPostParams(final Request request) { if (videoLayout != null) { request.addPostParam( "VideoLayout", - Converter.mapToJson(videoLayout) + Converter.objectToJson(videoLayout) ); } if (audioSources != null) { diff --git a/src/main/java/com/twilio/rest/video/v1/CompositionHookCreator.java b/src/main/java/com/twilio/rest/video/v1/CompositionHookCreator.java index 356fac4185..627d5ef831 100644 --- a/src/main/java/com/twilio/rest/video/v1/CompositionHookCreator.java +++ b/src/main/java/com/twilio/rest/video/v1/CompositionHookCreator.java @@ -31,14 +31,12 @@ import java.net.URI; import java.util.List; import java.util.List; -import java.util.Map; -import java.util.Map; public class CompositionHookCreator extends Creator { private String friendlyName; private Boolean enabled; - private Map videoLayout; + private Object videoLayout; private List audioSources; private List audioSourcesExcluded; private String resolution; @@ -61,9 +59,7 @@ public CompositionHookCreator setEnabled(final Boolean enabled) { return this; } - public CompositionHookCreator setVideoLayout( - final Map videoLayout - ) { + public CompositionHookCreator setVideoLayout(final Object videoLayout) { this.videoLayout = videoLayout; return this; } @@ -181,7 +177,7 @@ private void addPostParams(final Request request) { if (videoLayout != null) { request.addPostParam( "VideoLayout", - Converter.mapToJson(videoLayout) + Converter.objectToJson(videoLayout) ); } if (audioSources != null) { diff --git a/src/main/java/com/twilio/rest/video/v1/CompositionHookUpdater.java b/src/main/java/com/twilio/rest/video/v1/CompositionHookUpdater.java index 90c84daa88..7fe754444a 100644 --- a/src/main/java/com/twilio/rest/video/v1/CompositionHookUpdater.java +++ b/src/main/java/com/twilio/rest/video/v1/CompositionHookUpdater.java @@ -28,14 +28,13 @@ import com.twilio.rest.Domains; import java.net.URI; import java.util.List; -import java.util.Map; public class CompositionHookUpdater extends Updater { private String pathSid; private String friendlyName; private Boolean enabled; - private Map videoLayout; + private Object videoLayout; private List audioSources; private List audioSourcesExcluded; private Boolean trim; @@ -62,9 +61,7 @@ public CompositionHookUpdater setEnabled(final Boolean enabled) { return this; } - public CompositionHookUpdater setVideoLayout( - final Map videoLayout - ) { + public CompositionHookUpdater setVideoLayout(final Object videoLayout) { this.videoLayout = videoLayout; return this; } @@ -183,7 +180,7 @@ private void addPostParams(final Request request) { if (videoLayout != null) { request.addPostParam( "VideoLayout", - Converter.mapToJson(videoLayout) + Converter.objectToJson(videoLayout) ); } if (audioSources != null) { diff --git a/src/main/java/com/twilio/rest/video/v1/RoomCreator.java b/src/main/java/com/twilio/rest/video/v1/RoomCreator.java index 01acec6599..fae39d57e0 100644 --- a/src/main/java/com/twilio/rest/video/v1/RoomCreator.java +++ b/src/main/java/com/twilio/rest/video/v1/RoomCreator.java @@ -46,7 +46,7 @@ public class RoomCreator extends Creator { private Boolean transcribeParticipantsOnConnect; private List videoCodecs; private String mediaRegion; - private Map recordingRules; + private Object recordingRules; private Map transcriptionsConfiguration; private Boolean audioOnly; private Integer maxParticipantDuration; @@ -120,9 +120,7 @@ public RoomCreator setMediaRegion(final String mediaRegion) { return this; } - public RoomCreator setRecordingRules( - final Map recordingRules - ) { + public RoomCreator setRecordingRules(final Object recordingRules) { this.recordingRules = recordingRules; return this; } @@ -239,7 +237,7 @@ private void addPostParams(final Request request) { if (recordingRules != null) { request.addPostParam( "RecordingRules", - Converter.mapToJson(recordingRules) + Converter.objectToJson(recordingRules) ); } if (transcriptionsConfiguration != null) { diff --git a/src/main/java/com/twilio/rest/video/v1/room/RecordingRulesUpdater.java b/src/main/java/com/twilio/rest/video/v1/room/RecordingRulesUpdater.java index 4a726e6315..e4a8477092 100644 --- a/src/main/java/com/twilio/rest/video/v1/room/RecordingRulesUpdater.java +++ b/src/main/java/com/twilio/rest/video/v1/room/RecordingRulesUpdater.java @@ -25,18 +25,17 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -import java.util.Map; public class RecordingRulesUpdater extends Updater { private String pathRoomSid; - private Map rules; + private Object rules; public RecordingRulesUpdater(final String pathRoomSid) { this.pathRoomSid = pathRoomSid; } - public RecordingRulesUpdater setRules(final Map rules) { + public RecordingRulesUpdater setRules(final Object rules) { this.rules = rules; return this; } @@ -81,7 +80,7 @@ public RecordingRules update(final TwilioRestClient client) { private void addPostParams(final Request request) { if (rules != null) { - request.addPostParam("Rules", Converter.mapToJson(rules)); + request.addPostParam("Rules", Converter.objectToJson(rules)); } } } diff --git a/src/main/java/com/twilio/rest/video/v1/room/Transcriptions.java b/src/main/java/com/twilio/rest/video/v1/room/Transcriptions.java index d5f741d671..ed27576b7e 100644 --- a/src/main/java/com/twilio/rest/video/v1/room/Transcriptions.java +++ b/src/main/java/com/twilio/rest/video/v1/room/Transcriptions.java @@ -29,6 +29,8 @@ import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; +import java.util.Map; +import java.util.Map; import java.util.Objects; import lombok.ToString; import lombok.ToString; @@ -37,7 +39,7 @@ @ToString public class Transcriptions extends Resource { - private static final long serialVersionUID = 265092932948237L; + private static final long serialVersionUID = 69820289152110L; public static TranscriptionsCreator creator(final String pathRoomSid) { return new TranscriptionsCreator(pathRoomSid); @@ -108,13 +110,13 @@ public static Transcriptions fromJson( private final String accountSid; private final String roomSid; private final Transcriptions.Status status; - private final String identity; private final ZonedDateTime dateCreated; private final ZonedDateTime dateUpdated; private final ZonedDateTime startTime; private final ZonedDateTime endTime; private final Integer duration; private final URI url; + private final Map configuration; @JsonCreator private Transcriptions( @@ -122,25 +124,25 @@ private Transcriptions( @JsonProperty("account_sid") final String accountSid, @JsonProperty("room_sid") final String roomSid, @JsonProperty("status") final Transcriptions.Status status, - @JsonProperty("identity") final String identity, @JsonProperty("date_created") final String dateCreated, @JsonProperty("date_updated") final String dateUpdated, @JsonProperty("start_time") final String startTime, @JsonProperty("end_time") final String endTime, @JsonProperty("duration") final Integer duration, - @JsonProperty("url") final URI url + @JsonProperty("url") final URI url, + @JsonProperty("configuration") final Map configuration ) { this.ttid = ttid; this.accountSid = accountSid; this.roomSid = roomSid; this.status = status; - this.identity = identity; this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); this.startTime = DateConverter.iso8601DateTimeFromString(startTime); this.endTime = DateConverter.iso8601DateTimeFromString(endTime); this.duration = duration; this.url = url; + this.configuration = configuration; } public final String getTtid() { @@ -159,10 +161,6 @@ public final Transcriptions.Status getStatus() { return this.status; } - public final String getIdentity() { - return this.identity; - } - public final ZonedDateTime getDateCreated() { return this.dateCreated; } @@ -187,6 +185,10 @@ public final URI getUrl() { return this.url; } + public final Map getConfiguration() { + return this.configuration; + } + @Override public boolean equals(final Object o) { if (this == o) { @@ -204,13 +206,13 @@ public boolean equals(final Object o) { Objects.equals(accountSid, other.accountSid) && Objects.equals(roomSid, other.roomSid) && Objects.equals(status, other.status) && - Objects.equals(identity, other.identity) && Objects.equals(dateCreated, other.dateCreated) && Objects.equals(dateUpdated, other.dateUpdated) && Objects.equals(startTime, other.startTime) && Objects.equals(endTime, other.endTime) && Objects.equals(duration, other.duration) && - Objects.equals(url, other.url) + Objects.equals(url, other.url) && + Objects.equals(configuration, other.configuration) ); } @@ -221,18 +223,17 @@ public int hashCode() { accountSid, roomSid, status, - identity, dateCreated, dateUpdated, startTime, endTime, duration, - url + url, + configuration ); } public enum Status { - CREATED("created"), STARTED("started"), STOPPED("stopped"), FAILED("failed"); diff --git a/src/main/java/com/twilio/rest/video/v1/room/TranscriptionsReader.java b/src/main/java/com/twilio/rest/video/v1/room/TranscriptionsReader.java index 7cb0570421..32ee246d4a 100644 --- a/src/main/java/com/twilio/rest/video/v1/room/TranscriptionsReader.java +++ b/src/main/java/com/twilio/rest/video/v1/room/TranscriptionsReader.java @@ -86,7 +86,7 @@ private Page pageForRequest( } return Page.fromJson( - "extensions", + "transcriptions", response.getContent(), Transcriptions.class, client.getObjectMapper() diff --git a/src/main/java/com/twilio/rest/video/v1/room/participant/SubscribeRulesUpdater.java b/src/main/java/com/twilio/rest/video/v1/room/participant/SubscribeRulesUpdater.java index 6878b5373b..f33515b655 100644 --- a/src/main/java/com/twilio/rest/video/v1/room/participant/SubscribeRulesUpdater.java +++ b/src/main/java/com/twilio/rest/video/v1/room/participant/SubscribeRulesUpdater.java @@ -25,13 +25,12 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -import java.util.Map; public class SubscribeRulesUpdater extends Updater { private String pathRoomSid; private String pathParticipantSid; - private Map rules; + private Object rules; public SubscribeRulesUpdater( final String pathRoomSid, @@ -41,7 +40,7 @@ public SubscribeRulesUpdater( this.pathParticipantSid = pathParticipantSid; } - public SubscribeRulesUpdater setRules(final Map rules) { + public SubscribeRulesUpdater setRules(final Object rules) { this.rules = rules; return this; } @@ -92,7 +91,7 @@ public SubscribeRules update(final TwilioRestClient client) { private void addPostParams(final Request request) { if (rules != null) { - request.addPostParam("Rules", Converter.mapToJson(rules)); + request.addPostParam("Rules", Converter.objectToJson(rules)); } } } From 3ba6d3c95e5c4db06650721e454979266ba5982b Mon Sep 17 00:00:00 2001 From: Twilio Date: Thu, 10 Jul 2025 11:50:42 +0000 Subject: [PATCH 07/32] Release 11.0.0-rc.2 --- pom.xml | 4 ++-- src/main/java/com/twilio/Twilio.java | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/pom.xml b/pom.xml index c000ec13c2..6550cce867 100644 --- a/pom.xml +++ b/pom.xml @@ -5,7 +5,7 @@ twilio jar twilio - 11.0.0-rc.1 + 11.0.0-rc.2 Twilio Java Helper Library https://www.twilio.com @@ -19,7 +19,7 @@ git@github.com:twilio/twilio-java.git scm:git:git@github.com:twilio/twilio-java.git scm:git:git@github.com:twilio/twilio-java.git - 11.0.0-rc.1 + 11.0.0-rc.2 diff --git a/src/main/java/com/twilio/Twilio.java b/src/main/java/com/twilio/Twilio.java index 1fb6a5f9b5..a41f0fa68b 100644 --- a/src/main/java/com/twilio/Twilio.java +++ b/src/main/java/com/twilio/Twilio.java @@ -24,7 +24,7 @@ */ public class Twilio { - public static final String VERSION = "11.0.0-rc.1"; + public static final String VERSION = "11.0.0-rc.2"; public static final String JAVA_VERSION = System.getProperty("java.version"); public static final String OS_NAME = System.getProperty("os.name"); public static final String OS_ARCH = System.getProperty("os.arch"); From 5845dc39f3bc2933b7c851f7ee88607bdfc32e1e Mon Sep 17 00:00:00 2001 From: Twilio Date: Thu, 24 Jul 2025 07:59:12 +0000 Subject: [PATCH 08/32] [Librarian] Regenerated @ 4b32678e9d8859e19f1feb1af566eea8533a36c9 51518c9f2f9294597fd0471d5c647016ef4023ee --- CHANGES.md | 11 + .../rest/events/v1/SubscriptionUpdater.java | 9 - .../rest/insights/v1/CallSummariesReader.java | 38 ++ ...okConfigurationFetch.java => Webhook.java} | 33 +- ...nFetchFetcher.java => WebhookFetcher.java} | 16 +- src/main/java/com/twilio/twiml/voice/Say.java | 384 +++++++++++++++++- 6 files changed, 447 insertions(+), 44 deletions(-) rename src/main/java/com/twilio/rest/numbers/v1/{PortingWebhookConfigurationFetch.java => Webhook.java} (82%) rename src/main/java/com/twilio/rest/numbers/v1/{PortingWebhookConfigurationFetchFetcher.java => WebhookFetcher.java} (79%) diff --git a/CHANGES.md b/CHANGES.md index 46534c7b6d..b410ee82df 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,6 +1,17 @@ twilio-java changelog ===================== +[2025-07-24] Version 11.0.0-rc.3 +-------------------------------- +**Events** +- Remove `SinkSid` parameter when updating subscriptions. **(breaking change)** + +**Twiml** +- Remove Duplicates. +- Add Polly Generative voices. +- Add Latest Google (Chirp3-HD) voices. + + [2025-07-10] Version 11.0.0-rc.2 -------------------------------- **Flex** diff --git a/src/main/java/com/twilio/rest/events/v1/SubscriptionUpdater.java b/src/main/java/com/twilio/rest/events/v1/SubscriptionUpdater.java index adefd8eab6..a6907cb6e5 100644 --- a/src/main/java/com/twilio/rest/events/v1/SubscriptionUpdater.java +++ b/src/main/java/com/twilio/rest/events/v1/SubscriptionUpdater.java @@ -29,7 +29,6 @@ public class SubscriptionUpdater extends Updater { private String pathSid; private String description; - private String sinkSid; public SubscriptionUpdater(final String pathSid) { this.pathSid = pathSid; @@ -40,11 +39,6 @@ public SubscriptionUpdater setDescription(final String description) { return this; } - public SubscriptionUpdater setSinkSid(final String sinkSid) { - this.sinkSid = sinkSid; - return this; - } - @Override public Subscription update(final TwilioRestClient client) { String path = "/v1/Subscriptions/{Sid}"; @@ -87,8 +81,5 @@ private void addPostParams(final Request request) { if (description != null) { request.addPostParam("Description", description); } - if (sinkSid != null) { - request.addPostParam("SinkSid", sinkSid); - } } } diff --git a/src/main/java/com/twilio/rest/insights/v1/CallSummariesReader.java b/src/main/java/com/twilio/rest/insights/v1/CallSummariesReader.java index 5c1f1334a7..b298cde879 100644 --- a/src/main/java/com/twilio/rest/insights/v1/CallSummariesReader.java +++ b/src/main/java/com/twilio/rest/insights/v1/CallSummariesReader.java @@ -55,6 +55,10 @@ public class CallSummariesReader extends Reader { private Boolean brandedEnabled; private Boolean voiceIntegrityEnabled; private String brandedBundleSid; + private Boolean brandedLogo; + private String brandedType; + private String brandedUseCase; + private String brandedCallReason; private String voiceIntegrityBundleSid; private String voiceIntegrityUseCase; private String businessProfileIdentity; @@ -215,6 +219,28 @@ public CallSummariesReader setBrandedBundleSid( return this; } + public CallSummariesReader setBrandedLogo(final Boolean brandedLogo) { + this.brandedLogo = brandedLogo; + return this; + } + + public CallSummariesReader setBrandedType(final String brandedType) { + this.brandedType = brandedType; + return this; + } + + public CallSummariesReader setBrandedUseCase(final String brandedUseCase) { + this.brandedUseCase = brandedUseCase; + return this; + } + + public CallSummariesReader setBrandedCallReason( + final String brandedCallReason + ) { + this.brandedCallReason = brandedCallReason; + return this; + } + public CallSummariesReader setVoiceIntegrityBundleSid( final String voiceIntegrityBundleSid ) { @@ -441,6 +467,18 @@ private void addQueryParams(final Request request) { if (brandedBundleSid != null) { request.addQueryParam("BrandedBundleSid", brandedBundleSid); } + if (brandedLogo != null) { + request.addQueryParam("BrandedLogo", brandedLogo.toString()); + } + if (brandedType != null) { + request.addQueryParam("BrandedType", brandedType); + } + if (brandedUseCase != null) { + request.addQueryParam("BrandedUseCase", brandedUseCase); + } + if (brandedCallReason != null) { + request.addQueryParam("BrandedCallReason", brandedCallReason); + } if (voiceIntegrityBundleSid != null) { request.addQueryParam( "VoiceIntegrityBundleSid", diff --git a/src/main/java/com/twilio/rest/numbers/v1/PortingWebhookConfigurationFetch.java b/src/main/java/com/twilio/rest/numbers/v1/Webhook.java similarity index 82% rename from src/main/java/com/twilio/rest/numbers/v1/PortingWebhookConfigurationFetch.java rename to src/main/java/com/twilio/rest/numbers/v1/Webhook.java index 53c0f02a23..6e9c6921dd 100644 --- a/src/main/java/com/twilio/rest/numbers/v1/PortingWebhookConfigurationFetch.java +++ b/src/main/java/com/twilio/rest/numbers/v1/Webhook.java @@ -35,31 +35,28 @@ @JsonIgnoreProperties(ignoreUnknown = true) @ToString -public class PortingWebhookConfigurationFetch extends Resource { +public class Webhook extends Resource { private static final long serialVersionUID = 270526030240961L; - public static PortingWebhookConfigurationFetchFetcher fetcher() { - return new PortingWebhookConfigurationFetchFetcher(); + public static WebhookFetcher fetcher() { + return new WebhookFetcher(); } /** - * Converts a JSON String into a PortingWebhookConfigurationFetch object using the provided ObjectMapper. + * Converts a JSON String into a Webhook object using the provided ObjectMapper. * * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper - * @return PortingWebhookConfigurationFetch object represented by the provided JSON + * @return Webhook object represented by the provided JSON */ - public static PortingWebhookConfigurationFetch fromJson( + public static Webhook fromJson( final String json, final ObjectMapper objectMapper ) { // Convert all checked exceptions to Runtime try { - return objectMapper.readValue( - json, - PortingWebhookConfigurationFetch.class - ); + return objectMapper.readValue(json, Webhook.class); } catch (final JsonMappingException | JsonParseException e) { throw new ApiException(e.getMessage(), e); } catch (final IOException e) { @@ -68,23 +65,20 @@ public static PortingWebhookConfigurationFetch fromJson( } /** - * Converts a JSON InputStream into a PortingWebhookConfigurationFetch object using the provided + * Converts a JSON InputStream into a Webhook object using the provided * ObjectMapper. * * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper - * @return PortingWebhookConfigurationFetch object represented by the provided JSON + * @return Webhook object represented by the provided JSON */ - public static PortingWebhookConfigurationFetch fromJson( + public static Webhook fromJson( final InputStream json, final ObjectMapper objectMapper ) { // Convert all checked exceptions to Runtime try { - return objectMapper.readValue( - json, - PortingWebhookConfigurationFetch.class - ); + return objectMapper.readValue(json, Webhook.class); } catch (final JsonMappingException | JsonParseException e) { throw new ApiException(e.getMessage(), e); } catch (final IOException e) { @@ -100,7 +94,7 @@ public static PortingWebhookConfigurationFetch fromJson( private final ZonedDateTime portOutTargetDateCreated; @JsonCreator - private PortingWebhookConfigurationFetch( + private Webhook( @JsonProperty("url") final URI url, @JsonProperty("port_in_target_url") final URI portInTargetUrl, @JsonProperty("port_out_target_url") final URI portOutTargetUrl, @@ -156,8 +150,7 @@ public boolean equals(final Object o) { return false; } - PortingWebhookConfigurationFetch other = - (PortingWebhookConfigurationFetch) o; + Webhook other = (Webhook) o; return ( Objects.equals(url, other.url) && diff --git a/src/main/java/com/twilio/rest/numbers/v1/PortingWebhookConfigurationFetchFetcher.java b/src/main/java/com/twilio/rest/numbers/v1/WebhookFetcher.java similarity index 79% rename from src/main/java/com/twilio/rest/numbers/v1/PortingWebhookConfigurationFetchFetcher.java rename to src/main/java/com/twilio/rest/numbers/v1/WebhookFetcher.java index 59d0dc599f..ccffc00624 100644 --- a/src/main/java/com/twilio/rest/numbers/v1/PortingWebhookConfigurationFetchFetcher.java +++ b/src/main/java/com/twilio/rest/numbers/v1/WebhookFetcher.java @@ -25,15 +25,12 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class PortingWebhookConfigurationFetchFetcher - extends Fetcher { +public class WebhookFetcher extends Fetcher { - public PortingWebhookConfigurationFetchFetcher() {} + public WebhookFetcher() {} @Override - public PortingWebhookConfigurationFetch fetch( - final TwilioRestClient client - ) { + public Webhook fetch(final TwilioRestClient client) { String path = "/v1/Porting/Configuration/Webhook"; Request request = new Request( @@ -46,7 +43,7 @@ public PortingWebhookConfigurationFetch fetch( if (response == null) { throw new ApiConnectionException( - "PortingWebhookConfigurationFetch fetch failed: Unable to connect to server" + "Webhook fetch failed: Unable to connect to server" ); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( @@ -62,9 +59,6 @@ public PortingWebhookConfigurationFetch fetch( throw new ApiException(restException); } - return PortingWebhookConfigurationFetch.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Webhook.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/twiml/voice/Say.java b/src/main/java/com/twilio/twiml/voice/Say.java index 094000e5a7..c317fe078e 100644 --- a/src/main/java/com/twilio/twiml/voice/Say.java +++ b/src/main/java/com/twilio/twiml/voice/Say.java @@ -31,6 +31,14 @@ public enum Voice { GOOGLE_AM_ET_STANDARD_B("Google.am-ET-Standard-B"), GOOGLE_AM_ET_WAVENET_A("Google.am-ET-Wavenet-A"), GOOGLE_AM_ET_WAVENET_B("Google.am-ET-Wavenet-B"), + GOOGLE_AR_XA_CHIRP3_HD_AOEDE("Google.ar-XA-Chirp3-HD-Aoede"), + GOOGLE_AR_XA_CHIRP3_HD_CHARON("Google.ar-XA-Chirp3-HD-Charon"), + GOOGLE_AR_XA_CHIRP3_HD_FENRIR("Google.ar-XA-Chirp3-HD-Fenrir"), + GOOGLE_AR_XA_CHIRP3_HD_KORE("Google.ar-XA-Chirp3-HD-Kore"), + GOOGLE_AR_XA_CHIRP3_HD_LEDA("Google.ar-XA-Chirp3-HD-Leda"), + GOOGLE_AR_XA_CHIRP3_HD_ORUS("Google.ar-XA-Chirp3-HD-Orus"), + GOOGLE_AR_XA_CHIRP3_HD_PUCK("Google.ar-XA-Chirp3-HD-Puck"), + GOOGLE_AR_XA_CHIRP3_HD_ZEPHYR("Google.ar-XA-Chirp3-HD-Zephyr"), GOOGLE_AR_XA_STANDARD_A("Google.ar-XA-Standard-A"), GOOGLE_AR_XA_STANDARD_B("Google.ar-XA-Standard-B"), GOOGLE_AR_XA_STANDARD_C("Google.ar-XA-Standard-C"), @@ -40,11 +48,33 @@ public enum Voice { GOOGLE_AR_XA_WAVENET_C("Google.ar-XA-Wavenet-C"), GOOGLE_AR_XA_WAVENET_D("Google.ar-XA-Wavenet-D"), GOOGLE_BG_BG_STANDARD_A("Google.bg-BG-Standard-A"), + GOOGLE_BG_BG_STANDARD_B("Google.bg-BG-Standard-B"), + GOOGLE_BN_IN_CHIRP3_HD_AOEDE("Google.bn-IN-Chirp3-HD-Aoede"), + GOOGLE_BN_IN_CHIRP3_HD_CHARON("Google.bn-IN-Chirp3-HD-Charon"), + GOOGLE_BN_IN_CHIRP3_HD_FENRIR("Google.bn-IN-Chirp3-HD-Fenrir"), + GOOGLE_BN_IN_CHIRP3_HD_KORE("Google.bn-IN-Chirp3-HD-Kore"), + GOOGLE_BN_IN_CHIRP3_HD_LEDA("Google.bn-IN-Chirp3-HD-Leda"), + GOOGLE_BN_IN_CHIRP3_HD_ORUS("Google.bn-IN-Chirp3-HD-Orus"), + GOOGLE_BN_IN_CHIRP3_HD_PUCK("Google.bn-IN-Chirp3-HD-Puck"), + GOOGLE_BN_IN_CHIRP3_HD_ZEPHYR("Google.bn-IN-Chirp3-HD-Zephyr"), + GOOGLE_BN_IN_STANDARD_A("Google.bn-IN-Standard-A"), + GOOGLE_BN_IN_STANDARD_B("Google.bn-IN-Standard-B"), GOOGLE_BN_IN_STANDARD_C("Google.bn-IN-Standard-C"), GOOGLE_BN_IN_STANDARD_D("Google.bn-IN-Standard-D"), + GOOGLE_BN_IN_WAVENET_A("Google.bn-IN-Wavenet-A"), + GOOGLE_BN_IN_WAVENET_B("Google.bn-IN-Wavenet-B"), GOOGLE_BN_IN_WAVENET_C("Google.bn-IN-Wavenet-C"), GOOGLE_BN_IN_WAVENET_D("Google.bn-IN-Wavenet-D"), GOOGLE_CA_ES_STANDARD_A("Google.ca-ES-Standard-A"), + GOOGLE_CA_ES_STANDARD_B("Google.ca-ES-Standard-B"), + GOOGLE_CMN_CN_CHIRP3_HD_AOEDE("Google.cmn-CN-Chirp3-HD-Aoede"), + GOOGLE_CMN_CN_CHIRP3_HD_CHARON("Google.cmn-CN-Chirp3-HD-Charon"), + GOOGLE_CMN_CN_CHIRP3_HD_FENRIR("Google.cmn-CN-Chirp3-HD-Fenrir"), + GOOGLE_CMN_CN_CHIRP3_HD_KORE("Google.cmn-CN-Chirp3-HD-Kore"), + GOOGLE_CMN_CN_CHIRP3_HD_LEDA("Google.cmn-CN-Chirp3-HD-Leda"), + GOOGLE_CMN_CN_CHIRP3_HD_ORUS("Google.cmn-CN-Chirp3-HD-Orus"), + GOOGLE_CMN_CN_CHIRP3_HD_PUCK("Google.cmn-CN-Chirp3-HD-Puck"), + GOOGLE_CMN_CN_CHIRP3_HD_ZEPHYR("Google.cmn-CN-Chirp3-HD-Zephyr"), GOOGLE_CMN_CN_STANDARD_A("Google.cmn-CN-Standard-A"), GOOGLE_CMN_CN_STANDARD_B("Google.cmn-CN-Standard-B"), GOOGLE_CMN_CN_STANDARD_C("Google.cmn-CN-Standard-C"), @@ -60,36 +90,66 @@ public enum Voice { GOOGLE_CMN_TW_WAVENET_B("Google.cmn-TW-Wavenet-B"), GOOGLE_CMN_TW_WAVENET_C("Google.cmn-TW-Wavenet-C"), GOOGLE_CS_CZ_STANDARD_A("Google.cs-CZ-Standard-A"), + GOOGLE_CS_CZ_STANDARD_B("Google.cs-CZ-Standard-B"), GOOGLE_CS_CZ_WAVENET_A("Google.cs-CZ-Wavenet-A"), + GOOGLE_CS_CZ_WAVENET_B("Google.cs-CZ-Wavenet-B"), GOOGLE_DA_DK_NEURAL2_D("Google.da-DK-Neural2-D"), GOOGLE_DA_DK_NEURAL2_F("Google.da-DK-Neural2-F"), GOOGLE_DA_DK_STANDARD_A("Google.da-DK-Standard-A"), GOOGLE_DA_DK_STANDARD_C("Google.da-DK-Standard-C"), GOOGLE_DA_DK_STANDARD_D("Google.da-DK-Standard-D"), GOOGLE_DA_DK_STANDARD_E("Google.da-DK-Standard-E"), + GOOGLE_DA_DK_STANDARD_F("Google.da-DK-Standard-F"), + GOOGLE_DA_DK_STANDARD_G("Google.da-DK-Standard-G"), GOOGLE_DA_DK_WAVENET_A("Google.da-DK-Wavenet-A"), GOOGLE_DA_DK_WAVENET_C("Google.da-DK-Wavenet-C"), GOOGLE_DA_DK_WAVENET_D("Google.da-DK-Wavenet-D"), GOOGLE_DA_DK_WAVENET_E("Google.da-DK-Wavenet-E"), + GOOGLE_DA_DK_WAVENET_F("Google.da-DK-Wavenet-F"), + GOOGLE_DA_DK_WAVENET_G("Google.da-DK-Wavenet-G"), + GOOGLE_DE_DE_CHIRP3_HD_AOEDE("Google.de-DE-Chirp3-HD-Aoede"), + GOOGLE_DE_DE_CHIRP3_HD_CHARON("Google.de-DE-Chirp3-HD-Charon"), + GOOGLE_DE_DE_CHIRP3_HD_FENRIR("Google.de-DE-Chirp3-HD-Fenrir"), + GOOGLE_DE_DE_CHIRP3_HD_KORE("Google.de-DE-Chirp3-HD-Kore"), + GOOGLE_DE_DE_CHIRP3_HD_LEDA("Google.de-DE-Chirp3-HD-Leda"), + GOOGLE_DE_DE_CHIRP3_HD_ORUS("Google.de-DE-Chirp3-HD-Orus"), + GOOGLE_DE_DE_CHIRP3_HD_PUCK("Google.de-DE-Chirp3-HD-Puck"), + GOOGLE_DE_DE_CHIRP3_HD_ZEPHYR("Google.de-DE-Chirp3-HD-Zephyr"), GOOGLE_DE_DE_NEURAL2_A("Google.de-DE-Neural2-A"), GOOGLE_DE_DE_NEURAL2_B("Google.de-DE-Neural2-B"), GOOGLE_DE_DE_NEURAL2_C("Google.de-DE-Neural2-C"), GOOGLE_DE_DE_NEURAL2_D("Google.de-DE-Neural2-D"), GOOGLE_DE_DE_NEURAL2_F("Google.de-DE-Neural2-F"), + GOOGLE_DE_DE_NEURAL2_G("Google.de-DE-Neural2-G"), + GOOGLE_DE_DE_NEURAL2_H("Google.de-DE-Neural2-H"), GOOGLE_DE_DE_STANDARD_A("Google.de-DE-Standard-A"), GOOGLE_DE_DE_STANDARD_B("Google.de-DE-Standard-B"), GOOGLE_DE_DE_STANDARD_C("Google.de-DE-Standard-C"), GOOGLE_DE_DE_STANDARD_D("Google.de-DE-Standard-D"), GOOGLE_DE_DE_STANDARD_E("Google.de-DE-Standard-E"), GOOGLE_DE_DE_STANDARD_F("Google.de-DE-Standard-F"), + GOOGLE_DE_DE_STANDARD_G("Google.de-DE-Standard-G"), + GOOGLE_DE_DE_STANDARD_H("Google.de-DE-Standard-H"), GOOGLE_DE_DE_WAVENET_A("Google.de-DE-Wavenet-A"), GOOGLE_DE_DE_WAVENET_B("Google.de-DE-Wavenet-B"), GOOGLE_DE_DE_WAVENET_C("Google.de-DE-Wavenet-C"), GOOGLE_DE_DE_WAVENET_D("Google.de-DE-Wavenet-D"), GOOGLE_DE_DE_WAVENET_E("Google.de-DE-Wavenet-E"), GOOGLE_DE_DE_WAVENET_F("Google.de-DE-Wavenet-F"), + GOOGLE_DE_DE_WAVENET_G("Google.de-DE-Wavenet-G"), + GOOGLE_DE_DE_WAVENET_H("Google.de-DE-Wavenet-H"), GOOGLE_EL_GR_STANDARD_A("Google.el-GR-Standard-A"), + GOOGLE_EL_GR_STANDARD_B("Google.el-GR-Standard-B"), GOOGLE_EL_GR_WAVENET_A("Google.el-GR-Wavenet-A"), + GOOGLE_EL_GR_WAVENET_B("Google.el-GR-Wavenet-B"), + GOOGLE_EN_AU_CHIRP3_HD_AOEDE("Google.en-AU-Chirp3-HD-Aoede"), + GOOGLE_EN_AU_CHIRP3_HD_CHARON("Google.en-AU-Chirp3-HD-Charon"), + GOOGLE_EN_AU_CHIRP3_HD_FENRIR("Google.en-AU-Chirp3-HD-Fenrir"), + GOOGLE_EN_AU_CHIRP3_HD_KORE("Google.en-AU-Chirp3-HD-Kore"), + GOOGLE_EN_AU_CHIRP3_HD_LEDA("Google.en-AU-Chirp3-HD-Leda"), + GOOGLE_EN_AU_CHIRP3_HD_ORUS("Google.en-AU-Chirp3-HD-Orus"), + GOOGLE_EN_AU_CHIRP3_HD_PUCK("Google.en-AU-Chirp3-HD-Puck"), + GOOGLE_EN_AU_CHIRP3_HD_ZEPHYR("Google.en-AU-Chirp3-HD-Zephyr"), GOOGLE_EN_AU_NEURAL2_A("Google.en-AU-Neural2-A"), GOOGLE_EN_AU_NEURAL2_B("Google.en-AU-Neural2-B"), GOOGLE_EN_AU_NEURAL2_C("Google.en-AU-Neural2-C"), @@ -102,21 +162,43 @@ public enum Voice { GOOGLE_EN_AU_WAVENET_B("Google.en-AU-Wavenet-B"), GOOGLE_EN_AU_WAVENET_C("Google.en-AU-Wavenet-C"), GOOGLE_EN_AU_WAVENET_D("Google.en-AU-Wavenet-D"), + GOOGLE_EN_GB_CHIRP3_HD_AOEDE("Google.en-GB-Chirp3-HD-Aoede"), + GOOGLE_EN_GB_CHIRP3_HD_CHARON("Google.en-GB-Chirp3-HD-Charon"), + GOOGLE_EN_GB_CHIRP3_HD_FENRIR("Google.en-GB-Chirp3-HD-Fenrir"), + GOOGLE_EN_GB_CHIRP3_HD_KORE("Google.en-GB-Chirp3-HD-Kore"), + GOOGLE_EN_GB_CHIRP3_HD_LEDA("Google.en-GB-Chirp3-HD-Leda"), + GOOGLE_EN_GB_CHIRP3_HD_ORUS("Google.en-GB-Chirp3-HD-Orus"), + GOOGLE_EN_GB_CHIRP3_HD_PUCK("Google.en-GB-Chirp3-HD-Puck"), + GOOGLE_EN_GB_CHIRP3_HD_ZEPHYR("Google.en-GB-Chirp3-HD-Zephyr"), GOOGLE_EN_GB_NEURAL2_A("Google.en-GB-Neural2-A"), GOOGLE_EN_GB_NEURAL2_B("Google.en-GB-Neural2-B"), GOOGLE_EN_GB_NEURAL2_C("Google.en-GB-Neural2-C"), GOOGLE_EN_GB_NEURAL2_D("Google.en-GB-Neural2-D"), GOOGLE_EN_GB_NEURAL2_F("Google.en-GB-Neural2-F"), + GOOGLE_EN_GB_NEURAL2_N("Google.en-GB-Neural2-N"), + GOOGLE_EN_GB_NEURAL2_O("Google.en-GB-Neural2-O"), GOOGLE_EN_GB_STANDARD_A("Google.en-GB-Standard-A"), GOOGLE_EN_GB_STANDARD_B("Google.en-GB-Standard-B"), GOOGLE_EN_GB_STANDARD_C("Google.en-GB-Standard-C"), GOOGLE_EN_GB_STANDARD_D("Google.en-GB-Standard-D"), GOOGLE_EN_GB_STANDARD_F("Google.en-GB-Standard-F"), + GOOGLE_EN_GB_STANDARD_N("Google.en-GB-Standard-N"), + GOOGLE_EN_GB_STANDARD_O("Google.en-GB-Standard-O"), GOOGLE_EN_GB_WAVENET_A("Google.en-GB-Wavenet-A"), GOOGLE_EN_GB_WAVENET_B("Google.en-GB-Wavenet-B"), GOOGLE_EN_GB_WAVENET_C("Google.en-GB-Wavenet-C"), GOOGLE_EN_GB_WAVENET_D("Google.en-GB-Wavenet-D"), GOOGLE_EN_GB_WAVENET_F("Google.en-GB-Wavenet-F"), + GOOGLE_EN_GB_WAVENET_N("Google.en-GB-Wavenet-N"), + GOOGLE_EN_GB_WAVENET_O("Google.en-GB-Wavenet-O"), + GOOGLE_EN_IN_CHIRP3_HD_AOEDE("Google.en-IN-Chirp3-HD-Aoede"), + GOOGLE_EN_IN_CHIRP3_HD_CHARON("Google.en-IN-Chirp3-HD-Charon"), + GOOGLE_EN_IN_CHIRP3_HD_FENRIR("Google.en-IN-Chirp3-HD-Fenrir"), + GOOGLE_EN_IN_CHIRP3_HD_KORE("Google.en-IN-Chirp3-HD-Kore"), + GOOGLE_EN_IN_CHIRP3_HD_LEDA("Google.en-IN-Chirp3-HD-Leda"), + GOOGLE_EN_IN_CHIRP3_HD_ORUS("Google.en-IN-Chirp3-HD-Orus"), + GOOGLE_EN_IN_CHIRP3_HD_PUCK("Google.en-IN-Chirp3-HD-Puck"), + GOOGLE_EN_IN_CHIRP3_HD_ZEPHYR("Google.en-IN-Chirp3-HD-Zephyr"), GOOGLE_EN_IN_NEURAL2_A("Google.en-IN-Neural2-A"), GOOGLE_EN_IN_NEURAL2_B("Google.en-IN-Neural2-B"), GOOGLE_EN_IN_NEURAL2_C("Google.en-IN-Neural2-C"), @@ -125,10 +207,22 @@ public enum Voice { GOOGLE_EN_IN_STANDARD_B("Google.en-IN-Standard-B"), GOOGLE_EN_IN_STANDARD_C("Google.en-IN-Standard-C"), GOOGLE_EN_IN_STANDARD_D("Google.en-IN-Standard-D"), + GOOGLE_EN_IN_STANDARD_E("Google.en-IN-Standard-E"), + GOOGLE_EN_IN_STANDARD_F("Google.en-IN-Standard-F"), GOOGLE_EN_IN_WAVENET_A("Google.en-IN-Wavenet-A"), GOOGLE_EN_IN_WAVENET_B("Google.en-IN-Wavenet-B"), GOOGLE_EN_IN_WAVENET_C("Google.en-IN-Wavenet-C"), GOOGLE_EN_IN_WAVENET_D("Google.en-IN-Wavenet-D"), + GOOGLE_EN_IN_WAVENET_E("Google.en-IN-Wavenet-E"), + GOOGLE_EN_IN_WAVENET_F("Google.en-IN-Wavenet-F"), + GOOGLE_EN_US_CHIRP3_HD_AOEDE("Google.en-US-Chirp3-HD-Aoede"), + GOOGLE_EN_US_CHIRP3_HD_CHARON("Google.en-US-Chirp3-HD-Charon"), + GOOGLE_EN_US_CHIRP3_HD_FENRIR("Google.en-US-Chirp3-HD-Fenrir"), + GOOGLE_EN_US_CHIRP3_HD_KORE("Google.en-US-Chirp3-HD-Kore"), + GOOGLE_EN_US_CHIRP3_HD_LEDA("Google.en-US-Chirp3-HD-Leda"), + GOOGLE_EN_US_CHIRP3_HD_ORUS("Google.en-US-Chirp3-HD-Orus"), + GOOGLE_EN_US_CHIRP3_HD_PUCK("Google.en-US-Chirp3-HD-Puck"), + GOOGLE_EN_US_CHIRP3_HD_ZEPHYR("Google.en-US-Chirp3-HD-Zephyr"), GOOGLE_EN_US_NEURAL2_A("Google.en-US-Neural2-A"), GOOGLE_EN_US_NEURAL2_C("Google.en-US-Neural2-C"), GOOGLE_EN_US_NEURAL2_D("Google.en-US-Neural2-D"), @@ -158,18 +252,45 @@ public enum Voice { GOOGLE_EN_US_WAVENET_H("Google.en-US-Wavenet-H"), GOOGLE_EN_US_WAVENET_I("Google.en-US-Wavenet-I"), GOOGLE_EN_US_WAVENET_J("Google.en-US-Wavenet-J"), + GOOGLE_ES_ES_CHIRP3_HD_AOEDE("Google.es-ES-Chirp3-HD-Aoede"), + GOOGLE_ES_ES_CHIRP3_HD_CHARON("Google.es-ES-Chirp3-HD-Charon"), + GOOGLE_ES_ES_CHIRP3_HD_FENRIR("Google.es-ES-Chirp3-HD-Fenrir"), + GOOGLE_ES_ES_CHIRP3_HD_KORE("Google.es-ES-Chirp3-HD-Kore"), + GOOGLE_ES_ES_CHIRP3_HD_LEDA("Google.es-ES-Chirp3-HD-Leda"), + GOOGLE_ES_ES_CHIRP3_HD_ORUS("Google.es-ES-Chirp3-HD-Orus"), + GOOGLE_ES_ES_CHIRP3_HD_PUCK("Google.es-ES-Chirp3-HD-Puck"), + GOOGLE_ES_ES_CHIRP3_HD_ZEPHYR("Google.es-ES-Chirp3-HD-Zephyr"), GOOGLE_ES_ES_NEURAL2_A("Google.es-ES-Neural2-A"), GOOGLE_ES_ES_NEURAL2_B("Google.es-ES-Neural2-B"), GOOGLE_ES_ES_NEURAL2_C("Google.es-ES-Neural2-C"), GOOGLE_ES_ES_NEURAL2_D("Google.es-ES-Neural2-D"), GOOGLE_ES_ES_NEURAL2_E("Google.es-ES-Neural2-E"), GOOGLE_ES_ES_NEURAL2_F("Google.es-ES-Neural2-F"), + GOOGLE_ES_ES_NEURAL2_G("Google.es-ES-Neural2-G"), + GOOGLE_ES_ES_NEURAL2_H("Google.es-ES-Neural2-H"), + GOOGLE_ES_ES_STANDARD_A("Google.es-ES-Standard-A"), GOOGLE_ES_ES_STANDARD_B("Google.es-ES-Standard-B"), GOOGLE_ES_ES_STANDARD_C("Google.es-ES-Standard-C"), GOOGLE_ES_ES_STANDARD_D("Google.es-ES-Standard-D"), + GOOGLE_ES_ES_STANDARD_E("Google.es-ES-Standard-E"), + GOOGLE_ES_ES_STANDARD_F("Google.es-ES-Standard-F"), + GOOGLE_ES_ES_STANDARD_G("Google.es-ES-Standard-G"), + GOOGLE_ES_ES_STANDARD_H("Google.es-ES-Standard-H"), GOOGLE_ES_ES_WAVENET_B("Google.es-ES-Wavenet-B"), GOOGLE_ES_ES_WAVENET_C("Google.es-ES-Wavenet-C"), GOOGLE_ES_ES_WAVENET_D("Google.es-ES-Wavenet-D"), + GOOGLE_ES_ES_WAVENET_E("Google.es-ES-Wavenet-E"), + GOOGLE_ES_ES_WAVENET_F("Google.es-ES-Wavenet-F"), + GOOGLE_ES_ES_WAVENET_G("Google.es-ES-Wavenet-G"), + GOOGLE_ES_ES_WAVENET_H("Google.es-ES-Wavenet-H"), + GOOGLE_ES_US_CHIRP3_HD_AOEDE("Google.es-US-Chirp3-HD-Aoede"), + GOOGLE_ES_US_CHIRP3_HD_CHARON("Google.es-US-Chirp3-HD-Charon"), + GOOGLE_ES_US_CHIRP3_HD_FENRIR("Google.es-US-Chirp3-HD-Fenrir"), + GOOGLE_ES_US_CHIRP3_HD_KORE("Google.es-US-Chirp3-HD-Kore"), + GOOGLE_ES_US_CHIRP3_HD_LEDA("Google.es-US-Chirp3-HD-Leda"), + GOOGLE_ES_US_CHIRP3_HD_ORUS("Google.es-US-Chirp3-HD-Orus"), + GOOGLE_ES_US_CHIRP3_HD_PUCK("Google.es-US-Chirp3-HD-Puck"), + GOOGLE_ES_US_CHIRP3_HD_ZEPHYR("Google.es-US-Chirp3-HD-Zephyr"), GOOGLE_ES_US_NEURAL2_A("Google.es-US-Neural2-A"), GOOGLE_ES_US_NEURAL2_B("Google.es-US-Neural2-B"), GOOGLE_ES_US_NEURAL2_C("Google.es-US-Neural2-C"), @@ -180,8 +301,13 @@ public enum Voice { GOOGLE_ES_US_WAVENET_B("Google.es-US-Wavenet-B"), GOOGLE_ES_US_WAVENET_C("Google.es-US-Wavenet-C"), GOOGLE_EU_ES_STANDARD_A("Google.eu-ES-Standard-A"), + GOOGLE_EU_ES_STANDARD_B("Google.eu-ES-Standard-B"), GOOGLE_FI_FI_STANDARD_A("Google.fi-FI-Standard-A"), + GOOGLE_FI_FI_STANDARD_B("Google.fi-FI-Standard-B"), GOOGLE_FI_FI_WAVENET_A("Google.fi-FI-Wavenet-A"), + GOOGLE_FI_FI_WAVENET_B("Google.fi-FI-Wavenet-B"), + GOOGLE_FIL_PH_NEURAL2_A("Google.fil-ph-Neural2-A"), + GOOGLE_FIL_PH_NEURAL2_D("Google.fil-ph-Neural2-D"), GOOGLE_FIL_PH_STANDARD_A("Google.fil-PH-Standard-A"), GOOGLE_FIL_PH_STANDARD_B("Google.fil-PH-Standard-B"), GOOGLE_FIL_PH_STANDARD_C("Google.fil-PH-Standard-C"), @@ -190,8 +316,14 @@ public enum Voice { GOOGLE_FIL_PH_WAVENET_B("Google.fil-PH-Wavenet-B"), GOOGLE_FIL_PH_WAVENET_C("Google.fil-PH-Wavenet-C"), GOOGLE_FIL_PH_WAVENET_D("Google.fil-PH-Wavenet-D"), - GOOGLE_FIL_PH_NEURAL2_A("Google.fil-ph-Neural2-A"), - GOOGLE_FIL_PH_NEURAL2_D("Google.fil-ph-Neural2-D"), + GOOGLE_FR_CA_CHIRP3_HD_AOEDE("Google.fr-CA-Chirp3-HD-Aoede"), + GOOGLE_FR_CA_CHIRP3_HD_CHARON("Google.fr-CA-Chirp3-HD-Charon"), + GOOGLE_FR_CA_CHIRP3_HD_FENRIR("Google.fr-CA-Chirp3-HD-Fenrir"), + GOOGLE_FR_CA_CHIRP3_HD_KORE("Google.fr-CA-Chirp3-HD-Kore"), + GOOGLE_FR_CA_CHIRP3_HD_LEDA("Google.fr-CA-Chirp3-HD-Leda"), + GOOGLE_FR_CA_CHIRP3_HD_ORUS("Google.fr-CA-Chirp3-HD-Orus"), + GOOGLE_FR_CA_CHIRP3_HD_PUCK("Google.fr-CA-Chirp3-HD-Puck"), + GOOGLE_FR_CA_CHIRP3_HD_ZEPHYR("Google.fr-CA-Chirp3-HD-Zephyr"), GOOGLE_FR_CA_NEURAL2_A("Google.fr-CA-Neural2-A"), GOOGLE_FR_CA_NEURAL2_B("Google.fr-CA-Neural2-B"), GOOGLE_FR_CA_NEURAL2_C("Google.fr-CA-Neural2-C"), @@ -204,24 +336,51 @@ public enum Voice { GOOGLE_FR_CA_WAVENET_B("Google.fr-CA-Wavenet-B"), GOOGLE_FR_CA_WAVENET_C("Google.fr-CA-Wavenet-C"), GOOGLE_FR_CA_WAVENET_D("Google.fr-CA-Wavenet-D"), + GOOGLE_FR_FR_CHIRP3_HD_AOEDE("Google.fr-FR-Chirp3-HD-Aoede"), + GOOGLE_FR_FR_CHIRP3_HD_CHARON("Google.fr-FR-Chirp3-HD-Charon"), + GOOGLE_FR_FR_CHIRP3_HD_FENRIR("Google.fr-FR-Chirp3-HD-Fenrir"), + GOOGLE_FR_FR_CHIRP3_HD_KORE("Google.fr-FR-Chirp3-HD-Kore"), + GOOGLE_FR_FR_CHIRP3_HD_LEDA("Google.fr-FR-Chirp3-HD-Leda"), + GOOGLE_FR_FR_CHIRP3_HD_ORUS("Google.fr-FR-Chirp3-HD-Orus"), + GOOGLE_FR_FR_CHIRP3_HD_PUCK("Google.fr-FR-Chirp3-HD-Puck"), + GOOGLE_FR_FR_CHIRP3_HD_ZEPHYR("Google.fr-FR-Chirp3-HD-Zephyr"), GOOGLE_FR_FR_NEURAL2_A("Google.fr-FR-Neural2-A"), GOOGLE_FR_FR_NEURAL2_B("Google.fr-FR-Neural2-B"), GOOGLE_FR_FR_NEURAL2_C("Google.fr-FR-Neural2-C"), GOOGLE_FR_FR_NEURAL2_D("Google.fr-FR-Neural2-D"), GOOGLE_FR_FR_NEURAL2_E("Google.fr-FR-Neural2-E"), + GOOGLE_FR_FR_NEURAL2_F("Google.fr-FR-Neural2-F"), + GOOGLE_FR_FR_NEURAL2_G("Google.fr-FR-Neural2-G"), GOOGLE_FR_FR_STANDARD_A("Google.fr-FR-Standard-A"), GOOGLE_FR_FR_STANDARD_B("Google.fr-FR-Standard-B"), GOOGLE_FR_FR_STANDARD_C("Google.fr-FR-Standard-C"), GOOGLE_FR_FR_STANDARD_D("Google.fr-FR-Standard-D"), GOOGLE_FR_FR_STANDARD_E("Google.fr-FR-Standard-E"), + GOOGLE_FR_FR_STANDARD_F("Google.fr-FR-Standard-F"), + GOOGLE_FR_FR_STANDARD_G("Google.fr-FR-Standard-G"), GOOGLE_FR_FR_WAVENET_A("Google.fr-FR-Wavenet-A"), GOOGLE_FR_FR_WAVENET_B("Google.fr-FR-Wavenet-B"), GOOGLE_FR_FR_WAVENET_C("Google.fr-FR-Wavenet-C"), GOOGLE_FR_FR_WAVENET_D("Google.fr-FR-Wavenet-D"), GOOGLE_FR_FR_WAVENET_E("Google.fr-FR-Wavenet-E"), + GOOGLE_FR_FR_WAVENET_F("Google.fr-FR-Wavenet-F"), + GOOGLE_FR_FR_WAVENET_G("Google.fr-FR-Wavenet-G"), GOOGLE_GL_ES_STANDARD_A("Google.gl-ES-Standard-A"), + GOOGLE_GL_ES_STANDARD_B("Google.gl-ES-Standard-B"), + GOOGLE_GU_IN_CHIRP3_HD_AOEDE("Google.gu-IN-Chirp3-HD-Aoede"), + GOOGLE_GU_IN_CHIRP3_HD_CHARON("Google.gu-IN-Chirp3-HD-Charon"), + GOOGLE_GU_IN_CHIRP3_HD_FENRIR("Google.gu-IN-Chirp3-HD-Fenrir"), + GOOGLE_GU_IN_CHIRP3_HD_KORE("Google.gu-IN-Chirp3-HD-Kore"), + GOOGLE_GU_IN_CHIRP3_HD_LEDA("Google.gu-IN-Chirp3-HD-Leda"), + GOOGLE_GU_IN_CHIRP3_HD_ORUS("Google.gu-IN-Chirp3-HD-Orus"), + GOOGLE_GU_IN_CHIRP3_HD_PUCK("Google.gu-IN-Chirp3-HD-Puck"), + GOOGLE_GU_IN_CHIRP3_HD_ZEPHYR("Google.gu-IN-Chirp3-HD-Zephyr"), + GOOGLE_GU_IN_STANDARD_A("Google.gu-IN-Standard-A"), + GOOGLE_GU_IN_STANDARD_B("Google.gu-IN-Standard-B"), GOOGLE_GU_IN_STANDARD_C("Google.gu-IN-Standard-C"), GOOGLE_GU_IN_STANDARD_D("Google.gu-IN-Standard-D"), + GOOGLE_GU_IN_WAVENET_A("Google.gu-IN-Wavenet-A"), + GOOGLE_GU_IN_WAVENET_B("Google.gu-IN-Wavenet-B"), GOOGLE_GU_IN_WAVENET_C("Google.gu-IN-Wavenet-C"), GOOGLE_GU_IN_WAVENET_D("Google.gu-IN-Wavenet-D"), GOOGLE_HE_IL_STANDARD_A("Google.he-IL-Standard-A"), @@ -232,6 +391,14 @@ public enum Voice { GOOGLE_HE_IL_WAVENET_B("Google.he-IL-Wavenet-B"), GOOGLE_HE_IL_WAVENET_C("Google.he-IL-Wavenet-C"), GOOGLE_HE_IL_WAVENET_D("Google.he-IL-Wavenet-D"), + GOOGLE_HI_IN_CHIRP3_HD_AOEDE("Google.hi-IN-Chirp3-HD-Aoede"), + GOOGLE_HI_IN_CHIRP3_HD_CHARON("Google.hi-IN-Chirp3-HD-Charon"), + GOOGLE_HI_IN_CHIRP3_HD_FENRIR("Google.hi-IN-Chirp3-HD-Fenrir"), + GOOGLE_HI_IN_CHIRP3_HD_KORE("Google.hi-IN-Chirp3-HD-Kore"), + GOOGLE_HI_IN_CHIRP3_HD_LEDA("Google.hi-IN-Chirp3-HD-Leda"), + GOOGLE_HI_IN_CHIRP3_HD_ORUS("Google.hi-IN-Chirp3-HD-Orus"), + GOOGLE_HI_IN_CHIRP3_HD_PUCK("Google.hi-IN-Chirp3-HD-Puck"), + GOOGLE_HI_IN_CHIRP3_HD_ZEPHYR("Google.hi-IN-Chirp3-HD-Zephyr"), GOOGLE_HI_IN_NEURAL2_A("Google.hi-IN-Neural2-A"), GOOGLE_HI_IN_NEURAL2_B("Google.hi-IN-Neural2-B"), GOOGLE_HI_IN_NEURAL2_C("Google.hi-IN-Neural2-C"), @@ -240,12 +407,25 @@ public enum Voice { GOOGLE_HI_IN_STANDARD_B("Google.hi-IN-Standard-B"), GOOGLE_HI_IN_STANDARD_C("Google.hi-IN-Standard-C"), GOOGLE_HI_IN_STANDARD_D("Google.hi-IN-Standard-D"), + GOOGLE_HI_IN_STANDARD_E("Google.hi-IN-Standard-E"), + GOOGLE_HI_IN_STANDARD_F("Google.hi-IN-Standard-F"), GOOGLE_HI_IN_WAVENET_A("Google.hi-IN-Wavenet-A"), GOOGLE_HI_IN_WAVENET_B("Google.hi-IN-Wavenet-B"), GOOGLE_HI_IN_WAVENET_C("Google.hi-IN-Wavenet-C"), GOOGLE_HI_IN_WAVENET_D("Google.hi-IN-Wavenet-D"), + GOOGLE_HI_IN_WAVENET_E("Google.hi-IN-Wavenet-E"), + GOOGLE_HI_IN_WAVENET_F("Google.hi-IN-Wavenet-F"), GOOGLE_HU_HU_STANDARD_A("Google.hu-HU-Standard-A"), + GOOGLE_HU_HU_STANDARD_B("Google.hu-HU-Standard-B"), GOOGLE_HU_HU_WAVENET_A("Google.hu-HU-Wavenet-A"), + GOOGLE_ID_ID_CHIRP3_HD_AOEDE("Google.id-ID-Chirp3-HD-Aoede"), + GOOGLE_ID_ID_CHIRP3_HD_CHARON("Google.id-ID-Chirp3-HD-Charon"), + GOOGLE_ID_ID_CHIRP3_HD_FENRIR("Google.id-ID-Chirp3-HD-Fenrir"), + GOOGLE_ID_ID_CHIRP3_HD_KORE("Google.id-ID-Chirp3-HD-Kore"), + GOOGLE_ID_ID_CHIRP3_HD_LEDA("Google.id-ID-Chirp3-HD-Leda"), + GOOGLE_ID_ID_CHIRP3_HD_ORUS("Google.id-ID-Chirp3-HD-Orus"), + GOOGLE_ID_ID_CHIRP3_HD_PUCK("Google.id-ID-Chirp3-HD-Puck"), + GOOGLE_ID_ID_CHIRP3_HD_ZEPHYR("Google.id-ID-Chirp3-HD-Zephyr"), GOOGLE_ID_ID_STANDARD_A("Google.id-ID-Standard-A"), GOOGLE_ID_ID_STANDARD_B("Google.id-ID-Standard-B"), GOOGLE_ID_ID_STANDARD_C("Google.id-ID-Standard-C"), @@ -255,14 +435,38 @@ public enum Voice { GOOGLE_ID_ID_WAVENET_C("Google.id-ID-Wavenet-C"), GOOGLE_ID_ID_WAVENET_D("Google.id-ID-Wavenet-D"), GOOGLE_IS_IS_STANDARD_A("Google.is-IS-Standard-A"), + GOOGLE_IS_IS_STANDARD_B("Google.is-IS-Standard-B"), + GOOGLE_IT_IT_CHIRP3_HD_AOEDE("Google.it-IT-Chirp3-HD-Aoede"), + GOOGLE_IT_IT_CHIRP3_HD_CHARON("Google.it-IT-Chirp3-HD-Charon"), + GOOGLE_IT_IT_CHIRP3_HD_FENRIR("Google.it-IT-Chirp3-HD-Fenrir"), + GOOGLE_IT_IT_CHIRP3_HD_KORE("Google.it-IT-Chirp3-HD-Kore"), + GOOGLE_IT_IT_CHIRP3_HD_LEDA("Google.it-IT-Chirp3-HD-Leda"), + GOOGLE_IT_IT_CHIRP3_HD_ORUS("Google.it-IT-Chirp3-HD-Orus"), + GOOGLE_IT_IT_CHIRP3_HD_PUCK("Google.it-IT-Chirp3-HD-Puck"), + GOOGLE_IT_IT_CHIRP3_HD_ZEPHYR("Google.it-IT-Chirp3-HD-Zephyr"), GOOGLE_IT_IT_NEURAL2_A("Google.it-IT-Neural2-A"), GOOGLE_IT_IT_NEURAL2_C("Google.it-IT-Neural2-C"), + GOOGLE_IT_IT_NEURAL2_F("Google.it-IT-Neural2-F"), + GOOGLE_IT_IT_STANDARD_A("Google.it-IT-Standard-A"), GOOGLE_IT_IT_STANDARD_B("Google.it-IT-Standard-B"), GOOGLE_IT_IT_STANDARD_C("Google.it-IT-Standard-C"), GOOGLE_IT_IT_STANDARD_D("Google.it-IT-Standard-D"), + GOOGLE_IT_IT_STANDARD_E("Google.it-IT-Standard-E"), + GOOGLE_IT_IT_STANDARD_F("Google.it-IT-Standard-F"), + GOOGLE_IT_IT_WAVENET_A("Google.it-IT-Wavenet-A"), GOOGLE_IT_IT_WAVENET_B("Google.it-IT-Wavenet-B"), GOOGLE_IT_IT_WAVENET_C("Google.it-IT-Wavenet-C"), GOOGLE_IT_IT_WAVENET_D("Google.it-IT-Wavenet-D"), + GOOGLE_IT_IT_WAVENET_E("Google.it-IT-Wavenet-E"), + GOOGLE_IT_IT_WAVENET_F("Google.it-IT-Wavenet-F"), + GOOGLE_JA_JP_CHIRP3_HD_AOEDE("Google.ja-JP-Chirp3-HD-Aoede"), + GOOGLE_JA_JP_CHIRP3_HD_CHARON("Google.ja-JP-Chirp3-HD-Charon"), + GOOGLE_JA_JP_CHIRP3_HD_FENRIR("Google.ja-JP-Chirp3-HD-Fenrir"), + GOOGLE_JA_JP_CHIRP3_HD_KORE("Google.ja-JP-Chirp3-HD-Kore"), + GOOGLE_JA_JP_CHIRP3_HD_LEDA("Google.ja-JP-Chirp3-HD-Leda"), + GOOGLE_JA_JP_CHIRP3_HD_ORUS("Google.ja-JP-Chirp3-HD-Orus"), + GOOGLE_JA_JP_CHIRP3_HD_PUCK("Google.ja-JP-Chirp3-HD-Puck"), + GOOGLE_JA_JP_CHIRP3_HD_ZEPHYR("Google.ja-JP-Chirp3-HD-Zephyr"), GOOGLE_JA_JP_NEURAL2_B("Google.ja-JP-Neural2-B"), GOOGLE_JA_JP_NEURAL2_C("Google.ja-JP-Neural2-C"), GOOGLE_JA_JP_NEURAL2_D("Google.ja-JP-Neural2-D"), @@ -274,10 +478,30 @@ public enum Voice { GOOGLE_JA_JP_WAVENET_B("Google.ja-JP-Wavenet-B"), GOOGLE_JA_JP_WAVENET_C("Google.ja-JP-Wavenet-C"), GOOGLE_JA_JP_WAVENET_D("Google.ja-JP-Wavenet-D"), + GOOGLE_KN_IN_CHIRP3_HD_AOEDE("Google.kn-IN-Chirp3-HD-Aoede"), + GOOGLE_KN_IN_CHIRP3_HD_CHARON("Google.kn-IN-Chirp3-HD-Charon"), + GOOGLE_KN_IN_CHIRP3_HD_FENRIR("Google.kn-IN-Chirp3-HD-Fenrir"), + GOOGLE_KN_IN_CHIRP3_HD_KORE("Google.kn-IN-Chirp3-HD-Kore"), + GOOGLE_KN_IN_CHIRP3_HD_LEDA("Google.kn-IN-Chirp3-HD-Leda"), + GOOGLE_KN_IN_CHIRP3_HD_ORUS("Google.kn-IN-Chirp3-HD-Orus"), + GOOGLE_KN_IN_CHIRP3_HD_PUCK("Google.kn-IN-Chirp3-HD-Puck"), + GOOGLE_KN_IN_CHIRP3_HD_ZEPHYR("Google.kn-IN-Chirp3-HD-Zephyr"), + GOOGLE_KN_IN_STANDARD_A("Google.kn-IN-Standard-A"), + GOOGLE_KN_IN_STANDARD_B("Google.kn-IN-Standard-B"), GOOGLE_KN_IN_STANDARD_C("Google.kn-IN-Standard-C"), GOOGLE_KN_IN_STANDARD_D("Google.kn-IN-Standard-D"), + GOOGLE_KN_IN_WAVENET_A("Google.kn-IN-Wavenet-A"), + GOOGLE_KN_IN_WAVENET_B("Google.kn-IN-Wavenet-B"), GOOGLE_KN_IN_WAVENET_C("Google.kn-IN-Wavenet-C"), GOOGLE_KN_IN_WAVENET_D("Google.kn-IN-Wavenet-D"), + GOOGLE_KO_KR_CHIRP3_HD_AOEDE("Google.ko-KR-Chirp3-HD-Aoede"), + GOOGLE_KO_KR_CHIRP3_HD_CHARON("Google.ko-KR-Chirp3-HD-Charon"), + GOOGLE_KO_KR_CHIRP3_HD_FENRIR("Google.ko-KR-Chirp3-HD-Fenrir"), + GOOGLE_KO_KR_CHIRP3_HD_KORE("Google.ko-KR-Chirp3-HD-Kore"), + GOOGLE_KO_KR_CHIRP3_HD_LEDA("Google.ko-KR-Chirp3-HD-Leda"), + GOOGLE_KO_KR_CHIRP3_HD_ORUS("Google.ko-KR-Chirp3-HD-Orus"), + GOOGLE_KO_KR_CHIRP3_HD_PUCK("Google.ko-KR-Chirp3-HD-Puck"), + GOOGLE_KO_KR_CHIRP3_HD_ZEPHYR("Google.ko-KR-Chirp3-HD-Zephyr"), GOOGLE_KO_KR_NEURAL2_A("Google.ko-KR-Neural2-A"), GOOGLE_KO_KR_NEURAL2_B("Google.ko-KR-Neural2-B"), GOOGLE_KO_KR_NEURAL2_C("Google.ko-KR-Neural2-C"), @@ -290,9 +514,33 @@ public enum Voice { GOOGLE_KO_KR_WAVENET_C("Google.ko-KR-Wavenet-C"), GOOGLE_KO_KR_WAVENET_D("Google.ko-KR-Wavenet-D"), GOOGLE_LT_LT_STANDARD_A("Google.lt-LT-Standard-A"), + GOOGLE_LT_LT_STANDARD_B("Google.lt-LT-Standard-B"), GOOGLE_LV_LV_STANDARD_A("Google.lv-LV-Standard-A"), + GOOGLE_LV_LV_STANDARD_B("Google.lv-LV-Standard-B"), + GOOGLE_ML_IN_CHIRP3_HD_AOEDE("Google.ml-IN-Chirp3-HD-Aoede"), + GOOGLE_ML_IN_CHIRP3_HD_CHARON("Google.ml-IN-Chirp3-HD-Charon"), + GOOGLE_ML_IN_CHIRP3_HD_FENRIR("Google.ml-IN-Chirp3-HD-Fenrir"), + GOOGLE_ML_IN_CHIRP3_HD_KORE("Google.ml-IN-Chirp3-HD-Kore"), + GOOGLE_ML_IN_CHIRP3_HD_LEDA("Google.ml-IN-Chirp3-HD-Leda"), + GOOGLE_ML_IN_CHIRP3_HD_ORUS("Google.ml-IN-Chirp3-HD-Orus"), + GOOGLE_ML_IN_CHIRP3_HD_PUCK("Google.ml-IN-Chirp3-HD-Puck"), + GOOGLE_ML_IN_CHIRP3_HD_ZEPHYR("Google.ml-IN-Chirp3-HD-Zephyr"), + GOOGLE_ML_IN_STANDARD_A("Google.ml-IN-Standard-A"), + GOOGLE_ML_IN_STANDARD_B("Google.ml-IN-Standard-B"), + GOOGLE_ML_IN_STANDARD_C("Google.ml-IN-Standard-C"), + GOOGLE_ML_IN_STANDARD_D("Google.ml-IN-Standard-D"), + GOOGLE_ML_IN_WAVENET_A("Google.ml-IN-Wavenet-A"), + GOOGLE_ML_IN_WAVENET_B("Google.ml-IN-Wavenet-B"), GOOGLE_ML_IN_WAVENET_C("Google.ml-IN-Wavenet-C"), GOOGLE_ML_IN_WAVENET_D("Google.ml-IN-Wavenet-D"), + GOOGLE_MR_IN_CHIRP3_HD_AOEDE("Google.mr-IN-Chirp3-HD-Aoede"), + GOOGLE_MR_IN_CHIRP3_HD_CHARON("Google.mr-IN-Chirp3-HD-Charon"), + GOOGLE_MR_IN_CHIRP3_HD_FENRIR("Google.mr-IN-Chirp3-HD-Fenrir"), + GOOGLE_MR_IN_CHIRP3_HD_KORE("Google.mr-IN-Chirp3-HD-Kore"), + GOOGLE_MR_IN_CHIRP3_HD_LEDA("Google.mr-IN-Chirp3-HD-Leda"), + GOOGLE_MR_IN_CHIRP3_HD_ORUS("Google.mr-IN-Chirp3-HD-Orus"), + GOOGLE_MR_IN_CHIRP3_HD_PUCK("Google.mr-IN-Chirp3-HD-Puck"), + GOOGLE_MR_IN_CHIRP3_HD_ZEPHYR("Google.mr-IN-Chirp3-HD-Zephyr"), GOOGLE_MR_IN_STANDARD_A("Google.mr-IN-Standard-A"), GOOGLE_MR_IN_STANDARD_B("Google.mr-IN-Standard-B"), GOOGLE_MR_IN_STANDARD_C("Google.mr-IN-Standard-C"), @@ -312,25 +560,45 @@ public enum Voice { GOOGLE_NB_NO_STANDARD_C("Google.nb-NO-Standard-C"), GOOGLE_NB_NO_STANDARD_D("Google.nb-NO-Standard-D"), GOOGLE_NB_NO_STANDARD_E("Google.nb-NO-Standard-E"), + GOOGLE_NB_NO_STANDARD_F("Google.nb-NO-Standard-F"), + GOOGLE_NB_NO_STANDARD_G("Google.nb-NO-Standard-G"), GOOGLE_NB_NO_WAVENET_A("Google.nb-NO-Wavenet-A"), GOOGLE_NB_NO_WAVENET_B("Google.nb-NO-Wavenet-B"), GOOGLE_NB_NO_WAVENET_C("Google.nb-NO-Wavenet-C"), GOOGLE_NB_NO_WAVENET_D("Google.nb-NO-Wavenet-D"), GOOGLE_NB_NO_WAVENET_E("Google.nb-NO-Wavenet-E"), + GOOGLE_NB_NO_WAVENET_F("Google.nb-NO-Wavenet-F"), + GOOGLE_NB_NO_WAVENET_G("Google.nb-NO-Wavenet-G"), GOOGLE_NL_BE_STANDARD_A("Google.nl-BE-Standard-A"), GOOGLE_NL_BE_STANDARD_B("Google.nl-BE-Standard-B"), + GOOGLE_NL_BE_STANDARD_C("Google.nl-BE-Standard-C"), + GOOGLE_NL_BE_STANDARD_D("Google.nl-BE-Standard-D"), GOOGLE_NL_BE_WAVENET_A("Google.nl-BE-Wavenet-A"), GOOGLE_NL_BE_WAVENET_B("Google.nl-BE-Wavenet-B"), + GOOGLE_NL_BE_WAVENET_C("Google.nl-BE-Wavenet-C"), + GOOGLE_NL_BE_WAVENET_D("Google.nl-BE-Wavenet-D"), + GOOGLE_NL_NL_CHIRP3_HD_AOEDE("Google.nl-NL-Chirp3-HD-Aoede"), + GOOGLE_NL_NL_CHIRP3_HD_CHARON("Google.nl-NL-Chirp3-HD-Charon"), + GOOGLE_NL_NL_CHIRP3_HD_FENRIR("Google.nl-NL-Chirp3-HD-Fenrir"), + GOOGLE_NL_NL_CHIRP3_HD_KORE("Google.nl-NL-Chirp3-HD-Kore"), + GOOGLE_NL_NL_CHIRP3_HD_LEDA("Google.nl-NL-Chirp3-HD-Leda"), + GOOGLE_NL_NL_CHIRP3_HD_ORUS("Google.nl-NL-Chirp3-HD-Orus"), + GOOGLE_NL_NL_CHIRP3_HD_PUCK("Google.nl-NL-Chirp3-HD-Puck"), + GOOGLE_NL_NL_CHIRP3_HD_ZEPHYR("Google.nl-NL-Chirp3-HD-Zephyr"), GOOGLE_NL_NL_STANDARD_A("Google.nl-NL-Standard-A"), GOOGLE_NL_NL_STANDARD_B("Google.nl-NL-Standard-B"), GOOGLE_NL_NL_STANDARD_C("Google.nl-NL-Standard-C"), GOOGLE_NL_NL_STANDARD_D("Google.nl-NL-Standard-D"), GOOGLE_NL_NL_STANDARD_E("Google.nl-NL-Standard-E"), + GOOGLE_NL_NL_STANDARD_F("Google.nl-NL-Standard-F"), + GOOGLE_NL_NL_STANDARD_G("Google.nl-NL-Standard-G"), GOOGLE_NL_NL_WAVENET_A("Google.nl-NL-Wavenet-A"), GOOGLE_NL_NL_WAVENET_B("Google.nl-NL-Wavenet-B"), GOOGLE_NL_NL_WAVENET_C("Google.nl-NL-Wavenet-C"), GOOGLE_NL_NL_WAVENET_D("Google.nl-NL-Wavenet-D"), GOOGLE_NL_NL_WAVENET_E("Google.nl-NL-Wavenet-E"), + GOOGLE_NL_NL_WAVENET_F("Google.nl-NL-Wavenet-F"), + GOOGLE_NL_NL_WAVENET_G("Google.nl-NL-Wavenet-G"), GOOGLE_PA_IN_STANDARD_A("Google.pa-IN-Standard-A"), GOOGLE_PA_IN_STANDARD_B("Google.pa-IN-Standard-B"), GOOGLE_PA_IN_STANDARD_C("Google.pa-IN-Standard-C"), @@ -339,35 +607,73 @@ public enum Voice { GOOGLE_PA_IN_WAVENET_B("Google.pa-IN-Wavenet-B"), GOOGLE_PA_IN_WAVENET_C("Google.pa-IN-Wavenet-C"), GOOGLE_PA_IN_WAVENET_D("Google.pa-IN-Wavenet-D"), + GOOGLE_PL_PL_CHIRP3_HD_AOEDE("Google.pl-PL-Chirp3-HD-Aoede"), + GOOGLE_PL_PL_CHIRP3_HD_CHARON("Google.pl-PL-Chirp3-HD-Charon"), + GOOGLE_PL_PL_CHIRP3_HD_FENRIR("Google.pl-PL-Chirp3-HD-Fenrir"), + GOOGLE_PL_PL_CHIRP3_HD_KORE("Google.pl-PL-Chirp3-HD-Kore"), + GOOGLE_PL_PL_CHIRP3_HD_LEDA("Google.pl-PL-Chirp3-HD-Leda"), + GOOGLE_PL_PL_CHIRP3_HD_ORUS("Google.pl-PL-Chirp3-HD-Orus"), + GOOGLE_PL_PL_CHIRP3_HD_PUCK("Google.pl-PL-Chirp3-HD-Puck"), + GOOGLE_PL_PL_CHIRP3_HD_ZEPHYR("Google.pl-PL-Chirp3-HD-Zephyr"), GOOGLE_PL_PL_STANDARD_A("Google.pl-PL-Standard-A"), GOOGLE_PL_PL_STANDARD_B("Google.pl-PL-Standard-B"), GOOGLE_PL_PL_STANDARD_C("Google.pl-PL-Standard-C"), GOOGLE_PL_PL_STANDARD_D("Google.pl-PL-Standard-D"), GOOGLE_PL_PL_STANDARD_E("Google.pl-PL-Standard-E"), + GOOGLE_PL_PL_STANDARD_F("Google.pl-PL-Standard-F"), + GOOGLE_PL_PL_STANDARD_G("Google.pl-PL-Standard-G"), GOOGLE_PL_PL_WAVENET_A("Google.pl-PL-Wavenet-A"), GOOGLE_PL_PL_WAVENET_B("Google.pl-PL-Wavenet-B"), GOOGLE_PL_PL_WAVENET_C("Google.pl-PL-Wavenet-C"), GOOGLE_PL_PL_WAVENET_D("Google.pl-PL-Wavenet-D"), GOOGLE_PL_PL_WAVENET_E("Google.pl-PL-Wavenet-E"), + GOOGLE_PL_PL_WAVENET_F("Google.pl-PL-Wavenet-F"), + GOOGLE_PL_PL_WAVENET_G("Google.pl-PL-Wavenet-G"), + GOOGLE_PT_BR_CHIRP3_HD_AOEDE("Google.pt-BR-Chirp3-HD-Aoede"), + GOOGLE_PT_BR_CHIRP3_HD_CHARON("Google.pt-BR-Chirp3-HD-Charon"), + GOOGLE_PT_BR_CHIRP3_HD_FENRIR("Google.pt-BR-Chirp3-HD-Fenrir"), + GOOGLE_PT_BR_CHIRP3_HD_KORE("Google.pt-BR-Chirp3-HD-Kore"), + GOOGLE_PT_BR_CHIRP3_HD_LEDA("Google.pt-BR-Chirp3-HD-Leda"), + GOOGLE_PT_BR_CHIRP3_HD_ORUS("Google.pt-BR-Chirp3-HD-Orus"), + GOOGLE_PT_BR_CHIRP3_HD_PUCK("Google.pt-BR-Chirp3-HD-Puck"), + GOOGLE_PT_BR_CHIRP3_HD_ZEPHYR("Google.pt-BR-Chirp3-HD-Zephyr"), GOOGLE_PT_BR_NEURAL2_A("Google.pt-BR-Neural2-A"), GOOGLE_PT_BR_NEURAL2_B("Google.pt-BR-Neural2-B"), GOOGLE_PT_BR_NEURAL2_C("Google.pt-BR-Neural2-C"), GOOGLE_PT_BR_STANDARD_A("Google.pt-BR-Standard-A"), GOOGLE_PT_BR_STANDARD_B("Google.pt-BR-Standard-B"), GOOGLE_PT_BR_STANDARD_C("Google.pt-BR-Standard-C"), + GOOGLE_PT_BR_STANDARD_D("Google.pt-BR-Standard-D"), + GOOGLE_PT_BR_STANDARD_E("Google.pt-BR-Standard-E"), GOOGLE_PT_BR_WAVENET_A("Google.pt-BR-Wavenet-A"), GOOGLE_PT_BR_WAVENET_B("Google.pt-BR-Wavenet-B"), GOOGLE_PT_BR_WAVENET_C("Google.pt-BR-Wavenet-C"), + GOOGLE_PT_BR_WAVENET_D("Google.pt-BR-Wavenet-D"), + GOOGLE_PT_BR_WAVENET_E("Google.pt-BR-Wavenet-E"), GOOGLE_PT_PT_STANDARD_A("Google.pt-PT-Standard-A"), GOOGLE_PT_PT_STANDARD_B("Google.pt-PT-Standard-B"), GOOGLE_PT_PT_STANDARD_C("Google.pt-PT-Standard-C"), GOOGLE_PT_PT_STANDARD_D("Google.pt-PT-Standard-D"), + GOOGLE_PT_PT_STANDARD_E("Google.pt-PT-Standard-E"), + GOOGLE_PT_PT_STANDARD_F("Google.pt-PT-Standard-F"), GOOGLE_PT_PT_WAVENET_A("Google.pt-PT-Wavenet-A"), GOOGLE_PT_PT_WAVENET_B("Google.pt-PT-Wavenet-B"), GOOGLE_PT_PT_WAVENET_C("Google.pt-PT-Wavenet-C"), GOOGLE_PT_PT_WAVENET_D("Google.pt-PT-Wavenet-D"), + GOOGLE_PT_PT_WAVENET_E("Google.pt-PT-Wavenet-E"), + GOOGLE_PT_PT_WAVENET_F("Google.pt-PT-Wavenet-F"), GOOGLE_RO_RO_STANDARD_A("Google.ro-RO-Standard-A"), + GOOGLE_RO_RO_STANDARD_B("Google.ro-RO-Standard-B"), GOOGLE_RO_RO_WAVENET_A("Google.ro-RO-Wavenet-A"), + GOOGLE_RO_RO_WAVENET_B("Google.ro-RO-Wavenet-B"), + GOOGLE_RU_RU_CHIRP3_HD_AOEDE("Google.ru-RU-Chirp3-HD-Aoede"), + GOOGLE_RU_RU_CHIRP3_HD_CHARON("Google.ru-RU-Chirp3-HD-Charon"), + GOOGLE_RU_RU_CHIRP3_HD_FENRIR("Google.ru-RU-Chirp3-HD-Fenrir"), + GOOGLE_RU_RU_CHIRP3_HD_KORE("Google.ru-RU-Chirp3-HD-Kore"), + GOOGLE_RU_RU_CHIRP3_HD_LEDA("Google.ru-RU-Chirp3-HD-Leda"), + GOOGLE_RU_RU_CHIRP3_HD_ORUS("Google.ru-RU-Chirp3-HD-Orus"), + GOOGLE_RU_RU_CHIRP3_HD_PUCK("Google.ru-RU-Chirp3-HD-Puck"), + GOOGLE_RU_RU_CHIRP3_HD_ZEPHYR("Google.ru-RU-Chirp3-HD-Zephyr"), GOOGLE_RU_RU_STANDARD_A("Google.ru-RU-Standard-A"), GOOGLE_RU_RU_STANDARD_B("Google.ru-RU-Standard-B"), GOOGLE_RU_RU_STANDARD_C("Google.ru-RU-Standard-C"), @@ -379,18 +685,32 @@ public enum Voice { GOOGLE_RU_RU_WAVENET_D("Google.ru-RU-Wavenet-D"), GOOGLE_RU_RU_WAVENET_E("Google.ru-RU-Wavenet-E"), GOOGLE_SK_SK_STANDARD_A("Google.sk-SK-Standard-A"), + GOOGLE_SK_SK_STANDARD_B("Google.sk-SK-Standard-B"), GOOGLE_SK_SK_WAVENET_A("Google.sk-SK-Wavenet-A"), + GOOGLE_SK_SK_WAVENET_B("Google.sk-SK-Wavenet-B"), GOOGLE_SR_RS_STANDARD_A("Google.sr-RS-Standard-A"), GOOGLE_SV_SE_STANDARD_A("Google.sv-SE-Standard-A"), GOOGLE_SV_SE_STANDARD_B("Google.sv-SE-Standard-B"), GOOGLE_SV_SE_STANDARD_C("Google.sv-SE-Standard-C"), GOOGLE_SV_SE_STANDARD_D("Google.sv-SE-Standard-D"), GOOGLE_SV_SE_STANDARD_E("Google.sv-SE-Standard-E"), + GOOGLE_SV_SE_STANDARD_F("Google.sv-SE-Standard-F"), + GOOGLE_SV_SE_STANDARD_G("Google.sv-SE-Standard-G"), GOOGLE_SV_SE_WAVENET_A("Google.sv-SE-Wavenet-A"), GOOGLE_SV_SE_WAVENET_B("Google.sv-SE-Wavenet-B"), GOOGLE_SV_SE_WAVENET_C("Google.sv-SE-Wavenet-C"), GOOGLE_SV_SE_WAVENET_D("Google.sv-SE-Wavenet-D"), GOOGLE_SV_SE_WAVENET_E("Google.sv-SE-Wavenet-E"), + GOOGLE_SV_SE_WAVENET_F("Google.sv-SE-Wavenet-F"), + GOOGLE_SV_SE_WAVENET_G("Google.sv-SE-Wavenet-G"), + GOOGLE_TA_IN_CHIRP3_HD_AOEDE("Google.ta-IN-Chirp3-HD-Aoede"), + GOOGLE_TA_IN_CHIRP3_HD_CHARON("Google.ta-IN-Chirp3-HD-Charon"), + GOOGLE_TA_IN_CHIRP3_HD_FENRIR("Google.ta-IN-Chirp3-HD-Fenrir"), + GOOGLE_TA_IN_CHIRP3_HD_KORE("Google.ta-IN-Chirp3-HD-Kore"), + GOOGLE_TA_IN_CHIRP3_HD_LEDA("Google.ta-IN-Chirp3-HD-Leda"), + GOOGLE_TA_IN_CHIRP3_HD_ORUS("Google.ta-IN-Chirp3-HD-Orus"), + GOOGLE_TA_IN_CHIRP3_HD_PUCK("Google.ta-IN-Chirp3-HD-Puck"), + GOOGLE_TA_IN_CHIRP3_HD_ZEPHYR("Google.ta-IN-Chirp3-HD-Zephyr"), GOOGLE_TA_IN_STANDARD_A("Google.ta-IN-Standard-A"), GOOGLE_TA_IN_STANDARD_B("Google.ta-IN-Standard-B"), GOOGLE_TA_IN_STANDARD_C("Google.ta-IN-Standard-C"), @@ -399,10 +719,36 @@ public enum Voice { GOOGLE_TA_IN_WAVENET_B("Google.ta-IN-Wavenet-B"), GOOGLE_TA_IN_WAVENET_C("Google.ta-IN-Wavenet-C"), GOOGLE_TA_IN_WAVENET_D("Google.ta-IN-Wavenet-D"), + GOOGLE_TE_IN_CHIRP3_HD_AOEDE("Google.te-IN-Chirp3-HD-Aoede"), + GOOGLE_TE_IN_CHIRP3_HD_CHARON("Google.te-IN-Chirp3-HD-Charon"), + GOOGLE_TE_IN_CHIRP3_HD_FENRIR("Google.te-IN-Chirp3-HD-Fenrir"), + GOOGLE_TE_IN_CHIRP3_HD_KORE("Google.te-IN-Chirp3-HD-Kore"), + GOOGLE_TE_IN_CHIRP3_HD_LEDA("Google.te-IN-Chirp3-HD-Leda"), + GOOGLE_TE_IN_CHIRP3_HD_ORUS("Google.te-IN-Chirp3-HD-Orus"), + GOOGLE_TE_IN_CHIRP3_HD_PUCK("Google.te-IN-Chirp3-HD-Puck"), + GOOGLE_TE_IN_CHIRP3_HD_ZEPHYR("Google.te-IN-Chirp3-HD-Zephyr"), GOOGLE_TE_IN_STANDARD_A("Google.te-IN-Standard-A"), GOOGLE_TE_IN_STANDARD_B("Google.te-IN-Standard-B"), + GOOGLE_TE_IN_STANDARD_C("Google.te-IN-Standard-C"), + GOOGLE_TE_IN_STANDARD_D("Google.te-IN-Standard-D"), + GOOGLE_TH_TH_CHIRP3_HD_AOEDE("Google.th-TH-Chirp3-HD-Aoede"), + GOOGLE_TH_TH_CHIRP3_HD_CHARON("Google.th-TH-Chirp3-HD-Charon"), + GOOGLE_TH_TH_CHIRP3_HD_FENRIR("Google.th-TH-Chirp3-HD-Fenrir"), + GOOGLE_TH_TH_CHIRP3_HD_KORE("Google.th-TH-Chirp3-HD-Kore"), + GOOGLE_TH_TH_CHIRP3_HD_LEDA("Google.th-TH-Chirp3-HD-Leda"), + GOOGLE_TH_TH_CHIRP3_HD_ORUS("Google.th-TH-Chirp3-HD-Orus"), + GOOGLE_TH_TH_CHIRP3_HD_PUCK("Google.th-TH-Chirp3-HD-Puck"), + GOOGLE_TH_TH_CHIRP3_HD_ZEPHYR("Google.th-TH-Chirp3-HD-Zephyr"), GOOGLE_TH_TH_NEURAL2_C("Google.th-TH-Neural2-C"), GOOGLE_TH_TH_STANDARD_A("Google.th-TH-Standard-A"), + GOOGLE_TR_TR_CHIRP3_HD_AOEDE("Google.tr-TR-Chirp3-HD-Aoede"), + GOOGLE_TR_TR_CHIRP3_HD_CHARON("Google.tr-TR-Chirp3-HD-Charon"), + GOOGLE_TR_TR_CHIRP3_HD_FENRIR("Google.tr-TR-Chirp3-HD-Fenrir"), + GOOGLE_TR_TR_CHIRP3_HD_KORE("Google.tr-TR-Chirp3-HD-Kore"), + GOOGLE_TR_TR_CHIRP3_HD_LEDA("Google.tr-TR-Chirp3-HD-Leda"), + GOOGLE_TR_TR_CHIRP3_HD_ORUS("Google.tr-TR-Chirp3-HD-Orus"), + GOOGLE_TR_TR_CHIRP3_HD_PUCK("Google.tr-TR-Chirp3-HD-Puck"), + GOOGLE_TR_TR_CHIRP3_HD_ZEPHYR("Google.tr-TR-Chirp3-HD-Zephyr"), GOOGLE_TR_TR_STANDARD_A("Google.tr-TR-Standard-A"), GOOGLE_TR_TR_STANDARD_B("Google.tr-TR-Standard-B"), GOOGLE_TR_TR_STANDARD_C("Google.tr-TR-Standard-C"), @@ -415,6 +761,14 @@ public enum Voice { GOOGLE_TR_TR_WAVENET_E("Google.tr-TR-Wavenet-E"), GOOGLE_UK_UA_STANDARD_A("Google.uk-UA-Standard-A"), GOOGLE_UK_UA_WAVENET_A("Google.uk-UA-Wavenet-A"), + GOOGLE_VI_VN_CHIRP3_HD_AOEDE("Google.vi-VN-Chirp3-HD-Aoede"), + GOOGLE_VI_VN_CHIRP3_HD_CHARON("Google.vi-VN-Chirp3-HD-Charon"), + GOOGLE_VI_VN_CHIRP3_HD_FENRIR("Google.vi-VN-Chirp3-HD-Fenrir"), + GOOGLE_VI_VN_CHIRP3_HD_KORE("Google.vi-VN-Chirp3-HD-Kore"), + GOOGLE_VI_VN_CHIRP3_HD_LEDA("Google.vi-VN-Chirp3-HD-Leda"), + GOOGLE_VI_VN_CHIRP3_HD_ORUS("Google.vi-VN-Chirp3-HD-Orus"), + GOOGLE_VI_VN_CHIRP3_HD_PUCK("Google.vi-VN-Chirp3-HD-Puck"), + GOOGLE_VI_VN_CHIRP3_HD_ZEPHYR("Google.vi-VN-Chirp3-HD-Zephyr"), GOOGLE_VI_VN_NEURAL2_A("Google.vi-VN-Neural2-A"), GOOGLE_VI_VN_NEURAL2_D("Google.vi-VN-Neural2-D"), GOOGLE_VI_VN_STANDARD_A("Google.vi-VN-Standard-A"), @@ -459,6 +813,7 @@ public enum Voice { POLLY_JUSTIN("Polly.Justin"), POLLY_KARL("Polly.Karl"), POLLY_KENDRA("Polly.Kendra"), + POLLY_KEVIN("Polly.Kevin"), POLLY_KIMBERLY("Polly.Kimberly"), POLLY_LEA("Polly.Lea"), POLLY_LIV("Polly.Liv"), @@ -498,6 +853,7 @@ public enum Voice { POLLY_AYANDA_NEURAL("Polly.Ayanda-Neural"), POLLY_BIANCA_NEURAL("Polly.Bianca-Neural"), POLLY_BRIAN_NEURAL("Polly.Brian-Neural"), + POLLY_BURCU_NEURAL("Polly.Burcu-Neural"), POLLY_CAMILA_NEURAL("Polly.Camila-Neural"), POLLY_DANIEL_NEURAL("Polly.Daniel-Neural"), POLLY_DANIELLE_NEURAL("Polly.Danielle-Neural"), @@ -541,12 +897,32 @@ public enum Voice { POLLY_STEPHEN_NEURAL("Polly.Stephen-Neural"), POLLY_SUVI_NEURAL("Polly.Suvi-Neural"), POLLY_TAKUMI_NEURAL("Polly.Takumi-Neural"), - POLLY_TOMOKO_NEURAL("Polly.Tomoko-Neural"), POLLY_THIAGO_NEURAL("Polly.Thiago-Neural"), + POLLY_TOMOKO_NEURAL("Polly.Tomoko-Neural"), POLLY_VICKI_NEURAL("Polly.Vicki-Neural"), POLLY_VITORIA_NEURAL("Polly.Vitoria-Neural"), POLLY_ZAYD_NEURAL("Polly.Zayd-Neural"), - POLLY_ZHIYU_NEURAL("Polly.Zhiyu-Neural"); + POLLY_ZHIYU_NEURAL("Polly.Zhiyu-Neural"), + POLLY_AMY_GENERATIVE("Polly.Amy-Generative"), + POLLY_ANDRES_GENERATIVE("Polly.Andres-Generative"), + POLLY_AYANDA_GENERATIVE("Polly.Ayanda-Generative"), + POLLY_BIANCA_GENERATIVE("Polly.Bianca-Generative"), + POLLY_DANIEL_GENERATIVE("Polly.Daniel-Generative"), + POLLY_DANIELLE_GENERATIVE("Polly.Danielle-Generative"), + POLLY_JOANNA_GENERATIVE("Polly.Joanna-Generative"), + POLLY_KAJAL_GENERATIVE("Polly.Kajal-Generative"), + POLLY_LEA_GENERATIVE("Polly.Lea-Generative"), + POLLY_LUCIA_GENERATIVE("Polly.Lucia-Generative"), + POLLY_LUPE_GENERATIVE("Polly.Lupe-Generative"), + POLLY_MATTHEW_GENERATIVE("Polly.Matthew-Generative"), + POLLY_MÍA_GENERATIVE("Polly.Mía-Generative"), + POLLY_OLIVIA_GENERATIVE("Polly.Olivia-Generative"), + POLLY_PEDRO_GENERATIVE("Polly.Pedro-Generative"), + POLLY_RÉMI_GENERATIVE("Polly.Rémi-Generative"), + POLLY_RUTH_GENERATIVE("Polly.Ruth-Generative"), + POLLY_SERGIO_GENERATIVE("Polly.Sergio-Generative"), + POLLY_STEPHEN_GENERATIVE("Polly.Stephen-Generative"), + POLLY_VICKI_GENERATIVE("Polly.Vicki-Generative"); private final String value; From 0810ce5429d193d71837748cecdb6f4091d23721 Mon Sep 17 00:00:00 2001 From: Twilio Date: Thu, 24 Jul 2025 08:02:13 +0000 Subject: [PATCH 09/32] Release 11.0.0-rc.3 --- pom.xml | 4 ++-- src/main/java/com/twilio/Twilio.java | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/pom.xml b/pom.xml index 6550cce867..317961afc9 100644 --- a/pom.xml +++ b/pom.xml @@ -5,7 +5,7 @@ twilio jar twilio - 11.0.0-rc.2 + 11.0.0-rc.3 Twilio Java Helper Library https://www.twilio.com @@ -19,7 +19,7 @@ git@github.com:twilio/twilio-java.git scm:git:git@github.com:twilio/twilio-java.git scm:git:git@github.com:twilio/twilio-java.git - 11.0.0-rc.2 + 11.0.0-rc.3 diff --git a/src/main/java/com/twilio/Twilio.java b/src/main/java/com/twilio/Twilio.java index a41f0fa68b..3e33c76558 100644 --- a/src/main/java/com/twilio/Twilio.java +++ b/src/main/java/com/twilio/Twilio.java @@ -24,7 +24,7 @@ */ public class Twilio { - public static final String VERSION = "11.0.0-rc.2"; + public static final String VERSION = "11.0.0-rc.3"; public static final String JAVA_VERSION = System.getProperty("java.version"); public static final String OS_NAME = System.getProperty("os.name"); public static final String OS_ARCH = System.getProperty("os.arch"); From 4daff068cd1c63aa3fc7c19c80bdd997fabbdbf8 Mon Sep 17 00:00:00 2001 From: Twilio Date: Mon, 18 Aug 2025 08:59:41 +0000 Subject: [PATCH 10/32] [Librarian] Regenerated @ 3fba30a1b1e7c6460438ce1ca58c8ea68ad7b236 61d888152c68c1d07f711f67b7faf94bb9526469 --- CHANGES.md | 25 ++ .../rest/api/v2010/account/usage/Record.java | 16 + .../rest/api/v2010/account/usage/Trigger.java | 102 +++--- .../v2010/account/usage/record/AllTime.java | 16 + .../api/v2010/account/usage/record/Daily.java | 16 + .../v2010/account/usage/record/LastMonth.java | 16 + .../v2010/account/usage/record/Monthly.java | 16 + .../v2010/account/usage/record/ThisMonth.java | 16 + .../api/v2010/account/usage/record/Today.java | 16 + .../v2010/account/usage/record/Yearly.java | 16 + .../v2010/account/usage/record/Yesterday.java | 16 + .../rest/conversations/v1/Conversation.java | 27 +- .../v1/ConversationWithParticipants.java | 1 + .../service/ConversationWithParticipants.java | 1 + .../twilio/rest/flexapi/v1/Assessments.java | 20 +- .../v1/InsightsAssessmentsComment.java | 20 +- .../rest/flexapi/v2/WebChannelsCreator.java | 9 + .../com/twilio/rest/iam/v1/GetApiKeys.java | 17 +- .../rest/messaging/v2/ChannelsSender.java | 309 ++++++++++++++++-- .../twilio/rest/numbers/v1/PortingPortIn.java | 39 ++- .../com/twilio/rest/verify/v2/Service.java | 11 +- .../twilio/rest/verify/v2/ServiceCreator.java | 84 +++++ .../twilio/rest/verify/v2/ServiceUpdater.java | 42 +++ .../verify/v2/service/entity/Challenge.java | 29 +- .../rest/verify/v2/service/entity/Factor.java | 3 +- .../verify/v2/service/entity/NewFactor.java | 52 +-- 26 files changed, 784 insertions(+), 151 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index b410ee82df..d6ee45cb2e 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,6 +1,31 @@ twilio-java changelog ===================== +[2025-08-18] Version 11.0.0-rc.4 +-------------------------------- +**Accounts** +- Update beta feature flag for consent and contact bulk upsert APIs + +**Api** +- Add multiple missing usage categories to usage records and usage triggers api +- Add `channels-whatsapp-template-marketing` and `channels-whatsapp-template-utility` to usage categories + +**Conversations** +- Fix `state` spelling for `initializing` enum value +- Update `state` to include `intializing` for ServiceConversationWithParticipants and ConversationWithParticipants + +**Flex** +- Adding new optional parameter `identity` to `web_channels` API in version `v2` + +**Trusthub** +- Add required Permissions to the ComplianceInquiries API + +**Verify** +- Add passkeys support to Verify API creating and updating services. +- Update `ienum` type for Factor creation +- Add passkeys as challenge and factor type + + [2025-07-24] Version 11.0.0-rc.3 -------------------------------- **Events** diff --git a/src/main/java/com/twilio/rest/api/v2010/account/usage/Record.java b/src/main/java/com/twilio/rest/api/v2010/account/usage/Record.java index 5c05e36626..ec3633b60c 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/usage/Record.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/usage/Record.java @@ -363,6 +363,19 @@ public enum Category { ), CHANNELS_WHATSAPP_INBOUND("channels-whatsapp-inbound"), CHANNELS_WHATSAPP_OUTBOUND("channels-whatsapp-outbound"), + CHANNELS_WHATSAPP_SERVICE("channels-whatsapp-service"), + CHANNELS_WHATSAPP_TEMPLATE_AUTHENTICATION( + "channels-whatsapp-template-authentication" + ), + CHANNELS_WHATSAPP_TEMPLATE_MARKETING( + "channels-whatsapp-template-marketing" + ), + CHANNELS_WHATSAPP_TEMPLATE_SERVICE( + "channels-whatsapp-template-service" + ), + CHANNELS_WHATSAPP_TEMPLATE_UTILITY( + "channels-whatsapp-template-utility" + ), CHAT_VIRTUAL_AGENT("chat-virtual-agent"), CONVERSATION_RELAY("conversation-relay"), CONVERSATIONS("conversations"), @@ -772,6 +785,9 @@ public enum Category { VERIFY_WHATSAPP_CONVERSATIONS_BUSINESS_INITIATED( "verify-whatsapp-conversations-business-initiated" ), + VERIFY_WHATSAPP_TEMPLATE_BUSINESS_INITIATED( + "verify-whatsapp-template-business-initiated" + ), VIDEO_RECORDINGS("video-recordings"), VIDEO_ROOMS_TURN_MEGABYTES("video-rooms-turn-megabytes"), VIRTUAL_AGENT("virtual-agent"), diff --git a/src/main/java/com/twilio/rest/api/v2010/account/usage/Trigger.java b/src/main/java/com/twilio/rest/api/v2010/account/usage/Trigger.java index e18017d6e6..a29e15c04b 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/usage/Trigger.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/usage/Trigger.java @@ -320,6 +320,49 @@ public int hashCode() { ); } + public enum Recurring { + DAILY("daily"), + MONTHLY("monthly"), + YEARLY("yearly"), + ALLTIME("alltime"); + + private final String value; + + private Recurring(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static Recurring forValue(final String value) { + return Promoter.enumFromString(value, Recurring.values()); + } + } + + public enum TriggerField { + COUNT("count"), + USAGE("usage"), + PRICE("price"); + + private final String value; + + private TriggerField(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static TriggerField forValue(final String value) { + return Promoter.enumFromString(value, TriggerField.values()); + } + } + public enum UsageCategory { A2P_10DLC_REGISTRATIONFEES_BRANDREGISTRATION( "a2p-10dlc-registrationfees-brandregistration" @@ -420,6 +463,19 @@ public enum UsageCategory { ), CHANNELS_WHATSAPP_INBOUND("channels-whatsapp-inbound"), CHANNELS_WHATSAPP_OUTBOUND("channels-whatsapp-outbound"), + CHANNELS_WHATSAPP_SERVICE("channels-whatsapp-service"), + CHANNELS_WHATSAPP_TEMPLATE_AUTHENTICATION( + "channels-whatsapp-template-authentication" + ), + CHANNELS_WHATSAPP_TEMPLATE_MARKETING( + "channels-whatsapp-template-marketing" + ), + CHANNELS_WHATSAPP_TEMPLATE_SERVICE( + "channels-whatsapp-template-service" + ), + CHANNELS_WHATSAPP_TEMPLATE_UTILITY( + "channels-whatsapp-template-utility" + ), CHAT_VIRTUAL_AGENT("chat-virtual-agent"), CONVERSATION_RELAY("conversation-relay"), CONVERSATIONS("conversations"), @@ -829,6 +885,9 @@ public enum UsageCategory { VERIFY_WHATSAPP_CONVERSATIONS_BUSINESS_INITIATED( "verify-whatsapp-conversations-business-initiated" ), + VERIFY_WHATSAPP_TEMPLATE_BUSINESS_INITIATED( + "verify-whatsapp-template-business-initiated" + ), VIDEO_RECORDINGS("video-recordings"), VIDEO_ROOMS_TURN_MEGABYTES("video-rooms-turn-megabytes"), VIRTUAL_AGENT("virtual-agent"), @@ -1244,47 +1303,4 @@ public static UsageCategory forValue(final String value) { return Promoter.enumFromString(value, UsageCategory.values()); } } - - public enum Recurring { - DAILY("daily"), - MONTHLY("monthly"), - YEARLY("yearly"), - ALLTIME("alltime"); - - private final String value; - - private Recurring(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static Recurring forValue(final String value) { - return Promoter.enumFromString(value, Recurring.values()); - } - } - - public enum TriggerField { - COUNT("count"), - USAGE("usage"), - PRICE("price"); - - private final String value; - - private TriggerField(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static TriggerField forValue(final String value) { - return Promoter.enumFromString(value, TriggerField.values()); - } - } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/usage/record/AllTime.java b/src/main/java/com/twilio/rest/api/v2010/account/usage/record/AllTime.java index 2e5e8e1938..d838c14ce6 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/usage/record/AllTime.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/usage/record/AllTime.java @@ -363,6 +363,19 @@ public enum Category { ), CHANNELS_WHATSAPP_INBOUND("channels-whatsapp-inbound"), CHANNELS_WHATSAPP_OUTBOUND("channels-whatsapp-outbound"), + CHANNELS_WHATSAPP_SERVICE("channels-whatsapp-service"), + CHANNELS_WHATSAPP_TEMPLATE_AUTHENTICATION( + "channels-whatsapp-template-authentication" + ), + CHANNELS_WHATSAPP_TEMPLATE_MARKETING( + "channels-whatsapp-template-marketing" + ), + CHANNELS_WHATSAPP_TEMPLATE_SERVICE( + "channels-whatsapp-template-service" + ), + CHANNELS_WHATSAPP_TEMPLATE_UTILITY( + "channels-whatsapp-template-utility" + ), CHAT_VIRTUAL_AGENT("chat-virtual-agent"), CONVERSATION_RELAY("conversation-relay"), CONVERSATIONS("conversations"), @@ -772,6 +785,9 @@ public enum Category { VERIFY_WHATSAPP_CONVERSATIONS_BUSINESS_INITIATED( "verify-whatsapp-conversations-business-initiated" ), + VERIFY_WHATSAPP_TEMPLATE_BUSINESS_INITIATED( + "verify-whatsapp-template-business-initiated" + ), VIDEO_RECORDINGS("video-recordings"), VIDEO_ROOMS_TURN_MEGABYTES("video-rooms-turn-megabytes"), VIRTUAL_AGENT("virtual-agent"), diff --git a/src/main/java/com/twilio/rest/api/v2010/account/usage/record/Daily.java b/src/main/java/com/twilio/rest/api/v2010/account/usage/record/Daily.java index c562e8b219..854ee718c6 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/usage/record/Daily.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/usage/record/Daily.java @@ -363,6 +363,19 @@ public enum Category { ), CHANNELS_WHATSAPP_INBOUND("channels-whatsapp-inbound"), CHANNELS_WHATSAPP_OUTBOUND("channels-whatsapp-outbound"), + CHANNELS_WHATSAPP_SERVICE("channels-whatsapp-service"), + CHANNELS_WHATSAPP_TEMPLATE_AUTHENTICATION( + "channels-whatsapp-template-authentication" + ), + CHANNELS_WHATSAPP_TEMPLATE_MARKETING( + "channels-whatsapp-template-marketing" + ), + CHANNELS_WHATSAPP_TEMPLATE_SERVICE( + "channels-whatsapp-template-service" + ), + CHANNELS_WHATSAPP_TEMPLATE_UTILITY( + "channels-whatsapp-template-utility" + ), CHAT_VIRTUAL_AGENT("chat-virtual-agent"), CONVERSATION_RELAY("conversation-relay"), CONVERSATIONS("conversations"), @@ -772,6 +785,9 @@ public enum Category { VERIFY_WHATSAPP_CONVERSATIONS_BUSINESS_INITIATED( "verify-whatsapp-conversations-business-initiated" ), + VERIFY_WHATSAPP_TEMPLATE_BUSINESS_INITIATED( + "verify-whatsapp-template-business-initiated" + ), VIDEO_RECORDINGS("video-recordings"), VIDEO_ROOMS_TURN_MEGABYTES("video-rooms-turn-megabytes"), VIRTUAL_AGENT("virtual-agent"), diff --git a/src/main/java/com/twilio/rest/api/v2010/account/usage/record/LastMonth.java b/src/main/java/com/twilio/rest/api/v2010/account/usage/record/LastMonth.java index 471a20a4d8..87a6635f8c 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/usage/record/LastMonth.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/usage/record/LastMonth.java @@ -363,6 +363,19 @@ public enum Category { ), CHANNELS_WHATSAPP_INBOUND("channels-whatsapp-inbound"), CHANNELS_WHATSAPP_OUTBOUND("channels-whatsapp-outbound"), + CHANNELS_WHATSAPP_SERVICE("channels-whatsapp-service"), + CHANNELS_WHATSAPP_TEMPLATE_AUTHENTICATION( + "channels-whatsapp-template-authentication" + ), + CHANNELS_WHATSAPP_TEMPLATE_MARKETING( + "channels-whatsapp-template-marketing" + ), + CHANNELS_WHATSAPP_TEMPLATE_SERVICE( + "channels-whatsapp-template-service" + ), + CHANNELS_WHATSAPP_TEMPLATE_UTILITY( + "channels-whatsapp-template-utility" + ), CHAT_VIRTUAL_AGENT("chat-virtual-agent"), CONVERSATION_RELAY("conversation-relay"), CONVERSATIONS("conversations"), @@ -772,6 +785,9 @@ public enum Category { VERIFY_WHATSAPP_CONVERSATIONS_BUSINESS_INITIATED( "verify-whatsapp-conversations-business-initiated" ), + VERIFY_WHATSAPP_TEMPLATE_BUSINESS_INITIATED( + "verify-whatsapp-template-business-initiated" + ), VIDEO_RECORDINGS("video-recordings"), VIDEO_ROOMS_TURN_MEGABYTES("video-rooms-turn-megabytes"), VIRTUAL_AGENT("virtual-agent"), diff --git a/src/main/java/com/twilio/rest/api/v2010/account/usage/record/Monthly.java b/src/main/java/com/twilio/rest/api/v2010/account/usage/record/Monthly.java index 315837e39e..f6f3d7b082 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/usage/record/Monthly.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/usage/record/Monthly.java @@ -363,6 +363,19 @@ public enum Category { ), CHANNELS_WHATSAPP_INBOUND("channels-whatsapp-inbound"), CHANNELS_WHATSAPP_OUTBOUND("channels-whatsapp-outbound"), + CHANNELS_WHATSAPP_SERVICE("channels-whatsapp-service"), + CHANNELS_WHATSAPP_TEMPLATE_AUTHENTICATION( + "channels-whatsapp-template-authentication" + ), + CHANNELS_WHATSAPP_TEMPLATE_MARKETING( + "channels-whatsapp-template-marketing" + ), + CHANNELS_WHATSAPP_TEMPLATE_SERVICE( + "channels-whatsapp-template-service" + ), + CHANNELS_WHATSAPP_TEMPLATE_UTILITY( + "channels-whatsapp-template-utility" + ), CHAT_VIRTUAL_AGENT("chat-virtual-agent"), CONVERSATION_RELAY("conversation-relay"), CONVERSATIONS("conversations"), @@ -772,6 +785,9 @@ public enum Category { VERIFY_WHATSAPP_CONVERSATIONS_BUSINESS_INITIATED( "verify-whatsapp-conversations-business-initiated" ), + VERIFY_WHATSAPP_TEMPLATE_BUSINESS_INITIATED( + "verify-whatsapp-template-business-initiated" + ), VIDEO_RECORDINGS("video-recordings"), VIDEO_ROOMS_TURN_MEGABYTES("video-rooms-turn-megabytes"), VIRTUAL_AGENT("virtual-agent"), diff --git a/src/main/java/com/twilio/rest/api/v2010/account/usage/record/ThisMonth.java b/src/main/java/com/twilio/rest/api/v2010/account/usage/record/ThisMonth.java index f0799a55f9..8bcd8c6d99 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/usage/record/ThisMonth.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/usage/record/ThisMonth.java @@ -363,6 +363,19 @@ public enum Category { ), CHANNELS_WHATSAPP_INBOUND("channels-whatsapp-inbound"), CHANNELS_WHATSAPP_OUTBOUND("channels-whatsapp-outbound"), + CHANNELS_WHATSAPP_SERVICE("channels-whatsapp-service"), + CHANNELS_WHATSAPP_TEMPLATE_AUTHENTICATION( + "channels-whatsapp-template-authentication" + ), + CHANNELS_WHATSAPP_TEMPLATE_MARKETING( + "channels-whatsapp-template-marketing" + ), + CHANNELS_WHATSAPP_TEMPLATE_SERVICE( + "channels-whatsapp-template-service" + ), + CHANNELS_WHATSAPP_TEMPLATE_UTILITY( + "channels-whatsapp-template-utility" + ), CHAT_VIRTUAL_AGENT("chat-virtual-agent"), CONVERSATION_RELAY("conversation-relay"), CONVERSATIONS("conversations"), @@ -772,6 +785,9 @@ public enum Category { VERIFY_WHATSAPP_CONVERSATIONS_BUSINESS_INITIATED( "verify-whatsapp-conversations-business-initiated" ), + VERIFY_WHATSAPP_TEMPLATE_BUSINESS_INITIATED( + "verify-whatsapp-template-business-initiated" + ), VIDEO_RECORDINGS("video-recordings"), VIDEO_ROOMS_TURN_MEGABYTES("video-rooms-turn-megabytes"), VIRTUAL_AGENT("virtual-agent"), diff --git a/src/main/java/com/twilio/rest/api/v2010/account/usage/record/Today.java b/src/main/java/com/twilio/rest/api/v2010/account/usage/record/Today.java index 38c0f84024..dcfcc4fcb5 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/usage/record/Today.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/usage/record/Today.java @@ -363,6 +363,19 @@ public enum Category { ), CHANNELS_WHATSAPP_INBOUND("channels-whatsapp-inbound"), CHANNELS_WHATSAPP_OUTBOUND("channels-whatsapp-outbound"), + CHANNELS_WHATSAPP_SERVICE("channels-whatsapp-service"), + CHANNELS_WHATSAPP_TEMPLATE_AUTHENTICATION( + "channels-whatsapp-template-authentication" + ), + CHANNELS_WHATSAPP_TEMPLATE_MARKETING( + "channels-whatsapp-template-marketing" + ), + CHANNELS_WHATSAPP_TEMPLATE_SERVICE( + "channels-whatsapp-template-service" + ), + CHANNELS_WHATSAPP_TEMPLATE_UTILITY( + "channels-whatsapp-template-utility" + ), CHAT_VIRTUAL_AGENT("chat-virtual-agent"), CONVERSATION_RELAY("conversation-relay"), CONVERSATIONS("conversations"), @@ -772,6 +785,9 @@ public enum Category { VERIFY_WHATSAPP_CONVERSATIONS_BUSINESS_INITIATED( "verify-whatsapp-conversations-business-initiated" ), + VERIFY_WHATSAPP_TEMPLATE_BUSINESS_INITIATED( + "verify-whatsapp-template-business-initiated" + ), VIDEO_RECORDINGS("video-recordings"), VIDEO_ROOMS_TURN_MEGABYTES("video-rooms-turn-megabytes"), VIRTUAL_AGENT("virtual-agent"), diff --git a/src/main/java/com/twilio/rest/api/v2010/account/usage/record/Yearly.java b/src/main/java/com/twilio/rest/api/v2010/account/usage/record/Yearly.java index bc447957ac..71e97db657 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/usage/record/Yearly.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/usage/record/Yearly.java @@ -363,6 +363,19 @@ public enum Category { ), CHANNELS_WHATSAPP_INBOUND("channels-whatsapp-inbound"), CHANNELS_WHATSAPP_OUTBOUND("channels-whatsapp-outbound"), + CHANNELS_WHATSAPP_SERVICE("channels-whatsapp-service"), + CHANNELS_WHATSAPP_TEMPLATE_AUTHENTICATION( + "channels-whatsapp-template-authentication" + ), + CHANNELS_WHATSAPP_TEMPLATE_MARKETING( + "channels-whatsapp-template-marketing" + ), + CHANNELS_WHATSAPP_TEMPLATE_SERVICE( + "channels-whatsapp-template-service" + ), + CHANNELS_WHATSAPP_TEMPLATE_UTILITY( + "channels-whatsapp-template-utility" + ), CHAT_VIRTUAL_AGENT("chat-virtual-agent"), CONVERSATION_RELAY("conversation-relay"), CONVERSATIONS("conversations"), @@ -772,6 +785,9 @@ public enum Category { VERIFY_WHATSAPP_CONVERSATIONS_BUSINESS_INITIATED( "verify-whatsapp-conversations-business-initiated" ), + VERIFY_WHATSAPP_TEMPLATE_BUSINESS_INITIATED( + "verify-whatsapp-template-business-initiated" + ), VIDEO_RECORDINGS("video-recordings"), VIDEO_ROOMS_TURN_MEGABYTES("video-rooms-turn-megabytes"), VIRTUAL_AGENT("virtual-agent"), diff --git a/src/main/java/com/twilio/rest/api/v2010/account/usage/record/Yesterday.java b/src/main/java/com/twilio/rest/api/v2010/account/usage/record/Yesterday.java index f271504c4b..97223fff23 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/usage/record/Yesterday.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/usage/record/Yesterday.java @@ -363,6 +363,19 @@ public enum Category { ), CHANNELS_WHATSAPP_INBOUND("channels-whatsapp-inbound"), CHANNELS_WHATSAPP_OUTBOUND("channels-whatsapp-outbound"), + CHANNELS_WHATSAPP_SERVICE("channels-whatsapp-service"), + CHANNELS_WHATSAPP_TEMPLATE_AUTHENTICATION( + "channels-whatsapp-template-authentication" + ), + CHANNELS_WHATSAPP_TEMPLATE_MARKETING( + "channels-whatsapp-template-marketing" + ), + CHANNELS_WHATSAPP_TEMPLATE_SERVICE( + "channels-whatsapp-template-service" + ), + CHANNELS_WHATSAPP_TEMPLATE_UTILITY( + "channels-whatsapp-template-utility" + ), CHAT_VIRTUAL_AGENT("chat-virtual-agent"), CONVERSATION_RELAY("conversation-relay"), CONVERSATIONS("conversations"), @@ -772,6 +785,9 @@ public enum Category { VERIFY_WHATSAPP_CONVERSATIONS_BUSINESS_INITIATED( "verify-whatsapp-conversations-business-initiated" ), + VERIFY_WHATSAPP_TEMPLATE_BUSINESS_INITIATED( + "verify-whatsapp-template-business-initiated" + ), VIDEO_RECORDINGS("video-recordings"), VIDEO_ROOMS_TURN_MEGABYTES("video-rooms-turn-megabytes"), VIRTUAL_AGENT("virtual-agent"), diff --git a/src/main/java/com/twilio/rest/conversations/v1/Conversation.java b/src/main/java/com/twilio/rest/conversations/v1/Conversation.java index dc54e2affc..6a849cb54e 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/Conversation.java +++ b/src/main/java/com/twilio/rest/conversations/v1/Conversation.java @@ -258,14 +258,13 @@ public int hashCode() { ); } - public enum State { - INACTIVE("inactive"), - ACTIVE("active"), - CLOSED("closed"); + public enum WebhookEnabledType { + TRUE("true"), + FALSE("false"); private final String value; - private State(final String value) { + private WebhookEnabledType(final String value) { this.value = value; } @@ -274,18 +273,20 @@ public String toString() { } @JsonCreator - public static State forValue(final String value) { - return Promoter.enumFromString(value, State.values()); + public static WebhookEnabledType forValue(final String value) { + return Promoter.enumFromString(value, WebhookEnabledType.values()); } } - public enum WebhookEnabledType { - TRUE("true"), - FALSE("false"); + public enum State { + INITIALIZING("initializing"), + INACTIVE("inactive"), + ACTIVE("active"), + CLOSED("closed"); private final String value; - private WebhookEnabledType(final String value) { + private State(final String value) { this.value = value; } @@ -294,8 +295,8 @@ public String toString() { } @JsonCreator - public static WebhookEnabledType forValue(final String value) { - return Promoter.enumFromString(value, WebhookEnabledType.values()); + public static State forValue(final String value) { + return Promoter.enumFromString(value, State.values()); } } } diff --git a/src/main/java/com/twilio/rest/conversations/v1/ConversationWithParticipants.java b/src/main/java/com/twilio/rest/conversations/v1/ConversationWithParticipants.java index ac73b9afa2..5ae7e297d4 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/ConversationWithParticipants.java +++ b/src/main/java/com/twilio/rest/conversations/v1/ConversationWithParticipants.java @@ -249,6 +249,7 @@ public int hashCode() { } public enum State { + INITIALIZING("initializing"), INACTIVE("inactive"), ACTIVE("active"), CLOSED("closed"); diff --git a/src/main/java/com/twilio/rest/conversations/v1/service/ConversationWithParticipants.java b/src/main/java/com/twilio/rest/conversations/v1/service/ConversationWithParticipants.java index 939f0389d7..6726d9630b 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/service/ConversationWithParticipants.java +++ b/src/main/java/com/twilio/rest/conversations/v1/service/ConversationWithParticipants.java @@ -251,6 +251,7 @@ public int hashCode() { } public enum State { + INITIALIZING("initializing"), INACTIVE("inactive"), ACTIVE("active"), CLOSED("closed"); diff --git a/src/main/java/com/twilio/rest/flexapi/v1/Assessments.java b/src/main/java/com/twilio/rest/flexapi/v1/Assessments.java index 7bade94c98..21563c4279 100644 --- a/src/main/java/com/twilio/rest/flexapi/v1/Assessments.java +++ b/src/main/java/com/twilio/rest/flexapi/v1/Assessments.java @@ -37,7 +37,7 @@ @ToString public class Assessments extends Resource { - private static final long serialVersionUID = 249351913918322L; + private static final long serialVersionUID = 2474918794072L; public static AssessmentsCreator creator( final String categorySid, @@ -128,9 +128,9 @@ public static Assessments fromJson( private final String accountSid; private final String assessmentSid; - private final BigDecimal offset; + private final String offset; private final Boolean report; - private final BigDecimal weight; + private final String weight; private final String agentId; private final String segmentId; private final String userName; @@ -138,16 +138,16 @@ public static Assessments fromJson( private final String answerText; private final String answerId; private final Map assessment; - private final BigDecimal timestamp; + private final String timestamp; private final URI url; @JsonCreator private Assessments( @JsonProperty("account_sid") final String accountSid, @JsonProperty("assessment_sid") final String assessmentSid, - @JsonProperty("offset") final BigDecimal offset, + @JsonProperty("offset") final String offset, @JsonProperty("report") final Boolean report, - @JsonProperty("weight") final BigDecimal weight, + @JsonProperty("weight") final String weight, @JsonProperty("agent_id") final String agentId, @JsonProperty("segment_id") final String segmentId, @JsonProperty("user_name") final String userName, @@ -155,7 +155,7 @@ private Assessments( @JsonProperty("answer_text") final String answerText, @JsonProperty("answer_id") final String answerId, @JsonProperty("assessment") final Map assessment, - @JsonProperty("timestamp") final BigDecimal timestamp, + @JsonProperty("timestamp") final String timestamp, @JsonProperty("url") final URI url ) { this.accountSid = accountSid; @@ -182,7 +182,7 @@ public final String getAssessmentSid() { return this.assessmentSid; } - public final BigDecimal getOffset() { + public final String getOffset() { return this.offset; } @@ -190,7 +190,7 @@ public final Boolean getReport() { return this.report; } - public final BigDecimal getWeight() { + public final String getWeight() { return this.weight; } @@ -222,7 +222,7 @@ public final Map getAssessment() { return this.assessment; } - public final BigDecimal getTimestamp() { + public final String getTimestamp() { return this.timestamp; } diff --git a/src/main/java/com/twilio/rest/flexapi/v1/InsightsAssessmentsComment.java b/src/main/java/com/twilio/rest/flexapi/v1/InsightsAssessmentsComment.java index 115b9e464b..d895b3d0e4 100644 --- a/src/main/java/com/twilio/rest/flexapi/v1/InsightsAssessmentsComment.java +++ b/src/main/java/com/twilio/rest/flexapi/v1/InsightsAssessmentsComment.java @@ -37,7 +37,7 @@ @ToString public class InsightsAssessmentsComment extends Resource { - private static final long serialVersionUID = 175598645429423L; + private static final long serialVersionUID = 119423741777853L; public static InsightsAssessmentsCommentCreator creator( final String categoryId, @@ -113,14 +113,14 @@ public static InsightsAssessmentsComment fromJson( private final String accountSid; private final String assessmentSid; private final Map comment; - private final BigDecimal offset; + private final String offset; private final Boolean report; - private final BigDecimal weight; + private final String weight; private final String agentId; private final String segmentId; private final String userName; private final String userEmail; - private final BigDecimal timestamp; + private final String timestamp; private final URI url; @JsonCreator @@ -128,14 +128,14 @@ private InsightsAssessmentsComment( @JsonProperty("account_sid") final String accountSid, @JsonProperty("assessment_sid") final String assessmentSid, @JsonProperty("comment") final Map comment, - @JsonProperty("offset") final BigDecimal offset, + @JsonProperty("offset") final String offset, @JsonProperty("report") final Boolean report, - @JsonProperty("weight") final BigDecimal weight, + @JsonProperty("weight") final String weight, @JsonProperty("agent_id") final String agentId, @JsonProperty("segment_id") final String segmentId, @JsonProperty("user_name") final String userName, @JsonProperty("user_email") final String userEmail, - @JsonProperty("timestamp") final BigDecimal timestamp, + @JsonProperty("timestamp") final String timestamp, @JsonProperty("url") final URI url ) { this.accountSid = accountSid; @@ -164,7 +164,7 @@ public final Map getComment() { return this.comment; } - public final BigDecimal getOffset() { + public final String getOffset() { return this.offset; } @@ -172,7 +172,7 @@ public final Boolean getReport() { return this.report; } - public final BigDecimal getWeight() { + public final String getWeight() { return this.weight; } @@ -192,7 +192,7 @@ public final String getUserEmail() { return this.userEmail; } - public final BigDecimal getTimestamp() { + public final String getTimestamp() { return this.timestamp; } diff --git a/src/main/java/com/twilio/rest/flexapi/v2/WebChannelsCreator.java b/src/main/java/com/twilio/rest/flexapi/v2/WebChannelsCreator.java index e01a533e65..764380105a 100644 --- a/src/main/java/com/twilio/rest/flexapi/v2/WebChannelsCreator.java +++ b/src/main/java/com/twilio/rest/flexapi/v2/WebChannelsCreator.java @@ -32,6 +32,7 @@ public class WebChannelsCreator extends Creator { private String chatFriendlyName; private String customerFriendlyName; private String preEngagementData; + private String identity; public WebChannelsCreator(final String addressSid) { this.addressSid = addressSid; @@ -68,6 +69,11 @@ public WebChannelsCreator setPreEngagementData( return this; } + public WebChannelsCreator setIdentity(final String identity) { + this.identity = identity; + return this; + } + @Override public WebChannels create(final TwilioRestClient client) { String path = "/v2/WebChats"; @@ -121,6 +127,9 @@ private void addPostParams(final Request request) { if (preEngagementData != null) { request.addPostParam("PreEngagementData", preEngagementData); } + if (identity != null) { + request.addPostParam("Identity", identity); + } } private void addHeaderParams(final Request request) { diff --git a/src/main/java/com/twilio/rest/iam/v1/GetApiKeys.java b/src/main/java/com/twilio/rest/iam/v1/GetApiKeys.java index 56a2d87548..9357e8697e 100644 --- a/src/main/java/com/twilio/rest/iam/v1/GetApiKeys.java +++ b/src/main/java/com/twilio/rest/iam/v1/GetApiKeys.java @@ -27,6 +27,7 @@ import java.io.IOException; import java.io.InputStream; import java.time.ZonedDateTime; +import java.util.List; import java.util.Objects; import lombok.ToString; import lombok.ToString; @@ -35,7 +36,7 @@ @ToString public class GetApiKeys extends Resource { - private static final long serialVersionUID = 35259719636912L; + private static final long serialVersionUID = 72145637372666L; public static GetApiKeysReader reader(final String accountSid) { return new GetApiKeysReader(accountSid); @@ -88,18 +89,21 @@ public static GetApiKeys fromJson( private final String friendlyName; private final ZonedDateTime dateCreated; private final ZonedDateTime dateUpdated; + private final List flags; @JsonCreator private GetApiKeys( @JsonProperty("sid") final String sid, @JsonProperty("friendly_name") final String friendlyName, @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated + @JsonProperty("date_updated") final String dateUpdated, + @JsonProperty("flags") final List flags ) { this.sid = sid; this.friendlyName = friendlyName; this.dateCreated = DateConverter.rfc2822DateTimeFromString(dateCreated); this.dateUpdated = DateConverter.rfc2822DateTimeFromString(dateUpdated); + this.flags = flags; } public final String getSid() { @@ -118,6 +122,10 @@ public final ZonedDateTime getDateUpdated() { return this.dateUpdated; } + public final List getFlags() { + return this.flags; + } + @Override public boolean equals(final Object o) { if (this == o) { @@ -134,12 +142,13 @@ public boolean equals(final Object o) { Objects.equals(sid, other.sid) && Objects.equals(friendlyName, other.friendlyName) && Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(flags, other.flags) ); } @Override public int hashCode() { - return Objects.hash(sid, friendlyName, dateCreated, dateUpdated); + return Objects.hash(sid, friendlyName, dateCreated, dateUpdated, flags); } } diff --git a/src/main/java/com/twilio/rest/messaging/v2/ChannelsSender.java b/src/main/java/com/twilio/rest/messaging/v2/ChannelsSender.java index 668b7a85cb..3a3dbd704a 100644 --- a/src/main/java/com/twilio/rest/messaging/v2/ChannelsSender.java +++ b/src/main/java/com/twilio/rest/messaging/v2/ChannelsSender.java @@ -40,7 +40,7 @@ @ToString public class ChannelsSender extends Resource { - private static final long serialVersionUID = 103954331986266L; + private static final long serialVersionUID = 140943943425747L; @ToString public static class MessagingV2ChannelsSenderConfiguration { @@ -158,16 +158,34 @@ public static class MessagingV2ChannelsSenderProfile { private String description; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("emails") + @JsonProperty("logo_url") @Getter @Setter - private Object emails; + private String logoUrl; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("logo_url") + @JsonProperty("banner_url") @Getter @Setter - private String logoUrl; + private String bannerUrl; + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("privacy_url") + @Getter + @Setter + private String privacyUrl; + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("terms_of_service_url") + @Getter + @Setter + private String termsOfServiceUrl; + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("accent_color") + @Getter + @Setter + private String accentColor; @JsonInclude(JsonInclude.Include.NON_EMPTY) @JsonProperty("vertical") @@ -181,6 +199,18 @@ public static class MessagingV2ChannelsSenderProfile { @Setter private Object websites; + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("emails") + @Getter + @Setter + private Object emails; + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("phone_numbers") + @Getter + @Setter + private Object phoneNumbers; + public static MessagingV2ChannelsSenderProfile fromJson( String jsonString, ObjectMapper mapper @@ -269,7 +299,33 @@ public static MessagingV2ChannelsSenderRequestsUpdate fromJson( } @ToString - public static class MessagingV2ChannelsSenderProfileResponseEmails { + public static class MessagingV2ChannelsSenderProfileGenericResponseWebsites { + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("website") + @Getter + @Setter + private String website; + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("label") + @Getter + @Setter + private String label; + + public static MessagingV2ChannelsSenderProfileGenericResponseWebsites fromJson( + String jsonString, + ObjectMapper mapper + ) throws IOException { + return mapper.readValue( + jsonString, + MessagingV2ChannelsSenderProfileGenericResponseWebsites.class + ); + } + } + + @ToString + public static class MessagingV2ChannelsSenderProfileGenericResponseEmails { @JsonInclude(JsonInclude.Include.NON_EMPTY) @JsonProperty("email") @@ -283,25 +339,25 @@ public static class MessagingV2ChannelsSenderProfileResponseEmails { @Setter private String label; - public static MessagingV2ChannelsSenderProfileResponseEmails fromJson( + public static MessagingV2ChannelsSenderProfileGenericResponseEmails fromJson( String jsonString, ObjectMapper mapper ) throws IOException { return mapper.readValue( jsonString, - MessagingV2ChannelsSenderProfileResponseEmails.class + MessagingV2ChannelsSenderProfileGenericResponseEmails.class ); } } @ToString - public static class MessagingV2ChannelsSenderProfileResponseWebsites { + public static class MessagingV2ChannelsSenderProfileGenericResponsePhoneNumbers { @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("website") + @JsonProperty("phone_number") @Getter @Setter - private String website; + private String phoneNumber; @JsonInclude(JsonInclude.Include.NON_EMPTY) @JsonProperty("label") @@ -309,19 +365,19 @@ public static class MessagingV2ChannelsSenderProfileResponseWebsites { @Setter private String label; - public static MessagingV2ChannelsSenderProfileResponseWebsites fromJson( + public static MessagingV2ChannelsSenderProfileGenericResponsePhoneNumbers fromJson( String jsonString, ObjectMapper mapper ) throws IOException { return mapper.readValue( jsonString, - MessagingV2ChannelsSenderProfileResponseWebsites.class + MessagingV2ChannelsSenderProfileGenericResponsePhoneNumbers.class ); } } @ToString - public static class MessagingV2ChannelsSenderProfileResponse { + public static class MessagingV2ChannelsSenderProfileGenericResponse { @JsonInclude(JsonInclude.Include.NON_EMPTY) @JsonProperty("name") @@ -348,16 +404,34 @@ public static class MessagingV2ChannelsSenderProfileResponse { private String description; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("emails") + @JsonProperty("logo_url") @Getter @Setter - private List emails; + private String logoUrl; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("logo_url") + @JsonProperty("banner_url") @Getter @Setter - private String logoUrl; + private String bannerUrl; + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("privacy_url") + @Getter + @Setter + private String privacyUrl; + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("terms_of_service_url") + @Getter + @Setter + private String termsOfServiceUrl; + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("accent_color") + @Getter + @Setter + private String accentColor; @JsonInclude(JsonInclude.Include.NON_EMPTY) @JsonProperty("vertical") @@ -369,15 +443,33 @@ public static class MessagingV2ChannelsSenderProfileResponse { @JsonProperty("websites") @Getter @Setter - private List websites; + private List< + MessagingV2ChannelsSenderProfileGenericResponseWebsites + > websites; + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("emails") + @Getter + @Setter + private List< + MessagingV2ChannelsSenderProfileGenericResponseEmails + > emails; - public static MessagingV2ChannelsSenderProfileResponse fromJson( + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("phone_numbers") + @Getter + @Setter + private List< + MessagingV2ChannelsSenderProfileGenericResponsePhoneNumbers + > phoneNumbers; + + public static MessagingV2ChannelsSenderProfileGenericResponse fromJson( String jsonString, ObjectMapper mapper ) throws IOException { return mapper.readValue( jsonString, - MessagingV2ChannelsSenderProfileResponse.class + MessagingV2ChannelsSenderProfileGenericResponse.class ); } } @@ -440,6 +532,93 @@ public static MessagingV2ChannelsSenderOfflineReasonsItems fromJson( } } + @ToString + public static class MessagingV2RcsCarrier { + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("name") + @Getter + @Setter + private String name; + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("status") + @Getter + @Setter + private MessagingV2RcsCarrierStatus status; + + public static MessagingV2RcsCarrier fromJson( + String jsonString, + ObjectMapper mapper + ) throws IOException { + return mapper.readValue(jsonString, MessagingV2RcsCarrier.class); + } + } + + @ToString + public static class MessagingV2RcsComplianceCountryResponse { + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("country") + @Getter + @Setter + private String country; + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("registration_sid") + @Getter + @Setter + private String registrationSid; + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("status") + @Getter + @Setter + private MessagingV2RcsCountryStatus status; + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("carriers") + @Getter + @Setter + private List carriers; + + public static MessagingV2RcsComplianceCountryResponse fromJson( + String jsonString, + ObjectMapper mapper + ) throws IOException { + return mapper.readValue( + jsonString, + MessagingV2RcsComplianceCountryResponse.class + ); + } + } + + @ToString + public static class MessagingV2RcsComplianceResponse { + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("registration_sid") + @Getter + @Setter + private String registrationSid; + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("countries") + @Getter + @Setter + private List countries; + + public static MessagingV2RcsComplianceResponse fromJson( + String jsonString, + ObjectMapper mapper + ) throws IOException { + return mapper.readValue( + jsonString, + MessagingV2RcsComplianceResponse.class + ); + } + } + public static ChannelsSenderCreator creator( final ChannelsSender.MessagingV2ChannelsSenderRequestsCreate messagingV2ChannelsSenderRequestsCreate ) { @@ -524,11 +703,12 @@ public static String toJson(Object object, ObjectMapper mapper) { private final String senderId; private final MessagingV2ChannelsSenderConfiguration configuration; private final MessagingV2ChannelsSenderWebhook webhook; - private final MessagingV2ChannelsSenderProfileResponse profile; + private final MessagingV2ChannelsSenderProfileGenericResponse profile; private final MessagingV2ChannelsSenderProperties properties; private final List< MessagingV2ChannelsSenderOfflineReasonsItems > offlineReasons; + private final MessagingV2RcsComplianceResponse compliance; private final URI url; @JsonCreator @@ -542,13 +722,16 @@ private ChannelsSender( @JsonProperty("webhook") final MessagingV2ChannelsSenderWebhook webhook, @JsonProperty( "profile" - ) final MessagingV2ChannelsSenderProfileResponse profile, + ) final MessagingV2ChannelsSenderProfileGenericResponse profile, @JsonProperty( "properties" ) final MessagingV2ChannelsSenderProperties properties, @JsonProperty("offline_reasons") final List< MessagingV2ChannelsSenderOfflineReasonsItems > offlineReasons, + @JsonProperty( + "compliance" + ) final MessagingV2RcsComplianceResponse compliance, @JsonProperty("url") final URI url ) { this.sid = sid; @@ -559,6 +742,7 @@ private ChannelsSender( this.profile = profile; this.properties = properties; this.offlineReasons = offlineReasons; + this.compliance = compliance; this.url = url; } @@ -582,7 +766,7 @@ public final MessagingV2ChannelsSenderWebhook getWebhook() { return this.webhook; } - public final MessagingV2ChannelsSenderProfileResponse getProfile() { + public final MessagingV2ChannelsSenderProfileGenericResponse getProfile() { return this.profile; } @@ -596,6 +780,10 @@ > getOfflineReasons() { return this.offlineReasons; } + public final MessagingV2RcsComplianceResponse getCompliance() { + return this.compliance; + } + public final URI getUrl() { return this.url; } @@ -621,6 +809,7 @@ public boolean equals(final Object o) { Objects.equals(profile, other.profile) && Objects.equals(properties, other.properties) && Objects.equals(offlineReasons, other.offlineReasons) && + Objects.equals(compliance, other.compliance) && Objects.equals(url, other.url) ); } @@ -636,6 +825,7 @@ public int hashCode() { profile, properties, offlineReasons, + compliance, url ); } @@ -683,18 +873,15 @@ public static FallbackMethodEnum forValue(final String value) { } } - public enum Status { - CREATING("CREATING"), + public enum MessagingV2RcsCountryStatus { ONLINE("ONLINE"), OFFLINE("OFFLINE"), - PENDING_VERIFICATION("PENDING_VERIFICATION"), - VERIFYING("VERIFYING"), - ONLINE_UPDATING("ONLINE:UPDATING"), - STUBBED("STUBBED"); + TWILIO_REVIEW("TWILIO_REVIEW"), + PENDING_VERIFICATION("PENDING_VERIFICATION"); private final String value; - private Status(final String value) { + private MessagingV2RcsCountryStatus(final String value) { this.value = value; } @@ -703,8 +890,38 @@ public String toString() { } @JsonCreator - public static Status forValue(final String value) { - return Promoter.enumFromString(value, Status.values()); + public static MessagingV2RcsCountryStatus forValue(final String value) { + return Promoter.enumFromString( + value, + MessagingV2RcsCountryStatus.values() + ); + } + } + + public enum MessagingV2RcsCarrierStatus { + UNKNOWN("UNKNOWN"), + UNLAUNCHED("UNLAUNCHED"), + CARRIER_REVIEW("CARRIER_REVIEW"), + APPROVED("APPROVED"), + REJECTED("REJECTED"), + SUSPENDED("SUSPENDED"); + + private final String value; + + private MessagingV2RcsCarrierStatus(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static MessagingV2RcsCarrierStatus forValue(final String value) { + return Promoter.enumFromString( + value, + MessagingV2RcsCarrierStatus.values() + ); } } @@ -727,4 +944,30 @@ public static CallbackMethodEnum forValue(final String value) { return Promoter.enumFromString(value, CallbackMethodEnum.values()); } } + + public enum Status { + CREATING("CREATING"), + ONLINE("ONLINE"), + OFFLINE("OFFLINE"), + PENDING_VERIFICATION("PENDING_VERIFICATION"), + VERIFYING("VERIFYING"), + ONLINE_UPDATING("ONLINE:UPDATING"), + TWILIO_REVIEW("TWILIO_REVIEW"), + DRAFT("DRAFT"); + + private final String value; + + private Status(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static Status forValue(final String value) { + return Promoter.enumFromString(value, Status.values()); + } + } } diff --git a/src/main/java/com/twilio/rest/numbers/v1/PortingPortIn.java b/src/main/java/com/twilio/rest/numbers/v1/PortingPortIn.java index e399bb5b31..d3fc89c41a 100644 --- a/src/main/java/com/twilio/rest/numbers/v1/PortingPortIn.java +++ b/src/main/java/com/twilio/rest/numbers/v1/PortingPortIn.java @@ -41,7 +41,7 @@ @ToString public class PortingPortIn extends Resource { - private static final long serialVersionUID = 79710628855525L; + private static final long serialVersionUID = 109031413524724L; public static PortingPortInCreator creator() { return new PortingPortInCreator(); @@ -124,6 +124,9 @@ public static String toJson(Object object, ObjectMapper mapper) { private final String portInRequestStatus; private final Map losingCarrierInformation; private final List> phoneNumbers; + private final String bundleSid; + private final String portabilityAdvanceCarrier; + private final String autoCancelApprovalNumbers; private final List documents; private final ZonedDateTime dateCreated; @@ -152,6 +155,13 @@ private PortingPortIn( @JsonProperty("phone_numbers") final List< Map > phoneNumbers, + @JsonProperty("bundle_sid") final String bundleSid, + @JsonProperty( + "portability_advance_carrier" + ) final String portabilityAdvanceCarrier, + @JsonProperty( + "auto_cancel_approval_numbers" + ) final String autoCancelApprovalNumbers, @JsonProperty("documents") final List documents, @JsonProperty("date_created") final String dateCreated ) { @@ -166,6 +176,9 @@ private PortingPortIn( this.portInRequestStatus = portInRequestStatus; this.losingCarrierInformation = losingCarrierInformation; this.phoneNumbers = phoneNumbers; + this.bundleSid = bundleSid; + this.portabilityAdvanceCarrier = portabilityAdvanceCarrier; + this.autoCancelApprovalNumbers = autoCancelApprovalNumbers; this.documents = documents; this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); } @@ -210,6 +223,18 @@ public final List> getPhoneNumbers() { return this.phoneNumbers; } + public final String getBundleSid() { + return this.bundleSid; + } + + public final String getPortabilityAdvanceCarrier() { + return this.portabilityAdvanceCarrier; + } + + public final String getAutoCancelApprovalNumbers() { + return this.autoCancelApprovalNumbers; + } + public final List getDocuments() { return this.documents; } @@ -250,6 +275,15 @@ public boolean equals(final Object o) { other.losingCarrierInformation ) && Objects.equals(phoneNumbers, other.phoneNumbers) && + Objects.equals(bundleSid, other.bundleSid) && + Objects.equals( + portabilityAdvanceCarrier, + other.portabilityAdvanceCarrier + ) && + Objects.equals( + autoCancelApprovalNumbers, + other.autoCancelApprovalNumbers + ) && Objects.equals(documents, other.documents) && Objects.equals(dateCreated, other.dateCreated) ); @@ -268,6 +302,9 @@ public int hashCode() { portInRequestStatus, losingCarrierInformation, phoneNumbers, + bundleSid, + portabilityAdvanceCarrier, + autoCancelApprovalNumbers, documents, dateCreated ); diff --git a/src/main/java/com/twilio/rest/verify/v2/Service.java b/src/main/java/com/twilio/rest/verify/v2/Service.java index 627024b453..2692351b04 100644 --- a/src/main/java/com/twilio/rest/verify/v2/Service.java +++ b/src/main/java/com/twilio/rest/verify/v2/Service.java @@ -38,7 +38,7 @@ @ToString public class Service extends Resource { - private static final long serialVersionUID = 122585755386681L; + private static final long serialVersionUID = 189237551129366L; public static ServiceCreator creator(final String friendlyName) { return new ServiceCreator(friendlyName); @@ -118,6 +118,7 @@ public static Service fromJson( private final Map totp; private final String defaultTemplateSid; private final Map whatsapp; + private final Map passkeys; private final Boolean verifyEventSubscriptionEnabled; private final ZonedDateTime dateCreated; private final ZonedDateTime dateUpdated; @@ -143,6 +144,7 @@ private Service( @JsonProperty("totp") final Map totp, @JsonProperty("default_template_sid") final String defaultTemplateSid, @JsonProperty("whatsapp") final Map whatsapp, + @JsonProperty("passkeys") final Map passkeys, @JsonProperty( "verify_event_subscription_enabled" ) final Boolean verifyEventSubscriptionEnabled, @@ -166,6 +168,7 @@ private Service( this.totp = totp; this.defaultTemplateSid = defaultTemplateSid; this.whatsapp = whatsapp; + this.passkeys = passkeys; this.verifyEventSubscriptionEnabled = verifyEventSubscriptionEnabled; this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); @@ -233,6 +236,10 @@ public final Map getWhatsapp() { return this.whatsapp; } + public final Map getPasskeys() { + return this.passkeys; + } + public final Boolean getVerifyEventSubscriptionEnabled() { return this.verifyEventSubscriptionEnabled; } @@ -284,6 +291,7 @@ public boolean equals(final Object o) { Objects.equals(totp, other.totp) && Objects.equals(defaultTemplateSid, other.defaultTemplateSid) && Objects.equals(whatsapp, other.whatsapp) && + Objects.equals(passkeys, other.passkeys) && Objects.equals( verifyEventSubscriptionEnabled, other.verifyEventSubscriptionEnabled @@ -313,6 +321,7 @@ public int hashCode() { totp, defaultTemplateSid, whatsapp, + passkeys, verifyEventSubscriptionEnabled, dateCreated, dateUpdated, diff --git a/src/main/java/com/twilio/rest/verify/v2/ServiceCreator.java b/src/main/java/com/twilio/rest/verify/v2/ServiceCreator.java index b96a1a983a..ae9ed50518 100644 --- a/src/main/java/com/twilio/rest/verify/v2/ServiceCreator.java +++ b/src/main/java/com/twilio/rest/verify/v2/ServiceCreator.java @@ -46,6 +46,12 @@ public class ServiceCreator extends Creator { private String defaultTemplateSid; private String whatsappMsgServiceSid; private String whatsappFrom; + private String passkeysRelyingPartyId; + private String passkeysRelyingPartyName; + private String passkeysRelyingPartyOrigins; + private String passkeysAuthenticatorAttachment; + private String passkeysDiscoverableCredentials; + private String passkeysUserVerification; private Boolean verifyEventSubscriptionEnabled; public ServiceCreator(final String friendlyName) { @@ -163,6 +169,48 @@ public ServiceCreator setWhatsappFrom(final String whatsappFrom) { return this; } + public ServiceCreator setPasskeysRelyingPartyId( + final String passkeysRelyingPartyId + ) { + this.passkeysRelyingPartyId = passkeysRelyingPartyId; + return this; + } + + public ServiceCreator setPasskeysRelyingPartyName( + final String passkeysRelyingPartyName + ) { + this.passkeysRelyingPartyName = passkeysRelyingPartyName; + return this; + } + + public ServiceCreator setPasskeysRelyingPartyOrigins( + final String passkeysRelyingPartyOrigins + ) { + this.passkeysRelyingPartyOrigins = passkeysRelyingPartyOrigins; + return this; + } + + public ServiceCreator setPasskeysAuthenticatorAttachment( + final String passkeysAuthenticatorAttachment + ) { + this.passkeysAuthenticatorAttachment = passkeysAuthenticatorAttachment; + return this; + } + + public ServiceCreator setPasskeysDiscoverableCredentials( + final String passkeysDiscoverableCredentials + ) { + this.passkeysDiscoverableCredentials = passkeysDiscoverableCredentials; + return this; + } + + public ServiceCreator setPasskeysUserVerification( + final String passkeysUserVerification + ) { + this.passkeysUserVerification = passkeysUserVerification; + return this; + } + public ServiceCreator setVerifyEventSubscriptionEnabled( final Boolean verifyEventSubscriptionEnabled ) { @@ -285,6 +333,42 @@ private void addPostParams(final Request request) { if (whatsappFrom != null) { request.addPostParam("Whatsapp.From", whatsappFrom); } + if (passkeysRelyingPartyId != null) { + request.addPostParam( + "Passkeys.RelyingParty.Id", + passkeysRelyingPartyId + ); + } + if (passkeysRelyingPartyName != null) { + request.addPostParam( + "Passkeys.RelyingParty.Name", + passkeysRelyingPartyName + ); + } + if (passkeysRelyingPartyOrigins != null) { + request.addPostParam( + "Passkeys.RelyingParty.Origins", + passkeysRelyingPartyOrigins + ); + } + if (passkeysAuthenticatorAttachment != null) { + request.addPostParam( + "Passkeys.AuthenticatorAttachment", + passkeysAuthenticatorAttachment + ); + } + if (passkeysDiscoverableCredentials != null) { + request.addPostParam( + "Passkeys.DiscoverableCredentials", + passkeysDiscoverableCredentials + ); + } + if (passkeysUserVerification != null) { + request.addPostParam( + "Passkeys.UserVerification", + passkeysUserVerification + ); + } if (verifyEventSubscriptionEnabled != null) { request.addPostParam( "VerifyEventSubscriptionEnabled", diff --git a/src/main/java/com/twilio/rest/verify/v2/ServiceUpdater.java b/src/main/java/com/twilio/rest/verify/v2/ServiceUpdater.java index 87ffcc6601..ead69bb250 100644 --- a/src/main/java/com/twilio/rest/verify/v2/ServiceUpdater.java +++ b/src/main/java/com/twilio/rest/verify/v2/ServiceUpdater.java @@ -47,6 +47,9 @@ public class ServiceUpdater extends Updater { private String defaultTemplateSid; private String whatsappMsgServiceSid; private String whatsappFrom; + private String passkeysRelyingPartyId; + private String passkeysRelyingPartyName; + private String passkeysRelyingPartyOrigins; private Boolean verifyEventSubscriptionEnabled; public ServiceUpdater(final String pathSid) { @@ -164,6 +167,27 @@ public ServiceUpdater setWhatsappFrom(final String whatsappFrom) { return this; } + public ServiceUpdater setPasskeysRelyingPartyId( + final String passkeysRelyingPartyId + ) { + this.passkeysRelyingPartyId = passkeysRelyingPartyId; + return this; + } + + public ServiceUpdater setPasskeysRelyingPartyName( + final String passkeysRelyingPartyName + ) { + this.passkeysRelyingPartyName = passkeysRelyingPartyName; + return this; + } + + public ServiceUpdater setPasskeysRelyingPartyOrigins( + final String passkeysRelyingPartyOrigins + ) { + this.passkeysRelyingPartyOrigins = passkeysRelyingPartyOrigins; + return this; + } + public ServiceUpdater setVerifyEventSubscriptionEnabled( final Boolean verifyEventSubscriptionEnabled ) { @@ -282,6 +306,24 @@ private void addPostParams(final Request request) { if (whatsappFrom != null) { request.addPostParam("Whatsapp.From", whatsappFrom); } + if (passkeysRelyingPartyId != null) { + request.addPostParam( + "Passkeys.RelyingParty.Id", + passkeysRelyingPartyId + ); + } + if (passkeysRelyingPartyName != null) { + request.addPostParam( + "Passkeys.RelyingParty.Name", + passkeysRelyingPartyName + ); + } + if (passkeysRelyingPartyOrigins != null) { + request.addPostParam( + "Passkeys.RelyingParty.Origins", + passkeysRelyingPartyOrigins + ); + } if (verifyEventSubscriptionEnabled != null) { request.addPostParam( "VerifyEventSubscriptionEnabled", diff --git a/src/main/java/com/twilio/rest/verify/v2/service/entity/Challenge.java b/src/main/java/com/twilio/rest/verify/v2/service/entity/Challenge.java index 0d62df7622..56940c3fa7 100644 --- a/src/main/java/com/twilio/rest/verify/v2/service/entity/Challenge.java +++ b/src/main/java/com/twilio/rest/verify/v2/service/entity/Challenge.java @@ -350,15 +350,14 @@ public static ListOrders forValue(final String value) { } } - public enum ChallengeStatuses { - PENDING("pending"), - EXPIRED("expired"), - APPROVED("approved"), - DENIED("denied"); + public enum FactorTypes { + PUSH("push"), + TOTP("totp"), + PASSKEYS("passkeys"); private final String value; - private ChallengeStatuses(final String value) { + private FactorTypes(final String value) { this.value = value; } @@ -367,18 +366,20 @@ public String toString() { } @JsonCreator - public static ChallengeStatuses forValue(final String value) { - return Promoter.enumFromString(value, ChallengeStatuses.values()); + public static FactorTypes forValue(final String value) { + return Promoter.enumFromString(value, FactorTypes.values()); } } - public enum FactorTypes { - PUSH("push"), - TOTP("totp"); + public enum ChallengeStatuses { + PENDING("pending"), + EXPIRED("expired"), + APPROVED("approved"), + DENIED("denied"); private final String value; - private FactorTypes(final String value) { + private ChallengeStatuses(final String value) { this.value = value; } @@ -387,8 +388,8 @@ public String toString() { } @JsonCreator - public static FactorTypes forValue(final String value) { - return Promoter.enumFromString(value, FactorTypes.values()); + public static ChallengeStatuses forValue(final String value) { + return Promoter.enumFromString(value, ChallengeStatuses.values()); } } } diff --git a/src/main/java/com/twilio/rest/verify/v2/service/entity/Factor.java b/src/main/java/com/twilio/rest/verify/v2/service/entity/Factor.java index edeafe8f4e..0cf56cea25 100644 --- a/src/main/java/com/twilio/rest/verify/v2/service/entity/Factor.java +++ b/src/main/java/com/twilio/rest/verify/v2/service/entity/Factor.java @@ -262,7 +262,8 @@ public int hashCode() { public enum FactorTypes { PUSH("push"), - TOTP("totp"); + TOTP("totp"), + PASSKEYS("passkeys"); private final String value; diff --git a/src/main/java/com/twilio/rest/verify/v2/service/entity/NewFactor.java b/src/main/java/com/twilio/rest/verify/v2/service/entity/NewFactor.java index 308d23c721..a8677d589d 100644 --- a/src/main/java/com/twilio/rest/verify/v2/service/entity/NewFactor.java +++ b/src/main/java/com/twilio/rest/verify/v2/service/entity/NewFactor.java @@ -39,7 +39,7 @@ @ToString public class NewFactor extends Resource { - private static final long serialVersionUID = 115808224888150L; + private static final long serialVersionUID = 255981174125852L; public static NewFactorCreator creator( final String pathServiceSid, @@ -104,6 +104,7 @@ public static NewFactor fromJson( private final String entitySid; private final String identity; private final Map binding; + private final Map options; private final ZonedDateTime dateCreated; private final ZonedDateTime dateUpdated; private final String friendlyName; @@ -121,6 +122,7 @@ private NewFactor( @JsonProperty("entity_sid") final String entitySid, @JsonProperty("identity") final String identity, @JsonProperty("binding") final Map binding, + @JsonProperty("options") final Map options, @JsonProperty("date_created") final String dateCreated, @JsonProperty("date_updated") final String dateUpdated, @JsonProperty("friendly_name") final String friendlyName, @@ -136,6 +138,7 @@ private NewFactor( this.entitySid = entitySid; this.identity = identity; this.binding = binding; + this.options = options; this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); this.friendlyName = friendlyName; @@ -170,6 +173,10 @@ public final Map getBinding() { return this.binding; } + public final Map getOptions() { + return this.options; + } + public final ZonedDateTime getDateCreated() { return this.dateCreated; } @@ -221,6 +228,7 @@ public boolean equals(final Object o) { Objects.equals(entitySid, other.entitySid) && Objects.equals(identity, other.identity) && Objects.equals(binding, other.binding) && + Objects.equals(options, other.options) && Objects.equals(dateCreated, other.dateCreated) && Objects.equals(dateUpdated, other.dateUpdated) && Objects.equals(friendlyName, other.friendlyName) && @@ -241,6 +249,7 @@ public int hashCode() { entitySid, identity, binding, + options, dateCreated, dateUpdated, friendlyName, @@ -252,26 +261,6 @@ public int hashCode() { ); } - public enum FactorTypes { - PUSH("push"), - TOTP("totp"); - - private final String value; - - private FactorTypes(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static FactorTypes forValue(final String value) { - return Promoter.enumFromString(value, FactorTypes.values()); - } - } - public enum FactorStatuses { UNVERIFIED("unverified"), VERIFIED("verified"); @@ -336,4 +325,25 @@ public static NotificationPlatforms forValue(final String value) { ); } } + + public enum FactorTypes { + PUSH("push"), + TOTP("totp"), + PASSKEYS("passkeys"); + + private final String value; + + private FactorTypes(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static FactorTypes forValue(final String value) { + return Promoter.enumFromString(value, FactorTypes.values()); + } + } } From 54629b05791d9d12f6b798d3280015c5136d8f6b Mon Sep 17 00:00:00 2001 From: Twilio Date: Mon, 18 Aug 2025 09:02:48 +0000 Subject: [PATCH 11/32] Release 11.0.0-rc.4 --- pom.xml | 4 ++-- src/main/java/com/twilio/Twilio.java | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/pom.xml b/pom.xml index 317961afc9..7daf3ba941 100644 --- a/pom.xml +++ b/pom.xml @@ -5,7 +5,7 @@ twilio jar twilio - 11.0.0-rc.3 + 11.0.0-rc.4 Twilio Java Helper Library https://www.twilio.com @@ -19,7 +19,7 @@ git@github.com:twilio/twilio-java.git scm:git:git@github.com:twilio/twilio-java.git scm:git:git@github.com:twilio/twilio-java.git - 11.0.0-rc.3 + 11.0.0-rc.4 diff --git a/src/main/java/com/twilio/Twilio.java b/src/main/java/com/twilio/Twilio.java index 3e33c76558..7c1906790b 100644 --- a/src/main/java/com/twilio/Twilio.java +++ b/src/main/java/com/twilio/Twilio.java @@ -24,7 +24,7 @@ */ public class Twilio { - public static final String VERSION = "11.0.0-rc.3"; + public static final String VERSION = "11.0.0-rc.4"; public static final String JAVA_VERSION = System.getProperty("java.version"); public static final String OS_NAME = System.getProperty("os.name"); public static final String OS_ARCH = System.getProperty("os.arch"); From 4d0f1fa8034d2b911c532ec99d87912a2c5d9abe Mon Sep 17 00:00:00 2001 From: Twilio Date: Thu, 28 Aug 2025 11:44:00 +0000 Subject: [PATCH 12/32] [Librarian] Regenerated @ 741a326a48cb7081b6b7e1de11dfd3e942a09979 c69f995414b3de49d803f8cacdc0944ab8fb62ed --- CHANGES.md | 9 ++++ .../rest/studio/v1/flow/engagement/Step.java | 11 ++++- .../v1/flow/execution/ExecutionStep.java | 11 ++++- .../v2/flow/execution/ExecutionStep.java | 11 ++++- .../twilio/rest/verify/v2/ServiceUpdater.java | 42 +++++++++++++++++++ 5 files changed, 81 insertions(+), 3 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index d6ee45cb2e..f8fa340f45 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,6 +1,15 @@ twilio-java changelog ===================== +[2025-08-28] Version 11.0.0-rc.5 +-------------------------------- +**Studio** +- Add `type` to Step resource APIs + +**Verify** +- Allow to update all passkeys parameters in the service update + + [2025-08-18] Version 11.0.0-rc.4 -------------------------------- **Accounts** diff --git a/src/main/java/com/twilio/rest/studio/v1/flow/engagement/Step.java b/src/main/java/com/twilio/rest/studio/v1/flow/engagement/Step.java index a0b2dcbf54..6420719f71 100644 --- a/src/main/java/com/twilio/rest/studio/v1/flow/engagement/Step.java +++ b/src/main/java/com/twilio/rest/studio/v1/flow/engagement/Step.java @@ -38,7 +38,7 @@ @ToString public class Step extends Resource { - private static final long serialVersionUID = 84557375462184L; + private static final long serialVersionUID = 119488428044573L; public static StepFetcher fetcher( final String pathFlowSid, @@ -107,6 +107,7 @@ public static Step fromJson( private final String parentStepSid; private final String transitionedFrom; private final String transitionedTo; + private final String type; private final ZonedDateTime dateCreated; private final ZonedDateTime dateUpdated; private final URI url; @@ -123,6 +124,7 @@ private Step( @JsonProperty("parent_step_sid") final String parentStepSid, @JsonProperty("transitioned_from") final String transitionedFrom, @JsonProperty("transitioned_to") final String transitionedTo, + @JsonProperty("type") final String type, @JsonProperty("date_created") final String dateCreated, @JsonProperty("date_updated") final String dateUpdated, @JsonProperty("url") final URI url, @@ -137,6 +139,7 @@ private Step( this.parentStepSid = parentStepSid; this.transitionedFrom = transitionedFrom; this.transitionedTo = transitionedTo; + this.type = type; this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); this.url = url; @@ -179,6 +182,10 @@ public final String getTransitionedTo() { return this.transitionedTo; } + public final String getType() { + return this.type; + } + public final ZonedDateTime getDateCreated() { return this.dateCreated; } @@ -217,6 +224,7 @@ public boolean equals(final Object o) { Objects.equals(parentStepSid, other.parentStepSid) && Objects.equals(transitionedFrom, other.transitionedFrom) && Objects.equals(transitionedTo, other.transitionedTo) && + Objects.equals(type, other.type) && Objects.equals(dateCreated, other.dateCreated) && Objects.equals(dateUpdated, other.dateUpdated) && Objects.equals(url, other.url) && @@ -236,6 +244,7 @@ public int hashCode() { parentStepSid, transitionedFrom, transitionedTo, + type, dateCreated, dateUpdated, url, diff --git a/src/main/java/com/twilio/rest/studio/v1/flow/execution/ExecutionStep.java b/src/main/java/com/twilio/rest/studio/v1/flow/execution/ExecutionStep.java index 198f6d6067..3666d1e5b5 100644 --- a/src/main/java/com/twilio/rest/studio/v1/flow/execution/ExecutionStep.java +++ b/src/main/java/com/twilio/rest/studio/v1/flow/execution/ExecutionStep.java @@ -38,7 +38,7 @@ @ToString public class ExecutionStep extends Resource { - private static final long serialVersionUID = 56382327963536L; + private static final long serialVersionUID = 221887175359099L; public static ExecutionStepFetcher fetcher( final String pathFlowSid, @@ -107,6 +107,7 @@ public static ExecutionStep fromJson( private final Map context; private final String transitionedFrom; private final String transitionedTo; + private final String type; private final ZonedDateTime dateCreated; private final ZonedDateTime dateUpdated; private final URI url; @@ -123,6 +124,7 @@ private ExecutionStep( @JsonProperty("context") final Map context, @JsonProperty("transitioned_from") final String transitionedFrom, @JsonProperty("transitioned_to") final String transitionedTo, + @JsonProperty("type") final String type, @JsonProperty("date_created") final String dateCreated, @JsonProperty("date_updated") final String dateUpdated, @JsonProperty("url") final URI url, @@ -137,6 +139,7 @@ private ExecutionStep( this.context = context; this.transitionedFrom = transitionedFrom; this.transitionedTo = transitionedTo; + this.type = type; this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); this.url = url; @@ -179,6 +182,10 @@ public final String getTransitionedTo() { return this.transitionedTo; } + public final String getType() { + return this.type; + } + public final ZonedDateTime getDateCreated() { return this.dateCreated; } @@ -217,6 +224,7 @@ public boolean equals(final Object o) { Objects.equals(context, other.context) && Objects.equals(transitionedFrom, other.transitionedFrom) && Objects.equals(transitionedTo, other.transitionedTo) && + Objects.equals(type, other.type) && Objects.equals(dateCreated, other.dateCreated) && Objects.equals(dateUpdated, other.dateUpdated) && Objects.equals(url, other.url) && @@ -236,6 +244,7 @@ public int hashCode() { context, transitionedFrom, transitionedTo, + type, dateCreated, dateUpdated, url, diff --git a/src/main/java/com/twilio/rest/studio/v2/flow/execution/ExecutionStep.java b/src/main/java/com/twilio/rest/studio/v2/flow/execution/ExecutionStep.java index c6d8c0acce..48c1ebd0de 100644 --- a/src/main/java/com/twilio/rest/studio/v2/flow/execution/ExecutionStep.java +++ b/src/main/java/com/twilio/rest/studio/v2/flow/execution/ExecutionStep.java @@ -38,7 +38,7 @@ @ToString public class ExecutionStep extends Resource { - private static final long serialVersionUID = 56382327963536L; + private static final long serialVersionUID = 221887175359099L; public static ExecutionStepFetcher fetcher( final String pathFlowSid, @@ -107,6 +107,7 @@ public static ExecutionStep fromJson( private final Map context; private final String transitionedFrom; private final String transitionedTo; + private final String type; private final ZonedDateTime dateCreated; private final ZonedDateTime dateUpdated; private final URI url; @@ -123,6 +124,7 @@ private ExecutionStep( @JsonProperty("context") final Map context, @JsonProperty("transitioned_from") final String transitionedFrom, @JsonProperty("transitioned_to") final String transitionedTo, + @JsonProperty("type") final String type, @JsonProperty("date_created") final String dateCreated, @JsonProperty("date_updated") final String dateUpdated, @JsonProperty("url") final URI url, @@ -137,6 +139,7 @@ private ExecutionStep( this.context = context; this.transitionedFrom = transitionedFrom; this.transitionedTo = transitionedTo; + this.type = type; this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); this.url = url; @@ -179,6 +182,10 @@ public final String getTransitionedTo() { return this.transitionedTo; } + public final String getType() { + return this.type; + } + public final ZonedDateTime getDateCreated() { return this.dateCreated; } @@ -217,6 +224,7 @@ public boolean equals(final Object o) { Objects.equals(context, other.context) && Objects.equals(transitionedFrom, other.transitionedFrom) && Objects.equals(transitionedTo, other.transitionedTo) && + Objects.equals(type, other.type) && Objects.equals(dateCreated, other.dateCreated) && Objects.equals(dateUpdated, other.dateUpdated) && Objects.equals(url, other.url) && @@ -236,6 +244,7 @@ public int hashCode() { context, transitionedFrom, transitionedTo, + type, dateCreated, dateUpdated, url, diff --git a/src/main/java/com/twilio/rest/verify/v2/ServiceUpdater.java b/src/main/java/com/twilio/rest/verify/v2/ServiceUpdater.java index ead69bb250..52469c145f 100644 --- a/src/main/java/com/twilio/rest/verify/v2/ServiceUpdater.java +++ b/src/main/java/com/twilio/rest/verify/v2/ServiceUpdater.java @@ -50,6 +50,9 @@ public class ServiceUpdater extends Updater { private String passkeysRelyingPartyId; private String passkeysRelyingPartyName; private String passkeysRelyingPartyOrigins; + private String passkeysAuthenticatorAttachment; + private String passkeysDiscoverableCredentials; + private String passkeysUserVerification; private Boolean verifyEventSubscriptionEnabled; public ServiceUpdater(final String pathSid) { @@ -188,6 +191,27 @@ public ServiceUpdater setPasskeysRelyingPartyOrigins( return this; } + public ServiceUpdater setPasskeysAuthenticatorAttachment( + final String passkeysAuthenticatorAttachment + ) { + this.passkeysAuthenticatorAttachment = passkeysAuthenticatorAttachment; + return this; + } + + public ServiceUpdater setPasskeysDiscoverableCredentials( + final String passkeysDiscoverableCredentials + ) { + this.passkeysDiscoverableCredentials = passkeysDiscoverableCredentials; + return this; + } + + public ServiceUpdater setPasskeysUserVerification( + final String passkeysUserVerification + ) { + this.passkeysUserVerification = passkeysUserVerification; + return this; + } + public ServiceUpdater setVerifyEventSubscriptionEnabled( final Boolean verifyEventSubscriptionEnabled ) { @@ -324,6 +348,24 @@ private void addPostParams(final Request request) { passkeysRelyingPartyOrigins ); } + if (passkeysAuthenticatorAttachment != null) { + request.addPostParam( + "Passkeys.AuthenticatorAttachment", + passkeysAuthenticatorAttachment + ); + } + if (passkeysDiscoverableCredentials != null) { + request.addPostParam( + "Passkeys.DiscoverableCredentials", + passkeysDiscoverableCredentials + ); + } + if (passkeysUserVerification != null) { + request.addPostParam( + "Passkeys.UserVerification", + passkeysUserVerification + ); + } if (verifyEventSubscriptionEnabled != null) { request.addPostParam( "VerifyEventSubscriptionEnabled", From 2b01bb6af359cf4b3ecbc9a714d437e5b6aecccc Mon Sep 17 00:00:00 2001 From: Twilio Date: Thu, 28 Aug 2025 11:47:05 +0000 Subject: [PATCH 13/32] Release 11.0.0-rc.5 --- pom.xml | 4 ++-- src/main/java/com/twilio/Twilio.java | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/pom.xml b/pom.xml index 7daf3ba941..4f3efcd667 100644 --- a/pom.xml +++ b/pom.xml @@ -5,7 +5,7 @@ twilio jar twilio - 11.0.0-rc.4 + 11.0.0-rc.5 Twilio Java Helper Library https://www.twilio.com @@ -19,7 +19,7 @@ git@github.com:twilio/twilio-java.git scm:git:git@github.com:twilio/twilio-java.git scm:git:git@github.com:twilio/twilio-java.git - 11.0.0-rc.4 + 11.0.0-rc.5 diff --git a/src/main/java/com/twilio/Twilio.java b/src/main/java/com/twilio/Twilio.java index 7c1906790b..cd504549e2 100644 --- a/src/main/java/com/twilio/Twilio.java +++ b/src/main/java/com/twilio/Twilio.java @@ -24,7 +24,7 @@ */ public class Twilio { - public static final String VERSION = "11.0.0-rc.4"; + public static final String VERSION = "11.0.0-rc.5"; public static final String JAVA_VERSION = System.getProperty("java.version"); public static final String OS_NAME = System.getProperty("os.name"); public static final String OS_ARCH = System.getProperty("os.arch"); From ce29d45cd38d439c65de7cfc2fb5e77e08f3cc6d Mon Sep 17 00:00:00 2001 From: Twilio Date: Thu, 4 Sep 2025 10:08:01 +0000 Subject: [PATCH 14/32] [Librarian] Regenerated @ 42495c0486390f490dfedfd73999e2c259cdb011 f32b4455cbef0bc9ef11a79ab2b3046e1bab7a61 --- CHANGES.md | 6 + .../rest/api/v2010/account/usage/Record.java | 950 +---------------- .../api/v2010/account/usage/RecordReader.java | 6 +- .../rest/api/v2010/account/usage/Trigger.java | 955 +----------------- .../v2010/account/usage/TriggerCreator.java | 12 +- .../v2010/account/usage/TriggerReader.java | 8 +- .../v2010/account/usage/record/AllTime.java | 950 +---------------- .../account/usage/record/AllTimeReader.java | 6 +- .../api/v2010/account/usage/record/Daily.java | 950 +---------------- .../account/usage/record/DailyReader.java | 6 +- .../v2010/account/usage/record/LastMonth.java | 950 +---------------- .../account/usage/record/LastMonthReader.java | 6 +- .../v2010/account/usage/record/Monthly.java | 950 +---------------- .../account/usage/record/MonthlyReader.java | 6 +- .../v2010/account/usage/record/ThisMonth.java | 950 +---------------- .../account/usage/record/ThisMonthReader.java | 6 +- .../api/v2010/account/usage/record/Today.java | 950 +---------------- .../account/usage/record/TodayReader.java | 6 +- .../v2010/account/usage/record/Yearly.java | 950 +---------------- .../account/usage/record/YearlyReader.java | 6 +- .../v2010/account/usage/record/Yesterday.java | 950 +---------------- .../account/usage/record/YesterdayReader.java | 6 +- .../com/twilio/rest/content/v1/Content.java | 28 + .../com/twilio/rest/insights/v1/Room.java | 14 +- .../rest/insights/v1/room/Participant.java | 56 +- .../rest/messaging/v2/ChannelsSender.java | 84 +- 26 files changed, 176 insertions(+), 9591 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index f8fa340f45..70ff8c0dd9 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,6 +1,12 @@ twilio-java changelog ===================== +[2025-09-04] Version 11.0.0-rc.6 +-------------------------------- +**Api** +- Remove usage category enum from usage record and usage triggers API **(breaking change)** + + [2025-08-28] Version 11.0.0-rc.5 -------------------------------- **Studio** diff --git a/src/main/java/com/twilio/rest/api/v2010/account/usage/Record.java b/src/main/java/com/twilio/rest/api/v2010/account/usage/Record.java index ec3633b60c..26d3c3d8bf 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/usage/Record.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/usage/Record.java @@ -24,7 +24,6 @@ import com.twilio.base.Resource; import com.twilio.converter.CurrencyDeserializer; import com.twilio.converter.DateConverter; -import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import java.io.IOException; @@ -42,7 +41,7 @@ @ToString public class Record extends Resource { - private static final long serialVersionUID = 267972709897131L; + private static final long serialVersionUID = 158026917970511L; public static RecordReader reader() { return new RecordReader(); @@ -98,7 +97,7 @@ public static Record fromJson( private final String accountSid; private final String apiVersion; private final String asOf; - private final Record.Category category; + private final String category; private final String count; private final String countUnit; private final String description; @@ -116,7 +115,7 @@ private Record( @JsonProperty("account_sid") final String accountSid, @JsonProperty("api_version") final String apiVersion, @JsonProperty("as_of") final String asOf, - @JsonProperty("category") final Record.Category category, + @JsonProperty("category") final String category, @JsonProperty("count") final String count, @JsonProperty("count_unit") final String countUnit, @JsonProperty("description") final String description, @@ -163,7 +162,7 @@ public final String getAsOf() { return this.asOf; } - public final Record.Category getCategory() { + public final String getCategory() { return this.category; } @@ -262,945 +261,4 @@ public int hashCode() { usageUnit ); } - - public enum Category { - A2P_10DLC_REGISTRATIONFEES_BRANDREGISTRATION( - "a2p-10dlc-registrationfees-brandregistration" - ), - A2P_10DLC_REGISTRATIONFEES_BV("a2p-10dlc-registrationfees-bv"), - A2P_10DLC_REGISTRATIONFEES_CAMPAIGNCHARGES( - "a2p-10dlc-registrationfees-campaigncharges" - ), - A2P_10DLC_REGISTRATIONFEES_CAMPAIGNREGISTRATION( - "a2p-10dlc-registrationfees-campaignregistration" - ), - A2P_10DLC_REGISTRATIONFEES_CAMPAIGNVETTING( - "a2p-10dlc-registrationfees-campaignvetting" - ), - A2P_10DLC_REGISTRATIONFEES_MONTHLY( - "a2p-10dlc-registrationfees-monthly" - ), - A2P_10DLC_REGISTRATIONFEES_ONETIME( - "a2p-10dlc-registrationfees-onetime" - ), - A2P_REGISTRATION_FEES("a2p-registration-fees"), - ACCOUNT_SECURITY("account-security"), - AGENT_CONFERENCE("agent-conference"), - AGENT_COPILOT("agent-copilot"), - AGENT_COPILOT_MESSAGES("agent-copilot-messages"), - AGENT_COPILOT_PARTICIPANT_MINUTES("agent-copilot-participant-minutes"), - AI_ASSISTANTS("ai-assistants"), - AI_ASSISTANTS_VOICE("ai-assistants-voice"), - AMAZON_POLLY("amazon-polly"), - ANSWERING_MACHINE_DETECTION("answering-machine-detection"), - ASSETS("assets"), - AUDIENCE_MINUTES("audience-minutes"), - AUDIENCE_MINUTES_AUDIO("audience-minutes-audio"), - AUTHY_AUTHENTICATIONS("authy-authentications"), - AUTHY_CALLS_OUTBOUND("authy-calls-outbound"), - AUTHY_EMAIL_AUTHENTICATIONS("authy-email-authentications"), - AUTHY_MONTHLY_FEES("authy-monthly-fees"), - AUTHY_OUTBOUND_EMAIL("authy-outbound-email"), - AUTHY_PHONE_INTELLIGENCE("authy-phone-intelligence"), - AUTHY_PHONE_VERIFICATIONS("authy-phone-verifications"), - AUTHY_SMS_OUTBOUND("authy-sms-outbound"), - AUTHY_VERIFY_EMAIL_VERIFICATIONS("authy-verify-email-verifications"), - AUTHY_VERIFY_OUTBOUND_EMAIL("authy-verify-outbound-email"), - AUTOPILOT("autopilot"), - AUTOPILOT_HOME_ASSISTANTS("autopilot-home-assistants"), - AUTOPILOT_MESSAGING("autopilot-messaging"), - AUTOPILOT_OTHER("autopilot-other"), - AUTOPILOT_VOICE("autopilot-voice"), - BASIC_PEER_TO_PEER_ROOMS_PARTICIPANT_MINUTES( - "basic-peer-to-peer-rooms-participant-minutes" - ), - BRANDED_CALLING("branded-calling"), - BUNDLE_SMS_BUCKET("bundle-sms-bucket"), - BUNDLE_SUBSCRIPTION_FEES("bundle-subscription-fees"), - CALL_FORWARDING_LOOKUPS("call-forwarding-lookups"), - CALL_PROGESS_EVENTS("call-progess-events"), - CALLERIDLOOKUPS("calleridlookups"), - CALLS("calls"), - CALLS_CLIENT("calls-client"), - CALLS_EMERGENCY("calls-emergency"), - CALLS_GLOBALCONFERENCE("calls-globalconference"), - CALLS_INBOUND("calls-inbound"), - CALLS_INBOUND_LOCAL("calls-inbound-local"), - CALLS_INBOUND_MOBILE("calls-inbound-mobile"), - CALLS_INBOUND_TOLLFREE("calls-inbound-tollfree"), - CALLS_INBOUND_TOLLFREE_LOCAL("calls-inbound-tollfree-local"), - CALLS_INBOUND_TOLLFREE_MOBILE("calls-inbound-tollfree-mobile"), - CALLS_MEDIA_STREAM_MINUTES("calls-media-stream-minutes"), - CALLS_OUTBOUND("calls-outbound"), - CALLS_PAY_VERB_TRANSACTIONS("calls-pay-verb-transactions"), - CALLS_RECORDINGS("calls-recordings"), - CALLS_SIP("calls-sip"), - CALLS_SIP_INBOUND("calls-sip-inbound"), - CALLS_SIP_OUTBOUND("calls-sip-outbound"), - CALLS_TEXT_TO_SPEECH("calls-text-to-speech"), - CALLS_TRANSFERS("calls-transfers"), - CARRIER_LOOKUPS("carrier-lookups"), - CATEGORY("category"), - CHANNELS("channels"), - CHANNELS_MESSAGING("channels-messaging"), - CHANNELS_MESSAGING_INBOUND("channels-messaging-inbound"), - CHANNELS_MESSAGING_OUTBOUND("channels-messaging-outbound"), - CHANNELS_WHATSAPP("channels-whatsapp"), - CHANNELS_WHATSAPP_CONVERSATION_AUTHENTICATION( - "channels-whatsapp-conversation-authentication" - ), - CHANNELS_WHATSAPP_CONVERSATION_FREE( - "channels-whatsapp-conversation-free" - ), - CHANNELS_WHATSAPP_CONVERSATION_MARKETING( - "channels-whatsapp-conversation-marketing" - ), - CHANNELS_WHATSAPP_CONVERSATION_SERVICE( - "channels-whatsapp-conversation-service" - ), - CHANNELS_WHATSAPP_CONVERSATION_UTILITY( - "channels-whatsapp-conversation-utility" - ), - CHANNELS_WHATSAPP_INBOUND("channels-whatsapp-inbound"), - CHANNELS_WHATSAPP_OUTBOUND("channels-whatsapp-outbound"), - CHANNELS_WHATSAPP_SERVICE("channels-whatsapp-service"), - CHANNELS_WHATSAPP_TEMPLATE_AUTHENTICATION( - "channels-whatsapp-template-authentication" - ), - CHANNELS_WHATSAPP_TEMPLATE_MARKETING( - "channels-whatsapp-template-marketing" - ), - CHANNELS_WHATSAPP_TEMPLATE_SERVICE( - "channels-whatsapp-template-service" - ), - CHANNELS_WHATSAPP_TEMPLATE_UTILITY( - "channels-whatsapp-template-utility" - ), - CHAT_VIRTUAL_AGENT("chat-virtual-agent"), - CONVERSATION_RELAY("conversation-relay"), - CONVERSATIONS("conversations"), - CONVERSATIONS_API_REQUESTS("conversations-api-requests"), - CONVERSATIONS_CONVERSATION_EVENTS("conversations-conversation-events"), - CONVERSATIONS_ENDPOINT_CONNECTIVITY( - "conversations-endpoint-connectivity" - ), - CONVERSATIONS_EVENTS("conversations-events"), - CONVERSATIONS_PARTICIPANT_EVENTS("conversations-participant-events"), - CONVERSATIONS_PARTICIPANTS("conversations-participants"), - CPS("cps"), - CREDIT_TRANSFER("credit-transfer"), - EMAIL("email"), - EMERGING_TECH("emerging-tech"), - ENGAGEMENT_SUITE_PACKAGED_PLANS("engagement-suite-packaged-plans"), - ENHANCED_LINE_TYPE_LOOKUPS("enhanced-line-type-lookups"), - ENTERPRISE("enterprise"), - EVENTS("events"), - EXPERIMENT_FRANCE_SMS("experiment-france-sms"), - EXPERIMENT_INDIA_SMS("experiment-india-sms"), - EXPERIMENT_UK_SMS("experiment-uk-sms"), - FAILED_MESSAGE_PROCESSING_FEE("failed-message-processing-fee"), - FLEX("flex"), - FLEX_ACTIVE_USER_HOURS("flex-active-user-hours"), - FLEX_CONCURRENT_USERS("flex-concurrent-users"), - FLEX_CONVERSATIONAL_INSIGHTS("flex-conversational-insights"), - FLEX_CONVERSATIONAL_INSIGHTS_MESSAGES( - "flex-conversational-insights-messages" - ), - FLEX_CONVERSATIONAL_INSIGHTS_VOICE_MINUTES( - "flex-conversational-insights-voice-minutes" - ), - FLEX_EMAIL_USAGE("flex-email-usage"), - FLEX_MESSAGING_USAGE("flex-messaging-usage"), - FLEX_PARTNER_SPINSCI("flex-partner-spinsci"), - FLEX_PARTNER_XCELERATE("flex-partner-xcelerate"), - FLEX_RESELLER_ECOSYSTEM("flex-reseller-ecosystem"), - FLEX_UNIQUE_USER("flex-unique-user"), - FLEX_USAGE("flex-usage"), - FLEX_USERS("flex-users"), - FLEX_VOICE_MINUTE("flex-voice-minute"), - FLEX_YTICA("flex-ytica"), - FRAUD_LOOKUPS("fraud-lookups"), - FRONTLINE("frontline"), - FRONTLINE_USERS("frontline-users"), - FUNCTIONS("functions"), - GENERIC_PAY_TRANSACTIONS("generic-pay-transactions"), - GROUP_ROOMS("group-rooms"), - GROUP_ROOMS_DATA_TRACK("group-rooms-data-track"), - GROUP_ROOMS_ENCRYPTED_MEDIA_RECORDED( - "group-rooms-encrypted-media-recorded" - ), - GROUP_ROOMS_MEDIA_DOWNLOADED("group-rooms-media-downloaded"), - GROUP_ROOMS_MEDIA_RECORDED("group-rooms-media-recorded"), - GROUP_ROOMS_MEDIA_ROUTED("group-rooms-media-routed"), - GROUP_ROOMS_MEDIA_STORED("group-rooms-media-stored"), - GROUP_ROOMS_PARTICIPANT_MINUTES("group-rooms-participant-minutes"), - GROUP_ROOMS_RECORDED_MINUTES("group-rooms-recorded-minutes"), - IP_MESSAGING("ip-messaging"), - IP_MESSAGING_COMMANDS("ip-messaging-commands"), - IP_MESSAGING_DATA_STORAGE("ip-messaging-data-storage"), - IP_MESSAGING_DATA_TRANSFER("ip-messaging-data-transfer"), - IP_MESSAGING_ENDPOINT_CONNECTIVITY( - "ip-messaging-endpoint-connectivity" - ), - IVR_VIRTUAL_AGENT_CUSTOM_VOICES("ivr-virtual-agent-custom-voices"), - IVR_VIRTUAL_AGENT_GENAI("ivr-virtual-agent-genai"), - LINE_STATUS_LOOKUPS("line-status-lookups"), - LIVE_ACTIVITY_LOOKUPS("live-activity-lookups"), - LOOKUP_BUCKET_ADJUSTMENT("lookup-bucket-adjustment"), - LOOKUP_IDENTITY_MATCH("lookup-identity-match"), - LOOKUPS("lookups"), - MARKETPLACE("marketplace"), - MARKETPLACE_ALGORITHMIA_NAMED_ENTITY_RECOGNITION( - "marketplace-algorithmia-named-entity-recognition" - ), - MARKETPLACE_CADENCE_TRANSCRIPTION("marketplace-cadence-transcription"), - MARKETPLACE_CADENCE_TRANSLATION("marketplace-cadence-translation"), - MARKETPLACE_CAPIO_SPEECH_TO_TEXT("marketplace-capio-speech-to-text"), - MARKETPLACE_CONVRIZA_ABABA("marketplace-convriza-ababa"), - MARKETPLACE_DEEPGRAM_PHRASE_DETECTOR( - "marketplace-deepgram-phrase-detector" - ), - MARKETPLACE_DEEPGRAM_TRANSCRIPTION( - "marketplace-deepgram-transcription" - ), - MARKETPLACE_DEEPGRAM_TRANSCRIPTION_BASE( - "marketplace-deepgram-transcription-base" - ), - MARKETPLACE_DEEPGRAM_TRANSSCRIPTION_ENHANCED( - "marketplace-deepgram-transscription-enhanced" - ), - MARKETPLACE_DIGITAL_SEGMENT_BUSINESS_INFO( - "marketplace-digital-segment-business-info" - ), - MARKETPLACE_FACEBOOK_OFFLINE_CONVERSIONS( - "marketplace-facebook-offline-conversions" - ), - MARKETPLACE_GOOGLE_SPEECH_TO_TEXT("marketplace-google-speech-to-text"), - MARKETPLACE_IBM_WATSON_MESSAGE_INSIGHTS( - "marketplace-ibm-watson-message-insights" - ), - MARKETPLACE_IBM_WATSON_MESSAGE_SENTIMENT( - "marketplace-ibm-watson-message-sentiment" - ), - MARKETPLACE_IBM_WATSON_RECORDING_ANALYSIS( - "marketplace-ibm-watson-recording-analysis" - ), - MARKETPLACE_IBM_WATSON_TONE_ANALYZER( - "marketplace-ibm-watson-tone-analyzer" - ), - MARKETPLACE_ICEHOOK_SYSTEMS_SCOUT("marketplace-icehook-systems-scout"), - MARKETPLACE_INFOGROUP_DATAAXLE_BIZINFO( - "marketplace-infogroup-dataaxle-bizinfo" - ), - MARKETPLACE_KEEN_IO_CONTACT_CENTER_ANALYTICS( - "marketplace-keen-io-contact-center-analytics" - ), - MARKETPLACE_MARCHEX_CLEANCALL("marketplace-marchex-cleancall"), - MARKETPLACE_MARCHEX_RECORDING_ANALYSIS( - "marketplace-marchex-recording-analysis" - ), - MARKETPLACE_MARCHEX_SENTIMENT_ANALYSIS_FOR_SMS( - "marketplace-marchex-sentiment-analysis-for-sms" - ), - MARKETPLACE_MARKETPLACE_NEXTCALLER_SOCIAL_ID( - "marketplace-marketplace-nextcaller-social-id" - ), - MARKETPLACE_MOBILE_COMMONS_OPT_OUT_CLASSIFIER( - "marketplace-mobile-commons-opt-out-classifier" - ), - MARKETPLACE_NEXIWAVE_VOICEMAIL_TO_TEXT( - "marketplace-nexiwave-voicemail-to-text" - ), - MARKETPLACE_NEXTCALLER_ADVANCED_CALLER_IDENTIFICATION( - "marketplace-nextcaller-advanced-caller-identification" - ), - MARKETPLACE_NOMOROBO_SPAM_SCORE("marketplace-nomorobo-spam-score"), - MARKETPLACE_PAY_ADDONS("marketplace-pay-addons"), - MARKETPLACE_PAY_ADDONS_BASECOMMERCE_PAY_CONNECTOR( - "marketplace-pay-addons-basecommerce-pay-connector" - ), - MARKETPLACE_PAY_ADDONS_BRAINTREE_PAY_CONNECTOR( - "marketplace-pay-addons-braintree-pay-connector" - ), - MARKETPLACE_PAY_ADDONS_CARDCONNECT_PAY_CONNECTOR( - "marketplace-pay-addons-cardconnect-pay-connector" - ), - MARKETPLACE_PAY_ADDONS_CHASE_PAY_CONNECTOR( - "marketplace-pay-addons-chase-pay-connector" - ), - MARKETPLACE_PAY_ADDONS_SHUTTLE_PAY_CONNECTOR( - "marketplace-pay-addons-shuttle-pay-connector" - ), - MARKETPLACE_PAY_ADDONS_STRIPE_PAY_CONNECTOR( - "marketplace-pay-addons-stripe-pay-connector" - ), - MARKETPLACE_PAYFONE_TCPA_COMPLIANCE( - "marketplace-payfone-tcpa-compliance" - ), - MARKETPLACE_POLY_AI_CONNECTOR("marketplace-poly-ai-connector"), - MARKETPLACE_REALPHONEVALIDATION("marketplace-realphonevalidation"), - MARKETPLACE_REMEETING_AUTOMATIC_SPEECH_RECOGNITION( - "marketplace-remeeting-automatic-speech-recognition" - ), - MARKETPLACE_SPOKE_PHONE_LICENSE_PRO( - "marketplace-spoke-phone-license-pro" - ), - MARKETPLACE_SPOKE_PHONE_LICENSE_STANDARD( - "marketplace-spoke-phone-license-standard" - ), - MARKETPLACE_TCPA_DEFENSE_SOLUTIONS_BLACKLIST_FEED( - "marketplace-tcpa-defense-solutions-blacklist-feed" - ), - MARKETPLACE_TELO_OPENCNAM("marketplace-telo-opencnam"), - MARKETPLACE_TRESTLE_SOLUTIONS_CALLER_IDENTIFICATION( - "marketplace-trestle-solutions-caller-identification" - ), - MARKETPLACE_TRUECNAM_TRUE_SPAM("marketplace-truecnam-true-spam"), - MARKETPLACE_TWILIO_CALLER_NAME_LOOKUP_US( - "marketplace-twilio-caller-name-lookup-us" - ), - MARKETPLACE_TWILIO_CARRIER_INFORMATION_LOOKUP( - "marketplace-twilio-carrier-information-lookup" - ), - MARKETPLACE_VOICEBASE_PCI("marketplace-voicebase-pci"), - MARKETPLACE_VOICEBASE_TRANSCRIPTION( - "marketplace-voicebase-transcription" - ), - MARKETPLACE_VOICEBASE_TRANSCRIPTION_CUSTOM_VOCABULARY( - "marketplace-voicebase-transcription-custom-vocabulary" - ), - MARKETPLACE_WEB_PURIFY_PROFANITY_FILTER( - "marketplace-web-purify-profanity-filter" - ), - MARKETPLACE_WHITEPAGES_PRO_CALLER_IDENTIFICATION( - "marketplace-whitepages-pro-caller-identification" - ), - MARKETPLACE_WHITEPAGES_PRO_PHONE_INTELLIGENCE( - "marketplace-whitepages-pro-phone-intelligence" - ), - MARKETPLACE_WHITEPAGES_PRO_PHONE_REPUTATION( - "marketplace-whitepages-pro-phone-reputation" - ), - MARKETPLACE_WOLFARM_SPOKEN_RESULTS( - "marketplace-wolfarm-spoken-results" - ), - MARKETPLACE_WOLFRAM_SHORT_ANSWER("marketplace-wolfram-short-answer"), - MARKETPLACE_YTICA_CONTACT_CENTER_REPORTING_ANALYTICS( - "marketplace-ytica-contact-center-reporting-analytics" - ), - MARKETPLAY_PAY_ADDONS_SHUTTLE_PAY_CONNECTOR( - "marketplay-pay-addons-shuttle-pay-connector" - ), - MEDIA_COMPOSER_MINUTES("media-composer-minutes"), - MEDIASTORAGE("mediastorage"), - MIN_SPEND_ADJUSTMENTS("min-spend-adjustments"), - MMS("mms"), - MMS_INBOUND("mms-inbound"), - MMS_INBOUND_LONGCODE("mms-inbound-longcode"), - MMS_INBOUND_SHORTCODE("mms-inbound-shortcode"), - MMS_INBOUND_TOLL_FREE("mms-inbound-toll-free"), - MMS_MESSAGES_CARRIERFEES("mms-messages-carrierfees"), - MMS_OUTBOUND("mms-outbound"), - MMS_OUTBOUND_LONGCODE("mms-outbound-longcode"), - MMS_OUTBOUND_SHORTCODE("mms-outbound-shortcode"), - MMS_OUTBOUND_TOLLFREE("mms-outbound-tollfree"), - MONITOR("monitor"), - MONITOR_READS("monitor-reads"), - MONITOR_STORAGE("monitor-storage"), - MONITOR_WRITES("monitor-writes"), - NOTIFY("notify"), - NOTIFY_ACTIONS_ATTEMPTS("notify-actions-attempts"), - NOTIFY_CHANNELS("notify-channels"), - NUMBER_FORMAT_LOOKUPS("number-format-lookups"), - PCHAT("pchat"), - PCHAT_ACTIONS("pchat-actions"), - PCHAT_APS("pchat-aps"), - PCHAT_CONV_MED_STORAGE("pchat-conv-med-storage"), - PCHAT_MESSAGES("pchat-messages"), - PCHAT_NOTIFICATIONS("pchat-notifications"), - PCHAT_READS("pchat-reads"), - PCHAT_USERS("pchat-users"), - PEER_TO_PEER_ROOMS_PARTICIPANT_MINUTES( - "peer-to-peer-rooms-participant-minutes" - ), - PFAX("pfax"), - PFAX_MINUTES("pfax-minutes"), - PFAX_MINUTES_INBOUND("pfax-minutes-inbound"), - PFAX_MINUTES_OUTBOUND("pfax-minutes-outbound"), - PFAX_PAGES("pfax-pages"), - PHONE_QUALITY_SCORE_LOOKUPS("phone-quality-score-lookups"), - PHONENUMBERS("phonenumbers"), - PHONENUMBERS_CPS("phonenumbers-cps"), - PHONENUMBERS_EMERGENCY("phonenumbers-emergency"), - PHONENUMBERS_LOCAL("phonenumbers-local"), - PHONENUMBERS_MOBILE("phonenumbers-mobile"), - PHONENUMBERS_PORTING("phonenumbers-porting"), - PHONENUMBERS_SETUPS("phonenumbers-setups"), - PHONENUMBERS_TOLLFREE("phonenumbers-tollfree"), - PREMIUMSUPPORT("premiumsupport"), - PREMIUMSUPPORT_PERCENTAGE_SPEND("premiumsupport-percentage-spend"), - PROGRAMMABLEVOICE_PLATFORM("programmablevoice-platform"), - PROGRAMMABLEVOICECONN_CLIENTSDK("programmablevoiceconn-clientsdk"), - PROGRAMMABLEVOICECONN_CLIENTSDK_INBOUND( - "programmablevoiceconn-clientsdk-inbound" - ), - PROGRAMMABLEVOICECONN_CLIENTSDK_OUTBOUND( - "programmablevoiceconn-clientsdk-outbound" - ), - PROGRAMMABLEVOICECONN_ONNET("programmablevoiceconn-onnet"), - PROGRAMMABLEVOICECONN_ONNET_INBOUND( - "programmablevoiceconn-onnet-inbound" - ), - PROGRAMMABLEVOICECONN_ONNET_OUTBOUND( - "programmablevoiceconn-onnet-outbound" - ), - PROGRAMMABLEVOICECONN_SIP("programmablevoiceconn-sip"), - PROGRAMMABLEVOICECONN_SIP_INBOUND("programmablevoiceconn-sip-inbound"), - PROGRAMMABLEVOICECONN_SIP_OUTBOUND( - "programmablevoiceconn-sip-outbound" - ), - PROGRAMMABLEVOICECONNECTIVITY("programmablevoiceconnectivity"), - PROXY("proxy"), - PROXY_ACTIVE_SESSIONS("proxy-active-sessions"), - PROXY_BUCKET_ADJUSTMENT("proxy-bucket-adjustment"), - PROXY_LICENSES("proxy-licenses"), - PSTNCONNECTIVITY("pstnconnectivity"), - PSTNCONNECTIVITY_INBOUND("pstnconnectivity-inbound"), - PSTNCONNECTIVITY_OUTBOUND("pstnconnectivity-outbound"), - PV("pv"), - PV_BASIC_ROOMS("pv-basic-rooms"), - PV_COMPOSITION_MEDIA_DOWNLOADED("pv-composition-media-downloaded"), - PV_COMPOSITION_MEDIA_ENCRYPTED("pv-composition-media-encrypted"), - PV_COMPOSITION_MEDIA_STORED("pv-composition-media-stored"), - PV_COMPOSITION_MINUTES("pv-composition-minutes"), - PV_RECORDING_COMPOSITIONS("pv-recording-compositions"), - PV_ROOM_PARTICIPANTS("pv-room-participants"), - PV_ROOM_PARTICIPANTS_AU1("pv-room-participants-au1"), - PV_ROOM_PARTICIPANTS_BR1("pv-room-participants-br1"), - PV_ROOM_PARTICIPANTS_IE1("pv-room-participants-ie1"), - PV_ROOM_PARTICIPANTS_JP1("pv-room-participants-jp1"), - PV_ROOM_PARTICIPANTS_SG1("pv-room-participants-sg1"), - PV_ROOM_PARTICIPANTS_US1("pv-room-participants-us1"), - PV_ROOM_PARTICIPANTS_US2("pv-room-participants-us2"), - PV_ROOMS("pv-rooms"), - PV_SIP_ENDPOINT_REGISTRATIONS("pv-sip-endpoint-registrations"), - RCS_MESSAGES("rcs-messages"), - REASSIGNED_NUMBER("reassigned-number"), - RECORDINGS("recordings"), - RECORDINGSTORAGE("recordingstorage"), - SHORTCODES("shortcodes"), - SHORTCODES_CUSTOMEROWNED("shortcodes-customerowned"), - SHORTCODES_MMS_ENABLEMENT("shortcodes-mms-enablement"), - SHORTCODES_MPS("shortcodes-mps"), - SHORTCODES_RANDOM("shortcodes-random"), - SHORTCODES_SETUP_FEES("shortcodes-setup-fees"), - SHORTCODES_UK("shortcodes-uk"), - SHORTCODES_VANITY("shortcodes-vanity"), - SIM_SWAP_LOOKUPS("sim-swap-lookups"), - SIP_SECURE_MEDIA("sip-secure-media"), - SMALL_GROUP_ROOMS("small-group-rooms"), - SMALL_GROUP_ROOMS_DATA_TRACK("small-group-rooms-data-track"), - SMALL_GROUP_ROOMS_PARTICIPANT_MINUTES( - "small-group-rooms-participant-minutes" - ), - SMS("sms"), - SMS_INBOUND("sms-inbound"), - SMS_INBOUND_LONGCODE("sms-inbound-longcode"), - SMS_INBOUND_SHORTCODE("sms-inbound-shortcode"), - SMS_INBOUND_TOLLFREE("sms-inbound-tollfree"), - SMS_MESSAGES_CARRIERFEES("sms-messages-carrierfees"), - SMS_MESSAGES_FEATURES("sms-messages-features"), - SMS_MESSAGES_FEATURES_ENGAGEMENT_SUITE( - "sms-messages-features-engagement-suite" - ), - SMS_MESSAGES_FEATURES_MESSAGE_REDACTION( - "sms-messages-features-message-redaction" - ), - SMS_MESSAGES_FEATURES_SENDERID("sms-messages-features-senderid"), - SMS_MPS("sms-mps"), - SMS_MPS_SHORTCODE("sms-mps-shortcode"), - SMS_MPS_TOLLFREE("sms-mps-tollfree"), - SMS_MPS_TOLLFREE_SETUP("sms-mps-tollfree-setup"), - SMS_NATIONAL_REGULATORY_PROTECTION( - "sms-national-regulatory-protection" - ), - SMS_OUTBOUND("sms-outbound"), - SMS_OUTBOUND_CONTENT_INSPECTION("sms-outbound-content-inspection"), - SMS_OUTBOUND_LONGCODE("sms-outbound-longcode"), - SMS_OUTBOUND_SHORTCODE("sms-outbound-shortcode"), - SMS_OUTBOUND_TOLLFREE("sms-outbound-tollfree"), - SMS_PUMPING_PROTECTION("sms-pumping-protection"), - SMS_PUMPING_RISK("sms-pumping-risk"), - SMSMESSAGES_BUCKET_ADJUSTMENTS("smsmessages-bucket-adjustments"), - SMSMESSAGES_OUTBOUND_DOMESTIC("smsmessages-outbound-domestic"), - SPEECH_RECOGNITION("speech-recognition"), - STUDIO_ENGAGEMENTS("studio-engagements"), - SYNC("sync"), - SYNC_ACTIONS("sync-actions"), - SYNC_ENDPOINT_HOURS("sync-endpoint-hours"), - SYNC_ENDPOINT_HOURS_ABOVE_DAILY_CAP( - "sync-endpoint-hours-above-daily-cap" - ), - TASKROUTER_TASKS("taskrouter-tasks"), - TOTALPRICE("totalprice"), - TRANSCRIPTIONS("transcriptions"), - TRUNKING_CPS("trunking-cps"), - TRUNKING_EMERGENCY_CALLS("trunking-emergency-calls"), - TRUNKING_ORIGINATION("trunking-origination"), - TRUNKING_ORIGINATION_LOCAL("trunking-origination-local"), - TRUNKING_ORIGINATION_MOBILE("trunking-origination-mobile"), - TRUNKING_ORIGINATION_TOLLFREE("trunking-origination-tollfree"), - TRUNKING_RECORDINGS("trunking-recordings"), - TRUNKING_SECURE("trunking-secure"), - TRUNKING_TERMINATION("trunking-termination"), - TTS_GOOGLE("tts-google"), - TURNMEGABYTES("turnmegabytes"), - TURNMEGABYTES_AUSTRALIA("turnmegabytes-australia"), - TURNMEGABYTES_BRASIL("turnmegabytes-brasil"), - TURNMEGABYTES_GERMANY("turnmegabytes-germany"), - TURNMEGABYTES_INDIA("turnmegabytes-india"), - TURNMEGABYTES_IRELAND("turnmegabytes-ireland"), - TURNMEGABYTES_JAPAN("turnmegabytes-japan"), - TURNMEGABYTES_SINGAPORE("turnmegabytes-singapore"), - TURNMEGABYTES_USEAST("turnmegabytes-useast"), - TURNMEGABYTES_USWEST("turnmegabytes-uswest"), - TWILIO_FOR_SALESFORCE("twilio-for-salesforce"), - TWILIO_FOR_SALESFORCE_LICENSES("twilio-for-salesforce-licenses"), - TWILIO_INTERCONNECT("twilio-interconnect"), - TWIML("twiml"), - USAGE_FLEX_VIDEO("usage-flex-video"), - USAGE_FUNCTIONS("usage-functions"), - USAGE_RCS_BASIC_MESSAGES_OUTBOUND("usage-rcs-basic-messages-outbound"), - USAGE_RCS_MESSAGES("usage-rcs-messages"), - USAGE_RCS_MESSAGES_INBOUND("usage-rcs-messages-inbound"), - USAGE_RCS_MESSAGING_CARRIER_FEES("usage-rcs-messaging-carrier-fees"), - USAGE_RCS_SINGLE_MESSAGES_OUTBOUND( - "usage-rcs-single-messages-outbound" - ), - VERIFY_PACKAGE_PLANS("verify-package-plans"), - VERIFY_PUSH("verify-push"), - VERIFY_SNA("verify-sna"), - VERIFY_TOTP("verify-totp"), - VERIFY_VOICE_SMS("verify-voice-sms"), - VERIFY_WHATSAPP_CONVERSATIONS_BUSINESS_INITIATED( - "verify-whatsapp-conversations-business-initiated" - ), - VERIFY_WHATSAPP_TEMPLATE_BUSINESS_INITIATED( - "verify-whatsapp-template-business-initiated" - ), - VIDEO_RECORDINGS("video-recordings"), - VIDEO_ROOMS_TURN_MEGABYTES("video-rooms-turn-megabytes"), - VIRTUAL_AGENT("virtual-agent"), - VOICE_INSIGHTS("voice-insights"), - VOICE_INSIGHTS_CLIENT_INSIGHTS_ON_DEMAND_MINUTE( - "voice-insights-client-insights-on-demand-minute" - ), - VOICE_INSIGHTS_PTSN_INSIGHTS_ON_DEMAND_MINUTE( - "voice-insights-ptsn-insights-on-demand-minute" - ), - VOICE_INSIGHTS_SIP_INTERFACE_INSIGHTS_ON_DEMAND_MINUTE( - "voice-insights-sip-interface-insights-on-demand-minute" - ), - VOICE_INSIGHTS_SIP_TRUNKING_INSIGHTS_ON_DEMAND_MINUTE( - "voice-insights-sip-trunking-insights-on-demand-minute" - ), - VOICE_INTELLIGENCE("voice-intelligence"), - VOICE_INTELLIGENCE_EIP_OPERATORS("voice-intelligence-eip-operators"), - VOICE_INTELLIGENCE_OPERATORS("voice-intelligence-operators"), - VOICE_INTELLIGENCE_TRANSCRIPTION("voice-intelligence-transcription"), - WDS("wds"), - WIRELESS("wireless"), - WIRELESS_DATA("wireless-data"), - WIRELESS_DATA_PAYG("wireless-data-payg"), - WIRELESS_DATA_PAYG_AFRICA("wireless-data-payg-africa"), - WIRELESS_DATA_PAYG_ASIA("wireless-data-payg-asia"), - WIRELESS_DATA_PAYG_CENTRALANDSOUTHAMERICA( - "wireless-data-payg-centralandsouthamerica" - ), - WIRELESS_DATA_PAYG_EUROPE("wireless-data-payg-europe"), - WIRELESS_DATA_PAYG_NORTHAMERICA("wireless-data-payg-northamerica"), - WIRELESS_DATA_PAYG_OCEANIA("wireless-data-payg-oceania"), - WIRELESS_DATA_QUOTA1("wireless-data-quota1"), - WIRELESS_DATA_QUOTA1_AFRICA("wireless-data-quota1-africa"), - WIRELESS_DATA_QUOTA1_ASIA("wireless-data-quota1-asia"), - WIRELESS_DATA_QUOTA1_CENTRALANDSOUTHAMERICA( - "wireless-data-quota1-centralandsouthamerica" - ), - WIRELESS_DATA_QUOTA1_EUROPE("wireless-data-quota1-europe"), - WIRELESS_DATA_QUOTA1_NORTHAMERICA("wireless-data-quota1-northamerica"), - WIRELESS_DATA_QUOTA1_OCEANIA("wireless-data-quota1-oceania"), - WIRELESS_DATA_QUOTA10("wireless-data-quota10"), - WIRELESS_DATA_QUOTA10_AFRICA("wireless-data-quota10-africa"), - WIRELESS_DATA_QUOTA10_ASIA("wireless-data-quota10-asia"), - WIRELESS_DATA_QUOTA10_CENTRALANDSOUTHAMERICA( - "wireless-data-quota10-centralandsouthamerica" - ), - WIRELESS_DATA_QUOTA10_EUROPE("wireless-data-quota10-europe"), - WIRELESS_DATA_QUOTA10_NORTHAMERICA( - "wireless-data-quota10-northamerica" - ), - WIRELESS_DATA_QUOTA10_OCEANIA("wireless-data-quota10-oceania"), - WIRELESS_DATA_QUOTA50("wireless-data-quota50"), - WIRELESS_DATA_QUOTA50_AFRICA("wireless-data-quota50-africa"), - WIRELESS_DATA_QUOTA50_ASIA("wireless-data-quota50-asia"), - WIRELESS_DATA_QUOTA50_CENTRALANDSOUTHAMERICA( - "wireless-data-quota50-centralandsouthamerica" - ), - WIRELESS_DATA_QUOTA50_EUROPE("wireless-data-quota50-europe"), - WIRELESS_DATA_QUOTA50_NORTHAMERICA( - "wireless-data-quota50-northamerica" - ), - WIRELESS_DATA_QUOTA50_OCEANIA("wireless-data-quota50-oceania"), - WIRELESS_DATA_QUOTACUSTOM("wireless-data-quotacustom"), - WIRELESS_DATA_QUOTACUSTOM_AFRICA("wireless-data-quotacustom-africa"), - WIRELESS_DATA_QUOTACUSTOM_ASIA("wireless-data-quotacustom-asia"), - WIRELESS_DATA_QUOTACUSTOM_CENTRALANDSOUTHAMERICA( - "wireless-data-quotacustom-centralandsouthamerica" - ), - WIRELESS_DATA_QUOTACUSTOM_EUROPE("wireless-data-quotacustom-europe"), - WIRELESS_DATA_QUOTACUSTOM_NORTHAMERICA( - "wireless-data-quotacustom-northamerica" - ), - WIRELESS_DATA_QUOTACUSTOM_OCEANIA("wireless-data-quotacustom-oceania"), - WIRELESS_MRC_PAYG("wireless-mrc-payg"), - WIRELESS_MRC_QUOTA1("wireless-mrc-quota1"), - WIRELESS_MRC_QUOTA10("wireless-mrc-quota10"), - WIRELESS_MRC_QUOTA50("wireless-mrc-quota50"), - WIRELESS_MRC_QUOTACUSTOM("wireless-mrc-quotacustom"), - WIRELESS_ORDERS("wireless-orders"), - WIRELESS_ORDERS_ARTWORK("wireless-orders-artwork"), - WIRELESS_ORDERS_BULK("wireless-orders-bulk"), - WIRELESS_ORDERS_ESIM("wireless-orders-esim"), - WIRELESS_ORDERS_STARTER("wireless-orders-starter"), - WIRELESS_QUOTAS("wireless-quotas"), - WIRELESS_SMS_AFRICA("wireless-sms-africa"), - WIRELESS_SMS_ASIA("wireless-sms-asia"), - WIRELESS_SMS_CENTRALANDSOUTHAMERICA( - "wireless-sms-centralandsouthamerica" - ), - WIRELESS_SMS_EUROPE("wireless-sms-europe"), - WIRELESS_SMS_NORTHAMERICA("wireless-sms-northamerica"), - WIRELESS_SMS_OCEANIA("wireless-sms-oceania"), - WIRELESS_SUPER_SIM("wireless-super-sim"), - WIRELESS_SUPER_SIM_DATA("wireless-super-sim-data"), - WIRELESS_SUPER_SIM_DATA_NORTH_AMERICA_USA( - "wireless-super-sim-data-north-america-usa" - ), - WIRELESS_SUPER_SIM_DATA_PAYG("wireless-super-sim-data-payg"), - WIRELESS_SUPER_SIM_DATA_PAYG_EUROPE( - "wireless-super-sim-data-payg-europe" - ), - WIRELESS_SUPER_SIM_DATA_PAYG_NORTH_AMERICA( - "wireless-super-sim-data-payg-north-america" - ), - WIRELESS_SUPER_SIM_HARDWARE("wireless-super-sim-hardware"), - WIRELESS_SUPER_SIM_HARDWARE_BULK("wireless-super-sim-hardware-bulk"), - WIRELESS_SUPER_SIM_SMSCOMMANDS("wireless-super-sim-smscommands"), - WIRELESS_SUPER_SIM_SMSCOMMANDS_AFRICA( - "wireless-super-sim-smscommands-africa" - ), - WIRELESS_SUPER_SIM_SMSCOMMANDS_ASIA( - "wireless-super-sim-smscommands-asia" - ), - WIRELESS_SUPER_SIM_SMSCOMMANDS_CENT_AND_SOUTH_AMERICA( - "wireless-super-sim-smscommands-cent-and-south-america" - ), - WIRELESS_SUPER_SIM_SMSCOMMANDS_EUROPE( - "wireless-super-sim-smscommands-europe" - ), - WIRELESS_SUPER_SIM_SMSCOMMANDS_NORTH_AMERICA( - "wireless-super-sim-smscommands-north-america" - ), - WIRELESS_SUPER_SIM_SMSCOMMANDS_OCEANIA( - "wireless-super-sim-smscommands-oceania" - ), - WIRELESS_SUPER_SIM_SUBSCRIPTION("wireless-super-sim-subscription"), - WIRELESS_SUPER_SIM_SUBSCRIPTION_PAYG( - "wireless-super-sim-subscription-payg" - ), - WIRELESS_USAGE("wireless-usage"), - WIRELESS_USAGE_COMMANDS("wireless-usage-commands"), - WIRELESS_USAGE_COMMANDS_AFRICA("wireless-usage-commands-africa"), - WIRELESS_USAGE_COMMANDS_ASIA("wireless-usage-commands-asia"), - WIRELESS_USAGE_COMMANDS_CENTRALANDSOUTHAMERICA( - "wireless-usage-commands-centralandsouthamerica" - ), - WIRELESS_USAGE_COMMANDS_EUROPE("wireless-usage-commands-europe"), - WIRELESS_USAGE_COMMANDS_HOME("wireless-usage-commands-home"), - WIRELESS_USAGE_COMMANDS_NORTHAMERICA( - "wireless-usage-commands-northamerica" - ), - WIRELESS_USAGE_COMMANDS_OCEANIA("wireless-usage-commands-oceania"), - WIRELESS_USAGE_COMMANDS_ROAMING("wireless-usage-commands-roaming"), - WIRELESS_USAGE_DATA("wireless-usage-data"), - WIRELESS_USAGE_DATA_AFRICA("wireless-usage-data-africa"), - WIRELESS_USAGE_DATA_ASIA("wireless-usage-data-asia"), - WIRELESS_USAGE_DATA_CENTRALANDSOUTHAMERICA( - "wireless-usage-data-centralandsouthamerica" - ), - WIRELESS_USAGE_DATA_CUSTOM_ADDITIONALMB( - "wireless-usage-data-custom-additionalmb" - ), - WIRELESS_USAGE_DATA_CUSTOM_FIRST5MB( - "wireless-usage-data-custom-first5mb" - ), - WIRELESS_USAGE_DATA_DOMESTIC_ROAMING( - "wireless-usage-data-domestic-roaming" - ), - WIRELESS_USAGE_DATA_EUROPE("wireless-usage-data-europe"), - WIRELESS_USAGE_DATA_INDIVIDUAL_ADDITIONALGB( - "wireless-usage-data-individual-additionalgb" - ), - WIRELESS_USAGE_DATA_INDIVIDUAL_FIRSTGB( - "wireless-usage-data-individual-firstgb" - ), - WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_CANADA( - "wireless-usage-data-international-roaming-canada" - ), - WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_INDIA( - "wireless-usage-data-international-roaming-india" - ), - WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_MEXICO( - "wireless-usage-data-international-roaming-mexico" - ), - WIRELESS_USAGE_DATA_NORTHAMERICA("wireless-usage-data-northamerica"), - WIRELESS_USAGE_DATA_OCEANIA("wireless-usage-data-oceania"), - WIRELESS_USAGE_DATA_POOLED("wireless-usage-data-pooled"), - WIRELESS_USAGE_DATA_POOLED_DOWNLINK( - "wireless-usage-data-pooled-downlink" - ), - WIRELESS_USAGE_DATA_POOLED_UPLINK("wireless-usage-data-pooled-uplink"), - WIRELESS_USAGE_MRC("wireless-usage-mrc"), - WIRELESS_USAGE_MRC_CUSTOM("wireless-usage-mrc-custom"), - WIRELESS_USAGE_MRC_INDIVIDUAL("wireless-usage-mrc-individual"), - WIRELESS_USAGE_MRC_POOLED("wireless-usage-mrc-pooled"), - WIRELESS_USAGE_MRC_SUSPENDED("wireless-usage-mrc-suspended"), - WIRELESS_USAGE_SMS("wireless-usage-sms"), - WIRELESS_USAGE_VOICE("wireless-usage-voice"), - A2P_FAST_TRACK_ONBOARDING("a2p-fast-track-onboarding"), - ADVISORY_SERVICES("advisory-services"), - ADVISORY_SERVICES_BILLED("advisory-services-billed"), - ADVISORY_SERVICES_CALL_TRACKING("advisory-services-call-tracking"), - ADVISORY_SERVICES_DATA_SERVICES("advisory-services-data-services"), - ADVISORY_SERVICES_EXPENSES("advisory-services-expenses"), - ADVISORY_SERVICES_SIP_TRUNKING("advisory-services-sip-trunking"), - ASSETS_REQUESTS("assets-requests"), - AUDIENCE_MINUTES_VIDEO("audience-minutes-video"), - AUTHY_BUCKET_ADJUSTMENT("authy-bucket-adjustment"), - AUTHY_SOFTWARE("authy-software"), - CALLERIDLOOKUPS_API("calleridlookups-api"), - CALLERIDLOOKUPS_PROGRAMMABLEVOICE("calleridlookups-programmablevoice"), - CALLERIDLOOKUPS_TRUNKING("calleridlookups-trunking"), - CALLS_TRUNKING_INBOUND_TOLLFREE_LOCAL( - "calls-trunking-inbound-tollfree-local" - ), - CALLS_TRUNKING_INBOUND_TOLLFREE_MOBILE( - "calls-trunking-inbound-tollfree-mobile" - ), - CHANNELS_WHATSAPP_CONVERSATION_FREE_1( - "channels-whatsapp-conversation-free-1" - ), - CONFERENCE("conference"), - CONVERSATIONAL_INSIGHTS("conversational-insights"), - CONVERSATIONAL_INSIGHTS_MESSAGES("conversational-insights-messages"), - CONVERSATIONAL_INSIGHTS_VOICE_MINUTES( - "conversational-insights-voice-minutes" - ), - DEMO("demo"), - DEMO_UC_SCRIPT_TEST("demo-uc-script-test"), - ELASTIC_SIP_TRUNKING("elastic-sip-trunking"), - ELASTIC_SIP_TRUNKING_CALL_TRANSFERS( - "elastic-sip-trunking-call-transfers" - ), - ENTERPRISE_HIPPA("enterprise-hippa"), - FLEX_NAMED_USERS("flex-named-users"), - FLEX_SPINSCI("flex-spinsci"), - FLEX_USERS_1("flex-users-1"), - FLEX_WFO_PREMIUM_SPEECH_ANALYTICS("flex-wfo-premium-speech-analytics"), - FLEX_XCELERATE("flex-xcelerate"), - FUNCTIONS_ROLLUP("functions-rollup"), - IMP_V1_USAGE("imp-v1-usage"), - IP_MESSAGING_ADDONS("ip-messaging-addons"), - IVR("ivr"), - IVR_CONVERSATIONAL("ivr-conversational"), - IVR_DTMF("ivr-dtmf"), - IVR_VIRTUALAGENT("ivr-virtualagent"), - LIVE("live"), - LIVE_MEDIA_RECORDING_MINUTES("live-media-recording-minutes"), - LONGCODE_MPS("longcode-mps"), - MARKETPLACE_ANALYTICS_ADDONS("marketplace-analytics-addons"), - MARKETPLACE_ISV_ADDONS("marketplace-isv-addons"), - MARKETPLACE_MESSAGING_ADDONS("marketplace-messaging-addons"), - MARKETPLACE_PHONENUMBERS_ADDONS("marketplace-phonenumbers-addons"), - MARKETPLACE_RECORDING_ADDONS("marketplace-recording-addons"), - MARKETPLACE_VIRTUALAGENT_ADDONS("marketplace-virtualagent-addons"), - MARKETPLAY_PAY_ADDONS_SHUTTLE_PAY_CONNECTOR_1( - "marketplay-pay-addons-shuttle-pay-connector-1" - ), - MARKETPLAY_PAY_ADDONS_STRIPE_PAY_CONNECTOR( - "marketplay-pay-addons-stripe-pay-connector" - ), - MMS_INBOUND_LONGCODE_CANADA("mms-inbound-longcode-canada"), - MMS_INBOUND_LONGCODE_UNITEDSTATES("mms-inbound-longcode-unitedstates"), - MMS_OUTBOUND_LONGCODE_CANADA("mms-outbound-longcode-canada"), - MMS_OUTBOUND_LONGCODE_UNITEDSTATES( - "mms-outbound-longcode-unitedstates" - ), - MMS_OUTBOUND_TOLL_FREE("mms-outbound-toll-free"), - NOTIFY_CHATAPPSANDOTHERCHANNELS("notify-chatappsandotherchannels"), - NOTIFY_NOTIFYSERVICES("notify-notifyservices"), - NOTIFY_PUSHNOTIFICATIONS("notify-pushnotifications"), - PAYMENT_GATEWAY_CONNECTORS("payment-gateway-connectors"), - PAYMENT_SOLUTIONS("payment-solutions"), - PCHAT_BUCKET_ADJUSTMENT("pchat-bucket-adjustment"), - PHONENUMBERS_NUMBERS("phonenumbers-numbers"), - PROG_VOICE_CLIENT_ANDROID("prog-voice-client-android"), - PROG_VOICE_CLIENT_ANDROID_INBOUND("prog-voice-client-android-inbound"), - PROG_VOICE_CLIENT_ANDROID_OUTBOUND( - "prog-voice-client-android-outbound" - ), - PROG_VOICE_CLIENT_IOS("prog-voice-client-ios"), - PROG_VOICE_CLIENT_IOS_INBOUND("prog-voice-client-ios-inbound"), - PROG_VOICE_CLIENT_IOS_OUTBOUND("prog-voice-client-ios-outbound"), - PROG_VOICE_CLIENT_SDK("prog-voice-client-sdk"), - PROG_VOICE_CLIENT_WEB("prog-voice-client-web"), - PROG_VOICE_CLIENT_WEB_INBOUND("prog-voice-client-web-inbound"), - PROG_VOICE_CLIENT_WEB_OUTBOUND("prog-voice-client-web-outbound"), - PROGRAMMABLEVOICECONNECTIVITY_MEDIA_STREAMS( - "programmablevoiceconnectivity-media-streams" - ), - PSTNCONNECTIVITY_BYOC("pstnconnectivity-byoc"), - PSTNCONNECTIVITY_EMERGENCY("pstnconnectivity-emergency"), - PSTNCONNECTIVITY_MINUTES("pstnconnectivity-minutes"), - PSTNCONNECTIVITY_MINUTES_1("pstnconnectivity-minutes-1"), - PSTNCONNECTIVITY_MINUTESINBOUNDLOCAL( - "pstnconnectivity-minutesinboundlocal" - ), - PSTNCONNECTIVITY_MINUTESINBOUNDMOBILE( - "pstnconnectivity-minutesinboundmobile" - ), - PSTNCONNECTIVITY_MINUTESINBOUNDTOLLFREE( - "pstnconnectivity-minutesinboundtollfree" - ), - PSTNCONNECTIVITY_MINUTESINBOUNDTOLLFREELOCAL( - "pstnconnectivity-minutesinboundtollfreelocal" - ), - PSTNCONNECTIVITY_MINUTESINBOUNDTOLLFREEMOBILE( - "pstnconnectivity-minutesinboundtollfreemobile" - ), - PV_ROOM_HOURS("pv-room-hours"), - PV_ROOM_SIMULTANEOUS_PARTICIPANT_CONNECTIONS( - "pv-room-simultaneous-participant-connections" - ), - PVIDEO_ROOM_HOURS_AU1("pvideo-room-hours-au1"), - PVIDEO_ROOM_HOURS_BR1("pvideo-room-hours-br1"), - PVIDEO_ROOM_HOURS_IE1("pvideo-room-hours-ie1"), - PVIDEO_ROOM_HOURS_JP1("pvideo-room-hours-jp1"), - PVIDEO_ROOM_HOURS_SG1("pvideo-room-hours-sg1"), - PVIDEO_ROOM_HOURS_US1("pvideo-room-hours-us1"), - PVIDEO_ROOM_HOURS_US2("pvideo-room-hours-us2"), - RECORDINGS_ENCRYPTED("recordings-encrypted"), - SHORT_CODE_SETUP_FEES("short-code-setup-fees"), - SHORTCODES_MESSAGES_INBOUND("shortcodes-messages-inbound"), - SHORTCODES_MESSAGES_OUTBOUND("shortcodes-messages-outbound"), - SMS_MESSAGES_REGISTRATIONFEES("sms-messages-registrationfees"), - SMS_MMS_PENALTY_FEES("sms-mms-penalty-fees"), - SMS_MMS_PENALTY_FEES_1("sms-mms-penalty-fees-1"), - SMS_PUMPING_PROTECTION_NON_USCA("sms-pumping-protection-non-usca"), - SMS_PUMPING_PROTECTION_USCA("sms-pumping-protection-usca"), - STUDIO("studio"), - STUDIO_MONTHLY_FEES("studio-monthly-fees"), - SUPERSIM("supersim"), - TASK_ROUTER("task-router"), - TASK_ROUTER_WORKERS("task-router-workers"), - TEST_QUOTA_BUCKETS("test-quota-buckets"), - TEST_UC_SCRIPT_1("test-uc-script-1"), - TEST_UC_SCRIPT_DEMO_2("test-uc-script-demo-2"), - TEXT_TO_SPEECH("text-to-speech"), - TME("tme"), - TTS_BASIC("tts-basic"), - TWILIO_EDITIONS("twilio-editions"), - TWILIO_INTERCONNECT_CALIFORNIA("twilio-interconnect-california"), - TWILIO_INTERCONNECT_CALIFORNIA_MONTHLY( - "twilio-interconnect-california-monthly" - ), - TWILIO_INTERCONNECT_CALIFORNIA_SETUP( - "twilio-interconnect-california-setup" - ), - TWILIO_INTERCONNECT_FRANKFURT("twilio-interconnect-frankfurt"), - TWILIO_INTERCONNECT_FRANKFURT_MO("twilio-interconnect-frankfurt-mo"), - TWILIO_INTERCONNECT_FRANKFURT_SETUP( - "twilio-interconnect-frankfurt-setup" - ), - TWILIO_INTERCONNECT_LONDON("twilio-interconnect-london"), - TWILIO_INTERCONNECT_LONDON_MO("twilio-interconnect-london-mo"), - TWILIO_INTERCONNECT_LONDON_SETUP("twilio-interconnect-london-setup"), - TWILIO_INTERCONNECT_SAO_PAULO("twilio-interconnect-sao-paulo"), - TWILIO_INTERCONNECT_SAO_PAULO_MONTHLY( - "twilio-interconnect-sao-paulo-monthly" - ), - TWILIO_INTERCONNECT_SAO_PAULO_SETUP( - "twilio-interconnect-sao-paulo-setup" - ), - TWILIO_INTERCONNECT_SINGAPORE("twilio-interconnect-singapore"), - TWILIO_INTERCONNECT_SINGAPORE_MO("twilio-interconnect-singapore-mo"), - TWILIO_INTERCONNECT_SINGAPORE_SETUP( - "twilio-interconnect-singapore-setup" - ), - TWILIO_INTERCONNECT_SYDNEY("twilio-interconnect-sydney"), - TWILIO_INTERCONNECT_SYDNEY_MO("twilio-interconnect-sydney-mo"), - TWILIO_INTERCONNECT_SYDNEY_SETUP("twilio-interconnect-sydney-setup"), - TWILIO_INTERCONNECT_TOKYO("twilio-interconnect-tokyo"), - TWILIO_INTERCONNECT_TOKYO_MO("twilio-interconnect-tokyo-mo"), - TWILIO_INTERCONNECT_TOKYO_SETUP("twilio-interconnect-tokyo-setup"), - TWILIO_INTERCONNECT_VA("twilio-interconnect-va"), - TWILIO_INTERCONNECT_VA_MO("twilio-interconnect-va-mo"), - TWILIO_INTERCONNECT_VA_SETUP("twilio-interconnect-va-setup"), - TWIML_VERBS("twiml-verbs"), - TWIML_VERBS_SAY("twiml-verbs-say"), - USAGE_PROGRAMMABLE_MESSAGING_ENGAGEMENT_SUITE( - "usage-programmable-messaging-engagement-suite" - ), - USAGE_PROGRAMMABLE_MESSAGING_FEES_SERVICES( - "usage-programmable-messaging-fees-services" - ), - VERIFY_OUTBOUND_EMAIL("verify-outbound-email"), - VERIFY_PACKAGED_PLANS("verify-packaged-plans"), - VERIFY_SILENT_NETWORK_AUTH("verify-silent-network-auth"), - VERIFY_VOICE_AND_SMS("verify-voice-and-sms"), - VOICE_INSIGHTS_CLIENT_INSIGHTS_MONTHY_COMMIT( - "voice-insights-client-insights-monthy-commit" - ), - WIRELESS_DATA_PAYG_ASIA_AFG("wireless-data-payg-asia-afg"), - WIRELESS_MULTI_IMSI_SIM_COMMANDS("wireless-multi-imsi-sim-commands"), - WIRELESS_MULTI_IMSI_SIM_COMMANDS_USA( - "wireless-multi-imsi-sim-commands-usa" - ), - WIRELESS_MULTI_IMSI_SIM_DATA("wireless-multi-imsi-sim-data"), - WIRELESS_MULTI_IMSI_SIM_DATA_EU28("wireless-multi-imsi-sim-data-eu28"), - WIRELESS_MULTI_IMSI_SIM_DATA_USA("wireless-multi-imsi-sim-data-usa"), - WIRELESS_MULTI_IMSI_SIM_MONTHLY_FEES( - "wireless-multi-imsi-sim-monthly-fees" - ), - WIRELESS_MULTI_IMSI_SIM_USAGE("wireless-multi-imsi-sim-usage"), - WIRELESS_SUPER_SIM_DATA_NORTH_AMERICA( - "wireless-super-sim-data-north-america" - ), - WIRELESS_SUPER_SIM_USAGE("wireless-super-sim-usage"); - - private final String value; - - private Category(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static Category forValue(final String value) { - return Promoter.enumFromString(value, Category.values()); - } - } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/usage/RecordReader.java b/src/main/java/com/twilio/rest/api/v2010/account/usage/RecordReader.java index bccb2d1371..69dea74697 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/usage/RecordReader.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/usage/RecordReader.java @@ -32,7 +32,7 @@ public class RecordReader extends Reader { private String pathAccountSid; - private Record.Category category; + private String category; private LocalDate startDate; private LocalDate endDate; private Boolean includeSubaccounts; @@ -44,7 +44,7 @@ public RecordReader(final String pathAccountSid) { this.pathAccountSid = pathAccountSid; } - public RecordReader setCategory(final Record.Category category) { + public RecordReader setCategory(final String category) { this.category = category; return this; } @@ -167,7 +167,7 @@ public Page getPage( private void addQueryParams(final Request request) { if (category != null) { - request.addQueryParam("Category", category.toString()); + request.addQueryParam("Category", category); } if (startDate != null) { request.addQueryParam( diff --git a/src/main/java/com/twilio/rest/api/v2010/account/usage/Trigger.java b/src/main/java/com/twilio/rest/api/v2010/account/usage/Trigger.java index a29e15c04b..9e548a35d4 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/usage/Trigger.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/usage/Trigger.java @@ -38,12 +38,12 @@ @ToString public class Trigger extends Resource { - private static final long serialVersionUID = 180476898929579L; + private static final long serialVersionUID = 156058914793532L; public static TriggerCreator creator( final URI callbackUrl, final String triggerValue, - final Trigger.UsageCategory usageCategory + final String usageCategory ) { return new TriggerCreator(callbackUrl, triggerValue, usageCategory); } @@ -52,7 +52,7 @@ public static TriggerCreator creator( final String pathAccountSid, final URI callbackUrl, final String triggerValue, - final Trigger.UsageCategory usageCategory + final String usageCategory ) { return new TriggerCreator( pathAccountSid, @@ -160,7 +160,7 @@ public static Trigger fromJson( private final Trigger.TriggerField triggerBy; private final String triggerValue; private final String uri; - private final Trigger.UsageCategory usageCategory; + private final String usageCategory; private final String usageRecordUri; @JsonCreator @@ -179,9 +179,7 @@ private Trigger( @JsonProperty("trigger_by") final Trigger.TriggerField triggerBy, @JsonProperty("trigger_value") final String triggerValue, @JsonProperty("uri") final String uri, - @JsonProperty( - "usage_category" - ) final Trigger.UsageCategory usageCategory, + @JsonProperty("usage_category") final String usageCategory, @JsonProperty("usage_record_uri") final String usageRecordUri ) { this.accountSid = accountSid; @@ -258,7 +256,7 @@ public final String getUri() { return this.uri; } - public final Trigger.UsageCategory getUsageCategory() { + public final String getUsageCategory() { return this.usageCategory; } @@ -362,945 +360,4 @@ public static TriggerField forValue(final String value) { return Promoter.enumFromString(value, TriggerField.values()); } } - - public enum UsageCategory { - A2P_10DLC_REGISTRATIONFEES_BRANDREGISTRATION( - "a2p-10dlc-registrationfees-brandregistration" - ), - A2P_10DLC_REGISTRATIONFEES_BV("a2p-10dlc-registrationfees-bv"), - A2P_10DLC_REGISTRATIONFEES_CAMPAIGNCHARGES( - "a2p-10dlc-registrationfees-campaigncharges" - ), - A2P_10DLC_REGISTRATIONFEES_CAMPAIGNREGISTRATION( - "a2p-10dlc-registrationfees-campaignregistration" - ), - A2P_10DLC_REGISTRATIONFEES_CAMPAIGNVETTING( - "a2p-10dlc-registrationfees-campaignvetting" - ), - A2P_10DLC_REGISTRATIONFEES_MONTHLY( - "a2p-10dlc-registrationfees-monthly" - ), - A2P_10DLC_REGISTRATIONFEES_ONETIME( - "a2p-10dlc-registrationfees-onetime" - ), - A2P_REGISTRATION_FEES("a2p-registration-fees"), - ACCOUNT_SECURITY("account-security"), - AGENT_CONFERENCE("agent-conference"), - AGENT_COPILOT("agent-copilot"), - AGENT_COPILOT_MESSAGES("agent-copilot-messages"), - AGENT_COPILOT_PARTICIPANT_MINUTES("agent-copilot-participant-minutes"), - AI_ASSISTANTS("ai-assistants"), - AI_ASSISTANTS_VOICE("ai-assistants-voice"), - AMAZON_POLLY("amazon-polly"), - ANSWERING_MACHINE_DETECTION("answering-machine-detection"), - ASSETS("assets"), - AUDIENCE_MINUTES("audience-minutes"), - AUDIENCE_MINUTES_AUDIO("audience-minutes-audio"), - AUTHY_AUTHENTICATIONS("authy-authentications"), - AUTHY_CALLS_OUTBOUND("authy-calls-outbound"), - AUTHY_EMAIL_AUTHENTICATIONS("authy-email-authentications"), - AUTHY_MONTHLY_FEES("authy-monthly-fees"), - AUTHY_OUTBOUND_EMAIL("authy-outbound-email"), - AUTHY_PHONE_INTELLIGENCE("authy-phone-intelligence"), - AUTHY_PHONE_VERIFICATIONS("authy-phone-verifications"), - AUTHY_SMS_OUTBOUND("authy-sms-outbound"), - AUTHY_VERIFY_EMAIL_VERIFICATIONS("authy-verify-email-verifications"), - AUTHY_VERIFY_OUTBOUND_EMAIL("authy-verify-outbound-email"), - AUTOPILOT("autopilot"), - AUTOPILOT_HOME_ASSISTANTS("autopilot-home-assistants"), - AUTOPILOT_MESSAGING("autopilot-messaging"), - AUTOPILOT_OTHER("autopilot-other"), - AUTOPILOT_VOICE("autopilot-voice"), - BASIC_PEER_TO_PEER_ROOMS_PARTICIPANT_MINUTES( - "basic-peer-to-peer-rooms-participant-minutes" - ), - BRANDED_CALLING("branded-calling"), - BUNDLE_SMS_BUCKET("bundle-sms-bucket"), - BUNDLE_SUBSCRIPTION_FEES("bundle-subscription-fees"), - CALL_FORWARDING_LOOKUPS("call-forwarding-lookups"), - CALL_PROGESS_EVENTS("call-progess-events"), - CALLERIDLOOKUPS("calleridlookups"), - CALLS("calls"), - CALLS_CLIENT("calls-client"), - CALLS_EMERGENCY("calls-emergency"), - CALLS_GLOBALCONFERENCE("calls-globalconference"), - CALLS_INBOUND("calls-inbound"), - CALLS_INBOUND_LOCAL("calls-inbound-local"), - CALLS_INBOUND_MOBILE("calls-inbound-mobile"), - CALLS_INBOUND_TOLLFREE("calls-inbound-tollfree"), - CALLS_INBOUND_TOLLFREE_LOCAL("calls-inbound-tollfree-local"), - CALLS_INBOUND_TOLLFREE_MOBILE("calls-inbound-tollfree-mobile"), - CALLS_MEDIA_STREAM_MINUTES("calls-media-stream-minutes"), - CALLS_OUTBOUND("calls-outbound"), - CALLS_PAY_VERB_TRANSACTIONS("calls-pay-verb-transactions"), - CALLS_RECORDINGS("calls-recordings"), - CALLS_SIP("calls-sip"), - CALLS_SIP_INBOUND("calls-sip-inbound"), - CALLS_SIP_OUTBOUND("calls-sip-outbound"), - CALLS_TEXT_TO_SPEECH("calls-text-to-speech"), - CALLS_TRANSFERS("calls-transfers"), - CARRIER_LOOKUPS("carrier-lookups"), - CATEGORY("category"), - CHANNELS("channels"), - CHANNELS_MESSAGING("channels-messaging"), - CHANNELS_MESSAGING_INBOUND("channels-messaging-inbound"), - CHANNELS_MESSAGING_OUTBOUND("channels-messaging-outbound"), - CHANNELS_WHATSAPP("channels-whatsapp"), - CHANNELS_WHATSAPP_CONVERSATION_AUTHENTICATION( - "channels-whatsapp-conversation-authentication" - ), - CHANNELS_WHATSAPP_CONVERSATION_FREE( - "channels-whatsapp-conversation-free" - ), - CHANNELS_WHATSAPP_CONVERSATION_MARKETING( - "channels-whatsapp-conversation-marketing" - ), - CHANNELS_WHATSAPP_CONVERSATION_SERVICE( - "channels-whatsapp-conversation-service" - ), - CHANNELS_WHATSAPP_CONVERSATION_UTILITY( - "channels-whatsapp-conversation-utility" - ), - CHANNELS_WHATSAPP_INBOUND("channels-whatsapp-inbound"), - CHANNELS_WHATSAPP_OUTBOUND("channels-whatsapp-outbound"), - CHANNELS_WHATSAPP_SERVICE("channels-whatsapp-service"), - CHANNELS_WHATSAPP_TEMPLATE_AUTHENTICATION( - "channels-whatsapp-template-authentication" - ), - CHANNELS_WHATSAPP_TEMPLATE_MARKETING( - "channels-whatsapp-template-marketing" - ), - CHANNELS_WHATSAPP_TEMPLATE_SERVICE( - "channels-whatsapp-template-service" - ), - CHANNELS_WHATSAPP_TEMPLATE_UTILITY( - "channels-whatsapp-template-utility" - ), - CHAT_VIRTUAL_AGENT("chat-virtual-agent"), - CONVERSATION_RELAY("conversation-relay"), - CONVERSATIONS("conversations"), - CONVERSATIONS_API_REQUESTS("conversations-api-requests"), - CONVERSATIONS_CONVERSATION_EVENTS("conversations-conversation-events"), - CONVERSATIONS_ENDPOINT_CONNECTIVITY( - "conversations-endpoint-connectivity" - ), - CONVERSATIONS_EVENTS("conversations-events"), - CONVERSATIONS_PARTICIPANT_EVENTS("conversations-participant-events"), - CONVERSATIONS_PARTICIPANTS("conversations-participants"), - CPS("cps"), - CREDIT_TRANSFER("credit-transfer"), - EMAIL("email"), - EMERGING_TECH("emerging-tech"), - ENGAGEMENT_SUITE_PACKAGED_PLANS("engagement-suite-packaged-plans"), - ENHANCED_LINE_TYPE_LOOKUPS("enhanced-line-type-lookups"), - ENTERPRISE("enterprise"), - EVENTS("events"), - EXPERIMENT_FRANCE_SMS("experiment-france-sms"), - EXPERIMENT_INDIA_SMS("experiment-india-sms"), - EXPERIMENT_UK_SMS("experiment-uk-sms"), - FAILED_MESSAGE_PROCESSING_FEE("failed-message-processing-fee"), - FLEX("flex"), - FLEX_ACTIVE_USER_HOURS("flex-active-user-hours"), - FLEX_CONCURRENT_USERS("flex-concurrent-users"), - FLEX_CONVERSATIONAL_INSIGHTS("flex-conversational-insights"), - FLEX_CONVERSATIONAL_INSIGHTS_MESSAGES( - "flex-conversational-insights-messages" - ), - FLEX_CONVERSATIONAL_INSIGHTS_VOICE_MINUTES( - "flex-conversational-insights-voice-minutes" - ), - FLEX_EMAIL_USAGE("flex-email-usage"), - FLEX_MESSAGING_USAGE("flex-messaging-usage"), - FLEX_PARTNER_SPINSCI("flex-partner-spinsci"), - FLEX_PARTNER_XCELERATE("flex-partner-xcelerate"), - FLEX_RESELLER_ECOSYSTEM("flex-reseller-ecosystem"), - FLEX_UNIQUE_USER("flex-unique-user"), - FLEX_USAGE("flex-usage"), - FLEX_USERS("flex-users"), - FLEX_VOICE_MINUTE("flex-voice-minute"), - FLEX_YTICA("flex-ytica"), - FRAUD_LOOKUPS("fraud-lookups"), - FRONTLINE("frontline"), - FRONTLINE_USERS("frontline-users"), - FUNCTIONS("functions"), - GENERIC_PAY_TRANSACTIONS("generic-pay-transactions"), - GROUP_ROOMS("group-rooms"), - GROUP_ROOMS_DATA_TRACK("group-rooms-data-track"), - GROUP_ROOMS_ENCRYPTED_MEDIA_RECORDED( - "group-rooms-encrypted-media-recorded" - ), - GROUP_ROOMS_MEDIA_DOWNLOADED("group-rooms-media-downloaded"), - GROUP_ROOMS_MEDIA_RECORDED("group-rooms-media-recorded"), - GROUP_ROOMS_MEDIA_ROUTED("group-rooms-media-routed"), - GROUP_ROOMS_MEDIA_STORED("group-rooms-media-stored"), - GROUP_ROOMS_PARTICIPANT_MINUTES("group-rooms-participant-minutes"), - GROUP_ROOMS_RECORDED_MINUTES("group-rooms-recorded-minutes"), - IP_MESSAGING("ip-messaging"), - IP_MESSAGING_COMMANDS("ip-messaging-commands"), - IP_MESSAGING_DATA_STORAGE("ip-messaging-data-storage"), - IP_MESSAGING_DATA_TRANSFER("ip-messaging-data-transfer"), - IP_MESSAGING_ENDPOINT_CONNECTIVITY( - "ip-messaging-endpoint-connectivity" - ), - IVR_VIRTUAL_AGENT_CUSTOM_VOICES("ivr-virtual-agent-custom-voices"), - IVR_VIRTUAL_AGENT_GENAI("ivr-virtual-agent-genai"), - LINE_STATUS_LOOKUPS("line-status-lookups"), - LIVE_ACTIVITY_LOOKUPS("live-activity-lookups"), - LOOKUP_BUCKET_ADJUSTMENT("lookup-bucket-adjustment"), - LOOKUP_IDENTITY_MATCH("lookup-identity-match"), - LOOKUPS("lookups"), - MARKETPLACE("marketplace"), - MARKETPLACE_ALGORITHMIA_NAMED_ENTITY_RECOGNITION( - "marketplace-algorithmia-named-entity-recognition" - ), - MARKETPLACE_CADENCE_TRANSCRIPTION("marketplace-cadence-transcription"), - MARKETPLACE_CADENCE_TRANSLATION("marketplace-cadence-translation"), - MARKETPLACE_CAPIO_SPEECH_TO_TEXT("marketplace-capio-speech-to-text"), - MARKETPLACE_CONVRIZA_ABABA("marketplace-convriza-ababa"), - MARKETPLACE_DEEPGRAM_PHRASE_DETECTOR( - "marketplace-deepgram-phrase-detector" - ), - MARKETPLACE_DEEPGRAM_TRANSCRIPTION( - "marketplace-deepgram-transcription" - ), - MARKETPLACE_DEEPGRAM_TRANSCRIPTION_BASE( - "marketplace-deepgram-transcription-base" - ), - MARKETPLACE_DEEPGRAM_TRANSSCRIPTION_ENHANCED( - "marketplace-deepgram-transscription-enhanced" - ), - MARKETPLACE_DIGITAL_SEGMENT_BUSINESS_INFO( - "marketplace-digital-segment-business-info" - ), - MARKETPLACE_FACEBOOK_OFFLINE_CONVERSIONS( - "marketplace-facebook-offline-conversions" - ), - MARKETPLACE_GOOGLE_SPEECH_TO_TEXT("marketplace-google-speech-to-text"), - MARKETPLACE_IBM_WATSON_MESSAGE_INSIGHTS( - "marketplace-ibm-watson-message-insights" - ), - MARKETPLACE_IBM_WATSON_MESSAGE_SENTIMENT( - "marketplace-ibm-watson-message-sentiment" - ), - MARKETPLACE_IBM_WATSON_RECORDING_ANALYSIS( - "marketplace-ibm-watson-recording-analysis" - ), - MARKETPLACE_IBM_WATSON_TONE_ANALYZER( - "marketplace-ibm-watson-tone-analyzer" - ), - MARKETPLACE_ICEHOOK_SYSTEMS_SCOUT("marketplace-icehook-systems-scout"), - MARKETPLACE_INFOGROUP_DATAAXLE_BIZINFO( - "marketplace-infogroup-dataaxle-bizinfo" - ), - MARKETPLACE_KEEN_IO_CONTACT_CENTER_ANALYTICS( - "marketplace-keen-io-contact-center-analytics" - ), - MARKETPLACE_MARCHEX_CLEANCALL("marketplace-marchex-cleancall"), - MARKETPLACE_MARCHEX_RECORDING_ANALYSIS( - "marketplace-marchex-recording-analysis" - ), - MARKETPLACE_MARCHEX_SENTIMENT_ANALYSIS_FOR_SMS( - "marketplace-marchex-sentiment-analysis-for-sms" - ), - MARKETPLACE_MARKETPLACE_NEXTCALLER_SOCIAL_ID( - "marketplace-marketplace-nextcaller-social-id" - ), - MARKETPLACE_MOBILE_COMMONS_OPT_OUT_CLASSIFIER( - "marketplace-mobile-commons-opt-out-classifier" - ), - MARKETPLACE_NEXIWAVE_VOICEMAIL_TO_TEXT( - "marketplace-nexiwave-voicemail-to-text" - ), - MARKETPLACE_NEXTCALLER_ADVANCED_CALLER_IDENTIFICATION( - "marketplace-nextcaller-advanced-caller-identification" - ), - MARKETPLACE_NOMOROBO_SPAM_SCORE("marketplace-nomorobo-spam-score"), - MARKETPLACE_PAY_ADDONS("marketplace-pay-addons"), - MARKETPLACE_PAY_ADDONS_BASECOMMERCE_PAY_CONNECTOR( - "marketplace-pay-addons-basecommerce-pay-connector" - ), - MARKETPLACE_PAY_ADDONS_BRAINTREE_PAY_CONNECTOR( - "marketplace-pay-addons-braintree-pay-connector" - ), - MARKETPLACE_PAY_ADDONS_CARDCONNECT_PAY_CONNECTOR( - "marketplace-pay-addons-cardconnect-pay-connector" - ), - MARKETPLACE_PAY_ADDONS_CHASE_PAY_CONNECTOR( - "marketplace-pay-addons-chase-pay-connector" - ), - MARKETPLACE_PAY_ADDONS_SHUTTLE_PAY_CONNECTOR( - "marketplace-pay-addons-shuttle-pay-connector" - ), - MARKETPLACE_PAY_ADDONS_STRIPE_PAY_CONNECTOR( - "marketplace-pay-addons-stripe-pay-connector" - ), - MARKETPLACE_PAYFONE_TCPA_COMPLIANCE( - "marketplace-payfone-tcpa-compliance" - ), - MARKETPLACE_POLY_AI_CONNECTOR("marketplace-poly-ai-connector"), - MARKETPLACE_REALPHONEVALIDATION("marketplace-realphonevalidation"), - MARKETPLACE_REMEETING_AUTOMATIC_SPEECH_RECOGNITION( - "marketplace-remeeting-automatic-speech-recognition" - ), - MARKETPLACE_SPOKE_PHONE_LICENSE_PRO( - "marketplace-spoke-phone-license-pro" - ), - MARKETPLACE_SPOKE_PHONE_LICENSE_STANDARD( - "marketplace-spoke-phone-license-standard" - ), - MARKETPLACE_TCPA_DEFENSE_SOLUTIONS_BLACKLIST_FEED( - "marketplace-tcpa-defense-solutions-blacklist-feed" - ), - MARKETPLACE_TELO_OPENCNAM("marketplace-telo-opencnam"), - MARKETPLACE_TRESTLE_SOLUTIONS_CALLER_IDENTIFICATION( - "marketplace-trestle-solutions-caller-identification" - ), - MARKETPLACE_TRUECNAM_TRUE_SPAM("marketplace-truecnam-true-spam"), - MARKETPLACE_TWILIO_CALLER_NAME_LOOKUP_US( - "marketplace-twilio-caller-name-lookup-us" - ), - MARKETPLACE_TWILIO_CARRIER_INFORMATION_LOOKUP( - "marketplace-twilio-carrier-information-lookup" - ), - MARKETPLACE_VOICEBASE_PCI("marketplace-voicebase-pci"), - MARKETPLACE_VOICEBASE_TRANSCRIPTION( - "marketplace-voicebase-transcription" - ), - MARKETPLACE_VOICEBASE_TRANSCRIPTION_CUSTOM_VOCABULARY( - "marketplace-voicebase-transcription-custom-vocabulary" - ), - MARKETPLACE_WEB_PURIFY_PROFANITY_FILTER( - "marketplace-web-purify-profanity-filter" - ), - MARKETPLACE_WHITEPAGES_PRO_CALLER_IDENTIFICATION( - "marketplace-whitepages-pro-caller-identification" - ), - MARKETPLACE_WHITEPAGES_PRO_PHONE_INTELLIGENCE( - "marketplace-whitepages-pro-phone-intelligence" - ), - MARKETPLACE_WHITEPAGES_PRO_PHONE_REPUTATION( - "marketplace-whitepages-pro-phone-reputation" - ), - MARKETPLACE_WOLFARM_SPOKEN_RESULTS( - "marketplace-wolfarm-spoken-results" - ), - MARKETPLACE_WOLFRAM_SHORT_ANSWER("marketplace-wolfram-short-answer"), - MARKETPLACE_YTICA_CONTACT_CENTER_REPORTING_ANALYTICS( - "marketplace-ytica-contact-center-reporting-analytics" - ), - MARKETPLAY_PAY_ADDONS_SHUTTLE_PAY_CONNECTOR( - "marketplay-pay-addons-shuttle-pay-connector" - ), - MEDIA_COMPOSER_MINUTES("media-composer-minutes"), - MEDIASTORAGE("mediastorage"), - MIN_SPEND_ADJUSTMENTS("min-spend-adjustments"), - MMS("mms"), - MMS_INBOUND("mms-inbound"), - MMS_INBOUND_LONGCODE("mms-inbound-longcode"), - MMS_INBOUND_SHORTCODE("mms-inbound-shortcode"), - MMS_INBOUND_TOLL_FREE("mms-inbound-toll-free"), - MMS_MESSAGES_CARRIERFEES("mms-messages-carrierfees"), - MMS_OUTBOUND("mms-outbound"), - MMS_OUTBOUND_LONGCODE("mms-outbound-longcode"), - MMS_OUTBOUND_SHORTCODE("mms-outbound-shortcode"), - MMS_OUTBOUND_TOLLFREE("mms-outbound-tollfree"), - MONITOR("monitor"), - MONITOR_READS("monitor-reads"), - MONITOR_STORAGE("monitor-storage"), - MONITOR_WRITES("monitor-writes"), - NOTIFY("notify"), - NOTIFY_ACTIONS_ATTEMPTS("notify-actions-attempts"), - NOTIFY_CHANNELS("notify-channels"), - NUMBER_FORMAT_LOOKUPS("number-format-lookups"), - PCHAT("pchat"), - PCHAT_ACTIONS("pchat-actions"), - PCHAT_APS("pchat-aps"), - PCHAT_CONV_MED_STORAGE("pchat-conv-med-storage"), - PCHAT_MESSAGES("pchat-messages"), - PCHAT_NOTIFICATIONS("pchat-notifications"), - PCHAT_READS("pchat-reads"), - PCHAT_USERS("pchat-users"), - PEER_TO_PEER_ROOMS_PARTICIPANT_MINUTES( - "peer-to-peer-rooms-participant-minutes" - ), - PFAX("pfax"), - PFAX_MINUTES("pfax-minutes"), - PFAX_MINUTES_INBOUND("pfax-minutes-inbound"), - PFAX_MINUTES_OUTBOUND("pfax-minutes-outbound"), - PFAX_PAGES("pfax-pages"), - PHONE_QUALITY_SCORE_LOOKUPS("phone-quality-score-lookups"), - PHONENUMBERS("phonenumbers"), - PHONENUMBERS_CPS("phonenumbers-cps"), - PHONENUMBERS_EMERGENCY("phonenumbers-emergency"), - PHONENUMBERS_LOCAL("phonenumbers-local"), - PHONENUMBERS_MOBILE("phonenumbers-mobile"), - PHONENUMBERS_PORTING("phonenumbers-porting"), - PHONENUMBERS_SETUPS("phonenumbers-setups"), - PHONENUMBERS_TOLLFREE("phonenumbers-tollfree"), - PREMIUMSUPPORT("premiumsupport"), - PREMIUMSUPPORT_PERCENTAGE_SPEND("premiumsupport-percentage-spend"), - PROGRAMMABLEVOICE_PLATFORM("programmablevoice-platform"), - PROGRAMMABLEVOICECONN_CLIENTSDK("programmablevoiceconn-clientsdk"), - PROGRAMMABLEVOICECONN_CLIENTSDK_INBOUND( - "programmablevoiceconn-clientsdk-inbound" - ), - PROGRAMMABLEVOICECONN_CLIENTSDK_OUTBOUND( - "programmablevoiceconn-clientsdk-outbound" - ), - PROGRAMMABLEVOICECONN_ONNET("programmablevoiceconn-onnet"), - PROGRAMMABLEVOICECONN_ONNET_INBOUND( - "programmablevoiceconn-onnet-inbound" - ), - PROGRAMMABLEVOICECONN_ONNET_OUTBOUND( - "programmablevoiceconn-onnet-outbound" - ), - PROGRAMMABLEVOICECONN_SIP("programmablevoiceconn-sip"), - PROGRAMMABLEVOICECONN_SIP_INBOUND("programmablevoiceconn-sip-inbound"), - PROGRAMMABLEVOICECONN_SIP_OUTBOUND( - "programmablevoiceconn-sip-outbound" - ), - PROGRAMMABLEVOICECONNECTIVITY("programmablevoiceconnectivity"), - PROXY("proxy"), - PROXY_ACTIVE_SESSIONS("proxy-active-sessions"), - PROXY_BUCKET_ADJUSTMENT("proxy-bucket-adjustment"), - PROXY_LICENSES("proxy-licenses"), - PSTNCONNECTIVITY("pstnconnectivity"), - PSTNCONNECTIVITY_INBOUND("pstnconnectivity-inbound"), - PSTNCONNECTIVITY_OUTBOUND("pstnconnectivity-outbound"), - PV("pv"), - PV_BASIC_ROOMS("pv-basic-rooms"), - PV_COMPOSITION_MEDIA_DOWNLOADED("pv-composition-media-downloaded"), - PV_COMPOSITION_MEDIA_ENCRYPTED("pv-composition-media-encrypted"), - PV_COMPOSITION_MEDIA_STORED("pv-composition-media-stored"), - PV_COMPOSITION_MINUTES("pv-composition-minutes"), - PV_RECORDING_COMPOSITIONS("pv-recording-compositions"), - PV_ROOM_PARTICIPANTS("pv-room-participants"), - PV_ROOM_PARTICIPANTS_AU1("pv-room-participants-au1"), - PV_ROOM_PARTICIPANTS_BR1("pv-room-participants-br1"), - PV_ROOM_PARTICIPANTS_IE1("pv-room-participants-ie1"), - PV_ROOM_PARTICIPANTS_JP1("pv-room-participants-jp1"), - PV_ROOM_PARTICIPANTS_SG1("pv-room-participants-sg1"), - PV_ROOM_PARTICIPANTS_US1("pv-room-participants-us1"), - PV_ROOM_PARTICIPANTS_US2("pv-room-participants-us2"), - PV_ROOMS("pv-rooms"), - PV_SIP_ENDPOINT_REGISTRATIONS("pv-sip-endpoint-registrations"), - RCS_MESSAGES("rcs-messages"), - REASSIGNED_NUMBER("reassigned-number"), - RECORDINGS("recordings"), - RECORDINGSTORAGE("recordingstorage"), - SHORTCODES("shortcodes"), - SHORTCODES_CUSTOMEROWNED("shortcodes-customerowned"), - SHORTCODES_MMS_ENABLEMENT("shortcodes-mms-enablement"), - SHORTCODES_MPS("shortcodes-mps"), - SHORTCODES_RANDOM("shortcodes-random"), - SHORTCODES_SETUP_FEES("shortcodes-setup-fees"), - SHORTCODES_UK("shortcodes-uk"), - SHORTCODES_VANITY("shortcodes-vanity"), - SIM_SWAP_LOOKUPS("sim-swap-lookups"), - SIP_SECURE_MEDIA("sip-secure-media"), - SMALL_GROUP_ROOMS("small-group-rooms"), - SMALL_GROUP_ROOMS_DATA_TRACK("small-group-rooms-data-track"), - SMALL_GROUP_ROOMS_PARTICIPANT_MINUTES( - "small-group-rooms-participant-minutes" - ), - SMS("sms"), - SMS_INBOUND("sms-inbound"), - SMS_INBOUND_LONGCODE("sms-inbound-longcode"), - SMS_INBOUND_SHORTCODE("sms-inbound-shortcode"), - SMS_INBOUND_TOLLFREE("sms-inbound-tollfree"), - SMS_MESSAGES_CARRIERFEES("sms-messages-carrierfees"), - SMS_MESSAGES_FEATURES("sms-messages-features"), - SMS_MESSAGES_FEATURES_ENGAGEMENT_SUITE( - "sms-messages-features-engagement-suite" - ), - SMS_MESSAGES_FEATURES_MESSAGE_REDACTION( - "sms-messages-features-message-redaction" - ), - SMS_MESSAGES_FEATURES_SENDERID("sms-messages-features-senderid"), - SMS_MPS("sms-mps"), - SMS_MPS_SHORTCODE("sms-mps-shortcode"), - SMS_MPS_TOLLFREE("sms-mps-tollfree"), - SMS_MPS_TOLLFREE_SETUP("sms-mps-tollfree-setup"), - SMS_NATIONAL_REGULATORY_PROTECTION( - "sms-national-regulatory-protection" - ), - SMS_OUTBOUND("sms-outbound"), - SMS_OUTBOUND_CONTENT_INSPECTION("sms-outbound-content-inspection"), - SMS_OUTBOUND_LONGCODE("sms-outbound-longcode"), - SMS_OUTBOUND_SHORTCODE("sms-outbound-shortcode"), - SMS_OUTBOUND_TOLLFREE("sms-outbound-tollfree"), - SMS_PUMPING_PROTECTION("sms-pumping-protection"), - SMS_PUMPING_RISK("sms-pumping-risk"), - SMSMESSAGES_BUCKET_ADJUSTMENTS("smsmessages-bucket-adjustments"), - SMSMESSAGES_OUTBOUND_DOMESTIC("smsmessages-outbound-domestic"), - SPEECH_RECOGNITION("speech-recognition"), - STUDIO_ENGAGEMENTS("studio-engagements"), - SYNC("sync"), - SYNC_ACTIONS("sync-actions"), - SYNC_ENDPOINT_HOURS("sync-endpoint-hours"), - SYNC_ENDPOINT_HOURS_ABOVE_DAILY_CAP( - "sync-endpoint-hours-above-daily-cap" - ), - TASKROUTER_TASKS("taskrouter-tasks"), - TOTALPRICE("totalprice"), - TRANSCRIPTIONS("transcriptions"), - TRUNKING_CPS("trunking-cps"), - TRUNKING_EMERGENCY_CALLS("trunking-emergency-calls"), - TRUNKING_ORIGINATION("trunking-origination"), - TRUNKING_ORIGINATION_LOCAL("trunking-origination-local"), - TRUNKING_ORIGINATION_MOBILE("trunking-origination-mobile"), - TRUNKING_ORIGINATION_TOLLFREE("trunking-origination-tollfree"), - TRUNKING_RECORDINGS("trunking-recordings"), - TRUNKING_SECURE("trunking-secure"), - TRUNKING_TERMINATION("trunking-termination"), - TTS_GOOGLE("tts-google"), - TURNMEGABYTES("turnmegabytes"), - TURNMEGABYTES_AUSTRALIA("turnmegabytes-australia"), - TURNMEGABYTES_BRASIL("turnmegabytes-brasil"), - TURNMEGABYTES_GERMANY("turnmegabytes-germany"), - TURNMEGABYTES_INDIA("turnmegabytes-india"), - TURNMEGABYTES_IRELAND("turnmegabytes-ireland"), - TURNMEGABYTES_JAPAN("turnmegabytes-japan"), - TURNMEGABYTES_SINGAPORE("turnmegabytes-singapore"), - TURNMEGABYTES_USEAST("turnmegabytes-useast"), - TURNMEGABYTES_USWEST("turnmegabytes-uswest"), - TWILIO_FOR_SALESFORCE("twilio-for-salesforce"), - TWILIO_FOR_SALESFORCE_LICENSES("twilio-for-salesforce-licenses"), - TWILIO_INTERCONNECT("twilio-interconnect"), - TWIML("twiml"), - USAGE_FLEX_VIDEO("usage-flex-video"), - USAGE_FUNCTIONS("usage-functions"), - USAGE_RCS_BASIC_MESSAGES_OUTBOUND("usage-rcs-basic-messages-outbound"), - USAGE_RCS_MESSAGES("usage-rcs-messages"), - USAGE_RCS_MESSAGES_INBOUND("usage-rcs-messages-inbound"), - USAGE_RCS_MESSAGING_CARRIER_FEES("usage-rcs-messaging-carrier-fees"), - USAGE_RCS_SINGLE_MESSAGES_OUTBOUND( - "usage-rcs-single-messages-outbound" - ), - VERIFY_PACKAGE_PLANS("verify-package-plans"), - VERIFY_PUSH("verify-push"), - VERIFY_SNA("verify-sna"), - VERIFY_TOTP("verify-totp"), - VERIFY_VOICE_SMS("verify-voice-sms"), - VERIFY_WHATSAPP_CONVERSATIONS_BUSINESS_INITIATED( - "verify-whatsapp-conversations-business-initiated" - ), - VERIFY_WHATSAPP_TEMPLATE_BUSINESS_INITIATED( - "verify-whatsapp-template-business-initiated" - ), - VIDEO_RECORDINGS("video-recordings"), - VIDEO_ROOMS_TURN_MEGABYTES("video-rooms-turn-megabytes"), - VIRTUAL_AGENT("virtual-agent"), - VOICE_INSIGHTS("voice-insights"), - VOICE_INSIGHTS_CLIENT_INSIGHTS_ON_DEMAND_MINUTE( - "voice-insights-client-insights-on-demand-minute" - ), - VOICE_INSIGHTS_PTSN_INSIGHTS_ON_DEMAND_MINUTE( - "voice-insights-ptsn-insights-on-demand-minute" - ), - VOICE_INSIGHTS_SIP_INTERFACE_INSIGHTS_ON_DEMAND_MINUTE( - "voice-insights-sip-interface-insights-on-demand-minute" - ), - VOICE_INSIGHTS_SIP_TRUNKING_INSIGHTS_ON_DEMAND_MINUTE( - "voice-insights-sip-trunking-insights-on-demand-minute" - ), - VOICE_INTELLIGENCE("voice-intelligence"), - VOICE_INTELLIGENCE_EIP_OPERATORS("voice-intelligence-eip-operators"), - VOICE_INTELLIGENCE_OPERATORS("voice-intelligence-operators"), - VOICE_INTELLIGENCE_TRANSCRIPTION("voice-intelligence-transcription"), - WDS("wds"), - WIRELESS("wireless"), - WIRELESS_DATA("wireless-data"), - WIRELESS_DATA_PAYG("wireless-data-payg"), - WIRELESS_DATA_PAYG_AFRICA("wireless-data-payg-africa"), - WIRELESS_DATA_PAYG_ASIA("wireless-data-payg-asia"), - WIRELESS_DATA_PAYG_CENTRALANDSOUTHAMERICA( - "wireless-data-payg-centralandsouthamerica" - ), - WIRELESS_DATA_PAYG_EUROPE("wireless-data-payg-europe"), - WIRELESS_DATA_PAYG_NORTHAMERICA("wireless-data-payg-northamerica"), - WIRELESS_DATA_PAYG_OCEANIA("wireless-data-payg-oceania"), - WIRELESS_DATA_QUOTA1("wireless-data-quota1"), - WIRELESS_DATA_QUOTA1_AFRICA("wireless-data-quota1-africa"), - WIRELESS_DATA_QUOTA1_ASIA("wireless-data-quota1-asia"), - WIRELESS_DATA_QUOTA1_CENTRALANDSOUTHAMERICA( - "wireless-data-quota1-centralandsouthamerica" - ), - WIRELESS_DATA_QUOTA1_EUROPE("wireless-data-quota1-europe"), - WIRELESS_DATA_QUOTA1_NORTHAMERICA("wireless-data-quota1-northamerica"), - WIRELESS_DATA_QUOTA1_OCEANIA("wireless-data-quota1-oceania"), - WIRELESS_DATA_QUOTA10("wireless-data-quota10"), - WIRELESS_DATA_QUOTA10_AFRICA("wireless-data-quota10-africa"), - WIRELESS_DATA_QUOTA10_ASIA("wireless-data-quota10-asia"), - WIRELESS_DATA_QUOTA10_CENTRALANDSOUTHAMERICA( - "wireless-data-quota10-centralandsouthamerica" - ), - WIRELESS_DATA_QUOTA10_EUROPE("wireless-data-quota10-europe"), - WIRELESS_DATA_QUOTA10_NORTHAMERICA( - "wireless-data-quota10-northamerica" - ), - WIRELESS_DATA_QUOTA10_OCEANIA("wireless-data-quota10-oceania"), - WIRELESS_DATA_QUOTA50("wireless-data-quota50"), - WIRELESS_DATA_QUOTA50_AFRICA("wireless-data-quota50-africa"), - WIRELESS_DATA_QUOTA50_ASIA("wireless-data-quota50-asia"), - WIRELESS_DATA_QUOTA50_CENTRALANDSOUTHAMERICA( - "wireless-data-quota50-centralandsouthamerica" - ), - WIRELESS_DATA_QUOTA50_EUROPE("wireless-data-quota50-europe"), - WIRELESS_DATA_QUOTA50_NORTHAMERICA( - "wireless-data-quota50-northamerica" - ), - WIRELESS_DATA_QUOTA50_OCEANIA("wireless-data-quota50-oceania"), - WIRELESS_DATA_QUOTACUSTOM("wireless-data-quotacustom"), - WIRELESS_DATA_QUOTACUSTOM_AFRICA("wireless-data-quotacustom-africa"), - WIRELESS_DATA_QUOTACUSTOM_ASIA("wireless-data-quotacustom-asia"), - WIRELESS_DATA_QUOTACUSTOM_CENTRALANDSOUTHAMERICA( - "wireless-data-quotacustom-centralandsouthamerica" - ), - WIRELESS_DATA_QUOTACUSTOM_EUROPE("wireless-data-quotacustom-europe"), - WIRELESS_DATA_QUOTACUSTOM_NORTHAMERICA( - "wireless-data-quotacustom-northamerica" - ), - WIRELESS_DATA_QUOTACUSTOM_OCEANIA("wireless-data-quotacustom-oceania"), - WIRELESS_MRC_PAYG("wireless-mrc-payg"), - WIRELESS_MRC_QUOTA1("wireless-mrc-quota1"), - WIRELESS_MRC_QUOTA10("wireless-mrc-quota10"), - WIRELESS_MRC_QUOTA50("wireless-mrc-quota50"), - WIRELESS_MRC_QUOTACUSTOM("wireless-mrc-quotacustom"), - WIRELESS_ORDERS("wireless-orders"), - WIRELESS_ORDERS_ARTWORK("wireless-orders-artwork"), - WIRELESS_ORDERS_BULK("wireless-orders-bulk"), - WIRELESS_ORDERS_ESIM("wireless-orders-esim"), - WIRELESS_ORDERS_STARTER("wireless-orders-starter"), - WIRELESS_QUOTAS("wireless-quotas"), - WIRELESS_SMS_AFRICA("wireless-sms-africa"), - WIRELESS_SMS_ASIA("wireless-sms-asia"), - WIRELESS_SMS_CENTRALANDSOUTHAMERICA( - "wireless-sms-centralandsouthamerica" - ), - WIRELESS_SMS_EUROPE("wireless-sms-europe"), - WIRELESS_SMS_NORTHAMERICA("wireless-sms-northamerica"), - WIRELESS_SMS_OCEANIA("wireless-sms-oceania"), - WIRELESS_SUPER_SIM("wireless-super-sim"), - WIRELESS_SUPER_SIM_DATA("wireless-super-sim-data"), - WIRELESS_SUPER_SIM_DATA_NORTH_AMERICA_USA( - "wireless-super-sim-data-north-america-usa" - ), - WIRELESS_SUPER_SIM_DATA_PAYG("wireless-super-sim-data-payg"), - WIRELESS_SUPER_SIM_DATA_PAYG_EUROPE( - "wireless-super-sim-data-payg-europe" - ), - WIRELESS_SUPER_SIM_DATA_PAYG_NORTH_AMERICA( - "wireless-super-sim-data-payg-north-america" - ), - WIRELESS_SUPER_SIM_HARDWARE("wireless-super-sim-hardware"), - WIRELESS_SUPER_SIM_HARDWARE_BULK("wireless-super-sim-hardware-bulk"), - WIRELESS_SUPER_SIM_SMSCOMMANDS("wireless-super-sim-smscommands"), - WIRELESS_SUPER_SIM_SMSCOMMANDS_AFRICA( - "wireless-super-sim-smscommands-africa" - ), - WIRELESS_SUPER_SIM_SMSCOMMANDS_ASIA( - "wireless-super-sim-smscommands-asia" - ), - WIRELESS_SUPER_SIM_SMSCOMMANDS_CENT_AND_SOUTH_AMERICA( - "wireless-super-sim-smscommands-cent-and-south-america" - ), - WIRELESS_SUPER_SIM_SMSCOMMANDS_EUROPE( - "wireless-super-sim-smscommands-europe" - ), - WIRELESS_SUPER_SIM_SMSCOMMANDS_NORTH_AMERICA( - "wireless-super-sim-smscommands-north-america" - ), - WIRELESS_SUPER_SIM_SMSCOMMANDS_OCEANIA( - "wireless-super-sim-smscommands-oceania" - ), - WIRELESS_SUPER_SIM_SUBSCRIPTION("wireless-super-sim-subscription"), - WIRELESS_SUPER_SIM_SUBSCRIPTION_PAYG( - "wireless-super-sim-subscription-payg" - ), - WIRELESS_USAGE("wireless-usage"), - WIRELESS_USAGE_COMMANDS("wireless-usage-commands"), - WIRELESS_USAGE_COMMANDS_AFRICA("wireless-usage-commands-africa"), - WIRELESS_USAGE_COMMANDS_ASIA("wireless-usage-commands-asia"), - WIRELESS_USAGE_COMMANDS_CENTRALANDSOUTHAMERICA( - "wireless-usage-commands-centralandsouthamerica" - ), - WIRELESS_USAGE_COMMANDS_EUROPE("wireless-usage-commands-europe"), - WIRELESS_USAGE_COMMANDS_HOME("wireless-usage-commands-home"), - WIRELESS_USAGE_COMMANDS_NORTHAMERICA( - "wireless-usage-commands-northamerica" - ), - WIRELESS_USAGE_COMMANDS_OCEANIA("wireless-usage-commands-oceania"), - WIRELESS_USAGE_COMMANDS_ROAMING("wireless-usage-commands-roaming"), - WIRELESS_USAGE_DATA("wireless-usage-data"), - WIRELESS_USAGE_DATA_AFRICA("wireless-usage-data-africa"), - WIRELESS_USAGE_DATA_ASIA("wireless-usage-data-asia"), - WIRELESS_USAGE_DATA_CENTRALANDSOUTHAMERICA( - "wireless-usage-data-centralandsouthamerica" - ), - WIRELESS_USAGE_DATA_CUSTOM_ADDITIONALMB( - "wireless-usage-data-custom-additionalmb" - ), - WIRELESS_USAGE_DATA_CUSTOM_FIRST5MB( - "wireless-usage-data-custom-first5mb" - ), - WIRELESS_USAGE_DATA_DOMESTIC_ROAMING( - "wireless-usage-data-domestic-roaming" - ), - WIRELESS_USAGE_DATA_EUROPE("wireless-usage-data-europe"), - WIRELESS_USAGE_DATA_INDIVIDUAL_ADDITIONALGB( - "wireless-usage-data-individual-additionalgb" - ), - WIRELESS_USAGE_DATA_INDIVIDUAL_FIRSTGB( - "wireless-usage-data-individual-firstgb" - ), - WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_CANADA( - "wireless-usage-data-international-roaming-canada" - ), - WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_INDIA( - "wireless-usage-data-international-roaming-india" - ), - WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_MEXICO( - "wireless-usage-data-international-roaming-mexico" - ), - WIRELESS_USAGE_DATA_NORTHAMERICA("wireless-usage-data-northamerica"), - WIRELESS_USAGE_DATA_OCEANIA("wireless-usage-data-oceania"), - WIRELESS_USAGE_DATA_POOLED("wireless-usage-data-pooled"), - WIRELESS_USAGE_DATA_POOLED_DOWNLINK( - "wireless-usage-data-pooled-downlink" - ), - WIRELESS_USAGE_DATA_POOLED_UPLINK("wireless-usage-data-pooled-uplink"), - WIRELESS_USAGE_MRC("wireless-usage-mrc"), - WIRELESS_USAGE_MRC_CUSTOM("wireless-usage-mrc-custom"), - WIRELESS_USAGE_MRC_INDIVIDUAL("wireless-usage-mrc-individual"), - WIRELESS_USAGE_MRC_POOLED("wireless-usage-mrc-pooled"), - WIRELESS_USAGE_MRC_SUSPENDED("wireless-usage-mrc-suspended"), - WIRELESS_USAGE_SMS("wireless-usage-sms"), - WIRELESS_USAGE_VOICE("wireless-usage-voice"), - A2P_FAST_TRACK_ONBOARDING("a2p-fast-track-onboarding"), - ADVISORY_SERVICES("advisory-services"), - ADVISORY_SERVICES_BILLED("advisory-services-billed"), - ADVISORY_SERVICES_CALL_TRACKING("advisory-services-call-tracking"), - ADVISORY_SERVICES_DATA_SERVICES("advisory-services-data-services"), - ADVISORY_SERVICES_EXPENSES("advisory-services-expenses"), - ADVISORY_SERVICES_SIP_TRUNKING("advisory-services-sip-trunking"), - ASSETS_REQUESTS("assets-requests"), - AUDIENCE_MINUTES_VIDEO("audience-minutes-video"), - AUTHY_BUCKET_ADJUSTMENT("authy-bucket-adjustment"), - AUTHY_SOFTWARE("authy-software"), - CALLERIDLOOKUPS_API("calleridlookups-api"), - CALLERIDLOOKUPS_PROGRAMMABLEVOICE("calleridlookups-programmablevoice"), - CALLERIDLOOKUPS_TRUNKING("calleridlookups-trunking"), - CALLS_TRUNKING_INBOUND_TOLLFREE_LOCAL( - "calls-trunking-inbound-tollfree-local" - ), - CALLS_TRUNKING_INBOUND_TOLLFREE_MOBILE( - "calls-trunking-inbound-tollfree-mobile" - ), - CHANNELS_WHATSAPP_CONVERSATION_FREE_1( - "channels-whatsapp-conversation-free-1" - ), - CONFERENCE("conference"), - CONVERSATIONAL_INSIGHTS("conversational-insights"), - CONVERSATIONAL_INSIGHTS_MESSAGES("conversational-insights-messages"), - CONVERSATIONAL_INSIGHTS_VOICE_MINUTES( - "conversational-insights-voice-minutes" - ), - DEMO("demo"), - DEMO_UC_SCRIPT_TEST("demo-uc-script-test"), - ELASTIC_SIP_TRUNKING("elastic-sip-trunking"), - ELASTIC_SIP_TRUNKING_CALL_TRANSFERS( - "elastic-sip-trunking-call-transfers" - ), - ENTERPRISE_HIPPA("enterprise-hippa"), - FLEX_NAMED_USERS("flex-named-users"), - FLEX_SPINSCI("flex-spinsci"), - FLEX_USERS_1("flex-users-1"), - FLEX_WFO_PREMIUM_SPEECH_ANALYTICS("flex-wfo-premium-speech-analytics"), - FLEX_XCELERATE("flex-xcelerate"), - FUNCTIONS_ROLLUP("functions-rollup"), - IMP_V1_USAGE("imp-v1-usage"), - IP_MESSAGING_ADDONS("ip-messaging-addons"), - IVR("ivr"), - IVR_CONVERSATIONAL("ivr-conversational"), - IVR_DTMF("ivr-dtmf"), - IVR_VIRTUALAGENT("ivr-virtualagent"), - LIVE("live"), - LIVE_MEDIA_RECORDING_MINUTES("live-media-recording-minutes"), - LONGCODE_MPS("longcode-mps"), - MARKETPLACE_ANALYTICS_ADDONS("marketplace-analytics-addons"), - MARKETPLACE_ISV_ADDONS("marketplace-isv-addons"), - MARKETPLACE_MESSAGING_ADDONS("marketplace-messaging-addons"), - MARKETPLACE_PHONENUMBERS_ADDONS("marketplace-phonenumbers-addons"), - MARKETPLACE_RECORDING_ADDONS("marketplace-recording-addons"), - MARKETPLACE_VIRTUALAGENT_ADDONS("marketplace-virtualagent-addons"), - MARKETPLAY_PAY_ADDONS_SHUTTLE_PAY_CONNECTOR_1( - "marketplay-pay-addons-shuttle-pay-connector-1" - ), - MARKETPLAY_PAY_ADDONS_STRIPE_PAY_CONNECTOR( - "marketplay-pay-addons-stripe-pay-connector" - ), - MMS_INBOUND_LONGCODE_CANADA("mms-inbound-longcode-canada"), - MMS_INBOUND_LONGCODE_UNITEDSTATES("mms-inbound-longcode-unitedstates"), - MMS_OUTBOUND_LONGCODE_CANADA("mms-outbound-longcode-canada"), - MMS_OUTBOUND_LONGCODE_UNITEDSTATES( - "mms-outbound-longcode-unitedstates" - ), - MMS_OUTBOUND_TOLL_FREE("mms-outbound-toll-free"), - NOTIFY_CHATAPPSANDOTHERCHANNELS("notify-chatappsandotherchannels"), - NOTIFY_NOTIFYSERVICES("notify-notifyservices"), - NOTIFY_PUSHNOTIFICATIONS("notify-pushnotifications"), - PAYMENT_GATEWAY_CONNECTORS("payment-gateway-connectors"), - PAYMENT_SOLUTIONS("payment-solutions"), - PCHAT_BUCKET_ADJUSTMENT("pchat-bucket-adjustment"), - PHONENUMBERS_NUMBERS("phonenumbers-numbers"), - PROG_VOICE_CLIENT_ANDROID("prog-voice-client-android"), - PROG_VOICE_CLIENT_ANDROID_INBOUND("prog-voice-client-android-inbound"), - PROG_VOICE_CLIENT_ANDROID_OUTBOUND( - "prog-voice-client-android-outbound" - ), - PROG_VOICE_CLIENT_IOS("prog-voice-client-ios"), - PROG_VOICE_CLIENT_IOS_INBOUND("prog-voice-client-ios-inbound"), - PROG_VOICE_CLIENT_IOS_OUTBOUND("prog-voice-client-ios-outbound"), - PROG_VOICE_CLIENT_SDK("prog-voice-client-sdk"), - PROG_VOICE_CLIENT_WEB("prog-voice-client-web"), - PROG_VOICE_CLIENT_WEB_INBOUND("prog-voice-client-web-inbound"), - PROG_VOICE_CLIENT_WEB_OUTBOUND("prog-voice-client-web-outbound"), - PROGRAMMABLEVOICECONNECTIVITY_MEDIA_STREAMS( - "programmablevoiceconnectivity-media-streams" - ), - PSTNCONNECTIVITY_BYOC("pstnconnectivity-byoc"), - PSTNCONNECTIVITY_EMERGENCY("pstnconnectivity-emergency"), - PSTNCONNECTIVITY_MINUTES("pstnconnectivity-minutes"), - PSTNCONNECTIVITY_MINUTES_1("pstnconnectivity-minutes-1"), - PSTNCONNECTIVITY_MINUTESINBOUNDLOCAL( - "pstnconnectivity-minutesinboundlocal" - ), - PSTNCONNECTIVITY_MINUTESINBOUNDMOBILE( - "pstnconnectivity-minutesinboundmobile" - ), - PSTNCONNECTIVITY_MINUTESINBOUNDTOLLFREE( - "pstnconnectivity-minutesinboundtollfree" - ), - PSTNCONNECTIVITY_MINUTESINBOUNDTOLLFREELOCAL( - "pstnconnectivity-minutesinboundtollfreelocal" - ), - PSTNCONNECTIVITY_MINUTESINBOUNDTOLLFREEMOBILE( - "pstnconnectivity-minutesinboundtollfreemobile" - ), - PV_ROOM_HOURS("pv-room-hours"), - PV_ROOM_SIMULTANEOUS_PARTICIPANT_CONNECTIONS( - "pv-room-simultaneous-participant-connections" - ), - PVIDEO_ROOM_HOURS_AU1("pvideo-room-hours-au1"), - PVIDEO_ROOM_HOURS_BR1("pvideo-room-hours-br1"), - PVIDEO_ROOM_HOURS_IE1("pvideo-room-hours-ie1"), - PVIDEO_ROOM_HOURS_JP1("pvideo-room-hours-jp1"), - PVIDEO_ROOM_HOURS_SG1("pvideo-room-hours-sg1"), - PVIDEO_ROOM_HOURS_US1("pvideo-room-hours-us1"), - PVIDEO_ROOM_HOURS_US2("pvideo-room-hours-us2"), - RECORDINGS_ENCRYPTED("recordings-encrypted"), - SHORT_CODE_SETUP_FEES("short-code-setup-fees"), - SHORTCODES_MESSAGES_INBOUND("shortcodes-messages-inbound"), - SHORTCODES_MESSAGES_OUTBOUND("shortcodes-messages-outbound"), - SMS_MESSAGES_REGISTRATIONFEES("sms-messages-registrationfees"), - SMS_MMS_PENALTY_FEES("sms-mms-penalty-fees"), - SMS_MMS_PENALTY_FEES_1("sms-mms-penalty-fees-1"), - SMS_PUMPING_PROTECTION_NON_USCA("sms-pumping-protection-non-usca"), - SMS_PUMPING_PROTECTION_USCA("sms-pumping-protection-usca"), - STUDIO("studio"), - STUDIO_MONTHLY_FEES("studio-monthly-fees"), - SUPERSIM("supersim"), - TASK_ROUTER("task-router"), - TASK_ROUTER_WORKERS("task-router-workers"), - TEST_QUOTA_BUCKETS("test-quota-buckets"), - TEST_UC_SCRIPT_1("test-uc-script-1"), - TEST_UC_SCRIPT_DEMO_2("test-uc-script-demo-2"), - TEXT_TO_SPEECH("text-to-speech"), - TME("tme"), - TTS_BASIC("tts-basic"), - TWILIO_EDITIONS("twilio-editions"), - TWILIO_INTERCONNECT_CALIFORNIA("twilio-interconnect-california"), - TWILIO_INTERCONNECT_CALIFORNIA_MONTHLY( - "twilio-interconnect-california-monthly" - ), - TWILIO_INTERCONNECT_CALIFORNIA_SETUP( - "twilio-interconnect-california-setup" - ), - TWILIO_INTERCONNECT_FRANKFURT("twilio-interconnect-frankfurt"), - TWILIO_INTERCONNECT_FRANKFURT_MO("twilio-interconnect-frankfurt-mo"), - TWILIO_INTERCONNECT_FRANKFURT_SETUP( - "twilio-interconnect-frankfurt-setup" - ), - TWILIO_INTERCONNECT_LONDON("twilio-interconnect-london"), - TWILIO_INTERCONNECT_LONDON_MO("twilio-interconnect-london-mo"), - TWILIO_INTERCONNECT_LONDON_SETUP("twilio-interconnect-london-setup"), - TWILIO_INTERCONNECT_SAO_PAULO("twilio-interconnect-sao-paulo"), - TWILIO_INTERCONNECT_SAO_PAULO_MONTHLY( - "twilio-interconnect-sao-paulo-monthly" - ), - TWILIO_INTERCONNECT_SAO_PAULO_SETUP( - "twilio-interconnect-sao-paulo-setup" - ), - TWILIO_INTERCONNECT_SINGAPORE("twilio-interconnect-singapore"), - TWILIO_INTERCONNECT_SINGAPORE_MO("twilio-interconnect-singapore-mo"), - TWILIO_INTERCONNECT_SINGAPORE_SETUP( - "twilio-interconnect-singapore-setup" - ), - TWILIO_INTERCONNECT_SYDNEY("twilio-interconnect-sydney"), - TWILIO_INTERCONNECT_SYDNEY_MO("twilio-interconnect-sydney-mo"), - TWILIO_INTERCONNECT_SYDNEY_SETUP("twilio-interconnect-sydney-setup"), - TWILIO_INTERCONNECT_TOKYO("twilio-interconnect-tokyo"), - TWILIO_INTERCONNECT_TOKYO_MO("twilio-interconnect-tokyo-mo"), - TWILIO_INTERCONNECT_TOKYO_SETUP("twilio-interconnect-tokyo-setup"), - TWILIO_INTERCONNECT_VA("twilio-interconnect-va"), - TWILIO_INTERCONNECT_VA_MO("twilio-interconnect-va-mo"), - TWILIO_INTERCONNECT_VA_SETUP("twilio-interconnect-va-setup"), - TWIML_VERBS("twiml-verbs"), - TWIML_VERBS_SAY("twiml-verbs-say"), - USAGE_PROGRAMMABLE_MESSAGING_ENGAGEMENT_SUITE( - "usage-programmable-messaging-engagement-suite" - ), - USAGE_PROGRAMMABLE_MESSAGING_FEES_SERVICES( - "usage-programmable-messaging-fees-services" - ), - VERIFY_OUTBOUND_EMAIL("verify-outbound-email"), - VERIFY_PACKAGED_PLANS("verify-packaged-plans"), - VERIFY_SILENT_NETWORK_AUTH("verify-silent-network-auth"), - VERIFY_VOICE_AND_SMS("verify-voice-and-sms"), - VOICE_INSIGHTS_CLIENT_INSIGHTS_MONTHY_COMMIT( - "voice-insights-client-insights-monthy-commit" - ), - WIRELESS_DATA_PAYG_ASIA_AFG("wireless-data-payg-asia-afg"), - WIRELESS_MULTI_IMSI_SIM_COMMANDS("wireless-multi-imsi-sim-commands"), - WIRELESS_MULTI_IMSI_SIM_COMMANDS_USA( - "wireless-multi-imsi-sim-commands-usa" - ), - WIRELESS_MULTI_IMSI_SIM_DATA("wireless-multi-imsi-sim-data"), - WIRELESS_MULTI_IMSI_SIM_DATA_EU28("wireless-multi-imsi-sim-data-eu28"), - WIRELESS_MULTI_IMSI_SIM_DATA_USA("wireless-multi-imsi-sim-data-usa"), - WIRELESS_MULTI_IMSI_SIM_MONTHLY_FEES( - "wireless-multi-imsi-sim-monthly-fees" - ), - WIRELESS_MULTI_IMSI_SIM_USAGE("wireless-multi-imsi-sim-usage"), - WIRELESS_SUPER_SIM_DATA_NORTH_AMERICA( - "wireless-super-sim-data-north-america" - ), - WIRELESS_SUPER_SIM_USAGE("wireless-super-sim-usage"); - - private final String value; - - private UsageCategory(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static UsageCategory forValue(final String value) { - return Promoter.enumFromString(value, UsageCategory.values()); - } - } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/usage/TriggerCreator.java b/src/main/java/com/twilio/rest/api/v2010/account/usage/TriggerCreator.java index a917684656..1609ff12a8 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/usage/TriggerCreator.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/usage/TriggerCreator.java @@ -32,7 +32,7 @@ public class TriggerCreator extends Creator { private URI callbackUrl; private String triggerValue; - private Trigger.UsageCategory usageCategory; + private String usageCategory; private String pathAccountSid; private HttpMethod callbackMethod; private String friendlyName; @@ -42,7 +42,7 @@ public class TriggerCreator extends Creator { public TriggerCreator( final URI callbackUrl, final String triggerValue, - final Trigger.UsageCategory usageCategory + final String usageCategory ) { this.callbackUrl = callbackUrl; this.triggerValue = triggerValue; @@ -53,7 +53,7 @@ public TriggerCreator( final String pathAccountSid, final URI callbackUrl, final String triggerValue, - final Trigger.UsageCategory usageCategory + final String usageCategory ) { this.pathAccountSid = pathAccountSid; this.callbackUrl = callbackUrl; @@ -75,9 +75,7 @@ public TriggerCreator setTriggerValue(final String triggerValue) { return this; } - public TriggerCreator setUsageCategory( - final Trigger.UsageCategory usageCategory - ) { + public TriggerCreator setUsageCategory(final String usageCategory) { this.usageCategory = usageCategory; return this; } @@ -168,7 +166,7 @@ private void addPostParams(final Request request) { request.addPostParam("TriggerValue", triggerValue); } if (usageCategory != null) { - request.addPostParam("UsageCategory", usageCategory.toString()); + request.addPostParam("UsageCategory", usageCategory); } if (callbackMethod != null) { request.addPostParam("CallbackMethod", callbackMethod.toString()); diff --git a/src/main/java/com/twilio/rest/api/v2010/account/usage/TriggerReader.java b/src/main/java/com/twilio/rest/api/v2010/account/usage/TriggerReader.java index 3e0b03871d..6e839f3bcd 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/usage/TriggerReader.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/usage/TriggerReader.java @@ -32,7 +32,7 @@ public class TriggerReader extends Reader { private String pathAccountSid; private Trigger.Recurring recurring; private Trigger.TriggerField triggerBy; - private Trigger.UsageCategory usageCategory; + private String usageCategory; private Long pageSize; public TriggerReader() {} @@ -51,9 +51,7 @@ public TriggerReader setTriggerBy(final Trigger.TriggerField triggerBy) { return this; } - public TriggerReader setUsageCategory( - final Trigger.UsageCategory usageCategory - ) { + public TriggerReader setUsageCategory(final String usageCategory) { this.usageCategory = usageCategory; return this; } @@ -165,7 +163,7 @@ private void addQueryParams(final Request request) { request.addQueryParam("TriggerBy", triggerBy.toString()); } if (usageCategory != null) { - request.addQueryParam("UsageCategory", usageCategory.toString()); + request.addQueryParam("UsageCategory", usageCategory); } if (pageSize != null) { request.addQueryParam("PageSize", pageSize.toString()); diff --git a/src/main/java/com/twilio/rest/api/v2010/account/usage/record/AllTime.java b/src/main/java/com/twilio/rest/api/v2010/account/usage/record/AllTime.java index d838c14ce6..bf2f4409bf 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/usage/record/AllTime.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/usage/record/AllTime.java @@ -24,7 +24,6 @@ import com.twilio.base.Resource; import com.twilio.converter.CurrencyDeserializer; import com.twilio.converter.DateConverter; -import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import java.io.IOException; @@ -42,7 +41,7 @@ @ToString public class AllTime extends Resource { - private static final long serialVersionUID = 119534363835835L; + private static final long serialVersionUID = 158026917970511L; public static AllTimeReader reader() { return new AllTimeReader(); @@ -98,7 +97,7 @@ public static AllTime fromJson( private final String accountSid; private final String apiVersion; private final String asOf; - private final AllTime.Category category; + private final String category; private final String count; private final String countUnit; private final String description; @@ -116,7 +115,7 @@ private AllTime( @JsonProperty("account_sid") final String accountSid, @JsonProperty("api_version") final String apiVersion, @JsonProperty("as_of") final String asOf, - @JsonProperty("category") final AllTime.Category category, + @JsonProperty("category") final String category, @JsonProperty("count") final String count, @JsonProperty("count_unit") final String countUnit, @JsonProperty("description") final String description, @@ -163,7 +162,7 @@ public final String getAsOf() { return this.asOf; } - public final AllTime.Category getCategory() { + public final String getCategory() { return this.category; } @@ -262,945 +261,4 @@ public int hashCode() { usageUnit ); } - - public enum Category { - A2P_10DLC_REGISTRATIONFEES_BRANDREGISTRATION( - "a2p-10dlc-registrationfees-brandregistration" - ), - A2P_10DLC_REGISTRATIONFEES_BV("a2p-10dlc-registrationfees-bv"), - A2P_10DLC_REGISTRATIONFEES_CAMPAIGNCHARGES( - "a2p-10dlc-registrationfees-campaigncharges" - ), - A2P_10DLC_REGISTRATIONFEES_CAMPAIGNREGISTRATION( - "a2p-10dlc-registrationfees-campaignregistration" - ), - A2P_10DLC_REGISTRATIONFEES_CAMPAIGNVETTING( - "a2p-10dlc-registrationfees-campaignvetting" - ), - A2P_10DLC_REGISTRATIONFEES_MONTHLY( - "a2p-10dlc-registrationfees-monthly" - ), - A2P_10DLC_REGISTRATIONFEES_ONETIME( - "a2p-10dlc-registrationfees-onetime" - ), - A2P_REGISTRATION_FEES("a2p-registration-fees"), - ACCOUNT_SECURITY("account-security"), - AGENT_CONFERENCE("agent-conference"), - AGENT_COPILOT("agent-copilot"), - AGENT_COPILOT_MESSAGES("agent-copilot-messages"), - AGENT_COPILOT_PARTICIPANT_MINUTES("agent-copilot-participant-minutes"), - AI_ASSISTANTS("ai-assistants"), - AI_ASSISTANTS_VOICE("ai-assistants-voice"), - AMAZON_POLLY("amazon-polly"), - ANSWERING_MACHINE_DETECTION("answering-machine-detection"), - ASSETS("assets"), - AUDIENCE_MINUTES("audience-minutes"), - AUDIENCE_MINUTES_AUDIO("audience-minutes-audio"), - AUTHY_AUTHENTICATIONS("authy-authentications"), - AUTHY_CALLS_OUTBOUND("authy-calls-outbound"), - AUTHY_EMAIL_AUTHENTICATIONS("authy-email-authentications"), - AUTHY_MONTHLY_FEES("authy-monthly-fees"), - AUTHY_OUTBOUND_EMAIL("authy-outbound-email"), - AUTHY_PHONE_INTELLIGENCE("authy-phone-intelligence"), - AUTHY_PHONE_VERIFICATIONS("authy-phone-verifications"), - AUTHY_SMS_OUTBOUND("authy-sms-outbound"), - AUTHY_VERIFY_EMAIL_VERIFICATIONS("authy-verify-email-verifications"), - AUTHY_VERIFY_OUTBOUND_EMAIL("authy-verify-outbound-email"), - AUTOPILOT("autopilot"), - AUTOPILOT_HOME_ASSISTANTS("autopilot-home-assistants"), - AUTOPILOT_MESSAGING("autopilot-messaging"), - AUTOPILOT_OTHER("autopilot-other"), - AUTOPILOT_VOICE("autopilot-voice"), - BASIC_PEER_TO_PEER_ROOMS_PARTICIPANT_MINUTES( - "basic-peer-to-peer-rooms-participant-minutes" - ), - BRANDED_CALLING("branded-calling"), - BUNDLE_SMS_BUCKET("bundle-sms-bucket"), - BUNDLE_SUBSCRIPTION_FEES("bundle-subscription-fees"), - CALL_FORWARDING_LOOKUPS("call-forwarding-lookups"), - CALL_PROGESS_EVENTS("call-progess-events"), - CALLERIDLOOKUPS("calleridlookups"), - CALLS("calls"), - CALLS_CLIENT("calls-client"), - CALLS_EMERGENCY("calls-emergency"), - CALLS_GLOBALCONFERENCE("calls-globalconference"), - CALLS_INBOUND("calls-inbound"), - CALLS_INBOUND_LOCAL("calls-inbound-local"), - CALLS_INBOUND_MOBILE("calls-inbound-mobile"), - CALLS_INBOUND_TOLLFREE("calls-inbound-tollfree"), - CALLS_INBOUND_TOLLFREE_LOCAL("calls-inbound-tollfree-local"), - CALLS_INBOUND_TOLLFREE_MOBILE("calls-inbound-tollfree-mobile"), - CALLS_MEDIA_STREAM_MINUTES("calls-media-stream-minutes"), - CALLS_OUTBOUND("calls-outbound"), - CALLS_PAY_VERB_TRANSACTIONS("calls-pay-verb-transactions"), - CALLS_RECORDINGS("calls-recordings"), - CALLS_SIP("calls-sip"), - CALLS_SIP_INBOUND("calls-sip-inbound"), - CALLS_SIP_OUTBOUND("calls-sip-outbound"), - CALLS_TEXT_TO_SPEECH("calls-text-to-speech"), - CALLS_TRANSFERS("calls-transfers"), - CARRIER_LOOKUPS("carrier-lookups"), - CATEGORY("category"), - CHANNELS("channels"), - CHANNELS_MESSAGING("channels-messaging"), - CHANNELS_MESSAGING_INBOUND("channels-messaging-inbound"), - CHANNELS_MESSAGING_OUTBOUND("channels-messaging-outbound"), - CHANNELS_WHATSAPP("channels-whatsapp"), - CHANNELS_WHATSAPP_CONVERSATION_AUTHENTICATION( - "channels-whatsapp-conversation-authentication" - ), - CHANNELS_WHATSAPP_CONVERSATION_FREE( - "channels-whatsapp-conversation-free" - ), - CHANNELS_WHATSAPP_CONVERSATION_MARKETING( - "channels-whatsapp-conversation-marketing" - ), - CHANNELS_WHATSAPP_CONVERSATION_SERVICE( - "channels-whatsapp-conversation-service" - ), - CHANNELS_WHATSAPP_CONVERSATION_UTILITY( - "channels-whatsapp-conversation-utility" - ), - CHANNELS_WHATSAPP_INBOUND("channels-whatsapp-inbound"), - CHANNELS_WHATSAPP_OUTBOUND("channels-whatsapp-outbound"), - CHANNELS_WHATSAPP_SERVICE("channels-whatsapp-service"), - CHANNELS_WHATSAPP_TEMPLATE_AUTHENTICATION( - "channels-whatsapp-template-authentication" - ), - CHANNELS_WHATSAPP_TEMPLATE_MARKETING( - "channels-whatsapp-template-marketing" - ), - CHANNELS_WHATSAPP_TEMPLATE_SERVICE( - "channels-whatsapp-template-service" - ), - CHANNELS_WHATSAPP_TEMPLATE_UTILITY( - "channels-whatsapp-template-utility" - ), - CHAT_VIRTUAL_AGENT("chat-virtual-agent"), - CONVERSATION_RELAY("conversation-relay"), - CONVERSATIONS("conversations"), - CONVERSATIONS_API_REQUESTS("conversations-api-requests"), - CONVERSATIONS_CONVERSATION_EVENTS("conversations-conversation-events"), - CONVERSATIONS_ENDPOINT_CONNECTIVITY( - "conversations-endpoint-connectivity" - ), - CONVERSATIONS_EVENTS("conversations-events"), - CONVERSATIONS_PARTICIPANT_EVENTS("conversations-participant-events"), - CONVERSATIONS_PARTICIPANTS("conversations-participants"), - CPS("cps"), - CREDIT_TRANSFER("credit-transfer"), - EMAIL("email"), - EMERGING_TECH("emerging-tech"), - ENGAGEMENT_SUITE_PACKAGED_PLANS("engagement-suite-packaged-plans"), - ENHANCED_LINE_TYPE_LOOKUPS("enhanced-line-type-lookups"), - ENTERPRISE("enterprise"), - EVENTS("events"), - EXPERIMENT_FRANCE_SMS("experiment-france-sms"), - EXPERIMENT_INDIA_SMS("experiment-india-sms"), - EXPERIMENT_UK_SMS("experiment-uk-sms"), - FAILED_MESSAGE_PROCESSING_FEE("failed-message-processing-fee"), - FLEX("flex"), - FLEX_ACTIVE_USER_HOURS("flex-active-user-hours"), - FLEX_CONCURRENT_USERS("flex-concurrent-users"), - FLEX_CONVERSATIONAL_INSIGHTS("flex-conversational-insights"), - FLEX_CONVERSATIONAL_INSIGHTS_MESSAGES( - "flex-conversational-insights-messages" - ), - FLEX_CONVERSATIONAL_INSIGHTS_VOICE_MINUTES( - "flex-conversational-insights-voice-minutes" - ), - FLEX_EMAIL_USAGE("flex-email-usage"), - FLEX_MESSAGING_USAGE("flex-messaging-usage"), - FLEX_PARTNER_SPINSCI("flex-partner-spinsci"), - FLEX_PARTNER_XCELERATE("flex-partner-xcelerate"), - FLEX_RESELLER_ECOSYSTEM("flex-reseller-ecosystem"), - FLEX_UNIQUE_USER("flex-unique-user"), - FLEX_USAGE("flex-usage"), - FLEX_USERS("flex-users"), - FLEX_VOICE_MINUTE("flex-voice-minute"), - FLEX_YTICA("flex-ytica"), - FRAUD_LOOKUPS("fraud-lookups"), - FRONTLINE("frontline"), - FRONTLINE_USERS("frontline-users"), - FUNCTIONS("functions"), - GENERIC_PAY_TRANSACTIONS("generic-pay-transactions"), - GROUP_ROOMS("group-rooms"), - GROUP_ROOMS_DATA_TRACK("group-rooms-data-track"), - GROUP_ROOMS_ENCRYPTED_MEDIA_RECORDED( - "group-rooms-encrypted-media-recorded" - ), - GROUP_ROOMS_MEDIA_DOWNLOADED("group-rooms-media-downloaded"), - GROUP_ROOMS_MEDIA_RECORDED("group-rooms-media-recorded"), - GROUP_ROOMS_MEDIA_ROUTED("group-rooms-media-routed"), - GROUP_ROOMS_MEDIA_STORED("group-rooms-media-stored"), - GROUP_ROOMS_PARTICIPANT_MINUTES("group-rooms-participant-minutes"), - GROUP_ROOMS_RECORDED_MINUTES("group-rooms-recorded-minutes"), - IP_MESSAGING("ip-messaging"), - IP_MESSAGING_COMMANDS("ip-messaging-commands"), - IP_MESSAGING_DATA_STORAGE("ip-messaging-data-storage"), - IP_MESSAGING_DATA_TRANSFER("ip-messaging-data-transfer"), - IP_MESSAGING_ENDPOINT_CONNECTIVITY( - "ip-messaging-endpoint-connectivity" - ), - IVR_VIRTUAL_AGENT_CUSTOM_VOICES("ivr-virtual-agent-custom-voices"), - IVR_VIRTUAL_AGENT_GENAI("ivr-virtual-agent-genai"), - LINE_STATUS_LOOKUPS("line-status-lookups"), - LIVE_ACTIVITY_LOOKUPS("live-activity-lookups"), - LOOKUP_BUCKET_ADJUSTMENT("lookup-bucket-adjustment"), - LOOKUP_IDENTITY_MATCH("lookup-identity-match"), - LOOKUPS("lookups"), - MARKETPLACE("marketplace"), - MARKETPLACE_ALGORITHMIA_NAMED_ENTITY_RECOGNITION( - "marketplace-algorithmia-named-entity-recognition" - ), - MARKETPLACE_CADENCE_TRANSCRIPTION("marketplace-cadence-transcription"), - MARKETPLACE_CADENCE_TRANSLATION("marketplace-cadence-translation"), - MARKETPLACE_CAPIO_SPEECH_TO_TEXT("marketplace-capio-speech-to-text"), - MARKETPLACE_CONVRIZA_ABABA("marketplace-convriza-ababa"), - MARKETPLACE_DEEPGRAM_PHRASE_DETECTOR( - "marketplace-deepgram-phrase-detector" - ), - MARKETPLACE_DEEPGRAM_TRANSCRIPTION( - "marketplace-deepgram-transcription" - ), - MARKETPLACE_DEEPGRAM_TRANSCRIPTION_BASE( - "marketplace-deepgram-transcription-base" - ), - MARKETPLACE_DEEPGRAM_TRANSSCRIPTION_ENHANCED( - "marketplace-deepgram-transscription-enhanced" - ), - MARKETPLACE_DIGITAL_SEGMENT_BUSINESS_INFO( - "marketplace-digital-segment-business-info" - ), - MARKETPLACE_FACEBOOK_OFFLINE_CONVERSIONS( - "marketplace-facebook-offline-conversions" - ), - MARKETPLACE_GOOGLE_SPEECH_TO_TEXT("marketplace-google-speech-to-text"), - MARKETPLACE_IBM_WATSON_MESSAGE_INSIGHTS( - "marketplace-ibm-watson-message-insights" - ), - MARKETPLACE_IBM_WATSON_MESSAGE_SENTIMENT( - "marketplace-ibm-watson-message-sentiment" - ), - MARKETPLACE_IBM_WATSON_RECORDING_ANALYSIS( - "marketplace-ibm-watson-recording-analysis" - ), - MARKETPLACE_IBM_WATSON_TONE_ANALYZER( - "marketplace-ibm-watson-tone-analyzer" - ), - MARKETPLACE_ICEHOOK_SYSTEMS_SCOUT("marketplace-icehook-systems-scout"), - MARKETPLACE_INFOGROUP_DATAAXLE_BIZINFO( - "marketplace-infogroup-dataaxle-bizinfo" - ), - MARKETPLACE_KEEN_IO_CONTACT_CENTER_ANALYTICS( - "marketplace-keen-io-contact-center-analytics" - ), - MARKETPLACE_MARCHEX_CLEANCALL("marketplace-marchex-cleancall"), - MARKETPLACE_MARCHEX_RECORDING_ANALYSIS( - "marketplace-marchex-recording-analysis" - ), - MARKETPLACE_MARCHEX_SENTIMENT_ANALYSIS_FOR_SMS( - "marketplace-marchex-sentiment-analysis-for-sms" - ), - MARKETPLACE_MARKETPLACE_NEXTCALLER_SOCIAL_ID( - "marketplace-marketplace-nextcaller-social-id" - ), - MARKETPLACE_MOBILE_COMMONS_OPT_OUT_CLASSIFIER( - "marketplace-mobile-commons-opt-out-classifier" - ), - MARKETPLACE_NEXIWAVE_VOICEMAIL_TO_TEXT( - "marketplace-nexiwave-voicemail-to-text" - ), - MARKETPLACE_NEXTCALLER_ADVANCED_CALLER_IDENTIFICATION( - "marketplace-nextcaller-advanced-caller-identification" - ), - MARKETPLACE_NOMOROBO_SPAM_SCORE("marketplace-nomorobo-spam-score"), - MARKETPLACE_PAY_ADDONS("marketplace-pay-addons"), - MARKETPLACE_PAY_ADDONS_BASECOMMERCE_PAY_CONNECTOR( - "marketplace-pay-addons-basecommerce-pay-connector" - ), - MARKETPLACE_PAY_ADDONS_BRAINTREE_PAY_CONNECTOR( - "marketplace-pay-addons-braintree-pay-connector" - ), - MARKETPLACE_PAY_ADDONS_CARDCONNECT_PAY_CONNECTOR( - "marketplace-pay-addons-cardconnect-pay-connector" - ), - MARKETPLACE_PAY_ADDONS_CHASE_PAY_CONNECTOR( - "marketplace-pay-addons-chase-pay-connector" - ), - MARKETPLACE_PAY_ADDONS_SHUTTLE_PAY_CONNECTOR( - "marketplace-pay-addons-shuttle-pay-connector" - ), - MARKETPLACE_PAY_ADDONS_STRIPE_PAY_CONNECTOR( - "marketplace-pay-addons-stripe-pay-connector" - ), - MARKETPLACE_PAYFONE_TCPA_COMPLIANCE( - "marketplace-payfone-tcpa-compliance" - ), - MARKETPLACE_POLY_AI_CONNECTOR("marketplace-poly-ai-connector"), - MARKETPLACE_REALPHONEVALIDATION("marketplace-realphonevalidation"), - MARKETPLACE_REMEETING_AUTOMATIC_SPEECH_RECOGNITION( - "marketplace-remeeting-automatic-speech-recognition" - ), - MARKETPLACE_SPOKE_PHONE_LICENSE_PRO( - "marketplace-spoke-phone-license-pro" - ), - MARKETPLACE_SPOKE_PHONE_LICENSE_STANDARD( - "marketplace-spoke-phone-license-standard" - ), - MARKETPLACE_TCPA_DEFENSE_SOLUTIONS_BLACKLIST_FEED( - "marketplace-tcpa-defense-solutions-blacklist-feed" - ), - MARKETPLACE_TELO_OPENCNAM("marketplace-telo-opencnam"), - MARKETPLACE_TRESTLE_SOLUTIONS_CALLER_IDENTIFICATION( - "marketplace-trestle-solutions-caller-identification" - ), - MARKETPLACE_TRUECNAM_TRUE_SPAM("marketplace-truecnam-true-spam"), - MARKETPLACE_TWILIO_CALLER_NAME_LOOKUP_US( - "marketplace-twilio-caller-name-lookup-us" - ), - MARKETPLACE_TWILIO_CARRIER_INFORMATION_LOOKUP( - "marketplace-twilio-carrier-information-lookup" - ), - MARKETPLACE_VOICEBASE_PCI("marketplace-voicebase-pci"), - MARKETPLACE_VOICEBASE_TRANSCRIPTION( - "marketplace-voicebase-transcription" - ), - MARKETPLACE_VOICEBASE_TRANSCRIPTION_CUSTOM_VOCABULARY( - "marketplace-voicebase-transcription-custom-vocabulary" - ), - MARKETPLACE_WEB_PURIFY_PROFANITY_FILTER( - "marketplace-web-purify-profanity-filter" - ), - MARKETPLACE_WHITEPAGES_PRO_CALLER_IDENTIFICATION( - "marketplace-whitepages-pro-caller-identification" - ), - MARKETPLACE_WHITEPAGES_PRO_PHONE_INTELLIGENCE( - "marketplace-whitepages-pro-phone-intelligence" - ), - MARKETPLACE_WHITEPAGES_PRO_PHONE_REPUTATION( - "marketplace-whitepages-pro-phone-reputation" - ), - MARKETPLACE_WOLFARM_SPOKEN_RESULTS( - "marketplace-wolfarm-spoken-results" - ), - MARKETPLACE_WOLFRAM_SHORT_ANSWER("marketplace-wolfram-short-answer"), - MARKETPLACE_YTICA_CONTACT_CENTER_REPORTING_ANALYTICS( - "marketplace-ytica-contact-center-reporting-analytics" - ), - MARKETPLAY_PAY_ADDONS_SHUTTLE_PAY_CONNECTOR( - "marketplay-pay-addons-shuttle-pay-connector" - ), - MEDIA_COMPOSER_MINUTES("media-composer-minutes"), - MEDIASTORAGE("mediastorage"), - MIN_SPEND_ADJUSTMENTS("min-spend-adjustments"), - MMS("mms"), - MMS_INBOUND("mms-inbound"), - MMS_INBOUND_LONGCODE("mms-inbound-longcode"), - MMS_INBOUND_SHORTCODE("mms-inbound-shortcode"), - MMS_INBOUND_TOLL_FREE("mms-inbound-toll-free"), - MMS_MESSAGES_CARRIERFEES("mms-messages-carrierfees"), - MMS_OUTBOUND("mms-outbound"), - MMS_OUTBOUND_LONGCODE("mms-outbound-longcode"), - MMS_OUTBOUND_SHORTCODE("mms-outbound-shortcode"), - MMS_OUTBOUND_TOLLFREE("mms-outbound-tollfree"), - MONITOR("monitor"), - MONITOR_READS("monitor-reads"), - MONITOR_STORAGE("monitor-storage"), - MONITOR_WRITES("monitor-writes"), - NOTIFY("notify"), - NOTIFY_ACTIONS_ATTEMPTS("notify-actions-attempts"), - NOTIFY_CHANNELS("notify-channels"), - NUMBER_FORMAT_LOOKUPS("number-format-lookups"), - PCHAT("pchat"), - PCHAT_ACTIONS("pchat-actions"), - PCHAT_APS("pchat-aps"), - PCHAT_CONV_MED_STORAGE("pchat-conv-med-storage"), - PCHAT_MESSAGES("pchat-messages"), - PCHAT_NOTIFICATIONS("pchat-notifications"), - PCHAT_READS("pchat-reads"), - PCHAT_USERS("pchat-users"), - PEER_TO_PEER_ROOMS_PARTICIPANT_MINUTES( - "peer-to-peer-rooms-participant-minutes" - ), - PFAX("pfax"), - PFAX_MINUTES("pfax-minutes"), - PFAX_MINUTES_INBOUND("pfax-minutes-inbound"), - PFAX_MINUTES_OUTBOUND("pfax-minutes-outbound"), - PFAX_PAGES("pfax-pages"), - PHONE_QUALITY_SCORE_LOOKUPS("phone-quality-score-lookups"), - PHONENUMBERS("phonenumbers"), - PHONENUMBERS_CPS("phonenumbers-cps"), - PHONENUMBERS_EMERGENCY("phonenumbers-emergency"), - PHONENUMBERS_LOCAL("phonenumbers-local"), - PHONENUMBERS_MOBILE("phonenumbers-mobile"), - PHONENUMBERS_PORTING("phonenumbers-porting"), - PHONENUMBERS_SETUPS("phonenumbers-setups"), - PHONENUMBERS_TOLLFREE("phonenumbers-tollfree"), - PREMIUMSUPPORT("premiumsupport"), - PREMIUMSUPPORT_PERCENTAGE_SPEND("premiumsupport-percentage-spend"), - PROGRAMMABLEVOICE_PLATFORM("programmablevoice-platform"), - PROGRAMMABLEVOICECONN_CLIENTSDK("programmablevoiceconn-clientsdk"), - PROGRAMMABLEVOICECONN_CLIENTSDK_INBOUND( - "programmablevoiceconn-clientsdk-inbound" - ), - PROGRAMMABLEVOICECONN_CLIENTSDK_OUTBOUND( - "programmablevoiceconn-clientsdk-outbound" - ), - PROGRAMMABLEVOICECONN_ONNET("programmablevoiceconn-onnet"), - PROGRAMMABLEVOICECONN_ONNET_INBOUND( - "programmablevoiceconn-onnet-inbound" - ), - PROGRAMMABLEVOICECONN_ONNET_OUTBOUND( - "programmablevoiceconn-onnet-outbound" - ), - PROGRAMMABLEVOICECONN_SIP("programmablevoiceconn-sip"), - PROGRAMMABLEVOICECONN_SIP_INBOUND("programmablevoiceconn-sip-inbound"), - PROGRAMMABLEVOICECONN_SIP_OUTBOUND( - "programmablevoiceconn-sip-outbound" - ), - PROGRAMMABLEVOICECONNECTIVITY("programmablevoiceconnectivity"), - PROXY("proxy"), - PROXY_ACTIVE_SESSIONS("proxy-active-sessions"), - PROXY_BUCKET_ADJUSTMENT("proxy-bucket-adjustment"), - PROXY_LICENSES("proxy-licenses"), - PSTNCONNECTIVITY("pstnconnectivity"), - PSTNCONNECTIVITY_INBOUND("pstnconnectivity-inbound"), - PSTNCONNECTIVITY_OUTBOUND("pstnconnectivity-outbound"), - PV("pv"), - PV_BASIC_ROOMS("pv-basic-rooms"), - PV_COMPOSITION_MEDIA_DOWNLOADED("pv-composition-media-downloaded"), - PV_COMPOSITION_MEDIA_ENCRYPTED("pv-composition-media-encrypted"), - PV_COMPOSITION_MEDIA_STORED("pv-composition-media-stored"), - PV_COMPOSITION_MINUTES("pv-composition-minutes"), - PV_RECORDING_COMPOSITIONS("pv-recording-compositions"), - PV_ROOM_PARTICIPANTS("pv-room-participants"), - PV_ROOM_PARTICIPANTS_AU1("pv-room-participants-au1"), - PV_ROOM_PARTICIPANTS_BR1("pv-room-participants-br1"), - PV_ROOM_PARTICIPANTS_IE1("pv-room-participants-ie1"), - PV_ROOM_PARTICIPANTS_JP1("pv-room-participants-jp1"), - PV_ROOM_PARTICIPANTS_SG1("pv-room-participants-sg1"), - PV_ROOM_PARTICIPANTS_US1("pv-room-participants-us1"), - PV_ROOM_PARTICIPANTS_US2("pv-room-participants-us2"), - PV_ROOMS("pv-rooms"), - PV_SIP_ENDPOINT_REGISTRATIONS("pv-sip-endpoint-registrations"), - RCS_MESSAGES("rcs-messages"), - REASSIGNED_NUMBER("reassigned-number"), - RECORDINGS("recordings"), - RECORDINGSTORAGE("recordingstorage"), - SHORTCODES("shortcodes"), - SHORTCODES_CUSTOMEROWNED("shortcodes-customerowned"), - SHORTCODES_MMS_ENABLEMENT("shortcodes-mms-enablement"), - SHORTCODES_MPS("shortcodes-mps"), - SHORTCODES_RANDOM("shortcodes-random"), - SHORTCODES_SETUP_FEES("shortcodes-setup-fees"), - SHORTCODES_UK("shortcodes-uk"), - SHORTCODES_VANITY("shortcodes-vanity"), - SIM_SWAP_LOOKUPS("sim-swap-lookups"), - SIP_SECURE_MEDIA("sip-secure-media"), - SMALL_GROUP_ROOMS("small-group-rooms"), - SMALL_GROUP_ROOMS_DATA_TRACK("small-group-rooms-data-track"), - SMALL_GROUP_ROOMS_PARTICIPANT_MINUTES( - "small-group-rooms-participant-minutes" - ), - SMS("sms"), - SMS_INBOUND("sms-inbound"), - SMS_INBOUND_LONGCODE("sms-inbound-longcode"), - SMS_INBOUND_SHORTCODE("sms-inbound-shortcode"), - SMS_INBOUND_TOLLFREE("sms-inbound-tollfree"), - SMS_MESSAGES_CARRIERFEES("sms-messages-carrierfees"), - SMS_MESSAGES_FEATURES("sms-messages-features"), - SMS_MESSAGES_FEATURES_ENGAGEMENT_SUITE( - "sms-messages-features-engagement-suite" - ), - SMS_MESSAGES_FEATURES_MESSAGE_REDACTION( - "sms-messages-features-message-redaction" - ), - SMS_MESSAGES_FEATURES_SENDERID("sms-messages-features-senderid"), - SMS_MPS("sms-mps"), - SMS_MPS_SHORTCODE("sms-mps-shortcode"), - SMS_MPS_TOLLFREE("sms-mps-tollfree"), - SMS_MPS_TOLLFREE_SETUP("sms-mps-tollfree-setup"), - SMS_NATIONAL_REGULATORY_PROTECTION( - "sms-national-regulatory-protection" - ), - SMS_OUTBOUND("sms-outbound"), - SMS_OUTBOUND_CONTENT_INSPECTION("sms-outbound-content-inspection"), - SMS_OUTBOUND_LONGCODE("sms-outbound-longcode"), - SMS_OUTBOUND_SHORTCODE("sms-outbound-shortcode"), - SMS_OUTBOUND_TOLLFREE("sms-outbound-tollfree"), - SMS_PUMPING_PROTECTION("sms-pumping-protection"), - SMS_PUMPING_RISK("sms-pumping-risk"), - SMSMESSAGES_BUCKET_ADJUSTMENTS("smsmessages-bucket-adjustments"), - SMSMESSAGES_OUTBOUND_DOMESTIC("smsmessages-outbound-domestic"), - SPEECH_RECOGNITION("speech-recognition"), - STUDIO_ENGAGEMENTS("studio-engagements"), - SYNC("sync"), - SYNC_ACTIONS("sync-actions"), - SYNC_ENDPOINT_HOURS("sync-endpoint-hours"), - SYNC_ENDPOINT_HOURS_ABOVE_DAILY_CAP( - "sync-endpoint-hours-above-daily-cap" - ), - TASKROUTER_TASKS("taskrouter-tasks"), - TOTALPRICE("totalprice"), - TRANSCRIPTIONS("transcriptions"), - TRUNKING_CPS("trunking-cps"), - TRUNKING_EMERGENCY_CALLS("trunking-emergency-calls"), - TRUNKING_ORIGINATION("trunking-origination"), - TRUNKING_ORIGINATION_LOCAL("trunking-origination-local"), - TRUNKING_ORIGINATION_MOBILE("trunking-origination-mobile"), - TRUNKING_ORIGINATION_TOLLFREE("trunking-origination-tollfree"), - TRUNKING_RECORDINGS("trunking-recordings"), - TRUNKING_SECURE("trunking-secure"), - TRUNKING_TERMINATION("trunking-termination"), - TTS_GOOGLE("tts-google"), - TURNMEGABYTES("turnmegabytes"), - TURNMEGABYTES_AUSTRALIA("turnmegabytes-australia"), - TURNMEGABYTES_BRASIL("turnmegabytes-brasil"), - TURNMEGABYTES_GERMANY("turnmegabytes-germany"), - TURNMEGABYTES_INDIA("turnmegabytes-india"), - TURNMEGABYTES_IRELAND("turnmegabytes-ireland"), - TURNMEGABYTES_JAPAN("turnmegabytes-japan"), - TURNMEGABYTES_SINGAPORE("turnmegabytes-singapore"), - TURNMEGABYTES_USEAST("turnmegabytes-useast"), - TURNMEGABYTES_USWEST("turnmegabytes-uswest"), - TWILIO_FOR_SALESFORCE("twilio-for-salesforce"), - TWILIO_FOR_SALESFORCE_LICENSES("twilio-for-salesforce-licenses"), - TWILIO_INTERCONNECT("twilio-interconnect"), - TWIML("twiml"), - USAGE_FLEX_VIDEO("usage-flex-video"), - USAGE_FUNCTIONS("usage-functions"), - USAGE_RCS_BASIC_MESSAGES_OUTBOUND("usage-rcs-basic-messages-outbound"), - USAGE_RCS_MESSAGES("usage-rcs-messages"), - USAGE_RCS_MESSAGES_INBOUND("usage-rcs-messages-inbound"), - USAGE_RCS_MESSAGING_CARRIER_FEES("usage-rcs-messaging-carrier-fees"), - USAGE_RCS_SINGLE_MESSAGES_OUTBOUND( - "usage-rcs-single-messages-outbound" - ), - VERIFY_PACKAGE_PLANS("verify-package-plans"), - VERIFY_PUSH("verify-push"), - VERIFY_SNA("verify-sna"), - VERIFY_TOTP("verify-totp"), - VERIFY_VOICE_SMS("verify-voice-sms"), - VERIFY_WHATSAPP_CONVERSATIONS_BUSINESS_INITIATED( - "verify-whatsapp-conversations-business-initiated" - ), - VERIFY_WHATSAPP_TEMPLATE_BUSINESS_INITIATED( - "verify-whatsapp-template-business-initiated" - ), - VIDEO_RECORDINGS("video-recordings"), - VIDEO_ROOMS_TURN_MEGABYTES("video-rooms-turn-megabytes"), - VIRTUAL_AGENT("virtual-agent"), - VOICE_INSIGHTS("voice-insights"), - VOICE_INSIGHTS_CLIENT_INSIGHTS_ON_DEMAND_MINUTE( - "voice-insights-client-insights-on-demand-minute" - ), - VOICE_INSIGHTS_PTSN_INSIGHTS_ON_DEMAND_MINUTE( - "voice-insights-ptsn-insights-on-demand-minute" - ), - VOICE_INSIGHTS_SIP_INTERFACE_INSIGHTS_ON_DEMAND_MINUTE( - "voice-insights-sip-interface-insights-on-demand-minute" - ), - VOICE_INSIGHTS_SIP_TRUNKING_INSIGHTS_ON_DEMAND_MINUTE( - "voice-insights-sip-trunking-insights-on-demand-minute" - ), - VOICE_INTELLIGENCE("voice-intelligence"), - VOICE_INTELLIGENCE_EIP_OPERATORS("voice-intelligence-eip-operators"), - VOICE_INTELLIGENCE_OPERATORS("voice-intelligence-operators"), - VOICE_INTELLIGENCE_TRANSCRIPTION("voice-intelligence-transcription"), - WDS("wds"), - WIRELESS("wireless"), - WIRELESS_DATA("wireless-data"), - WIRELESS_DATA_PAYG("wireless-data-payg"), - WIRELESS_DATA_PAYG_AFRICA("wireless-data-payg-africa"), - WIRELESS_DATA_PAYG_ASIA("wireless-data-payg-asia"), - WIRELESS_DATA_PAYG_CENTRALANDSOUTHAMERICA( - "wireless-data-payg-centralandsouthamerica" - ), - WIRELESS_DATA_PAYG_EUROPE("wireless-data-payg-europe"), - WIRELESS_DATA_PAYG_NORTHAMERICA("wireless-data-payg-northamerica"), - WIRELESS_DATA_PAYG_OCEANIA("wireless-data-payg-oceania"), - WIRELESS_DATA_QUOTA1("wireless-data-quota1"), - WIRELESS_DATA_QUOTA1_AFRICA("wireless-data-quota1-africa"), - WIRELESS_DATA_QUOTA1_ASIA("wireless-data-quota1-asia"), - WIRELESS_DATA_QUOTA1_CENTRALANDSOUTHAMERICA( - "wireless-data-quota1-centralandsouthamerica" - ), - WIRELESS_DATA_QUOTA1_EUROPE("wireless-data-quota1-europe"), - WIRELESS_DATA_QUOTA1_NORTHAMERICA("wireless-data-quota1-northamerica"), - WIRELESS_DATA_QUOTA1_OCEANIA("wireless-data-quota1-oceania"), - WIRELESS_DATA_QUOTA10("wireless-data-quota10"), - WIRELESS_DATA_QUOTA10_AFRICA("wireless-data-quota10-africa"), - WIRELESS_DATA_QUOTA10_ASIA("wireless-data-quota10-asia"), - WIRELESS_DATA_QUOTA10_CENTRALANDSOUTHAMERICA( - "wireless-data-quota10-centralandsouthamerica" - ), - WIRELESS_DATA_QUOTA10_EUROPE("wireless-data-quota10-europe"), - WIRELESS_DATA_QUOTA10_NORTHAMERICA( - "wireless-data-quota10-northamerica" - ), - WIRELESS_DATA_QUOTA10_OCEANIA("wireless-data-quota10-oceania"), - WIRELESS_DATA_QUOTA50("wireless-data-quota50"), - WIRELESS_DATA_QUOTA50_AFRICA("wireless-data-quota50-africa"), - WIRELESS_DATA_QUOTA50_ASIA("wireless-data-quota50-asia"), - WIRELESS_DATA_QUOTA50_CENTRALANDSOUTHAMERICA( - "wireless-data-quota50-centralandsouthamerica" - ), - WIRELESS_DATA_QUOTA50_EUROPE("wireless-data-quota50-europe"), - WIRELESS_DATA_QUOTA50_NORTHAMERICA( - "wireless-data-quota50-northamerica" - ), - WIRELESS_DATA_QUOTA50_OCEANIA("wireless-data-quota50-oceania"), - WIRELESS_DATA_QUOTACUSTOM("wireless-data-quotacustom"), - WIRELESS_DATA_QUOTACUSTOM_AFRICA("wireless-data-quotacustom-africa"), - WIRELESS_DATA_QUOTACUSTOM_ASIA("wireless-data-quotacustom-asia"), - WIRELESS_DATA_QUOTACUSTOM_CENTRALANDSOUTHAMERICA( - "wireless-data-quotacustom-centralandsouthamerica" - ), - WIRELESS_DATA_QUOTACUSTOM_EUROPE("wireless-data-quotacustom-europe"), - WIRELESS_DATA_QUOTACUSTOM_NORTHAMERICA( - "wireless-data-quotacustom-northamerica" - ), - WIRELESS_DATA_QUOTACUSTOM_OCEANIA("wireless-data-quotacustom-oceania"), - WIRELESS_MRC_PAYG("wireless-mrc-payg"), - WIRELESS_MRC_QUOTA1("wireless-mrc-quota1"), - WIRELESS_MRC_QUOTA10("wireless-mrc-quota10"), - WIRELESS_MRC_QUOTA50("wireless-mrc-quota50"), - WIRELESS_MRC_QUOTACUSTOM("wireless-mrc-quotacustom"), - WIRELESS_ORDERS("wireless-orders"), - WIRELESS_ORDERS_ARTWORK("wireless-orders-artwork"), - WIRELESS_ORDERS_BULK("wireless-orders-bulk"), - WIRELESS_ORDERS_ESIM("wireless-orders-esim"), - WIRELESS_ORDERS_STARTER("wireless-orders-starter"), - WIRELESS_QUOTAS("wireless-quotas"), - WIRELESS_SMS_AFRICA("wireless-sms-africa"), - WIRELESS_SMS_ASIA("wireless-sms-asia"), - WIRELESS_SMS_CENTRALANDSOUTHAMERICA( - "wireless-sms-centralandsouthamerica" - ), - WIRELESS_SMS_EUROPE("wireless-sms-europe"), - WIRELESS_SMS_NORTHAMERICA("wireless-sms-northamerica"), - WIRELESS_SMS_OCEANIA("wireless-sms-oceania"), - WIRELESS_SUPER_SIM("wireless-super-sim"), - WIRELESS_SUPER_SIM_DATA("wireless-super-sim-data"), - WIRELESS_SUPER_SIM_DATA_NORTH_AMERICA_USA( - "wireless-super-sim-data-north-america-usa" - ), - WIRELESS_SUPER_SIM_DATA_PAYG("wireless-super-sim-data-payg"), - WIRELESS_SUPER_SIM_DATA_PAYG_EUROPE( - "wireless-super-sim-data-payg-europe" - ), - WIRELESS_SUPER_SIM_DATA_PAYG_NORTH_AMERICA( - "wireless-super-sim-data-payg-north-america" - ), - WIRELESS_SUPER_SIM_HARDWARE("wireless-super-sim-hardware"), - WIRELESS_SUPER_SIM_HARDWARE_BULK("wireless-super-sim-hardware-bulk"), - WIRELESS_SUPER_SIM_SMSCOMMANDS("wireless-super-sim-smscommands"), - WIRELESS_SUPER_SIM_SMSCOMMANDS_AFRICA( - "wireless-super-sim-smscommands-africa" - ), - WIRELESS_SUPER_SIM_SMSCOMMANDS_ASIA( - "wireless-super-sim-smscommands-asia" - ), - WIRELESS_SUPER_SIM_SMSCOMMANDS_CENT_AND_SOUTH_AMERICA( - "wireless-super-sim-smscommands-cent-and-south-america" - ), - WIRELESS_SUPER_SIM_SMSCOMMANDS_EUROPE( - "wireless-super-sim-smscommands-europe" - ), - WIRELESS_SUPER_SIM_SMSCOMMANDS_NORTH_AMERICA( - "wireless-super-sim-smscommands-north-america" - ), - WIRELESS_SUPER_SIM_SMSCOMMANDS_OCEANIA( - "wireless-super-sim-smscommands-oceania" - ), - WIRELESS_SUPER_SIM_SUBSCRIPTION("wireless-super-sim-subscription"), - WIRELESS_SUPER_SIM_SUBSCRIPTION_PAYG( - "wireless-super-sim-subscription-payg" - ), - WIRELESS_USAGE("wireless-usage"), - WIRELESS_USAGE_COMMANDS("wireless-usage-commands"), - WIRELESS_USAGE_COMMANDS_AFRICA("wireless-usage-commands-africa"), - WIRELESS_USAGE_COMMANDS_ASIA("wireless-usage-commands-asia"), - WIRELESS_USAGE_COMMANDS_CENTRALANDSOUTHAMERICA( - "wireless-usage-commands-centralandsouthamerica" - ), - WIRELESS_USAGE_COMMANDS_EUROPE("wireless-usage-commands-europe"), - WIRELESS_USAGE_COMMANDS_HOME("wireless-usage-commands-home"), - WIRELESS_USAGE_COMMANDS_NORTHAMERICA( - "wireless-usage-commands-northamerica" - ), - WIRELESS_USAGE_COMMANDS_OCEANIA("wireless-usage-commands-oceania"), - WIRELESS_USAGE_COMMANDS_ROAMING("wireless-usage-commands-roaming"), - WIRELESS_USAGE_DATA("wireless-usage-data"), - WIRELESS_USAGE_DATA_AFRICA("wireless-usage-data-africa"), - WIRELESS_USAGE_DATA_ASIA("wireless-usage-data-asia"), - WIRELESS_USAGE_DATA_CENTRALANDSOUTHAMERICA( - "wireless-usage-data-centralandsouthamerica" - ), - WIRELESS_USAGE_DATA_CUSTOM_ADDITIONALMB( - "wireless-usage-data-custom-additionalmb" - ), - WIRELESS_USAGE_DATA_CUSTOM_FIRST5MB( - "wireless-usage-data-custom-first5mb" - ), - WIRELESS_USAGE_DATA_DOMESTIC_ROAMING( - "wireless-usage-data-domestic-roaming" - ), - WIRELESS_USAGE_DATA_EUROPE("wireless-usage-data-europe"), - WIRELESS_USAGE_DATA_INDIVIDUAL_ADDITIONALGB( - "wireless-usage-data-individual-additionalgb" - ), - WIRELESS_USAGE_DATA_INDIVIDUAL_FIRSTGB( - "wireless-usage-data-individual-firstgb" - ), - WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_CANADA( - "wireless-usage-data-international-roaming-canada" - ), - WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_INDIA( - "wireless-usage-data-international-roaming-india" - ), - WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_MEXICO( - "wireless-usage-data-international-roaming-mexico" - ), - WIRELESS_USAGE_DATA_NORTHAMERICA("wireless-usage-data-northamerica"), - WIRELESS_USAGE_DATA_OCEANIA("wireless-usage-data-oceania"), - WIRELESS_USAGE_DATA_POOLED("wireless-usage-data-pooled"), - WIRELESS_USAGE_DATA_POOLED_DOWNLINK( - "wireless-usage-data-pooled-downlink" - ), - WIRELESS_USAGE_DATA_POOLED_UPLINK("wireless-usage-data-pooled-uplink"), - WIRELESS_USAGE_MRC("wireless-usage-mrc"), - WIRELESS_USAGE_MRC_CUSTOM("wireless-usage-mrc-custom"), - WIRELESS_USAGE_MRC_INDIVIDUAL("wireless-usage-mrc-individual"), - WIRELESS_USAGE_MRC_POOLED("wireless-usage-mrc-pooled"), - WIRELESS_USAGE_MRC_SUSPENDED("wireless-usage-mrc-suspended"), - WIRELESS_USAGE_SMS("wireless-usage-sms"), - WIRELESS_USAGE_VOICE("wireless-usage-voice"), - A2P_FAST_TRACK_ONBOARDING("a2p-fast-track-onboarding"), - ADVISORY_SERVICES("advisory-services"), - ADVISORY_SERVICES_BILLED("advisory-services-billed"), - ADVISORY_SERVICES_CALL_TRACKING("advisory-services-call-tracking"), - ADVISORY_SERVICES_DATA_SERVICES("advisory-services-data-services"), - ADVISORY_SERVICES_EXPENSES("advisory-services-expenses"), - ADVISORY_SERVICES_SIP_TRUNKING("advisory-services-sip-trunking"), - ASSETS_REQUESTS("assets-requests"), - AUDIENCE_MINUTES_VIDEO("audience-minutes-video"), - AUTHY_BUCKET_ADJUSTMENT("authy-bucket-adjustment"), - AUTHY_SOFTWARE("authy-software"), - CALLERIDLOOKUPS_API("calleridlookups-api"), - CALLERIDLOOKUPS_PROGRAMMABLEVOICE("calleridlookups-programmablevoice"), - CALLERIDLOOKUPS_TRUNKING("calleridlookups-trunking"), - CALLS_TRUNKING_INBOUND_TOLLFREE_LOCAL( - "calls-trunking-inbound-tollfree-local" - ), - CALLS_TRUNKING_INBOUND_TOLLFREE_MOBILE( - "calls-trunking-inbound-tollfree-mobile" - ), - CHANNELS_WHATSAPP_CONVERSATION_FREE_1( - "channels-whatsapp-conversation-free-1" - ), - CONFERENCE("conference"), - CONVERSATIONAL_INSIGHTS("conversational-insights"), - CONVERSATIONAL_INSIGHTS_MESSAGES("conversational-insights-messages"), - CONVERSATIONAL_INSIGHTS_VOICE_MINUTES( - "conversational-insights-voice-minutes" - ), - DEMO("demo"), - DEMO_UC_SCRIPT_TEST("demo-uc-script-test"), - ELASTIC_SIP_TRUNKING("elastic-sip-trunking"), - ELASTIC_SIP_TRUNKING_CALL_TRANSFERS( - "elastic-sip-trunking-call-transfers" - ), - ENTERPRISE_HIPPA("enterprise-hippa"), - FLEX_NAMED_USERS("flex-named-users"), - FLEX_SPINSCI("flex-spinsci"), - FLEX_USERS_1("flex-users-1"), - FLEX_WFO_PREMIUM_SPEECH_ANALYTICS("flex-wfo-premium-speech-analytics"), - FLEX_XCELERATE("flex-xcelerate"), - FUNCTIONS_ROLLUP("functions-rollup"), - IMP_V1_USAGE("imp-v1-usage"), - IP_MESSAGING_ADDONS("ip-messaging-addons"), - IVR("ivr"), - IVR_CONVERSATIONAL("ivr-conversational"), - IVR_DTMF("ivr-dtmf"), - IVR_VIRTUALAGENT("ivr-virtualagent"), - LIVE("live"), - LIVE_MEDIA_RECORDING_MINUTES("live-media-recording-minutes"), - LONGCODE_MPS("longcode-mps"), - MARKETPLACE_ANALYTICS_ADDONS("marketplace-analytics-addons"), - MARKETPLACE_ISV_ADDONS("marketplace-isv-addons"), - MARKETPLACE_MESSAGING_ADDONS("marketplace-messaging-addons"), - MARKETPLACE_PHONENUMBERS_ADDONS("marketplace-phonenumbers-addons"), - MARKETPLACE_RECORDING_ADDONS("marketplace-recording-addons"), - MARKETPLACE_VIRTUALAGENT_ADDONS("marketplace-virtualagent-addons"), - MARKETPLAY_PAY_ADDONS_SHUTTLE_PAY_CONNECTOR_1( - "marketplay-pay-addons-shuttle-pay-connector-1" - ), - MARKETPLAY_PAY_ADDONS_STRIPE_PAY_CONNECTOR( - "marketplay-pay-addons-stripe-pay-connector" - ), - MMS_INBOUND_LONGCODE_CANADA("mms-inbound-longcode-canada"), - MMS_INBOUND_LONGCODE_UNITEDSTATES("mms-inbound-longcode-unitedstates"), - MMS_OUTBOUND_LONGCODE_CANADA("mms-outbound-longcode-canada"), - MMS_OUTBOUND_LONGCODE_UNITEDSTATES( - "mms-outbound-longcode-unitedstates" - ), - MMS_OUTBOUND_TOLL_FREE("mms-outbound-toll-free"), - NOTIFY_CHATAPPSANDOTHERCHANNELS("notify-chatappsandotherchannels"), - NOTIFY_NOTIFYSERVICES("notify-notifyservices"), - NOTIFY_PUSHNOTIFICATIONS("notify-pushnotifications"), - PAYMENT_GATEWAY_CONNECTORS("payment-gateway-connectors"), - PAYMENT_SOLUTIONS("payment-solutions"), - PCHAT_BUCKET_ADJUSTMENT("pchat-bucket-adjustment"), - PHONENUMBERS_NUMBERS("phonenumbers-numbers"), - PROG_VOICE_CLIENT_ANDROID("prog-voice-client-android"), - PROG_VOICE_CLIENT_ANDROID_INBOUND("prog-voice-client-android-inbound"), - PROG_VOICE_CLIENT_ANDROID_OUTBOUND( - "prog-voice-client-android-outbound" - ), - PROG_VOICE_CLIENT_IOS("prog-voice-client-ios"), - PROG_VOICE_CLIENT_IOS_INBOUND("prog-voice-client-ios-inbound"), - PROG_VOICE_CLIENT_IOS_OUTBOUND("prog-voice-client-ios-outbound"), - PROG_VOICE_CLIENT_SDK("prog-voice-client-sdk"), - PROG_VOICE_CLIENT_WEB("prog-voice-client-web"), - PROG_VOICE_CLIENT_WEB_INBOUND("prog-voice-client-web-inbound"), - PROG_VOICE_CLIENT_WEB_OUTBOUND("prog-voice-client-web-outbound"), - PROGRAMMABLEVOICECONNECTIVITY_MEDIA_STREAMS( - "programmablevoiceconnectivity-media-streams" - ), - PSTNCONNECTIVITY_BYOC("pstnconnectivity-byoc"), - PSTNCONNECTIVITY_EMERGENCY("pstnconnectivity-emergency"), - PSTNCONNECTIVITY_MINUTES("pstnconnectivity-minutes"), - PSTNCONNECTIVITY_MINUTES_1("pstnconnectivity-minutes-1"), - PSTNCONNECTIVITY_MINUTESINBOUNDLOCAL( - "pstnconnectivity-minutesinboundlocal" - ), - PSTNCONNECTIVITY_MINUTESINBOUNDMOBILE( - "pstnconnectivity-minutesinboundmobile" - ), - PSTNCONNECTIVITY_MINUTESINBOUNDTOLLFREE( - "pstnconnectivity-minutesinboundtollfree" - ), - PSTNCONNECTIVITY_MINUTESINBOUNDTOLLFREELOCAL( - "pstnconnectivity-minutesinboundtollfreelocal" - ), - PSTNCONNECTIVITY_MINUTESINBOUNDTOLLFREEMOBILE( - "pstnconnectivity-minutesinboundtollfreemobile" - ), - PV_ROOM_HOURS("pv-room-hours"), - PV_ROOM_SIMULTANEOUS_PARTICIPANT_CONNECTIONS( - "pv-room-simultaneous-participant-connections" - ), - PVIDEO_ROOM_HOURS_AU1("pvideo-room-hours-au1"), - PVIDEO_ROOM_HOURS_BR1("pvideo-room-hours-br1"), - PVIDEO_ROOM_HOURS_IE1("pvideo-room-hours-ie1"), - PVIDEO_ROOM_HOURS_JP1("pvideo-room-hours-jp1"), - PVIDEO_ROOM_HOURS_SG1("pvideo-room-hours-sg1"), - PVIDEO_ROOM_HOURS_US1("pvideo-room-hours-us1"), - PVIDEO_ROOM_HOURS_US2("pvideo-room-hours-us2"), - RECORDINGS_ENCRYPTED("recordings-encrypted"), - SHORT_CODE_SETUP_FEES("short-code-setup-fees"), - SHORTCODES_MESSAGES_INBOUND("shortcodes-messages-inbound"), - SHORTCODES_MESSAGES_OUTBOUND("shortcodes-messages-outbound"), - SMS_MESSAGES_REGISTRATIONFEES("sms-messages-registrationfees"), - SMS_MMS_PENALTY_FEES("sms-mms-penalty-fees"), - SMS_MMS_PENALTY_FEES_1("sms-mms-penalty-fees-1"), - SMS_PUMPING_PROTECTION_NON_USCA("sms-pumping-protection-non-usca"), - SMS_PUMPING_PROTECTION_USCA("sms-pumping-protection-usca"), - STUDIO("studio"), - STUDIO_MONTHLY_FEES("studio-monthly-fees"), - SUPERSIM("supersim"), - TASK_ROUTER("task-router"), - TASK_ROUTER_WORKERS("task-router-workers"), - TEST_QUOTA_BUCKETS("test-quota-buckets"), - TEST_UC_SCRIPT_1("test-uc-script-1"), - TEST_UC_SCRIPT_DEMO_2("test-uc-script-demo-2"), - TEXT_TO_SPEECH("text-to-speech"), - TME("tme"), - TTS_BASIC("tts-basic"), - TWILIO_EDITIONS("twilio-editions"), - TWILIO_INTERCONNECT_CALIFORNIA("twilio-interconnect-california"), - TWILIO_INTERCONNECT_CALIFORNIA_MONTHLY( - "twilio-interconnect-california-monthly" - ), - TWILIO_INTERCONNECT_CALIFORNIA_SETUP( - "twilio-interconnect-california-setup" - ), - TWILIO_INTERCONNECT_FRANKFURT("twilio-interconnect-frankfurt"), - TWILIO_INTERCONNECT_FRANKFURT_MO("twilio-interconnect-frankfurt-mo"), - TWILIO_INTERCONNECT_FRANKFURT_SETUP( - "twilio-interconnect-frankfurt-setup" - ), - TWILIO_INTERCONNECT_LONDON("twilio-interconnect-london"), - TWILIO_INTERCONNECT_LONDON_MO("twilio-interconnect-london-mo"), - TWILIO_INTERCONNECT_LONDON_SETUP("twilio-interconnect-london-setup"), - TWILIO_INTERCONNECT_SAO_PAULO("twilio-interconnect-sao-paulo"), - TWILIO_INTERCONNECT_SAO_PAULO_MONTHLY( - "twilio-interconnect-sao-paulo-monthly" - ), - TWILIO_INTERCONNECT_SAO_PAULO_SETUP( - "twilio-interconnect-sao-paulo-setup" - ), - TWILIO_INTERCONNECT_SINGAPORE("twilio-interconnect-singapore"), - TWILIO_INTERCONNECT_SINGAPORE_MO("twilio-interconnect-singapore-mo"), - TWILIO_INTERCONNECT_SINGAPORE_SETUP( - "twilio-interconnect-singapore-setup" - ), - TWILIO_INTERCONNECT_SYDNEY("twilio-interconnect-sydney"), - TWILIO_INTERCONNECT_SYDNEY_MO("twilio-interconnect-sydney-mo"), - TWILIO_INTERCONNECT_SYDNEY_SETUP("twilio-interconnect-sydney-setup"), - TWILIO_INTERCONNECT_TOKYO("twilio-interconnect-tokyo"), - TWILIO_INTERCONNECT_TOKYO_MO("twilio-interconnect-tokyo-mo"), - TWILIO_INTERCONNECT_TOKYO_SETUP("twilio-interconnect-tokyo-setup"), - TWILIO_INTERCONNECT_VA("twilio-interconnect-va"), - TWILIO_INTERCONNECT_VA_MO("twilio-interconnect-va-mo"), - TWILIO_INTERCONNECT_VA_SETUP("twilio-interconnect-va-setup"), - TWIML_VERBS("twiml-verbs"), - TWIML_VERBS_SAY("twiml-verbs-say"), - USAGE_PROGRAMMABLE_MESSAGING_ENGAGEMENT_SUITE( - "usage-programmable-messaging-engagement-suite" - ), - USAGE_PROGRAMMABLE_MESSAGING_FEES_SERVICES( - "usage-programmable-messaging-fees-services" - ), - VERIFY_OUTBOUND_EMAIL("verify-outbound-email"), - VERIFY_PACKAGED_PLANS("verify-packaged-plans"), - VERIFY_SILENT_NETWORK_AUTH("verify-silent-network-auth"), - VERIFY_VOICE_AND_SMS("verify-voice-and-sms"), - VOICE_INSIGHTS_CLIENT_INSIGHTS_MONTHY_COMMIT( - "voice-insights-client-insights-monthy-commit" - ), - WIRELESS_DATA_PAYG_ASIA_AFG("wireless-data-payg-asia-afg"), - WIRELESS_MULTI_IMSI_SIM_COMMANDS("wireless-multi-imsi-sim-commands"), - WIRELESS_MULTI_IMSI_SIM_COMMANDS_USA( - "wireless-multi-imsi-sim-commands-usa" - ), - WIRELESS_MULTI_IMSI_SIM_DATA("wireless-multi-imsi-sim-data"), - WIRELESS_MULTI_IMSI_SIM_DATA_EU28("wireless-multi-imsi-sim-data-eu28"), - WIRELESS_MULTI_IMSI_SIM_DATA_USA("wireless-multi-imsi-sim-data-usa"), - WIRELESS_MULTI_IMSI_SIM_MONTHLY_FEES( - "wireless-multi-imsi-sim-monthly-fees" - ), - WIRELESS_MULTI_IMSI_SIM_USAGE("wireless-multi-imsi-sim-usage"), - WIRELESS_SUPER_SIM_DATA_NORTH_AMERICA( - "wireless-super-sim-data-north-america" - ), - WIRELESS_SUPER_SIM_USAGE("wireless-super-sim-usage"); - - private final String value; - - private Category(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static Category forValue(final String value) { - return Promoter.enumFromString(value, Category.values()); - } - } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/usage/record/AllTimeReader.java b/src/main/java/com/twilio/rest/api/v2010/account/usage/record/AllTimeReader.java index a37156682f..5d8d1e2f79 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/usage/record/AllTimeReader.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/usage/record/AllTimeReader.java @@ -32,7 +32,7 @@ public class AllTimeReader extends Reader { private String pathAccountSid; - private AllTime.Category category; + private String category; private LocalDate startDate; private LocalDate endDate; private Boolean includeSubaccounts; @@ -44,7 +44,7 @@ public AllTimeReader(final String pathAccountSid) { this.pathAccountSid = pathAccountSid; } - public AllTimeReader setCategory(final AllTime.Category category) { + public AllTimeReader setCategory(final String category) { this.category = category; return this; } @@ -168,7 +168,7 @@ public Page getPage( private void addQueryParams(final Request request) { if (category != null) { - request.addQueryParam("Category", category.toString()); + request.addQueryParam("Category", category); } if (startDate != null) { request.addQueryParam( diff --git a/src/main/java/com/twilio/rest/api/v2010/account/usage/record/Daily.java b/src/main/java/com/twilio/rest/api/v2010/account/usage/record/Daily.java index 854ee718c6..34441ee37d 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/usage/record/Daily.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/usage/record/Daily.java @@ -24,7 +24,6 @@ import com.twilio.base.Resource; import com.twilio.converter.CurrencyDeserializer; import com.twilio.converter.DateConverter; -import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import java.io.IOException; @@ -42,7 +41,7 @@ @ToString public class Daily extends Resource { - private static final long serialVersionUID = 73710721233963L; + private static final long serialVersionUID = 158026917970511L; public static DailyReader reader() { return new DailyReader(); @@ -98,7 +97,7 @@ public static Daily fromJson( private final String accountSid; private final String apiVersion; private final String asOf; - private final Daily.Category category; + private final String category; private final String count; private final String countUnit; private final String description; @@ -116,7 +115,7 @@ private Daily( @JsonProperty("account_sid") final String accountSid, @JsonProperty("api_version") final String apiVersion, @JsonProperty("as_of") final String asOf, - @JsonProperty("category") final Daily.Category category, + @JsonProperty("category") final String category, @JsonProperty("count") final String count, @JsonProperty("count_unit") final String countUnit, @JsonProperty("description") final String description, @@ -163,7 +162,7 @@ public final String getAsOf() { return this.asOf; } - public final Daily.Category getCategory() { + public final String getCategory() { return this.category; } @@ -262,945 +261,4 @@ public int hashCode() { usageUnit ); } - - public enum Category { - A2P_10DLC_REGISTRATIONFEES_BRANDREGISTRATION( - "a2p-10dlc-registrationfees-brandregistration" - ), - A2P_10DLC_REGISTRATIONFEES_BV("a2p-10dlc-registrationfees-bv"), - A2P_10DLC_REGISTRATIONFEES_CAMPAIGNCHARGES( - "a2p-10dlc-registrationfees-campaigncharges" - ), - A2P_10DLC_REGISTRATIONFEES_CAMPAIGNREGISTRATION( - "a2p-10dlc-registrationfees-campaignregistration" - ), - A2P_10DLC_REGISTRATIONFEES_CAMPAIGNVETTING( - "a2p-10dlc-registrationfees-campaignvetting" - ), - A2P_10DLC_REGISTRATIONFEES_MONTHLY( - "a2p-10dlc-registrationfees-monthly" - ), - A2P_10DLC_REGISTRATIONFEES_ONETIME( - "a2p-10dlc-registrationfees-onetime" - ), - A2P_REGISTRATION_FEES("a2p-registration-fees"), - ACCOUNT_SECURITY("account-security"), - AGENT_CONFERENCE("agent-conference"), - AGENT_COPILOT("agent-copilot"), - AGENT_COPILOT_MESSAGES("agent-copilot-messages"), - AGENT_COPILOT_PARTICIPANT_MINUTES("agent-copilot-participant-minutes"), - AI_ASSISTANTS("ai-assistants"), - AI_ASSISTANTS_VOICE("ai-assistants-voice"), - AMAZON_POLLY("amazon-polly"), - ANSWERING_MACHINE_DETECTION("answering-machine-detection"), - ASSETS("assets"), - AUDIENCE_MINUTES("audience-minutes"), - AUDIENCE_MINUTES_AUDIO("audience-minutes-audio"), - AUTHY_AUTHENTICATIONS("authy-authentications"), - AUTHY_CALLS_OUTBOUND("authy-calls-outbound"), - AUTHY_EMAIL_AUTHENTICATIONS("authy-email-authentications"), - AUTHY_MONTHLY_FEES("authy-monthly-fees"), - AUTHY_OUTBOUND_EMAIL("authy-outbound-email"), - AUTHY_PHONE_INTELLIGENCE("authy-phone-intelligence"), - AUTHY_PHONE_VERIFICATIONS("authy-phone-verifications"), - AUTHY_SMS_OUTBOUND("authy-sms-outbound"), - AUTHY_VERIFY_EMAIL_VERIFICATIONS("authy-verify-email-verifications"), - AUTHY_VERIFY_OUTBOUND_EMAIL("authy-verify-outbound-email"), - AUTOPILOT("autopilot"), - AUTOPILOT_HOME_ASSISTANTS("autopilot-home-assistants"), - AUTOPILOT_MESSAGING("autopilot-messaging"), - AUTOPILOT_OTHER("autopilot-other"), - AUTOPILOT_VOICE("autopilot-voice"), - BASIC_PEER_TO_PEER_ROOMS_PARTICIPANT_MINUTES( - "basic-peer-to-peer-rooms-participant-minutes" - ), - BRANDED_CALLING("branded-calling"), - BUNDLE_SMS_BUCKET("bundle-sms-bucket"), - BUNDLE_SUBSCRIPTION_FEES("bundle-subscription-fees"), - CALL_FORWARDING_LOOKUPS("call-forwarding-lookups"), - CALL_PROGESS_EVENTS("call-progess-events"), - CALLERIDLOOKUPS("calleridlookups"), - CALLS("calls"), - CALLS_CLIENT("calls-client"), - CALLS_EMERGENCY("calls-emergency"), - CALLS_GLOBALCONFERENCE("calls-globalconference"), - CALLS_INBOUND("calls-inbound"), - CALLS_INBOUND_LOCAL("calls-inbound-local"), - CALLS_INBOUND_MOBILE("calls-inbound-mobile"), - CALLS_INBOUND_TOLLFREE("calls-inbound-tollfree"), - CALLS_INBOUND_TOLLFREE_LOCAL("calls-inbound-tollfree-local"), - CALLS_INBOUND_TOLLFREE_MOBILE("calls-inbound-tollfree-mobile"), - CALLS_MEDIA_STREAM_MINUTES("calls-media-stream-minutes"), - CALLS_OUTBOUND("calls-outbound"), - CALLS_PAY_VERB_TRANSACTIONS("calls-pay-verb-transactions"), - CALLS_RECORDINGS("calls-recordings"), - CALLS_SIP("calls-sip"), - CALLS_SIP_INBOUND("calls-sip-inbound"), - CALLS_SIP_OUTBOUND("calls-sip-outbound"), - CALLS_TEXT_TO_SPEECH("calls-text-to-speech"), - CALLS_TRANSFERS("calls-transfers"), - CARRIER_LOOKUPS("carrier-lookups"), - CATEGORY("category"), - CHANNELS("channels"), - CHANNELS_MESSAGING("channels-messaging"), - CHANNELS_MESSAGING_INBOUND("channels-messaging-inbound"), - CHANNELS_MESSAGING_OUTBOUND("channels-messaging-outbound"), - CHANNELS_WHATSAPP("channels-whatsapp"), - CHANNELS_WHATSAPP_CONVERSATION_AUTHENTICATION( - "channels-whatsapp-conversation-authentication" - ), - CHANNELS_WHATSAPP_CONVERSATION_FREE( - "channels-whatsapp-conversation-free" - ), - CHANNELS_WHATSAPP_CONVERSATION_MARKETING( - "channels-whatsapp-conversation-marketing" - ), - CHANNELS_WHATSAPP_CONVERSATION_SERVICE( - "channels-whatsapp-conversation-service" - ), - CHANNELS_WHATSAPP_CONVERSATION_UTILITY( - "channels-whatsapp-conversation-utility" - ), - CHANNELS_WHATSAPP_INBOUND("channels-whatsapp-inbound"), - CHANNELS_WHATSAPP_OUTBOUND("channels-whatsapp-outbound"), - CHANNELS_WHATSAPP_SERVICE("channels-whatsapp-service"), - CHANNELS_WHATSAPP_TEMPLATE_AUTHENTICATION( - "channels-whatsapp-template-authentication" - ), - CHANNELS_WHATSAPP_TEMPLATE_MARKETING( - "channels-whatsapp-template-marketing" - ), - CHANNELS_WHATSAPP_TEMPLATE_SERVICE( - "channels-whatsapp-template-service" - ), - CHANNELS_WHATSAPP_TEMPLATE_UTILITY( - "channels-whatsapp-template-utility" - ), - CHAT_VIRTUAL_AGENT("chat-virtual-agent"), - CONVERSATION_RELAY("conversation-relay"), - CONVERSATIONS("conversations"), - CONVERSATIONS_API_REQUESTS("conversations-api-requests"), - CONVERSATIONS_CONVERSATION_EVENTS("conversations-conversation-events"), - CONVERSATIONS_ENDPOINT_CONNECTIVITY( - "conversations-endpoint-connectivity" - ), - CONVERSATIONS_EVENTS("conversations-events"), - CONVERSATIONS_PARTICIPANT_EVENTS("conversations-participant-events"), - CONVERSATIONS_PARTICIPANTS("conversations-participants"), - CPS("cps"), - CREDIT_TRANSFER("credit-transfer"), - EMAIL("email"), - EMERGING_TECH("emerging-tech"), - ENGAGEMENT_SUITE_PACKAGED_PLANS("engagement-suite-packaged-plans"), - ENHANCED_LINE_TYPE_LOOKUPS("enhanced-line-type-lookups"), - ENTERPRISE("enterprise"), - EVENTS("events"), - EXPERIMENT_FRANCE_SMS("experiment-france-sms"), - EXPERIMENT_INDIA_SMS("experiment-india-sms"), - EXPERIMENT_UK_SMS("experiment-uk-sms"), - FAILED_MESSAGE_PROCESSING_FEE("failed-message-processing-fee"), - FLEX("flex"), - FLEX_ACTIVE_USER_HOURS("flex-active-user-hours"), - FLEX_CONCURRENT_USERS("flex-concurrent-users"), - FLEX_CONVERSATIONAL_INSIGHTS("flex-conversational-insights"), - FLEX_CONVERSATIONAL_INSIGHTS_MESSAGES( - "flex-conversational-insights-messages" - ), - FLEX_CONVERSATIONAL_INSIGHTS_VOICE_MINUTES( - "flex-conversational-insights-voice-minutes" - ), - FLEX_EMAIL_USAGE("flex-email-usage"), - FLEX_MESSAGING_USAGE("flex-messaging-usage"), - FLEX_PARTNER_SPINSCI("flex-partner-spinsci"), - FLEX_PARTNER_XCELERATE("flex-partner-xcelerate"), - FLEX_RESELLER_ECOSYSTEM("flex-reseller-ecosystem"), - FLEX_UNIQUE_USER("flex-unique-user"), - FLEX_USAGE("flex-usage"), - FLEX_USERS("flex-users"), - FLEX_VOICE_MINUTE("flex-voice-minute"), - FLEX_YTICA("flex-ytica"), - FRAUD_LOOKUPS("fraud-lookups"), - FRONTLINE("frontline"), - FRONTLINE_USERS("frontline-users"), - FUNCTIONS("functions"), - GENERIC_PAY_TRANSACTIONS("generic-pay-transactions"), - GROUP_ROOMS("group-rooms"), - GROUP_ROOMS_DATA_TRACK("group-rooms-data-track"), - GROUP_ROOMS_ENCRYPTED_MEDIA_RECORDED( - "group-rooms-encrypted-media-recorded" - ), - GROUP_ROOMS_MEDIA_DOWNLOADED("group-rooms-media-downloaded"), - GROUP_ROOMS_MEDIA_RECORDED("group-rooms-media-recorded"), - GROUP_ROOMS_MEDIA_ROUTED("group-rooms-media-routed"), - GROUP_ROOMS_MEDIA_STORED("group-rooms-media-stored"), - GROUP_ROOMS_PARTICIPANT_MINUTES("group-rooms-participant-minutes"), - GROUP_ROOMS_RECORDED_MINUTES("group-rooms-recorded-minutes"), - IP_MESSAGING("ip-messaging"), - IP_MESSAGING_COMMANDS("ip-messaging-commands"), - IP_MESSAGING_DATA_STORAGE("ip-messaging-data-storage"), - IP_MESSAGING_DATA_TRANSFER("ip-messaging-data-transfer"), - IP_MESSAGING_ENDPOINT_CONNECTIVITY( - "ip-messaging-endpoint-connectivity" - ), - IVR_VIRTUAL_AGENT_CUSTOM_VOICES("ivr-virtual-agent-custom-voices"), - IVR_VIRTUAL_AGENT_GENAI("ivr-virtual-agent-genai"), - LINE_STATUS_LOOKUPS("line-status-lookups"), - LIVE_ACTIVITY_LOOKUPS("live-activity-lookups"), - LOOKUP_BUCKET_ADJUSTMENT("lookup-bucket-adjustment"), - LOOKUP_IDENTITY_MATCH("lookup-identity-match"), - LOOKUPS("lookups"), - MARKETPLACE("marketplace"), - MARKETPLACE_ALGORITHMIA_NAMED_ENTITY_RECOGNITION( - "marketplace-algorithmia-named-entity-recognition" - ), - MARKETPLACE_CADENCE_TRANSCRIPTION("marketplace-cadence-transcription"), - MARKETPLACE_CADENCE_TRANSLATION("marketplace-cadence-translation"), - MARKETPLACE_CAPIO_SPEECH_TO_TEXT("marketplace-capio-speech-to-text"), - MARKETPLACE_CONVRIZA_ABABA("marketplace-convriza-ababa"), - MARKETPLACE_DEEPGRAM_PHRASE_DETECTOR( - "marketplace-deepgram-phrase-detector" - ), - MARKETPLACE_DEEPGRAM_TRANSCRIPTION( - "marketplace-deepgram-transcription" - ), - MARKETPLACE_DEEPGRAM_TRANSCRIPTION_BASE( - "marketplace-deepgram-transcription-base" - ), - MARKETPLACE_DEEPGRAM_TRANSSCRIPTION_ENHANCED( - "marketplace-deepgram-transscription-enhanced" - ), - MARKETPLACE_DIGITAL_SEGMENT_BUSINESS_INFO( - "marketplace-digital-segment-business-info" - ), - MARKETPLACE_FACEBOOK_OFFLINE_CONVERSIONS( - "marketplace-facebook-offline-conversions" - ), - MARKETPLACE_GOOGLE_SPEECH_TO_TEXT("marketplace-google-speech-to-text"), - MARKETPLACE_IBM_WATSON_MESSAGE_INSIGHTS( - "marketplace-ibm-watson-message-insights" - ), - MARKETPLACE_IBM_WATSON_MESSAGE_SENTIMENT( - "marketplace-ibm-watson-message-sentiment" - ), - MARKETPLACE_IBM_WATSON_RECORDING_ANALYSIS( - "marketplace-ibm-watson-recording-analysis" - ), - MARKETPLACE_IBM_WATSON_TONE_ANALYZER( - "marketplace-ibm-watson-tone-analyzer" - ), - MARKETPLACE_ICEHOOK_SYSTEMS_SCOUT("marketplace-icehook-systems-scout"), - MARKETPLACE_INFOGROUP_DATAAXLE_BIZINFO( - "marketplace-infogroup-dataaxle-bizinfo" - ), - MARKETPLACE_KEEN_IO_CONTACT_CENTER_ANALYTICS( - "marketplace-keen-io-contact-center-analytics" - ), - MARKETPLACE_MARCHEX_CLEANCALL("marketplace-marchex-cleancall"), - MARKETPLACE_MARCHEX_RECORDING_ANALYSIS( - "marketplace-marchex-recording-analysis" - ), - MARKETPLACE_MARCHEX_SENTIMENT_ANALYSIS_FOR_SMS( - "marketplace-marchex-sentiment-analysis-for-sms" - ), - MARKETPLACE_MARKETPLACE_NEXTCALLER_SOCIAL_ID( - "marketplace-marketplace-nextcaller-social-id" - ), - MARKETPLACE_MOBILE_COMMONS_OPT_OUT_CLASSIFIER( - "marketplace-mobile-commons-opt-out-classifier" - ), - MARKETPLACE_NEXIWAVE_VOICEMAIL_TO_TEXT( - "marketplace-nexiwave-voicemail-to-text" - ), - MARKETPLACE_NEXTCALLER_ADVANCED_CALLER_IDENTIFICATION( - "marketplace-nextcaller-advanced-caller-identification" - ), - MARKETPLACE_NOMOROBO_SPAM_SCORE("marketplace-nomorobo-spam-score"), - MARKETPLACE_PAY_ADDONS("marketplace-pay-addons"), - MARKETPLACE_PAY_ADDONS_BASECOMMERCE_PAY_CONNECTOR( - "marketplace-pay-addons-basecommerce-pay-connector" - ), - MARKETPLACE_PAY_ADDONS_BRAINTREE_PAY_CONNECTOR( - "marketplace-pay-addons-braintree-pay-connector" - ), - MARKETPLACE_PAY_ADDONS_CARDCONNECT_PAY_CONNECTOR( - "marketplace-pay-addons-cardconnect-pay-connector" - ), - MARKETPLACE_PAY_ADDONS_CHASE_PAY_CONNECTOR( - "marketplace-pay-addons-chase-pay-connector" - ), - MARKETPLACE_PAY_ADDONS_SHUTTLE_PAY_CONNECTOR( - "marketplace-pay-addons-shuttle-pay-connector" - ), - MARKETPLACE_PAY_ADDONS_STRIPE_PAY_CONNECTOR( - "marketplace-pay-addons-stripe-pay-connector" - ), - MARKETPLACE_PAYFONE_TCPA_COMPLIANCE( - "marketplace-payfone-tcpa-compliance" - ), - MARKETPLACE_POLY_AI_CONNECTOR("marketplace-poly-ai-connector"), - MARKETPLACE_REALPHONEVALIDATION("marketplace-realphonevalidation"), - MARKETPLACE_REMEETING_AUTOMATIC_SPEECH_RECOGNITION( - "marketplace-remeeting-automatic-speech-recognition" - ), - MARKETPLACE_SPOKE_PHONE_LICENSE_PRO( - "marketplace-spoke-phone-license-pro" - ), - MARKETPLACE_SPOKE_PHONE_LICENSE_STANDARD( - "marketplace-spoke-phone-license-standard" - ), - MARKETPLACE_TCPA_DEFENSE_SOLUTIONS_BLACKLIST_FEED( - "marketplace-tcpa-defense-solutions-blacklist-feed" - ), - MARKETPLACE_TELO_OPENCNAM("marketplace-telo-opencnam"), - MARKETPLACE_TRESTLE_SOLUTIONS_CALLER_IDENTIFICATION( - "marketplace-trestle-solutions-caller-identification" - ), - MARKETPLACE_TRUECNAM_TRUE_SPAM("marketplace-truecnam-true-spam"), - MARKETPLACE_TWILIO_CALLER_NAME_LOOKUP_US( - "marketplace-twilio-caller-name-lookup-us" - ), - MARKETPLACE_TWILIO_CARRIER_INFORMATION_LOOKUP( - "marketplace-twilio-carrier-information-lookup" - ), - MARKETPLACE_VOICEBASE_PCI("marketplace-voicebase-pci"), - MARKETPLACE_VOICEBASE_TRANSCRIPTION( - "marketplace-voicebase-transcription" - ), - MARKETPLACE_VOICEBASE_TRANSCRIPTION_CUSTOM_VOCABULARY( - "marketplace-voicebase-transcription-custom-vocabulary" - ), - MARKETPLACE_WEB_PURIFY_PROFANITY_FILTER( - "marketplace-web-purify-profanity-filter" - ), - MARKETPLACE_WHITEPAGES_PRO_CALLER_IDENTIFICATION( - "marketplace-whitepages-pro-caller-identification" - ), - MARKETPLACE_WHITEPAGES_PRO_PHONE_INTELLIGENCE( - "marketplace-whitepages-pro-phone-intelligence" - ), - MARKETPLACE_WHITEPAGES_PRO_PHONE_REPUTATION( - "marketplace-whitepages-pro-phone-reputation" - ), - MARKETPLACE_WOLFARM_SPOKEN_RESULTS( - "marketplace-wolfarm-spoken-results" - ), - MARKETPLACE_WOLFRAM_SHORT_ANSWER("marketplace-wolfram-short-answer"), - MARKETPLACE_YTICA_CONTACT_CENTER_REPORTING_ANALYTICS( - "marketplace-ytica-contact-center-reporting-analytics" - ), - MARKETPLAY_PAY_ADDONS_SHUTTLE_PAY_CONNECTOR( - "marketplay-pay-addons-shuttle-pay-connector" - ), - MEDIA_COMPOSER_MINUTES("media-composer-minutes"), - MEDIASTORAGE("mediastorage"), - MIN_SPEND_ADJUSTMENTS("min-spend-adjustments"), - MMS("mms"), - MMS_INBOUND("mms-inbound"), - MMS_INBOUND_LONGCODE("mms-inbound-longcode"), - MMS_INBOUND_SHORTCODE("mms-inbound-shortcode"), - MMS_INBOUND_TOLL_FREE("mms-inbound-toll-free"), - MMS_MESSAGES_CARRIERFEES("mms-messages-carrierfees"), - MMS_OUTBOUND("mms-outbound"), - MMS_OUTBOUND_LONGCODE("mms-outbound-longcode"), - MMS_OUTBOUND_SHORTCODE("mms-outbound-shortcode"), - MMS_OUTBOUND_TOLLFREE("mms-outbound-tollfree"), - MONITOR("monitor"), - MONITOR_READS("monitor-reads"), - MONITOR_STORAGE("monitor-storage"), - MONITOR_WRITES("monitor-writes"), - NOTIFY("notify"), - NOTIFY_ACTIONS_ATTEMPTS("notify-actions-attempts"), - NOTIFY_CHANNELS("notify-channels"), - NUMBER_FORMAT_LOOKUPS("number-format-lookups"), - PCHAT("pchat"), - PCHAT_ACTIONS("pchat-actions"), - PCHAT_APS("pchat-aps"), - PCHAT_CONV_MED_STORAGE("pchat-conv-med-storage"), - PCHAT_MESSAGES("pchat-messages"), - PCHAT_NOTIFICATIONS("pchat-notifications"), - PCHAT_READS("pchat-reads"), - PCHAT_USERS("pchat-users"), - PEER_TO_PEER_ROOMS_PARTICIPANT_MINUTES( - "peer-to-peer-rooms-participant-minutes" - ), - PFAX("pfax"), - PFAX_MINUTES("pfax-minutes"), - PFAX_MINUTES_INBOUND("pfax-minutes-inbound"), - PFAX_MINUTES_OUTBOUND("pfax-minutes-outbound"), - PFAX_PAGES("pfax-pages"), - PHONE_QUALITY_SCORE_LOOKUPS("phone-quality-score-lookups"), - PHONENUMBERS("phonenumbers"), - PHONENUMBERS_CPS("phonenumbers-cps"), - PHONENUMBERS_EMERGENCY("phonenumbers-emergency"), - PHONENUMBERS_LOCAL("phonenumbers-local"), - PHONENUMBERS_MOBILE("phonenumbers-mobile"), - PHONENUMBERS_PORTING("phonenumbers-porting"), - PHONENUMBERS_SETUPS("phonenumbers-setups"), - PHONENUMBERS_TOLLFREE("phonenumbers-tollfree"), - PREMIUMSUPPORT("premiumsupport"), - PREMIUMSUPPORT_PERCENTAGE_SPEND("premiumsupport-percentage-spend"), - PROGRAMMABLEVOICE_PLATFORM("programmablevoice-platform"), - PROGRAMMABLEVOICECONN_CLIENTSDK("programmablevoiceconn-clientsdk"), - PROGRAMMABLEVOICECONN_CLIENTSDK_INBOUND( - "programmablevoiceconn-clientsdk-inbound" - ), - PROGRAMMABLEVOICECONN_CLIENTSDK_OUTBOUND( - "programmablevoiceconn-clientsdk-outbound" - ), - PROGRAMMABLEVOICECONN_ONNET("programmablevoiceconn-onnet"), - PROGRAMMABLEVOICECONN_ONNET_INBOUND( - "programmablevoiceconn-onnet-inbound" - ), - PROGRAMMABLEVOICECONN_ONNET_OUTBOUND( - "programmablevoiceconn-onnet-outbound" - ), - PROGRAMMABLEVOICECONN_SIP("programmablevoiceconn-sip"), - PROGRAMMABLEVOICECONN_SIP_INBOUND("programmablevoiceconn-sip-inbound"), - PROGRAMMABLEVOICECONN_SIP_OUTBOUND( - "programmablevoiceconn-sip-outbound" - ), - PROGRAMMABLEVOICECONNECTIVITY("programmablevoiceconnectivity"), - PROXY("proxy"), - PROXY_ACTIVE_SESSIONS("proxy-active-sessions"), - PROXY_BUCKET_ADJUSTMENT("proxy-bucket-adjustment"), - PROXY_LICENSES("proxy-licenses"), - PSTNCONNECTIVITY("pstnconnectivity"), - PSTNCONNECTIVITY_INBOUND("pstnconnectivity-inbound"), - PSTNCONNECTIVITY_OUTBOUND("pstnconnectivity-outbound"), - PV("pv"), - PV_BASIC_ROOMS("pv-basic-rooms"), - PV_COMPOSITION_MEDIA_DOWNLOADED("pv-composition-media-downloaded"), - PV_COMPOSITION_MEDIA_ENCRYPTED("pv-composition-media-encrypted"), - PV_COMPOSITION_MEDIA_STORED("pv-composition-media-stored"), - PV_COMPOSITION_MINUTES("pv-composition-minutes"), - PV_RECORDING_COMPOSITIONS("pv-recording-compositions"), - PV_ROOM_PARTICIPANTS("pv-room-participants"), - PV_ROOM_PARTICIPANTS_AU1("pv-room-participants-au1"), - PV_ROOM_PARTICIPANTS_BR1("pv-room-participants-br1"), - PV_ROOM_PARTICIPANTS_IE1("pv-room-participants-ie1"), - PV_ROOM_PARTICIPANTS_JP1("pv-room-participants-jp1"), - PV_ROOM_PARTICIPANTS_SG1("pv-room-participants-sg1"), - PV_ROOM_PARTICIPANTS_US1("pv-room-participants-us1"), - PV_ROOM_PARTICIPANTS_US2("pv-room-participants-us2"), - PV_ROOMS("pv-rooms"), - PV_SIP_ENDPOINT_REGISTRATIONS("pv-sip-endpoint-registrations"), - RCS_MESSAGES("rcs-messages"), - REASSIGNED_NUMBER("reassigned-number"), - RECORDINGS("recordings"), - RECORDINGSTORAGE("recordingstorage"), - SHORTCODES("shortcodes"), - SHORTCODES_CUSTOMEROWNED("shortcodes-customerowned"), - SHORTCODES_MMS_ENABLEMENT("shortcodes-mms-enablement"), - SHORTCODES_MPS("shortcodes-mps"), - SHORTCODES_RANDOM("shortcodes-random"), - SHORTCODES_SETUP_FEES("shortcodes-setup-fees"), - SHORTCODES_UK("shortcodes-uk"), - SHORTCODES_VANITY("shortcodes-vanity"), - SIM_SWAP_LOOKUPS("sim-swap-lookups"), - SIP_SECURE_MEDIA("sip-secure-media"), - SMALL_GROUP_ROOMS("small-group-rooms"), - SMALL_GROUP_ROOMS_DATA_TRACK("small-group-rooms-data-track"), - SMALL_GROUP_ROOMS_PARTICIPANT_MINUTES( - "small-group-rooms-participant-minutes" - ), - SMS("sms"), - SMS_INBOUND("sms-inbound"), - SMS_INBOUND_LONGCODE("sms-inbound-longcode"), - SMS_INBOUND_SHORTCODE("sms-inbound-shortcode"), - SMS_INBOUND_TOLLFREE("sms-inbound-tollfree"), - SMS_MESSAGES_CARRIERFEES("sms-messages-carrierfees"), - SMS_MESSAGES_FEATURES("sms-messages-features"), - SMS_MESSAGES_FEATURES_ENGAGEMENT_SUITE( - "sms-messages-features-engagement-suite" - ), - SMS_MESSAGES_FEATURES_MESSAGE_REDACTION( - "sms-messages-features-message-redaction" - ), - SMS_MESSAGES_FEATURES_SENDERID("sms-messages-features-senderid"), - SMS_MPS("sms-mps"), - SMS_MPS_SHORTCODE("sms-mps-shortcode"), - SMS_MPS_TOLLFREE("sms-mps-tollfree"), - SMS_MPS_TOLLFREE_SETUP("sms-mps-tollfree-setup"), - SMS_NATIONAL_REGULATORY_PROTECTION( - "sms-national-regulatory-protection" - ), - SMS_OUTBOUND("sms-outbound"), - SMS_OUTBOUND_CONTENT_INSPECTION("sms-outbound-content-inspection"), - SMS_OUTBOUND_LONGCODE("sms-outbound-longcode"), - SMS_OUTBOUND_SHORTCODE("sms-outbound-shortcode"), - SMS_OUTBOUND_TOLLFREE("sms-outbound-tollfree"), - SMS_PUMPING_PROTECTION("sms-pumping-protection"), - SMS_PUMPING_RISK("sms-pumping-risk"), - SMSMESSAGES_BUCKET_ADJUSTMENTS("smsmessages-bucket-adjustments"), - SMSMESSAGES_OUTBOUND_DOMESTIC("smsmessages-outbound-domestic"), - SPEECH_RECOGNITION("speech-recognition"), - STUDIO_ENGAGEMENTS("studio-engagements"), - SYNC("sync"), - SYNC_ACTIONS("sync-actions"), - SYNC_ENDPOINT_HOURS("sync-endpoint-hours"), - SYNC_ENDPOINT_HOURS_ABOVE_DAILY_CAP( - "sync-endpoint-hours-above-daily-cap" - ), - TASKROUTER_TASKS("taskrouter-tasks"), - TOTALPRICE("totalprice"), - TRANSCRIPTIONS("transcriptions"), - TRUNKING_CPS("trunking-cps"), - TRUNKING_EMERGENCY_CALLS("trunking-emergency-calls"), - TRUNKING_ORIGINATION("trunking-origination"), - TRUNKING_ORIGINATION_LOCAL("trunking-origination-local"), - TRUNKING_ORIGINATION_MOBILE("trunking-origination-mobile"), - TRUNKING_ORIGINATION_TOLLFREE("trunking-origination-tollfree"), - TRUNKING_RECORDINGS("trunking-recordings"), - TRUNKING_SECURE("trunking-secure"), - TRUNKING_TERMINATION("trunking-termination"), - TTS_GOOGLE("tts-google"), - TURNMEGABYTES("turnmegabytes"), - TURNMEGABYTES_AUSTRALIA("turnmegabytes-australia"), - TURNMEGABYTES_BRASIL("turnmegabytes-brasil"), - TURNMEGABYTES_GERMANY("turnmegabytes-germany"), - TURNMEGABYTES_INDIA("turnmegabytes-india"), - TURNMEGABYTES_IRELAND("turnmegabytes-ireland"), - TURNMEGABYTES_JAPAN("turnmegabytes-japan"), - TURNMEGABYTES_SINGAPORE("turnmegabytes-singapore"), - TURNMEGABYTES_USEAST("turnmegabytes-useast"), - TURNMEGABYTES_USWEST("turnmegabytes-uswest"), - TWILIO_FOR_SALESFORCE("twilio-for-salesforce"), - TWILIO_FOR_SALESFORCE_LICENSES("twilio-for-salesforce-licenses"), - TWILIO_INTERCONNECT("twilio-interconnect"), - TWIML("twiml"), - USAGE_FLEX_VIDEO("usage-flex-video"), - USAGE_FUNCTIONS("usage-functions"), - USAGE_RCS_BASIC_MESSAGES_OUTBOUND("usage-rcs-basic-messages-outbound"), - USAGE_RCS_MESSAGES("usage-rcs-messages"), - USAGE_RCS_MESSAGES_INBOUND("usage-rcs-messages-inbound"), - USAGE_RCS_MESSAGING_CARRIER_FEES("usage-rcs-messaging-carrier-fees"), - USAGE_RCS_SINGLE_MESSAGES_OUTBOUND( - "usage-rcs-single-messages-outbound" - ), - VERIFY_PACKAGE_PLANS("verify-package-plans"), - VERIFY_PUSH("verify-push"), - VERIFY_SNA("verify-sna"), - VERIFY_TOTP("verify-totp"), - VERIFY_VOICE_SMS("verify-voice-sms"), - VERIFY_WHATSAPP_CONVERSATIONS_BUSINESS_INITIATED( - "verify-whatsapp-conversations-business-initiated" - ), - VERIFY_WHATSAPP_TEMPLATE_BUSINESS_INITIATED( - "verify-whatsapp-template-business-initiated" - ), - VIDEO_RECORDINGS("video-recordings"), - VIDEO_ROOMS_TURN_MEGABYTES("video-rooms-turn-megabytes"), - VIRTUAL_AGENT("virtual-agent"), - VOICE_INSIGHTS("voice-insights"), - VOICE_INSIGHTS_CLIENT_INSIGHTS_ON_DEMAND_MINUTE( - "voice-insights-client-insights-on-demand-minute" - ), - VOICE_INSIGHTS_PTSN_INSIGHTS_ON_DEMAND_MINUTE( - "voice-insights-ptsn-insights-on-demand-minute" - ), - VOICE_INSIGHTS_SIP_INTERFACE_INSIGHTS_ON_DEMAND_MINUTE( - "voice-insights-sip-interface-insights-on-demand-minute" - ), - VOICE_INSIGHTS_SIP_TRUNKING_INSIGHTS_ON_DEMAND_MINUTE( - "voice-insights-sip-trunking-insights-on-demand-minute" - ), - VOICE_INTELLIGENCE("voice-intelligence"), - VOICE_INTELLIGENCE_EIP_OPERATORS("voice-intelligence-eip-operators"), - VOICE_INTELLIGENCE_OPERATORS("voice-intelligence-operators"), - VOICE_INTELLIGENCE_TRANSCRIPTION("voice-intelligence-transcription"), - WDS("wds"), - WIRELESS("wireless"), - WIRELESS_DATA("wireless-data"), - WIRELESS_DATA_PAYG("wireless-data-payg"), - WIRELESS_DATA_PAYG_AFRICA("wireless-data-payg-africa"), - WIRELESS_DATA_PAYG_ASIA("wireless-data-payg-asia"), - WIRELESS_DATA_PAYG_CENTRALANDSOUTHAMERICA( - "wireless-data-payg-centralandsouthamerica" - ), - WIRELESS_DATA_PAYG_EUROPE("wireless-data-payg-europe"), - WIRELESS_DATA_PAYG_NORTHAMERICA("wireless-data-payg-northamerica"), - WIRELESS_DATA_PAYG_OCEANIA("wireless-data-payg-oceania"), - WIRELESS_DATA_QUOTA1("wireless-data-quota1"), - WIRELESS_DATA_QUOTA1_AFRICA("wireless-data-quota1-africa"), - WIRELESS_DATA_QUOTA1_ASIA("wireless-data-quota1-asia"), - WIRELESS_DATA_QUOTA1_CENTRALANDSOUTHAMERICA( - "wireless-data-quota1-centralandsouthamerica" - ), - WIRELESS_DATA_QUOTA1_EUROPE("wireless-data-quota1-europe"), - WIRELESS_DATA_QUOTA1_NORTHAMERICA("wireless-data-quota1-northamerica"), - WIRELESS_DATA_QUOTA1_OCEANIA("wireless-data-quota1-oceania"), - WIRELESS_DATA_QUOTA10("wireless-data-quota10"), - WIRELESS_DATA_QUOTA10_AFRICA("wireless-data-quota10-africa"), - WIRELESS_DATA_QUOTA10_ASIA("wireless-data-quota10-asia"), - WIRELESS_DATA_QUOTA10_CENTRALANDSOUTHAMERICA( - "wireless-data-quota10-centralandsouthamerica" - ), - WIRELESS_DATA_QUOTA10_EUROPE("wireless-data-quota10-europe"), - WIRELESS_DATA_QUOTA10_NORTHAMERICA( - "wireless-data-quota10-northamerica" - ), - WIRELESS_DATA_QUOTA10_OCEANIA("wireless-data-quota10-oceania"), - WIRELESS_DATA_QUOTA50("wireless-data-quota50"), - WIRELESS_DATA_QUOTA50_AFRICA("wireless-data-quota50-africa"), - WIRELESS_DATA_QUOTA50_ASIA("wireless-data-quota50-asia"), - WIRELESS_DATA_QUOTA50_CENTRALANDSOUTHAMERICA( - "wireless-data-quota50-centralandsouthamerica" - ), - WIRELESS_DATA_QUOTA50_EUROPE("wireless-data-quota50-europe"), - WIRELESS_DATA_QUOTA50_NORTHAMERICA( - "wireless-data-quota50-northamerica" - ), - WIRELESS_DATA_QUOTA50_OCEANIA("wireless-data-quota50-oceania"), - WIRELESS_DATA_QUOTACUSTOM("wireless-data-quotacustom"), - WIRELESS_DATA_QUOTACUSTOM_AFRICA("wireless-data-quotacustom-africa"), - WIRELESS_DATA_QUOTACUSTOM_ASIA("wireless-data-quotacustom-asia"), - WIRELESS_DATA_QUOTACUSTOM_CENTRALANDSOUTHAMERICA( - "wireless-data-quotacustom-centralandsouthamerica" - ), - WIRELESS_DATA_QUOTACUSTOM_EUROPE("wireless-data-quotacustom-europe"), - WIRELESS_DATA_QUOTACUSTOM_NORTHAMERICA( - "wireless-data-quotacustom-northamerica" - ), - WIRELESS_DATA_QUOTACUSTOM_OCEANIA("wireless-data-quotacustom-oceania"), - WIRELESS_MRC_PAYG("wireless-mrc-payg"), - WIRELESS_MRC_QUOTA1("wireless-mrc-quota1"), - WIRELESS_MRC_QUOTA10("wireless-mrc-quota10"), - WIRELESS_MRC_QUOTA50("wireless-mrc-quota50"), - WIRELESS_MRC_QUOTACUSTOM("wireless-mrc-quotacustom"), - WIRELESS_ORDERS("wireless-orders"), - WIRELESS_ORDERS_ARTWORK("wireless-orders-artwork"), - WIRELESS_ORDERS_BULK("wireless-orders-bulk"), - WIRELESS_ORDERS_ESIM("wireless-orders-esim"), - WIRELESS_ORDERS_STARTER("wireless-orders-starter"), - WIRELESS_QUOTAS("wireless-quotas"), - WIRELESS_SMS_AFRICA("wireless-sms-africa"), - WIRELESS_SMS_ASIA("wireless-sms-asia"), - WIRELESS_SMS_CENTRALANDSOUTHAMERICA( - "wireless-sms-centralandsouthamerica" - ), - WIRELESS_SMS_EUROPE("wireless-sms-europe"), - WIRELESS_SMS_NORTHAMERICA("wireless-sms-northamerica"), - WIRELESS_SMS_OCEANIA("wireless-sms-oceania"), - WIRELESS_SUPER_SIM("wireless-super-sim"), - WIRELESS_SUPER_SIM_DATA("wireless-super-sim-data"), - WIRELESS_SUPER_SIM_DATA_NORTH_AMERICA_USA( - "wireless-super-sim-data-north-america-usa" - ), - WIRELESS_SUPER_SIM_DATA_PAYG("wireless-super-sim-data-payg"), - WIRELESS_SUPER_SIM_DATA_PAYG_EUROPE( - "wireless-super-sim-data-payg-europe" - ), - WIRELESS_SUPER_SIM_DATA_PAYG_NORTH_AMERICA( - "wireless-super-sim-data-payg-north-america" - ), - WIRELESS_SUPER_SIM_HARDWARE("wireless-super-sim-hardware"), - WIRELESS_SUPER_SIM_HARDWARE_BULK("wireless-super-sim-hardware-bulk"), - WIRELESS_SUPER_SIM_SMSCOMMANDS("wireless-super-sim-smscommands"), - WIRELESS_SUPER_SIM_SMSCOMMANDS_AFRICA( - "wireless-super-sim-smscommands-africa" - ), - WIRELESS_SUPER_SIM_SMSCOMMANDS_ASIA( - "wireless-super-sim-smscommands-asia" - ), - WIRELESS_SUPER_SIM_SMSCOMMANDS_CENT_AND_SOUTH_AMERICA( - "wireless-super-sim-smscommands-cent-and-south-america" - ), - WIRELESS_SUPER_SIM_SMSCOMMANDS_EUROPE( - "wireless-super-sim-smscommands-europe" - ), - WIRELESS_SUPER_SIM_SMSCOMMANDS_NORTH_AMERICA( - "wireless-super-sim-smscommands-north-america" - ), - WIRELESS_SUPER_SIM_SMSCOMMANDS_OCEANIA( - "wireless-super-sim-smscommands-oceania" - ), - WIRELESS_SUPER_SIM_SUBSCRIPTION("wireless-super-sim-subscription"), - WIRELESS_SUPER_SIM_SUBSCRIPTION_PAYG( - "wireless-super-sim-subscription-payg" - ), - WIRELESS_USAGE("wireless-usage"), - WIRELESS_USAGE_COMMANDS("wireless-usage-commands"), - WIRELESS_USAGE_COMMANDS_AFRICA("wireless-usage-commands-africa"), - WIRELESS_USAGE_COMMANDS_ASIA("wireless-usage-commands-asia"), - WIRELESS_USAGE_COMMANDS_CENTRALANDSOUTHAMERICA( - "wireless-usage-commands-centralandsouthamerica" - ), - WIRELESS_USAGE_COMMANDS_EUROPE("wireless-usage-commands-europe"), - WIRELESS_USAGE_COMMANDS_HOME("wireless-usage-commands-home"), - WIRELESS_USAGE_COMMANDS_NORTHAMERICA( - "wireless-usage-commands-northamerica" - ), - WIRELESS_USAGE_COMMANDS_OCEANIA("wireless-usage-commands-oceania"), - WIRELESS_USAGE_COMMANDS_ROAMING("wireless-usage-commands-roaming"), - WIRELESS_USAGE_DATA("wireless-usage-data"), - WIRELESS_USAGE_DATA_AFRICA("wireless-usage-data-africa"), - WIRELESS_USAGE_DATA_ASIA("wireless-usage-data-asia"), - WIRELESS_USAGE_DATA_CENTRALANDSOUTHAMERICA( - "wireless-usage-data-centralandsouthamerica" - ), - WIRELESS_USAGE_DATA_CUSTOM_ADDITIONALMB( - "wireless-usage-data-custom-additionalmb" - ), - WIRELESS_USAGE_DATA_CUSTOM_FIRST5MB( - "wireless-usage-data-custom-first5mb" - ), - WIRELESS_USAGE_DATA_DOMESTIC_ROAMING( - "wireless-usage-data-domestic-roaming" - ), - WIRELESS_USAGE_DATA_EUROPE("wireless-usage-data-europe"), - WIRELESS_USAGE_DATA_INDIVIDUAL_ADDITIONALGB( - "wireless-usage-data-individual-additionalgb" - ), - WIRELESS_USAGE_DATA_INDIVIDUAL_FIRSTGB( - "wireless-usage-data-individual-firstgb" - ), - WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_CANADA( - "wireless-usage-data-international-roaming-canada" - ), - WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_INDIA( - "wireless-usage-data-international-roaming-india" - ), - WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_MEXICO( - "wireless-usage-data-international-roaming-mexico" - ), - WIRELESS_USAGE_DATA_NORTHAMERICA("wireless-usage-data-northamerica"), - WIRELESS_USAGE_DATA_OCEANIA("wireless-usage-data-oceania"), - WIRELESS_USAGE_DATA_POOLED("wireless-usage-data-pooled"), - WIRELESS_USAGE_DATA_POOLED_DOWNLINK( - "wireless-usage-data-pooled-downlink" - ), - WIRELESS_USAGE_DATA_POOLED_UPLINK("wireless-usage-data-pooled-uplink"), - WIRELESS_USAGE_MRC("wireless-usage-mrc"), - WIRELESS_USAGE_MRC_CUSTOM("wireless-usage-mrc-custom"), - WIRELESS_USAGE_MRC_INDIVIDUAL("wireless-usage-mrc-individual"), - WIRELESS_USAGE_MRC_POOLED("wireless-usage-mrc-pooled"), - WIRELESS_USAGE_MRC_SUSPENDED("wireless-usage-mrc-suspended"), - WIRELESS_USAGE_SMS("wireless-usage-sms"), - WIRELESS_USAGE_VOICE("wireless-usage-voice"), - A2P_FAST_TRACK_ONBOARDING("a2p-fast-track-onboarding"), - ADVISORY_SERVICES("advisory-services"), - ADVISORY_SERVICES_BILLED("advisory-services-billed"), - ADVISORY_SERVICES_CALL_TRACKING("advisory-services-call-tracking"), - ADVISORY_SERVICES_DATA_SERVICES("advisory-services-data-services"), - ADVISORY_SERVICES_EXPENSES("advisory-services-expenses"), - ADVISORY_SERVICES_SIP_TRUNKING("advisory-services-sip-trunking"), - ASSETS_REQUESTS("assets-requests"), - AUDIENCE_MINUTES_VIDEO("audience-minutes-video"), - AUTHY_BUCKET_ADJUSTMENT("authy-bucket-adjustment"), - AUTHY_SOFTWARE("authy-software"), - CALLERIDLOOKUPS_API("calleridlookups-api"), - CALLERIDLOOKUPS_PROGRAMMABLEVOICE("calleridlookups-programmablevoice"), - CALLERIDLOOKUPS_TRUNKING("calleridlookups-trunking"), - CALLS_TRUNKING_INBOUND_TOLLFREE_LOCAL( - "calls-trunking-inbound-tollfree-local" - ), - CALLS_TRUNKING_INBOUND_TOLLFREE_MOBILE( - "calls-trunking-inbound-tollfree-mobile" - ), - CHANNELS_WHATSAPP_CONVERSATION_FREE_1( - "channels-whatsapp-conversation-free-1" - ), - CONFERENCE("conference"), - CONVERSATIONAL_INSIGHTS("conversational-insights"), - CONVERSATIONAL_INSIGHTS_MESSAGES("conversational-insights-messages"), - CONVERSATIONAL_INSIGHTS_VOICE_MINUTES( - "conversational-insights-voice-minutes" - ), - DEMO("demo"), - DEMO_UC_SCRIPT_TEST("demo-uc-script-test"), - ELASTIC_SIP_TRUNKING("elastic-sip-trunking"), - ELASTIC_SIP_TRUNKING_CALL_TRANSFERS( - "elastic-sip-trunking-call-transfers" - ), - ENTERPRISE_HIPPA("enterprise-hippa"), - FLEX_NAMED_USERS("flex-named-users"), - FLEX_SPINSCI("flex-spinsci"), - FLEX_USERS_1("flex-users-1"), - FLEX_WFO_PREMIUM_SPEECH_ANALYTICS("flex-wfo-premium-speech-analytics"), - FLEX_XCELERATE("flex-xcelerate"), - FUNCTIONS_ROLLUP("functions-rollup"), - IMP_V1_USAGE("imp-v1-usage"), - IP_MESSAGING_ADDONS("ip-messaging-addons"), - IVR("ivr"), - IVR_CONVERSATIONAL("ivr-conversational"), - IVR_DTMF("ivr-dtmf"), - IVR_VIRTUALAGENT("ivr-virtualagent"), - LIVE("live"), - LIVE_MEDIA_RECORDING_MINUTES("live-media-recording-minutes"), - LONGCODE_MPS("longcode-mps"), - MARKETPLACE_ANALYTICS_ADDONS("marketplace-analytics-addons"), - MARKETPLACE_ISV_ADDONS("marketplace-isv-addons"), - MARKETPLACE_MESSAGING_ADDONS("marketplace-messaging-addons"), - MARKETPLACE_PHONENUMBERS_ADDONS("marketplace-phonenumbers-addons"), - MARKETPLACE_RECORDING_ADDONS("marketplace-recording-addons"), - MARKETPLACE_VIRTUALAGENT_ADDONS("marketplace-virtualagent-addons"), - MARKETPLAY_PAY_ADDONS_SHUTTLE_PAY_CONNECTOR_1( - "marketplay-pay-addons-shuttle-pay-connector-1" - ), - MARKETPLAY_PAY_ADDONS_STRIPE_PAY_CONNECTOR( - "marketplay-pay-addons-stripe-pay-connector" - ), - MMS_INBOUND_LONGCODE_CANADA("mms-inbound-longcode-canada"), - MMS_INBOUND_LONGCODE_UNITEDSTATES("mms-inbound-longcode-unitedstates"), - MMS_OUTBOUND_LONGCODE_CANADA("mms-outbound-longcode-canada"), - MMS_OUTBOUND_LONGCODE_UNITEDSTATES( - "mms-outbound-longcode-unitedstates" - ), - MMS_OUTBOUND_TOLL_FREE("mms-outbound-toll-free"), - NOTIFY_CHATAPPSANDOTHERCHANNELS("notify-chatappsandotherchannels"), - NOTIFY_NOTIFYSERVICES("notify-notifyservices"), - NOTIFY_PUSHNOTIFICATIONS("notify-pushnotifications"), - PAYMENT_GATEWAY_CONNECTORS("payment-gateway-connectors"), - PAYMENT_SOLUTIONS("payment-solutions"), - PCHAT_BUCKET_ADJUSTMENT("pchat-bucket-adjustment"), - PHONENUMBERS_NUMBERS("phonenumbers-numbers"), - PROG_VOICE_CLIENT_ANDROID("prog-voice-client-android"), - PROG_VOICE_CLIENT_ANDROID_INBOUND("prog-voice-client-android-inbound"), - PROG_VOICE_CLIENT_ANDROID_OUTBOUND( - "prog-voice-client-android-outbound" - ), - PROG_VOICE_CLIENT_IOS("prog-voice-client-ios"), - PROG_VOICE_CLIENT_IOS_INBOUND("prog-voice-client-ios-inbound"), - PROG_VOICE_CLIENT_IOS_OUTBOUND("prog-voice-client-ios-outbound"), - PROG_VOICE_CLIENT_SDK("prog-voice-client-sdk"), - PROG_VOICE_CLIENT_WEB("prog-voice-client-web"), - PROG_VOICE_CLIENT_WEB_INBOUND("prog-voice-client-web-inbound"), - PROG_VOICE_CLIENT_WEB_OUTBOUND("prog-voice-client-web-outbound"), - PROGRAMMABLEVOICECONNECTIVITY_MEDIA_STREAMS( - "programmablevoiceconnectivity-media-streams" - ), - PSTNCONNECTIVITY_BYOC("pstnconnectivity-byoc"), - PSTNCONNECTIVITY_EMERGENCY("pstnconnectivity-emergency"), - PSTNCONNECTIVITY_MINUTES("pstnconnectivity-minutes"), - PSTNCONNECTIVITY_MINUTES_1("pstnconnectivity-minutes-1"), - PSTNCONNECTIVITY_MINUTESINBOUNDLOCAL( - "pstnconnectivity-minutesinboundlocal" - ), - PSTNCONNECTIVITY_MINUTESINBOUNDMOBILE( - "pstnconnectivity-minutesinboundmobile" - ), - PSTNCONNECTIVITY_MINUTESINBOUNDTOLLFREE( - "pstnconnectivity-minutesinboundtollfree" - ), - PSTNCONNECTIVITY_MINUTESINBOUNDTOLLFREELOCAL( - "pstnconnectivity-minutesinboundtollfreelocal" - ), - PSTNCONNECTIVITY_MINUTESINBOUNDTOLLFREEMOBILE( - "pstnconnectivity-minutesinboundtollfreemobile" - ), - PV_ROOM_HOURS("pv-room-hours"), - PV_ROOM_SIMULTANEOUS_PARTICIPANT_CONNECTIONS( - "pv-room-simultaneous-participant-connections" - ), - PVIDEO_ROOM_HOURS_AU1("pvideo-room-hours-au1"), - PVIDEO_ROOM_HOURS_BR1("pvideo-room-hours-br1"), - PVIDEO_ROOM_HOURS_IE1("pvideo-room-hours-ie1"), - PVIDEO_ROOM_HOURS_JP1("pvideo-room-hours-jp1"), - PVIDEO_ROOM_HOURS_SG1("pvideo-room-hours-sg1"), - PVIDEO_ROOM_HOURS_US1("pvideo-room-hours-us1"), - PVIDEO_ROOM_HOURS_US2("pvideo-room-hours-us2"), - RECORDINGS_ENCRYPTED("recordings-encrypted"), - SHORT_CODE_SETUP_FEES("short-code-setup-fees"), - SHORTCODES_MESSAGES_INBOUND("shortcodes-messages-inbound"), - SHORTCODES_MESSAGES_OUTBOUND("shortcodes-messages-outbound"), - SMS_MESSAGES_REGISTRATIONFEES("sms-messages-registrationfees"), - SMS_MMS_PENALTY_FEES("sms-mms-penalty-fees"), - SMS_MMS_PENALTY_FEES_1("sms-mms-penalty-fees-1"), - SMS_PUMPING_PROTECTION_NON_USCA("sms-pumping-protection-non-usca"), - SMS_PUMPING_PROTECTION_USCA("sms-pumping-protection-usca"), - STUDIO("studio"), - STUDIO_MONTHLY_FEES("studio-monthly-fees"), - SUPERSIM("supersim"), - TASK_ROUTER("task-router"), - TASK_ROUTER_WORKERS("task-router-workers"), - TEST_QUOTA_BUCKETS("test-quota-buckets"), - TEST_UC_SCRIPT_1("test-uc-script-1"), - TEST_UC_SCRIPT_DEMO_2("test-uc-script-demo-2"), - TEXT_TO_SPEECH("text-to-speech"), - TME("tme"), - TTS_BASIC("tts-basic"), - TWILIO_EDITIONS("twilio-editions"), - TWILIO_INTERCONNECT_CALIFORNIA("twilio-interconnect-california"), - TWILIO_INTERCONNECT_CALIFORNIA_MONTHLY( - "twilio-interconnect-california-monthly" - ), - TWILIO_INTERCONNECT_CALIFORNIA_SETUP( - "twilio-interconnect-california-setup" - ), - TWILIO_INTERCONNECT_FRANKFURT("twilio-interconnect-frankfurt"), - TWILIO_INTERCONNECT_FRANKFURT_MO("twilio-interconnect-frankfurt-mo"), - TWILIO_INTERCONNECT_FRANKFURT_SETUP( - "twilio-interconnect-frankfurt-setup" - ), - TWILIO_INTERCONNECT_LONDON("twilio-interconnect-london"), - TWILIO_INTERCONNECT_LONDON_MO("twilio-interconnect-london-mo"), - TWILIO_INTERCONNECT_LONDON_SETUP("twilio-interconnect-london-setup"), - TWILIO_INTERCONNECT_SAO_PAULO("twilio-interconnect-sao-paulo"), - TWILIO_INTERCONNECT_SAO_PAULO_MONTHLY( - "twilio-interconnect-sao-paulo-monthly" - ), - TWILIO_INTERCONNECT_SAO_PAULO_SETUP( - "twilio-interconnect-sao-paulo-setup" - ), - TWILIO_INTERCONNECT_SINGAPORE("twilio-interconnect-singapore"), - TWILIO_INTERCONNECT_SINGAPORE_MO("twilio-interconnect-singapore-mo"), - TWILIO_INTERCONNECT_SINGAPORE_SETUP( - "twilio-interconnect-singapore-setup" - ), - TWILIO_INTERCONNECT_SYDNEY("twilio-interconnect-sydney"), - TWILIO_INTERCONNECT_SYDNEY_MO("twilio-interconnect-sydney-mo"), - TWILIO_INTERCONNECT_SYDNEY_SETUP("twilio-interconnect-sydney-setup"), - TWILIO_INTERCONNECT_TOKYO("twilio-interconnect-tokyo"), - TWILIO_INTERCONNECT_TOKYO_MO("twilio-interconnect-tokyo-mo"), - TWILIO_INTERCONNECT_TOKYO_SETUP("twilio-interconnect-tokyo-setup"), - TWILIO_INTERCONNECT_VA("twilio-interconnect-va"), - TWILIO_INTERCONNECT_VA_MO("twilio-interconnect-va-mo"), - TWILIO_INTERCONNECT_VA_SETUP("twilio-interconnect-va-setup"), - TWIML_VERBS("twiml-verbs"), - TWIML_VERBS_SAY("twiml-verbs-say"), - USAGE_PROGRAMMABLE_MESSAGING_ENGAGEMENT_SUITE( - "usage-programmable-messaging-engagement-suite" - ), - USAGE_PROGRAMMABLE_MESSAGING_FEES_SERVICES( - "usage-programmable-messaging-fees-services" - ), - VERIFY_OUTBOUND_EMAIL("verify-outbound-email"), - VERIFY_PACKAGED_PLANS("verify-packaged-plans"), - VERIFY_SILENT_NETWORK_AUTH("verify-silent-network-auth"), - VERIFY_VOICE_AND_SMS("verify-voice-and-sms"), - VOICE_INSIGHTS_CLIENT_INSIGHTS_MONTHY_COMMIT( - "voice-insights-client-insights-monthy-commit" - ), - WIRELESS_DATA_PAYG_ASIA_AFG("wireless-data-payg-asia-afg"), - WIRELESS_MULTI_IMSI_SIM_COMMANDS("wireless-multi-imsi-sim-commands"), - WIRELESS_MULTI_IMSI_SIM_COMMANDS_USA( - "wireless-multi-imsi-sim-commands-usa" - ), - WIRELESS_MULTI_IMSI_SIM_DATA("wireless-multi-imsi-sim-data"), - WIRELESS_MULTI_IMSI_SIM_DATA_EU28("wireless-multi-imsi-sim-data-eu28"), - WIRELESS_MULTI_IMSI_SIM_DATA_USA("wireless-multi-imsi-sim-data-usa"), - WIRELESS_MULTI_IMSI_SIM_MONTHLY_FEES( - "wireless-multi-imsi-sim-monthly-fees" - ), - WIRELESS_MULTI_IMSI_SIM_USAGE("wireless-multi-imsi-sim-usage"), - WIRELESS_SUPER_SIM_DATA_NORTH_AMERICA( - "wireless-super-sim-data-north-america" - ), - WIRELESS_SUPER_SIM_USAGE("wireless-super-sim-usage"); - - private final String value; - - private Category(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static Category forValue(final String value) { - return Promoter.enumFromString(value, Category.values()); - } - } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/usage/record/DailyReader.java b/src/main/java/com/twilio/rest/api/v2010/account/usage/record/DailyReader.java index b3cf835c6e..a62bbfe107 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/usage/record/DailyReader.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/usage/record/DailyReader.java @@ -32,7 +32,7 @@ public class DailyReader extends Reader { private String pathAccountSid; - private Daily.Category category; + private String category; private LocalDate startDate; private LocalDate endDate; private Boolean includeSubaccounts; @@ -44,7 +44,7 @@ public DailyReader(final String pathAccountSid) { this.pathAccountSid = pathAccountSid; } - public DailyReader setCategory(final Daily.Category category) { + public DailyReader setCategory(final String category) { this.category = category; return this; } @@ -166,7 +166,7 @@ public Page getPage( private void addQueryParams(final Request request) { if (category != null) { - request.addQueryParam("Category", category.toString()); + request.addQueryParam("Category", category); } if (startDate != null) { request.addQueryParam( diff --git a/src/main/java/com/twilio/rest/api/v2010/account/usage/record/LastMonth.java b/src/main/java/com/twilio/rest/api/v2010/account/usage/record/LastMonth.java index 87a6635f8c..920a2a555f 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/usage/record/LastMonth.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/usage/record/LastMonth.java @@ -24,7 +24,6 @@ import com.twilio.base.Resource; import com.twilio.converter.CurrencyDeserializer; import com.twilio.converter.DateConverter; -import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import java.io.IOException; @@ -42,7 +41,7 @@ @ToString public class LastMonth extends Resource { - private static final long serialVersionUID = 240801278405798L; + private static final long serialVersionUID = 158026917970511L; public static LastMonthReader reader() { return new LastMonthReader(); @@ -98,7 +97,7 @@ public static LastMonth fromJson( private final String accountSid; private final String apiVersion; private final String asOf; - private final LastMonth.Category category; + private final String category; private final String count; private final String countUnit; private final String description; @@ -116,7 +115,7 @@ private LastMonth( @JsonProperty("account_sid") final String accountSid, @JsonProperty("api_version") final String apiVersion, @JsonProperty("as_of") final String asOf, - @JsonProperty("category") final LastMonth.Category category, + @JsonProperty("category") final String category, @JsonProperty("count") final String count, @JsonProperty("count_unit") final String countUnit, @JsonProperty("description") final String description, @@ -163,7 +162,7 @@ public final String getAsOf() { return this.asOf; } - public final LastMonth.Category getCategory() { + public final String getCategory() { return this.category; } @@ -262,945 +261,4 @@ public int hashCode() { usageUnit ); } - - public enum Category { - A2P_10DLC_REGISTRATIONFEES_BRANDREGISTRATION( - "a2p-10dlc-registrationfees-brandregistration" - ), - A2P_10DLC_REGISTRATIONFEES_BV("a2p-10dlc-registrationfees-bv"), - A2P_10DLC_REGISTRATIONFEES_CAMPAIGNCHARGES( - "a2p-10dlc-registrationfees-campaigncharges" - ), - A2P_10DLC_REGISTRATIONFEES_CAMPAIGNREGISTRATION( - "a2p-10dlc-registrationfees-campaignregistration" - ), - A2P_10DLC_REGISTRATIONFEES_CAMPAIGNVETTING( - "a2p-10dlc-registrationfees-campaignvetting" - ), - A2P_10DLC_REGISTRATIONFEES_MONTHLY( - "a2p-10dlc-registrationfees-monthly" - ), - A2P_10DLC_REGISTRATIONFEES_ONETIME( - "a2p-10dlc-registrationfees-onetime" - ), - A2P_REGISTRATION_FEES("a2p-registration-fees"), - ACCOUNT_SECURITY("account-security"), - AGENT_CONFERENCE("agent-conference"), - AGENT_COPILOT("agent-copilot"), - AGENT_COPILOT_MESSAGES("agent-copilot-messages"), - AGENT_COPILOT_PARTICIPANT_MINUTES("agent-copilot-participant-minutes"), - AI_ASSISTANTS("ai-assistants"), - AI_ASSISTANTS_VOICE("ai-assistants-voice"), - AMAZON_POLLY("amazon-polly"), - ANSWERING_MACHINE_DETECTION("answering-machine-detection"), - ASSETS("assets"), - AUDIENCE_MINUTES("audience-minutes"), - AUDIENCE_MINUTES_AUDIO("audience-minutes-audio"), - AUTHY_AUTHENTICATIONS("authy-authentications"), - AUTHY_CALLS_OUTBOUND("authy-calls-outbound"), - AUTHY_EMAIL_AUTHENTICATIONS("authy-email-authentications"), - AUTHY_MONTHLY_FEES("authy-monthly-fees"), - AUTHY_OUTBOUND_EMAIL("authy-outbound-email"), - AUTHY_PHONE_INTELLIGENCE("authy-phone-intelligence"), - AUTHY_PHONE_VERIFICATIONS("authy-phone-verifications"), - AUTHY_SMS_OUTBOUND("authy-sms-outbound"), - AUTHY_VERIFY_EMAIL_VERIFICATIONS("authy-verify-email-verifications"), - AUTHY_VERIFY_OUTBOUND_EMAIL("authy-verify-outbound-email"), - AUTOPILOT("autopilot"), - AUTOPILOT_HOME_ASSISTANTS("autopilot-home-assistants"), - AUTOPILOT_MESSAGING("autopilot-messaging"), - AUTOPILOT_OTHER("autopilot-other"), - AUTOPILOT_VOICE("autopilot-voice"), - BASIC_PEER_TO_PEER_ROOMS_PARTICIPANT_MINUTES( - "basic-peer-to-peer-rooms-participant-minutes" - ), - BRANDED_CALLING("branded-calling"), - BUNDLE_SMS_BUCKET("bundle-sms-bucket"), - BUNDLE_SUBSCRIPTION_FEES("bundle-subscription-fees"), - CALL_FORWARDING_LOOKUPS("call-forwarding-lookups"), - CALL_PROGESS_EVENTS("call-progess-events"), - CALLERIDLOOKUPS("calleridlookups"), - CALLS("calls"), - CALLS_CLIENT("calls-client"), - CALLS_EMERGENCY("calls-emergency"), - CALLS_GLOBALCONFERENCE("calls-globalconference"), - CALLS_INBOUND("calls-inbound"), - CALLS_INBOUND_LOCAL("calls-inbound-local"), - CALLS_INBOUND_MOBILE("calls-inbound-mobile"), - CALLS_INBOUND_TOLLFREE("calls-inbound-tollfree"), - CALLS_INBOUND_TOLLFREE_LOCAL("calls-inbound-tollfree-local"), - CALLS_INBOUND_TOLLFREE_MOBILE("calls-inbound-tollfree-mobile"), - CALLS_MEDIA_STREAM_MINUTES("calls-media-stream-minutes"), - CALLS_OUTBOUND("calls-outbound"), - CALLS_PAY_VERB_TRANSACTIONS("calls-pay-verb-transactions"), - CALLS_RECORDINGS("calls-recordings"), - CALLS_SIP("calls-sip"), - CALLS_SIP_INBOUND("calls-sip-inbound"), - CALLS_SIP_OUTBOUND("calls-sip-outbound"), - CALLS_TEXT_TO_SPEECH("calls-text-to-speech"), - CALLS_TRANSFERS("calls-transfers"), - CARRIER_LOOKUPS("carrier-lookups"), - CATEGORY("category"), - CHANNELS("channels"), - CHANNELS_MESSAGING("channels-messaging"), - CHANNELS_MESSAGING_INBOUND("channels-messaging-inbound"), - CHANNELS_MESSAGING_OUTBOUND("channels-messaging-outbound"), - CHANNELS_WHATSAPP("channels-whatsapp"), - CHANNELS_WHATSAPP_CONVERSATION_AUTHENTICATION( - "channels-whatsapp-conversation-authentication" - ), - CHANNELS_WHATSAPP_CONVERSATION_FREE( - "channels-whatsapp-conversation-free" - ), - CHANNELS_WHATSAPP_CONVERSATION_MARKETING( - "channels-whatsapp-conversation-marketing" - ), - CHANNELS_WHATSAPP_CONVERSATION_SERVICE( - "channels-whatsapp-conversation-service" - ), - CHANNELS_WHATSAPP_CONVERSATION_UTILITY( - "channels-whatsapp-conversation-utility" - ), - CHANNELS_WHATSAPP_INBOUND("channels-whatsapp-inbound"), - CHANNELS_WHATSAPP_OUTBOUND("channels-whatsapp-outbound"), - CHANNELS_WHATSAPP_SERVICE("channels-whatsapp-service"), - CHANNELS_WHATSAPP_TEMPLATE_AUTHENTICATION( - "channels-whatsapp-template-authentication" - ), - CHANNELS_WHATSAPP_TEMPLATE_MARKETING( - "channels-whatsapp-template-marketing" - ), - CHANNELS_WHATSAPP_TEMPLATE_SERVICE( - "channels-whatsapp-template-service" - ), - CHANNELS_WHATSAPP_TEMPLATE_UTILITY( - "channels-whatsapp-template-utility" - ), - CHAT_VIRTUAL_AGENT("chat-virtual-agent"), - CONVERSATION_RELAY("conversation-relay"), - CONVERSATIONS("conversations"), - CONVERSATIONS_API_REQUESTS("conversations-api-requests"), - CONVERSATIONS_CONVERSATION_EVENTS("conversations-conversation-events"), - CONVERSATIONS_ENDPOINT_CONNECTIVITY( - "conversations-endpoint-connectivity" - ), - CONVERSATIONS_EVENTS("conversations-events"), - CONVERSATIONS_PARTICIPANT_EVENTS("conversations-participant-events"), - CONVERSATIONS_PARTICIPANTS("conversations-participants"), - CPS("cps"), - CREDIT_TRANSFER("credit-transfer"), - EMAIL("email"), - EMERGING_TECH("emerging-tech"), - ENGAGEMENT_SUITE_PACKAGED_PLANS("engagement-suite-packaged-plans"), - ENHANCED_LINE_TYPE_LOOKUPS("enhanced-line-type-lookups"), - ENTERPRISE("enterprise"), - EVENTS("events"), - EXPERIMENT_FRANCE_SMS("experiment-france-sms"), - EXPERIMENT_INDIA_SMS("experiment-india-sms"), - EXPERIMENT_UK_SMS("experiment-uk-sms"), - FAILED_MESSAGE_PROCESSING_FEE("failed-message-processing-fee"), - FLEX("flex"), - FLEX_ACTIVE_USER_HOURS("flex-active-user-hours"), - FLEX_CONCURRENT_USERS("flex-concurrent-users"), - FLEX_CONVERSATIONAL_INSIGHTS("flex-conversational-insights"), - FLEX_CONVERSATIONAL_INSIGHTS_MESSAGES( - "flex-conversational-insights-messages" - ), - FLEX_CONVERSATIONAL_INSIGHTS_VOICE_MINUTES( - "flex-conversational-insights-voice-minutes" - ), - FLEX_EMAIL_USAGE("flex-email-usage"), - FLEX_MESSAGING_USAGE("flex-messaging-usage"), - FLEX_PARTNER_SPINSCI("flex-partner-spinsci"), - FLEX_PARTNER_XCELERATE("flex-partner-xcelerate"), - FLEX_RESELLER_ECOSYSTEM("flex-reseller-ecosystem"), - FLEX_UNIQUE_USER("flex-unique-user"), - FLEX_USAGE("flex-usage"), - FLEX_USERS("flex-users"), - FLEX_VOICE_MINUTE("flex-voice-minute"), - FLEX_YTICA("flex-ytica"), - FRAUD_LOOKUPS("fraud-lookups"), - FRONTLINE("frontline"), - FRONTLINE_USERS("frontline-users"), - FUNCTIONS("functions"), - GENERIC_PAY_TRANSACTIONS("generic-pay-transactions"), - GROUP_ROOMS("group-rooms"), - GROUP_ROOMS_DATA_TRACK("group-rooms-data-track"), - GROUP_ROOMS_ENCRYPTED_MEDIA_RECORDED( - "group-rooms-encrypted-media-recorded" - ), - GROUP_ROOMS_MEDIA_DOWNLOADED("group-rooms-media-downloaded"), - GROUP_ROOMS_MEDIA_RECORDED("group-rooms-media-recorded"), - GROUP_ROOMS_MEDIA_ROUTED("group-rooms-media-routed"), - GROUP_ROOMS_MEDIA_STORED("group-rooms-media-stored"), - GROUP_ROOMS_PARTICIPANT_MINUTES("group-rooms-participant-minutes"), - GROUP_ROOMS_RECORDED_MINUTES("group-rooms-recorded-minutes"), - IP_MESSAGING("ip-messaging"), - IP_MESSAGING_COMMANDS("ip-messaging-commands"), - IP_MESSAGING_DATA_STORAGE("ip-messaging-data-storage"), - IP_MESSAGING_DATA_TRANSFER("ip-messaging-data-transfer"), - IP_MESSAGING_ENDPOINT_CONNECTIVITY( - "ip-messaging-endpoint-connectivity" - ), - IVR_VIRTUAL_AGENT_CUSTOM_VOICES("ivr-virtual-agent-custom-voices"), - IVR_VIRTUAL_AGENT_GENAI("ivr-virtual-agent-genai"), - LINE_STATUS_LOOKUPS("line-status-lookups"), - LIVE_ACTIVITY_LOOKUPS("live-activity-lookups"), - LOOKUP_BUCKET_ADJUSTMENT("lookup-bucket-adjustment"), - LOOKUP_IDENTITY_MATCH("lookup-identity-match"), - LOOKUPS("lookups"), - MARKETPLACE("marketplace"), - MARKETPLACE_ALGORITHMIA_NAMED_ENTITY_RECOGNITION( - "marketplace-algorithmia-named-entity-recognition" - ), - MARKETPLACE_CADENCE_TRANSCRIPTION("marketplace-cadence-transcription"), - MARKETPLACE_CADENCE_TRANSLATION("marketplace-cadence-translation"), - MARKETPLACE_CAPIO_SPEECH_TO_TEXT("marketplace-capio-speech-to-text"), - MARKETPLACE_CONVRIZA_ABABA("marketplace-convriza-ababa"), - MARKETPLACE_DEEPGRAM_PHRASE_DETECTOR( - "marketplace-deepgram-phrase-detector" - ), - MARKETPLACE_DEEPGRAM_TRANSCRIPTION( - "marketplace-deepgram-transcription" - ), - MARKETPLACE_DEEPGRAM_TRANSCRIPTION_BASE( - "marketplace-deepgram-transcription-base" - ), - MARKETPLACE_DEEPGRAM_TRANSSCRIPTION_ENHANCED( - "marketplace-deepgram-transscription-enhanced" - ), - MARKETPLACE_DIGITAL_SEGMENT_BUSINESS_INFO( - "marketplace-digital-segment-business-info" - ), - MARKETPLACE_FACEBOOK_OFFLINE_CONVERSIONS( - "marketplace-facebook-offline-conversions" - ), - MARKETPLACE_GOOGLE_SPEECH_TO_TEXT("marketplace-google-speech-to-text"), - MARKETPLACE_IBM_WATSON_MESSAGE_INSIGHTS( - "marketplace-ibm-watson-message-insights" - ), - MARKETPLACE_IBM_WATSON_MESSAGE_SENTIMENT( - "marketplace-ibm-watson-message-sentiment" - ), - MARKETPLACE_IBM_WATSON_RECORDING_ANALYSIS( - "marketplace-ibm-watson-recording-analysis" - ), - MARKETPLACE_IBM_WATSON_TONE_ANALYZER( - "marketplace-ibm-watson-tone-analyzer" - ), - MARKETPLACE_ICEHOOK_SYSTEMS_SCOUT("marketplace-icehook-systems-scout"), - MARKETPLACE_INFOGROUP_DATAAXLE_BIZINFO( - "marketplace-infogroup-dataaxle-bizinfo" - ), - MARKETPLACE_KEEN_IO_CONTACT_CENTER_ANALYTICS( - "marketplace-keen-io-contact-center-analytics" - ), - MARKETPLACE_MARCHEX_CLEANCALL("marketplace-marchex-cleancall"), - MARKETPLACE_MARCHEX_RECORDING_ANALYSIS( - "marketplace-marchex-recording-analysis" - ), - MARKETPLACE_MARCHEX_SENTIMENT_ANALYSIS_FOR_SMS( - "marketplace-marchex-sentiment-analysis-for-sms" - ), - MARKETPLACE_MARKETPLACE_NEXTCALLER_SOCIAL_ID( - "marketplace-marketplace-nextcaller-social-id" - ), - MARKETPLACE_MOBILE_COMMONS_OPT_OUT_CLASSIFIER( - "marketplace-mobile-commons-opt-out-classifier" - ), - MARKETPLACE_NEXIWAVE_VOICEMAIL_TO_TEXT( - "marketplace-nexiwave-voicemail-to-text" - ), - MARKETPLACE_NEXTCALLER_ADVANCED_CALLER_IDENTIFICATION( - "marketplace-nextcaller-advanced-caller-identification" - ), - MARKETPLACE_NOMOROBO_SPAM_SCORE("marketplace-nomorobo-spam-score"), - MARKETPLACE_PAY_ADDONS("marketplace-pay-addons"), - MARKETPLACE_PAY_ADDONS_BASECOMMERCE_PAY_CONNECTOR( - "marketplace-pay-addons-basecommerce-pay-connector" - ), - MARKETPLACE_PAY_ADDONS_BRAINTREE_PAY_CONNECTOR( - "marketplace-pay-addons-braintree-pay-connector" - ), - MARKETPLACE_PAY_ADDONS_CARDCONNECT_PAY_CONNECTOR( - "marketplace-pay-addons-cardconnect-pay-connector" - ), - MARKETPLACE_PAY_ADDONS_CHASE_PAY_CONNECTOR( - "marketplace-pay-addons-chase-pay-connector" - ), - MARKETPLACE_PAY_ADDONS_SHUTTLE_PAY_CONNECTOR( - "marketplace-pay-addons-shuttle-pay-connector" - ), - MARKETPLACE_PAY_ADDONS_STRIPE_PAY_CONNECTOR( - "marketplace-pay-addons-stripe-pay-connector" - ), - MARKETPLACE_PAYFONE_TCPA_COMPLIANCE( - "marketplace-payfone-tcpa-compliance" - ), - MARKETPLACE_POLY_AI_CONNECTOR("marketplace-poly-ai-connector"), - MARKETPLACE_REALPHONEVALIDATION("marketplace-realphonevalidation"), - MARKETPLACE_REMEETING_AUTOMATIC_SPEECH_RECOGNITION( - "marketplace-remeeting-automatic-speech-recognition" - ), - MARKETPLACE_SPOKE_PHONE_LICENSE_PRO( - "marketplace-spoke-phone-license-pro" - ), - MARKETPLACE_SPOKE_PHONE_LICENSE_STANDARD( - "marketplace-spoke-phone-license-standard" - ), - MARKETPLACE_TCPA_DEFENSE_SOLUTIONS_BLACKLIST_FEED( - "marketplace-tcpa-defense-solutions-blacklist-feed" - ), - MARKETPLACE_TELO_OPENCNAM("marketplace-telo-opencnam"), - MARKETPLACE_TRESTLE_SOLUTIONS_CALLER_IDENTIFICATION( - "marketplace-trestle-solutions-caller-identification" - ), - MARKETPLACE_TRUECNAM_TRUE_SPAM("marketplace-truecnam-true-spam"), - MARKETPLACE_TWILIO_CALLER_NAME_LOOKUP_US( - "marketplace-twilio-caller-name-lookup-us" - ), - MARKETPLACE_TWILIO_CARRIER_INFORMATION_LOOKUP( - "marketplace-twilio-carrier-information-lookup" - ), - MARKETPLACE_VOICEBASE_PCI("marketplace-voicebase-pci"), - MARKETPLACE_VOICEBASE_TRANSCRIPTION( - "marketplace-voicebase-transcription" - ), - MARKETPLACE_VOICEBASE_TRANSCRIPTION_CUSTOM_VOCABULARY( - "marketplace-voicebase-transcription-custom-vocabulary" - ), - MARKETPLACE_WEB_PURIFY_PROFANITY_FILTER( - "marketplace-web-purify-profanity-filter" - ), - MARKETPLACE_WHITEPAGES_PRO_CALLER_IDENTIFICATION( - "marketplace-whitepages-pro-caller-identification" - ), - MARKETPLACE_WHITEPAGES_PRO_PHONE_INTELLIGENCE( - "marketplace-whitepages-pro-phone-intelligence" - ), - MARKETPLACE_WHITEPAGES_PRO_PHONE_REPUTATION( - "marketplace-whitepages-pro-phone-reputation" - ), - MARKETPLACE_WOLFARM_SPOKEN_RESULTS( - "marketplace-wolfarm-spoken-results" - ), - MARKETPLACE_WOLFRAM_SHORT_ANSWER("marketplace-wolfram-short-answer"), - MARKETPLACE_YTICA_CONTACT_CENTER_REPORTING_ANALYTICS( - "marketplace-ytica-contact-center-reporting-analytics" - ), - MARKETPLAY_PAY_ADDONS_SHUTTLE_PAY_CONNECTOR( - "marketplay-pay-addons-shuttle-pay-connector" - ), - MEDIA_COMPOSER_MINUTES("media-composer-minutes"), - MEDIASTORAGE("mediastorage"), - MIN_SPEND_ADJUSTMENTS("min-spend-adjustments"), - MMS("mms"), - MMS_INBOUND("mms-inbound"), - MMS_INBOUND_LONGCODE("mms-inbound-longcode"), - MMS_INBOUND_SHORTCODE("mms-inbound-shortcode"), - MMS_INBOUND_TOLL_FREE("mms-inbound-toll-free"), - MMS_MESSAGES_CARRIERFEES("mms-messages-carrierfees"), - MMS_OUTBOUND("mms-outbound"), - MMS_OUTBOUND_LONGCODE("mms-outbound-longcode"), - MMS_OUTBOUND_SHORTCODE("mms-outbound-shortcode"), - MMS_OUTBOUND_TOLLFREE("mms-outbound-tollfree"), - MONITOR("monitor"), - MONITOR_READS("monitor-reads"), - MONITOR_STORAGE("monitor-storage"), - MONITOR_WRITES("monitor-writes"), - NOTIFY("notify"), - NOTIFY_ACTIONS_ATTEMPTS("notify-actions-attempts"), - NOTIFY_CHANNELS("notify-channels"), - NUMBER_FORMAT_LOOKUPS("number-format-lookups"), - PCHAT("pchat"), - PCHAT_ACTIONS("pchat-actions"), - PCHAT_APS("pchat-aps"), - PCHAT_CONV_MED_STORAGE("pchat-conv-med-storage"), - PCHAT_MESSAGES("pchat-messages"), - PCHAT_NOTIFICATIONS("pchat-notifications"), - PCHAT_READS("pchat-reads"), - PCHAT_USERS("pchat-users"), - PEER_TO_PEER_ROOMS_PARTICIPANT_MINUTES( - "peer-to-peer-rooms-participant-minutes" - ), - PFAX("pfax"), - PFAX_MINUTES("pfax-minutes"), - PFAX_MINUTES_INBOUND("pfax-minutes-inbound"), - PFAX_MINUTES_OUTBOUND("pfax-minutes-outbound"), - PFAX_PAGES("pfax-pages"), - PHONE_QUALITY_SCORE_LOOKUPS("phone-quality-score-lookups"), - PHONENUMBERS("phonenumbers"), - PHONENUMBERS_CPS("phonenumbers-cps"), - PHONENUMBERS_EMERGENCY("phonenumbers-emergency"), - PHONENUMBERS_LOCAL("phonenumbers-local"), - PHONENUMBERS_MOBILE("phonenumbers-mobile"), - PHONENUMBERS_PORTING("phonenumbers-porting"), - PHONENUMBERS_SETUPS("phonenumbers-setups"), - PHONENUMBERS_TOLLFREE("phonenumbers-tollfree"), - PREMIUMSUPPORT("premiumsupport"), - PREMIUMSUPPORT_PERCENTAGE_SPEND("premiumsupport-percentage-spend"), - PROGRAMMABLEVOICE_PLATFORM("programmablevoice-platform"), - PROGRAMMABLEVOICECONN_CLIENTSDK("programmablevoiceconn-clientsdk"), - PROGRAMMABLEVOICECONN_CLIENTSDK_INBOUND( - "programmablevoiceconn-clientsdk-inbound" - ), - PROGRAMMABLEVOICECONN_CLIENTSDK_OUTBOUND( - "programmablevoiceconn-clientsdk-outbound" - ), - PROGRAMMABLEVOICECONN_ONNET("programmablevoiceconn-onnet"), - PROGRAMMABLEVOICECONN_ONNET_INBOUND( - "programmablevoiceconn-onnet-inbound" - ), - PROGRAMMABLEVOICECONN_ONNET_OUTBOUND( - "programmablevoiceconn-onnet-outbound" - ), - PROGRAMMABLEVOICECONN_SIP("programmablevoiceconn-sip"), - PROGRAMMABLEVOICECONN_SIP_INBOUND("programmablevoiceconn-sip-inbound"), - PROGRAMMABLEVOICECONN_SIP_OUTBOUND( - "programmablevoiceconn-sip-outbound" - ), - PROGRAMMABLEVOICECONNECTIVITY("programmablevoiceconnectivity"), - PROXY("proxy"), - PROXY_ACTIVE_SESSIONS("proxy-active-sessions"), - PROXY_BUCKET_ADJUSTMENT("proxy-bucket-adjustment"), - PROXY_LICENSES("proxy-licenses"), - PSTNCONNECTIVITY("pstnconnectivity"), - PSTNCONNECTIVITY_INBOUND("pstnconnectivity-inbound"), - PSTNCONNECTIVITY_OUTBOUND("pstnconnectivity-outbound"), - PV("pv"), - PV_BASIC_ROOMS("pv-basic-rooms"), - PV_COMPOSITION_MEDIA_DOWNLOADED("pv-composition-media-downloaded"), - PV_COMPOSITION_MEDIA_ENCRYPTED("pv-composition-media-encrypted"), - PV_COMPOSITION_MEDIA_STORED("pv-composition-media-stored"), - PV_COMPOSITION_MINUTES("pv-composition-minutes"), - PV_RECORDING_COMPOSITIONS("pv-recording-compositions"), - PV_ROOM_PARTICIPANTS("pv-room-participants"), - PV_ROOM_PARTICIPANTS_AU1("pv-room-participants-au1"), - PV_ROOM_PARTICIPANTS_BR1("pv-room-participants-br1"), - PV_ROOM_PARTICIPANTS_IE1("pv-room-participants-ie1"), - PV_ROOM_PARTICIPANTS_JP1("pv-room-participants-jp1"), - PV_ROOM_PARTICIPANTS_SG1("pv-room-participants-sg1"), - PV_ROOM_PARTICIPANTS_US1("pv-room-participants-us1"), - PV_ROOM_PARTICIPANTS_US2("pv-room-participants-us2"), - PV_ROOMS("pv-rooms"), - PV_SIP_ENDPOINT_REGISTRATIONS("pv-sip-endpoint-registrations"), - RCS_MESSAGES("rcs-messages"), - REASSIGNED_NUMBER("reassigned-number"), - RECORDINGS("recordings"), - RECORDINGSTORAGE("recordingstorage"), - SHORTCODES("shortcodes"), - SHORTCODES_CUSTOMEROWNED("shortcodes-customerowned"), - SHORTCODES_MMS_ENABLEMENT("shortcodes-mms-enablement"), - SHORTCODES_MPS("shortcodes-mps"), - SHORTCODES_RANDOM("shortcodes-random"), - SHORTCODES_SETUP_FEES("shortcodes-setup-fees"), - SHORTCODES_UK("shortcodes-uk"), - SHORTCODES_VANITY("shortcodes-vanity"), - SIM_SWAP_LOOKUPS("sim-swap-lookups"), - SIP_SECURE_MEDIA("sip-secure-media"), - SMALL_GROUP_ROOMS("small-group-rooms"), - SMALL_GROUP_ROOMS_DATA_TRACK("small-group-rooms-data-track"), - SMALL_GROUP_ROOMS_PARTICIPANT_MINUTES( - "small-group-rooms-participant-minutes" - ), - SMS("sms"), - SMS_INBOUND("sms-inbound"), - SMS_INBOUND_LONGCODE("sms-inbound-longcode"), - SMS_INBOUND_SHORTCODE("sms-inbound-shortcode"), - SMS_INBOUND_TOLLFREE("sms-inbound-tollfree"), - SMS_MESSAGES_CARRIERFEES("sms-messages-carrierfees"), - SMS_MESSAGES_FEATURES("sms-messages-features"), - SMS_MESSAGES_FEATURES_ENGAGEMENT_SUITE( - "sms-messages-features-engagement-suite" - ), - SMS_MESSAGES_FEATURES_MESSAGE_REDACTION( - "sms-messages-features-message-redaction" - ), - SMS_MESSAGES_FEATURES_SENDERID("sms-messages-features-senderid"), - SMS_MPS("sms-mps"), - SMS_MPS_SHORTCODE("sms-mps-shortcode"), - SMS_MPS_TOLLFREE("sms-mps-tollfree"), - SMS_MPS_TOLLFREE_SETUP("sms-mps-tollfree-setup"), - SMS_NATIONAL_REGULATORY_PROTECTION( - "sms-national-regulatory-protection" - ), - SMS_OUTBOUND("sms-outbound"), - SMS_OUTBOUND_CONTENT_INSPECTION("sms-outbound-content-inspection"), - SMS_OUTBOUND_LONGCODE("sms-outbound-longcode"), - SMS_OUTBOUND_SHORTCODE("sms-outbound-shortcode"), - SMS_OUTBOUND_TOLLFREE("sms-outbound-tollfree"), - SMS_PUMPING_PROTECTION("sms-pumping-protection"), - SMS_PUMPING_RISK("sms-pumping-risk"), - SMSMESSAGES_BUCKET_ADJUSTMENTS("smsmessages-bucket-adjustments"), - SMSMESSAGES_OUTBOUND_DOMESTIC("smsmessages-outbound-domestic"), - SPEECH_RECOGNITION("speech-recognition"), - STUDIO_ENGAGEMENTS("studio-engagements"), - SYNC("sync"), - SYNC_ACTIONS("sync-actions"), - SYNC_ENDPOINT_HOURS("sync-endpoint-hours"), - SYNC_ENDPOINT_HOURS_ABOVE_DAILY_CAP( - "sync-endpoint-hours-above-daily-cap" - ), - TASKROUTER_TASKS("taskrouter-tasks"), - TOTALPRICE("totalprice"), - TRANSCRIPTIONS("transcriptions"), - TRUNKING_CPS("trunking-cps"), - TRUNKING_EMERGENCY_CALLS("trunking-emergency-calls"), - TRUNKING_ORIGINATION("trunking-origination"), - TRUNKING_ORIGINATION_LOCAL("trunking-origination-local"), - TRUNKING_ORIGINATION_MOBILE("trunking-origination-mobile"), - TRUNKING_ORIGINATION_TOLLFREE("trunking-origination-tollfree"), - TRUNKING_RECORDINGS("trunking-recordings"), - TRUNKING_SECURE("trunking-secure"), - TRUNKING_TERMINATION("trunking-termination"), - TTS_GOOGLE("tts-google"), - TURNMEGABYTES("turnmegabytes"), - TURNMEGABYTES_AUSTRALIA("turnmegabytes-australia"), - TURNMEGABYTES_BRASIL("turnmegabytes-brasil"), - TURNMEGABYTES_GERMANY("turnmegabytes-germany"), - TURNMEGABYTES_INDIA("turnmegabytes-india"), - TURNMEGABYTES_IRELAND("turnmegabytes-ireland"), - TURNMEGABYTES_JAPAN("turnmegabytes-japan"), - TURNMEGABYTES_SINGAPORE("turnmegabytes-singapore"), - TURNMEGABYTES_USEAST("turnmegabytes-useast"), - TURNMEGABYTES_USWEST("turnmegabytes-uswest"), - TWILIO_FOR_SALESFORCE("twilio-for-salesforce"), - TWILIO_FOR_SALESFORCE_LICENSES("twilio-for-salesforce-licenses"), - TWILIO_INTERCONNECT("twilio-interconnect"), - TWIML("twiml"), - USAGE_FLEX_VIDEO("usage-flex-video"), - USAGE_FUNCTIONS("usage-functions"), - USAGE_RCS_BASIC_MESSAGES_OUTBOUND("usage-rcs-basic-messages-outbound"), - USAGE_RCS_MESSAGES("usage-rcs-messages"), - USAGE_RCS_MESSAGES_INBOUND("usage-rcs-messages-inbound"), - USAGE_RCS_MESSAGING_CARRIER_FEES("usage-rcs-messaging-carrier-fees"), - USAGE_RCS_SINGLE_MESSAGES_OUTBOUND( - "usage-rcs-single-messages-outbound" - ), - VERIFY_PACKAGE_PLANS("verify-package-plans"), - VERIFY_PUSH("verify-push"), - VERIFY_SNA("verify-sna"), - VERIFY_TOTP("verify-totp"), - VERIFY_VOICE_SMS("verify-voice-sms"), - VERIFY_WHATSAPP_CONVERSATIONS_BUSINESS_INITIATED( - "verify-whatsapp-conversations-business-initiated" - ), - VERIFY_WHATSAPP_TEMPLATE_BUSINESS_INITIATED( - "verify-whatsapp-template-business-initiated" - ), - VIDEO_RECORDINGS("video-recordings"), - VIDEO_ROOMS_TURN_MEGABYTES("video-rooms-turn-megabytes"), - VIRTUAL_AGENT("virtual-agent"), - VOICE_INSIGHTS("voice-insights"), - VOICE_INSIGHTS_CLIENT_INSIGHTS_ON_DEMAND_MINUTE( - "voice-insights-client-insights-on-demand-minute" - ), - VOICE_INSIGHTS_PTSN_INSIGHTS_ON_DEMAND_MINUTE( - "voice-insights-ptsn-insights-on-demand-minute" - ), - VOICE_INSIGHTS_SIP_INTERFACE_INSIGHTS_ON_DEMAND_MINUTE( - "voice-insights-sip-interface-insights-on-demand-minute" - ), - VOICE_INSIGHTS_SIP_TRUNKING_INSIGHTS_ON_DEMAND_MINUTE( - "voice-insights-sip-trunking-insights-on-demand-minute" - ), - VOICE_INTELLIGENCE("voice-intelligence"), - VOICE_INTELLIGENCE_EIP_OPERATORS("voice-intelligence-eip-operators"), - VOICE_INTELLIGENCE_OPERATORS("voice-intelligence-operators"), - VOICE_INTELLIGENCE_TRANSCRIPTION("voice-intelligence-transcription"), - WDS("wds"), - WIRELESS("wireless"), - WIRELESS_DATA("wireless-data"), - WIRELESS_DATA_PAYG("wireless-data-payg"), - WIRELESS_DATA_PAYG_AFRICA("wireless-data-payg-africa"), - WIRELESS_DATA_PAYG_ASIA("wireless-data-payg-asia"), - WIRELESS_DATA_PAYG_CENTRALANDSOUTHAMERICA( - "wireless-data-payg-centralandsouthamerica" - ), - WIRELESS_DATA_PAYG_EUROPE("wireless-data-payg-europe"), - WIRELESS_DATA_PAYG_NORTHAMERICA("wireless-data-payg-northamerica"), - WIRELESS_DATA_PAYG_OCEANIA("wireless-data-payg-oceania"), - WIRELESS_DATA_QUOTA1("wireless-data-quota1"), - WIRELESS_DATA_QUOTA1_AFRICA("wireless-data-quota1-africa"), - WIRELESS_DATA_QUOTA1_ASIA("wireless-data-quota1-asia"), - WIRELESS_DATA_QUOTA1_CENTRALANDSOUTHAMERICA( - "wireless-data-quota1-centralandsouthamerica" - ), - WIRELESS_DATA_QUOTA1_EUROPE("wireless-data-quota1-europe"), - WIRELESS_DATA_QUOTA1_NORTHAMERICA("wireless-data-quota1-northamerica"), - WIRELESS_DATA_QUOTA1_OCEANIA("wireless-data-quota1-oceania"), - WIRELESS_DATA_QUOTA10("wireless-data-quota10"), - WIRELESS_DATA_QUOTA10_AFRICA("wireless-data-quota10-africa"), - WIRELESS_DATA_QUOTA10_ASIA("wireless-data-quota10-asia"), - WIRELESS_DATA_QUOTA10_CENTRALANDSOUTHAMERICA( - "wireless-data-quota10-centralandsouthamerica" - ), - WIRELESS_DATA_QUOTA10_EUROPE("wireless-data-quota10-europe"), - WIRELESS_DATA_QUOTA10_NORTHAMERICA( - "wireless-data-quota10-northamerica" - ), - WIRELESS_DATA_QUOTA10_OCEANIA("wireless-data-quota10-oceania"), - WIRELESS_DATA_QUOTA50("wireless-data-quota50"), - WIRELESS_DATA_QUOTA50_AFRICA("wireless-data-quota50-africa"), - WIRELESS_DATA_QUOTA50_ASIA("wireless-data-quota50-asia"), - WIRELESS_DATA_QUOTA50_CENTRALANDSOUTHAMERICA( - "wireless-data-quota50-centralandsouthamerica" - ), - WIRELESS_DATA_QUOTA50_EUROPE("wireless-data-quota50-europe"), - WIRELESS_DATA_QUOTA50_NORTHAMERICA( - "wireless-data-quota50-northamerica" - ), - WIRELESS_DATA_QUOTA50_OCEANIA("wireless-data-quota50-oceania"), - WIRELESS_DATA_QUOTACUSTOM("wireless-data-quotacustom"), - WIRELESS_DATA_QUOTACUSTOM_AFRICA("wireless-data-quotacustom-africa"), - WIRELESS_DATA_QUOTACUSTOM_ASIA("wireless-data-quotacustom-asia"), - WIRELESS_DATA_QUOTACUSTOM_CENTRALANDSOUTHAMERICA( - "wireless-data-quotacustom-centralandsouthamerica" - ), - WIRELESS_DATA_QUOTACUSTOM_EUROPE("wireless-data-quotacustom-europe"), - WIRELESS_DATA_QUOTACUSTOM_NORTHAMERICA( - "wireless-data-quotacustom-northamerica" - ), - WIRELESS_DATA_QUOTACUSTOM_OCEANIA("wireless-data-quotacustom-oceania"), - WIRELESS_MRC_PAYG("wireless-mrc-payg"), - WIRELESS_MRC_QUOTA1("wireless-mrc-quota1"), - WIRELESS_MRC_QUOTA10("wireless-mrc-quota10"), - WIRELESS_MRC_QUOTA50("wireless-mrc-quota50"), - WIRELESS_MRC_QUOTACUSTOM("wireless-mrc-quotacustom"), - WIRELESS_ORDERS("wireless-orders"), - WIRELESS_ORDERS_ARTWORK("wireless-orders-artwork"), - WIRELESS_ORDERS_BULK("wireless-orders-bulk"), - WIRELESS_ORDERS_ESIM("wireless-orders-esim"), - WIRELESS_ORDERS_STARTER("wireless-orders-starter"), - WIRELESS_QUOTAS("wireless-quotas"), - WIRELESS_SMS_AFRICA("wireless-sms-africa"), - WIRELESS_SMS_ASIA("wireless-sms-asia"), - WIRELESS_SMS_CENTRALANDSOUTHAMERICA( - "wireless-sms-centralandsouthamerica" - ), - WIRELESS_SMS_EUROPE("wireless-sms-europe"), - WIRELESS_SMS_NORTHAMERICA("wireless-sms-northamerica"), - WIRELESS_SMS_OCEANIA("wireless-sms-oceania"), - WIRELESS_SUPER_SIM("wireless-super-sim"), - WIRELESS_SUPER_SIM_DATA("wireless-super-sim-data"), - WIRELESS_SUPER_SIM_DATA_NORTH_AMERICA_USA( - "wireless-super-sim-data-north-america-usa" - ), - WIRELESS_SUPER_SIM_DATA_PAYG("wireless-super-sim-data-payg"), - WIRELESS_SUPER_SIM_DATA_PAYG_EUROPE( - "wireless-super-sim-data-payg-europe" - ), - WIRELESS_SUPER_SIM_DATA_PAYG_NORTH_AMERICA( - "wireless-super-sim-data-payg-north-america" - ), - WIRELESS_SUPER_SIM_HARDWARE("wireless-super-sim-hardware"), - WIRELESS_SUPER_SIM_HARDWARE_BULK("wireless-super-sim-hardware-bulk"), - WIRELESS_SUPER_SIM_SMSCOMMANDS("wireless-super-sim-smscommands"), - WIRELESS_SUPER_SIM_SMSCOMMANDS_AFRICA( - "wireless-super-sim-smscommands-africa" - ), - WIRELESS_SUPER_SIM_SMSCOMMANDS_ASIA( - "wireless-super-sim-smscommands-asia" - ), - WIRELESS_SUPER_SIM_SMSCOMMANDS_CENT_AND_SOUTH_AMERICA( - "wireless-super-sim-smscommands-cent-and-south-america" - ), - WIRELESS_SUPER_SIM_SMSCOMMANDS_EUROPE( - "wireless-super-sim-smscommands-europe" - ), - WIRELESS_SUPER_SIM_SMSCOMMANDS_NORTH_AMERICA( - "wireless-super-sim-smscommands-north-america" - ), - WIRELESS_SUPER_SIM_SMSCOMMANDS_OCEANIA( - "wireless-super-sim-smscommands-oceania" - ), - WIRELESS_SUPER_SIM_SUBSCRIPTION("wireless-super-sim-subscription"), - WIRELESS_SUPER_SIM_SUBSCRIPTION_PAYG( - "wireless-super-sim-subscription-payg" - ), - WIRELESS_USAGE("wireless-usage"), - WIRELESS_USAGE_COMMANDS("wireless-usage-commands"), - WIRELESS_USAGE_COMMANDS_AFRICA("wireless-usage-commands-africa"), - WIRELESS_USAGE_COMMANDS_ASIA("wireless-usage-commands-asia"), - WIRELESS_USAGE_COMMANDS_CENTRALANDSOUTHAMERICA( - "wireless-usage-commands-centralandsouthamerica" - ), - WIRELESS_USAGE_COMMANDS_EUROPE("wireless-usage-commands-europe"), - WIRELESS_USAGE_COMMANDS_HOME("wireless-usage-commands-home"), - WIRELESS_USAGE_COMMANDS_NORTHAMERICA( - "wireless-usage-commands-northamerica" - ), - WIRELESS_USAGE_COMMANDS_OCEANIA("wireless-usage-commands-oceania"), - WIRELESS_USAGE_COMMANDS_ROAMING("wireless-usage-commands-roaming"), - WIRELESS_USAGE_DATA("wireless-usage-data"), - WIRELESS_USAGE_DATA_AFRICA("wireless-usage-data-africa"), - WIRELESS_USAGE_DATA_ASIA("wireless-usage-data-asia"), - WIRELESS_USAGE_DATA_CENTRALANDSOUTHAMERICA( - "wireless-usage-data-centralandsouthamerica" - ), - WIRELESS_USAGE_DATA_CUSTOM_ADDITIONALMB( - "wireless-usage-data-custom-additionalmb" - ), - WIRELESS_USAGE_DATA_CUSTOM_FIRST5MB( - "wireless-usage-data-custom-first5mb" - ), - WIRELESS_USAGE_DATA_DOMESTIC_ROAMING( - "wireless-usage-data-domestic-roaming" - ), - WIRELESS_USAGE_DATA_EUROPE("wireless-usage-data-europe"), - WIRELESS_USAGE_DATA_INDIVIDUAL_ADDITIONALGB( - "wireless-usage-data-individual-additionalgb" - ), - WIRELESS_USAGE_DATA_INDIVIDUAL_FIRSTGB( - "wireless-usage-data-individual-firstgb" - ), - WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_CANADA( - "wireless-usage-data-international-roaming-canada" - ), - WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_INDIA( - "wireless-usage-data-international-roaming-india" - ), - WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_MEXICO( - "wireless-usage-data-international-roaming-mexico" - ), - WIRELESS_USAGE_DATA_NORTHAMERICA("wireless-usage-data-northamerica"), - WIRELESS_USAGE_DATA_OCEANIA("wireless-usage-data-oceania"), - WIRELESS_USAGE_DATA_POOLED("wireless-usage-data-pooled"), - WIRELESS_USAGE_DATA_POOLED_DOWNLINK( - "wireless-usage-data-pooled-downlink" - ), - WIRELESS_USAGE_DATA_POOLED_UPLINK("wireless-usage-data-pooled-uplink"), - WIRELESS_USAGE_MRC("wireless-usage-mrc"), - WIRELESS_USAGE_MRC_CUSTOM("wireless-usage-mrc-custom"), - WIRELESS_USAGE_MRC_INDIVIDUAL("wireless-usage-mrc-individual"), - WIRELESS_USAGE_MRC_POOLED("wireless-usage-mrc-pooled"), - WIRELESS_USAGE_MRC_SUSPENDED("wireless-usage-mrc-suspended"), - WIRELESS_USAGE_SMS("wireless-usage-sms"), - WIRELESS_USAGE_VOICE("wireless-usage-voice"), - A2P_FAST_TRACK_ONBOARDING("a2p-fast-track-onboarding"), - ADVISORY_SERVICES("advisory-services"), - ADVISORY_SERVICES_BILLED("advisory-services-billed"), - ADVISORY_SERVICES_CALL_TRACKING("advisory-services-call-tracking"), - ADVISORY_SERVICES_DATA_SERVICES("advisory-services-data-services"), - ADVISORY_SERVICES_EXPENSES("advisory-services-expenses"), - ADVISORY_SERVICES_SIP_TRUNKING("advisory-services-sip-trunking"), - ASSETS_REQUESTS("assets-requests"), - AUDIENCE_MINUTES_VIDEO("audience-minutes-video"), - AUTHY_BUCKET_ADJUSTMENT("authy-bucket-adjustment"), - AUTHY_SOFTWARE("authy-software"), - CALLERIDLOOKUPS_API("calleridlookups-api"), - CALLERIDLOOKUPS_PROGRAMMABLEVOICE("calleridlookups-programmablevoice"), - CALLERIDLOOKUPS_TRUNKING("calleridlookups-trunking"), - CALLS_TRUNKING_INBOUND_TOLLFREE_LOCAL( - "calls-trunking-inbound-tollfree-local" - ), - CALLS_TRUNKING_INBOUND_TOLLFREE_MOBILE( - "calls-trunking-inbound-tollfree-mobile" - ), - CHANNELS_WHATSAPP_CONVERSATION_FREE_1( - "channels-whatsapp-conversation-free-1" - ), - CONFERENCE("conference"), - CONVERSATIONAL_INSIGHTS("conversational-insights"), - CONVERSATIONAL_INSIGHTS_MESSAGES("conversational-insights-messages"), - CONVERSATIONAL_INSIGHTS_VOICE_MINUTES( - "conversational-insights-voice-minutes" - ), - DEMO("demo"), - DEMO_UC_SCRIPT_TEST("demo-uc-script-test"), - ELASTIC_SIP_TRUNKING("elastic-sip-trunking"), - ELASTIC_SIP_TRUNKING_CALL_TRANSFERS( - "elastic-sip-trunking-call-transfers" - ), - ENTERPRISE_HIPPA("enterprise-hippa"), - FLEX_NAMED_USERS("flex-named-users"), - FLEX_SPINSCI("flex-spinsci"), - FLEX_USERS_1("flex-users-1"), - FLEX_WFO_PREMIUM_SPEECH_ANALYTICS("flex-wfo-premium-speech-analytics"), - FLEX_XCELERATE("flex-xcelerate"), - FUNCTIONS_ROLLUP("functions-rollup"), - IMP_V1_USAGE("imp-v1-usage"), - IP_MESSAGING_ADDONS("ip-messaging-addons"), - IVR("ivr"), - IVR_CONVERSATIONAL("ivr-conversational"), - IVR_DTMF("ivr-dtmf"), - IVR_VIRTUALAGENT("ivr-virtualagent"), - LIVE("live"), - LIVE_MEDIA_RECORDING_MINUTES("live-media-recording-minutes"), - LONGCODE_MPS("longcode-mps"), - MARKETPLACE_ANALYTICS_ADDONS("marketplace-analytics-addons"), - MARKETPLACE_ISV_ADDONS("marketplace-isv-addons"), - MARKETPLACE_MESSAGING_ADDONS("marketplace-messaging-addons"), - MARKETPLACE_PHONENUMBERS_ADDONS("marketplace-phonenumbers-addons"), - MARKETPLACE_RECORDING_ADDONS("marketplace-recording-addons"), - MARKETPLACE_VIRTUALAGENT_ADDONS("marketplace-virtualagent-addons"), - MARKETPLAY_PAY_ADDONS_SHUTTLE_PAY_CONNECTOR_1( - "marketplay-pay-addons-shuttle-pay-connector-1" - ), - MARKETPLAY_PAY_ADDONS_STRIPE_PAY_CONNECTOR( - "marketplay-pay-addons-stripe-pay-connector" - ), - MMS_INBOUND_LONGCODE_CANADA("mms-inbound-longcode-canada"), - MMS_INBOUND_LONGCODE_UNITEDSTATES("mms-inbound-longcode-unitedstates"), - MMS_OUTBOUND_LONGCODE_CANADA("mms-outbound-longcode-canada"), - MMS_OUTBOUND_LONGCODE_UNITEDSTATES( - "mms-outbound-longcode-unitedstates" - ), - MMS_OUTBOUND_TOLL_FREE("mms-outbound-toll-free"), - NOTIFY_CHATAPPSANDOTHERCHANNELS("notify-chatappsandotherchannels"), - NOTIFY_NOTIFYSERVICES("notify-notifyservices"), - NOTIFY_PUSHNOTIFICATIONS("notify-pushnotifications"), - PAYMENT_GATEWAY_CONNECTORS("payment-gateway-connectors"), - PAYMENT_SOLUTIONS("payment-solutions"), - PCHAT_BUCKET_ADJUSTMENT("pchat-bucket-adjustment"), - PHONENUMBERS_NUMBERS("phonenumbers-numbers"), - PROG_VOICE_CLIENT_ANDROID("prog-voice-client-android"), - PROG_VOICE_CLIENT_ANDROID_INBOUND("prog-voice-client-android-inbound"), - PROG_VOICE_CLIENT_ANDROID_OUTBOUND( - "prog-voice-client-android-outbound" - ), - PROG_VOICE_CLIENT_IOS("prog-voice-client-ios"), - PROG_VOICE_CLIENT_IOS_INBOUND("prog-voice-client-ios-inbound"), - PROG_VOICE_CLIENT_IOS_OUTBOUND("prog-voice-client-ios-outbound"), - PROG_VOICE_CLIENT_SDK("prog-voice-client-sdk"), - PROG_VOICE_CLIENT_WEB("prog-voice-client-web"), - PROG_VOICE_CLIENT_WEB_INBOUND("prog-voice-client-web-inbound"), - PROG_VOICE_CLIENT_WEB_OUTBOUND("prog-voice-client-web-outbound"), - PROGRAMMABLEVOICECONNECTIVITY_MEDIA_STREAMS( - "programmablevoiceconnectivity-media-streams" - ), - PSTNCONNECTIVITY_BYOC("pstnconnectivity-byoc"), - PSTNCONNECTIVITY_EMERGENCY("pstnconnectivity-emergency"), - PSTNCONNECTIVITY_MINUTES("pstnconnectivity-minutes"), - PSTNCONNECTIVITY_MINUTES_1("pstnconnectivity-minutes-1"), - PSTNCONNECTIVITY_MINUTESINBOUNDLOCAL( - "pstnconnectivity-minutesinboundlocal" - ), - PSTNCONNECTIVITY_MINUTESINBOUNDMOBILE( - "pstnconnectivity-minutesinboundmobile" - ), - PSTNCONNECTIVITY_MINUTESINBOUNDTOLLFREE( - "pstnconnectivity-minutesinboundtollfree" - ), - PSTNCONNECTIVITY_MINUTESINBOUNDTOLLFREELOCAL( - "pstnconnectivity-minutesinboundtollfreelocal" - ), - PSTNCONNECTIVITY_MINUTESINBOUNDTOLLFREEMOBILE( - "pstnconnectivity-minutesinboundtollfreemobile" - ), - PV_ROOM_HOURS("pv-room-hours"), - PV_ROOM_SIMULTANEOUS_PARTICIPANT_CONNECTIONS( - "pv-room-simultaneous-participant-connections" - ), - PVIDEO_ROOM_HOURS_AU1("pvideo-room-hours-au1"), - PVIDEO_ROOM_HOURS_BR1("pvideo-room-hours-br1"), - PVIDEO_ROOM_HOURS_IE1("pvideo-room-hours-ie1"), - PVIDEO_ROOM_HOURS_JP1("pvideo-room-hours-jp1"), - PVIDEO_ROOM_HOURS_SG1("pvideo-room-hours-sg1"), - PVIDEO_ROOM_HOURS_US1("pvideo-room-hours-us1"), - PVIDEO_ROOM_HOURS_US2("pvideo-room-hours-us2"), - RECORDINGS_ENCRYPTED("recordings-encrypted"), - SHORT_CODE_SETUP_FEES("short-code-setup-fees"), - SHORTCODES_MESSAGES_INBOUND("shortcodes-messages-inbound"), - SHORTCODES_MESSAGES_OUTBOUND("shortcodes-messages-outbound"), - SMS_MESSAGES_REGISTRATIONFEES("sms-messages-registrationfees"), - SMS_MMS_PENALTY_FEES("sms-mms-penalty-fees"), - SMS_MMS_PENALTY_FEES_1("sms-mms-penalty-fees-1"), - SMS_PUMPING_PROTECTION_NON_USCA("sms-pumping-protection-non-usca"), - SMS_PUMPING_PROTECTION_USCA("sms-pumping-protection-usca"), - STUDIO("studio"), - STUDIO_MONTHLY_FEES("studio-monthly-fees"), - SUPERSIM("supersim"), - TASK_ROUTER("task-router"), - TASK_ROUTER_WORKERS("task-router-workers"), - TEST_QUOTA_BUCKETS("test-quota-buckets"), - TEST_UC_SCRIPT_1("test-uc-script-1"), - TEST_UC_SCRIPT_DEMO_2("test-uc-script-demo-2"), - TEXT_TO_SPEECH("text-to-speech"), - TME("tme"), - TTS_BASIC("tts-basic"), - TWILIO_EDITIONS("twilio-editions"), - TWILIO_INTERCONNECT_CALIFORNIA("twilio-interconnect-california"), - TWILIO_INTERCONNECT_CALIFORNIA_MONTHLY( - "twilio-interconnect-california-monthly" - ), - TWILIO_INTERCONNECT_CALIFORNIA_SETUP( - "twilio-interconnect-california-setup" - ), - TWILIO_INTERCONNECT_FRANKFURT("twilio-interconnect-frankfurt"), - TWILIO_INTERCONNECT_FRANKFURT_MO("twilio-interconnect-frankfurt-mo"), - TWILIO_INTERCONNECT_FRANKFURT_SETUP( - "twilio-interconnect-frankfurt-setup" - ), - TWILIO_INTERCONNECT_LONDON("twilio-interconnect-london"), - TWILIO_INTERCONNECT_LONDON_MO("twilio-interconnect-london-mo"), - TWILIO_INTERCONNECT_LONDON_SETUP("twilio-interconnect-london-setup"), - TWILIO_INTERCONNECT_SAO_PAULO("twilio-interconnect-sao-paulo"), - TWILIO_INTERCONNECT_SAO_PAULO_MONTHLY( - "twilio-interconnect-sao-paulo-monthly" - ), - TWILIO_INTERCONNECT_SAO_PAULO_SETUP( - "twilio-interconnect-sao-paulo-setup" - ), - TWILIO_INTERCONNECT_SINGAPORE("twilio-interconnect-singapore"), - TWILIO_INTERCONNECT_SINGAPORE_MO("twilio-interconnect-singapore-mo"), - TWILIO_INTERCONNECT_SINGAPORE_SETUP( - "twilio-interconnect-singapore-setup" - ), - TWILIO_INTERCONNECT_SYDNEY("twilio-interconnect-sydney"), - TWILIO_INTERCONNECT_SYDNEY_MO("twilio-interconnect-sydney-mo"), - TWILIO_INTERCONNECT_SYDNEY_SETUP("twilio-interconnect-sydney-setup"), - TWILIO_INTERCONNECT_TOKYO("twilio-interconnect-tokyo"), - TWILIO_INTERCONNECT_TOKYO_MO("twilio-interconnect-tokyo-mo"), - TWILIO_INTERCONNECT_TOKYO_SETUP("twilio-interconnect-tokyo-setup"), - TWILIO_INTERCONNECT_VA("twilio-interconnect-va"), - TWILIO_INTERCONNECT_VA_MO("twilio-interconnect-va-mo"), - TWILIO_INTERCONNECT_VA_SETUP("twilio-interconnect-va-setup"), - TWIML_VERBS("twiml-verbs"), - TWIML_VERBS_SAY("twiml-verbs-say"), - USAGE_PROGRAMMABLE_MESSAGING_ENGAGEMENT_SUITE( - "usage-programmable-messaging-engagement-suite" - ), - USAGE_PROGRAMMABLE_MESSAGING_FEES_SERVICES( - "usage-programmable-messaging-fees-services" - ), - VERIFY_OUTBOUND_EMAIL("verify-outbound-email"), - VERIFY_PACKAGED_PLANS("verify-packaged-plans"), - VERIFY_SILENT_NETWORK_AUTH("verify-silent-network-auth"), - VERIFY_VOICE_AND_SMS("verify-voice-and-sms"), - VOICE_INSIGHTS_CLIENT_INSIGHTS_MONTHY_COMMIT( - "voice-insights-client-insights-monthy-commit" - ), - WIRELESS_DATA_PAYG_ASIA_AFG("wireless-data-payg-asia-afg"), - WIRELESS_MULTI_IMSI_SIM_COMMANDS("wireless-multi-imsi-sim-commands"), - WIRELESS_MULTI_IMSI_SIM_COMMANDS_USA( - "wireless-multi-imsi-sim-commands-usa" - ), - WIRELESS_MULTI_IMSI_SIM_DATA("wireless-multi-imsi-sim-data"), - WIRELESS_MULTI_IMSI_SIM_DATA_EU28("wireless-multi-imsi-sim-data-eu28"), - WIRELESS_MULTI_IMSI_SIM_DATA_USA("wireless-multi-imsi-sim-data-usa"), - WIRELESS_MULTI_IMSI_SIM_MONTHLY_FEES( - "wireless-multi-imsi-sim-monthly-fees" - ), - WIRELESS_MULTI_IMSI_SIM_USAGE("wireless-multi-imsi-sim-usage"), - WIRELESS_SUPER_SIM_DATA_NORTH_AMERICA( - "wireless-super-sim-data-north-america" - ), - WIRELESS_SUPER_SIM_USAGE("wireless-super-sim-usage"); - - private final String value; - - private Category(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static Category forValue(final String value) { - return Promoter.enumFromString(value, Category.values()); - } - } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/usage/record/LastMonthReader.java b/src/main/java/com/twilio/rest/api/v2010/account/usage/record/LastMonthReader.java index cfda6eefd5..b7e7e08fae 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/usage/record/LastMonthReader.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/usage/record/LastMonthReader.java @@ -32,7 +32,7 @@ public class LastMonthReader extends Reader { private String pathAccountSid; - private LastMonth.Category category; + private String category; private LocalDate startDate; private LocalDate endDate; private Boolean includeSubaccounts; @@ -44,7 +44,7 @@ public LastMonthReader(final String pathAccountSid) { this.pathAccountSid = pathAccountSid; } - public LastMonthReader setCategory(final LastMonth.Category category) { + public LastMonthReader setCategory(final String category) { this.category = category; return this; } @@ -168,7 +168,7 @@ public Page getPage( private void addQueryParams(final Request request) { if (category != null) { - request.addQueryParam("Category", category.toString()); + request.addQueryParam("Category", category); } if (startDate != null) { request.addQueryParam( diff --git a/src/main/java/com/twilio/rest/api/v2010/account/usage/record/Monthly.java b/src/main/java/com/twilio/rest/api/v2010/account/usage/record/Monthly.java index f6f3d7b082..9394d8b01a 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/usage/record/Monthly.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/usage/record/Monthly.java @@ -24,7 +24,6 @@ import com.twilio.base.Resource; import com.twilio.converter.CurrencyDeserializer; import com.twilio.converter.DateConverter; -import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import java.io.IOException; @@ -42,7 +41,7 @@ @ToString public class Monthly extends Resource { - private static final long serialVersionUID = 22373500842023L; + private static final long serialVersionUID = 158026917970511L; public static MonthlyReader reader() { return new MonthlyReader(); @@ -98,7 +97,7 @@ public static Monthly fromJson( private final String accountSid; private final String apiVersion; private final String asOf; - private final Monthly.Category category; + private final String category; private final String count; private final String countUnit; private final String description; @@ -116,7 +115,7 @@ private Monthly( @JsonProperty("account_sid") final String accountSid, @JsonProperty("api_version") final String apiVersion, @JsonProperty("as_of") final String asOf, - @JsonProperty("category") final Monthly.Category category, + @JsonProperty("category") final String category, @JsonProperty("count") final String count, @JsonProperty("count_unit") final String countUnit, @JsonProperty("description") final String description, @@ -163,7 +162,7 @@ public final String getAsOf() { return this.asOf; } - public final Monthly.Category getCategory() { + public final String getCategory() { return this.category; } @@ -262,945 +261,4 @@ public int hashCode() { usageUnit ); } - - public enum Category { - A2P_10DLC_REGISTRATIONFEES_BRANDREGISTRATION( - "a2p-10dlc-registrationfees-brandregistration" - ), - A2P_10DLC_REGISTRATIONFEES_BV("a2p-10dlc-registrationfees-bv"), - A2P_10DLC_REGISTRATIONFEES_CAMPAIGNCHARGES( - "a2p-10dlc-registrationfees-campaigncharges" - ), - A2P_10DLC_REGISTRATIONFEES_CAMPAIGNREGISTRATION( - "a2p-10dlc-registrationfees-campaignregistration" - ), - A2P_10DLC_REGISTRATIONFEES_CAMPAIGNVETTING( - "a2p-10dlc-registrationfees-campaignvetting" - ), - A2P_10DLC_REGISTRATIONFEES_MONTHLY( - "a2p-10dlc-registrationfees-monthly" - ), - A2P_10DLC_REGISTRATIONFEES_ONETIME( - "a2p-10dlc-registrationfees-onetime" - ), - A2P_REGISTRATION_FEES("a2p-registration-fees"), - ACCOUNT_SECURITY("account-security"), - AGENT_CONFERENCE("agent-conference"), - AGENT_COPILOT("agent-copilot"), - AGENT_COPILOT_MESSAGES("agent-copilot-messages"), - AGENT_COPILOT_PARTICIPANT_MINUTES("agent-copilot-participant-minutes"), - AI_ASSISTANTS("ai-assistants"), - AI_ASSISTANTS_VOICE("ai-assistants-voice"), - AMAZON_POLLY("amazon-polly"), - ANSWERING_MACHINE_DETECTION("answering-machine-detection"), - ASSETS("assets"), - AUDIENCE_MINUTES("audience-minutes"), - AUDIENCE_MINUTES_AUDIO("audience-minutes-audio"), - AUTHY_AUTHENTICATIONS("authy-authentications"), - AUTHY_CALLS_OUTBOUND("authy-calls-outbound"), - AUTHY_EMAIL_AUTHENTICATIONS("authy-email-authentications"), - AUTHY_MONTHLY_FEES("authy-monthly-fees"), - AUTHY_OUTBOUND_EMAIL("authy-outbound-email"), - AUTHY_PHONE_INTELLIGENCE("authy-phone-intelligence"), - AUTHY_PHONE_VERIFICATIONS("authy-phone-verifications"), - AUTHY_SMS_OUTBOUND("authy-sms-outbound"), - AUTHY_VERIFY_EMAIL_VERIFICATIONS("authy-verify-email-verifications"), - AUTHY_VERIFY_OUTBOUND_EMAIL("authy-verify-outbound-email"), - AUTOPILOT("autopilot"), - AUTOPILOT_HOME_ASSISTANTS("autopilot-home-assistants"), - AUTOPILOT_MESSAGING("autopilot-messaging"), - AUTOPILOT_OTHER("autopilot-other"), - AUTOPILOT_VOICE("autopilot-voice"), - BASIC_PEER_TO_PEER_ROOMS_PARTICIPANT_MINUTES( - "basic-peer-to-peer-rooms-participant-minutes" - ), - BRANDED_CALLING("branded-calling"), - BUNDLE_SMS_BUCKET("bundle-sms-bucket"), - BUNDLE_SUBSCRIPTION_FEES("bundle-subscription-fees"), - CALL_FORWARDING_LOOKUPS("call-forwarding-lookups"), - CALL_PROGESS_EVENTS("call-progess-events"), - CALLERIDLOOKUPS("calleridlookups"), - CALLS("calls"), - CALLS_CLIENT("calls-client"), - CALLS_EMERGENCY("calls-emergency"), - CALLS_GLOBALCONFERENCE("calls-globalconference"), - CALLS_INBOUND("calls-inbound"), - CALLS_INBOUND_LOCAL("calls-inbound-local"), - CALLS_INBOUND_MOBILE("calls-inbound-mobile"), - CALLS_INBOUND_TOLLFREE("calls-inbound-tollfree"), - CALLS_INBOUND_TOLLFREE_LOCAL("calls-inbound-tollfree-local"), - CALLS_INBOUND_TOLLFREE_MOBILE("calls-inbound-tollfree-mobile"), - CALLS_MEDIA_STREAM_MINUTES("calls-media-stream-minutes"), - CALLS_OUTBOUND("calls-outbound"), - CALLS_PAY_VERB_TRANSACTIONS("calls-pay-verb-transactions"), - CALLS_RECORDINGS("calls-recordings"), - CALLS_SIP("calls-sip"), - CALLS_SIP_INBOUND("calls-sip-inbound"), - CALLS_SIP_OUTBOUND("calls-sip-outbound"), - CALLS_TEXT_TO_SPEECH("calls-text-to-speech"), - CALLS_TRANSFERS("calls-transfers"), - CARRIER_LOOKUPS("carrier-lookups"), - CATEGORY("category"), - CHANNELS("channels"), - CHANNELS_MESSAGING("channels-messaging"), - CHANNELS_MESSAGING_INBOUND("channels-messaging-inbound"), - CHANNELS_MESSAGING_OUTBOUND("channels-messaging-outbound"), - CHANNELS_WHATSAPP("channels-whatsapp"), - CHANNELS_WHATSAPP_CONVERSATION_AUTHENTICATION( - "channels-whatsapp-conversation-authentication" - ), - CHANNELS_WHATSAPP_CONVERSATION_FREE( - "channels-whatsapp-conversation-free" - ), - CHANNELS_WHATSAPP_CONVERSATION_MARKETING( - "channels-whatsapp-conversation-marketing" - ), - CHANNELS_WHATSAPP_CONVERSATION_SERVICE( - "channels-whatsapp-conversation-service" - ), - CHANNELS_WHATSAPP_CONVERSATION_UTILITY( - "channels-whatsapp-conversation-utility" - ), - CHANNELS_WHATSAPP_INBOUND("channels-whatsapp-inbound"), - CHANNELS_WHATSAPP_OUTBOUND("channels-whatsapp-outbound"), - CHANNELS_WHATSAPP_SERVICE("channels-whatsapp-service"), - CHANNELS_WHATSAPP_TEMPLATE_AUTHENTICATION( - "channels-whatsapp-template-authentication" - ), - CHANNELS_WHATSAPP_TEMPLATE_MARKETING( - "channels-whatsapp-template-marketing" - ), - CHANNELS_WHATSAPP_TEMPLATE_SERVICE( - "channels-whatsapp-template-service" - ), - CHANNELS_WHATSAPP_TEMPLATE_UTILITY( - "channels-whatsapp-template-utility" - ), - CHAT_VIRTUAL_AGENT("chat-virtual-agent"), - CONVERSATION_RELAY("conversation-relay"), - CONVERSATIONS("conversations"), - CONVERSATIONS_API_REQUESTS("conversations-api-requests"), - CONVERSATIONS_CONVERSATION_EVENTS("conversations-conversation-events"), - CONVERSATIONS_ENDPOINT_CONNECTIVITY( - "conversations-endpoint-connectivity" - ), - CONVERSATIONS_EVENTS("conversations-events"), - CONVERSATIONS_PARTICIPANT_EVENTS("conversations-participant-events"), - CONVERSATIONS_PARTICIPANTS("conversations-participants"), - CPS("cps"), - CREDIT_TRANSFER("credit-transfer"), - EMAIL("email"), - EMERGING_TECH("emerging-tech"), - ENGAGEMENT_SUITE_PACKAGED_PLANS("engagement-suite-packaged-plans"), - ENHANCED_LINE_TYPE_LOOKUPS("enhanced-line-type-lookups"), - ENTERPRISE("enterprise"), - EVENTS("events"), - EXPERIMENT_FRANCE_SMS("experiment-france-sms"), - EXPERIMENT_INDIA_SMS("experiment-india-sms"), - EXPERIMENT_UK_SMS("experiment-uk-sms"), - FAILED_MESSAGE_PROCESSING_FEE("failed-message-processing-fee"), - FLEX("flex"), - FLEX_ACTIVE_USER_HOURS("flex-active-user-hours"), - FLEX_CONCURRENT_USERS("flex-concurrent-users"), - FLEX_CONVERSATIONAL_INSIGHTS("flex-conversational-insights"), - FLEX_CONVERSATIONAL_INSIGHTS_MESSAGES( - "flex-conversational-insights-messages" - ), - FLEX_CONVERSATIONAL_INSIGHTS_VOICE_MINUTES( - "flex-conversational-insights-voice-minutes" - ), - FLEX_EMAIL_USAGE("flex-email-usage"), - FLEX_MESSAGING_USAGE("flex-messaging-usage"), - FLEX_PARTNER_SPINSCI("flex-partner-spinsci"), - FLEX_PARTNER_XCELERATE("flex-partner-xcelerate"), - FLEX_RESELLER_ECOSYSTEM("flex-reseller-ecosystem"), - FLEX_UNIQUE_USER("flex-unique-user"), - FLEX_USAGE("flex-usage"), - FLEX_USERS("flex-users"), - FLEX_VOICE_MINUTE("flex-voice-minute"), - FLEX_YTICA("flex-ytica"), - FRAUD_LOOKUPS("fraud-lookups"), - FRONTLINE("frontline"), - FRONTLINE_USERS("frontline-users"), - FUNCTIONS("functions"), - GENERIC_PAY_TRANSACTIONS("generic-pay-transactions"), - GROUP_ROOMS("group-rooms"), - GROUP_ROOMS_DATA_TRACK("group-rooms-data-track"), - GROUP_ROOMS_ENCRYPTED_MEDIA_RECORDED( - "group-rooms-encrypted-media-recorded" - ), - GROUP_ROOMS_MEDIA_DOWNLOADED("group-rooms-media-downloaded"), - GROUP_ROOMS_MEDIA_RECORDED("group-rooms-media-recorded"), - GROUP_ROOMS_MEDIA_ROUTED("group-rooms-media-routed"), - GROUP_ROOMS_MEDIA_STORED("group-rooms-media-stored"), - GROUP_ROOMS_PARTICIPANT_MINUTES("group-rooms-participant-minutes"), - GROUP_ROOMS_RECORDED_MINUTES("group-rooms-recorded-minutes"), - IP_MESSAGING("ip-messaging"), - IP_MESSAGING_COMMANDS("ip-messaging-commands"), - IP_MESSAGING_DATA_STORAGE("ip-messaging-data-storage"), - IP_MESSAGING_DATA_TRANSFER("ip-messaging-data-transfer"), - IP_MESSAGING_ENDPOINT_CONNECTIVITY( - "ip-messaging-endpoint-connectivity" - ), - IVR_VIRTUAL_AGENT_CUSTOM_VOICES("ivr-virtual-agent-custom-voices"), - IVR_VIRTUAL_AGENT_GENAI("ivr-virtual-agent-genai"), - LINE_STATUS_LOOKUPS("line-status-lookups"), - LIVE_ACTIVITY_LOOKUPS("live-activity-lookups"), - LOOKUP_BUCKET_ADJUSTMENT("lookup-bucket-adjustment"), - LOOKUP_IDENTITY_MATCH("lookup-identity-match"), - LOOKUPS("lookups"), - MARKETPLACE("marketplace"), - MARKETPLACE_ALGORITHMIA_NAMED_ENTITY_RECOGNITION( - "marketplace-algorithmia-named-entity-recognition" - ), - MARKETPLACE_CADENCE_TRANSCRIPTION("marketplace-cadence-transcription"), - MARKETPLACE_CADENCE_TRANSLATION("marketplace-cadence-translation"), - MARKETPLACE_CAPIO_SPEECH_TO_TEXT("marketplace-capio-speech-to-text"), - MARKETPLACE_CONVRIZA_ABABA("marketplace-convriza-ababa"), - MARKETPLACE_DEEPGRAM_PHRASE_DETECTOR( - "marketplace-deepgram-phrase-detector" - ), - MARKETPLACE_DEEPGRAM_TRANSCRIPTION( - "marketplace-deepgram-transcription" - ), - MARKETPLACE_DEEPGRAM_TRANSCRIPTION_BASE( - "marketplace-deepgram-transcription-base" - ), - MARKETPLACE_DEEPGRAM_TRANSSCRIPTION_ENHANCED( - "marketplace-deepgram-transscription-enhanced" - ), - MARKETPLACE_DIGITAL_SEGMENT_BUSINESS_INFO( - "marketplace-digital-segment-business-info" - ), - MARKETPLACE_FACEBOOK_OFFLINE_CONVERSIONS( - "marketplace-facebook-offline-conversions" - ), - MARKETPLACE_GOOGLE_SPEECH_TO_TEXT("marketplace-google-speech-to-text"), - MARKETPLACE_IBM_WATSON_MESSAGE_INSIGHTS( - "marketplace-ibm-watson-message-insights" - ), - MARKETPLACE_IBM_WATSON_MESSAGE_SENTIMENT( - "marketplace-ibm-watson-message-sentiment" - ), - MARKETPLACE_IBM_WATSON_RECORDING_ANALYSIS( - "marketplace-ibm-watson-recording-analysis" - ), - MARKETPLACE_IBM_WATSON_TONE_ANALYZER( - "marketplace-ibm-watson-tone-analyzer" - ), - MARKETPLACE_ICEHOOK_SYSTEMS_SCOUT("marketplace-icehook-systems-scout"), - MARKETPLACE_INFOGROUP_DATAAXLE_BIZINFO( - "marketplace-infogroup-dataaxle-bizinfo" - ), - MARKETPLACE_KEEN_IO_CONTACT_CENTER_ANALYTICS( - "marketplace-keen-io-contact-center-analytics" - ), - MARKETPLACE_MARCHEX_CLEANCALL("marketplace-marchex-cleancall"), - MARKETPLACE_MARCHEX_RECORDING_ANALYSIS( - "marketplace-marchex-recording-analysis" - ), - MARKETPLACE_MARCHEX_SENTIMENT_ANALYSIS_FOR_SMS( - "marketplace-marchex-sentiment-analysis-for-sms" - ), - MARKETPLACE_MARKETPLACE_NEXTCALLER_SOCIAL_ID( - "marketplace-marketplace-nextcaller-social-id" - ), - MARKETPLACE_MOBILE_COMMONS_OPT_OUT_CLASSIFIER( - "marketplace-mobile-commons-opt-out-classifier" - ), - MARKETPLACE_NEXIWAVE_VOICEMAIL_TO_TEXT( - "marketplace-nexiwave-voicemail-to-text" - ), - MARKETPLACE_NEXTCALLER_ADVANCED_CALLER_IDENTIFICATION( - "marketplace-nextcaller-advanced-caller-identification" - ), - MARKETPLACE_NOMOROBO_SPAM_SCORE("marketplace-nomorobo-spam-score"), - MARKETPLACE_PAY_ADDONS("marketplace-pay-addons"), - MARKETPLACE_PAY_ADDONS_BASECOMMERCE_PAY_CONNECTOR( - "marketplace-pay-addons-basecommerce-pay-connector" - ), - MARKETPLACE_PAY_ADDONS_BRAINTREE_PAY_CONNECTOR( - "marketplace-pay-addons-braintree-pay-connector" - ), - MARKETPLACE_PAY_ADDONS_CARDCONNECT_PAY_CONNECTOR( - "marketplace-pay-addons-cardconnect-pay-connector" - ), - MARKETPLACE_PAY_ADDONS_CHASE_PAY_CONNECTOR( - "marketplace-pay-addons-chase-pay-connector" - ), - MARKETPLACE_PAY_ADDONS_SHUTTLE_PAY_CONNECTOR( - "marketplace-pay-addons-shuttle-pay-connector" - ), - MARKETPLACE_PAY_ADDONS_STRIPE_PAY_CONNECTOR( - "marketplace-pay-addons-stripe-pay-connector" - ), - MARKETPLACE_PAYFONE_TCPA_COMPLIANCE( - "marketplace-payfone-tcpa-compliance" - ), - MARKETPLACE_POLY_AI_CONNECTOR("marketplace-poly-ai-connector"), - MARKETPLACE_REALPHONEVALIDATION("marketplace-realphonevalidation"), - MARKETPLACE_REMEETING_AUTOMATIC_SPEECH_RECOGNITION( - "marketplace-remeeting-automatic-speech-recognition" - ), - MARKETPLACE_SPOKE_PHONE_LICENSE_PRO( - "marketplace-spoke-phone-license-pro" - ), - MARKETPLACE_SPOKE_PHONE_LICENSE_STANDARD( - "marketplace-spoke-phone-license-standard" - ), - MARKETPLACE_TCPA_DEFENSE_SOLUTIONS_BLACKLIST_FEED( - "marketplace-tcpa-defense-solutions-blacklist-feed" - ), - MARKETPLACE_TELO_OPENCNAM("marketplace-telo-opencnam"), - MARKETPLACE_TRESTLE_SOLUTIONS_CALLER_IDENTIFICATION( - "marketplace-trestle-solutions-caller-identification" - ), - MARKETPLACE_TRUECNAM_TRUE_SPAM("marketplace-truecnam-true-spam"), - MARKETPLACE_TWILIO_CALLER_NAME_LOOKUP_US( - "marketplace-twilio-caller-name-lookup-us" - ), - MARKETPLACE_TWILIO_CARRIER_INFORMATION_LOOKUP( - "marketplace-twilio-carrier-information-lookup" - ), - MARKETPLACE_VOICEBASE_PCI("marketplace-voicebase-pci"), - MARKETPLACE_VOICEBASE_TRANSCRIPTION( - "marketplace-voicebase-transcription" - ), - MARKETPLACE_VOICEBASE_TRANSCRIPTION_CUSTOM_VOCABULARY( - "marketplace-voicebase-transcription-custom-vocabulary" - ), - MARKETPLACE_WEB_PURIFY_PROFANITY_FILTER( - "marketplace-web-purify-profanity-filter" - ), - MARKETPLACE_WHITEPAGES_PRO_CALLER_IDENTIFICATION( - "marketplace-whitepages-pro-caller-identification" - ), - MARKETPLACE_WHITEPAGES_PRO_PHONE_INTELLIGENCE( - "marketplace-whitepages-pro-phone-intelligence" - ), - MARKETPLACE_WHITEPAGES_PRO_PHONE_REPUTATION( - "marketplace-whitepages-pro-phone-reputation" - ), - MARKETPLACE_WOLFARM_SPOKEN_RESULTS( - "marketplace-wolfarm-spoken-results" - ), - MARKETPLACE_WOLFRAM_SHORT_ANSWER("marketplace-wolfram-short-answer"), - MARKETPLACE_YTICA_CONTACT_CENTER_REPORTING_ANALYTICS( - "marketplace-ytica-contact-center-reporting-analytics" - ), - MARKETPLAY_PAY_ADDONS_SHUTTLE_PAY_CONNECTOR( - "marketplay-pay-addons-shuttle-pay-connector" - ), - MEDIA_COMPOSER_MINUTES("media-composer-minutes"), - MEDIASTORAGE("mediastorage"), - MIN_SPEND_ADJUSTMENTS("min-spend-adjustments"), - MMS("mms"), - MMS_INBOUND("mms-inbound"), - MMS_INBOUND_LONGCODE("mms-inbound-longcode"), - MMS_INBOUND_SHORTCODE("mms-inbound-shortcode"), - MMS_INBOUND_TOLL_FREE("mms-inbound-toll-free"), - MMS_MESSAGES_CARRIERFEES("mms-messages-carrierfees"), - MMS_OUTBOUND("mms-outbound"), - MMS_OUTBOUND_LONGCODE("mms-outbound-longcode"), - MMS_OUTBOUND_SHORTCODE("mms-outbound-shortcode"), - MMS_OUTBOUND_TOLLFREE("mms-outbound-tollfree"), - MONITOR("monitor"), - MONITOR_READS("monitor-reads"), - MONITOR_STORAGE("monitor-storage"), - MONITOR_WRITES("monitor-writes"), - NOTIFY("notify"), - NOTIFY_ACTIONS_ATTEMPTS("notify-actions-attempts"), - NOTIFY_CHANNELS("notify-channels"), - NUMBER_FORMAT_LOOKUPS("number-format-lookups"), - PCHAT("pchat"), - PCHAT_ACTIONS("pchat-actions"), - PCHAT_APS("pchat-aps"), - PCHAT_CONV_MED_STORAGE("pchat-conv-med-storage"), - PCHAT_MESSAGES("pchat-messages"), - PCHAT_NOTIFICATIONS("pchat-notifications"), - PCHAT_READS("pchat-reads"), - PCHAT_USERS("pchat-users"), - PEER_TO_PEER_ROOMS_PARTICIPANT_MINUTES( - "peer-to-peer-rooms-participant-minutes" - ), - PFAX("pfax"), - PFAX_MINUTES("pfax-minutes"), - PFAX_MINUTES_INBOUND("pfax-minutes-inbound"), - PFAX_MINUTES_OUTBOUND("pfax-minutes-outbound"), - PFAX_PAGES("pfax-pages"), - PHONE_QUALITY_SCORE_LOOKUPS("phone-quality-score-lookups"), - PHONENUMBERS("phonenumbers"), - PHONENUMBERS_CPS("phonenumbers-cps"), - PHONENUMBERS_EMERGENCY("phonenumbers-emergency"), - PHONENUMBERS_LOCAL("phonenumbers-local"), - PHONENUMBERS_MOBILE("phonenumbers-mobile"), - PHONENUMBERS_PORTING("phonenumbers-porting"), - PHONENUMBERS_SETUPS("phonenumbers-setups"), - PHONENUMBERS_TOLLFREE("phonenumbers-tollfree"), - PREMIUMSUPPORT("premiumsupport"), - PREMIUMSUPPORT_PERCENTAGE_SPEND("premiumsupport-percentage-spend"), - PROGRAMMABLEVOICE_PLATFORM("programmablevoice-platform"), - PROGRAMMABLEVOICECONN_CLIENTSDK("programmablevoiceconn-clientsdk"), - PROGRAMMABLEVOICECONN_CLIENTSDK_INBOUND( - "programmablevoiceconn-clientsdk-inbound" - ), - PROGRAMMABLEVOICECONN_CLIENTSDK_OUTBOUND( - "programmablevoiceconn-clientsdk-outbound" - ), - PROGRAMMABLEVOICECONN_ONNET("programmablevoiceconn-onnet"), - PROGRAMMABLEVOICECONN_ONNET_INBOUND( - "programmablevoiceconn-onnet-inbound" - ), - PROGRAMMABLEVOICECONN_ONNET_OUTBOUND( - "programmablevoiceconn-onnet-outbound" - ), - PROGRAMMABLEVOICECONN_SIP("programmablevoiceconn-sip"), - PROGRAMMABLEVOICECONN_SIP_INBOUND("programmablevoiceconn-sip-inbound"), - PROGRAMMABLEVOICECONN_SIP_OUTBOUND( - "programmablevoiceconn-sip-outbound" - ), - PROGRAMMABLEVOICECONNECTIVITY("programmablevoiceconnectivity"), - PROXY("proxy"), - PROXY_ACTIVE_SESSIONS("proxy-active-sessions"), - PROXY_BUCKET_ADJUSTMENT("proxy-bucket-adjustment"), - PROXY_LICENSES("proxy-licenses"), - PSTNCONNECTIVITY("pstnconnectivity"), - PSTNCONNECTIVITY_INBOUND("pstnconnectivity-inbound"), - PSTNCONNECTIVITY_OUTBOUND("pstnconnectivity-outbound"), - PV("pv"), - PV_BASIC_ROOMS("pv-basic-rooms"), - PV_COMPOSITION_MEDIA_DOWNLOADED("pv-composition-media-downloaded"), - PV_COMPOSITION_MEDIA_ENCRYPTED("pv-composition-media-encrypted"), - PV_COMPOSITION_MEDIA_STORED("pv-composition-media-stored"), - PV_COMPOSITION_MINUTES("pv-composition-minutes"), - PV_RECORDING_COMPOSITIONS("pv-recording-compositions"), - PV_ROOM_PARTICIPANTS("pv-room-participants"), - PV_ROOM_PARTICIPANTS_AU1("pv-room-participants-au1"), - PV_ROOM_PARTICIPANTS_BR1("pv-room-participants-br1"), - PV_ROOM_PARTICIPANTS_IE1("pv-room-participants-ie1"), - PV_ROOM_PARTICIPANTS_JP1("pv-room-participants-jp1"), - PV_ROOM_PARTICIPANTS_SG1("pv-room-participants-sg1"), - PV_ROOM_PARTICIPANTS_US1("pv-room-participants-us1"), - PV_ROOM_PARTICIPANTS_US2("pv-room-participants-us2"), - PV_ROOMS("pv-rooms"), - PV_SIP_ENDPOINT_REGISTRATIONS("pv-sip-endpoint-registrations"), - RCS_MESSAGES("rcs-messages"), - REASSIGNED_NUMBER("reassigned-number"), - RECORDINGS("recordings"), - RECORDINGSTORAGE("recordingstorage"), - SHORTCODES("shortcodes"), - SHORTCODES_CUSTOMEROWNED("shortcodes-customerowned"), - SHORTCODES_MMS_ENABLEMENT("shortcodes-mms-enablement"), - SHORTCODES_MPS("shortcodes-mps"), - SHORTCODES_RANDOM("shortcodes-random"), - SHORTCODES_SETUP_FEES("shortcodes-setup-fees"), - SHORTCODES_UK("shortcodes-uk"), - SHORTCODES_VANITY("shortcodes-vanity"), - SIM_SWAP_LOOKUPS("sim-swap-lookups"), - SIP_SECURE_MEDIA("sip-secure-media"), - SMALL_GROUP_ROOMS("small-group-rooms"), - SMALL_GROUP_ROOMS_DATA_TRACK("small-group-rooms-data-track"), - SMALL_GROUP_ROOMS_PARTICIPANT_MINUTES( - "small-group-rooms-participant-minutes" - ), - SMS("sms"), - SMS_INBOUND("sms-inbound"), - SMS_INBOUND_LONGCODE("sms-inbound-longcode"), - SMS_INBOUND_SHORTCODE("sms-inbound-shortcode"), - SMS_INBOUND_TOLLFREE("sms-inbound-tollfree"), - SMS_MESSAGES_CARRIERFEES("sms-messages-carrierfees"), - SMS_MESSAGES_FEATURES("sms-messages-features"), - SMS_MESSAGES_FEATURES_ENGAGEMENT_SUITE( - "sms-messages-features-engagement-suite" - ), - SMS_MESSAGES_FEATURES_MESSAGE_REDACTION( - "sms-messages-features-message-redaction" - ), - SMS_MESSAGES_FEATURES_SENDERID("sms-messages-features-senderid"), - SMS_MPS("sms-mps"), - SMS_MPS_SHORTCODE("sms-mps-shortcode"), - SMS_MPS_TOLLFREE("sms-mps-tollfree"), - SMS_MPS_TOLLFREE_SETUP("sms-mps-tollfree-setup"), - SMS_NATIONAL_REGULATORY_PROTECTION( - "sms-national-regulatory-protection" - ), - SMS_OUTBOUND("sms-outbound"), - SMS_OUTBOUND_CONTENT_INSPECTION("sms-outbound-content-inspection"), - SMS_OUTBOUND_LONGCODE("sms-outbound-longcode"), - SMS_OUTBOUND_SHORTCODE("sms-outbound-shortcode"), - SMS_OUTBOUND_TOLLFREE("sms-outbound-tollfree"), - SMS_PUMPING_PROTECTION("sms-pumping-protection"), - SMS_PUMPING_RISK("sms-pumping-risk"), - SMSMESSAGES_BUCKET_ADJUSTMENTS("smsmessages-bucket-adjustments"), - SMSMESSAGES_OUTBOUND_DOMESTIC("smsmessages-outbound-domestic"), - SPEECH_RECOGNITION("speech-recognition"), - STUDIO_ENGAGEMENTS("studio-engagements"), - SYNC("sync"), - SYNC_ACTIONS("sync-actions"), - SYNC_ENDPOINT_HOURS("sync-endpoint-hours"), - SYNC_ENDPOINT_HOURS_ABOVE_DAILY_CAP( - "sync-endpoint-hours-above-daily-cap" - ), - TASKROUTER_TASKS("taskrouter-tasks"), - TOTALPRICE("totalprice"), - TRANSCRIPTIONS("transcriptions"), - TRUNKING_CPS("trunking-cps"), - TRUNKING_EMERGENCY_CALLS("trunking-emergency-calls"), - TRUNKING_ORIGINATION("trunking-origination"), - TRUNKING_ORIGINATION_LOCAL("trunking-origination-local"), - TRUNKING_ORIGINATION_MOBILE("trunking-origination-mobile"), - TRUNKING_ORIGINATION_TOLLFREE("trunking-origination-tollfree"), - TRUNKING_RECORDINGS("trunking-recordings"), - TRUNKING_SECURE("trunking-secure"), - TRUNKING_TERMINATION("trunking-termination"), - TTS_GOOGLE("tts-google"), - TURNMEGABYTES("turnmegabytes"), - TURNMEGABYTES_AUSTRALIA("turnmegabytes-australia"), - TURNMEGABYTES_BRASIL("turnmegabytes-brasil"), - TURNMEGABYTES_GERMANY("turnmegabytes-germany"), - TURNMEGABYTES_INDIA("turnmegabytes-india"), - TURNMEGABYTES_IRELAND("turnmegabytes-ireland"), - TURNMEGABYTES_JAPAN("turnmegabytes-japan"), - TURNMEGABYTES_SINGAPORE("turnmegabytes-singapore"), - TURNMEGABYTES_USEAST("turnmegabytes-useast"), - TURNMEGABYTES_USWEST("turnmegabytes-uswest"), - TWILIO_FOR_SALESFORCE("twilio-for-salesforce"), - TWILIO_FOR_SALESFORCE_LICENSES("twilio-for-salesforce-licenses"), - TWILIO_INTERCONNECT("twilio-interconnect"), - TWIML("twiml"), - USAGE_FLEX_VIDEO("usage-flex-video"), - USAGE_FUNCTIONS("usage-functions"), - USAGE_RCS_BASIC_MESSAGES_OUTBOUND("usage-rcs-basic-messages-outbound"), - USAGE_RCS_MESSAGES("usage-rcs-messages"), - USAGE_RCS_MESSAGES_INBOUND("usage-rcs-messages-inbound"), - USAGE_RCS_MESSAGING_CARRIER_FEES("usage-rcs-messaging-carrier-fees"), - USAGE_RCS_SINGLE_MESSAGES_OUTBOUND( - "usage-rcs-single-messages-outbound" - ), - VERIFY_PACKAGE_PLANS("verify-package-plans"), - VERIFY_PUSH("verify-push"), - VERIFY_SNA("verify-sna"), - VERIFY_TOTP("verify-totp"), - VERIFY_VOICE_SMS("verify-voice-sms"), - VERIFY_WHATSAPP_CONVERSATIONS_BUSINESS_INITIATED( - "verify-whatsapp-conversations-business-initiated" - ), - VERIFY_WHATSAPP_TEMPLATE_BUSINESS_INITIATED( - "verify-whatsapp-template-business-initiated" - ), - VIDEO_RECORDINGS("video-recordings"), - VIDEO_ROOMS_TURN_MEGABYTES("video-rooms-turn-megabytes"), - VIRTUAL_AGENT("virtual-agent"), - VOICE_INSIGHTS("voice-insights"), - VOICE_INSIGHTS_CLIENT_INSIGHTS_ON_DEMAND_MINUTE( - "voice-insights-client-insights-on-demand-minute" - ), - VOICE_INSIGHTS_PTSN_INSIGHTS_ON_DEMAND_MINUTE( - "voice-insights-ptsn-insights-on-demand-minute" - ), - VOICE_INSIGHTS_SIP_INTERFACE_INSIGHTS_ON_DEMAND_MINUTE( - "voice-insights-sip-interface-insights-on-demand-minute" - ), - VOICE_INSIGHTS_SIP_TRUNKING_INSIGHTS_ON_DEMAND_MINUTE( - "voice-insights-sip-trunking-insights-on-demand-minute" - ), - VOICE_INTELLIGENCE("voice-intelligence"), - VOICE_INTELLIGENCE_EIP_OPERATORS("voice-intelligence-eip-operators"), - VOICE_INTELLIGENCE_OPERATORS("voice-intelligence-operators"), - VOICE_INTELLIGENCE_TRANSCRIPTION("voice-intelligence-transcription"), - WDS("wds"), - WIRELESS("wireless"), - WIRELESS_DATA("wireless-data"), - WIRELESS_DATA_PAYG("wireless-data-payg"), - WIRELESS_DATA_PAYG_AFRICA("wireless-data-payg-africa"), - WIRELESS_DATA_PAYG_ASIA("wireless-data-payg-asia"), - WIRELESS_DATA_PAYG_CENTRALANDSOUTHAMERICA( - "wireless-data-payg-centralandsouthamerica" - ), - WIRELESS_DATA_PAYG_EUROPE("wireless-data-payg-europe"), - WIRELESS_DATA_PAYG_NORTHAMERICA("wireless-data-payg-northamerica"), - WIRELESS_DATA_PAYG_OCEANIA("wireless-data-payg-oceania"), - WIRELESS_DATA_QUOTA1("wireless-data-quota1"), - WIRELESS_DATA_QUOTA1_AFRICA("wireless-data-quota1-africa"), - WIRELESS_DATA_QUOTA1_ASIA("wireless-data-quota1-asia"), - WIRELESS_DATA_QUOTA1_CENTRALANDSOUTHAMERICA( - "wireless-data-quota1-centralandsouthamerica" - ), - WIRELESS_DATA_QUOTA1_EUROPE("wireless-data-quota1-europe"), - WIRELESS_DATA_QUOTA1_NORTHAMERICA("wireless-data-quota1-northamerica"), - WIRELESS_DATA_QUOTA1_OCEANIA("wireless-data-quota1-oceania"), - WIRELESS_DATA_QUOTA10("wireless-data-quota10"), - WIRELESS_DATA_QUOTA10_AFRICA("wireless-data-quota10-africa"), - WIRELESS_DATA_QUOTA10_ASIA("wireless-data-quota10-asia"), - WIRELESS_DATA_QUOTA10_CENTRALANDSOUTHAMERICA( - "wireless-data-quota10-centralandsouthamerica" - ), - WIRELESS_DATA_QUOTA10_EUROPE("wireless-data-quota10-europe"), - WIRELESS_DATA_QUOTA10_NORTHAMERICA( - "wireless-data-quota10-northamerica" - ), - WIRELESS_DATA_QUOTA10_OCEANIA("wireless-data-quota10-oceania"), - WIRELESS_DATA_QUOTA50("wireless-data-quota50"), - WIRELESS_DATA_QUOTA50_AFRICA("wireless-data-quota50-africa"), - WIRELESS_DATA_QUOTA50_ASIA("wireless-data-quota50-asia"), - WIRELESS_DATA_QUOTA50_CENTRALANDSOUTHAMERICA( - "wireless-data-quota50-centralandsouthamerica" - ), - WIRELESS_DATA_QUOTA50_EUROPE("wireless-data-quota50-europe"), - WIRELESS_DATA_QUOTA50_NORTHAMERICA( - "wireless-data-quota50-northamerica" - ), - WIRELESS_DATA_QUOTA50_OCEANIA("wireless-data-quota50-oceania"), - WIRELESS_DATA_QUOTACUSTOM("wireless-data-quotacustom"), - WIRELESS_DATA_QUOTACUSTOM_AFRICA("wireless-data-quotacustom-africa"), - WIRELESS_DATA_QUOTACUSTOM_ASIA("wireless-data-quotacustom-asia"), - WIRELESS_DATA_QUOTACUSTOM_CENTRALANDSOUTHAMERICA( - "wireless-data-quotacustom-centralandsouthamerica" - ), - WIRELESS_DATA_QUOTACUSTOM_EUROPE("wireless-data-quotacustom-europe"), - WIRELESS_DATA_QUOTACUSTOM_NORTHAMERICA( - "wireless-data-quotacustom-northamerica" - ), - WIRELESS_DATA_QUOTACUSTOM_OCEANIA("wireless-data-quotacustom-oceania"), - WIRELESS_MRC_PAYG("wireless-mrc-payg"), - WIRELESS_MRC_QUOTA1("wireless-mrc-quota1"), - WIRELESS_MRC_QUOTA10("wireless-mrc-quota10"), - WIRELESS_MRC_QUOTA50("wireless-mrc-quota50"), - WIRELESS_MRC_QUOTACUSTOM("wireless-mrc-quotacustom"), - WIRELESS_ORDERS("wireless-orders"), - WIRELESS_ORDERS_ARTWORK("wireless-orders-artwork"), - WIRELESS_ORDERS_BULK("wireless-orders-bulk"), - WIRELESS_ORDERS_ESIM("wireless-orders-esim"), - WIRELESS_ORDERS_STARTER("wireless-orders-starter"), - WIRELESS_QUOTAS("wireless-quotas"), - WIRELESS_SMS_AFRICA("wireless-sms-africa"), - WIRELESS_SMS_ASIA("wireless-sms-asia"), - WIRELESS_SMS_CENTRALANDSOUTHAMERICA( - "wireless-sms-centralandsouthamerica" - ), - WIRELESS_SMS_EUROPE("wireless-sms-europe"), - WIRELESS_SMS_NORTHAMERICA("wireless-sms-northamerica"), - WIRELESS_SMS_OCEANIA("wireless-sms-oceania"), - WIRELESS_SUPER_SIM("wireless-super-sim"), - WIRELESS_SUPER_SIM_DATA("wireless-super-sim-data"), - WIRELESS_SUPER_SIM_DATA_NORTH_AMERICA_USA( - "wireless-super-sim-data-north-america-usa" - ), - WIRELESS_SUPER_SIM_DATA_PAYG("wireless-super-sim-data-payg"), - WIRELESS_SUPER_SIM_DATA_PAYG_EUROPE( - "wireless-super-sim-data-payg-europe" - ), - WIRELESS_SUPER_SIM_DATA_PAYG_NORTH_AMERICA( - "wireless-super-sim-data-payg-north-america" - ), - WIRELESS_SUPER_SIM_HARDWARE("wireless-super-sim-hardware"), - WIRELESS_SUPER_SIM_HARDWARE_BULK("wireless-super-sim-hardware-bulk"), - WIRELESS_SUPER_SIM_SMSCOMMANDS("wireless-super-sim-smscommands"), - WIRELESS_SUPER_SIM_SMSCOMMANDS_AFRICA( - "wireless-super-sim-smscommands-africa" - ), - WIRELESS_SUPER_SIM_SMSCOMMANDS_ASIA( - "wireless-super-sim-smscommands-asia" - ), - WIRELESS_SUPER_SIM_SMSCOMMANDS_CENT_AND_SOUTH_AMERICA( - "wireless-super-sim-smscommands-cent-and-south-america" - ), - WIRELESS_SUPER_SIM_SMSCOMMANDS_EUROPE( - "wireless-super-sim-smscommands-europe" - ), - WIRELESS_SUPER_SIM_SMSCOMMANDS_NORTH_AMERICA( - "wireless-super-sim-smscommands-north-america" - ), - WIRELESS_SUPER_SIM_SMSCOMMANDS_OCEANIA( - "wireless-super-sim-smscommands-oceania" - ), - WIRELESS_SUPER_SIM_SUBSCRIPTION("wireless-super-sim-subscription"), - WIRELESS_SUPER_SIM_SUBSCRIPTION_PAYG( - "wireless-super-sim-subscription-payg" - ), - WIRELESS_USAGE("wireless-usage"), - WIRELESS_USAGE_COMMANDS("wireless-usage-commands"), - WIRELESS_USAGE_COMMANDS_AFRICA("wireless-usage-commands-africa"), - WIRELESS_USAGE_COMMANDS_ASIA("wireless-usage-commands-asia"), - WIRELESS_USAGE_COMMANDS_CENTRALANDSOUTHAMERICA( - "wireless-usage-commands-centralandsouthamerica" - ), - WIRELESS_USAGE_COMMANDS_EUROPE("wireless-usage-commands-europe"), - WIRELESS_USAGE_COMMANDS_HOME("wireless-usage-commands-home"), - WIRELESS_USAGE_COMMANDS_NORTHAMERICA( - "wireless-usage-commands-northamerica" - ), - WIRELESS_USAGE_COMMANDS_OCEANIA("wireless-usage-commands-oceania"), - WIRELESS_USAGE_COMMANDS_ROAMING("wireless-usage-commands-roaming"), - WIRELESS_USAGE_DATA("wireless-usage-data"), - WIRELESS_USAGE_DATA_AFRICA("wireless-usage-data-africa"), - WIRELESS_USAGE_DATA_ASIA("wireless-usage-data-asia"), - WIRELESS_USAGE_DATA_CENTRALANDSOUTHAMERICA( - "wireless-usage-data-centralandsouthamerica" - ), - WIRELESS_USAGE_DATA_CUSTOM_ADDITIONALMB( - "wireless-usage-data-custom-additionalmb" - ), - WIRELESS_USAGE_DATA_CUSTOM_FIRST5MB( - "wireless-usage-data-custom-first5mb" - ), - WIRELESS_USAGE_DATA_DOMESTIC_ROAMING( - "wireless-usage-data-domestic-roaming" - ), - WIRELESS_USAGE_DATA_EUROPE("wireless-usage-data-europe"), - WIRELESS_USAGE_DATA_INDIVIDUAL_ADDITIONALGB( - "wireless-usage-data-individual-additionalgb" - ), - WIRELESS_USAGE_DATA_INDIVIDUAL_FIRSTGB( - "wireless-usage-data-individual-firstgb" - ), - WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_CANADA( - "wireless-usage-data-international-roaming-canada" - ), - WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_INDIA( - "wireless-usage-data-international-roaming-india" - ), - WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_MEXICO( - "wireless-usage-data-international-roaming-mexico" - ), - WIRELESS_USAGE_DATA_NORTHAMERICA("wireless-usage-data-northamerica"), - WIRELESS_USAGE_DATA_OCEANIA("wireless-usage-data-oceania"), - WIRELESS_USAGE_DATA_POOLED("wireless-usage-data-pooled"), - WIRELESS_USAGE_DATA_POOLED_DOWNLINK( - "wireless-usage-data-pooled-downlink" - ), - WIRELESS_USAGE_DATA_POOLED_UPLINK("wireless-usage-data-pooled-uplink"), - WIRELESS_USAGE_MRC("wireless-usage-mrc"), - WIRELESS_USAGE_MRC_CUSTOM("wireless-usage-mrc-custom"), - WIRELESS_USAGE_MRC_INDIVIDUAL("wireless-usage-mrc-individual"), - WIRELESS_USAGE_MRC_POOLED("wireless-usage-mrc-pooled"), - WIRELESS_USAGE_MRC_SUSPENDED("wireless-usage-mrc-suspended"), - WIRELESS_USAGE_SMS("wireless-usage-sms"), - WIRELESS_USAGE_VOICE("wireless-usage-voice"), - A2P_FAST_TRACK_ONBOARDING("a2p-fast-track-onboarding"), - ADVISORY_SERVICES("advisory-services"), - ADVISORY_SERVICES_BILLED("advisory-services-billed"), - ADVISORY_SERVICES_CALL_TRACKING("advisory-services-call-tracking"), - ADVISORY_SERVICES_DATA_SERVICES("advisory-services-data-services"), - ADVISORY_SERVICES_EXPENSES("advisory-services-expenses"), - ADVISORY_SERVICES_SIP_TRUNKING("advisory-services-sip-trunking"), - ASSETS_REQUESTS("assets-requests"), - AUDIENCE_MINUTES_VIDEO("audience-minutes-video"), - AUTHY_BUCKET_ADJUSTMENT("authy-bucket-adjustment"), - AUTHY_SOFTWARE("authy-software"), - CALLERIDLOOKUPS_API("calleridlookups-api"), - CALLERIDLOOKUPS_PROGRAMMABLEVOICE("calleridlookups-programmablevoice"), - CALLERIDLOOKUPS_TRUNKING("calleridlookups-trunking"), - CALLS_TRUNKING_INBOUND_TOLLFREE_LOCAL( - "calls-trunking-inbound-tollfree-local" - ), - CALLS_TRUNKING_INBOUND_TOLLFREE_MOBILE( - "calls-trunking-inbound-tollfree-mobile" - ), - CHANNELS_WHATSAPP_CONVERSATION_FREE_1( - "channels-whatsapp-conversation-free-1" - ), - CONFERENCE("conference"), - CONVERSATIONAL_INSIGHTS("conversational-insights"), - CONVERSATIONAL_INSIGHTS_MESSAGES("conversational-insights-messages"), - CONVERSATIONAL_INSIGHTS_VOICE_MINUTES( - "conversational-insights-voice-minutes" - ), - DEMO("demo"), - DEMO_UC_SCRIPT_TEST("demo-uc-script-test"), - ELASTIC_SIP_TRUNKING("elastic-sip-trunking"), - ELASTIC_SIP_TRUNKING_CALL_TRANSFERS( - "elastic-sip-trunking-call-transfers" - ), - ENTERPRISE_HIPPA("enterprise-hippa"), - FLEX_NAMED_USERS("flex-named-users"), - FLEX_SPINSCI("flex-spinsci"), - FLEX_USERS_1("flex-users-1"), - FLEX_WFO_PREMIUM_SPEECH_ANALYTICS("flex-wfo-premium-speech-analytics"), - FLEX_XCELERATE("flex-xcelerate"), - FUNCTIONS_ROLLUP("functions-rollup"), - IMP_V1_USAGE("imp-v1-usage"), - IP_MESSAGING_ADDONS("ip-messaging-addons"), - IVR("ivr"), - IVR_CONVERSATIONAL("ivr-conversational"), - IVR_DTMF("ivr-dtmf"), - IVR_VIRTUALAGENT("ivr-virtualagent"), - LIVE("live"), - LIVE_MEDIA_RECORDING_MINUTES("live-media-recording-minutes"), - LONGCODE_MPS("longcode-mps"), - MARKETPLACE_ANALYTICS_ADDONS("marketplace-analytics-addons"), - MARKETPLACE_ISV_ADDONS("marketplace-isv-addons"), - MARKETPLACE_MESSAGING_ADDONS("marketplace-messaging-addons"), - MARKETPLACE_PHONENUMBERS_ADDONS("marketplace-phonenumbers-addons"), - MARKETPLACE_RECORDING_ADDONS("marketplace-recording-addons"), - MARKETPLACE_VIRTUALAGENT_ADDONS("marketplace-virtualagent-addons"), - MARKETPLAY_PAY_ADDONS_SHUTTLE_PAY_CONNECTOR_1( - "marketplay-pay-addons-shuttle-pay-connector-1" - ), - MARKETPLAY_PAY_ADDONS_STRIPE_PAY_CONNECTOR( - "marketplay-pay-addons-stripe-pay-connector" - ), - MMS_INBOUND_LONGCODE_CANADA("mms-inbound-longcode-canada"), - MMS_INBOUND_LONGCODE_UNITEDSTATES("mms-inbound-longcode-unitedstates"), - MMS_OUTBOUND_LONGCODE_CANADA("mms-outbound-longcode-canada"), - MMS_OUTBOUND_LONGCODE_UNITEDSTATES( - "mms-outbound-longcode-unitedstates" - ), - MMS_OUTBOUND_TOLL_FREE("mms-outbound-toll-free"), - NOTIFY_CHATAPPSANDOTHERCHANNELS("notify-chatappsandotherchannels"), - NOTIFY_NOTIFYSERVICES("notify-notifyservices"), - NOTIFY_PUSHNOTIFICATIONS("notify-pushnotifications"), - PAYMENT_GATEWAY_CONNECTORS("payment-gateway-connectors"), - PAYMENT_SOLUTIONS("payment-solutions"), - PCHAT_BUCKET_ADJUSTMENT("pchat-bucket-adjustment"), - PHONENUMBERS_NUMBERS("phonenumbers-numbers"), - PROG_VOICE_CLIENT_ANDROID("prog-voice-client-android"), - PROG_VOICE_CLIENT_ANDROID_INBOUND("prog-voice-client-android-inbound"), - PROG_VOICE_CLIENT_ANDROID_OUTBOUND( - "prog-voice-client-android-outbound" - ), - PROG_VOICE_CLIENT_IOS("prog-voice-client-ios"), - PROG_VOICE_CLIENT_IOS_INBOUND("prog-voice-client-ios-inbound"), - PROG_VOICE_CLIENT_IOS_OUTBOUND("prog-voice-client-ios-outbound"), - PROG_VOICE_CLIENT_SDK("prog-voice-client-sdk"), - PROG_VOICE_CLIENT_WEB("prog-voice-client-web"), - PROG_VOICE_CLIENT_WEB_INBOUND("prog-voice-client-web-inbound"), - PROG_VOICE_CLIENT_WEB_OUTBOUND("prog-voice-client-web-outbound"), - PROGRAMMABLEVOICECONNECTIVITY_MEDIA_STREAMS( - "programmablevoiceconnectivity-media-streams" - ), - PSTNCONNECTIVITY_BYOC("pstnconnectivity-byoc"), - PSTNCONNECTIVITY_EMERGENCY("pstnconnectivity-emergency"), - PSTNCONNECTIVITY_MINUTES("pstnconnectivity-minutes"), - PSTNCONNECTIVITY_MINUTES_1("pstnconnectivity-minutes-1"), - PSTNCONNECTIVITY_MINUTESINBOUNDLOCAL( - "pstnconnectivity-minutesinboundlocal" - ), - PSTNCONNECTIVITY_MINUTESINBOUNDMOBILE( - "pstnconnectivity-minutesinboundmobile" - ), - PSTNCONNECTIVITY_MINUTESINBOUNDTOLLFREE( - "pstnconnectivity-minutesinboundtollfree" - ), - PSTNCONNECTIVITY_MINUTESINBOUNDTOLLFREELOCAL( - "pstnconnectivity-minutesinboundtollfreelocal" - ), - PSTNCONNECTIVITY_MINUTESINBOUNDTOLLFREEMOBILE( - "pstnconnectivity-minutesinboundtollfreemobile" - ), - PV_ROOM_HOURS("pv-room-hours"), - PV_ROOM_SIMULTANEOUS_PARTICIPANT_CONNECTIONS( - "pv-room-simultaneous-participant-connections" - ), - PVIDEO_ROOM_HOURS_AU1("pvideo-room-hours-au1"), - PVIDEO_ROOM_HOURS_BR1("pvideo-room-hours-br1"), - PVIDEO_ROOM_HOURS_IE1("pvideo-room-hours-ie1"), - PVIDEO_ROOM_HOURS_JP1("pvideo-room-hours-jp1"), - PVIDEO_ROOM_HOURS_SG1("pvideo-room-hours-sg1"), - PVIDEO_ROOM_HOURS_US1("pvideo-room-hours-us1"), - PVIDEO_ROOM_HOURS_US2("pvideo-room-hours-us2"), - RECORDINGS_ENCRYPTED("recordings-encrypted"), - SHORT_CODE_SETUP_FEES("short-code-setup-fees"), - SHORTCODES_MESSAGES_INBOUND("shortcodes-messages-inbound"), - SHORTCODES_MESSAGES_OUTBOUND("shortcodes-messages-outbound"), - SMS_MESSAGES_REGISTRATIONFEES("sms-messages-registrationfees"), - SMS_MMS_PENALTY_FEES("sms-mms-penalty-fees"), - SMS_MMS_PENALTY_FEES_1("sms-mms-penalty-fees-1"), - SMS_PUMPING_PROTECTION_NON_USCA("sms-pumping-protection-non-usca"), - SMS_PUMPING_PROTECTION_USCA("sms-pumping-protection-usca"), - STUDIO("studio"), - STUDIO_MONTHLY_FEES("studio-monthly-fees"), - SUPERSIM("supersim"), - TASK_ROUTER("task-router"), - TASK_ROUTER_WORKERS("task-router-workers"), - TEST_QUOTA_BUCKETS("test-quota-buckets"), - TEST_UC_SCRIPT_1("test-uc-script-1"), - TEST_UC_SCRIPT_DEMO_2("test-uc-script-demo-2"), - TEXT_TO_SPEECH("text-to-speech"), - TME("tme"), - TTS_BASIC("tts-basic"), - TWILIO_EDITIONS("twilio-editions"), - TWILIO_INTERCONNECT_CALIFORNIA("twilio-interconnect-california"), - TWILIO_INTERCONNECT_CALIFORNIA_MONTHLY( - "twilio-interconnect-california-monthly" - ), - TWILIO_INTERCONNECT_CALIFORNIA_SETUP( - "twilio-interconnect-california-setup" - ), - TWILIO_INTERCONNECT_FRANKFURT("twilio-interconnect-frankfurt"), - TWILIO_INTERCONNECT_FRANKFURT_MO("twilio-interconnect-frankfurt-mo"), - TWILIO_INTERCONNECT_FRANKFURT_SETUP( - "twilio-interconnect-frankfurt-setup" - ), - TWILIO_INTERCONNECT_LONDON("twilio-interconnect-london"), - TWILIO_INTERCONNECT_LONDON_MO("twilio-interconnect-london-mo"), - TWILIO_INTERCONNECT_LONDON_SETUP("twilio-interconnect-london-setup"), - TWILIO_INTERCONNECT_SAO_PAULO("twilio-interconnect-sao-paulo"), - TWILIO_INTERCONNECT_SAO_PAULO_MONTHLY( - "twilio-interconnect-sao-paulo-monthly" - ), - TWILIO_INTERCONNECT_SAO_PAULO_SETUP( - "twilio-interconnect-sao-paulo-setup" - ), - TWILIO_INTERCONNECT_SINGAPORE("twilio-interconnect-singapore"), - TWILIO_INTERCONNECT_SINGAPORE_MO("twilio-interconnect-singapore-mo"), - TWILIO_INTERCONNECT_SINGAPORE_SETUP( - "twilio-interconnect-singapore-setup" - ), - TWILIO_INTERCONNECT_SYDNEY("twilio-interconnect-sydney"), - TWILIO_INTERCONNECT_SYDNEY_MO("twilio-interconnect-sydney-mo"), - TWILIO_INTERCONNECT_SYDNEY_SETUP("twilio-interconnect-sydney-setup"), - TWILIO_INTERCONNECT_TOKYO("twilio-interconnect-tokyo"), - TWILIO_INTERCONNECT_TOKYO_MO("twilio-interconnect-tokyo-mo"), - TWILIO_INTERCONNECT_TOKYO_SETUP("twilio-interconnect-tokyo-setup"), - TWILIO_INTERCONNECT_VA("twilio-interconnect-va"), - TWILIO_INTERCONNECT_VA_MO("twilio-interconnect-va-mo"), - TWILIO_INTERCONNECT_VA_SETUP("twilio-interconnect-va-setup"), - TWIML_VERBS("twiml-verbs"), - TWIML_VERBS_SAY("twiml-verbs-say"), - USAGE_PROGRAMMABLE_MESSAGING_ENGAGEMENT_SUITE( - "usage-programmable-messaging-engagement-suite" - ), - USAGE_PROGRAMMABLE_MESSAGING_FEES_SERVICES( - "usage-programmable-messaging-fees-services" - ), - VERIFY_OUTBOUND_EMAIL("verify-outbound-email"), - VERIFY_PACKAGED_PLANS("verify-packaged-plans"), - VERIFY_SILENT_NETWORK_AUTH("verify-silent-network-auth"), - VERIFY_VOICE_AND_SMS("verify-voice-and-sms"), - VOICE_INSIGHTS_CLIENT_INSIGHTS_MONTHY_COMMIT( - "voice-insights-client-insights-monthy-commit" - ), - WIRELESS_DATA_PAYG_ASIA_AFG("wireless-data-payg-asia-afg"), - WIRELESS_MULTI_IMSI_SIM_COMMANDS("wireless-multi-imsi-sim-commands"), - WIRELESS_MULTI_IMSI_SIM_COMMANDS_USA( - "wireless-multi-imsi-sim-commands-usa" - ), - WIRELESS_MULTI_IMSI_SIM_DATA("wireless-multi-imsi-sim-data"), - WIRELESS_MULTI_IMSI_SIM_DATA_EU28("wireless-multi-imsi-sim-data-eu28"), - WIRELESS_MULTI_IMSI_SIM_DATA_USA("wireless-multi-imsi-sim-data-usa"), - WIRELESS_MULTI_IMSI_SIM_MONTHLY_FEES( - "wireless-multi-imsi-sim-monthly-fees" - ), - WIRELESS_MULTI_IMSI_SIM_USAGE("wireless-multi-imsi-sim-usage"), - WIRELESS_SUPER_SIM_DATA_NORTH_AMERICA( - "wireless-super-sim-data-north-america" - ), - WIRELESS_SUPER_SIM_USAGE("wireless-super-sim-usage"); - - private final String value; - - private Category(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static Category forValue(final String value) { - return Promoter.enumFromString(value, Category.values()); - } - } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/usage/record/MonthlyReader.java b/src/main/java/com/twilio/rest/api/v2010/account/usage/record/MonthlyReader.java index 45ed86e749..a6e596d267 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/usage/record/MonthlyReader.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/usage/record/MonthlyReader.java @@ -32,7 +32,7 @@ public class MonthlyReader extends Reader { private String pathAccountSid; - private Monthly.Category category; + private String category; private LocalDate startDate; private LocalDate endDate; private Boolean includeSubaccounts; @@ -44,7 +44,7 @@ public MonthlyReader(final String pathAccountSid) { this.pathAccountSid = pathAccountSid; } - public MonthlyReader setCategory(final Monthly.Category category) { + public MonthlyReader setCategory(final String category) { this.category = category; return this; } @@ -168,7 +168,7 @@ public Page getPage( private void addQueryParams(final Request request) { if (category != null) { - request.addQueryParam("Category", category.toString()); + request.addQueryParam("Category", category); } if (startDate != null) { request.addQueryParam( diff --git a/src/main/java/com/twilio/rest/api/v2010/account/usage/record/ThisMonth.java b/src/main/java/com/twilio/rest/api/v2010/account/usage/record/ThisMonth.java index 8bcd8c6d99..ebd25dee79 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/usage/record/ThisMonth.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/usage/record/ThisMonth.java @@ -24,7 +24,6 @@ import com.twilio.base.Resource; import com.twilio.converter.CurrencyDeserializer; import com.twilio.converter.DateConverter; -import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import java.io.IOException; @@ -42,7 +41,7 @@ @ToString public class ThisMonth extends Resource { - private static final long serialVersionUID = 273687321693897L; + private static final long serialVersionUID = 158026917970511L; public static ThisMonthReader reader() { return new ThisMonthReader(); @@ -98,7 +97,7 @@ public static ThisMonth fromJson( private final String accountSid; private final String apiVersion; private final String asOf; - private final ThisMonth.Category category; + private final String category; private final String count; private final String countUnit; private final String description; @@ -116,7 +115,7 @@ private ThisMonth( @JsonProperty("account_sid") final String accountSid, @JsonProperty("api_version") final String apiVersion, @JsonProperty("as_of") final String asOf, - @JsonProperty("category") final ThisMonth.Category category, + @JsonProperty("category") final String category, @JsonProperty("count") final String count, @JsonProperty("count_unit") final String countUnit, @JsonProperty("description") final String description, @@ -163,7 +162,7 @@ public final String getAsOf() { return this.asOf; } - public final ThisMonth.Category getCategory() { + public final String getCategory() { return this.category; } @@ -262,945 +261,4 @@ public int hashCode() { usageUnit ); } - - public enum Category { - A2P_10DLC_REGISTRATIONFEES_BRANDREGISTRATION( - "a2p-10dlc-registrationfees-brandregistration" - ), - A2P_10DLC_REGISTRATIONFEES_BV("a2p-10dlc-registrationfees-bv"), - A2P_10DLC_REGISTRATIONFEES_CAMPAIGNCHARGES( - "a2p-10dlc-registrationfees-campaigncharges" - ), - A2P_10DLC_REGISTRATIONFEES_CAMPAIGNREGISTRATION( - "a2p-10dlc-registrationfees-campaignregistration" - ), - A2P_10DLC_REGISTRATIONFEES_CAMPAIGNVETTING( - "a2p-10dlc-registrationfees-campaignvetting" - ), - A2P_10DLC_REGISTRATIONFEES_MONTHLY( - "a2p-10dlc-registrationfees-monthly" - ), - A2P_10DLC_REGISTRATIONFEES_ONETIME( - "a2p-10dlc-registrationfees-onetime" - ), - A2P_REGISTRATION_FEES("a2p-registration-fees"), - ACCOUNT_SECURITY("account-security"), - AGENT_CONFERENCE("agent-conference"), - AGENT_COPILOT("agent-copilot"), - AGENT_COPILOT_MESSAGES("agent-copilot-messages"), - AGENT_COPILOT_PARTICIPANT_MINUTES("agent-copilot-participant-minutes"), - AI_ASSISTANTS("ai-assistants"), - AI_ASSISTANTS_VOICE("ai-assistants-voice"), - AMAZON_POLLY("amazon-polly"), - ANSWERING_MACHINE_DETECTION("answering-machine-detection"), - ASSETS("assets"), - AUDIENCE_MINUTES("audience-minutes"), - AUDIENCE_MINUTES_AUDIO("audience-minutes-audio"), - AUTHY_AUTHENTICATIONS("authy-authentications"), - AUTHY_CALLS_OUTBOUND("authy-calls-outbound"), - AUTHY_EMAIL_AUTHENTICATIONS("authy-email-authentications"), - AUTHY_MONTHLY_FEES("authy-monthly-fees"), - AUTHY_OUTBOUND_EMAIL("authy-outbound-email"), - AUTHY_PHONE_INTELLIGENCE("authy-phone-intelligence"), - AUTHY_PHONE_VERIFICATIONS("authy-phone-verifications"), - AUTHY_SMS_OUTBOUND("authy-sms-outbound"), - AUTHY_VERIFY_EMAIL_VERIFICATIONS("authy-verify-email-verifications"), - AUTHY_VERIFY_OUTBOUND_EMAIL("authy-verify-outbound-email"), - AUTOPILOT("autopilot"), - AUTOPILOT_HOME_ASSISTANTS("autopilot-home-assistants"), - AUTOPILOT_MESSAGING("autopilot-messaging"), - AUTOPILOT_OTHER("autopilot-other"), - AUTOPILOT_VOICE("autopilot-voice"), - BASIC_PEER_TO_PEER_ROOMS_PARTICIPANT_MINUTES( - "basic-peer-to-peer-rooms-participant-minutes" - ), - BRANDED_CALLING("branded-calling"), - BUNDLE_SMS_BUCKET("bundle-sms-bucket"), - BUNDLE_SUBSCRIPTION_FEES("bundle-subscription-fees"), - CALL_FORWARDING_LOOKUPS("call-forwarding-lookups"), - CALL_PROGESS_EVENTS("call-progess-events"), - CALLERIDLOOKUPS("calleridlookups"), - CALLS("calls"), - CALLS_CLIENT("calls-client"), - CALLS_EMERGENCY("calls-emergency"), - CALLS_GLOBALCONFERENCE("calls-globalconference"), - CALLS_INBOUND("calls-inbound"), - CALLS_INBOUND_LOCAL("calls-inbound-local"), - CALLS_INBOUND_MOBILE("calls-inbound-mobile"), - CALLS_INBOUND_TOLLFREE("calls-inbound-tollfree"), - CALLS_INBOUND_TOLLFREE_LOCAL("calls-inbound-tollfree-local"), - CALLS_INBOUND_TOLLFREE_MOBILE("calls-inbound-tollfree-mobile"), - CALLS_MEDIA_STREAM_MINUTES("calls-media-stream-minutes"), - CALLS_OUTBOUND("calls-outbound"), - CALLS_PAY_VERB_TRANSACTIONS("calls-pay-verb-transactions"), - CALLS_RECORDINGS("calls-recordings"), - CALLS_SIP("calls-sip"), - CALLS_SIP_INBOUND("calls-sip-inbound"), - CALLS_SIP_OUTBOUND("calls-sip-outbound"), - CALLS_TEXT_TO_SPEECH("calls-text-to-speech"), - CALLS_TRANSFERS("calls-transfers"), - CARRIER_LOOKUPS("carrier-lookups"), - CATEGORY("category"), - CHANNELS("channels"), - CHANNELS_MESSAGING("channels-messaging"), - CHANNELS_MESSAGING_INBOUND("channels-messaging-inbound"), - CHANNELS_MESSAGING_OUTBOUND("channels-messaging-outbound"), - CHANNELS_WHATSAPP("channels-whatsapp"), - CHANNELS_WHATSAPP_CONVERSATION_AUTHENTICATION( - "channels-whatsapp-conversation-authentication" - ), - CHANNELS_WHATSAPP_CONVERSATION_FREE( - "channels-whatsapp-conversation-free" - ), - CHANNELS_WHATSAPP_CONVERSATION_MARKETING( - "channels-whatsapp-conversation-marketing" - ), - CHANNELS_WHATSAPP_CONVERSATION_SERVICE( - "channels-whatsapp-conversation-service" - ), - CHANNELS_WHATSAPP_CONVERSATION_UTILITY( - "channels-whatsapp-conversation-utility" - ), - CHANNELS_WHATSAPP_INBOUND("channels-whatsapp-inbound"), - CHANNELS_WHATSAPP_OUTBOUND("channels-whatsapp-outbound"), - CHANNELS_WHATSAPP_SERVICE("channels-whatsapp-service"), - CHANNELS_WHATSAPP_TEMPLATE_AUTHENTICATION( - "channels-whatsapp-template-authentication" - ), - CHANNELS_WHATSAPP_TEMPLATE_MARKETING( - "channels-whatsapp-template-marketing" - ), - CHANNELS_WHATSAPP_TEMPLATE_SERVICE( - "channels-whatsapp-template-service" - ), - CHANNELS_WHATSAPP_TEMPLATE_UTILITY( - "channels-whatsapp-template-utility" - ), - CHAT_VIRTUAL_AGENT("chat-virtual-agent"), - CONVERSATION_RELAY("conversation-relay"), - CONVERSATIONS("conversations"), - CONVERSATIONS_API_REQUESTS("conversations-api-requests"), - CONVERSATIONS_CONVERSATION_EVENTS("conversations-conversation-events"), - CONVERSATIONS_ENDPOINT_CONNECTIVITY( - "conversations-endpoint-connectivity" - ), - CONVERSATIONS_EVENTS("conversations-events"), - CONVERSATIONS_PARTICIPANT_EVENTS("conversations-participant-events"), - CONVERSATIONS_PARTICIPANTS("conversations-participants"), - CPS("cps"), - CREDIT_TRANSFER("credit-transfer"), - EMAIL("email"), - EMERGING_TECH("emerging-tech"), - ENGAGEMENT_SUITE_PACKAGED_PLANS("engagement-suite-packaged-plans"), - ENHANCED_LINE_TYPE_LOOKUPS("enhanced-line-type-lookups"), - ENTERPRISE("enterprise"), - EVENTS("events"), - EXPERIMENT_FRANCE_SMS("experiment-france-sms"), - EXPERIMENT_INDIA_SMS("experiment-india-sms"), - EXPERIMENT_UK_SMS("experiment-uk-sms"), - FAILED_MESSAGE_PROCESSING_FEE("failed-message-processing-fee"), - FLEX("flex"), - FLEX_ACTIVE_USER_HOURS("flex-active-user-hours"), - FLEX_CONCURRENT_USERS("flex-concurrent-users"), - FLEX_CONVERSATIONAL_INSIGHTS("flex-conversational-insights"), - FLEX_CONVERSATIONAL_INSIGHTS_MESSAGES( - "flex-conversational-insights-messages" - ), - FLEX_CONVERSATIONAL_INSIGHTS_VOICE_MINUTES( - "flex-conversational-insights-voice-minutes" - ), - FLEX_EMAIL_USAGE("flex-email-usage"), - FLEX_MESSAGING_USAGE("flex-messaging-usage"), - FLEX_PARTNER_SPINSCI("flex-partner-spinsci"), - FLEX_PARTNER_XCELERATE("flex-partner-xcelerate"), - FLEX_RESELLER_ECOSYSTEM("flex-reseller-ecosystem"), - FLEX_UNIQUE_USER("flex-unique-user"), - FLEX_USAGE("flex-usage"), - FLEX_USERS("flex-users"), - FLEX_VOICE_MINUTE("flex-voice-minute"), - FLEX_YTICA("flex-ytica"), - FRAUD_LOOKUPS("fraud-lookups"), - FRONTLINE("frontline"), - FRONTLINE_USERS("frontline-users"), - FUNCTIONS("functions"), - GENERIC_PAY_TRANSACTIONS("generic-pay-transactions"), - GROUP_ROOMS("group-rooms"), - GROUP_ROOMS_DATA_TRACK("group-rooms-data-track"), - GROUP_ROOMS_ENCRYPTED_MEDIA_RECORDED( - "group-rooms-encrypted-media-recorded" - ), - GROUP_ROOMS_MEDIA_DOWNLOADED("group-rooms-media-downloaded"), - GROUP_ROOMS_MEDIA_RECORDED("group-rooms-media-recorded"), - GROUP_ROOMS_MEDIA_ROUTED("group-rooms-media-routed"), - GROUP_ROOMS_MEDIA_STORED("group-rooms-media-stored"), - GROUP_ROOMS_PARTICIPANT_MINUTES("group-rooms-participant-minutes"), - GROUP_ROOMS_RECORDED_MINUTES("group-rooms-recorded-minutes"), - IP_MESSAGING("ip-messaging"), - IP_MESSAGING_COMMANDS("ip-messaging-commands"), - IP_MESSAGING_DATA_STORAGE("ip-messaging-data-storage"), - IP_MESSAGING_DATA_TRANSFER("ip-messaging-data-transfer"), - IP_MESSAGING_ENDPOINT_CONNECTIVITY( - "ip-messaging-endpoint-connectivity" - ), - IVR_VIRTUAL_AGENT_CUSTOM_VOICES("ivr-virtual-agent-custom-voices"), - IVR_VIRTUAL_AGENT_GENAI("ivr-virtual-agent-genai"), - LINE_STATUS_LOOKUPS("line-status-lookups"), - LIVE_ACTIVITY_LOOKUPS("live-activity-lookups"), - LOOKUP_BUCKET_ADJUSTMENT("lookup-bucket-adjustment"), - LOOKUP_IDENTITY_MATCH("lookup-identity-match"), - LOOKUPS("lookups"), - MARKETPLACE("marketplace"), - MARKETPLACE_ALGORITHMIA_NAMED_ENTITY_RECOGNITION( - "marketplace-algorithmia-named-entity-recognition" - ), - MARKETPLACE_CADENCE_TRANSCRIPTION("marketplace-cadence-transcription"), - MARKETPLACE_CADENCE_TRANSLATION("marketplace-cadence-translation"), - MARKETPLACE_CAPIO_SPEECH_TO_TEXT("marketplace-capio-speech-to-text"), - MARKETPLACE_CONVRIZA_ABABA("marketplace-convriza-ababa"), - MARKETPLACE_DEEPGRAM_PHRASE_DETECTOR( - "marketplace-deepgram-phrase-detector" - ), - MARKETPLACE_DEEPGRAM_TRANSCRIPTION( - "marketplace-deepgram-transcription" - ), - MARKETPLACE_DEEPGRAM_TRANSCRIPTION_BASE( - "marketplace-deepgram-transcription-base" - ), - MARKETPLACE_DEEPGRAM_TRANSSCRIPTION_ENHANCED( - "marketplace-deepgram-transscription-enhanced" - ), - MARKETPLACE_DIGITAL_SEGMENT_BUSINESS_INFO( - "marketplace-digital-segment-business-info" - ), - MARKETPLACE_FACEBOOK_OFFLINE_CONVERSIONS( - "marketplace-facebook-offline-conversions" - ), - MARKETPLACE_GOOGLE_SPEECH_TO_TEXT("marketplace-google-speech-to-text"), - MARKETPLACE_IBM_WATSON_MESSAGE_INSIGHTS( - "marketplace-ibm-watson-message-insights" - ), - MARKETPLACE_IBM_WATSON_MESSAGE_SENTIMENT( - "marketplace-ibm-watson-message-sentiment" - ), - MARKETPLACE_IBM_WATSON_RECORDING_ANALYSIS( - "marketplace-ibm-watson-recording-analysis" - ), - MARKETPLACE_IBM_WATSON_TONE_ANALYZER( - "marketplace-ibm-watson-tone-analyzer" - ), - MARKETPLACE_ICEHOOK_SYSTEMS_SCOUT("marketplace-icehook-systems-scout"), - MARKETPLACE_INFOGROUP_DATAAXLE_BIZINFO( - "marketplace-infogroup-dataaxle-bizinfo" - ), - MARKETPLACE_KEEN_IO_CONTACT_CENTER_ANALYTICS( - "marketplace-keen-io-contact-center-analytics" - ), - MARKETPLACE_MARCHEX_CLEANCALL("marketplace-marchex-cleancall"), - MARKETPLACE_MARCHEX_RECORDING_ANALYSIS( - "marketplace-marchex-recording-analysis" - ), - MARKETPLACE_MARCHEX_SENTIMENT_ANALYSIS_FOR_SMS( - "marketplace-marchex-sentiment-analysis-for-sms" - ), - MARKETPLACE_MARKETPLACE_NEXTCALLER_SOCIAL_ID( - "marketplace-marketplace-nextcaller-social-id" - ), - MARKETPLACE_MOBILE_COMMONS_OPT_OUT_CLASSIFIER( - "marketplace-mobile-commons-opt-out-classifier" - ), - MARKETPLACE_NEXIWAVE_VOICEMAIL_TO_TEXT( - "marketplace-nexiwave-voicemail-to-text" - ), - MARKETPLACE_NEXTCALLER_ADVANCED_CALLER_IDENTIFICATION( - "marketplace-nextcaller-advanced-caller-identification" - ), - MARKETPLACE_NOMOROBO_SPAM_SCORE("marketplace-nomorobo-spam-score"), - MARKETPLACE_PAY_ADDONS("marketplace-pay-addons"), - MARKETPLACE_PAY_ADDONS_BASECOMMERCE_PAY_CONNECTOR( - "marketplace-pay-addons-basecommerce-pay-connector" - ), - MARKETPLACE_PAY_ADDONS_BRAINTREE_PAY_CONNECTOR( - "marketplace-pay-addons-braintree-pay-connector" - ), - MARKETPLACE_PAY_ADDONS_CARDCONNECT_PAY_CONNECTOR( - "marketplace-pay-addons-cardconnect-pay-connector" - ), - MARKETPLACE_PAY_ADDONS_CHASE_PAY_CONNECTOR( - "marketplace-pay-addons-chase-pay-connector" - ), - MARKETPLACE_PAY_ADDONS_SHUTTLE_PAY_CONNECTOR( - "marketplace-pay-addons-shuttle-pay-connector" - ), - MARKETPLACE_PAY_ADDONS_STRIPE_PAY_CONNECTOR( - "marketplace-pay-addons-stripe-pay-connector" - ), - MARKETPLACE_PAYFONE_TCPA_COMPLIANCE( - "marketplace-payfone-tcpa-compliance" - ), - MARKETPLACE_POLY_AI_CONNECTOR("marketplace-poly-ai-connector"), - MARKETPLACE_REALPHONEVALIDATION("marketplace-realphonevalidation"), - MARKETPLACE_REMEETING_AUTOMATIC_SPEECH_RECOGNITION( - "marketplace-remeeting-automatic-speech-recognition" - ), - MARKETPLACE_SPOKE_PHONE_LICENSE_PRO( - "marketplace-spoke-phone-license-pro" - ), - MARKETPLACE_SPOKE_PHONE_LICENSE_STANDARD( - "marketplace-spoke-phone-license-standard" - ), - MARKETPLACE_TCPA_DEFENSE_SOLUTIONS_BLACKLIST_FEED( - "marketplace-tcpa-defense-solutions-blacklist-feed" - ), - MARKETPLACE_TELO_OPENCNAM("marketplace-telo-opencnam"), - MARKETPLACE_TRESTLE_SOLUTIONS_CALLER_IDENTIFICATION( - "marketplace-trestle-solutions-caller-identification" - ), - MARKETPLACE_TRUECNAM_TRUE_SPAM("marketplace-truecnam-true-spam"), - MARKETPLACE_TWILIO_CALLER_NAME_LOOKUP_US( - "marketplace-twilio-caller-name-lookup-us" - ), - MARKETPLACE_TWILIO_CARRIER_INFORMATION_LOOKUP( - "marketplace-twilio-carrier-information-lookup" - ), - MARKETPLACE_VOICEBASE_PCI("marketplace-voicebase-pci"), - MARKETPLACE_VOICEBASE_TRANSCRIPTION( - "marketplace-voicebase-transcription" - ), - MARKETPLACE_VOICEBASE_TRANSCRIPTION_CUSTOM_VOCABULARY( - "marketplace-voicebase-transcription-custom-vocabulary" - ), - MARKETPLACE_WEB_PURIFY_PROFANITY_FILTER( - "marketplace-web-purify-profanity-filter" - ), - MARKETPLACE_WHITEPAGES_PRO_CALLER_IDENTIFICATION( - "marketplace-whitepages-pro-caller-identification" - ), - MARKETPLACE_WHITEPAGES_PRO_PHONE_INTELLIGENCE( - "marketplace-whitepages-pro-phone-intelligence" - ), - MARKETPLACE_WHITEPAGES_PRO_PHONE_REPUTATION( - "marketplace-whitepages-pro-phone-reputation" - ), - MARKETPLACE_WOLFARM_SPOKEN_RESULTS( - "marketplace-wolfarm-spoken-results" - ), - MARKETPLACE_WOLFRAM_SHORT_ANSWER("marketplace-wolfram-short-answer"), - MARKETPLACE_YTICA_CONTACT_CENTER_REPORTING_ANALYTICS( - "marketplace-ytica-contact-center-reporting-analytics" - ), - MARKETPLAY_PAY_ADDONS_SHUTTLE_PAY_CONNECTOR( - "marketplay-pay-addons-shuttle-pay-connector" - ), - MEDIA_COMPOSER_MINUTES("media-composer-minutes"), - MEDIASTORAGE("mediastorage"), - MIN_SPEND_ADJUSTMENTS("min-spend-adjustments"), - MMS("mms"), - MMS_INBOUND("mms-inbound"), - MMS_INBOUND_LONGCODE("mms-inbound-longcode"), - MMS_INBOUND_SHORTCODE("mms-inbound-shortcode"), - MMS_INBOUND_TOLL_FREE("mms-inbound-toll-free"), - MMS_MESSAGES_CARRIERFEES("mms-messages-carrierfees"), - MMS_OUTBOUND("mms-outbound"), - MMS_OUTBOUND_LONGCODE("mms-outbound-longcode"), - MMS_OUTBOUND_SHORTCODE("mms-outbound-shortcode"), - MMS_OUTBOUND_TOLLFREE("mms-outbound-tollfree"), - MONITOR("monitor"), - MONITOR_READS("monitor-reads"), - MONITOR_STORAGE("monitor-storage"), - MONITOR_WRITES("monitor-writes"), - NOTIFY("notify"), - NOTIFY_ACTIONS_ATTEMPTS("notify-actions-attempts"), - NOTIFY_CHANNELS("notify-channels"), - NUMBER_FORMAT_LOOKUPS("number-format-lookups"), - PCHAT("pchat"), - PCHAT_ACTIONS("pchat-actions"), - PCHAT_APS("pchat-aps"), - PCHAT_CONV_MED_STORAGE("pchat-conv-med-storage"), - PCHAT_MESSAGES("pchat-messages"), - PCHAT_NOTIFICATIONS("pchat-notifications"), - PCHAT_READS("pchat-reads"), - PCHAT_USERS("pchat-users"), - PEER_TO_PEER_ROOMS_PARTICIPANT_MINUTES( - "peer-to-peer-rooms-participant-minutes" - ), - PFAX("pfax"), - PFAX_MINUTES("pfax-minutes"), - PFAX_MINUTES_INBOUND("pfax-minutes-inbound"), - PFAX_MINUTES_OUTBOUND("pfax-minutes-outbound"), - PFAX_PAGES("pfax-pages"), - PHONE_QUALITY_SCORE_LOOKUPS("phone-quality-score-lookups"), - PHONENUMBERS("phonenumbers"), - PHONENUMBERS_CPS("phonenumbers-cps"), - PHONENUMBERS_EMERGENCY("phonenumbers-emergency"), - PHONENUMBERS_LOCAL("phonenumbers-local"), - PHONENUMBERS_MOBILE("phonenumbers-mobile"), - PHONENUMBERS_PORTING("phonenumbers-porting"), - PHONENUMBERS_SETUPS("phonenumbers-setups"), - PHONENUMBERS_TOLLFREE("phonenumbers-tollfree"), - PREMIUMSUPPORT("premiumsupport"), - PREMIUMSUPPORT_PERCENTAGE_SPEND("premiumsupport-percentage-spend"), - PROGRAMMABLEVOICE_PLATFORM("programmablevoice-platform"), - PROGRAMMABLEVOICECONN_CLIENTSDK("programmablevoiceconn-clientsdk"), - PROGRAMMABLEVOICECONN_CLIENTSDK_INBOUND( - "programmablevoiceconn-clientsdk-inbound" - ), - PROGRAMMABLEVOICECONN_CLIENTSDK_OUTBOUND( - "programmablevoiceconn-clientsdk-outbound" - ), - PROGRAMMABLEVOICECONN_ONNET("programmablevoiceconn-onnet"), - PROGRAMMABLEVOICECONN_ONNET_INBOUND( - "programmablevoiceconn-onnet-inbound" - ), - PROGRAMMABLEVOICECONN_ONNET_OUTBOUND( - "programmablevoiceconn-onnet-outbound" - ), - PROGRAMMABLEVOICECONN_SIP("programmablevoiceconn-sip"), - PROGRAMMABLEVOICECONN_SIP_INBOUND("programmablevoiceconn-sip-inbound"), - PROGRAMMABLEVOICECONN_SIP_OUTBOUND( - "programmablevoiceconn-sip-outbound" - ), - PROGRAMMABLEVOICECONNECTIVITY("programmablevoiceconnectivity"), - PROXY("proxy"), - PROXY_ACTIVE_SESSIONS("proxy-active-sessions"), - PROXY_BUCKET_ADJUSTMENT("proxy-bucket-adjustment"), - PROXY_LICENSES("proxy-licenses"), - PSTNCONNECTIVITY("pstnconnectivity"), - PSTNCONNECTIVITY_INBOUND("pstnconnectivity-inbound"), - PSTNCONNECTIVITY_OUTBOUND("pstnconnectivity-outbound"), - PV("pv"), - PV_BASIC_ROOMS("pv-basic-rooms"), - PV_COMPOSITION_MEDIA_DOWNLOADED("pv-composition-media-downloaded"), - PV_COMPOSITION_MEDIA_ENCRYPTED("pv-composition-media-encrypted"), - PV_COMPOSITION_MEDIA_STORED("pv-composition-media-stored"), - PV_COMPOSITION_MINUTES("pv-composition-minutes"), - PV_RECORDING_COMPOSITIONS("pv-recording-compositions"), - PV_ROOM_PARTICIPANTS("pv-room-participants"), - PV_ROOM_PARTICIPANTS_AU1("pv-room-participants-au1"), - PV_ROOM_PARTICIPANTS_BR1("pv-room-participants-br1"), - PV_ROOM_PARTICIPANTS_IE1("pv-room-participants-ie1"), - PV_ROOM_PARTICIPANTS_JP1("pv-room-participants-jp1"), - PV_ROOM_PARTICIPANTS_SG1("pv-room-participants-sg1"), - PV_ROOM_PARTICIPANTS_US1("pv-room-participants-us1"), - PV_ROOM_PARTICIPANTS_US2("pv-room-participants-us2"), - PV_ROOMS("pv-rooms"), - PV_SIP_ENDPOINT_REGISTRATIONS("pv-sip-endpoint-registrations"), - RCS_MESSAGES("rcs-messages"), - REASSIGNED_NUMBER("reassigned-number"), - RECORDINGS("recordings"), - RECORDINGSTORAGE("recordingstorage"), - SHORTCODES("shortcodes"), - SHORTCODES_CUSTOMEROWNED("shortcodes-customerowned"), - SHORTCODES_MMS_ENABLEMENT("shortcodes-mms-enablement"), - SHORTCODES_MPS("shortcodes-mps"), - SHORTCODES_RANDOM("shortcodes-random"), - SHORTCODES_SETUP_FEES("shortcodes-setup-fees"), - SHORTCODES_UK("shortcodes-uk"), - SHORTCODES_VANITY("shortcodes-vanity"), - SIM_SWAP_LOOKUPS("sim-swap-lookups"), - SIP_SECURE_MEDIA("sip-secure-media"), - SMALL_GROUP_ROOMS("small-group-rooms"), - SMALL_GROUP_ROOMS_DATA_TRACK("small-group-rooms-data-track"), - SMALL_GROUP_ROOMS_PARTICIPANT_MINUTES( - "small-group-rooms-participant-minutes" - ), - SMS("sms"), - SMS_INBOUND("sms-inbound"), - SMS_INBOUND_LONGCODE("sms-inbound-longcode"), - SMS_INBOUND_SHORTCODE("sms-inbound-shortcode"), - SMS_INBOUND_TOLLFREE("sms-inbound-tollfree"), - SMS_MESSAGES_CARRIERFEES("sms-messages-carrierfees"), - SMS_MESSAGES_FEATURES("sms-messages-features"), - SMS_MESSAGES_FEATURES_ENGAGEMENT_SUITE( - "sms-messages-features-engagement-suite" - ), - SMS_MESSAGES_FEATURES_MESSAGE_REDACTION( - "sms-messages-features-message-redaction" - ), - SMS_MESSAGES_FEATURES_SENDERID("sms-messages-features-senderid"), - SMS_MPS("sms-mps"), - SMS_MPS_SHORTCODE("sms-mps-shortcode"), - SMS_MPS_TOLLFREE("sms-mps-tollfree"), - SMS_MPS_TOLLFREE_SETUP("sms-mps-tollfree-setup"), - SMS_NATIONAL_REGULATORY_PROTECTION( - "sms-national-regulatory-protection" - ), - SMS_OUTBOUND("sms-outbound"), - SMS_OUTBOUND_CONTENT_INSPECTION("sms-outbound-content-inspection"), - SMS_OUTBOUND_LONGCODE("sms-outbound-longcode"), - SMS_OUTBOUND_SHORTCODE("sms-outbound-shortcode"), - SMS_OUTBOUND_TOLLFREE("sms-outbound-tollfree"), - SMS_PUMPING_PROTECTION("sms-pumping-protection"), - SMS_PUMPING_RISK("sms-pumping-risk"), - SMSMESSAGES_BUCKET_ADJUSTMENTS("smsmessages-bucket-adjustments"), - SMSMESSAGES_OUTBOUND_DOMESTIC("smsmessages-outbound-domestic"), - SPEECH_RECOGNITION("speech-recognition"), - STUDIO_ENGAGEMENTS("studio-engagements"), - SYNC("sync"), - SYNC_ACTIONS("sync-actions"), - SYNC_ENDPOINT_HOURS("sync-endpoint-hours"), - SYNC_ENDPOINT_HOURS_ABOVE_DAILY_CAP( - "sync-endpoint-hours-above-daily-cap" - ), - TASKROUTER_TASKS("taskrouter-tasks"), - TOTALPRICE("totalprice"), - TRANSCRIPTIONS("transcriptions"), - TRUNKING_CPS("trunking-cps"), - TRUNKING_EMERGENCY_CALLS("trunking-emergency-calls"), - TRUNKING_ORIGINATION("trunking-origination"), - TRUNKING_ORIGINATION_LOCAL("trunking-origination-local"), - TRUNKING_ORIGINATION_MOBILE("trunking-origination-mobile"), - TRUNKING_ORIGINATION_TOLLFREE("trunking-origination-tollfree"), - TRUNKING_RECORDINGS("trunking-recordings"), - TRUNKING_SECURE("trunking-secure"), - TRUNKING_TERMINATION("trunking-termination"), - TTS_GOOGLE("tts-google"), - TURNMEGABYTES("turnmegabytes"), - TURNMEGABYTES_AUSTRALIA("turnmegabytes-australia"), - TURNMEGABYTES_BRASIL("turnmegabytes-brasil"), - TURNMEGABYTES_GERMANY("turnmegabytes-germany"), - TURNMEGABYTES_INDIA("turnmegabytes-india"), - TURNMEGABYTES_IRELAND("turnmegabytes-ireland"), - TURNMEGABYTES_JAPAN("turnmegabytes-japan"), - TURNMEGABYTES_SINGAPORE("turnmegabytes-singapore"), - TURNMEGABYTES_USEAST("turnmegabytes-useast"), - TURNMEGABYTES_USWEST("turnmegabytes-uswest"), - TWILIO_FOR_SALESFORCE("twilio-for-salesforce"), - TWILIO_FOR_SALESFORCE_LICENSES("twilio-for-salesforce-licenses"), - TWILIO_INTERCONNECT("twilio-interconnect"), - TWIML("twiml"), - USAGE_FLEX_VIDEO("usage-flex-video"), - USAGE_FUNCTIONS("usage-functions"), - USAGE_RCS_BASIC_MESSAGES_OUTBOUND("usage-rcs-basic-messages-outbound"), - USAGE_RCS_MESSAGES("usage-rcs-messages"), - USAGE_RCS_MESSAGES_INBOUND("usage-rcs-messages-inbound"), - USAGE_RCS_MESSAGING_CARRIER_FEES("usage-rcs-messaging-carrier-fees"), - USAGE_RCS_SINGLE_MESSAGES_OUTBOUND( - "usage-rcs-single-messages-outbound" - ), - VERIFY_PACKAGE_PLANS("verify-package-plans"), - VERIFY_PUSH("verify-push"), - VERIFY_SNA("verify-sna"), - VERIFY_TOTP("verify-totp"), - VERIFY_VOICE_SMS("verify-voice-sms"), - VERIFY_WHATSAPP_CONVERSATIONS_BUSINESS_INITIATED( - "verify-whatsapp-conversations-business-initiated" - ), - VERIFY_WHATSAPP_TEMPLATE_BUSINESS_INITIATED( - "verify-whatsapp-template-business-initiated" - ), - VIDEO_RECORDINGS("video-recordings"), - VIDEO_ROOMS_TURN_MEGABYTES("video-rooms-turn-megabytes"), - VIRTUAL_AGENT("virtual-agent"), - VOICE_INSIGHTS("voice-insights"), - VOICE_INSIGHTS_CLIENT_INSIGHTS_ON_DEMAND_MINUTE( - "voice-insights-client-insights-on-demand-minute" - ), - VOICE_INSIGHTS_PTSN_INSIGHTS_ON_DEMAND_MINUTE( - "voice-insights-ptsn-insights-on-demand-minute" - ), - VOICE_INSIGHTS_SIP_INTERFACE_INSIGHTS_ON_DEMAND_MINUTE( - "voice-insights-sip-interface-insights-on-demand-minute" - ), - VOICE_INSIGHTS_SIP_TRUNKING_INSIGHTS_ON_DEMAND_MINUTE( - "voice-insights-sip-trunking-insights-on-demand-minute" - ), - VOICE_INTELLIGENCE("voice-intelligence"), - VOICE_INTELLIGENCE_EIP_OPERATORS("voice-intelligence-eip-operators"), - VOICE_INTELLIGENCE_OPERATORS("voice-intelligence-operators"), - VOICE_INTELLIGENCE_TRANSCRIPTION("voice-intelligence-transcription"), - WDS("wds"), - WIRELESS("wireless"), - WIRELESS_DATA("wireless-data"), - WIRELESS_DATA_PAYG("wireless-data-payg"), - WIRELESS_DATA_PAYG_AFRICA("wireless-data-payg-africa"), - WIRELESS_DATA_PAYG_ASIA("wireless-data-payg-asia"), - WIRELESS_DATA_PAYG_CENTRALANDSOUTHAMERICA( - "wireless-data-payg-centralandsouthamerica" - ), - WIRELESS_DATA_PAYG_EUROPE("wireless-data-payg-europe"), - WIRELESS_DATA_PAYG_NORTHAMERICA("wireless-data-payg-northamerica"), - WIRELESS_DATA_PAYG_OCEANIA("wireless-data-payg-oceania"), - WIRELESS_DATA_QUOTA1("wireless-data-quota1"), - WIRELESS_DATA_QUOTA1_AFRICA("wireless-data-quota1-africa"), - WIRELESS_DATA_QUOTA1_ASIA("wireless-data-quota1-asia"), - WIRELESS_DATA_QUOTA1_CENTRALANDSOUTHAMERICA( - "wireless-data-quota1-centralandsouthamerica" - ), - WIRELESS_DATA_QUOTA1_EUROPE("wireless-data-quota1-europe"), - WIRELESS_DATA_QUOTA1_NORTHAMERICA("wireless-data-quota1-northamerica"), - WIRELESS_DATA_QUOTA1_OCEANIA("wireless-data-quota1-oceania"), - WIRELESS_DATA_QUOTA10("wireless-data-quota10"), - WIRELESS_DATA_QUOTA10_AFRICA("wireless-data-quota10-africa"), - WIRELESS_DATA_QUOTA10_ASIA("wireless-data-quota10-asia"), - WIRELESS_DATA_QUOTA10_CENTRALANDSOUTHAMERICA( - "wireless-data-quota10-centralandsouthamerica" - ), - WIRELESS_DATA_QUOTA10_EUROPE("wireless-data-quota10-europe"), - WIRELESS_DATA_QUOTA10_NORTHAMERICA( - "wireless-data-quota10-northamerica" - ), - WIRELESS_DATA_QUOTA10_OCEANIA("wireless-data-quota10-oceania"), - WIRELESS_DATA_QUOTA50("wireless-data-quota50"), - WIRELESS_DATA_QUOTA50_AFRICA("wireless-data-quota50-africa"), - WIRELESS_DATA_QUOTA50_ASIA("wireless-data-quota50-asia"), - WIRELESS_DATA_QUOTA50_CENTRALANDSOUTHAMERICA( - "wireless-data-quota50-centralandsouthamerica" - ), - WIRELESS_DATA_QUOTA50_EUROPE("wireless-data-quota50-europe"), - WIRELESS_DATA_QUOTA50_NORTHAMERICA( - "wireless-data-quota50-northamerica" - ), - WIRELESS_DATA_QUOTA50_OCEANIA("wireless-data-quota50-oceania"), - WIRELESS_DATA_QUOTACUSTOM("wireless-data-quotacustom"), - WIRELESS_DATA_QUOTACUSTOM_AFRICA("wireless-data-quotacustom-africa"), - WIRELESS_DATA_QUOTACUSTOM_ASIA("wireless-data-quotacustom-asia"), - WIRELESS_DATA_QUOTACUSTOM_CENTRALANDSOUTHAMERICA( - "wireless-data-quotacustom-centralandsouthamerica" - ), - WIRELESS_DATA_QUOTACUSTOM_EUROPE("wireless-data-quotacustom-europe"), - WIRELESS_DATA_QUOTACUSTOM_NORTHAMERICA( - "wireless-data-quotacustom-northamerica" - ), - WIRELESS_DATA_QUOTACUSTOM_OCEANIA("wireless-data-quotacustom-oceania"), - WIRELESS_MRC_PAYG("wireless-mrc-payg"), - WIRELESS_MRC_QUOTA1("wireless-mrc-quota1"), - WIRELESS_MRC_QUOTA10("wireless-mrc-quota10"), - WIRELESS_MRC_QUOTA50("wireless-mrc-quota50"), - WIRELESS_MRC_QUOTACUSTOM("wireless-mrc-quotacustom"), - WIRELESS_ORDERS("wireless-orders"), - WIRELESS_ORDERS_ARTWORK("wireless-orders-artwork"), - WIRELESS_ORDERS_BULK("wireless-orders-bulk"), - WIRELESS_ORDERS_ESIM("wireless-orders-esim"), - WIRELESS_ORDERS_STARTER("wireless-orders-starter"), - WIRELESS_QUOTAS("wireless-quotas"), - WIRELESS_SMS_AFRICA("wireless-sms-africa"), - WIRELESS_SMS_ASIA("wireless-sms-asia"), - WIRELESS_SMS_CENTRALANDSOUTHAMERICA( - "wireless-sms-centralandsouthamerica" - ), - WIRELESS_SMS_EUROPE("wireless-sms-europe"), - WIRELESS_SMS_NORTHAMERICA("wireless-sms-northamerica"), - WIRELESS_SMS_OCEANIA("wireless-sms-oceania"), - WIRELESS_SUPER_SIM("wireless-super-sim"), - WIRELESS_SUPER_SIM_DATA("wireless-super-sim-data"), - WIRELESS_SUPER_SIM_DATA_NORTH_AMERICA_USA( - "wireless-super-sim-data-north-america-usa" - ), - WIRELESS_SUPER_SIM_DATA_PAYG("wireless-super-sim-data-payg"), - WIRELESS_SUPER_SIM_DATA_PAYG_EUROPE( - "wireless-super-sim-data-payg-europe" - ), - WIRELESS_SUPER_SIM_DATA_PAYG_NORTH_AMERICA( - "wireless-super-sim-data-payg-north-america" - ), - WIRELESS_SUPER_SIM_HARDWARE("wireless-super-sim-hardware"), - WIRELESS_SUPER_SIM_HARDWARE_BULK("wireless-super-sim-hardware-bulk"), - WIRELESS_SUPER_SIM_SMSCOMMANDS("wireless-super-sim-smscommands"), - WIRELESS_SUPER_SIM_SMSCOMMANDS_AFRICA( - "wireless-super-sim-smscommands-africa" - ), - WIRELESS_SUPER_SIM_SMSCOMMANDS_ASIA( - "wireless-super-sim-smscommands-asia" - ), - WIRELESS_SUPER_SIM_SMSCOMMANDS_CENT_AND_SOUTH_AMERICA( - "wireless-super-sim-smscommands-cent-and-south-america" - ), - WIRELESS_SUPER_SIM_SMSCOMMANDS_EUROPE( - "wireless-super-sim-smscommands-europe" - ), - WIRELESS_SUPER_SIM_SMSCOMMANDS_NORTH_AMERICA( - "wireless-super-sim-smscommands-north-america" - ), - WIRELESS_SUPER_SIM_SMSCOMMANDS_OCEANIA( - "wireless-super-sim-smscommands-oceania" - ), - WIRELESS_SUPER_SIM_SUBSCRIPTION("wireless-super-sim-subscription"), - WIRELESS_SUPER_SIM_SUBSCRIPTION_PAYG( - "wireless-super-sim-subscription-payg" - ), - WIRELESS_USAGE("wireless-usage"), - WIRELESS_USAGE_COMMANDS("wireless-usage-commands"), - WIRELESS_USAGE_COMMANDS_AFRICA("wireless-usage-commands-africa"), - WIRELESS_USAGE_COMMANDS_ASIA("wireless-usage-commands-asia"), - WIRELESS_USAGE_COMMANDS_CENTRALANDSOUTHAMERICA( - "wireless-usage-commands-centralandsouthamerica" - ), - WIRELESS_USAGE_COMMANDS_EUROPE("wireless-usage-commands-europe"), - WIRELESS_USAGE_COMMANDS_HOME("wireless-usage-commands-home"), - WIRELESS_USAGE_COMMANDS_NORTHAMERICA( - "wireless-usage-commands-northamerica" - ), - WIRELESS_USAGE_COMMANDS_OCEANIA("wireless-usage-commands-oceania"), - WIRELESS_USAGE_COMMANDS_ROAMING("wireless-usage-commands-roaming"), - WIRELESS_USAGE_DATA("wireless-usage-data"), - WIRELESS_USAGE_DATA_AFRICA("wireless-usage-data-africa"), - WIRELESS_USAGE_DATA_ASIA("wireless-usage-data-asia"), - WIRELESS_USAGE_DATA_CENTRALANDSOUTHAMERICA( - "wireless-usage-data-centralandsouthamerica" - ), - WIRELESS_USAGE_DATA_CUSTOM_ADDITIONALMB( - "wireless-usage-data-custom-additionalmb" - ), - WIRELESS_USAGE_DATA_CUSTOM_FIRST5MB( - "wireless-usage-data-custom-first5mb" - ), - WIRELESS_USAGE_DATA_DOMESTIC_ROAMING( - "wireless-usage-data-domestic-roaming" - ), - WIRELESS_USAGE_DATA_EUROPE("wireless-usage-data-europe"), - WIRELESS_USAGE_DATA_INDIVIDUAL_ADDITIONALGB( - "wireless-usage-data-individual-additionalgb" - ), - WIRELESS_USAGE_DATA_INDIVIDUAL_FIRSTGB( - "wireless-usage-data-individual-firstgb" - ), - WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_CANADA( - "wireless-usage-data-international-roaming-canada" - ), - WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_INDIA( - "wireless-usage-data-international-roaming-india" - ), - WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_MEXICO( - "wireless-usage-data-international-roaming-mexico" - ), - WIRELESS_USAGE_DATA_NORTHAMERICA("wireless-usage-data-northamerica"), - WIRELESS_USAGE_DATA_OCEANIA("wireless-usage-data-oceania"), - WIRELESS_USAGE_DATA_POOLED("wireless-usage-data-pooled"), - WIRELESS_USAGE_DATA_POOLED_DOWNLINK( - "wireless-usage-data-pooled-downlink" - ), - WIRELESS_USAGE_DATA_POOLED_UPLINK("wireless-usage-data-pooled-uplink"), - WIRELESS_USAGE_MRC("wireless-usage-mrc"), - WIRELESS_USAGE_MRC_CUSTOM("wireless-usage-mrc-custom"), - WIRELESS_USAGE_MRC_INDIVIDUAL("wireless-usage-mrc-individual"), - WIRELESS_USAGE_MRC_POOLED("wireless-usage-mrc-pooled"), - WIRELESS_USAGE_MRC_SUSPENDED("wireless-usage-mrc-suspended"), - WIRELESS_USAGE_SMS("wireless-usage-sms"), - WIRELESS_USAGE_VOICE("wireless-usage-voice"), - A2P_FAST_TRACK_ONBOARDING("a2p-fast-track-onboarding"), - ADVISORY_SERVICES("advisory-services"), - ADVISORY_SERVICES_BILLED("advisory-services-billed"), - ADVISORY_SERVICES_CALL_TRACKING("advisory-services-call-tracking"), - ADVISORY_SERVICES_DATA_SERVICES("advisory-services-data-services"), - ADVISORY_SERVICES_EXPENSES("advisory-services-expenses"), - ADVISORY_SERVICES_SIP_TRUNKING("advisory-services-sip-trunking"), - ASSETS_REQUESTS("assets-requests"), - AUDIENCE_MINUTES_VIDEO("audience-minutes-video"), - AUTHY_BUCKET_ADJUSTMENT("authy-bucket-adjustment"), - AUTHY_SOFTWARE("authy-software"), - CALLERIDLOOKUPS_API("calleridlookups-api"), - CALLERIDLOOKUPS_PROGRAMMABLEVOICE("calleridlookups-programmablevoice"), - CALLERIDLOOKUPS_TRUNKING("calleridlookups-trunking"), - CALLS_TRUNKING_INBOUND_TOLLFREE_LOCAL( - "calls-trunking-inbound-tollfree-local" - ), - CALLS_TRUNKING_INBOUND_TOLLFREE_MOBILE( - "calls-trunking-inbound-tollfree-mobile" - ), - CHANNELS_WHATSAPP_CONVERSATION_FREE_1( - "channels-whatsapp-conversation-free-1" - ), - CONFERENCE("conference"), - CONVERSATIONAL_INSIGHTS("conversational-insights"), - CONVERSATIONAL_INSIGHTS_MESSAGES("conversational-insights-messages"), - CONVERSATIONAL_INSIGHTS_VOICE_MINUTES( - "conversational-insights-voice-minutes" - ), - DEMO("demo"), - DEMO_UC_SCRIPT_TEST("demo-uc-script-test"), - ELASTIC_SIP_TRUNKING("elastic-sip-trunking"), - ELASTIC_SIP_TRUNKING_CALL_TRANSFERS( - "elastic-sip-trunking-call-transfers" - ), - ENTERPRISE_HIPPA("enterprise-hippa"), - FLEX_NAMED_USERS("flex-named-users"), - FLEX_SPINSCI("flex-spinsci"), - FLEX_USERS_1("flex-users-1"), - FLEX_WFO_PREMIUM_SPEECH_ANALYTICS("flex-wfo-premium-speech-analytics"), - FLEX_XCELERATE("flex-xcelerate"), - FUNCTIONS_ROLLUP("functions-rollup"), - IMP_V1_USAGE("imp-v1-usage"), - IP_MESSAGING_ADDONS("ip-messaging-addons"), - IVR("ivr"), - IVR_CONVERSATIONAL("ivr-conversational"), - IVR_DTMF("ivr-dtmf"), - IVR_VIRTUALAGENT("ivr-virtualagent"), - LIVE("live"), - LIVE_MEDIA_RECORDING_MINUTES("live-media-recording-minutes"), - LONGCODE_MPS("longcode-mps"), - MARKETPLACE_ANALYTICS_ADDONS("marketplace-analytics-addons"), - MARKETPLACE_ISV_ADDONS("marketplace-isv-addons"), - MARKETPLACE_MESSAGING_ADDONS("marketplace-messaging-addons"), - MARKETPLACE_PHONENUMBERS_ADDONS("marketplace-phonenumbers-addons"), - MARKETPLACE_RECORDING_ADDONS("marketplace-recording-addons"), - MARKETPLACE_VIRTUALAGENT_ADDONS("marketplace-virtualagent-addons"), - MARKETPLAY_PAY_ADDONS_SHUTTLE_PAY_CONNECTOR_1( - "marketplay-pay-addons-shuttle-pay-connector-1" - ), - MARKETPLAY_PAY_ADDONS_STRIPE_PAY_CONNECTOR( - "marketplay-pay-addons-stripe-pay-connector" - ), - MMS_INBOUND_LONGCODE_CANADA("mms-inbound-longcode-canada"), - MMS_INBOUND_LONGCODE_UNITEDSTATES("mms-inbound-longcode-unitedstates"), - MMS_OUTBOUND_LONGCODE_CANADA("mms-outbound-longcode-canada"), - MMS_OUTBOUND_LONGCODE_UNITEDSTATES( - "mms-outbound-longcode-unitedstates" - ), - MMS_OUTBOUND_TOLL_FREE("mms-outbound-toll-free"), - NOTIFY_CHATAPPSANDOTHERCHANNELS("notify-chatappsandotherchannels"), - NOTIFY_NOTIFYSERVICES("notify-notifyservices"), - NOTIFY_PUSHNOTIFICATIONS("notify-pushnotifications"), - PAYMENT_GATEWAY_CONNECTORS("payment-gateway-connectors"), - PAYMENT_SOLUTIONS("payment-solutions"), - PCHAT_BUCKET_ADJUSTMENT("pchat-bucket-adjustment"), - PHONENUMBERS_NUMBERS("phonenumbers-numbers"), - PROG_VOICE_CLIENT_ANDROID("prog-voice-client-android"), - PROG_VOICE_CLIENT_ANDROID_INBOUND("prog-voice-client-android-inbound"), - PROG_VOICE_CLIENT_ANDROID_OUTBOUND( - "prog-voice-client-android-outbound" - ), - PROG_VOICE_CLIENT_IOS("prog-voice-client-ios"), - PROG_VOICE_CLIENT_IOS_INBOUND("prog-voice-client-ios-inbound"), - PROG_VOICE_CLIENT_IOS_OUTBOUND("prog-voice-client-ios-outbound"), - PROG_VOICE_CLIENT_SDK("prog-voice-client-sdk"), - PROG_VOICE_CLIENT_WEB("prog-voice-client-web"), - PROG_VOICE_CLIENT_WEB_INBOUND("prog-voice-client-web-inbound"), - PROG_VOICE_CLIENT_WEB_OUTBOUND("prog-voice-client-web-outbound"), - PROGRAMMABLEVOICECONNECTIVITY_MEDIA_STREAMS( - "programmablevoiceconnectivity-media-streams" - ), - PSTNCONNECTIVITY_BYOC("pstnconnectivity-byoc"), - PSTNCONNECTIVITY_EMERGENCY("pstnconnectivity-emergency"), - PSTNCONNECTIVITY_MINUTES("pstnconnectivity-minutes"), - PSTNCONNECTIVITY_MINUTES_1("pstnconnectivity-minutes-1"), - PSTNCONNECTIVITY_MINUTESINBOUNDLOCAL( - "pstnconnectivity-minutesinboundlocal" - ), - PSTNCONNECTIVITY_MINUTESINBOUNDMOBILE( - "pstnconnectivity-minutesinboundmobile" - ), - PSTNCONNECTIVITY_MINUTESINBOUNDTOLLFREE( - "pstnconnectivity-minutesinboundtollfree" - ), - PSTNCONNECTIVITY_MINUTESINBOUNDTOLLFREELOCAL( - "pstnconnectivity-minutesinboundtollfreelocal" - ), - PSTNCONNECTIVITY_MINUTESINBOUNDTOLLFREEMOBILE( - "pstnconnectivity-minutesinboundtollfreemobile" - ), - PV_ROOM_HOURS("pv-room-hours"), - PV_ROOM_SIMULTANEOUS_PARTICIPANT_CONNECTIONS( - "pv-room-simultaneous-participant-connections" - ), - PVIDEO_ROOM_HOURS_AU1("pvideo-room-hours-au1"), - PVIDEO_ROOM_HOURS_BR1("pvideo-room-hours-br1"), - PVIDEO_ROOM_HOURS_IE1("pvideo-room-hours-ie1"), - PVIDEO_ROOM_HOURS_JP1("pvideo-room-hours-jp1"), - PVIDEO_ROOM_HOURS_SG1("pvideo-room-hours-sg1"), - PVIDEO_ROOM_HOURS_US1("pvideo-room-hours-us1"), - PVIDEO_ROOM_HOURS_US2("pvideo-room-hours-us2"), - RECORDINGS_ENCRYPTED("recordings-encrypted"), - SHORT_CODE_SETUP_FEES("short-code-setup-fees"), - SHORTCODES_MESSAGES_INBOUND("shortcodes-messages-inbound"), - SHORTCODES_MESSAGES_OUTBOUND("shortcodes-messages-outbound"), - SMS_MESSAGES_REGISTRATIONFEES("sms-messages-registrationfees"), - SMS_MMS_PENALTY_FEES("sms-mms-penalty-fees"), - SMS_MMS_PENALTY_FEES_1("sms-mms-penalty-fees-1"), - SMS_PUMPING_PROTECTION_NON_USCA("sms-pumping-protection-non-usca"), - SMS_PUMPING_PROTECTION_USCA("sms-pumping-protection-usca"), - STUDIO("studio"), - STUDIO_MONTHLY_FEES("studio-monthly-fees"), - SUPERSIM("supersim"), - TASK_ROUTER("task-router"), - TASK_ROUTER_WORKERS("task-router-workers"), - TEST_QUOTA_BUCKETS("test-quota-buckets"), - TEST_UC_SCRIPT_1("test-uc-script-1"), - TEST_UC_SCRIPT_DEMO_2("test-uc-script-demo-2"), - TEXT_TO_SPEECH("text-to-speech"), - TME("tme"), - TTS_BASIC("tts-basic"), - TWILIO_EDITIONS("twilio-editions"), - TWILIO_INTERCONNECT_CALIFORNIA("twilio-interconnect-california"), - TWILIO_INTERCONNECT_CALIFORNIA_MONTHLY( - "twilio-interconnect-california-monthly" - ), - TWILIO_INTERCONNECT_CALIFORNIA_SETUP( - "twilio-interconnect-california-setup" - ), - TWILIO_INTERCONNECT_FRANKFURT("twilio-interconnect-frankfurt"), - TWILIO_INTERCONNECT_FRANKFURT_MO("twilio-interconnect-frankfurt-mo"), - TWILIO_INTERCONNECT_FRANKFURT_SETUP( - "twilio-interconnect-frankfurt-setup" - ), - TWILIO_INTERCONNECT_LONDON("twilio-interconnect-london"), - TWILIO_INTERCONNECT_LONDON_MO("twilio-interconnect-london-mo"), - TWILIO_INTERCONNECT_LONDON_SETUP("twilio-interconnect-london-setup"), - TWILIO_INTERCONNECT_SAO_PAULO("twilio-interconnect-sao-paulo"), - TWILIO_INTERCONNECT_SAO_PAULO_MONTHLY( - "twilio-interconnect-sao-paulo-monthly" - ), - TWILIO_INTERCONNECT_SAO_PAULO_SETUP( - "twilio-interconnect-sao-paulo-setup" - ), - TWILIO_INTERCONNECT_SINGAPORE("twilio-interconnect-singapore"), - TWILIO_INTERCONNECT_SINGAPORE_MO("twilio-interconnect-singapore-mo"), - TWILIO_INTERCONNECT_SINGAPORE_SETUP( - "twilio-interconnect-singapore-setup" - ), - TWILIO_INTERCONNECT_SYDNEY("twilio-interconnect-sydney"), - TWILIO_INTERCONNECT_SYDNEY_MO("twilio-interconnect-sydney-mo"), - TWILIO_INTERCONNECT_SYDNEY_SETUP("twilio-interconnect-sydney-setup"), - TWILIO_INTERCONNECT_TOKYO("twilio-interconnect-tokyo"), - TWILIO_INTERCONNECT_TOKYO_MO("twilio-interconnect-tokyo-mo"), - TWILIO_INTERCONNECT_TOKYO_SETUP("twilio-interconnect-tokyo-setup"), - TWILIO_INTERCONNECT_VA("twilio-interconnect-va"), - TWILIO_INTERCONNECT_VA_MO("twilio-interconnect-va-mo"), - TWILIO_INTERCONNECT_VA_SETUP("twilio-interconnect-va-setup"), - TWIML_VERBS("twiml-verbs"), - TWIML_VERBS_SAY("twiml-verbs-say"), - USAGE_PROGRAMMABLE_MESSAGING_ENGAGEMENT_SUITE( - "usage-programmable-messaging-engagement-suite" - ), - USAGE_PROGRAMMABLE_MESSAGING_FEES_SERVICES( - "usage-programmable-messaging-fees-services" - ), - VERIFY_OUTBOUND_EMAIL("verify-outbound-email"), - VERIFY_PACKAGED_PLANS("verify-packaged-plans"), - VERIFY_SILENT_NETWORK_AUTH("verify-silent-network-auth"), - VERIFY_VOICE_AND_SMS("verify-voice-and-sms"), - VOICE_INSIGHTS_CLIENT_INSIGHTS_MONTHY_COMMIT( - "voice-insights-client-insights-monthy-commit" - ), - WIRELESS_DATA_PAYG_ASIA_AFG("wireless-data-payg-asia-afg"), - WIRELESS_MULTI_IMSI_SIM_COMMANDS("wireless-multi-imsi-sim-commands"), - WIRELESS_MULTI_IMSI_SIM_COMMANDS_USA( - "wireless-multi-imsi-sim-commands-usa" - ), - WIRELESS_MULTI_IMSI_SIM_DATA("wireless-multi-imsi-sim-data"), - WIRELESS_MULTI_IMSI_SIM_DATA_EU28("wireless-multi-imsi-sim-data-eu28"), - WIRELESS_MULTI_IMSI_SIM_DATA_USA("wireless-multi-imsi-sim-data-usa"), - WIRELESS_MULTI_IMSI_SIM_MONTHLY_FEES( - "wireless-multi-imsi-sim-monthly-fees" - ), - WIRELESS_MULTI_IMSI_SIM_USAGE("wireless-multi-imsi-sim-usage"), - WIRELESS_SUPER_SIM_DATA_NORTH_AMERICA( - "wireless-super-sim-data-north-america" - ), - WIRELESS_SUPER_SIM_USAGE("wireless-super-sim-usage"); - - private final String value; - - private Category(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static Category forValue(final String value) { - return Promoter.enumFromString(value, Category.values()); - } - } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/usage/record/ThisMonthReader.java b/src/main/java/com/twilio/rest/api/v2010/account/usage/record/ThisMonthReader.java index 75a05e825d..c68527fae5 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/usage/record/ThisMonthReader.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/usage/record/ThisMonthReader.java @@ -32,7 +32,7 @@ public class ThisMonthReader extends Reader { private String pathAccountSid; - private ThisMonth.Category category; + private String category; private LocalDate startDate; private LocalDate endDate; private Boolean includeSubaccounts; @@ -44,7 +44,7 @@ public ThisMonthReader(final String pathAccountSid) { this.pathAccountSid = pathAccountSid; } - public ThisMonthReader setCategory(final ThisMonth.Category category) { + public ThisMonthReader setCategory(final String category) { this.category = category; return this; } @@ -168,7 +168,7 @@ public Page getPage( private void addQueryParams(final Request request) { if (category != null) { - request.addQueryParam("Category", category.toString()); + request.addQueryParam("Category", category); } if (startDate != null) { request.addQueryParam( diff --git a/src/main/java/com/twilio/rest/api/v2010/account/usage/record/Today.java b/src/main/java/com/twilio/rest/api/v2010/account/usage/record/Today.java index dcfcc4fcb5..61c98c4bc3 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/usage/record/Today.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/usage/record/Today.java @@ -24,7 +24,6 @@ import com.twilio.base.Resource; import com.twilio.converter.CurrencyDeserializer; import com.twilio.converter.DateConverter; -import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import java.io.IOException; @@ -42,7 +41,7 @@ @ToString public class Today extends Resource { - private static final long serialVersionUID = 120182361368915L; + private static final long serialVersionUID = 158026917970511L; public static TodayReader reader() { return new TodayReader(); @@ -98,7 +97,7 @@ public static Today fromJson( private final String accountSid; private final String apiVersion; private final String asOf; - private final Today.Category category; + private final String category; private final String count; private final String countUnit; private final String description; @@ -116,7 +115,7 @@ private Today( @JsonProperty("account_sid") final String accountSid, @JsonProperty("api_version") final String apiVersion, @JsonProperty("as_of") final String asOf, - @JsonProperty("category") final Today.Category category, + @JsonProperty("category") final String category, @JsonProperty("count") final String count, @JsonProperty("count_unit") final String countUnit, @JsonProperty("description") final String description, @@ -163,7 +162,7 @@ public final String getAsOf() { return this.asOf; } - public final Today.Category getCategory() { + public final String getCategory() { return this.category; } @@ -262,945 +261,4 @@ public int hashCode() { usageUnit ); } - - public enum Category { - A2P_10DLC_REGISTRATIONFEES_BRANDREGISTRATION( - "a2p-10dlc-registrationfees-brandregistration" - ), - A2P_10DLC_REGISTRATIONFEES_BV("a2p-10dlc-registrationfees-bv"), - A2P_10DLC_REGISTRATIONFEES_CAMPAIGNCHARGES( - "a2p-10dlc-registrationfees-campaigncharges" - ), - A2P_10DLC_REGISTRATIONFEES_CAMPAIGNREGISTRATION( - "a2p-10dlc-registrationfees-campaignregistration" - ), - A2P_10DLC_REGISTRATIONFEES_CAMPAIGNVETTING( - "a2p-10dlc-registrationfees-campaignvetting" - ), - A2P_10DLC_REGISTRATIONFEES_MONTHLY( - "a2p-10dlc-registrationfees-monthly" - ), - A2P_10DLC_REGISTRATIONFEES_ONETIME( - "a2p-10dlc-registrationfees-onetime" - ), - A2P_REGISTRATION_FEES("a2p-registration-fees"), - ACCOUNT_SECURITY("account-security"), - AGENT_CONFERENCE("agent-conference"), - AGENT_COPILOT("agent-copilot"), - AGENT_COPILOT_MESSAGES("agent-copilot-messages"), - AGENT_COPILOT_PARTICIPANT_MINUTES("agent-copilot-participant-minutes"), - AI_ASSISTANTS("ai-assistants"), - AI_ASSISTANTS_VOICE("ai-assistants-voice"), - AMAZON_POLLY("amazon-polly"), - ANSWERING_MACHINE_DETECTION("answering-machine-detection"), - ASSETS("assets"), - AUDIENCE_MINUTES("audience-minutes"), - AUDIENCE_MINUTES_AUDIO("audience-minutes-audio"), - AUTHY_AUTHENTICATIONS("authy-authentications"), - AUTHY_CALLS_OUTBOUND("authy-calls-outbound"), - AUTHY_EMAIL_AUTHENTICATIONS("authy-email-authentications"), - AUTHY_MONTHLY_FEES("authy-monthly-fees"), - AUTHY_OUTBOUND_EMAIL("authy-outbound-email"), - AUTHY_PHONE_INTELLIGENCE("authy-phone-intelligence"), - AUTHY_PHONE_VERIFICATIONS("authy-phone-verifications"), - AUTHY_SMS_OUTBOUND("authy-sms-outbound"), - AUTHY_VERIFY_EMAIL_VERIFICATIONS("authy-verify-email-verifications"), - AUTHY_VERIFY_OUTBOUND_EMAIL("authy-verify-outbound-email"), - AUTOPILOT("autopilot"), - AUTOPILOT_HOME_ASSISTANTS("autopilot-home-assistants"), - AUTOPILOT_MESSAGING("autopilot-messaging"), - AUTOPILOT_OTHER("autopilot-other"), - AUTOPILOT_VOICE("autopilot-voice"), - BASIC_PEER_TO_PEER_ROOMS_PARTICIPANT_MINUTES( - "basic-peer-to-peer-rooms-participant-minutes" - ), - BRANDED_CALLING("branded-calling"), - BUNDLE_SMS_BUCKET("bundle-sms-bucket"), - BUNDLE_SUBSCRIPTION_FEES("bundle-subscription-fees"), - CALL_FORWARDING_LOOKUPS("call-forwarding-lookups"), - CALL_PROGESS_EVENTS("call-progess-events"), - CALLERIDLOOKUPS("calleridlookups"), - CALLS("calls"), - CALLS_CLIENT("calls-client"), - CALLS_EMERGENCY("calls-emergency"), - CALLS_GLOBALCONFERENCE("calls-globalconference"), - CALLS_INBOUND("calls-inbound"), - CALLS_INBOUND_LOCAL("calls-inbound-local"), - CALLS_INBOUND_MOBILE("calls-inbound-mobile"), - CALLS_INBOUND_TOLLFREE("calls-inbound-tollfree"), - CALLS_INBOUND_TOLLFREE_LOCAL("calls-inbound-tollfree-local"), - CALLS_INBOUND_TOLLFREE_MOBILE("calls-inbound-tollfree-mobile"), - CALLS_MEDIA_STREAM_MINUTES("calls-media-stream-minutes"), - CALLS_OUTBOUND("calls-outbound"), - CALLS_PAY_VERB_TRANSACTIONS("calls-pay-verb-transactions"), - CALLS_RECORDINGS("calls-recordings"), - CALLS_SIP("calls-sip"), - CALLS_SIP_INBOUND("calls-sip-inbound"), - CALLS_SIP_OUTBOUND("calls-sip-outbound"), - CALLS_TEXT_TO_SPEECH("calls-text-to-speech"), - CALLS_TRANSFERS("calls-transfers"), - CARRIER_LOOKUPS("carrier-lookups"), - CATEGORY("category"), - CHANNELS("channels"), - CHANNELS_MESSAGING("channels-messaging"), - CHANNELS_MESSAGING_INBOUND("channels-messaging-inbound"), - CHANNELS_MESSAGING_OUTBOUND("channels-messaging-outbound"), - CHANNELS_WHATSAPP("channels-whatsapp"), - CHANNELS_WHATSAPP_CONVERSATION_AUTHENTICATION( - "channels-whatsapp-conversation-authentication" - ), - CHANNELS_WHATSAPP_CONVERSATION_FREE( - "channels-whatsapp-conversation-free" - ), - CHANNELS_WHATSAPP_CONVERSATION_MARKETING( - "channels-whatsapp-conversation-marketing" - ), - CHANNELS_WHATSAPP_CONVERSATION_SERVICE( - "channels-whatsapp-conversation-service" - ), - CHANNELS_WHATSAPP_CONVERSATION_UTILITY( - "channels-whatsapp-conversation-utility" - ), - CHANNELS_WHATSAPP_INBOUND("channels-whatsapp-inbound"), - CHANNELS_WHATSAPP_OUTBOUND("channels-whatsapp-outbound"), - CHANNELS_WHATSAPP_SERVICE("channels-whatsapp-service"), - CHANNELS_WHATSAPP_TEMPLATE_AUTHENTICATION( - "channels-whatsapp-template-authentication" - ), - CHANNELS_WHATSAPP_TEMPLATE_MARKETING( - "channels-whatsapp-template-marketing" - ), - CHANNELS_WHATSAPP_TEMPLATE_SERVICE( - "channels-whatsapp-template-service" - ), - CHANNELS_WHATSAPP_TEMPLATE_UTILITY( - "channels-whatsapp-template-utility" - ), - CHAT_VIRTUAL_AGENT("chat-virtual-agent"), - CONVERSATION_RELAY("conversation-relay"), - CONVERSATIONS("conversations"), - CONVERSATIONS_API_REQUESTS("conversations-api-requests"), - CONVERSATIONS_CONVERSATION_EVENTS("conversations-conversation-events"), - CONVERSATIONS_ENDPOINT_CONNECTIVITY( - "conversations-endpoint-connectivity" - ), - CONVERSATIONS_EVENTS("conversations-events"), - CONVERSATIONS_PARTICIPANT_EVENTS("conversations-participant-events"), - CONVERSATIONS_PARTICIPANTS("conversations-participants"), - CPS("cps"), - CREDIT_TRANSFER("credit-transfer"), - EMAIL("email"), - EMERGING_TECH("emerging-tech"), - ENGAGEMENT_SUITE_PACKAGED_PLANS("engagement-suite-packaged-plans"), - ENHANCED_LINE_TYPE_LOOKUPS("enhanced-line-type-lookups"), - ENTERPRISE("enterprise"), - EVENTS("events"), - EXPERIMENT_FRANCE_SMS("experiment-france-sms"), - EXPERIMENT_INDIA_SMS("experiment-india-sms"), - EXPERIMENT_UK_SMS("experiment-uk-sms"), - FAILED_MESSAGE_PROCESSING_FEE("failed-message-processing-fee"), - FLEX("flex"), - FLEX_ACTIVE_USER_HOURS("flex-active-user-hours"), - FLEX_CONCURRENT_USERS("flex-concurrent-users"), - FLEX_CONVERSATIONAL_INSIGHTS("flex-conversational-insights"), - FLEX_CONVERSATIONAL_INSIGHTS_MESSAGES( - "flex-conversational-insights-messages" - ), - FLEX_CONVERSATIONAL_INSIGHTS_VOICE_MINUTES( - "flex-conversational-insights-voice-minutes" - ), - FLEX_EMAIL_USAGE("flex-email-usage"), - FLEX_MESSAGING_USAGE("flex-messaging-usage"), - FLEX_PARTNER_SPINSCI("flex-partner-spinsci"), - FLEX_PARTNER_XCELERATE("flex-partner-xcelerate"), - FLEX_RESELLER_ECOSYSTEM("flex-reseller-ecosystem"), - FLEX_UNIQUE_USER("flex-unique-user"), - FLEX_USAGE("flex-usage"), - FLEX_USERS("flex-users"), - FLEX_VOICE_MINUTE("flex-voice-minute"), - FLEX_YTICA("flex-ytica"), - FRAUD_LOOKUPS("fraud-lookups"), - FRONTLINE("frontline"), - FRONTLINE_USERS("frontline-users"), - FUNCTIONS("functions"), - GENERIC_PAY_TRANSACTIONS("generic-pay-transactions"), - GROUP_ROOMS("group-rooms"), - GROUP_ROOMS_DATA_TRACK("group-rooms-data-track"), - GROUP_ROOMS_ENCRYPTED_MEDIA_RECORDED( - "group-rooms-encrypted-media-recorded" - ), - GROUP_ROOMS_MEDIA_DOWNLOADED("group-rooms-media-downloaded"), - GROUP_ROOMS_MEDIA_RECORDED("group-rooms-media-recorded"), - GROUP_ROOMS_MEDIA_ROUTED("group-rooms-media-routed"), - GROUP_ROOMS_MEDIA_STORED("group-rooms-media-stored"), - GROUP_ROOMS_PARTICIPANT_MINUTES("group-rooms-participant-minutes"), - GROUP_ROOMS_RECORDED_MINUTES("group-rooms-recorded-minutes"), - IP_MESSAGING("ip-messaging"), - IP_MESSAGING_COMMANDS("ip-messaging-commands"), - IP_MESSAGING_DATA_STORAGE("ip-messaging-data-storage"), - IP_MESSAGING_DATA_TRANSFER("ip-messaging-data-transfer"), - IP_MESSAGING_ENDPOINT_CONNECTIVITY( - "ip-messaging-endpoint-connectivity" - ), - IVR_VIRTUAL_AGENT_CUSTOM_VOICES("ivr-virtual-agent-custom-voices"), - IVR_VIRTUAL_AGENT_GENAI("ivr-virtual-agent-genai"), - LINE_STATUS_LOOKUPS("line-status-lookups"), - LIVE_ACTIVITY_LOOKUPS("live-activity-lookups"), - LOOKUP_BUCKET_ADJUSTMENT("lookup-bucket-adjustment"), - LOOKUP_IDENTITY_MATCH("lookup-identity-match"), - LOOKUPS("lookups"), - MARKETPLACE("marketplace"), - MARKETPLACE_ALGORITHMIA_NAMED_ENTITY_RECOGNITION( - "marketplace-algorithmia-named-entity-recognition" - ), - MARKETPLACE_CADENCE_TRANSCRIPTION("marketplace-cadence-transcription"), - MARKETPLACE_CADENCE_TRANSLATION("marketplace-cadence-translation"), - MARKETPLACE_CAPIO_SPEECH_TO_TEXT("marketplace-capio-speech-to-text"), - MARKETPLACE_CONVRIZA_ABABA("marketplace-convriza-ababa"), - MARKETPLACE_DEEPGRAM_PHRASE_DETECTOR( - "marketplace-deepgram-phrase-detector" - ), - MARKETPLACE_DEEPGRAM_TRANSCRIPTION( - "marketplace-deepgram-transcription" - ), - MARKETPLACE_DEEPGRAM_TRANSCRIPTION_BASE( - "marketplace-deepgram-transcription-base" - ), - MARKETPLACE_DEEPGRAM_TRANSSCRIPTION_ENHANCED( - "marketplace-deepgram-transscription-enhanced" - ), - MARKETPLACE_DIGITAL_SEGMENT_BUSINESS_INFO( - "marketplace-digital-segment-business-info" - ), - MARKETPLACE_FACEBOOK_OFFLINE_CONVERSIONS( - "marketplace-facebook-offline-conversions" - ), - MARKETPLACE_GOOGLE_SPEECH_TO_TEXT("marketplace-google-speech-to-text"), - MARKETPLACE_IBM_WATSON_MESSAGE_INSIGHTS( - "marketplace-ibm-watson-message-insights" - ), - MARKETPLACE_IBM_WATSON_MESSAGE_SENTIMENT( - "marketplace-ibm-watson-message-sentiment" - ), - MARKETPLACE_IBM_WATSON_RECORDING_ANALYSIS( - "marketplace-ibm-watson-recording-analysis" - ), - MARKETPLACE_IBM_WATSON_TONE_ANALYZER( - "marketplace-ibm-watson-tone-analyzer" - ), - MARKETPLACE_ICEHOOK_SYSTEMS_SCOUT("marketplace-icehook-systems-scout"), - MARKETPLACE_INFOGROUP_DATAAXLE_BIZINFO( - "marketplace-infogroup-dataaxle-bizinfo" - ), - MARKETPLACE_KEEN_IO_CONTACT_CENTER_ANALYTICS( - "marketplace-keen-io-contact-center-analytics" - ), - MARKETPLACE_MARCHEX_CLEANCALL("marketplace-marchex-cleancall"), - MARKETPLACE_MARCHEX_RECORDING_ANALYSIS( - "marketplace-marchex-recording-analysis" - ), - MARKETPLACE_MARCHEX_SENTIMENT_ANALYSIS_FOR_SMS( - "marketplace-marchex-sentiment-analysis-for-sms" - ), - MARKETPLACE_MARKETPLACE_NEXTCALLER_SOCIAL_ID( - "marketplace-marketplace-nextcaller-social-id" - ), - MARKETPLACE_MOBILE_COMMONS_OPT_OUT_CLASSIFIER( - "marketplace-mobile-commons-opt-out-classifier" - ), - MARKETPLACE_NEXIWAVE_VOICEMAIL_TO_TEXT( - "marketplace-nexiwave-voicemail-to-text" - ), - MARKETPLACE_NEXTCALLER_ADVANCED_CALLER_IDENTIFICATION( - "marketplace-nextcaller-advanced-caller-identification" - ), - MARKETPLACE_NOMOROBO_SPAM_SCORE("marketplace-nomorobo-spam-score"), - MARKETPLACE_PAY_ADDONS("marketplace-pay-addons"), - MARKETPLACE_PAY_ADDONS_BASECOMMERCE_PAY_CONNECTOR( - "marketplace-pay-addons-basecommerce-pay-connector" - ), - MARKETPLACE_PAY_ADDONS_BRAINTREE_PAY_CONNECTOR( - "marketplace-pay-addons-braintree-pay-connector" - ), - MARKETPLACE_PAY_ADDONS_CARDCONNECT_PAY_CONNECTOR( - "marketplace-pay-addons-cardconnect-pay-connector" - ), - MARKETPLACE_PAY_ADDONS_CHASE_PAY_CONNECTOR( - "marketplace-pay-addons-chase-pay-connector" - ), - MARKETPLACE_PAY_ADDONS_SHUTTLE_PAY_CONNECTOR( - "marketplace-pay-addons-shuttle-pay-connector" - ), - MARKETPLACE_PAY_ADDONS_STRIPE_PAY_CONNECTOR( - "marketplace-pay-addons-stripe-pay-connector" - ), - MARKETPLACE_PAYFONE_TCPA_COMPLIANCE( - "marketplace-payfone-tcpa-compliance" - ), - MARKETPLACE_POLY_AI_CONNECTOR("marketplace-poly-ai-connector"), - MARKETPLACE_REALPHONEVALIDATION("marketplace-realphonevalidation"), - MARKETPLACE_REMEETING_AUTOMATIC_SPEECH_RECOGNITION( - "marketplace-remeeting-automatic-speech-recognition" - ), - MARKETPLACE_SPOKE_PHONE_LICENSE_PRO( - "marketplace-spoke-phone-license-pro" - ), - MARKETPLACE_SPOKE_PHONE_LICENSE_STANDARD( - "marketplace-spoke-phone-license-standard" - ), - MARKETPLACE_TCPA_DEFENSE_SOLUTIONS_BLACKLIST_FEED( - "marketplace-tcpa-defense-solutions-blacklist-feed" - ), - MARKETPLACE_TELO_OPENCNAM("marketplace-telo-opencnam"), - MARKETPLACE_TRESTLE_SOLUTIONS_CALLER_IDENTIFICATION( - "marketplace-trestle-solutions-caller-identification" - ), - MARKETPLACE_TRUECNAM_TRUE_SPAM("marketplace-truecnam-true-spam"), - MARKETPLACE_TWILIO_CALLER_NAME_LOOKUP_US( - "marketplace-twilio-caller-name-lookup-us" - ), - MARKETPLACE_TWILIO_CARRIER_INFORMATION_LOOKUP( - "marketplace-twilio-carrier-information-lookup" - ), - MARKETPLACE_VOICEBASE_PCI("marketplace-voicebase-pci"), - MARKETPLACE_VOICEBASE_TRANSCRIPTION( - "marketplace-voicebase-transcription" - ), - MARKETPLACE_VOICEBASE_TRANSCRIPTION_CUSTOM_VOCABULARY( - "marketplace-voicebase-transcription-custom-vocabulary" - ), - MARKETPLACE_WEB_PURIFY_PROFANITY_FILTER( - "marketplace-web-purify-profanity-filter" - ), - MARKETPLACE_WHITEPAGES_PRO_CALLER_IDENTIFICATION( - "marketplace-whitepages-pro-caller-identification" - ), - MARKETPLACE_WHITEPAGES_PRO_PHONE_INTELLIGENCE( - "marketplace-whitepages-pro-phone-intelligence" - ), - MARKETPLACE_WHITEPAGES_PRO_PHONE_REPUTATION( - "marketplace-whitepages-pro-phone-reputation" - ), - MARKETPLACE_WOLFARM_SPOKEN_RESULTS( - "marketplace-wolfarm-spoken-results" - ), - MARKETPLACE_WOLFRAM_SHORT_ANSWER("marketplace-wolfram-short-answer"), - MARKETPLACE_YTICA_CONTACT_CENTER_REPORTING_ANALYTICS( - "marketplace-ytica-contact-center-reporting-analytics" - ), - MARKETPLAY_PAY_ADDONS_SHUTTLE_PAY_CONNECTOR( - "marketplay-pay-addons-shuttle-pay-connector" - ), - MEDIA_COMPOSER_MINUTES("media-composer-minutes"), - MEDIASTORAGE("mediastorage"), - MIN_SPEND_ADJUSTMENTS("min-spend-adjustments"), - MMS("mms"), - MMS_INBOUND("mms-inbound"), - MMS_INBOUND_LONGCODE("mms-inbound-longcode"), - MMS_INBOUND_SHORTCODE("mms-inbound-shortcode"), - MMS_INBOUND_TOLL_FREE("mms-inbound-toll-free"), - MMS_MESSAGES_CARRIERFEES("mms-messages-carrierfees"), - MMS_OUTBOUND("mms-outbound"), - MMS_OUTBOUND_LONGCODE("mms-outbound-longcode"), - MMS_OUTBOUND_SHORTCODE("mms-outbound-shortcode"), - MMS_OUTBOUND_TOLLFREE("mms-outbound-tollfree"), - MONITOR("monitor"), - MONITOR_READS("monitor-reads"), - MONITOR_STORAGE("monitor-storage"), - MONITOR_WRITES("monitor-writes"), - NOTIFY("notify"), - NOTIFY_ACTIONS_ATTEMPTS("notify-actions-attempts"), - NOTIFY_CHANNELS("notify-channels"), - NUMBER_FORMAT_LOOKUPS("number-format-lookups"), - PCHAT("pchat"), - PCHAT_ACTIONS("pchat-actions"), - PCHAT_APS("pchat-aps"), - PCHAT_CONV_MED_STORAGE("pchat-conv-med-storage"), - PCHAT_MESSAGES("pchat-messages"), - PCHAT_NOTIFICATIONS("pchat-notifications"), - PCHAT_READS("pchat-reads"), - PCHAT_USERS("pchat-users"), - PEER_TO_PEER_ROOMS_PARTICIPANT_MINUTES( - "peer-to-peer-rooms-participant-minutes" - ), - PFAX("pfax"), - PFAX_MINUTES("pfax-minutes"), - PFAX_MINUTES_INBOUND("pfax-minutes-inbound"), - PFAX_MINUTES_OUTBOUND("pfax-minutes-outbound"), - PFAX_PAGES("pfax-pages"), - PHONE_QUALITY_SCORE_LOOKUPS("phone-quality-score-lookups"), - PHONENUMBERS("phonenumbers"), - PHONENUMBERS_CPS("phonenumbers-cps"), - PHONENUMBERS_EMERGENCY("phonenumbers-emergency"), - PHONENUMBERS_LOCAL("phonenumbers-local"), - PHONENUMBERS_MOBILE("phonenumbers-mobile"), - PHONENUMBERS_PORTING("phonenumbers-porting"), - PHONENUMBERS_SETUPS("phonenumbers-setups"), - PHONENUMBERS_TOLLFREE("phonenumbers-tollfree"), - PREMIUMSUPPORT("premiumsupport"), - PREMIUMSUPPORT_PERCENTAGE_SPEND("premiumsupport-percentage-spend"), - PROGRAMMABLEVOICE_PLATFORM("programmablevoice-platform"), - PROGRAMMABLEVOICECONN_CLIENTSDK("programmablevoiceconn-clientsdk"), - PROGRAMMABLEVOICECONN_CLIENTSDK_INBOUND( - "programmablevoiceconn-clientsdk-inbound" - ), - PROGRAMMABLEVOICECONN_CLIENTSDK_OUTBOUND( - "programmablevoiceconn-clientsdk-outbound" - ), - PROGRAMMABLEVOICECONN_ONNET("programmablevoiceconn-onnet"), - PROGRAMMABLEVOICECONN_ONNET_INBOUND( - "programmablevoiceconn-onnet-inbound" - ), - PROGRAMMABLEVOICECONN_ONNET_OUTBOUND( - "programmablevoiceconn-onnet-outbound" - ), - PROGRAMMABLEVOICECONN_SIP("programmablevoiceconn-sip"), - PROGRAMMABLEVOICECONN_SIP_INBOUND("programmablevoiceconn-sip-inbound"), - PROGRAMMABLEVOICECONN_SIP_OUTBOUND( - "programmablevoiceconn-sip-outbound" - ), - PROGRAMMABLEVOICECONNECTIVITY("programmablevoiceconnectivity"), - PROXY("proxy"), - PROXY_ACTIVE_SESSIONS("proxy-active-sessions"), - PROXY_BUCKET_ADJUSTMENT("proxy-bucket-adjustment"), - PROXY_LICENSES("proxy-licenses"), - PSTNCONNECTIVITY("pstnconnectivity"), - PSTNCONNECTIVITY_INBOUND("pstnconnectivity-inbound"), - PSTNCONNECTIVITY_OUTBOUND("pstnconnectivity-outbound"), - PV("pv"), - PV_BASIC_ROOMS("pv-basic-rooms"), - PV_COMPOSITION_MEDIA_DOWNLOADED("pv-composition-media-downloaded"), - PV_COMPOSITION_MEDIA_ENCRYPTED("pv-composition-media-encrypted"), - PV_COMPOSITION_MEDIA_STORED("pv-composition-media-stored"), - PV_COMPOSITION_MINUTES("pv-composition-minutes"), - PV_RECORDING_COMPOSITIONS("pv-recording-compositions"), - PV_ROOM_PARTICIPANTS("pv-room-participants"), - PV_ROOM_PARTICIPANTS_AU1("pv-room-participants-au1"), - PV_ROOM_PARTICIPANTS_BR1("pv-room-participants-br1"), - PV_ROOM_PARTICIPANTS_IE1("pv-room-participants-ie1"), - PV_ROOM_PARTICIPANTS_JP1("pv-room-participants-jp1"), - PV_ROOM_PARTICIPANTS_SG1("pv-room-participants-sg1"), - PV_ROOM_PARTICIPANTS_US1("pv-room-participants-us1"), - PV_ROOM_PARTICIPANTS_US2("pv-room-participants-us2"), - PV_ROOMS("pv-rooms"), - PV_SIP_ENDPOINT_REGISTRATIONS("pv-sip-endpoint-registrations"), - RCS_MESSAGES("rcs-messages"), - REASSIGNED_NUMBER("reassigned-number"), - RECORDINGS("recordings"), - RECORDINGSTORAGE("recordingstorage"), - SHORTCODES("shortcodes"), - SHORTCODES_CUSTOMEROWNED("shortcodes-customerowned"), - SHORTCODES_MMS_ENABLEMENT("shortcodes-mms-enablement"), - SHORTCODES_MPS("shortcodes-mps"), - SHORTCODES_RANDOM("shortcodes-random"), - SHORTCODES_SETUP_FEES("shortcodes-setup-fees"), - SHORTCODES_UK("shortcodes-uk"), - SHORTCODES_VANITY("shortcodes-vanity"), - SIM_SWAP_LOOKUPS("sim-swap-lookups"), - SIP_SECURE_MEDIA("sip-secure-media"), - SMALL_GROUP_ROOMS("small-group-rooms"), - SMALL_GROUP_ROOMS_DATA_TRACK("small-group-rooms-data-track"), - SMALL_GROUP_ROOMS_PARTICIPANT_MINUTES( - "small-group-rooms-participant-minutes" - ), - SMS("sms"), - SMS_INBOUND("sms-inbound"), - SMS_INBOUND_LONGCODE("sms-inbound-longcode"), - SMS_INBOUND_SHORTCODE("sms-inbound-shortcode"), - SMS_INBOUND_TOLLFREE("sms-inbound-tollfree"), - SMS_MESSAGES_CARRIERFEES("sms-messages-carrierfees"), - SMS_MESSAGES_FEATURES("sms-messages-features"), - SMS_MESSAGES_FEATURES_ENGAGEMENT_SUITE( - "sms-messages-features-engagement-suite" - ), - SMS_MESSAGES_FEATURES_MESSAGE_REDACTION( - "sms-messages-features-message-redaction" - ), - SMS_MESSAGES_FEATURES_SENDERID("sms-messages-features-senderid"), - SMS_MPS("sms-mps"), - SMS_MPS_SHORTCODE("sms-mps-shortcode"), - SMS_MPS_TOLLFREE("sms-mps-tollfree"), - SMS_MPS_TOLLFREE_SETUP("sms-mps-tollfree-setup"), - SMS_NATIONAL_REGULATORY_PROTECTION( - "sms-national-regulatory-protection" - ), - SMS_OUTBOUND("sms-outbound"), - SMS_OUTBOUND_CONTENT_INSPECTION("sms-outbound-content-inspection"), - SMS_OUTBOUND_LONGCODE("sms-outbound-longcode"), - SMS_OUTBOUND_SHORTCODE("sms-outbound-shortcode"), - SMS_OUTBOUND_TOLLFREE("sms-outbound-tollfree"), - SMS_PUMPING_PROTECTION("sms-pumping-protection"), - SMS_PUMPING_RISK("sms-pumping-risk"), - SMSMESSAGES_BUCKET_ADJUSTMENTS("smsmessages-bucket-adjustments"), - SMSMESSAGES_OUTBOUND_DOMESTIC("smsmessages-outbound-domestic"), - SPEECH_RECOGNITION("speech-recognition"), - STUDIO_ENGAGEMENTS("studio-engagements"), - SYNC("sync"), - SYNC_ACTIONS("sync-actions"), - SYNC_ENDPOINT_HOURS("sync-endpoint-hours"), - SYNC_ENDPOINT_HOURS_ABOVE_DAILY_CAP( - "sync-endpoint-hours-above-daily-cap" - ), - TASKROUTER_TASKS("taskrouter-tasks"), - TOTALPRICE("totalprice"), - TRANSCRIPTIONS("transcriptions"), - TRUNKING_CPS("trunking-cps"), - TRUNKING_EMERGENCY_CALLS("trunking-emergency-calls"), - TRUNKING_ORIGINATION("trunking-origination"), - TRUNKING_ORIGINATION_LOCAL("trunking-origination-local"), - TRUNKING_ORIGINATION_MOBILE("trunking-origination-mobile"), - TRUNKING_ORIGINATION_TOLLFREE("trunking-origination-tollfree"), - TRUNKING_RECORDINGS("trunking-recordings"), - TRUNKING_SECURE("trunking-secure"), - TRUNKING_TERMINATION("trunking-termination"), - TTS_GOOGLE("tts-google"), - TURNMEGABYTES("turnmegabytes"), - TURNMEGABYTES_AUSTRALIA("turnmegabytes-australia"), - TURNMEGABYTES_BRASIL("turnmegabytes-brasil"), - TURNMEGABYTES_GERMANY("turnmegabytes-germany"), - TURNMEGABYTES_INDIA("turnmegabytes-india"), - TURNMEGABYTES_IRELAND("turnmegabytes-ireland"), - TURNMEGABYTES_JAPAN("turnmegabytes-japan"), - TURNMEGABYTES_SINGAPORE("turnmegabytes-singapore"), - TURNMEGABYTES_USEAST("turnmegabytes-useast"), - TURNMEGABYTES_USWEST("turnmegabytes-uswest"), - TWILIO_FOR_SALESFORCE("twilio-for-salesforce"), - TWILIO_FOR_SALESFORCE_LICENSES("twilio-for-salesforce-licenses"), - TWILIO_INTERCONNECT("twilio-interconnect"), - TWIML("twiml"), - USAGE_FLEX_VIDEO("usage-flex-video"), - USAGE_FUNCTIONS("usage-functions"), - USAGE_RCS_BASIC_MESSAGES_OUTBOUND("usage-rcs-basic-messages-outbound"), - USAGE_RCS_MESSAGES("usage-rcs-messages"), - USAGE_RCS_MESSAGES_INBOUND("usage-rcs-messages-inbound"), - USAGE_RCS_MESSAGING_CARRIER_FEES("usage-rcs-messaging-carrier-fees"), - USAGE_RCS_SINGLE_MESSAGES_OUTBOUND( - "usage-rcs-single-messages-outbound" - ), - VERIFY_PACKAGE_PLANS("verify-package-plans"), - VERIFY_PUSH("verify-push"), - VERIFY_SNA("verify-sna"), - VERIFY_TOTP("verify-totp"), - VERIFY_VOICE_SMS("verify-voice-sms"), - VERIFY_WHATSAPP_CONVERSATIONS_BUSINESS_INITIATED( - "verify-whatsapp-conversations-business-initiated" - ), - VERIFY_WHATSAPP_TEMPLATE_BUSINESS_INITIATED( - "verify-whatsapp-template-business-initiated" - ), - VIDEO_RECORDINGS("video-recordings"), - VIDEO_ROOMS_TURN_MEGABYTES("video-rooms-turn-megabytes"), - VIRTUAL_AGENT("virtual-agent"), - VOICE_INSIGHTS("voice-insights"), - VOICE_INSIGHTS_CLIENT_INSIGHTS_ON_DEMAND_MINUTE( - "voice-insights-client-insights-on-demand-minute" - ), - VOICE_INSIGHTS_PTSN_INSIGHTS_ON_DEMAND_MINUTE( - "voice-insights-ptsn-insights-on-demand-minute" - ), - VOICE_INSIGHTS_SIP_INTERFACE_INSIGHTS_ON_DEMAND_MINUTE( - "voice-insights-sip-interface-insights-on-demand-minute" - ), - VOICE_INSIGHTS_SIP_TRUNKING_INSIGHTS_ON_DEMAND_MINUTE( - "voice-insights-sip-trunking-insights-on-demand-minute" - ), - VOICE_INTELLIGENCE("voice-intelligence"), - VOICE_INTELLIGENCE_EIP_OPERATORS("voice-intelligence-eip-operators"), - VOICE_INTELLIGENCE_OPERATORS("voice-intelligence-operators"), - VOICE_INTELLIGENCE_TRANSCRIPTION("voice-intelligence-transcription"), - WDS("wds"), - WIRELESS("wireless"), - WIRELESS_DATA("wireless-data"), - WIRELESS_DATA_PAYG("wireless-data-payg"), - WIRELESS_DATA_PAYG_AFRICA("wireless-data-payg-africa"), - WIRELESS_DATA_PAYG_ASIA("wireless-data-payg-asia"), - WIRELESS_DATA_PAYG_CENTRALANDSOUTHAMERICA( - "wireless-data-payg-centralandsouthamerica" - ), - WIRELESS_DATA_PAYG_EUROPE("wireless-data-payg-europe"), - WIRELESS_DATA_PAYG_NORTHAMERICA("wireless-data-payg-northamerica"), - WIRELESS_DATA_PAYG_OCEANIA("wireless-data-payg-oceania"), - WIRELESS_DATA_QUOTA1("wireless-data-quota1"), - WIRELESS_DATA_QUOTA1_AFRICA("wireless-data-quota1-africa"), - WIRELESS_DATA_QUOTA1_ASIA("wireless-data-quota1-asia"), - WIRELESS_DATA_QUOTA1_CENTRALANDSOUTHAMERICA( - "wireless-data-quota1-centralandsouthamerica" - ), - WIRELESS_DATA_QUOTA1_EUROPE("wireless-data-quota1-europe"), - WIRELESS_DATA_QUOTA1_NORTHAMERICA("wireless-data-quota1-northamerica"), - WIRELESS_DATA_QUOTA1_OCEANIA("wireless-data-quota1-oceania"), - WIRELESS_DATA_QUOTA10("wireless-data-quota10"), - WIRELESS_DATA_QUOTA10_AFRICA("wireless-data-quota10-africa"), - WIRELESS_DATA_QUOTA10_ASIA("wireless-data-quota10-asia"), - WIRELESS_DATA_QUOTA10_CENTRALANDSOUTHAMERICA( - "wireless-data-quota10-centralandsouthamerica" - ), - WIRELESS_DATA_QUOTA10_EUROPE("wireless-data-quota10-europe"), - WIRELESS_DATA_QUOTA10_NORTHAMERICA( - "wireless-data-quota10-northamerica" - ), - WIRELESS_DATA_QUOTA10_OCEANIA("wireless-data-quota10-oceania"), - WIRELESS_DATA_QUOTA50("wireless-data-quota50"), - WIRELESS_DATA_QUOTA50_AFRICA("wireless-data-quota50-africa"), - WIRELESS_DATA_QUOTA50_ASIA("wireless-data-quota50-asia"), - WIRELESS_DATA_QUOTA50_CENTRALANDSOUTHAMERICA( - "wireless-data-quota50-centralandsouthamerica" - ), - WIRELESS_DATA_QUOTA50_EUROPE("wireless-data-quota50-europe"), - WIRELESS_DATA_QUOTA50_NORTHAMERICA( - "wireless-data-quota50-northamerica" - ), - WIRELESS_DATA_QUOTA50_OCEANIA("wireless-data-quota50-oceania"), - WIRELESS_DATA_QUOTACUSTOM("wireless-data-quotacustom"), - WIRELESS_DATA_QUOTACUSTOM_AFRICA("wireless-data-quotacustom-africa"), - WIRELESS_DATA_QUOTACUSTOM_ASIA("wireless-data-quotacustom-asia"), - WIRELESS_DATA_QUOTACUSTOM_CENTRALANDSOUTHAMERICA( - "wireless-data-quotacustom-centralandsouthamerica" - ), - WIRELESS_DATA_QUOTACUSTOM_EUROPE("wireless-data-quotacustom-europe"), - WIRELESS_DATA_QUOTACUSTOM_NORTHAMERICA( - "wireless-data-quotacustom-northamerica" - ), - WIRELESS_DATA_QUOTACUSTOM_OCEANIA("wireless-data-quotacustom-oceania"), - WIRELESS_MRC_PAYG("wireless-mrc-payg"), - WIRELESS_MRC_QUOTA1("wireless-mrc-quota1"), - WIRELESS_MRC_QUOTA10("wireless-mrc-quota10"), - WIRELESS_MRC_QUOTA50("wireless-mrc-quota50"), - WIRELESS_MRC_QUOTACUSTOM("wireless-mrc-quotacustom"), - WIRELESS_ORDERS("wireless-orders"), - WIRELESS_ORDERS_ARTWORK("wireless-orders-artwork"), - WIRELESS_ORDERS_BULK("wireless-orders-bulk"), - WIRELESS_ORDERS_ESIM("wireless-orders-esim"), - WIRELESS_ORDERS_STARTER("wireless-orders-starter"), - WIRELESS_QUOTAS("wireless-quotas"), - WIRELESS_SMS_AFRICA("wireless-sms-africa"), - WIRELESS_SMS_ASIA("wireless-sms-asia"), - WIRELESS_SMS_CENTRALANDSOUTHAMERICA( - "wireless-sms-centralandsouthamerica" - ), - WIRELESS_SMS_EUROPE("wireless-sms-europe"), - WIRELESS_SMS_NORTHAMERICA("wireless-sms-northamerica"), - WIRELESS_SMS_OCEANIA("wireless-sms-oceania"), - WIRELESS_SUPER_SIM("wireless-super-sim"), - WIRELESS_SUPER_SIM_DATA("wireless-super-sim-data"), - WIRELESS_SUPER_SIM_DATA_NORTH_AMERICA_USA( - "wireless-super-sim-data-north-america-usa" - ), - WIRELESS_SUPER_SIM_DATA_PAYG("wireless-super-sim-data-payg"), - WIRELESS_SUPER_SIM_DATA_PAYG_EUROPE( - "wireless-super-sim-data-payg-europe" - ), - WIRELESS_SUPER_SIM_DATA_PAYG_NORTH_AMERICA( - "wireless-super-sim-data-payg-north-america" - ), - WIRELESS_SUPER_SIM_HARDWARE("wireless-super-sim-hardware"), - WIRELESS_SUPER_SIM_HARDWARE_BULK("wireless-super-sim-hardware-bulk"), - WIRELESS_SUPER_SIM_SMSCOMMANDS("wireless-super-sim-smscommands"), - WIRELESS_SUPER_SIM_SMSCOMMANDS_AFRICA( - "wireless-super-sim-smscommands-africa" - ), - WIRELESS_SUPER_SIM_SMSCOMMANDS_ASIA( - "wireless-super-sim-smscommands-asia" - ), - WIRELESS_SUPER_SIM_SMSCOMMANDS_CENT_AND_SOUTH_AMERICA( - "wireless-super-sim-smscommands-cent-and-south-america" - ), - WIRELESS_SUPER_SIM_SMSCOMMANDS_EUROPE( - "wireless-super-sim-smscommands-europe" - ), - WIRELESS_SUPER_SIM_SMSCOMMANDS_NORTH_AMERICA( - "wireless-super-sim-smscommands-north-america" - ), - WIRELESS_SUPER_SIM_SMSCOMMANDS_OCEANIA( - "wireless-super-sim-smscommands-oceania" - ), - WIRELESS_SUPER_SIM_SUBSCRIPTION("wireless-super-sim-subscription"), - WIRELESS_SUPER_SIM_SUBSCRIPTION_PAYG( - "wireless-super-sim-subscription-payg" - ), - WIRELESS_USAGE("wireless-usage"), - WIRELESS_USAGE_COMMANDS("wireless-usage-commands"), - WIRELESS_USAGE_COMMANDS_AFRICA("wireless-usage-commands-africa"), - WIRELESS_USAGE_COMMANDS_ASIA("wireless-usage-commands-asia"), - WIRELESS_USAGE_COMMANDS_CENTRALANDSOUTHAMERICA( - "wireless-usage-commands-centralandsouthamerica" - ), - WIRELESS_USAGE_COMMANDS_EUROPE("wireless-usage-commands-europe"), - WIRELESS_USAGE_COMMANDS_HOME("wireless-usage-commands-home"), - WIRELESS_USAGE_COMMANDS_NORTHAMERICA( - "wireless-usage-commands-northamerica" - ), - WIRELESS_USAGE_COMMANDS_OCEANIA("wireless-usage-commands-oceania"), - WIRELESS_USAGE_COMMANDS_ROAMING("wireless-usage-commands-roaming"), - WIRELESS_USAGE_DATA("wireless-usage-data"), - WIRELESS_USAGE_DATA_AFRICA("wireless-usage-data-africa"), - WIRELESS_USAGE_DATA_ASIA("wireless-usage-data-asia"), - WIRELESS_USAGE_DATA_CENTRALANDSOUTHAMERICA( - "wireless-usage-data-centralandsouthamerica" - ), - WIRELESS_USAGE_DATA_CUSTOM_ADDITIONALMB( - "wireless-usage-data-custom-additionalmb" - ), - WIRELESS_USAGE_DATA_CUSTOM_FIRST5MB( - "wireless-usage-data-custom-first5mb" - ), - WIRELESS_USAGE_DATA_DOMESTIC_ROAMING( - "wireless-usage-data-domestic-roaming" - ), - WIRELESS_USAGE_DATA_EUROPE("wireless-usage-data-europe"), - WIRELESS_USAGE_DATA_INDIVIDUAL_ADDITIONALGB( - "wireless-usage-data-individual-additionalgb" - ), - WIRELESS_USAGE_DATA_INDIVIDUAL_FIRSTGB( - "wireless-usage-data-individual-firstgb" - ), - WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_CANADA( - "wireless-usage-data-international-roaming-canada" - ), - WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_INDIA( - "wireless-usage-data-international-roaming-india" - ), - WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_MEXICO( - "wireless-usage-data-international-roaming-mexico" - ), - WIRELESS_USAGE_DATA_NORTHAMERICA("wireless-usage-data-northamerica"), - WIRELESS_USAGE_DATA_OCEANIA("wireless-usage-data-oceania"), - WIRELESS_USAGE_DATA_POOLED("wireless-usage-data-pooled"), - WIRELESS_USAGE_DATA_POOLED_DOWNLINK( - "wireless-usage-data-pooled-downlink" - ), - WIRELESS_USAGE_DATA_POOLED_UPLINK("wireless-usage-data-pooled-uplink"), - WIRELESS_USAGE_MRC("wireless-usage-mrc"), - WIRELESS_USAGE_MRC_CUSTOM("wireless-usage-mrc-custom"), - WIRELESS_USAGE_MRC_INDIVIDUAL("wireless-usage-mrc-individual"), - WIRELESS_USAGE_MRC_POOLED("wireless-usage-mrc-pooled"), - WIRELESS_USAGE_MRC_SUSPENDED("wireless-usage-mrc-suspended"), - WIRELESS_USAGE_SMS("wireless-usage-sms"), - WIRELESS_USAGE_VOICE("wireless-usage-voice"), - A2P_FAST_TRACK_ONBOARDING("a2p-fast-track-onboarding"), - ADVISORY_SERVICES("advisory-services"), - ADVISORY_SERVICES_BILLED("advisory-services-billed"), - ADVISORY_SERVICES_CALL_TRACKING("advisory-services-call-tracking"), - ADVISORY_SERVICES_DATA_SERVICES("advisory-services-data-services"), - ADVISORY_SERVICES_EXPENSES("advisory-services-expenses"), - ADVISORY_SERVICES_SIP_TRUNKING("advisory-services-sip-trunking"), - ASSETS_REQUESTS("assets-requests"), - AUDIENCE_MINUTES_VIDEO("audience-minutes-video"), - AUTHY_BUCKET_ADJUSTMENT("authy-bucket-adjustment"), - AUTHY_SOFTWARE("authy-software"), - CALLERIDLOOKUPS_API("calleridlookups-api"), - CALLERIDLOOKUPS_PROGRAMMABLEVOICE("calleridlookups-programmablevoice"), - CALLERIDLOOKUPS_TRUNKING("calleridlookups-trunking"), - CALLS_TRUNKING_INBOUND_TOLLFREE_LOCAL( - "calls-trunking-inbound-tollfree-local" - ), - CALLS_TRUNKING_INBOUND_TOLLFREE_MOBILE( - "calls-trunking-inbound-tollfree-mobile" - ), - CHANNELS_WHATSAPP_CONVERSATION_FREE_1( - "channels-whatsapp-conversation-free-1" - ), - CONFERENCE("conference"), - CONVERSATIONAL_INSIGHTS("conversational-insights"), - CONVERSATIONAL_INSIGHTS_MESSAGES("conversational-insights-messages"), - CONVERSATIONAL_INSIGHTS_VOICE_MINUTES( - "conversational-insights-voice-minutes" - ), - DEMO("demo"), - DEMO_UC_SCRIPT_TEST("demo-uc-script-test"), - ELASTIC_SIP_TRUNKING("elastic-sip-trunking"), - ELASTIC_SIP_TRUNKING_CALL_TRANSFERS( - "elastic-sip-trunking-call-transfers" - ), - ENTERPRISE_HIPPA("enterprise-hippa"), - FLEX_NAMED_USERS("flex-named-users"), - FLEX_SPINSCI("flex-spinsci"), - FLEX_USERS_1("flex-users-1"), - FLEX_WFO_PREMIUM_SPEECH_ANALYTICS("flex-wfo-premium-speech-analytics"), - FLEX_XCELERATE("flex-xcelerate"), - FUNCTIONS_ROLLUP("functions-rollup"), - IMP_V1_USAGE("imp-v1-usage"), - IP_MESSAGING_ADDONS("ip-messaging-addons"), - IVR("ivr"), - IVR_CONVERSATIONAL("ivr-conversational"), - IVR_DTMF("ivr-dtmf"), - IVR_VIRTUALAGENT("ivr-virtualagent"), - LIVE("live"), - LIVE_MEDIA_RECORDING_MINUTES("live-media-recording-minutes"), - LONGCODE_MPS("longcode-mps"), - MARKETPLACE_ANALYTICS_ADDONS("marketplace-analytics-addons"), - MARKETPLACE_ISV_ADDONS("marketplace-isv-addons"), - MARKETPLACE_MESSAGING_ADDONS("marketplace-messaging-addons"), - MARKETPLACE_PHONENUMBERS_ADDONS("marketplace-phonenumbers-addons"), - MARKETPLACE_RECORDING_ADDONS("marketplace-recording-addons"), - MARKETPLACE_VIRTUALAGENT_ADDONS("marketplace-virtualagent-addons"), - MARKETPLAY_PAY_ADDONS_SHUTTLE_PAY_CONNECTOR_1( - "marketplay-pay-addons-shuttle-pay-connector-1" - ), - MARKETPLAY_PAY_ADDONS_STRIPE_PAY_CONNECTOR( - "marketplay-pay-addons-stripe-pay-connector" - ), - MMS_INBOUND_LONGCODE_CANADA("mms-inbound-longcode-canada"), - MMS_INBOUND_LONGCODE_UNITEDSTATES("mms-inbound-longcode-unitedstates"), - MMS_OUTBOUND_LONGCODE_CANADA("mms-outbound-longcode-canada"), - MMS_OUTBOUND_LONGCODE_UNITEDSTATES( - "mms-outbound-longcode-unitedstates" - ), - MMS_OUTBOUND_TOLL_FREE("mms-outbound-toll-free"), - NOTIFY_CHATAPPSANDOTHERCHANNELS("notify-chatappsandotherchannels"), - NOTIFY_NOTIFYSERVICES("notify-notifyservices"), - NOTIFY_PUSHNOTIFICATIONS("notify-pushnotifications"), - PAYMENT_GATEWAY_CONNECTORS("payment-gateway-connectors"), - PAYMENT_SOLUTIONS("payment-solutions"), - PCHAT_BUCKET_ADJUSTMENT("pchat-bucket-adjustment"), - PHONENUMBERS_NUMBERS("phonenumbers-numbers"), - PROG_VOICE_CLIENT_ANDROID("prog-voice-client-android"), - PROG_VOICE_CLIENT_ANDROID_INBOUND("prog-voice-client-android-inbound"), - PROG_VOICE_CLIENT_ANDROID_OUTBOUND( - "prog-voice-client-android-outbound" - ), - PROG_VOICE_CLIENT_IOS("prog-voice-client-ios"), - PROG_VOICE_CLIENT_IOS_INBOUND("prog-voice-client-ios-inbound"), - PROG_VOICE_CLIENT_IOS_OUTBOUND("prog-voice-client-ios-outbound"), - PROG_VOICE_CLIENT_SDK("prog-voice-client-sdk"), - PROG_VOICE_CLIENT_WEB("prog-voice-client-web"), - PROG_VOICE_CLIENT_WEB_INBOUND("prog-voice-client-web-inbound"), - PROG_VOICE_CLIENT_WEB_OUTBOUND("prog-voice-client-web-outbound"), - PROGRAMMABLEVOICECONNECTIVITY_MEDIA_STREAMS( - "programmablevoiceconnectivity-media-streams" - ), - PSTNCONNECTIVITY_BYOC("pstnconnectivity-byoc"), - PSTNCONNECTIVITY_EMERGENCY("pstnconnectivity-emergency"), - PSTNCONNECTIVITY_MINUTES("pstnconnectivity-minutes"), - PSTNCONNECTIVITY_MINUTES_1("pstnconnectivity-minutes-1"), - PSTNCONNECTIVITY_MINUTESINBOUNDLOCAL( - "pstnconnectivity-minutesinboundlocal" - ), - PSTNCONNECTIVITY_MINUTESINBOUNDMOBILE( - "pstnconnectivity-minutesinboundmobile" - ), - PSTNCONNECTIVITY_MINUTESINBOUNDTOLLFREE( - "pstnconnectivity-minutesinboundtollfree" - ), - PSTNCONNECTIVITY_MINUTESINBOUNDTOLLFREELOCAL( - "pstnconnectivity-minutesinboundtollfreelocal" - ), - PSTNCONNECTIVITY_MINUTESINBOUNDTOLLFREEMOBILE( - "pstnconnectivity-minutesinboundtollfreemobile" - ), - PV_ROOM_HOURS("pv-room-hours"), - PV_ROOM_SIMULTANEOUS_PARTICIPANT_CONNECTIONS( - "pv-room-simultaneous-participant-connections" - ), - PVIDEO_ROOM_HOURS_AU1("pvideo-room-hours-au1"), - PVIDEO_ROOM_HOURS_BR1("pvideo-room-hours-br1"), - PVIDEO_ROOM_HOURS_IE1("pvideo-room-hours-ie1"), - PVIDEO_ROOM_HOURS_JP1("pvideo-room-hours-jp1"), - PVIDEO_ROOM_HOURS_SG1("pvideo-room-hours-sg1"), - PVIDEO_ROOM_HOURS_US1("pvideo-room-hours-us1"), - PVIDEO_ROOM_HOURS_US2("pvideo-room-hours-us2"), - RECORDINGS_ENCRYPTED("recordings-encrypted"), - SHORT_CODE_SETUP_FEES("short-code-setup-fees"), - SHORTCODES_MESSAGES_INBOUND("shortcodes-messages-inbound"), - SHORTCODES_MESSAGES_OUTBOUND("shortcodes-messages-outbound"), - SMS_MESSAGES_REGISTRATIONFEES("sms-messages-registrationfees"), - SMS_MMS_PENALTY_FEES("sms-mms-penalty-fees"), - SMS_MMS_PENALTY_FEES_1("sms-mms-penalty-fees-1"), - SMS_PUMPING_PROTECTION_NON_USCA("sms-pumping-protection-non-usca"), - SMS_PUMPING_PROTECTION_USCA("sms-pumping-protection-usca"), - STUDIO("studio"), - STUDIO_MONTHLY_FEES("studio-monthly-fees"), - SUPERSIM("supersim"), - TASK_ROUTER("task-router"), - TASK_ROUTER_WORKERS("task-router-workers"), - TEST_QUOTA_BUCKETS("test-quota-buckets"), - TEST_UC_SCRIPT_1("test-uc-script-1"), - TEST_UC_SCRIPT_DEMO_2("test-uc-script-demo-2"), - TEXT_TO_SPEECH("text-to-speech"), - TME("tme"), - TTS_BASIC("tts-basic"), - TWILIO_EDITIONS("twilio-editions"), - TWILIO_INTERCONNECT_CALIFORNIA("twilio-interconnect-california"), - TWILIO_INTERCONNECT_CALIFORNIA_MONTHLY( - "twilio-interconnect-california-monthly" - ), - TWILIO_INTERCONNECT_CALIFORNIA_SETUP( - "twilio-interconnect-california-setup" - ), - TWILIO_INTERCONNECT_FRANKFURT("twilio-interconnect-frankfurt"), - TWILIO_INTERCONNECT_FRANKFURT_MO("twilio-interconnect-frankfurt-mo"), - TWILIO_INTERCONNECT_FRANKFURT_SETUP( - "twilio-interconnect-frankfurt-setup" - ), - TWILIO_INTERCONNECT_LONDON("twilio-interconnect-london"), - TWILIO_INTERCONNECT_LONDON_MO("twilio-interconnect-london-mo"), - TWILIO_INTERCONNECT_LONDON_SETUP("twilio-interconnect-london-setup"), - TWILIO_INTERCONNECT_SAO_PAULO("twilio-interconnect-sao-paulo"), - TWILIO_INTERCONNECT_SAO_PAULO_MONTHLY( - "twilio-interconnect-sao-paulo-monthly" - ), - TWILIO_INTERCONNECT_SAO_PAULO_SETUP( - "twilio-interconnect-sao-paulo-setup" - ), - TWILIO_INTERCONNECT_SINGAPORE("twilio-interconnect-singapore"), - TWILIO_INTERCONNECT_SINGAPORE_MO("twilio-interconnect-singapore-mo"), - TWILIO_INTERCONNECT_SINGAPORE_SETUP( - "twilio-interconnect-singapore-setup" - ), - TWILIO_INTERCONNECT_SYDNEY("twilio-interconnect-sydney"), - TWILIO_INTERCONNECT_SYDNEY_MO("twilio-interconnect-sydney-mo"), - TWILIO_INTERCONNECT_SYDNEY_SETUP("twilio-interconnect-sydney-setup"), - TWILIO_INTERCONNECT_TOKYO("twilio-interconnect-tokyo"), - TWILIO_INTERCONNECT_TOKYO_MO("twilio-interconnect-tokyo-mo"), - TWILIO_INTERCONNECT_TOKYO_SETUP("twilio-interconnect-tokyo-setup"), - TWILIO_INTERCONNECT_VA("twilio-interconnect-va"), - TWILIO_INTERCONNECT_VA_MO("twilio-interconnect-va-mo"), - TWILIO_INTERCONNECT_VA_SETUP("twilio-interconnect-va-setup"), - TWIML_VERBS("twiml-verbs"), - TWIML_VERBS_SAY("twiml-verbs-say"), - USAGE_PROGRAMMABLE_MESSAGING_ENGAGEMENT_SUITE( - "usage-programmable-messaging-engagement-suite" - ), - USAGE_PROGRAMMABLE_MESSAGING_FEES_SERVICES( - "usage-programmable-messaging-fees-services" - ), - VERIFY_OUTBOUND_EMAIL("verify-outbound-email"), - VERIFY_PACKAGED_PLANS("verify-packaged-plans"), - VERIFY_SILENT_NETWORK_AUTH("verify-silent-network-auth"), - VERIFY_VOICE_AND_SMS("verify-voice-and-sms"), - VOICE_INSIGHTS_CLIENT_INSIGHTS_MONTHY_COMMIT( - "voice-insights-client-insights-monthy-commit" - ), - WIRELESS_DATA_PAYG_ASIA_AFG("wireless-data-payg-asia-afg"), - WIRELESS_MULTI_IMSI_SIM_COMMANDS("wireless-multi-imsi-sim-commands"), - WIRELESS_MULTI_IMSI_SIM_COMMANDS_USA( - "wireless-multi-imsi-sim-commands-usa" - ), - WIRELESS_MULTI_IMSI_SIM_DATA("wireless-multi-imsi-sim-data"), - WIRELESS_MULTI_IMSI_SIM_DATA_EU28("wireless-multi-imsi-sim-data-eu28"), - WIRELESS_MULTI_IMSI_SIM_DATA_USA("wireless-multi-imsi-sim-data-usa"), - WIRELESS_MULTI_IMSI_SIM_MONTHLY_FEES( - "wireless-multi-imsi-sim-monthly-fees" - ), - WIRELESS_MULTI_IMSI_SIM_USAGE("wireless-multi-imsi-sim-usage"), - WIRELESS_SUPER_SIM_DATA_NORTH_AMERICA( - "wireless-super-sim-data-north-america" - ), - WIRELESS_SUPER_SIM_USAGE("wireless-super-sim-usage"); - - private final String value; - - private Category(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static Category forValue(final String value) { - return Promoter.enumFromString(value, Category.values()); - } - } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/usage/record/TodayReader.java b/src/main/java/com/twilio/rest/api/v2010/account/usage/record/TodayReader.java index 3ea401df3d..daac07498b 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/usage/record/TodayReader.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/usage/record/TodayReader.java @@ -32,7 +32,7 @@ public class TodayReader extends Reader { private String pathAccountSid; - private Today.Category category; + private String category; private LocalDate startDate; private LocalDate endDate; private Boolean includeSubaccounts; @@ -44,7 +44,7 @@ public TodayReader(final String pathAccountSid) { this.pathAccountSid = pathAccountSid; } - public TodayReader setCategory(final Today.Category category) { + public TodayReader setCategory(final String category) { this.category = category; return this; } @@ -166,7 +166,7 @@ public Page getPage( private void addQueryParams(final Request request) { if (category != null) { - request.addQueryParam("Category", category.toString()); + request.addQueryParam("Category", category); } if (startDate != null) { request.addQueryParam( diff --git a/src/main/java/com/twilio/rest/api/v2010/account/usage/record/Yearly.java b/src/main/java/com/twilio/rest/api/v2010/account/usage/record/Yearly.java index 71e97db657..aea93b7084 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/usage/record/Yearly.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/usage/record/Yearly.java @@ -24,7 +24,6 @@ import com.twilio.base.Resource; import com.twilio.converter.CurrencyDeserializer; import com.twilio.converter.DateConverter; -import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import java.io.IOException; @@ -42,7 +41,7 @@ @ToString public class Yearly extends Resource { - private static final long serialVersionUID = 266687924235941L; + private static final long serialVersionUID = 158026917970511L; public static YearlyReader reader() { return new YearlyReader(); @@ -98,7 +97,7 @@ public static Yearly fromJson( private final String accountSid; private final String apiVersion; private final String asOf; - private final Yearly.Category category; + private final String category; private final String count; private final String countUnit; private final String description; @@ -116,7 +115,7 @@ private Yearly( @JsonProperty("account_sid") final String accountSid, @JsonProperty("api_version") final String apiVersion, @JsonProperty("as_of") final String asOf, - @JsonProperty("category") final Yearly.Category category, + @JsonProperty("category") final String category, @JsonProperty("count") final String count, @JsonProperty("count_unit") final String countUnit, @JsonProperty("description") final String description, @@ -163,7 +162,7 @@ public final String getAsOf() { return this.asOf; } - public final Yearly.Category getCategory() { + public final String getCategory() { return this.category; } @@ -262,945 +261,4 @@ public int hashCode() { usageUnit ); } - - public enum Category { - A2P_10DLC_REGISTRATIONFEES_BRANDREGISTRATION( - "a2p-10dlc-registrationfees-brandregistration" - ), - A2P_10DLC_REGISTRATIONFEES_BV("a2p-10dlc-registrationfees-bv"), - A2P_10DLC_REGISTRATIONFEES_CAMPAIGNCHARGES( - "a2p-10dlc-registrationfees-campaigncharges" - ), - A2P_10DLC_REGISTRATIONFEES_CAMPAIGNREGISTRATION( - "a2p-10dlc-registrationfees-campaignregistration" - ), - A2P_10DLC_REGISTRATIONFEES_CAMPAIGNVETTING( - "a2p-10dlc-registrationfees-campaignvetting" - ), - A2P_10DLC_REGISTRATIONFEES_MONTHLY( - "a2p-10dlc-registrationfees-monthly" - ), - A2P_10DLC_REGISTRATIONFEES_ONETIME( - "a2p-10dlc-registrationfees-onetime" - ), - A2P_REGISTRATION_FEES("a2p-registration-fees"), - ACCOUNT_SECURITY("account-security"), - AGENT_CONFERENCE("agent-conference"), - AGENT_COPILOT("agent-copilot"), - AGENT_COPILOT_MESSAGES("agent-copilot-messages"), - AGENT_COPILOT_PARTICIPANT_MINUTES("agent-copilot-participant-minutes"), - AI_ASSISTANTS("ai-assistants"), - AI_ASSISTANTS_VOICE("ai-assistants-voice"), - AMAZON_POLLY("amazon-polly"), - ANSWERING_MACHINE_DETECTION("answering-machine-detection"), - ASSETS("assets"), - AUDIENCE_MINUTES("audience-minutes"), - AUDIENCE_MINUTES_AUDIO("audience-minutes-audio"), - AUTHY_AUTHENTICATIONS("authy-authentications"), - AUTHY_CALLS_OUTBOUND("authy-calls-outbound"), - AUTHY_EMAIL_AUTHENTICATIONS("authy-email-authentications"), - AUTHY_MONTHLY_FEES("authy-monthly-fees"), - AUTHY_OUTBOUND_EMAIL("authy-outbound-email"), - AUTHY_PHONE_INTELLIGENCE("authy-phone-intelligence"), - AUTHY_PHONE_VERIFICATIONS("authy-phone-verifications"), - AUTHY_SMS_OUTBOUND("authy-sms-outbound"), - AUTHY_VERIFY_EMAIL_VERIFICATIONS("authy-verify-email-verifications"), - AUTHY_VERIFY_OUTBOUND_EMAIL("authy-verify-outbound-email"), - AUTOPILOT("autopilot"), - AUTOPILOT_HOME_ASSISTANTS("autopilot-home-assistants"), - AUTOPILOT_MESSAGING("autopilot-messaging"), - AUTOPILOT_OTHER("autopilot-other"), - AUTOPILOT_VOICE("autopilot-voice"), - BASIC_PEER_TO_PEER_ROOMS_PARTICIPANT_MINUTES( - "basic-peer-to-peer-rooms-participant-minutes" - ), - BRANDED_CALLING("branded-calling"), - BUNDLE_SMS_BUCKET("bundle-sms-bucket"), - BUNDLE_SUBSCRIPTION_FEES("bundle-subscription-fees"), - CALL_FORWARDING_LOOKUPS("call-forwarding-lookups"), - CALL_PROGESS_EVENTS("call-progess-events"), - CALLERIDLOOKUPS("calleridlookups"), - CALLS("calls"), - CALLS_CLIENT("calls-client"), - CALLS_EMERGENCY("calls-emergency"), - CALLS_GLOBALCONFERENCE("calls-globalconference"), - CALLS_INBOUND("calls-inbound"), - CALLS_INBOUND_LOCAL("calls-inbound-local"), - CALLS_INBOUND_MOBILE("calls-inbound-mobile"), - CALLS_INBOUND_TOLLFREE("calls-inbound-tollfree"), - CALLS_INBOUND_TOLLFREE_LOCAL("calls-inbound-tollfree-local"), - CALLS_INBOUND_TOLLFREE_MOBILE("calls-inbound-tollfree-mobile"), - CALLS_MEDIA_STREAM_MINUTES("calls-media-stream-minutes"), - CALLS_OUTBOUND("calls-outbound"), - CALLS_PAY_VERB_TRANSACTIONS("calls-pay-verb-transactions"), - CALLS_RECORDINGS("calls-recordings"), - CALLS_SIP("calls-sip"), - CALLS_SIP_INBOUND("calls-sip-inbound"), - CALLS_SIP_OUTBOUND("calls-sip-outbound"), - CALLS_TEXT_TO_SPEECH("calls-text-to-speech"), - CALLS_TRANSFERS("calls-transfers"), - CARRIER_LOOKUPS("carrier-lookups"), - CATEGORY("category"), - CHANNELS("channels"), - CHANNELS_MESSAGING("channels-messaging"), - CHANNELS_MESSAGING_INBOUND("channels-messaging-inbound"), - CHANNELS_MESSAGING_OUTBOUND("channels-messaging-outbound"), - CHANNELS_WHATSAPP("channels-whatsapp"), - CHANNELS_WHATSAPP_CONVERSATION_AUTHENTICATION( - "channels-whatsapp-conversation-authentication" - ), - CHANNELS_WHATSAPP_CONVERSATION_FREE( - "channels-whatsapp-conversation-free" - ), - CHANNELS_WHATSAPP_CONVERSATION_MARKETING( - "channels-whatsapp-conversation-marketing" - ), - CHANNELS_WHATSAPP_CONVERSATION_SERVICE( - "channels-whatsapp-conversation-service" - ), - CHANNELS_WHATSAPP_CONVERSATION_UTILITY( - "channels-whatsapp-conversation-utility" - ), - CHANNELS_WHATSAPP_INBOUND("channels-whatsapp-inbound"), - CHANNELS_WHATSAPP_OUTBOUND("channels-whatsapp-outbound"), - CHANNELS_WHATSAPP_SERVICE("channels-whatsapp-service"), - CHANNELS_WHATSAPP_TEMPLATE_AUTHENTICATION( - "channels-whatsapp-template-authentication" - ), - CHANNELS_WHATSAPP_TEMPLATE_MARKETING( - "channels-whatsapp-template-marketing" - ), - CHANNELS_WHATSAPP_TEMPLATE_SERVICE( - "channels-whatsapp-template-service" - ), - CHANNELS_WHATSAPP_TEMPLATE_UTILITY( - "channels-whatsapp-template-utility" - ), - CHAT_VIRTUAL_AGENT("chat-virtual-agent"), - CONVERSATION_RELAY("conversation-relay"), - CONVERSATIONS("conversations"), - CONVERSATIONS_API_REQUESTS("conversations-api-requests"), - CONVERSATIONS_CONVERSATION_EVENTS("conversations-conversation-events"), - CONVERSATIONS_ENDPOINT_CONNECTIVITY( - "conversations-endpoint-connectivity" - ), - CONVERSATIONS_EVENTS("conversations-events"), - CONVERSATIONS_PARTICIPANT_EVENTS("conversations-participant-events"), - CONVERSATIONS_PARTICIPANTS("conversations-participants"), - CPS("cps"), - CREDIT_TRANSFER("credit-transfer"), - EMAIL("email"), - EMERGING_TECH("emerging-tech"), - ENGAGEMENT_SUITE_PACKAGED_PLANS("engagement-suite-packaged-plans"), - ENHANCED_LINE_TYPE_LOOKUPS("enhanced-line-type-lookups"), - ENTERPRISE("enterprise"), - EVENTS("events"), - EXPERIMENT_FRANCE_SMS("experiment-france-sms"), - EXPERIMENT_INDIA_SMS("experiment-india-sms"), - EXPERIMENT_UK_SMS("experiment-uk-sms"), - FAILED_MESSAGE_PROCESSING_FEE("failed-message-processing-fee"), - FLEX("flex"), - FLEX_ACTIVE_USER_HOURS("flex-active-user-hours"), - FLEX_CONCURRENT_USERS("flex-concurrent-users"), - FLEX_CONVERSATIONAL_INSIGHTS("flex-conversational-insights"), - FLEX_CONVERSATIONAL_INSIGHTS_MESSAGES( - "flex-conversational-insights-messages" - ), - FLEX_CONVERSATIONAL_INSIGHTS_VOICE_MINUTES( - "flex-conversational-insights-voice-minutes" - ), - FLEX_EMAIL_USAGE("flex-email-usage"), - FLEX_MESSAGING_USAGE("flex-messaging-usage"), - FLEX_PARTNER_SPINSCI("flex-partner-spinsci"), - FLEX_PARTNER_XCELERATE("flex-partner-xcelerate"), - FLEX_RESELLER_ECOSYSTEM("flex-reseller-ecosystem"), - FLEX_UNIQUE_USER("flex-unique-user"), - FLEX_USAGE("flex-usage"), - FLEX_USERS("flex-users"), - FLEX_VOICE_MINUTE("flex-voice-minute"), - FLEX_YTICA("flex-ytica"), - FRAUD_LOOKUPS("fraud-lookups"), - FRONTLINE("frontline"), - FRONTLINE_USERS("frontline-users"), - FUNCTIONS("functions"), - GENERIC_PAY_TRANSACTIONS("generic-pay-transactions"), - GROUP_ROOMS("group-rooms"), - GROUP_ROOMS_DATA_TRACK("group-rooms-data-track"), - GROUP_ROOMS_ENCRYPTED_MEDIA_RECORDED( - "group-rooms-encrypted-media-recorded" - ), - GROUP_ROOMS_MEDIA_DOWNLOADED("group-rooms-media-downloaded"), - GROUP_ROOMS_MEDIA_RECORDED("group-rooms-media-recorded"), - GROUP_ROOMS_MEDIA_ROUTED("group-rooms-media-routed"), - GROUP_ROOMS_MEDIA_STORED("group-rooms-media-stored"), - GROUP_ROOMS_PARTICIPANT_MINUTES("group-rooms-participant-minutes"), - GROUP_ROOMS_RECORDED_MINUTES("group-rooms-recorded-minutes"), - IP_MESSAGING("ip-messaging"), - IP_MESSAGING_COMMANDS("ip-messaging-commands"), - IP_MESSAGING_DATA_STORAGE("ip-messaging-data-storage"), - IP_MESSAGING_DATA_TRANSFER("ip-messaging-data-transfer"), - IP_MESSAGING_ENDPOINT_CONNECTIVITY( - "ip-messaging-endpoint-connectivity" - ), - IVR_VIRTUAL_AGENT_CUSTOM_VOICES("ivr-virtual-agent-custom-voices"), - IVR_VIRTUAL_AGENT_GENAI("ivr-virtual-agent-genai"), - LINE_STATUS_LOOKUPS("line-status-lookups"), - LIVE_ACTIVITY_LOOKUPS("live-activity-lookups"), - LOOKUP_BUCKET_ADJUSTMENT("lookup-bucket-adjustment"), - LOOKUP_IDENTITY_MATCH("lookup-identity-match"), - LOOKUPS("lookups"), - MARKETPLACE("marketplace"), - MARKETPLACE_ALGORITHMIA_NAMED_ENTITY_RECOGNITION( - "marketplace-algorithmia-named-entity-recognition" - ), - MARKETPLACE_CADENCE_TRANSCRIPTION("marketplace-cadence-transcription"), - MARKETPLACE_CADENCE_TRANSLATION("marketplace-cadence-translation"), - MARKETPLACE_CAPIO_SPEECH_TO_TEXT("marketplace-capio-speech-to-text"), - MARKETPLACE_CONVRIZA_ABABA("marketplace-convriza-ababa"), - MARKETPLACE_DEEPGRAM_PHRASE_DETECTOR( - "marketplace-deepgram-phrase-detector" - ), - MARKETPLACE_DEEPGRAM_TRANSCRIPTION( - "marketplace-deepgram-transcription" - ), - MARKETPLACE_DEEPGRAM_TRANSCRIPTION_BASE( - "marketplace-deepgram-transcription-base" - ), - MARKETPLACE_DEEPGRAM_TRANSSCRIPTION_ENHANCED( - "marketplace-deepgram-transscription-enhanced" - ), - MARKETPLACE_DIGITAL_SEGMENT_BUSINESS_INFO( - "marketplace-digital-segment-business-info" - ), - MARKETPLACE_FACEBOOK_OFFLINE_CONVERSIONS( - "marketplace-facebook-offline-conversions" - ), - MARKETPLACE_GOOGLE_SPEECH_TO_TEXT("marketplace-google-speech-to-text"), - MARKETPLACE_IBM_WATSON_MESSAGE_INSIGHTS( - "marketplace-ibm-watson-message-insights" - ), - MARKETPLACE_IBM_WATSON_MESSAGE_SENTIMENT( - "marketplace-ibm-watson-message-sentiment" - ), - MARKETPLACE_IBM_WATSON_RECORDING_ANALYSIS( - "marketplace-ibm-watson-recording-analysis" - ), - MARKETPLACE_IBM_WATSON_TONE_ANALYZER( - "marketplace-ibm-watson-tone-analyzer" - ), - MARKETPLACE_ICEHOOK_SYSTEMS_SCOUT("marketplace-icehook-systems-scout"), - MARKETPLACE_INFOGROUP_DATAAXLE_BIZINFO( - "marketplace-infogroup-dataaxle-bizinfo" - ), - MARKETPLACE_KEEN_IO_CONTACT_CENTER_ANALYTICS( - "marketplace-keen-io-contact-center-analytics" - ), - MARKETPLACE_MARCHEX_CLEANCALL("marketplace-marchex-cleancall"), - MARKETPLACE_MARCHEX_RECORDING_ANALYSIS( - "marketplace-marchex-recording-analysis" - ), - MARKETPLACE_MARCHEX_SENTIMENT_ANALYSIS_FOR_SMS( - "marketplace-marchex-sentiment-analysis-for-sms" - ), - MARKETPLACE_MARKETPLACE_NEXTCALLER_SOCIAL_ID( - "marketplace-marketplace-nextcaller-social-id" - ), - MARKETPLACE_MOBILE_COMMONS_OPT_OUT_CLASSIFIER( - "marketplace-mobile-commons-opt-out-classifier" - ), - MARKETPLACE_NEXIWAVE_VOICEMAIL_TO_TEXT( - "marketplace-nexiwave-voicemail-to-text" - ), - MARKETPLACE_NEXTCALLER_ADVANCED_CALLER_IDENTIFICATION( - "marketplace-nextcaller-advanced-caller-identification" - ), - MARKETPLACE_NOMOROBO_SPAM_SCORE("marketplace-nomorobo-spam-score"), - MARKETPLACE_PAY_ADDONS("marketplace-pay-addons"), - MARKETPLACE_PAY_ADDONS_BASECOMMERCE_PAY_CONNECTOR( - "marketplace-pay-addons-basecommerce-pay-connector" - ), - MARKETPLACE_PAY_ADDONS_BRAINTREE_PAY_CONNECTOR( - "marketplace-pay-addons-braintree-pay-connector" - ), - MARKETPLACE_PAY_ADDONS_CARDCONNECT_PAY_CONNECTOR( - "marketplace-pay-addons-cardconnect-pay-connector" - ), - MARKETPLACE_PAY_ADDONS_CHASE_PAY_CONNECTOR( - "marketplace-pay-addons-chase-pay-connector" - ), - MARKETPLACE_PAY_ADDONS_SHUTTLE_PAY_CONNECTOR( - "marketplace-pay-addons-shuttle-pay-connector" - ), - MARKETPLACE_PAY_ADDONS_STRIPE_PAY_CONNECTOR( - "marketplace-pay-addons-stripe-pay-connector" - ), - MARKETPLACE_PAYFONE_TCPA_COMPLIANCE( - "marketplace-payfone-tcpa-compliance" - ), - MARKETPLACE_POLY_AI_CONNECTOR("marketplace-poly-ai-connector"), - MARKETPLACE_REALPHONEVALIDATION("marketplace-realphonevalidation"), - MARKETPLACE_REMEETING_AUTOMATIC_SPEECH_RECOGNITION( - "marketplace-remeeting-automatic-speech-recognition" - ), - MARKETPLACE_SPOKE_PHONE_LICENSE_PRO( - "marketplace-spoke-phone-license-pro" - ), - MARKETPLACE_SPOKE_PHONE_LICENSE_STANDARD( - "marketplace-spoke-phone-license-standard" - ), - MARKETPLACE_TCPA_DEFENSE_SOLUTIONS_BLACKLIST_FEED( - "marketplace-tcpa-defense-solutions-blacklist-feed" - ), - MARKETPLACE_TELO_OPENCNAM("marketplace-telo-opencnam"), - MARKETPLACE_TRESTLE_SOLUTIONS_CALLER_IDENTIFICATION( - "marketplace-trestle-solutions-caller-identification" - ), - MARKETPLACE_TRUECNAM_TRUE_SPAM("marketplace-truecnam-true-spam"), - MARKETPLACE_TWILIO_CALLER_NAME_LOOKUP_US( - "marketplace-twilio-caller-name-lookup-us" - ), - MARKETPLACE_TWILIO_CARRIER_INFORMATION_LOOKUP( - "marketplace-twilio-carrier-information-lookup" - ), - MARKETPLACE_VOICEBASE_PCI("marketplace-voicebase-pci"), - MARKETPLACE_VOICEBASE_TRANSCRIPTION( - "marketplace-voicebase-transcription" - ), - MARKETPLACE_VOICEBASE_TRANSCRIPTION_CUSTOM_VOCABULARY( - "marketplace-voicebase-transcription-custom-vocabulary" - ), - MARKETPLACE_WEB_PURIFY_PROFANITY_FILTER( - "marketplace-web-purify-profanity-filter" - ), - MARKETPLACE_WHITEPAGES_PRO_CALLER_IDENTIFICATION( - "marketplace-whitepages-pro-caller-identification" - ), - MARKETPLACE_WHITEPAGES_PRO_PHONE_INTELLIGENCE( - "marketplace-whitepages-pro-phone-intelligence" - ), - MARKETPLACE_WHITEPAGES_PRO_PHONE_REPUTATION( - "marketplace-whitepages-pro-phone-reputation" - ), - MARKETPLACE_WOLFARM_SPOKEN_RESULTS( - "marketplace-wolfarm-spoken-results" - ), - MARKETPLACE_WOLFRAM_SHORT_ANSWER("marketplace-wolfram-short-answer"), - MARKETPLACE_YTICA_CONTACT_CENTER_REPORTING_ANALYTICS( - "marketplace-ytica-contact-center-reporting-analytics" - ), - MARKETPLAY_PAY_ADDONS_SHUTTLE_PAY_CONNECTOR( - "marketplay-pay-addons-shuttle-pay-connector" - ), - MEDIA_COMPOSER_MINUTES("media-composer-minutes"), - MEDIASTORAGE("mediastorage"), - MIN_SPEND_ADJUSTMENTS("min-spend-adjustments"), - MMS("mms"), - MMS_INBOUND("mms-inbound"), - MMS_INBOUND_LONGCODE("mms-inbound-longcode"), - MMS_INBOUND_SHORTCODE("mms-inbound-shortcode"), - MMS_INBOUND_TOLL_FREE("mms-inbound-toll-free"), - MMS_MESSAGES_CARRIERFEES("mms-messages-carrierfees"), - MMS_OUTBOUND("mms-outbound"), - MMS_OUTBOUND_LONGCODE("mms-outbound-longcode"), - MMS_OUTBOUND_SHORTCODE("mms-outbound-shortcode"), - MMS_OUTBOUND_TOLLFREE("mms-outbound-tollfree"), - MONITOR("monitor"), - MONITOR_READS("monitor-reads"), - MONITOR_STORAGE("monitor-storage"), - MONITOR_WRITES("monitor-writes"), - NOTIFY("notify"), - NOTIFY_ACTIONS_ATTEMPTS("notify-actions-attempts"), - NOTIFY_CHANNELS("notify-channels"), - NUMBER_FORMAT_LOOKUPS("number-format-lookups"), - PCHAT("pchat"), - PCHAT_ACTIONS("pchat-actions"), - PCHAT_APS("pchat-aps"), - PCHAT_CONV_MED_STORAGE("pchat-conv-med-storage"), - PCHAT_MESSAGES("pchat-messages"), - PCHAT_NOTIFICATIONS("pchat-notifications"), - PCHAT_READS("pchat-reads"), - PCHAT_USERS("pchat-users"), - PEER_TO_PEER_ROOMS_PARTICIPANT_MINUTES( - "peer-to-peer-rooms-participant-minutes" - ), - PFAX("pfax"), - PFAX_MINUTES("pfax-minutes"), - PFAX_MINUTES_INBOUND("pfax-minutes-inbound"), - PFAX_MINUTES_OUTBOUND("pfax-minutes-outbound"), - PFAX_PAGES("pfax-pages"), - PHONE_QUALITY_SCORE_LOOKUPS("phone-quality-score-lookups"), - PHONENUMBERS("phonenumbers"), - PHONENUMBERS_CPS("phonenumbers-cps"), - PHONENUMBERS_EMERGENCY("phonenumbers-emergency"), - PHONENUMBERS_LOCAL("phonenumbers-local"), - PHONENUMBERS_MOBILE("phonenumbers-mobile"), - PHONENUMBERS_PORTING("phonenumbers-porting"), - PHONENUMBERS_SETUPS("phonenumbers-setups"), - PHONENUMBERS_TOLLFREE("phonenumbers-tollfree"), - PREMIUMSUPPORT("premiumsupport"), - PREMIUMSUPPORT_PERCENTAGE_SPEND("premiumsupport-percentage-spend"), - PROGRAMMABLEVOICE_PLATFORM("programmablevoice-platform"), - PROGRAMMABLEVOICECONN_CLIENTSDK("programmablevoiceconn-clientsdk"), - PROGRAMMABLEVOICECONN_CLIENTSDK_INBOUND( - "programmablevoiceconn-clientsdk-inbound" - ), - PROGRAMMABLEVOICECONN_CLIENTSDK_OUTBOUND( - "programmablevoiceconn-clientsdk-outbound" - ), - PROGRAMMABLEVOICECONN_ONNET("programmablevoiceconn-onnet"), - PROGRAMMABLEVOICECONN_ONNET_INBOUND( - "programmablevoiceconn-onnet-inbound" - ), - PROGRAMMABLEVOICECONN_ONNET_OUTBOUND( - "programmablevoiceconn-onnet-outbound" - ), - PROGRAMMABLEVOICECONN_SIP("programmablevoiceconn-sip"), - PROGRAMMABLEVOICECONN_SIP_INBOUND("programmablevoiceconn-sip-inbound"), - PROGRAMMABLEVOICECONN_SIP_OUTBOUND( - "programmablevoiceconn-sip-outbound" - ), - PROGRAMMABLEVOICECONNECTIVITY("programmablevoiceconnectivity"), - PROXY("proxy"), - PROXY_ACTIVE_SESSIONS("proxy-active-sessions"), - PROXY_BUCKET_ADJUSTMENT("proxy-bucket-adjustment"), - PROXY_LICENSES("proxy-licenses"), - PSTNCONNECTIVITY("pstnconnectivity"), - PSTNCONNECTIVITY_INBOUND("pstnconnectivity-inbound"), - PSTNCONNECTIVITY_OUTBOUND("pstnconnectivity-outbound"), - PV("pv"), - PV_BASIC_ROOMS("pv-basic-rooms"), - PV_COMPOSITION_MEDIA_DOWNLOADED("pv-composition-media-downloaded"), - PV_COMPOSITION_MEDIA_ENCRYPTED("pv-composition-media-encrypted"), - PV_COMPOSITION_MEDIA_STORED("pv-composition-media-stored"), - PV_COMPOSITION_MINUTES("pv-composition-minutes"), - PV_RECORDING_COMPOSITIONS("pv-recording-compositions"), - PV_ROOM_PARTICIPANTS("pv-room-participants"), - PV_ROOM_PARTICIPANTS_AU1("pv-room-participants-au1"), - PV_ROOM_PARTICIPANTS_BR1("pv-room-participants-br1"), - PV_ROOM_PARTICIPANTS_IE1("pv-room-participants-ie1"), - PV_ROOM_PARTICIPANTS_JP1("pv-room-participants-jp1"), - PV_ROOM_PARTICIPANTS_SG1("pv-room-participants-sg1"), - PV_ROOM_PARTICIPANTS_US1("pv-room-participants-us1"), - PV_ROOM_PARTICIPANTS_US2("pv-room-participants-us2"), - PV_ROOMS("pv-rooms"), - PV_SIP_ENDPOINT_REGISTRATIONS("pv-sip-endpoint-registrations"), - RCS_MESSAGES("rcs-messages"), - REASSIGNED_NUMBER("reassigned-number"), - RECORDINGS("recordings"), - RECORDINGSTORAGE("recordingstorage"), - SHORTCODES("shortcodes"), - SHORTCODES_CUSTOMEROWNED("shortcodes-customerowned"), - SHORTCODES_MMS_ENABLEMENT("shortcodes-mms-enablement"), - SHORTCODES_MPS("shortcodes-mps"), - SHORTCODES_RANDOM("shortcodes-random"), - SHORTCODES_SETUP_FEES("shortcodes-setup-fees"), - SHORTCODES_UK("shortcodes-uk"), - SHORTCODES_VANITY("shortcodes-vanity"), - SIM_SWAP_LOOKUPS("sim-swap-lookups"), - SIP_SECURE_MEDIA("sip-secure-media"), - SMALL_GROUP_ROOMS("small-group-rooms"), - SMALL_GROUP_ROOMS_DATA_TRACK("small-group-rooms-data-track"), - SMALL_GROUP_ROOMS_PARTICIPANT_MINUTES( - "small-group-rooms-participant-minutes" - ), - SMS("sms"), - SMS_INBOUND("sms-inbound"), - SMS_INBOUND_LONGCODE("sms-inbound-longcode"), - SMS_INBOUND_SHORTCODE("sms-inbound-shortcode"), - SMS_INBOUND_TOLLFREE("sms-inbound-tollfree"), - SMS_MESSAGES_CARRIERFEES("sms-messages-carrierfees"), - SMS_MESSAGES_FEATURES("sms-messages-features"), - SMS_MESSAGES_FEATURES_ENGAGEMENT_SUITE( - "sms-messages-features-engagement-suite" - ), - SMS_MESSAGES_FEATURES_MESSAGE_REDACTION( - "sms-messages-features-message-redaction" - ), - SMS_MESSAGES_FEATURES_SENDERID("sms-messages-features-senderid"), - SMS_MPS("sms-mps"), - SMS_MPS_SHORTCODE("sms-mps-shortcode"), - SMS_MPS_TOLLFREE("sms-mps-tollfree"), - SMS_MPS_TOLLFREE_SETUP("sms-mps-tollfree-setup"), - SMS_NATIONAL_REGULATORY_PROTECTION( - "sms-national-regulatory-protection" - ), - SMS_OUTBOUND("sms-outbound"), - SMS_OUTBOUND_CONTENT_INSPECTION("sms-outbound-content-inspection"), - SMS_OUTBOUND_LONGCODE("sms-outbound-longcode"), - SMS_OUTBOUND_SHORTCODE("sms-outbound-shortcode"), - SMS_OUTBOUND_TOLLFREE("sms-outbound-tollfree"), - SMS_PUMPING_PROTECTION("sms-pumping-protection"), - SMS_PUMPING_RISK("sms-pumping-risk"), - SMSMESSAGES_BUCKET_ADJUSTMENTS("smsmessages-bucket-adjustments"), - SMSMESSAGES_OUTBOUND_DOMESTIC("smsmessages-outbound-domestic"), - SPEECH_RECOGNITION("speech-recognition"), - STUDIO_ENGAGEMENTS("studio-engagements"), - SYNC("sync"), - SYNC_ACTIONS("sync-actions"), - SYNC_ENDPOINT_HOURS("sync-endpoint-hours"), - SYNC_ENDPOINT_HOURS_ABOVE_DAILY_CAP( - "sync-endpoint-hours-above-daily-cap" - ), - TASKROUTER_TASKS("taskrouter-tasks"), - TOTALPRICE("totalprice"), - TRANSCRIPTIONS("transcriptions"), - TRUNKING_CPS("trunking-cps"), - TRUNKING_EMERGENCY_CALLS("trunking-emergency-calls"), - TRUNKING_ORIGINATION("trunking-origination"), - TRUNKING_ORIGINATION_LOCAL("trunking-origination-local"), - TRUNKING_ORIGINATION_MOBILE("trunking-origination-mobile"), - TRUNKING_ORIGINATION_TOLLFREE("trunking-origination-tollfree"), - TRUNKING_RECORDINGS("trunking-recordings"), - TRUNKING_SECURE("trunking-secure"), - TRUNKING_TERMINATION("trunking-termination"), - TTS_GOOGLE("tts-google"), - TURNMEGABYTES("turnmegabytes"), - TURNMEGABYTES_AUSTRALIA("turnmegabytes-australia"), - TURNMEGABYTES_BRASIL("turnmegabytes-brasil"), - TURNMEGABYTES_GERMANY("turnmegabytes-germany"), - TURNMEGABYTES_INDIA("turnmegabytes-india"), - TURNMEGABYTES_IRELAND("turnmegabytes-ireland"), - TURNMEGABYTES_JAPAN("turnmegabytes-japan"), - TURNMEGABYTES_SINGAPORE("turnmegabytes-singapore"), - TURNMEGABYTES_USEAST("turnmegabytes-useast"), - TURNMEGABYTES_USWEST("turnmegabytes-uswest"), - TWILIO_FOR_SALESFORCE("twilio-for-salesforce"), - TWILIO_FOR_SALESFORCE_LICENSES("twilio-for-salesforce-licenses"), - TWILIO_INTERCONNECT("twilio-interconnect"), - TWIML("twiml"), - USAGE_FLEX_VIDEO("usage-flex-video"), - USAGE_FUNCTIONS("usage-functions"), - USAGE_RCS_BASIC_MESSAGES_OUTBOUND("usage-rcs-basic-messages-outbound"), - USAGE_RCS_MESSAGES("usage-rcs-messages"), - USAGE_RCS_MESSAGES_INBOUND("usage-rcs-messages-inbound"), - USAGE_RCS_MESSAGING_CARRIER_FEES("usage-rcs-messaging-carrier-fees"), - USAGE_RCS_SINGLE_MESSAGES_OUTBOUND( - "usage-rcs-single-messages-outbound" - ), - VERIFY_PACKAGE_PLANS("verify-package-plans"), - VERIFY_PUSH("verify-push"), - VERIFY_SNA("verify-sna"), - VERIFY_TOTP("verify-totp"), - VERIFY_VOICE_SMS("verify-voice-sms"), - VERIFY_WHATSAPP_CONVERSATIONS_BUSINESS_INITIATED( - "verify-whatsapp-conversations-business-initiated" - ), - VERIFY_WHATSAPP_TEMPLATE_BUSINESS_INITIATED( - "verify-whatsapp-template-business-initiated" - ), - VIDEO_RECORDINGS("video-recordings"), - VIDEO_ROOMS_TURN_MEGABYTES("video-rooms-turn-megabytes"), - VIRTUAL_AGENT("virtual-agent"), - VOICE_INSIGHTS("voice-insights"), - VOICE_INSIGHTS_CLIENT_INSIGHTS_ON_DEMAND_MINUTE( - "voice-insights-client-insights-on-demand-minute" - ), - VOICE_INSIGHTS_PTSN_INSIGHTS_ON_DEMAND_MINUTE( - "voice-insights-ptsn-insights-on-demand-minute" - ), - VOICE_INSIGHTS_SIP_INTERFACE_INSIGHTS_ON_DEMAND_MINUTE( - "voice-insights-sip-interface-insights-on-demand-minute" - ), - VOICE_INSIGHTS_SIP_TRUNKING_INSIGHTS_ON_DEMAND_MINUTE( - "voice-insights-sip-trunking-insights-on-demand-minute" - ), - VOICE_INTELLIGENCE("voice-intelligence"), - VOICE_INTELLIGENCE_EIP_OPERATORS("voice-intelligence-eip-operators"), - VOICE_INTELLIGENCE_OPERATORS("voice-intelligence-operators"), - VOICE_INTELLIGENCE_TRANSCRIPTION("voice-intelligence-transcription"), - WDS("wds"), - WIRELESS("wireless"), - WIRELESS_DATA("wireless-data"), - WIRELESS_DATA_PAYG("wireless-data-payg"), - WIRELESS_DATA_PAYG_AFRICA("wireless-data-payg-africa"), - WIRELESS_DATA_PAYG_ASIA("wireless-data-payg-asia"), - WIRELESS_DATA_PAYG_CENTRALANDSOUTHAMERICA( - "wireless-data-payg-centralandsouthamerica" - ), - WIRELESS_DATA_PAYG_EUROPE("wireless-data-payg-europe"), - WIRELESS_DATA_PAYG_NORTHAMERICA("wireless-data-payg-northamerica"), - WIRELESS_DATA_PAYG_OCEANIA("wireless-data-payg-oceania"), - WIRELESS_DATA_QUOTA1("wireless-data-quota1"), - WIRELESS_DATA_QUOTA1_AFRICA("wireless-data-quota1-africa"), - WIRELESS_DATA_QUOTA1_ASIA("wireless-data-quota1-asia"), - WIRELESS_DATA_QUOTA1_CENTRALANDSOUTHAMERICA( - "wireless-data-quota1-centralandsouthamerica" - ), - WIRELESS_DATA_QUOTA1_EUROPE("wireless-data-quota1-europe"), - WIRELESS_DATA_QUOTA1_NORTHAMERICA("wireless-data-quota1-northamerica"), - WIRELESS_DATA_QUOTA1_OCEANIA("wireless-data-quota1-oceania"), - WIRELESS_DATA_QUOTA10("wireless-data-quota10"), - WIRELESS_DATA_QUOTA10_AFRICA("wireless-data-quota10-africa"), - WIRELESS_DATA_QUOTA10_ASIA("wireless-data-quota10-asia"), - WIRELESS_DATA_QUOTA10_CENTRALANDSOUTHAMERICA( - "wireless-data-quota10-centralandsouthamerica" - ), - WIRELESS_DATA_QUOTA10_EUROPE("wireless-data-quota10-europe"), - WIRELESS_DATA_QUOTA10_NORTHAMERICA( - "wireless-data-quota10-northamerica" - ), - WIRELESS_DATA_QUOTA10_OCEANIA("wireless-data-quota10-oceania"), - WIRELESS_DATA_QUOTA50("wireless-data-quota50"), - WIRELESS_DATA_QUOTA50_AFRICA("wireless-data-quota50-africa"), - WIRELESS_DATA_QUOTA50_ASIA("wireless-data-quota50-asia"), - WIRELESS_DATA_QUOTA50_CENTRALANDSOUTHAMERICA( - "wireless-data-quota50-centralandsouthamerica" - ), - WIRELESS_DATA_QUOTA50_EUROPE("wireless-data-quota50-europe"), - WIRELESS_DATA_QUOTA50_NORTHAMERICA( - "wireless-data-quota50-northamerica" - ), - WIRELESS_DATA_QUOTA50_OCEANIA("wireless-data-quota50-oceania"), - WIRELESS_DATA_QUOTACUSTOM("wireless-data-quotacustom"), - WIRELESS_DATA_QUOTACUSTOM_AFRICA("wireless-data-quotacustom-africa"), - WIRELESS_DATA_QUOTACUSTOM_ASIA("wireless-data-quotacustom-asia"), - WIRELESS_DATA_QUOTACUSTOM_CENTRALANDSOUTHAMERICA( - "wireless-data-quotacustom-centralandsouthamerica" - ), - WIRELESS_DATA_QUOTACUSTOM_EUROPE("wireless-data-quotacustom-europe"), - WIRELESS_DATA_QUOTACUSTOM_NORTHAMERICA( - "wireless-data-quotacustom-northamerica" - ), - WIRELESS_DATA_QUOTACUSTOM_OCEANIA("wireless-data-quotacustom-oceania"), - WIRELESS_MRC_PAYG("wireless-mrc-payg"), - WIRELESS_MRC_QUOTA1("wireless-mrc-quota1"), - WIRELESS_MRC_QUOTA10("wireless-mrc-quota10"), - WIRELESS_MRC_QUOTA50("wireless-mrc-quota50"), - WIRELESS_MRC_QUOTACUSTOM("wireless-mrc-quotacustom"), - WIRELESS_ORDERS("wireless-orders"), - WIRELESS_ORDERS_ARTWORK("wireless-orders-artwork"), - WIRELESS_ORDERS_BULK("wireless-orders-bulk"), - WIRELESS_ORDERS_ESIM("wireless-orders-esim"), - WIRELESS_ORDERS_STARTER("wireless-orders-starter"), - WIRELESS_QUOTAS("wireless-quotas"), - WIRELESS_SMS_AFRICA("wireless-sms-africa"), - WIRELESS_SMS_ASIA("wireless-sms-asia"), - WIRELESS_SMS_CENTRALANDSOUTHAMERICA( - "wireless-sms-centralandsouthamerica" - ), - WIRELESS_SMS_EUROPE("wireless-sms-europe"), - WIRELESS_SMS_NORTHAMERICA("wireless-sms-northamerica"), - WIRELESS_SMS_OCEANIA("wireless-sms-oceania"), - WIRELESS_SUPER_SIM("wireless-super-sim"), - WIRELESS_SUPER_SIM_DATA("wireless-super-sim-data"), - WIRELESS_SUPER_SIM_DATA_NORTH_AMERICA_USA( - "wireless-super-sim-data-north-america-usa" - ), - WIRELESS_SUPER_SIM_DATA_PAYG("wireless-super-sim-data-payg"), - WIRELESS_SUPER_SIM_DATA_PAYG_EUROPE( - "wireless-super-sim-data-payg-europe" - ), - WIRELESS_SUPER_SIM_DATA_PAYG_NORTH_AMERICA( - "wireless-super-sim-data-payg-north-america" - ), - WIRELESS_SUPER_SIM_HARDWARE("wireless-super-sim-hardware"), - WIRELESS_SUPER_SIM_HARDWARE_BULK("wireless-super-sim-hardware-bulk"), - WIRELESS_SUPER_SIM_SMSCOMMANDS("wireless-super-sim-smscommands"), - WIRELESS_SUPER_SIM_SMSCOMMANDS_AFRICA( - "wireless-super-sim-smscommands-africa" - ), - WIRELESS_SUPER_SIM_SMSCOMMANDS_ASIA( - "wireless-super-sim-smscommands-asia" - ), - WIRELESS_SUPER_SIM_SMSCOMMANDS_CENT_AND_SOUTH_AMERICA( - "wireless-super-sim-smscommands-cent-and-south-america" - ), - WIRELESS_SUPER_SIM_SMSCOMMANDS_EUROPE( - "wireless-super-sim-smscommands-europe" - ), - WIRELESS_SUPER_SIM_SMSCOMMANDS_NORTH_AMERICA( - "wireless-super-sim-smscommands-north-america" - ), - WIRELESS_SUPER_SIM_SMSCOMMANDS_OCEANIA( - "wireless-super-sim-smscommands-oceania" - ), - WIRELESS_SUPER_SIM_SUBSCRIPTION("wireless-super-sim-subscription"), - WIRELESS_SUPER_SIM_SUBSCRIPTION_PAYG( - "wireless-super-sim-subscription-payg" - ), - WIRELESS_USAGE("wireless-usage"), - WIRELESS_USAGE_COMMANDS("wireless-usage-commands"), - WIRELESS_USAGE_COMMANDS_AFRICA("wireless-usage-commands-africa"), - WIRELESS_USAGE_COMMANDS_ASIA("wireless-usage-commands-asia"), - WIRELESS_USAGE_COMMANDS_CENTRALANDSOUTHAMERICA( - "wireless-usage-commands-centralandsouthamerica" - ), - WIRELESS_USAGE_COMMANDS_EUROPE("wireless-usage-commands-europe"), - WIRELESS_USAGE_COMMANDS_HOME("wireless-usage-commands-home"), - WIRELESS_USAGE_COMMANDS_NORTHAMERICA( - "wireless-usage-commands-northamerica" - ), - WIRELESS_USAGE_COMMANDS_OCEANIA("wireless-usage-commands-oceania"), - WIRELESS_USAGE_COMMANDS_ROAMING("wireless-usage-commands-roaming"), - WIRELESS_USAGE_DATA("wireless-usage-data"), - WIRELESS_USAGE_DATA_AFRICA("wireless-usage-data-africa"), - WIRELESS_USAGE_DATA_ASIA("wireless-usage-data-asia"), - WIRELESS_USAGE_DATA_CENTRALANDSOUTHAMERICA( - "wireless-usage-data-centralandsouthamerica" - ), - WIRELESS_USAGE_DATA_CUSTOM_ADDITIONALMB( - "wireless-usage-data-custom-additionalmb" - ), - WIRELESS_USAGE_DATA_CUSTOM_FIRST5MB( - "wireless-usage-data-custom-first5mb" - ), - WIRELESS_USAGE_DATA_DOMESTIC_ROAMING( - "wireless-usage-data-domestic-roaming" - ), - WIRELESS_USAGE_DATA_EUROPE("wireless-usage-data-europe"), - WIRELESS_USAGE_DATA_INDIVIDUAL_ADDITIONALGB( - "wireless-usage-data-individual-additionalgb" - ), - WIRELESS_USAGE_DATA_INDIVIDUAL_FIRSTGB( - "wireless-usage-data-individual-firstgb" - ), - WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_CANADA( - "wireless-usage-data-international-roaming-canada" - ), - WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_INDIA( - "wireless-usage-data-international-roaming-india" - ), - WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_MEXICO( - "wireless-usage-data-international-roaming-mexico" - ), - WIRELESS_USAGE_DATA_NORTHAMERICA("wireless-usage-data-northamerica"), - WIRELESS_USAGE_DATA_OCEANIA("wireless-usage-data-oceania"), - WIRELESS_USAGE_DATA_POOLED("wireless-usage-data-pooled"), - WIRELESS_USAGE_DATA_POOLED_DOWNLINK( - "wireless-usage-data-pooled-downlink" - ), - WIRELESS_USAGE_DATA_POOLED_UPLINK("wireless-usage-data-pooled-uplink"), - WIRELESS_USAGE_MRC("wireless-usage-mrc"), - WIRELESS_USAGE_MRC_CUSTOM("wireless-usage-mrc-custom"), - WIRELESS_USAGE_MRC_INDIVIDUAL("wireless-usage-mrc-individual"), - WIRELESS_USAGE_MRC_POOLED("wireless-usage-mrc-pooled"), - WIRELESS_USAGE_MRC_SUSPENDED("wireless-usage-mrc-suspended"), - WIRELESS_USAGE_SMS("wireless-usage-sms"), - WIRELESS_USAGE_VOICE("wireless-usage-voice"), - A2P_FAST_TRACK_ONBOARDING("a2p-fast-track-onboarding"), - ADVISORY_SERVICES("advisory-services"), - ADVISORY_SERVICES_BILLED("advisory-services-billed"), - ADVISORY_SERVICES_CALL_TRACKING("advisory-services-call-tracking"), - ADVISORY_SERVICES_DATA_SERVICES("advisory-services-data-services"), - ADVISORY_SERVICES_EXPENSES("advisory-services-expenses"), - ADVISORY_SERVICES_SIP_TRUNKING("advisory-services-sip-trunking"), - ASSETS_REQUESTS("assets-requests"), - AUDIENCE_MINUTES_VIDEO("audience-minutes-video"), - AUTHY_BUCKET_ADJUSTMENT("authy-bucket-adjustment"), - AUTHY_SOFTWARE("authy-software"), - CALLERIDLOOKUPS_API("calleridlookups-api"), - CALLERIDLOOKUPS_PROGRAMMABLEVOICE("calleridlookups-programmablevoice"), - CALLERIDLOOKUPS_TRUNKING("calleridlookups-trunking"), - CALLS_TRUNKING_INBOUND_TOLLFREE_LOCAL( - "calls-trunking-inbound-tollfree-local" - ), - CALLS_TRUNKING_INBOUND_TOLLFREE_MOBILE( - "calls-trunking-inbound-tollfree-mobile" - ), - CHANNELS_WHATSAPP_CONVERSATION_FREE_1( - "channels-whatsapp-conversation-free-1" - ), - CONFERENCE("conference"), - CONVERSATIONAL_INSIGHTS("conversational-insights"), - CONVERSATIONAL_INSIGHTS_MESSAGES("conversational-insights-messages"), - CONVERSATIONAL_INSIGHTS_VOICE_MINUTES( - "conversational-insights-voice-minutes" - ), - DEMO("demo"), - DEMO_UC_SCRIPT_TEST("demo-uc-script-test"), - ELASTIC_SIP_TRUNKING("elastic-sip-trunking"), - ELASTIC_SIP_TRUNKING_CALL_TRANSFERS( - "elastic-sip-trunking-call-transfers" - ), - ENTERPRISE_HIPPA("enterprise-hippa"), - FLEX_NAMED_USERS("flex-named-users"), - FLEX_SPINSCI("flex-spinsci"), - FLEX_USERS_1("flex-users-1"), - FLEX_WFO_PREMIUM_SPEECH_ANALYTICS("flex-wfo-premium-speech-analytics"), - FLEX_XCELERATE("flex-xcelerate"), - FUNCTIONS_ROLLUP("functions-rollup"), - IMP_V1_USAGE("imp-v1-usage"), - IP_MESSAGING_ADDONS("ip-messaging-addons"), - IVR("ivr"), - IVR_CONVERSATIONAL("ivr-conversational"), - IVR_DTMF("ivr-dtmf"), - IVR_VIRTUALAGENT("ivr-virtualagent"), - LIVE("live"), - LIVE_MEDIA_RECORDING_MINUTES("live-media-recording-minutes"), - LONGCODE_MPS("longcode-mps"), - MARKETPLACE_ANALYTICS_ADDONS("marketplace-analytics-addons"), - MARKETPLACE_ISV_ADDONS("marketplace-isv-addons"), - MARKETPLACE_MESSAGING_ADDONS("marketplace-messaging-addons"), - MARKETPLACE_PHONENUMBERS_ADDONS("marketplace-phonenumbers-addons"), - MARKETPLACE_RECORDING_ADDONS("marketplace-recording-addons"), - MARKETPLACE_VIRTUALAGENT_ADDONS("marketplace-virtualagent-addons"), - MARKETPLAY_PAY_ADDONS_SHUTTLE_PAY_CONNECTOR_1( - "marketplay-pay-addons-shuttle-pay-connector-1" - ), - MARKETPLAY_PAY_ADDONS_STRIPE_PAY_CONNECTOR( - "marketplay-pay-addons-stripe-pay-connector" - ), - MMS_INBOUND_LONGCODE_CANADA("mms-inbound-longcode-canada"), - MMS_INBOUND_LONGCODE_UNITEDSTATES("mms-inbound-longcode-unitedstates"), - MMS_OUTBOUND_LONGCODE_CANADA("mms-outbound-longcode-canada"), - MMS_OUTBOUND_LONGCODE_UNITEDSTATES( - "mms-outbound-longcode-unitedstates" - ), - MMS_OUTBOUND_TOLL_FREE("mms-outbound-toll-free"), - NOTIFY_CHATAPPSANDOTHERCHANNELS("notify-chatappsandotherchannels"), - NOTIFY_NOTIFYSERVICES("notify-notifyservices"), - NOTIFY_PUSHNOTIFICATIONS("notify-pushnotifications"), - PAYMENT_GATEWAY_CONNECTORS("payment-gateway-connectors"), - PAYMENT_SOLUTIONS("payment-solutions"), - PCHAT_BUCKET_ADJUSTMENT("pchat-bucket-adjustment"), - PHONENUMBERS_NUMBERS("phonenumbers-numbers"), - PROG_VOICE_CLIENT_ANDROID("prog-voice-client-android"), - PROG_VOICE_CLIENT_ANDROID_INBOUND("prog-voice-client-android-inbound"), - PROG_VOICE_CLIENT_ANDROID_OUTBOUND( - "prog-voice-client-android-outbound" - ), - PROG_VOICE_CLIENT_IOS("prog-voice-client-ios"), - PROG_VOICE_CLIENT_IOS_INBOUND("prog-voice-client-ios-inbound"), - PROG_VOICE_CLIENT_IOS_OUTBOUND("prog-voice-client-ios-outbound"), - PROG_VOICE_CLIENT_SDK("prog-voice-client-sdk"), - PROG_VOICE_CLIENT_WEB("prog-voice-client-web"), - PROG_VOICE_CLIENT_WEB_INBOUND("prog-voice-client-web-inbound"), - PROG_VOICE_CLIENT_WEB_OUTBOUND("prog-voice-client-web-outbound"), - PROGRAMMABLEVOICECONNECTIVITY_MEDIA_STREAMS( - "programmablevoiceconnectivity-media-streams" - ), - PSTNCONNECTIVITY_BYOC("pstnconnectivity-byoc"), - PSTNCONNECTIVITY_EMERGENCY("pstnconnectivity-emergency"), - PSTNCONNECTIVITY_MINUTES("pstnconnectivity-minutes"), - PSTNCONNECTIVITY_MINUTES_1("pstnconnectivity-minutes-1"), - PSTNCONNECTIVITY_MINUTESINBOUNDLOCAL( - "pstnconnectivity-minutesinboundlocal" - ), - PSTNCONNECTIVITY_MINUTESINBOUNDMOBILE( - "pstnconnectivity-minutesinboundmobile" - ), - PSTNCONNECTIVITY_MINUTESINBOUNDTOLLFREE( - "pstnconnectivity-minutesinboundtollfree" - ), - PSTNCONNECTIVITY_MINUTESINBOUNDTOLLFREELOCAL( - "pstnconnectivity-minutesinboundtollfreelocal" - ), - PSTNCONNECTIVITY_MINUTESINBOUNDTOLLFREEMOBILE( - "pstnconnectivity-minutesinboundtollfreemobile" - ), - PV_ROOM_HOURS("pv-room-hours"), - PV_ROOM_SIMULTANEOUS_PARTICIPANT_CONNECTIONS( - "pv-room-simultaneous-participant-connections" - ), - PVIDEO_ROOM_HOURS_AU1("pvideo-room-hours-au1"), - PVIDEO_ROOM_HOURS_BR1("pvideo-room-hours-br1"), - PVIDEO_ROOM_HOURS_IE1("pvideo-room-hours-ie1"), - PVIDEO_ROOM_HOURS_JP1("pvideo-room-hours-jp1"), - PVIDEO_ROOM_HOURS_SG1("pvideo-room-hours-sg1"), - PVIDEO_ROOM_HOURS_US1("pvideo-room-hours-us1"), - PVIDEO_ROOM_HOURS_US2("pvideo-room-hours-us2"), - RECORDINGS_ENCRYPTED("recordings-encrypted"), - SHORT_CODE_SETUP_FEES("short-code-setup-fees"), - SHORTCODES_MESSAGES_INBOUND("shortcodes-messages-inbound"), - SHORTCODES_MESSAGES_OUTBOUND("shortcodes-messages-outbound"), - SMS_MESSAGES_REGISTRATIONFEES("sms-messages-registrationfees"), - SMS_MMS_PENALTY_FEES("sms-mms-penalty-fees"), - SMS_MMS_PENALTY_FEES_1("sms-mms-penalty-fees-1"), - SMS_PUMPING_PROTECTION_NON_USCA("sms-pumping-protection-non-usca"), - SMS_PUMPING_PROTECTION_USCA("sms-pumping-protection-usca"), - STUDIO("studio"), - STUDIO_MONTHLY_FEES("studio-monthly-fees"), - SUPERSIM("supersim"), - TASK_ROUTER("task-router"), - TASK_ROUTER_WORKERS("task-router-workers"), - TEST_QUOTA_BUCKETS("test-quota-buckets"), - TEST_UC_SCRIPT_1("test-uc-script-1"), - TEST_UC_SCRIPT_DEMO_2("test-uc-script-demo-2"), - TEXT_TO_SPEECH("text-to-speech"), - TME("tme"), - TTS_BASIC("tts-basic"), - TWILIO_EDITIONS("twilio-editions"), - TWILIO_INTERCONNECT_CALIFORNIA("twilio-interconnect-california"), - TWILIO_INTERCONNECT_CALIFORNIA_MONTHLY( - "twilio-interconnect-california-monthly" - ), - TWILIO_INTERCONNECT_CALIFORNIA_SETUP( - "twilio-interconnect-california-setup" - ), - TWILIO_INTERCONNECT_FRANKFURT("twilio-interconnect-frankfurt"), - TWILIO_INTERCONNECT_FRANKFURT_MO("twilio-interconnect-frankfurt-mo"), - TWILIO_INTERCONNECT_FRANKFURT_SETUP( - "twilio-interconnect-frankfurt-setup" - ), - TWILIO_INTERCONNECT_LONDON("twilio-interconnect-london"), - TWILIO_INTERCONNECT_LONDON_MO("twilio-interconnect-london-mo"), - TWILIO_INTERCONNECT_LONDON_SETUP("twilio-interconnect-london-setup"), - TWILIO_INTERCONNECT_SAO_PAULO("twilio-interconnect-sao-paulo"), - TWILIO_INTERCONNECT_SAO_PAULO_MONTHLY( - "twilio-interconnect-sao-paulo-monthly" - ), - TWILIO_INTERCONNECT_SAO_PAULO_SETUP( - "twilio-interconnect-sao-paulo-setup" - ), - TWILIO_INTERCONNECT_SINGAPORE("twilio-interconnect-singapore"), - TWILIO_INTERCONNECT_SINGAPORE_MO("twilio-interconnect-singapore-mo"), - TWILIO_INTERCONNECT_SINGAPORE_SETUP( - "twilio-interconnect-singapore-setup" - ), - TWILIO_INTERCONNECT_SYDNEY("twilio-interconnect-sydney"), - TWILIO_INTERCONNECT_SYDNEY_MO("twilio-interconnect-sydney-mo"), - TWILIO_INTERCONNECT_SYDNEY_SETUP("twilio-interconnect-sydney-setup"), - TWILIO_INTERCONNECT_TOKYO("twilio-interconnect-tokyo"), - TWILIO_INTERCONNECT_TOKYO_MO("twilio-interconnect-tokyo-mo"), - TWILIO_INTERCONNECT_TOKYO_SETUP("twilio-interconnect-tokyo-setup"), - TWILIO_INTERCONNECT_VA("twilio-interconnect-va"), - TWILIO_INTERCONNECT_VA_MO("twilio-interconnect-va-mo"), - TWILIO_INTERCONNECT_VA_SETUP("twilio-interconnect-va-setup"), - TWIML_VERBS("twiml-verbs"), - TWIML_VERBS_SAY("twiml-verbs-say"), - USAGE_PROGRAMMABLE_MESSAGING_ENGAGEMENT_SUITE( - "usage-programmable-messaging-engagement-suite" - ), - USAGE_PROGRAMMABLE_MESSAGING_FEES_SERVICES( - "usage-programmable-messaging-fees-services" - ), - VERIFY_OUTBOUND_EMAIL("verify-outbound-email"), - VERIFY_PACKAGED_PLANS("verify-packaged-plans"), - VERIFY_SILENT_NETWORK_AUTH("verify-silent-network-auth"), - VERIFY_VOICE_AND_SMS("verify-voice-and-sms"), - VOICE_INSIGHTS_CLIENT_INSIGHTS_MONTHY_COMMIT( - "voice-insights-client-insights-monthy-commit" - ), - WIRELESS_DATA_PAYG_ASIA_AFG("wireless-data-payg-asia-afg"), - WIRELESS_MULTI_IMSI_SIM_COMMANDS("wireless-multi-imsi-sim-commands"), - WIRELESS_MULTI_IMSI_SIM_COMMANDS_USA( - "wireless-multi-imsi-sim-commands-usa" - ), - WIRELESS_MULTI_IMSI_SIM_DATA("wireless-multi-imsi-sim-data"), - WIRELESS_MULTI_IMSI_SIM_DATA_EU28("wireless-multi-imsi-sim-data-eu28"), - WIRELESS_MULTI_IMSI_SIM_DATA_USA("wireless-multi-imsi-sim-data-usa"), - WIRELESS_MULTI_IMSI_SIM_MONTHLY_FEES( - "wireless-multi-imsi-sim-monthly-fees" - ), - WIRELESS_MULTI_IMSI_SIM_USAGE("wireless-multi-imsi-sim-usage"), - WIRELESS_SUPER_SIM_DATA_NORTH_AMERICA( - "wireless-super-sim-data-north-america" - ), - WIRELESS_SUPER_SIM_USAGE("wireless-super-sim-usage"); - - private final String value; - - private Category(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static Category forValue(final String value) { - return Promoter.enumFromString(value, Category.values()); - } - } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/usage/record/YearlyReader.java b/src/main/java/com/twilio/rest/api/v2010/account/usage/record/YearlyReader.java index efc5743989..2c0d681587 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/usage/record/YearlyReader.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/usage/record/YearlyReader.java @@ -32,7 +32,7 @@ public class YearlyReader extends Reader { private String pathAccountSid; - private Yearly.Category category; + private String category; private LocalDate startDate; private LocalDate endDate; private Boolean includeSubaccounts; @@ -44,7 +44,7 @@ public YearlyReader(final String pathAccountSid) { this.pathAccountSid = pathAccountSid; } - public YearlyReader setCategory(final Yearly.Category category) { + public YearlyReader setCategory(final String category) { this.category = category; return this; } @@ -168,7 +168,7 @@ public Page getPage( private void addQueryParams(final Request request) { if (category != null) { - request.addQueryParam("Category", category.toString()); + request.addQueryParam("Category", category); } if (startDate != null) { request.addQueryParam( diff --git a/src/main/java/com/twilio/rest/api/v2010/account/usage/record/Yesterday.java b/src/main/java/com/twilio/rest/api/v2010/account/usage/record/Yesterday.java index 97223fff23..50d71c25ab 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/usage/record/Yesterday.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/usage/record/Yesterday.java @@ -24,7 +24,6 @@ import com.twilio.base.Resource; import com.twilio.converter.CurrencyDeserializer; import com.twilio.converter.DateConverter; -import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import java.io.IOException; @@ -42,7 +41,7 @@ @ToString public class Yesterday extends Resource { - private static final long serialVersionUID = 252061486411277L; + private static final long serialVersionUID = 158026917970511L; public static YesterdayReader reader() { return new YesterdayReader(); @@ -98,7 +97,7 @@ public static Yesterday fromJson( private final String accountSid; private final String apiVersion; private final String asOf; - private final Yesterday.Category category; + private final String category; private final String count; private final String countUnit; private final String description; @@ -116,7 +115,7 @@ private Yesterday( @JsonProperty("account_sid") final String accountSid, @JsonProperty("api_version") final String apiVersion, @JsonProperty("as_of") final String asOf, - @JsonProperty("category") final Yesterday.Category category, + @JsonProperty("category") final String category, @JsonProperty("count") final String count, @JsonProperty("count_unit") final String countUnit, @JsonProperty("description") final String description, @@ -163,7 +162,7 @@ public final String getAsOf() { return this.asOf; } - public final Yesterday.Category getCategory() { + public final String getCategory() { return this.category; } @@ -262,945 +261,4 @@ public int hashCode() { usageUnit ); } - - public enum Category { - A2P_10DLC_REGISTRATIONFEES_BRANDREGISTRATION( - "a2p-10dlc-registrationfees-brandregistration" - ), - A2P_10DLC_REGISTRATIONFEES_BV("a2p-10dlc-registrationfees-bv"), - A2P_10DLC_REGISTRATIONFEES_CAMPAIGNCHARGES( - "a2p-10dlc-registrationfees-campaigncharges" - ), - A2P_10DLC_REGISTRATIONFEES_CAMPAIGNREGISTRATION( - "a2p-10dlc-registrationfees-campaignregistration" - ), - A2P_10DLC_REGISTRATIONFEES_CAMPAIGNVETTING( - "a2p-10dlc-registrationfees-campaignvetting" - ), - A2P_10DLC_REGISTRATIONFEES_MONTHLY( - "a2p-10dlc-registrationfees-monthly" - ), - A2P_10DLC_REGISTRATIONFEES_ONETIME( - "a2p-10dlc-registrationfees-onetime" - ), - A2P_REGISTRATION_FEES("a2p-registration-fees"), - ACCOUNT_SECURITY("account-security"), - AGENT_CONFERENCE("agent-conference"), - AGENT_COPILOT("agent-copilot"), - AGENT_COPILOT_MESSAGES("agent-copilot-messages"), - AGENT_COPILOT_PARTICIPANT_MINUTES("agent-copilot-participant-minutes"), - AI_ASSISTANTS("ai-assistants"), - AI_ASSISTANTS_VOICE("ai-assistants-voice"), - AMAZON_POLLY("amazon-polly"), - ANSWERING_MACHINE_DETECTION("answering-machine-detection"), - ASSETS("assets"), - AUDIENCE_MINUTES("audience-minutes"), - AUDIENCE_MINUTES_AUDIO("audience-minutes-audio"), - AUTHY_AUTHENTICATIONS("authy-authentications"), - AUTHY_CALLS_OUTBOUND("authy-calls-outbound"), - AUTHY_EMAIL_AUTHENTICATIONS("authy-email-authentications"), - AUTHY_MONTHLY_FEES("authy-monthly-fees"), - AUTHY_OUTBOUND_EMAIL("authy-outbound-email"), - AUTHY_PHONE_INTELLIGENCE("authy-phone-intelligence"), - AUTHY_PHONE_VERIFICATIONS("authy-phone-verifications"), - AUTHY_SMS_OUTBOUND("authy-sms-outbound"), - AUTHY_VERIFY_EMAIL_VERIFICATIONS("authy-verify-email-verifications"), - AUTHY_VERIFY_OUTBOUND_EMAIL("authy-verify-outbound-email"), - AUTOPILOT("autopilot"), - AUTOPILOT_HOME_ASSISTANTS("autopilot-home-assistants"), - AUTOPILOT_MESSAGING("autopilot-messaging"), - AUTOPILOT_OTHER("autopilot-other"), - AUTOPILOT_VOICE("autopilot-voice"), - BASIC_PEER_TO_PEER_ROOMS_PARTICIPANT_MINUTES( - "basic-peer-to-peer-rooms-participant-minutes" - ), - BRANDED_CALLING("branded-calling"), - BUNDLE_SMS_BUCKET("bundle-sms-bucket"), - BUNDLE_SUBSCRIPTION_FEES("bundle-subscription-fees"), - CALL_FORWARDING_LOOKUPS("call-forwarding-lookups"), - CALL_PROGESS_EVENTS("call-progess-events"), - CALLERIDLOOKUPS("calleridlookups"), - CALLS("calls"), - CALLS_CLIENT("calls-client"), - CALLS_EMERGENCY("calls-emergency"), - CALLS_GLOBALCONFERENCE("calls-globalconference"), - CALLS_INBOUND("calls-inbound"), - CALLS_INBOUND_LOCAL("calls-inbound-local"), - CALLS_INBOUND_MOBILE("calls-inbound-mobile"), - CALLS_INBOUND_TOLLFREE("calls-inbound-tollfree"), - CALLS_INBOUND_TOLLFREE_LOCAL("calls-inbound-tollfree-local"), - CALLS_INBOUND_TOLLFREE_MOBILE("calls-inbound-tollfree-mobile"), - CALLS_MEDIA_STREAM_MINUTES("calls-media-stream-minutes"), - CALLS_OUTBOUND("calls-outbound"), - CALLS_PAY_VERB_TRANSACTIONS("calls-pay-verb-transactions"), - CALLS_RECORDINGS("calls-recordings"), - CALLS_SIP("calls-sip"), - CALLS_SIP_INBOUND("calls-sip-inbound"), - CALLS_SIP_OUTBOUND("calls-sip-outbound"), - CALLS_TEXT_TO_SPEECH("calls-text-to-speech"), - CALLS_TRANSFERS("calls-transfers"), - CARRIER_LOOKUPS("carrier-lookups"), - CATEGORY("category"), - CHANNELS("channels"), - CHANNELS_MESSAGING("channels-messaging"), - CHANNELS_MESSAGING_INBOUND("channels-messaging-inbound"), - CHANNELS_MESSAGING_OUTBOUND("channels-messaging-outbound"), - CHANNELS_WHATSAPP("channels-whatsapp"), - CHANNELS_WHATSAPP_CONVERSATION_AUTHENTICATION( - "channels-whatsapp-conversation-authentication" - ), - CHANNELS_WHATSAPP_CONVERSATION_FREE( - "channels-whatsapp-conversation-free" - ), - CHANNELS_WHATSAPP_CONVERSATION_MARKETING( - "channels-whatsapp-conversation-marketing" - ), - CHANNELS_WHATSAPP_CONVERSATION_SERVICE( - "channels-whatsapp-conversation-service" - ), - CHANNELS_WHATSAPP_CONVERSATION_UTILITY( - "channels-whatsapp-conversation-utility" - ), - CHANNELS_WHATSAPP_INBOUND("channels-whatsapp-inbound"), - CHANNELS_WHATSAPP_OUTBOUND("channels-whatsapp-outbound"), - CHANNELS_WHATSAPP_SERVICE("channels-whatsapp-service"), - CHANNELS_WHATSAPP_TEMPLATE_AUTHENTICATION( - "channels-whatsapp-template-authentication" - ), - CHANNELS_WHATSAPP_TEMPLATE_MARKETING( - "channels-whatsapp-template-marketing" - ), - CHANNELS_WHATSAPP_TEMPLATE_SERVICE( - "channels-whatsapp-template-service" - ), - CHANNELS_WHATSAPP_TEMPLATE_UTILITY( - "channels-whatsapp-template-utility" - ), - CHAT_VIRTUAL_AGENT("chat-virtual-agent"), - CONVERSATION_RELAY("conversation-relay"), - CONVERSATIONS("conversations"), - CONVERSATIONS_API_REQUESTS("conversations-api-requests"), - CONVERSATIONS_CONVERSATION_EVENTS("conversations-conversation-events"), - CONVERSATIONS_ENDPOINT_CONNECTIVITY( - "conversations-endpoint-connectivity" - ), - CONVERSATIONS_EVENTS("conversations-events"), - CONVERSATIONS_PARTICIPANT_EVENTS("conversations-participant-events"), - CONVERSATIONS_PARTICIPANTS("conversations-participants"), - CPS("cps"), - CREDIT_TRANSFER("credit-transfer"), - EMAIL("email"), - EMERGING_TECH("emerging-tech"), - ENGAGEMENT_SUITE_PACKAGED_PLANS("engagement-suite-packaged-plans"), - ENHANCED_LINE_TYPE_LOOKUPS("enhanced-line-type-lookups"), - ENTERPRISE("enterprise"), - EVENTS("events"), - EXPERIMENT_FRANCE_SMS("experiment-france-sms"), - EXPERIMENT_INDIA_SMS("experiment-india-sms"), - EXPERIMENT_UK_SMS("experiment-uk-sms"), - FAILED_MESSAGE_PROCESSING_FEE("failed-message-processing-fee"), - FLEX("flex"), - FLEX_ACTIVE_USER_HOURS("flex-active-user-hours"), - FLEX_CONCURRENT_USERS("flex-concurrent-users"), - FLEX_CONVERSATIONAL_INSIGHTS("flex-conversational-insights"), - FLEX_CONVERSATIONAL_INSIGHTS_MESSAGES( - "flex-conversational-insights-messages" - ), - FLEX_CONVERSATIONAL_INSIGHTS_VOICE_MINUTES( - "flex-conversational-insights-voice-minutes" - ), - FLEX_EMAIL_USAGE("flex-email-usage"), - FLEX_MESSAGING_USAGE("flex-messaging-usage"), - FLEX_PARTNER_SPINSCI("flex-partner-spinsci"), - FLEX_PARTNER_XCELERATE("flex-partner-xcelerate"), - FLEX_RESELLER_ECOSYSTEM("flex-reseller-ecosystem"), - FLEX_UNIQUE_USER("flex-unique-user"), - FLEX_USAGE("flex-usage"), - FLEX_USERS("flex-users"), - FLEX_VOICE_MINUTE("flex-voice-minute"), - FLEX_YTICA("flex-ytica"), - FRAUD_LOOKUPS("fraud-lookups"), - FRONTLINE("frontline"), - FRONTLINE_USERS("frontline-users"), - FUNCTIONS("functions"), - GENERIC_PAY_TRANSACTIONS("generic-pay-transactions"), - GROUP_ROOMS("group-rooms"), - GROUP_ROOMS_DATA_TRACK("group-rooms-data-track"), - GROUP_ROOMS_ENCRYPTED_MEDIA_RECORDED( - "group-rooms-encrypted-media-recorded" - ), - GROUP_ROOMS_MEDIA_DOWNLOADED("group-rooms-media-downloaded"), - GROUP_ROOMS_MEDIA_RECORDED("group-rooms-media-recorded"), - GROUP_ROOMS_MEDIA_ROUTED("group-rooms-media-routed"), - GROUP_ROOMS_MEDIA_STORED("group-rooms-media-stored"), - GROUP_ROOMS_PARTICIPANT_MINUTES("group-rooms-participant-minutes"), - GROUP_ROOMS_RECORDED_MINUTES("group-rooms-recorded-minutes"), - IP_MESSAGING("ip-messaging"), - IP_MESSAGING_COMMANDS("ip-messaging-commands"), - IP_MESSAGING_DATA_STORAGE("ip-messaging-data-storage"), - IP_MESSAGING_DATA_TRANSFER("ip-messaging-data-transfer"), - IP_MESSAGING_ENDPOINT_CONNECTIVITY( - "ip-messaging-endpoint-connectivity" - ), - IVR_VIRTUAL_AGENT_CUSTOM_VOICES("ivr-virtual-agent-custom-voices"), - IVR_VIRTUAL_AGENT_GENAI("ivr-virtual-agent-genai"), - LINE_STATUS_LOOKUPS("line-status-lookups"), - LIVE_ACTIVITY_LOOKUPS("live-activity-lookups"), - LOOKUP_BUCKET_ADJUSTMENT("lookup-bucket-adjustment"), - LOOKUP_IDENTITY_MATCH("lookup-identity-match"), - LOOKUPS("lookups"), - MARKETPLACE("marketplace"), - MARKETPLACE_ALGORITHMIA_NAMED_ENTITY_RECOGNITION( - "marketplace-algorithmia-named-entity-recognition" - ), - MARKETPLACE_CADENCE_TRANSCRIPTION("marketplace-cadence-transcription"), - MARKETPLACE_CADENCE_TRANSLATION("marketplace-cadence-translation"), - MARKETPLACE_CAPIO_SPEECH_TO_TEXT("marketplace-capio-speech-to-text"), - MARKETPLACE_CONVRIZA_ABABA("marketplace-convriza-ababa"), - MARKETPLACE_DEEPGRAM_PHRASE_DETECTOR( - "marketplace-deepgram-phrase-detector" - ), - MARKETPLACE_DEEPGRAM_TRANSCRIPTION( - "marketplace-deepgram-transcription" - ), - MARKETPLACE_DEEPGRAM_TRANSCRIPTION_BASE( - "marketplace-deepgram-transcription-base" - ), - MARKETPLACE_DEEPGRAM_TRANSSCRIPTION_ENHANCED( - "marketplace-deepgram-transscription-enhanced" - ), - MARKETPLACE_DIGITAL_SEGMENT_BUSINESS_INFO( - "marketplace-digital-segment-business-info" - ), - MARKETPLACE_FACEBOOK_OFFLINE_CONVERSIONS( - "marketplace-facebook-offline-conversions" - ), - MARKETPLACE_GOOGLE_SPEECH_TO_TEXT("marketplace-google-speech-to-text"), - MARKETPLACE_IBM_WATSON_MESSAGE_INSIGHTS( - "marketplace-ibm-watson-message-insights" - ), - MARKETPLACE_IBM_WATSON_MESSAGE_SENTIMENT( - "marketplace-ibm-watson-message-sentiment" - ), - MARKETPLACE_IBM_WATSON_RECORDING_ANALYSIS( - "marketplace-ibm-watson-recording-analysis" - ), - MARKETPLACE_IBM_WATSON_TONE_ANALYZER( - "marketplace-ibm-watson-tone-analyzer" - ), - MARKETPLACE_ICEHOOK_SYSTEMS_SCOUT("marketplace-icehook-systems-scout"), - MARKETPLACE_INFOGROUP_DATAAXLE_BIZINFO( - "marketplace-infogroup-dataaxle-bizinfo" - ), - MARKETPLACE_KEEN_IO_CONTACT_CENTER_ANALYTICS( - "marketplace-keen-io-contact-center-analytics" - ), - MARKETPLACE_MARCHEX_CLEANCALL("marketplace-marchex-cleancall"), - MARKETPLACE_MARCHEX_RECORDING_ANALYSIS( - "marketplace-marchex-recording-analysis" - ), - MARKETPLACE_MARCHEX_SENTIMENT_ANALYSIS_FOR_SMS( - "marketplace-marchex-sentiment-analysis-for-sms" - ), - MARKETPLACE_MARKETPLACE_NEXTCALLER_SOCIAL_ID( - "marketplace-marketplace-nextcaller-social-id" - ), - MARKETPLACE_MOBILE_COMMONS_OPT_OUT_CLASSIFIER( - "marketplace-mobile-commons-opt-out-classifier" - ), - MARKETPLACE_NEXIWAVE_VOICEMAIL_TO_TEXT( - "marketplace-nexiwave-voicemail-to-text" - ), - MARKETPLACE_NEXTCALLER_ADVANCED_CALLER_IDENTIFICATION( - "marketplace-nextcaller-advanced-caller-identification" - ), - MARKETPLACE_NOMOROBO_SPAM_SCORE("marketplace-nomorobo-spam-score"), - MARKETPLACE_PAY_ADDONS("marketplace-pay-addons"), - MARKETPLACE_PAY_ADDONS_BASECOMMERCE_PAY_CONNECTOR( - "marketplace-pay-addons-basecommerce-pay-connector" - ), - MARKETPLACE_PAY_ADDONS_BRAINTREE_PAY_CONNECTOR( - "marketplace-pay-addons-braintree-pay-connector" - ), - MARKETPLACE_PAY_ADDONS_CARDCONNECT_PAY_CONNECTOR( - "marketplace-pay-addons-cardconnect-pay-connector" - ), - MARKETPLACE_PAY_ADDONS_CHASE_PAY_CONNECTOR( - "marketplace-pay-addons-chase-pay-connector" - ), - MARKETPLACE_PAY_ADDONS_SHUTTLE_PAY_CONNECTOR( - "marketplace-pay-addons-shuttle-pay-connector" - ), - MARKETPLACE_PAY_ADDONS_STRIPE_PAY_CONNECTOR( - "marketplace-pay-addons-stripe-pay-connector" - ), - MARKETPLACE_PAYFONE_TCPA_COMPLIANCE( - "marketplace-payfone-tcpa-compliance" - ), - MARKETPLACE_POLY_AI_CONNECTOR("marketplace-poly-ai-connector"), - MARKETPLACE_REALPHONEVALIDATION("marketplace-realphonevalidation"), - MARKETPLACE_REMEETING_AUTOMATIC_SPEECH_RECOGNITION( - "marketplace-remeeting-automatic-speech-recognition" - ), - MARKETPLACE_SPOKE_PHONE_LICENSE_PRO( - "marketplace-spoke-phone-license-pro" - ), - MARKETPLACE_SPOKE_PHONE_LICENSE_STANDARD( - "marketplace-spoke-phone-license-standard" - ), - MARKETPLACE_TCPA_DEFENSE_SOLUTIONS_BLACKLIST_FEED( - "marketplace-tcpa-defense-solutions-blacklist-feed" - ), - MARKETPLACE_TELO_OPENCNAM("marketplace-telo-opencnam"), - MARKETPLACE_TRESTLE_SOLUTIONS_CALLER_IDENTIFICATION( - "marketplace-trestle-solutions-caller-identification" - ), - MARKETPLACE_TRUECNAM_TRUE_SPAM("marketplace-truecnam-true-spam"), - MARKETPLACE_TWILIO_CALLER_NAME_LOOKUP_US( - "marketplace-twilio-caller-name-lookup-us" - ), - MARKETPLACE_TWILIO_CARRIER_INFORMATION_LOOKUP( - "marketplace-twilio-carrier-information-lookup" - ), - MARKETPLACE_VOICEBASE_PCI("marketplace-voicebase-pci"), - MARKETPLACE_VOICEBASE_TRANSCRIPTION( - "marketplace-voicebase-transcription" - ), - MARKETPLACE_VOICEBASE_TRANSCRIPTION_CUSTOM_VOCABULARY( - "marketplace-voicebase-transcription-custom-vocabulary" - ), - MARKETPLACE_WEB_PURIFY_PROFANITY_FILTER( - "marketplace-web-purify-profanity-filter" - ), - MARKETPLACE_WHITEPAGES_PRO_CALLER_IDENTIFICATION( - "marketplace-whitepages-pro-caller-identification" - ), - MARKETPLACE_WHITEPAGES_PRO_PHONE_INTELLIGENCE( - "marketplace-whitepages-pro-phone-intelligence" - ), - MARKETPLACE_WHITEPAGES_PRO_PHONE_REPUTATION( - "marketplace-whitepages-pro-phone-reputation" - ), - MARKETPLACE_WOLFARM_SPOKEN_RESULTS( - "marketplace-wolfarm-spoken-results" - ), - MARKETPLACE_WOLFRAM_SHORT_ANSWER("marketplace-wolfram-short-answer"), - MARKETPLACE_YTICA_CONTACT_CENTER_REPORTING_ANALYTICS( - "marketplace-ytica-contact-center-reporting-analytics" - ), - MARKETPLAY_PAY_ADDONS_SHUTTLE_PAY_CONNECTOR( - "marketplay-pay-addons-shuttle-pay-connector" - ), - MEDIA_COMPOSER_MINUTES("media-composer-minutes"), - MEDIASTORAGE("mediastorage"), - MIN_SPEND_ADJUSTMENTS("min-spend-adjustments"), - MMS("mms"), - MMS_INBOUND("mms-inbound"), - MMS_INBOUND_LONGCODE("mms-inbound-longcode"), - MMS_INBOUND_SHORTCODE("mms-inbound-shortcode"), - MMS_INBOUND_TOLL_FREE("mms-inbound-toll-free"), - MMS_MESSAGES_CARRIERFEES("mms-messages-carrierfees"), - MMS_OUTBOUND("mms-outbound"), - MMS_OUTBOUND_LONGCODE("mms-outbound-longcode"), - MMS_OUTBOUND_SHORTCODE("mms-outbound-shortcode"), - MMS_OUTBOUND_TOLLFREE("mms-outbound-tollfree"), - MONITOR("monitor"), - MONITOR_READS("monitor-reads"), - MONITOR_STORAGE("monitor-storage"), - MONITOR_WRITES("monitor-writes"), - NOTIFY("notify"), - NOTIFY_ACTIONS_ATTEMPTS("notify-actions-attempts"), - NOTIFY_CHANNELS("notify-channels"), - NUMBER_FORMAT_LOOKUPS("number-format-lookups"), - PCHAT("pchat"), - PCHAT_ACTIONS("pchat-actions"), - PCHAT_APS("pchat-aps"), - PCHAT_CONV_MED_STORAGE("pchat-conv-med-storage"), - PCHAT_MESSAGES("pchat-messages"), - PCHAT_NOTIFICATIONS("pchat-notifications"), - PCHAT_READS("pchat-reads"), - PCHAT_USERS("pchat-users"), - PEER_TO_PEER_ROOMS_PARTICIPANT_MINUTES( - "peer-to-peer-rooms-participant-minutes" - ), - PFAX("pfax"), - PFAX_MINUTES("pfax-minutes"), - PFAX_MINUTES_INBOUND("pfax-minutes-inbound"), - PFAX_MINUTES_OUTBOUND("pfax-minutes-outbound"), - PFAX_PAGES("pfax-pages"), - PHONE_QUALITY_SCORE_LOOKUPS("phone-quality-score-lookups"), - PHONENUMBERS("phonenumbers"), - PHONENUMBERS_CPS("phonenumbers-cps"), - PHONENUMBERS_EMERGENCY("phonenumbers-emergency"), - PHONENUMBERS_LOCAL("phonenumbers-local"), - PHONENUMBERS_MOBILE("phonenumbers-mobile"), - PHONENUMBERS_PORTING("phonenumbers-porting"), - PHONENUMBERS_SETUPS("phonenumbers-setups"), - PHONENUMBERS_TOLLFREE("phonenumbers-tollfree"), - PREMIUMSUPPORT("premiumsupport"), - PREMIUMSUPPORT_PERCENTAGE_SPEND("premiumsupport-percentage-spend"), - PROGRAMMABLEVOICE_PLATFORM("programmablevoice-platform"), - PROGRAMMABLEVOICECONN_CLIENTSDK("programmablevoiceconn-clientsdk"), - PROGRAMMABLEVOICECONN_CLIENTSDK_INBOUND( - "programmablevoiceconn-clientsdk-inbound" - ), - PROGRAMMABLEVOICECONN_CLIENTSDK_OUTBOUND( - "programmablevoiceconn-clientsdk-outbound" - ), - PROGRAMMABLEVOICECONN_ONNET("programmablevoiceconn-onnet"), - PROGRAMMABLEVOICECONN_ONNET_INBOUND( - "programmablevoiceconn-onnet-inbound" - ), - PROGRAMMABLEVOICECONN_ONNET_OUTBOUND( - "programmablevoiceconn-onnet-outbound" - ), - PROGRAMMABLEVOICECONN_SIP("programmablevoiceconn-sip"), - PROGRAMMABLEVOICECONN_SIP_INBOUND("programmablevoiceconn-sip-inbound"), - PROGRAMMABLEVOICECONN_SIP_OUTBOUND( - "programmablevoiceconn-sip-outbound" - ), - PROGRAMMABLEVOICECONNECTIVITY("programmablevoiceconnectivity"), - PROXY("proxy"), - PROXY_ACTIVE_SESSIONS("proxy-active-sessions"), - PROXY_BUCKET_ADJUSTMENT("proxy-bucket-adjustment"), - PROXY_LICENSES("proxy-licenses"), - PSTNCONNECTIVITY("pstnconnectivity"), - PSTNCONNECTIVITY_INBOUND("pstnconnectivity-inbound"), - PSTNCONNECTIVITY_OUTBOUND("pstnconnectivity-outbound"), - PV("pv"), - PV_BASIC_ROOMS("pv-basic-rooms"), - PV_COMPOSITION_MEDIA_DOWNLOADED("pv-composition-media-downloaded"), - PV_COMPOSITION_MEDIA_ENCRYPTED("pv-composition-media-encrypted"), - PV_COMPOSITION_MEDIA_STORED("pv-composition-media-stored"), - PV_COMPOSITION_MINUTES("pv-composition-minutes"), - PV_RECORDING_COMPOSITIONS("pv-recording-compositions"), - PV_ROOM_PARTICIPANTS("pv-room-participants"), - PV_ROOM_PARTICIPANTS_AU1("pv-room-participants-au1"), - PV_ROOM_PARTICIPANTS_BR1("pv-room-participants-br1"), - PV_ROOM_PARTICIPANTS_IE1("pv-room-participants-ie1"), - PV_ROOM_PARTICIPANTS_JP1("pv-room-participants-jp1"), - PV_ROOM_PARTICIPANTS_SG1("pv-room-participants-sg1"), - PV_ROOM_PARTICIPANTS_US1("pv-room-participants-us1"), - PV_ROOM_PARTICIPANTS_US2("pv-room-participants-us2"), - PV_ROOMS("pv-rooms"), - PV_SIP_ENDPOINT_REGISTRATIONS("pv-sip-endpoint-registrations"), - RCS_MESSAGES("rcs-messages"), - REASSIGNED_NUMBER("reassigned-number"), - RECORDINGS("recordings"), - RECORDINGSTORAGE("recordingstorage"), - SHORTCODES("shortcodes"), - SHORTCODES_CUSTOMEROWNED("shortcodes-customerowned"), - SHORTCODES_MMS_ENABLEMENT("shortcodes-mms-enablement"), - SHORTCODES_MPS("shortcodes-mps"), - SHORTCODES_RANDOM("shortcodes-random"), - SHORTCODES_SETUP_FEES("shortcodes-setup-fees"), - SHORTCODES_UK("shortcodes-uk"), - SHORTCODES_VANITY("shortcodes-vanity"), - SIM_SWAP_LOOKUPS("sim-swap-lookups"), - SIP_SECURE_MEDIA("sip-secure-media"), - SMALL_GROUP_ROOMS("small-group-rooms"), - SMALL_GROUP_ROOMS_DATA_TRACK("small-group-rooms-data-track"), - SMALL_GROUP_ROOMS_PARTICIPANT_MINUTES( - "small-group-rooms-participant-minutes" - ), - SMS("sms"), - SMS_INBOUND("sms-inbound"), - SMS_INBOUND_LONGCODE("sms-inbound-longcode"), - SMS_INBOUND_SHORTCODE("sms-inbound-shortcode"), - SMS_INBOUND_TOLLFREE("sms-inbound-tollfree"), - SMS_MESSAGES_CARRIERFEES("sms-messages-carrierfees"), - SMS_MESSAGES_FEATURES("sms-messages-features"), - SMS_MESSAGES_FEATURES_ENGAGEMENT_SUITE( - "sms-messages-features-engagement-suite" - ), - SMS_MESSAGES_FEATURES_MESSAGE_REDACTION( - "sms-messages-features-message-redaction" - ), - SMS_MESSAGES_FEATURES_SENDERID("sms-messages-features-senderid"), - SMS_MPS("sms-mps"), - SMS_MPS_SHORTCODE("sms-mps-shortcode"), - SMS_MPS_TOLLFREE("sms-mps-tollfree"), - SMS_MPS_TOLLFREE_SETUP("sms-mps-tollfree-setup"), - SMS_NATIONAL_REGULATORY_PROTECTION( - "sms-national-regulatory-protection" - ), - SMS_OUTBOUND("sms-outbound"), - SMS_OUTBOUND_CONTENT_INSPECTION("sms-outbound-content-inspection"), - SMS_OUTBOUND_LONGCODE("sms-outbound-longcode"), - SMS_OUTBOUND_SHORTCODE("sms-outbound-shortcode"), - SMS_OUTBOUND_TOLLFREE("sms-outbound-tollfree"), - SMS_PUMPING_PROTECTION("sms-pumping-protection"), - SMS_PUMPING_RISK("sms-pumping-risk"), - SMSMESSAGES_BUCKET_ADJUSTMENTS("smsmessages-bucket-adjustments"), - SMSMESSAGES_OUTBOUND_DOMESTIC("smsmessages-outbound-domestic"), - SPEECH_RECOGNITION("speech-recognition"), - STUDIO_ENGAGEMENTS("studio-engagements"), - SYNC("sync"), - SYNC_ACTIONS("sync-actions"), - SYNC_ENDPOINT_HOURS("sync-endpoint-hours"), - SYNC_ENDPOINT_HOURS_ABOVE_DAILY_CAP( - "sync-endpoint-hours-above-daily-cap" - ), - TASKROUTER_TASKS("taskrouter-tasks"), - TOTALPRICE("totalprice"), - TRANSCRIPTIONS("transcriptions"), - TRUNKING_CPS("trunking-cps"), - TRUNKING_EMERGENCY_CALLS("trunking-emergency-calls"), - TRUNKING_ORIGINATION("trunking-origination"), - TRUNKING_ORIGINATION_LOCAL("trunking-origination-local"), - TRUNKING_ORIGINATION_MOBILE("trunking-origination-mobile"), - TRUNKING_ORIGINATION_TOLLFREE("trunking-origination-tollfree"), - TRUNKING_RECORDINGS("trunking-recordings"), - TRUNKING_SECURE("trunking-secure"), - TRUNKING_TERMINATION("trunking-termination"), - TTS_GOOGLE("tts-google"), - TURNMEGABYTES("turnmegabytes"), - TURNMEGABYTES_AUSTRALIA("turnmegabytes-australia"), - TURNMEGABYTES_BRASIL("turnmegabytes-brasil"), - TURNMEGABYTES_GERMANY("turnmegabytes-germany"), - TURNMEGABYTES_INDIA("turnmegabytes-india"), - TURNMEGABYTES_IRELAND("turnmegabytes-ireland"), - TURNMEGABYTES_JAPAN("turnmegabytes-japan"), - TURNMEGABYTES_SINGAPORE("turnmegabytes-singapore"), - TURNMEGABYTES_USEAST("turnmegabytes-useast"), - TURNMEGABYTES_USWEST("turnmegabytes-uswest"), - TWILIO_FOR_SALESFORCE("twilio-for-salesforce"), - TWILIO_FOR_SALESFORCE_LICENSES("twilio-for-salesforce-licenses"), - TWILIO_INTERCONNECT("twilio-interconnect"), - TWIML("twiml"), - USAGE_FLEX_VIDEO("usage-flex-video"), - USAGE_FUNCTIONS("usage-functions"), - USAGE_RCS_BASIC_MESSAGES_OUTBOUND("usage-rcs-basic-messages-outbound"), - USAGE_RCS_MESSAGES("usage-rcs-messages"), - USAGE_RCS_MESSAGES_INBOUND("usage-rcs-messages-inbound"), - USAGE_RCS_MESSAGING_CARRIER_FEES("usage-rcs-messaging-carrier-fees"), - USAGE_RCS_SINGLE_MESSAGES_OUTBOUND( - "usage-rcs-single-messages-outbound" - ), - VERIFY_PACKAGE_PLANS("verify-package-plans"), - VERIFY_PUSH("verify-push"), - VERIFY_SNA("verify-sna"), - VERIFY_TOTP("verify-totp"), - VERIFY_VOICE_SMS("verify-voice-sms"), - VERIFY_WHATSAPP_CONVERSATIONS_BUSINESS_INITIATED( - "verify-whatsapp-conversations-business-initiated" - ), - VERIFY_WHATSAPP_TEMPLATE_BUSINESS_INITIATED( - "verify-whatsapp-template-business-initiated" - ), - VIDEO_RECORDINGS("video-recordings"), - VIDEO_ROOMS_TURN_MEGABYTES("video-rooms-turn-megabytes"), - VIRTUAL_AGENT("virtual-agent"), - VOICE_INSIGHTS("voice-insights"), - VOICE_INSIGHTS_CLIENT_INSIGHTS_ON_DEMAND_MINUTE( - "voice-insights-client-insights-on-demand-minute" - ), - VOICE_INSIGHTS_PTSN_INSIGHTS_ON_DEMAND_MINUTE( - "voice-insights-ptsn-insights-on-demand-minute" - ), - VOICE_INSIGHTS_SIP_INTERFACE_INSIGHTS_ON_DEMAND_MINUTE( - "voice-insights-sip-interface-insights-on-demand-minute" - ), - VOICE_INSIGHTS_SIP_TRUNKING_INSIGHTS_ON_DEMAND_MINUTE( - "voice-insights-sip-trunking-insights-on-demand-minute" - ), - VOICE_INTELLIGENCE("voice-intelligence"), - VOICE_INTELLIGENCE_EIP_OPERATORS("voice-intelligence-eip-operators"), - VOICE_INTELLIGENCE_OPERATORS("voice-intelligence-operators"), - VOICE_INTELLIGENCE_TRANSCRIPTION("voice-intelligence-transcription"), - WDS("wds"), - WIRELESS("wireless"), - WIRELESS_DATA("wireless-data"), - WIRELESS_DATA_PAYG("wireless-data-payg"), - WIRELESS_DATA_PAYG_AFRICA("wireless-data-payg-africa"), - WIRELESS_DATA_PAYG_ASIA("wireless-data-payg-asia"), - WIRELESS_DATA_PAYG_CENTRALANDSOUTHAMERICA( - "wireless-data-payg-centralandsouthamerica" - ), - WIRELESS_DATA_PAYG_EUROPE("wireless-data-payg-europe"), - WIRELESS_DATA_PAYG_NORTHAMERICA("wireless-data-payg-northamerica"), - WIRELESS_DATA_PAYG_OCEANIA("wireless-data-payg-oceania"), - WIRELESS_DATA_QUOTA1("wireless-data-quota1"), - WIRELESS_DATA_QUOTA1_AFRICA("wireless-data-quota1-africa"), - WIRELESS_DATA_QUOTA1_ASIA("wireless-data-quota1-asia"), - WIRELESS_DATA_QUOTA1_CENTRALANDSOUTHAMERICA( - "wireless-data-quota1-centralandsouthamerica" - ), - WIRELESS_DATA_QUOTA1_EUROPE("wireless-data-quota1-europe"), - WIRELESS_DATA_QUOTA1_NORTHAMERICA("wireless-data-quota1-northamerica"), - WIRELESS_DATA_QUOTA1_OCEANIA("wireless-data-quota1-oceania"), - WIRELESS_DATA_QUOTA10("wireless-data-quota10"), - WIRELESS_DATA_QUOTA10_AFRICA("wireless-data-quota10-africa"), - WIRELESS_DATA_QUOTA10_ASIA("wireless-data-quota10-asia"), - WIRELESS_DATA_QUOTA10_CENTRALANDSOUTHAMERICA( - "wireless-data-quota10-centralandsouthamerica" - ), - WIRELESS_DATA_QUOTA10_EUROPE("wireless-data-quota10-europe"), - WIRELESS_DATA_QUOTA10_NORTHAMERICA( - "wireless-data-quota10-northamerica" - ), - WIRELESS_DATA_QUOTA10_OCEANIA("wireless-data-quota10-oceania"), - WIRELESS_DATA_QUOTA50("wireless-data-quota50"), - WIRELESS_DATA_QUOTA50_AFRICA("wireless-data-quota50-africa"), - WIRELESS_DATA_QUOTA50_ASIA("wireless-data-quota50-asia"), - WIRELESS_DATA_QUOTA50_CENTRALANDSOUTHAMERICA( - "wireless-data-quota50-centralandsouthamerica" - ), - WIRELESS_DATA_QUOTA50_EUROPE("wireless-data-quota50-europe"), - WIRELESS_DATA_QUOTA50_NORTHAMERICA( - "wireless-data-quota50-northamerica" - ), - WIRELESS_DATA_QUOTA50_OCEANIA("wireless-data-quota50-oceania"), - WIRELESS_DATA_QUOTACUSTOM("wireless-data-quotacustom"), - WIRELESS_DATA_QUOTACUSTOM_AFRICA("wireless-data-quotacustom-africa"), - WIRELESS_DATA_QUOTACUSTOM_ASIA("wireless-data-quotacustom-asia"), - WIRELESS_DATA_QUOTACUSTOM_CENTRALANDSOUTHAMERICA( - "wireless-data-quotacustom-centralandsouthamerica" - ), - WIRELESS_DATA_QUOTACUSTOM_EUROPE("wireless-data-quotacustom-europe"), - WIRELESS_DATA_QUOTACUSTOM_NORTHAMERICA( - "wireless-data-quotacustom-northamerica" - ), - WIRELESS_DATA_QUOTACUSTOM_OCEANIA("wireless-data-quotacustom-oceania"), - WIRELESS_MRC_PAYG("wireless-mrc-payg"), - WIRELESS_MRC_QUOTA1("wireless-mrc-quota1"), - WIRELESS_MRC_QUOTA10("wireless-mrc-quota10"), - WIRELESS_MRC_QUOTA50("wireless-mrc-quota50"), - WIRELESS_MRC_QUOTACUSTOM("wireless-mrc-quotacustom"), - WIRELESS_ORDERS("wireless-orders"), - WIRELESS_ORDERS_ARTWORK("wireless-orders-artwork"), - WIRELESS_ORDERS_BULK("wireless-orders-bulk"), - WIRELESS_ORDERS_ESIM("wireless-orders-esim"), - WIRELESS_ORDERS_STARTER("wireless-orders-starter"), - WIRELESS_QUOTAS("wireless-quotas"), - WIRELESS_SMS_AFRICA("wireless-sms-africa"), - WIRELESS_SMS_ASIA("wireless-sms-asia"), - WIRELESS_SMS_CENTRALANDSOUTHAMERICA( - "wireless-sms-centralandsouthamerica" - ), - WIRELESS_SMS_EUROPE("wireless-sms-europe"), - WIRELESS_SMS_NORTHAMERICA("wireless-sms-northamerica"), - WIRELESS_SMS_OCEANIA("wireless-sms-oceania"), - WIRELESS_SUPER_SIM("wireless-super-sim"), - WIRELESS_SUPER_SIM_DATA("wireless-super-sim-data"), - WIRELESS_SUPER_SIM_DATA_NORTH_AMERICA_USA( - "wireless-super-sim-data-north-america-usa" - ), - WIRELESS_SUPER_SIM_DATA_PAYG("wireless-super-sim-data-payg"), - WIRELESS_SUPER_SIM_DATA_PAYG_EUROPE( - "wireless-super-sim-data-payg-europe" - ), - WIRELESS_SUPER_SIM_DATA_PAYG_NORTH_AMERICA( - "wireless-super-sim-data-payg-north-america" - ), - WIRELESS_SUPER_SIM_HARDWARE("wireless-super-sim-hardware"), - WIRELESS_SUPER_SIM_HARDWARE_BULK("wireless-super-sim-hardware-bulk"), - WIRELESS_SUPER_SIM_SMSCOMMANDS("wireless-super-sim-smscommands"), - WIRELESS_SUPER_SIM_SMSCOMMANDS_AFRICA( - "wireless-super-sim-smscommands-africa" - ), - WIRELESS_SUPER_SIM_SMSCOMMANDS_ASIA( - "wireless-super-sim-smscommands-asia" - ), - WIRELESS_SUPER_SIM_SMSCOMMANDS_CENT_AND_SOUTH_AMERICA( - "wireless-super-sim-smscommands-cent-and-south-america" - ), - WIRELESS_SUPER_SIM_SMSCOMMANDS_EUROPE( - "wireless-super-sim-smscommands-europe" - ), - WIRELESS_SUPER_SIM_SMSCOMMANDS_NORTH_AMERICA( - "wireless-super-sim-smscommands-north-america" - ), - WIRELESS_SUPER_SIM_SMSCOMMANDS_OCEANIA( - "wireless-super-sim-smscommands-oceania" - ), - WIRELESS_SUPER_SIM_SUBSCRIPTION("wireless-super-sim-subscription"), - WIRELESS_SUPER_SIM_SUBSCRIPTION_PAYG( - "wireless-super-sim-subscription-payg" - ), - WIRELESS_USAGE("wireless-usage"), - WIRELESS_USAGE_COMMANDS("wireless-usage-commands"), - WIRELESS_USAGE_COMMANDS_AFRICA("wireless-usage-commands-africa"), - WIRELESS_USAGE_COMMANDS_ASIA("wireless-usage-commands-asia"), - WIRELESS_USAGE_COMMANDS_CENTRALANDSOUTHAMERICA( - "wireless-usage-commands-centralandsouthamerica" - ), - WIRELESS_USAGE_COMMANDS_EUROPE("wireless-usage-commands-europe"), - WIRELESS_USAGE_COMMANDS_HOME("wireless-usage-commands-home"), - WIRELESS_USAGE_COMMANDS_NORTHAMERICA( - "wireless-usage-commands-northamerica" - ), - WIRELESS_USAGE_COMMANDS_OCEANIA("wireless-usage-commands-oceania"), - WIRELESS_USAGE_COMMANDS_ROAMING("wireless-usage-commands-roaming"), - WIRELESS_USAGE_DATA("wireless-usage-data"), - WIRELESS_USAGE_DATA_AFRICA("wireless-usage-data-africa"), - WIRELESS_USAGE_DATA_ASIA("wireless-usage-data-asia"), - WIRELESS_USAGE_DATA_CENTRALANDSOUTHAMERICA( - "wireless-usage-data-centralandsouthamerica" - ), - WIRELESS_USAGE_DATA_CUSTOM_ADDITIONALMB( - "wireless-usage-data-custom-additionalmb" - ), - WIRELESS_USAGE_DATA_CUSTOM_FIRST5MB( - "wireless-usage-data-custom-first5mb" - ), - WIRELESS_USAGE_DATA_DOMESTIC_ROAMING( - "wireless-usage-data-domestic-roaming" - ), - WIRELESS_USAGE_DATA_EUROPE("wireless-usage-data-europe"), - WIRELESS_USAGE_DATA_INDIVIDUAL_ADDITIONALGB( - "wireless-usage-data-individual-additionalgb" - ), - WIRELESS_USAGE_DATA_INDIVIDUAL_FIRSTGB( - "wireless-usage-data-individual-firstgb" - ), - WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_CANADA( - "wireless-usage-data-international-roaming-canada" - ), - WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_INDIA( - "wireless-usage-data-international-roaming-india" - ), - WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_MEXICO( - "wireless-usage-data-international-roaming-mexico" - ), - WIRELESS_USAGE_DATA_NORTHAMERICA("wireless-usage-data-northamerica"), - WIRELESS_USAGE_DATA_OCEANIA("wireless-usage-data-oceania"), - WIRELESS_USAGE_DATA_POOLED("wireless-usage-data-pooled"), - WIRELESS_USAGE_DATA_POOLED_DOWNLINK( - "wireless-usage-data-pooled-downlink" - ), - WIRELESS_USAGE_DATA_POOLED_UPLINK("wireless-usage-data-pooled-uplink"), - WIRELESS_USAGE_MRC("wireless-usage-mrc"), - WIRELESS_USAGE_MRC_CUSTOM("wireless-usage-mrc-custom"), - WIRELESS_USAGE_MRC_INDIVIDUAL("wireless-usage-mrc-individual"), - WIRELESS_USAGE_MRC_POOLED("wireless-usage-mrc-pooled"), - WIRELESS_USAGE_MRC_SUSPENDED("wireless-usage-mrc-suspended"), - WIRELESS_USAGE_SMS("wireless-usage-sms"), - WIRELESS_USAGE_VOICE("wireless-usage-voice"), - A2P_FAST_TRACK_ONBOARDING("a2p-fast-track-onboarding"), - ADVISORY_SERVICES("advisory-services"), - ADVISORY_SERVICES_BILLED("advisory-services-billed"), - ADVISORY_SERVICES_CALL_TRACKING("advisory-services-call-tracking"), - ADVISORY_SERVICES_DATA_SERVICES("advisory-services-data-services"), - ADVISORY_SERVICES_EXPENSES("advisory-services-expenses"), - ADVISORY_SERVICES_SIP_TRUNKING("advisory-services-sip-trunking"), - ASSETS_REQUESTS("assets-requests"), - AUDIENCE_MINUTES_VIDEO("audience-minutes-video"), - AUTHY_BUCKET_ADJUSTMENT("authy-bucket-adjustment"), - AUTHY_SOFTWARE("authy-software"), - CALLERIDLOOKUPS_API("calleridlookups-api"), - CALLERIDLOOKUPS_PROGRAMMABLEVOICE("calleridlookups-programmablevoice"), - CALLERIDLOOKUPS_TRUNKING("calleridlookups-trunking"), - CALLS_TRUNKING_INBOUND_TOLLFREE_LOCAL( - "calls-trunking-inbound-tollfree-local" - ), - CALLS_TRUNKING_INBOUND_TOLLFREE_MOBILE( - "calls-trunking-inbound-tollfree-mobile" - ), - CHANNELS_WHATSAPP_CONVERSATION_FREE_1( - "channels-whatsapp-conversation-free-1" - ), - CONFERENCE("conference"), - CONVERSATIONAL_INSIGHTS("conversational-insights"), - CONVERSATIONAL_INSIGHTS_MESSAGES("conversational-insights-messages"), - CONVERSATIONAL_INSIGHTS_VOICE_MINUTES( - "conversational-insights-voice-minutes" - ), - DEMO("demo"), - DEMO_UC_SCRIPT_TEST("demo-uc-script-test"), - ELASTIC_SIP_TRUNKING("elastic-sip-trunking"), - ELASTIC_SIP_TRUNKING_CALL_TRANSFERS( - "elastic-sip-trunking-call-transfers" - ), - ENTERPRISE_HIPPA("enterprise-hippa"), - FLEX_NAMED_USERS("flex-named-users"), - FLEX_SPINSCI("flex-spinsci"), - FLEX_USERS_1("flex-users-1"), - FLEX_WFO_PREMIUM_SPEECH_ANALYTICS("flex-wfo-premium-speech-analytics"), - FLEX_XCELERATE("flex-xcelerate"), - FUNCTIONS_ROLLUP("functions-rollup"), - IMP_V1_USAGE("imp-v1-usage"), - IP_MESSAGING_ADDONS("ip-messaging-addons"), - IVR("ivr"), - IVR_CONVERSATIONAL("ivr-conversational"), - IVR_DTMF("ivr-dtmf"), - IVR_VIRTUALAGENT("ivr-virtualagent"), - LIVE("live"), - LIVE_MEDIA_RECORDING_MINUTES("live-media-recording-minutes"), - LONGCODE_MPS("longcode-mps"), - MARKETPLACE_ANALYTICS_ADDONS("marketplace-analytics-addons"), - MARKETPLACE_ISV_ADDONS("marketplace-isv-addons"), - MARKETPLACE_MESSAGING_ADDONS("marketplace-messaging-addons"), - MARKETPLACE_PHONENUMBERS_ADDONS("marketplace-phonenumbers-addons"), - MARKETPLACE_RECORDING_ADDONS("marketplace-recording-addons"), - MARKETPLACE_VIRTUALAGENT_ADDONS("marketplace-virtualagent-addons"), - MARKETPLAY_PAY_ADDONS_SHUTTLE_PAY_CONNECTOR_1( - "marketplay-pay-addons-shuttle-pay-connector-1" - ), - MARKETPLAY_PAY_ADDONS_STRIPE_PAY_CONNECTOR( - "marketplay-pay-addons-stripe-pay-connector" - ), - MMS_INBOUND_LONGCODE_CANADA("mms-inbound-longcode-canada"), - MMS_INBOUND_LONGCODE_UNITEDSTATES("mms-inbound-longcode-unitedstates"), - MMS_OUTBOUND_LONGCODE_CANADA("mms-outbound-longcode-canada"), - MMS_OUTBOUND_LONGCODE_UNITEDSTATES( - "mms-outbound-longcode-unitedstates" - ), - MMS_OUTBOUND_TOLL_FREE("mms-outbound-toll-free"), - NOTIFY_CHATAPPSANDOTHERCHANNELS("notify-chatappsandotherchannels"), - NOTIFY_NOTIFYSERVICES("notify-notifyservices"), - NOTIFY_PUSHNOTIFICATIONS("notify-pushnotifications"), - PAYMENT_GATEWAY_CONNECTORS("payment-gateway-connectors"), - PAYMENT_SOLUTIONS("payment-solutions"), - PCHAT_BUCKET_ADJUSTMENT("pchat-bucket-adjustment"), - PHONENUMBERS_NUMBERS("phonenumbers-numbers"), - PROG_VOICE_CLIENT_ANDROID("prog-voice-client-android"), - PROG_VOICE_CLIENT_ANDROID_INBOUND("prog-voice-client-android-inbound"), - PROG_VOICE_CLIENT_ANDROID_OUTBOUND( - "prog-voice-client-android-outbound" - ), - PROG_VOICE_CLIENT_IOS("prog-voice-client-ios"), - PROG_VOICE_CLIENT_IOS_INBOUND("prog-voice-client-ios-inbound"), - PROG_VOICE_CLIENT_IOS_OUTBOUND("prog-voice-client-ios-outbound"), - PROG_VOICE_CLIENT_SDK("prog-voice-client-sdk"), - PROG_VOICE_CLIENT_WEB("prog-voice-client-web"), - PROG_VOICE_CLIENT_WEB_INBOUND("prog-voice-client-web-inbound"), - PROG_VOICE_CLIENT_WEB_OUTBOUND("prog-voice-client-web-outbound"), - PROGRAMMABLEVOICECONNECTIVITY_MEDIA_STREAMS( - "programmablevoiceconnectivity-media-streams" - ), - PSTNCONNECTIVITY_BYOC("pstnconnectivity-byoc"), - PSTNCONNECTIVITY_EMERGENCY("pstnconnectivity-emergency"), - PSTNCONNECTIVITY_MINUTES("pstnconnectivity-minutes"), - PSTNCONNECTIVITY_MINUTES_1("pstnconnectivity-minutes-1"), - PSTNCONNECTIVITY_MINUTESINBOUNDLOCAL( - "pstnconnectivity-minutesinboundlocal" - ), - PSTNCONNECTIVITY_MINUTESINBOUNDMOBILE( - "pstnconnectivity-minutesinboundmobile" - ), - PSTNCONNECTIVITY_MINUTESINBOUNDTOLLFREE( - "pstnconnectivity-minutesinboundtollfree" - ), - PSTNCONNECTIVITY_MINUTESINBOUNDTOLLFREELOCAL( - "pstnconnectivity-minutesinboundtollfreelocal" - ), - PSTNCONNECTIVITY_MINUTESINBOUNDTOLLFREEMOBILE( - "pstnconnectivity-minutesinboundtollfreemobile" - ), - PV_ROOM_HOURS("pv-room-hours"), - PV_ROOM_SIMULTANEOUS_PARTICIPANT_CONNECTIONS( - "pv-room-simultaneous-participant-connections" - ), - PVIDEO_ROOM_HOURS_AU1("pvideo-room-hours-au1"), - PVIDEO_ROOM_HOURS_BR1("pvideo-room-hours-br1"), - PVIDEO_ROOM_HOURS_IE1("pvideo-room-hours-ie1"), - PVIDEO_ROOM_HOURS_JP1("pvideo-room-hours-jp1"), - PVIDEO_ROOM_HOURS_SG1("pvideo-room-hours-sg1"), - PVIDEO_ROOM_HOURS_US1("pvideo-room-hours-us1"), - PVIDEO_ROOM_HOURS_US2("pvideo-room-hours-us2"), - RECORDINGS_ENCRYPTED("recordings-encrypted"), - SHORT_CODE_SETUP_FEES("short-code-setup-fees"), - SHORTCODES_MESSAGES_INBOUND("shortcodes-messages-inbound"), - SHORTCODES_MESSAGES_OUTBOUND("shortcodes-messages-outbound"), - SMS_MESSAGES_REGISTRATIONFEES("sms-messages-registrationfees"), - SMS_MMS_PENALTY_FEES("sms-mms-penalty-fees"), - SMS_MMS_PENALTY_FEES_1("sms-mms-penalty-fees-1"), - SMS_PUMPING_PROTECTION_NON_USCA("sms-pumping-protection-non-usca"), - SMS_PUMPING_PROTECTION_USCA("sms-pumping-protection-usca"), - STUDIO("studio"), - STUDIO_MONTHLY_FEES("studio-monthly-fees"), - SUPERSIM("supersim"), - TASK_ROUTER("task-router"), - TASK_ROUTER_WORKERS("task-router-workers"), - TEST_QUOTA_BUCKETS("test-quota-buckets"), - TEST_UC_SCRIPT_1("test-uc-script-1"), - TEST_UC_SCRIPT_DEMO_2("test-uc-script-demo-2"), - TEXT_TO_SPEECH("text-to-speech"), - TME("tme"), - TTS_BASIC("tts-basic"), - TWILIO_EDITIONS("twilio-editions"), - TWILIO_INTERCONNECT_CALIFORNIA("twilio-interconnect-california"), - TWILIO_INTERCONNECT_CALIFORNIA_MONTHLY( - "twilio-interconnect-california-monthly" - ), - TWILIO_INTERCONNECT_CALIFORNIA_SETUP( - "twilio-interconnect-california-setup" - ), - TWILIO_INTERCONNECT_FRANKFURT("twilio-interconnect-frankfurt"), - TWILIO_INTERCONNECT_FRANKFURT_MO("twilio-interconnect-frankfurt-mo"), - TWILIO_INTERCONNECT_FRANKFURT_SETUP( - "twilio-interconnect-frankfurt-setup" - ), - TWILIO_INTERCONNECT_LONDON("twilio-interconnect-london"), - TWILIO_INTERCONNECT_LONDON_MO("twilio-interconnect-london-mo"), - TWILIO_INTERCONNECT_LONDON_SETUP("twilio-interconnect-london-setup"), - TWILIO_INTERCONNECT_SAO_PAULO("twilio-interconnect-sao-paulo"), - TWILIO_INTERCONNECT_SAO_PAULO_MONTHLY( - "twilio-interconnect-sao-paulo-monthly" - ), - TWILIO_INTERCONNECT_SAO_PAULO_SETUP( - "twilio-interconnect-sao-paulo-setup" - ), - TWILIO_INTERCONNECT_SINGAPORE("twilio-interconnect-singapore"), - TWILIO_INTERCONNECT_SINGAPORE_MO("twilio-interconnect-singapore-mo"), - TWILIO_INTERCONNECT_SINGAPORE_SETUP( - "twilio-interconnect-singapore-setup" - ), - TWILIO_INTERCONNECT_SYDNEY("twilio-interconnect-sydney"), - TWILIO_INTERCONNECT_SYDNEY_MO("twilio-interconnect-sydney-mo"), - TWILIO_INTERCONNECT_SYDNEY_SETUP("twilio-interconnect-sydney-setup"), - TWILIO_INTERCONNECT_TOKYO("twilio-interconnect-tokyo"), - TWILIO_INTERCONNECT_TOKYO_MO("twilio-interconnect-tokyo-mo"), - TWILIO_INTERCONNECT_TOKYO_SETUP("twilio-interconnect-tokyo-setup"), - TWILIO_INTERCONNECT_VA("twilio-interconnect-va"), - TWILIO_INTERCONNECT_VA_MO("twilio-interconnect-va-mo"), - TWILIO_INTERCONNECT_VA_SETUP("twilio-interconnect-va-setup"), - TWIML_VERBS("twiml-verbs"), - TWIML_VERBS_SAY("twiml-verbs-say"), - USAGE_PROGRAMMABLE_MESSAGING_ENGAGEMENT_SUITE( - "usage-programmable-messaging-engagement-suite" - ), - USAGE_PROGRAMMABLE_MESSAGING_FEES_SERVICES( - "usage-programmable-messaging-fees-services" - ), - VERIFY_OUTBOUND_EMAIL("verify-outbound-email"), - VERIFY_PACKAGED_PLANS("verify-packaged-plans"), - VERIFY_SILENT_NETWORK_AUTH("verify-silent-network-auth"), - VERIFY_VOICE_AND_SMS("verify-voice-and-sms"), - VOICE_INSIGHTS_CLIENT_INSIGHTS_MONTHY_COMMIT( - "voice-insights-client-insights-monthy-commit" - ), - WIRELESS_DATA_PAYG_ASIA_AFG("wireless-data-payg-asia-afg"), - WIRELESS_MULTI_IMSI_SIM_COMMANDS("wireless-multi-imsi-sim-commands"), - WIRELESS_MULTI_IMSI_SIM_COMMANDS_USA( - "wireless-multi-imsi-sim-commands-usa" - ), - WIRELESS_MULTI_IMSI_SIM_DATA("wireless-multi-imsi-sim-data"), - WIRELESS_MULTI_IMSI_SIM_DATA_EU28("wireless-multi-imsi-sim-data-eu28"), - WIRELESS_MULTI_IMSI_SIM_DATA_USA("wireless-multi-imsi-sim-data-usa"), - WIRELESS_MULTI_IMSI_SIM_MONTHLY_FEES( - "wireless-multi-imsi-sim-monthly-fees" - ), - WIRELESS_MULTI_IMSI_SIM_USAGE("wireless-multi-imsi-sim-usage"), - WIRELESS_SUPER_SIM_DATA_NORTH_AMERICA( - "wireless-super-sim-data-north-america" - ), - WIRELESS_SUPER_SIM_USAGE("wireless-super-sim-usage"); - - private final String value; - - private Category(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static Category forValue(final String value) { - return Promoter.enumFromString(value, Category.values()); - } - } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/usage/record/YesterdayReader.java b/src/main/java/com/twilio/rest/api/v2010/account/usage/record/YesterdayReader.java index 02af335b4b..08ea9f7fe9 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/usage/record/YesterdayReader.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/usage/record/YesterdayReader.java @@ -32,7 +32,7 @@ public class YesterdayReader extends Reader { private String pathAccountSid; - private Yesterday.Category category; + private String category; private LocalDate startDate; private LocalDate endDate; private Boolean includeSubaccounts; @@ -44,7 +44,7 @@ public YesterdayReader(final String pathAccountSid) { this.pathAccountSid = pathAccountSid; } - public YesterdayReader setCategory(final Yesterday.Category category) { + public YesterdayReader setCategory(final String category) { this.category = category; return this; } @@ -168,7 +168,7 @@ public Page getPage( private void addQueryParams(final Request request) { if (category != null) { - request.addQueryParam("Category", category.toString()); + request.addQueryParam("Category", category); } if (startDate != null) { request.addQueryParam( diff --git a/src/main/java/com/twilio/rest/content/v1/Content.java b/src/main/java/com/twilio/rest/content/v1/Content.java index addc44ae73..a33471a7df 100644 --- a/src/main/java/com/twilio/rest/content/v1/Content.java +++ b/src/main/java/com/twilio/rest/content/v1/Content.java @@ -345,6 +345,12 @@ public static class CardAction { @Setter private String code; + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("webview_size") + @Getter + @Setter + private WebviewSizeType webviewSize; + public static CardAction fromJson( String jsonString, ObjectMapper mapper @@ -1154,6 +1160,28 @@ public static QuickReplyActionType forValue(final String value) { } } + public enum WebviewSizeType { + TALL("TALL"), + FULL("FULL"), + HALF("HALF"), + NONE("NONE"); + + private final String value; + + private WebviewSizeType(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static WebviewSizeType forValue(final String value) { + return Promoter.enumFromString(value, WebviewSizeType.values()); + } + } + public enum CardActionType { URL("URL"), PHONE_NUMBER("PHONE_NUMBER"), diff --git a/src/main/java/com/twilio/rest/insights/v1/Room.java b/src/main/java/com/twilio/rest/insights/v1/Room.java index 32a1fb2ece..762e15d75d 100644 --- a/src/main/java/com/twilio/rest/insights/v1/Room.java +++ b/src/main/java/com/twilio/rest/insights/v1/Room.java @@ -437,19 +437,7 @@ public enum TwilioRealm { SG1("sg1"), IN1("in1"), DE1("de1"), - GLL("gll"), - STAGE_US1("stage_us1"), - STAGE_US2("stage_us2"), - DEV_US1("dev_us1"), - DEV_US2("dev_us2"), - STAGE_DE1("stage_de1"), - STAGE_IN1("stage_in1"), - STAGE_IE1("stage_ie1"), - STAGE_BR1("stage_br1"), - STAGE_AU1("stage_au1"), - STAGE_SG1("stage_sg1"), - STAGE_JP1("stage_jp1"), - OUTSIDE("outside"); + GLL("gll"); private final String value; diff --git a/src/main/java/com/twilio/rest/insights/v1/room/Participant.java b/src/main/java/com/twilio/rest/insights/v1/room/Participant.java index db0b8b2325..b575a7042a 100644 --- a/src/main/java/com/twilio/rest/insights/v1/room/Participant.java +++ b/src/main/java/com/twilio/rest/insights/v1/room/Participant.java @@ -279,15 +279,21 @@ public int hashCode() { ); } - public enum RoomStatus { - IN_PROGRESS("in_progress"), - CONNECTED("connected"), - COMPLETED("completed"), - DISCONNECTED("disconnected"); + public enum TwilioRealm { + US1("us1"), + US2("us2"), + AU1("au1"), + BR1("br1"), + IE1("ie1"), + JP1("jp1"), + SG1("sg1"), + IN1("in1"), + DE1("de1"), + GLL("gll"); private final String value; - private RoomStatus(final String value) { + private TwilioRealm(final String value) { this.value = value; } @@ -296,38 +302,20 @@ public String toString() { } @JsonCreator - public static RoomStatus forValue(final String value) { - return Promoter.enumFromString(value, RoomStatus.values()); + public static TwilioRealm forValue(final String value) { + return Promoter.enumFromString(value, TwilioRealm.values()); } } - public enum TwilioRealm { - US1("us1"), - US2("us2"), - AU1("au1"), - BR1("br1"), - IE1("ie1"), - JP1("jp1"), - SG1("sg1"), - IN1("in1"), - DE1("de1"), - GLL("gll"), - STAGE_US1("stage_us1"), - DEV_US1("dev_us1"), - STAGE_AU1("stage_au1"), - STAGE_SG1("stage_sg1"), - STAGE_BR1("stage_br1"), - STAGE_IN1("stage_in1"), - STAGE_JP1("stage_jp1"), - STAGE_DE1("stage_de1"), - STAGE_IE1("stage_ie1"), - STAGE_US2("stage_us2"), - DEV_US2("dev_us2"), - OUTSIDE("outside"); + public enum RoomStatus { + IN_PROGRESS("in_progress"), + CONNECTED("connected"), + COMPLETED("completed"), + DISCONNECTED("disconnected"); private final String value; - private TwilioRealm(final String value) { + private RoomStatus(final String value) { this.value = value; } @@ -336,8 +324,8 @@ public String toString() { } @JsonCreator - public static TwilioRealm forValue(final String value) { - return Promoter.enumFromString(value, TwilioRealm.values()); + public static RoomStatus forValue(final String value) { + return Promoter.enumFromString(value, RoomStatus.values()); } } diff --git a/src/main/java/com/twilio/rest/messaging/v2/ChannelsSender.java b/src/main/java/com/twilio/rest/messaging/v2/ChannelsSender.java index 3a3dbd704a..457b66eaf8 100644 --- a/src/main/java/com/twilio/rest/messaging/v2/ChannelsSender.java +++ b/src/main/java/com/twilio/rest/messaging/v2/ChannelsSender.java @@ -830,13 +830,15 @@ public int hashCode() { ); } - public enum VerificationMethodEnum { - SMS("sms"), - VOICE("voice"); + public enum MessagingV2RcsCountryStatus { + ONLINE("ONLINE"), + OFFLINE("OFFLINE"), + TWILIO_REVIEW("TWILIO_REVIEW"), + PENDING_VERIFICATION("PENDING_VERIFICATION"); private final String value; - private VerificationMethodEnum(final String value) { + private MessagingV2RcsCountryStatus(final String value) { this.value = value; } @@ -845,21 +847,25 @@ public String toString() { } @JsonCreator - public static VerificationMethodEnum forValue(final String value) { + public static MessagingV2RcsCountryStatus forValue(final String value) { return Promoter.enumFromString( value, - VerificationMethodEnum.values() + MessagingV2RcsCountryStatus.values() ); } } - public enum FallbackMethodEnum { - POST("POST"), - PUT("PUT"); + public enum MessagingV2RcsCarrierStatus { + UNKNOWN("UNKNOWN"), + UNLAUNCHED("UNLAUNCHED"), + CARRIER_REVIEW("CARRIER_REVIEW"), + APPROVED("APPROVED"), + REJECTED("REJECTED"), + SUSPENDED("SUSPENDED"); private final String value; - private FallbackMethodEnum(final String value) { + private MessagingV2RcsCarrierStatus(final String value) { this.value = value; } @@ -868,20 +874,21 @@ public String toString() { } @JsonCreator - public static FallbackMethodEnum forValue(final String value) { - return Promoter.enumFromString(value, FallbackMethodEnum.values()); + public static MessagingV2RcsCarrierStatus forValue(final String value) { + return Promoter.enumFromString( + value, + MessagingV2RcsCarrierStatus.values() + ); } } - public enum MessagingV2RcsCountryStatus { - ONLINE("ONLINE"), - OFFLINE("OFFLINE"), - TWILIO_REVIEW("TWILIO_REVIEW"), - PENDING_VERIFICATION("PENDING_VERIFICATION"); + public enum CallbackMethodEnum { + POST("POST"), + PUT("PUT"); private final String value; - private MessagingV2RcsCountryStatus(final String value) { + private CallbackMethodEnum(final String value) { this.value = value; } @@ -890,25 +897,18 @@ public String toString() { } @JsonCreator - public static MessagingV2RcsCountryStatus forValue(final String value) { - return Promoter.enumFromString( - value, - MessagingV2RcsCountryStatus.values() - ); + public static CallbackMethodEnum forValue(final String value) { + return Promoter.enumFromString(value, CallbackMethodEnum.values()); } } - public enum MessagingV2RcsCarrierStatus { - UNKNOWN("UNKNOWN"), - UNLAUNCHED("UNLAUNCHED"), - CARRIER_REVIEW("CARRIER_REVIEW"), - APPROVED("APPROVED"), - REJECTED("REJECTED"), - SUSPENDED("SUSPENDED"); + public enum FallbackMethodEnum { + POST("POST"), + PUT("PUT"); private final String value; - private MessagingV2RcsCarrierStatus(final String value) { + private FallbackMethodEnum(final String value) { this.value = value; } @@ -917,21 +917,18 @@ public String toString() { } @JsonCreator - public static MessagingV2RcsCarrierStatus forValue(final String value) { - return Promoter.enumFromString( - value, - MessagingV2RcsCarrierStatus.values() - ); + public static FallbackMethodEnum forValue(final String value) { + return Promoter.enumFromString(value, FallbackMethodEnum.values()); } } - public enum CallbackMethodEnum { - POST("POST"), - PUT("PUT"); + public enum VerificationMethodEnum { + SMS("sms"), + VOICE("voice"); private final String value; - private CallbackMethodEnum(final String value) { + private VerificationMethodEnum(final String value) { this.value = value; } @@ -940,8 +937,11 @@ public String toString() { } @JsonCreator - public static CallbackMethodEnum forValue(final String value) { - return Promoter.enumFromString(value, CallbackMethodEnum.values()); + public static VerificationMethodEnum forValue(final String value) { + return Promoter.enumFromString( + value, + VerificationMethodEnum.values() + ); } } From 6533f63bfb5fce25908cf31e946e3380a2ac9302 Mon Sep 17 00:00:00 2001 From: Twilio Date: Thu, 4 Sep 2025 10:13:47 +0000 Subject: [PATCH 15/32] Release 11.0.0-rc.6 --- pom.xml | 4 ++-- src/main/java/com/twilio/Twilio.java | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/pom.xml b/pom.xml index 4f3efcd667..fc66150cc7 100644 --- a/pom.xml +++ b/pom.xml @@ -5,7 +5,7 @@ twilio jar twilio - 11.0.0-rc.5 + 11.0.0-rc.6 Twilio Java Helper Library https://www.twilio.com @@ -19,7 +19,7 @@ git@github.com:twilio/twilio-java.git scm:git:git@github.com:twilio/twilio-java.git scm:git:git@github.com:twilio/twilio-java.git - 11.0.0-rc.5 + 11.0.0-rc.6 diff --git a/src/main/java/com/twilio/Twilio.java b/src/main/java/com/twilio/Twilio.java index cd504549e2..2457814e0d 100644 --- a/src/main/java/com/twilio/Twilio.java +++ b/src/main/java/com/twilio/Twilio.java @@ -24,7 +24,7 @@ */ public class Twilio { - public static final String VERSION = "11.0.0-rc.5"; + public static final String VERSION = "11.0.0-rc.6"; public static final String JAVA_VERSION = System.getProperty("java.version"); public static final String OS_NAME = System.getProperty("os.name"); public static final String OS_ARCH = System.getProperty("os.arch"); From 2d81ceb661e2a608b706e7b4834d18df33c81aef Mon Sep 17 00:00:00 2001 From: Shubham Date: Tue, 9 Sep 2025 10:04:39 +0530 Subject: [PATCH 16/32] chore: sync with main (#884) * chore: updating maven repository link in release notes (#876) * chore: Fix ResourceSet iterator to allow multiple iterations and reduce code duplication (#883) --------- Co-authored-by: Copilot <198982749+Copilot@users.noreply.github.com> --- .github/workflows/test-and-deploy.yml | 4 +- .../java/com/twilio/base/ResourceSet.java | 8 + .../twilio/base/bearertoken/ResourceSet.java | 8 + .../twilio/base/ResourceSetIterationTest.java | 148 ++++++++++++++++++ 4 files changed, 166 insertions(+), 2 deletions(-) create mode 100644 src/test/java/com/twilio/base/ResourceSetIterationTest.java diff --git a/.github/workflows/test-and-deploy.yml b/.github/workflows/test-and-deploy.yml index 07178db5f3..d9aace8a70 100644 --- a/.github/workflows/test-and-deploy.yml +++ b/.github/workflows/test-and-deploy.yml @@ -62,7 +62,7 @@ jobs: with: distribution: 'zulu' java-version: '17' - + - name: SonarCloud Scan if: ${{ (github.event_name == 'pull_request' || github.ref_type == 'branch') && matrix.java == 11 && !github.event.pull_request.head.repo.fork }} env: @@ -94,7 +94,7 @@ jobs: - name: Create GitHub Release uses: sendgrid/dx-automator/actions/release@main with: - footer: '**[Maven](https://mvnrepository.com/artifact/com.twilio.sdk/twilio/${version})**' + footer: '**[Maven](https://central.sonatype.com/artifact/com.twilio.sdk/twilio/${version})**' env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/src/main/java/com/twilio/base/ResourceSet.java b/src/main/java/com/twilio/base/ResourceSet.java index 37fec6c969..6e5608adce 100644 --- a/src/main/java/com/twilio/base/ResourceSet.java +++ b/src/main/java/com/twilio/base/ResourceSet.java @@ -14,6 +14,7 @@ public class ResourceSet implements Iterable { private final Reader reader; private final TwilioRestClient client; + private final Page firstPage; // Store reference to first page to enable multiple iterations private boolean autoPaging; private long pages = 1; @@ -32,6 +33,7 @@ public class ResourceSet implements Iterable { public ResourceSet(final Reader reader, final TwilioRestClient client, final Page page) { this.reader = reader; this.client = client; + this.firstPage = page; // Save first page to allow resetting iterator state this.page = page; this.iterator = page.getRecords().iterator(); this.autoPaging = true; @@ -74,6 +76,12 @@ public long getPageLimit() { @Override public Iterator iterator() { + // Reset state to allow multiple iterations + this.processed = 0; + this.pages = 1; + this.page = this.firstPage; // Reset to first page for new iteration + this.iterator = this.firstPage.getRecords().iterator(); // Reset iterator to start of first page + return new ResourceSetIterator<>(this); } diff --git a/src/main/java/com/twilio/base/bearertoken/ResourceSet.java b/src/main/java/com/twilio/base/bearertoken/ResourceSet.java index 16bc369084..4cc09d8c2d 100644 --- a/src/main/java/com/twilio/base/bearertoken/ResourceSet.java +++ b/src/main/java/com/twilio/base/bearertoken/ResourceSet.java @@ -14,6 +14,7 @@ public class ResourceSet implements Iterable { private final Reader reader; private final BearerTokenTwilioRestClient client; + private final Page firstPage; // Store reference to first page to enable multiple iterations private boolean autoPaging; private long pages = 1; @@ -32,6 +33,7 @@ public class ResourceSet implements Iterable { public ResourceSet(final Reader reader, final BearerTokenTwilioRestClient client, final Page page) { this.reader = reader; this.client = client; + this.firstPage = page; // Save first page to allow resetting iterator state this.page = page; this.iterator = page.getRecords().iterator(); this.autoPaging = true; @@ -74,6 +76,12 @@ public long getPageLimit() { @Override public Iterator iterator() { + // Reset state to allow multiple iterations + this.processed = 0; + this.pages = 1; + this.page = this.firstPage; // Reset to first page for new iteration + this.iterator = this.firstPage.getRecords().iterator(); // Reset iterator to start of first page + return new ResourceSetIterator<>(this); } diff --git a/src/test/java/com/twilio/base/ResourceSetIterationTest.java b/src/test/java/com/twilio/base/ResourceSetIterationTest.java new file mode 100644 index 0000000000..7cc7a8b80f --- /dev/null +++ b/src/test/java/com/twilio/base/ResourceSetIterationTest.java @@ -0,0 +1,148 @@ +package com.twilio.base; + +import com.twilio.http.TwilioRestClient; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Iterator; +import java.util.List; + +import static org.mockito.Mockito.when; + +// Simple test resource for testing ResourceSet iteration +class TestResource extends Resource { + private final String id; + + public TestResource(String id) { + this.id = id; + } + + public String getId() { + return id; + } +} + +// Simple test reader for testing ResourceSet iteration +class TestReader extends Reader { + @Override + public ResourceSet read(TwilioRestClient client) { + return null; // Not needed for our test + } + + @Override + public Page firstPage(TwilioRestClient client) { + return null; // Not needed for our test + } + + @Override + public Page previousPage(Page page, TwilioRestClient client) { + return null; // Not needed for our test + } + + @Override + public Page nextPage(Page page, TwilioRestClient client) { + return null; // Not needed for our test + } + + @Override + public Page getPage(String targetUrl, TwilioRestClient client) { + return null; // Not needed for our test + } +} + +public class ResourceSetIterationTest { + + @Mock + TwilioRestClient client; + + @Mock + Page page; + + @Before + public void init() { + MockitoAnnotations.initMocks(this); + } + + @Test + public void testResourceSetCanBeIteratedMultipleTimes() { + // Setup mock data with concrete objects + TestResource resource1 = new TestResource("resource1"); + TestResource resource2 = new TestResource("resource2"); + List resources = Arrays.asList(resource1, resource2); + + when(page.getRecords()).thenReturn(resources); + when(page.getPageSize()).thenReturn(2); + when(page.hasNextPage()).thenReturn(false); + + Reader reader = new TestReader().limit(2); + ResourceSet resourceSet = new ResourceSet<>(reader, client, page); + + // First iteration - should work + List firstIterationResults = new ArrayList<>(); + for (TestResource resource : resourceSet) { + firstIterationResults.add(resource.getId()); + } + Assert.assertEquals(2, firstIterationResults.size()); + Assert.assertEquals("resource1", firstIterationResults.get(0)); + Assert.assertEquals("resource2", firstIterationResults.get(1)); + + // Second iteration - should also work and return the same results + List secondIterationResults = new ArrayList<>(); + for (TestResource resource : resourceSet) { + secondIterationResults.add(resource.getId()); + } + Assert.assertEquals("Second iteration should return same number of elements", 2, secondIterationResults.size()); + Assert.assertEquals("resource1", secondIterationResults.get(0)); + Assert.assertEquals("resource2", secondIterationResults.get(1)); + + // Third iteration using explicit iterator - should also work + List thirdIterationResults = new ArrayList<>(); + for (Iterator it = resourceSet.iterator(); it.hasNext(); ) { + TestResource resource = it.next(); + thirdIterationResults.add(resource.getId()); + } + Assert.assertEquals("Third iteration should return same number of elements", 2, thirdIterationResults.size()); + Assert.assertEquals("resource1", thirdIterationResults.get(0)); + Assert.assertEquals("resource2", thirdIterationResults.get(1)); + } + + @Test + public void testResourceSetWithLimitCanBeIteratedMultipleTimes() { + // Setup mock data with more resources than the limit + TestResource resource1 = new TestResource("resource1"); + TestResource resource2 = new TestResource("resource2"); + TestResource resource3 = new TestResource("resource3"); + List resources = Arrays.asList(resource1, resource2, resource3); + + when(page.getRecords()).thenReturn(resources); + when(page.getPageSize()).thenReturn(3); + when(page.hasNextPage()).thenReturn(false); + + // Set limit to 2, so only first 2 should be returned + Reader reader = new TestReader().limit(2); + ResourceSet resourceSet = new ResourceSet<>(reader, client, page); + + // First iteration - should only return 2 elements due to limit + List firstIterationResults = new ArrayList<>(); + for (TestResource resource : resourceSet) { + firstIterationResults.add(resource.getId()); + } + Assert.assertEquals("First iteration should respect limit", 2, firstIterationResults.size()); + Assert.assertEquals("resource1", firstIterationResults.get(0)); + Assert.assertEquals("resource2", firstIterationResults.get(1)); + + // Second iteration - should also respect limit and return same results + List secondIterationResults = new ArrayList<>(); + for (TestResource resource : resourceSet) { + secondIterationResults.add(resource.getId()); + } + Assert.assertEquals("Second iteration should respect limit", 2, secondIterationResults.size()); + Assert.assertEquals("resource1", secondIterationResults.get(0)); + Assert.assertEquals("resource2", secondIterationResults.get(1)); + } +} \ No newline at end of file From 519b65a1e83c6031c8c187c4dc4fc156c1c11427 Mon Sep 17 00:00:00 2001 From: sbansla <104902068+sbansla@users.noreply.github.com> Date: Tue, 9 Sep 2025 17:08:32 +0530 Subject: [PATCH 17/32] created centralized serialization and added tests (#894) --- .../com/twilio/constant/EnumConstants.java | 11 + .../java/com/twilio/converter/Serializer.java | 100 +++++++ .../com/twilio/converter/SerializerTest.java | 252 ++++++++++++++++++ 3 files changed, 363 insertions(+) create mode 100644 src/main/java/com/twilio/converter/Serializer.java create mode 100644 src/test/java/com/twilio/converter/SerializerTest.java diff --git a/src/main/java/com/twilio/constant/EnumConstants.java b/src/main/java/com/twilio/constant/EnumConstants.java index acd23702f4..f5f8438cf8 100644 --- a/src/main/java/com/twilio/constant/EnumConstants.java +++ b/src/main/java/com/twilio/constant/EnumConstants.java @@ -26,4 +26,15 @@ public enum AuthType { private final String value; } + + @Getter + @RequiredArgsConstructor + public enum ParameterType { + QUERY("Query"), + HEADER("Header"), + URLENCODED("Urlencoded"), + JSON("Json"); + + private final String value; + } } diff --git a/src/main/java/com/twilio/converter/Serializer.java b/src/main/java/com/twilio/converter/Serializer.java new file mode 100644 index 0000000000..f0ba1e46a1 --- /dev/null +++ b/src/main/java/com/twilio/converter/Serializer.java @@ -0,0 +1,100 @@ +package com.twilio.converter; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.exception.ApiConnectionException; +import com.twilio.exception.ApiException; +import com.twilio.http.Request; +import java.io.IOException; + +import java.time.LocalDate; +import java.time.ZonedDateTime; +import java.time.format.DateTimeFormatter; +import java.util.Map; +import java.util.Objects; + +public class Serializer { + + public static void toString(Request request, String key, T value, ParameterType parameterType) { + if (value == null) return; + + String stringValue = convertToString(value); + addParamToRequest(request, key, stringValue, parameterType); + } + + public static void toString(Request request, ObjectMapper mapper, T value) { + if (value == null) return; + + if (mapper == null) { + throw new IllegalArgumentException("ObjectMapper is required for JSON serialization"); + } + + String stringValue = toJson(value, mapper); + request.setBody(stringValue); + } + + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + private static String convertToString(T value) { + if (value instanceof Map) { + return Converter.mapToJson((Map) value); + } else { + return String.valueOf(value); + } + } + + private static void addParamToRequest(Request request, String key, String value, ParameterType parameterType) { + Objects.requireNonNull(parameterType, "ParameterType cannot be null"); + switch (parameterType) { + case HEADER: + request.addHeaderParam(key, value); + break; + case QUERY: + request.addQueryParam(key, value); + break; + case URLENCODED: + request.addPostParam(key, value); + break; + case JSON: + request.setBody(value); + default: + throw new IllegalArgumentException("Unsupported ParameterType: " + parameterType); + } + } + + /* + Inequality fields are only supported in Query parameters. + dateBefore is upperBound and dateAfter is lowerBound + */ + public static void toString(final Request request, final String key, LocalDate date, LocalDate dateBefore, LocalDate dateAfter) { + if (date != null) { + request.addQueryParam(key, date.format(DateTimeFormatter.ofPattern(Request.QUERY_STRING_DATE_FORMAT))); + } else if (dateAfter != null || dateBefore != null) { + request.addQueryDateRange(key, dateAfter, dateBefore); + } + } + + /* + Inequality fields are only supported in Query parameters. + dateBefore is upperBound and dateAfter is lowerBound + */ + public static void toString(final Request request, final String key, ZonedDateTime date, ZonedDateTime dateBefore, ZonedDateTime dateAfter) { + if (date != null) { + request.addQueryParam(key, date.format(DateTimeFormatter.ofPattern(Request.QUERY_STRING_DATE_TIME_FORMAT))); + } else if (dateAfter != null || dateBefore != null) { + request.addQueryDateTimeRange(key, dateAfter, dateBefore); + } + } +} \ No newline at end of file diff --git a/src/test/java/com/twilio/converter/SerializerTest.java b/src/test/java/com/twilio/converter/SerializerTest.java new file mode 100644 index 0000000000..7f949e8dac --- /dev/null +++ b/src/test/java/com/twilio/converter/SerializerTest.java @@ -0,0 +1,252 @@ +package com.twilio.converter; + +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.http.HttpMethod; +import com.twilio.http.Request; +import com.twilio.rest.Domains; +import org.junit.Test; +import org.mockito.Mockito; + +import java.time.LocalDate; +import java.time.ZonedDateTime; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNull; +import static org.mockito.Mockito.*; + +public class SerializerTest { + + public Request buildRequest() { + String path = "/2010-04-01/Accounts.json"; + Request request = new Request(HttpMethod.POST, Domains.API.toString(), path); + return request; + } + + @Test + public void testToStringWithString() { + Request request = buildRequest(); + Serializer.toString(request, "key", "value", ParameterType.QUERY); + assertEquals("value", request.getQueryParams().get("key").get(0)); + } + + // String value test with new line character + @Test + public void testToStringWithStringNewLine() { + Request request = buildRequest(); + Serializer.toString(request, "key", "Hello \n World", ParameterType.URLENCODED); + assertNotEquals("Hello \\n World", request.getPostParams().get("key").get(0)); + assertEquals("Hello \n World", request.getPostParams().get("key").get(0)); + } + + @Test + public void testToStringWithStringSpecialCharacters() { + Request request = buildRequest(); + Serializer.toString(request, "key", "Hello@World#2023!", ParameterType.QUERY); + assertEquals("Hello@World#2023!", request.getQueryParams().get("key").get(0)); + } + + @Test + public void testToStringWithInt32() { + Request request = buildRequest(); + Serializer.toString(request, "key", 32, ParameterType.HEADER); + assertEquals("32", request.getHeaderParams().get("key").get(0)); + } + + @Test + public void testToStringWithInt64() { + Request request = buildRequest(); + Serializer.toString(request, "key", 64L, ParameterType.QUERY); + assertEquals("64", request.getQueryParams().get("key").get(0)); + } + + @Test + public void testToStringWithFloat() { + Request request = buildRequest(); + Float value = 3.14f; + Serializer.toString(request, "key", value, ParameterType.QUERY); + assertEquals("3.14", request.getQueryParams().get("key").get(0)); + } + + @Test + public void testToStringWithFloatPrimitive() { + Request request = buildRequest(); + float value = 3.14f; + Serializer.toString(request, "key", value, ParameterType.QUERY); + assertEquals("3.14", request.getQueryParams().get("key").get(0)); + } + + @Test + public void testToStringWithLong() { + Request request = buildRequest(); + Long value = 123456789L; + Serializer.toString(request, "key", value, ParameterType.QUERY); + assertEquals("123456789", request.getQueryParams().get("key").get(0)); + } + + @Test + public void testToStringWithLongPrimitive() { + Request request = buildRequest(); + long value = 123456789L; + Serializer.toString(request, "key", value, ParameterType.QUERY); + assertEquals("123456789", request.getQueryParams().get("key").get(0)); + } + + @Test + public void testToStringWithBoolean() { + Request request = buildRequest(); + Boolean value = true; + Serializer.toString(request, "key", value, ParameterType.QUERY); + assertEquals("true", request.getQueryParams().get("key").get(0)); + } + + @Test + public void testToStringWithBooleanPrimitive() { + Request request = buildRequest(); + boolean value = false; + Serializer.toString(request, "key", value, ParameterType.QUERY); + assertEquals("false", request.getQueryParams().get("key").get(0)); + } + + @Test + public void testToStringWithInteger() { + Request request = buildRequest(); + Serializer.toString(request, "key", Integer.valueOf(42), ParameterType.QUERY); + assertEquals("42", request.getQueryParams().get("key").get(0)); + } + + @Test + public void testToStringWithIntegerPrimitive() { + Request request = buildRequest(); + int value = 42; + Serializer.toString(request, "key", value, ParameterType.QUERY); + assertEquals("42", request.getQueryParams().get("key").get(0)); + } + + @Test + public void testToStringWithDouble() { + Request request = buildRequest(); + Double value = 3.14159; + Serializer.toString(request, "key", value, ParameterType.QUERY); + assertEquals("3.14159", request.getQueryParams().get("key").get(0)); + } + + @Test + public void testToStringWithDoublePrimitive() { + Request request = buildRequest(); + double value = 3.14159; + Serializer.toString(request, "key", value, ParameterType.QUERY); + assertEquals("3.14159", request.getQueryParams().get("key").get(0)); + } + + @Test + public void testToStringWithArray() { + Request request = buildRequest(); + List values = Arrays.asList("value1", "value2", "value3"); + for (String value: values) { + Serializer.toString(request, "arrayKey", value, ParameterType.QUERY); + } + Serializer.toString(request, "key", "value", ParameterType.QUERY); + assertEquals(2, request.getQueryParams().size()); // 2 keys present + assertEquals(3, request.getQueryParams().get("arrayKey").size()); + assertEquals(1, request.getQueryParams().get("key").size()); + } + + @Test + public void testToStringWithHashMapStringObject() { + Request request = buildRequest(); + Map map = new HashMap<>(); + map.put("key1", "value1"); + map.put("key2", 123); + map.put("key3", true); + + Serializer.toString(request, "mapKey", map, ParameterType.QUERY); + assertEquals("{\"key1\":\"value1\",\"key2\":123,\"key3\":true}", request.getQueryParams().get("mapKey").get(0)); + } + + @Test + public void testToStringWithHashMapStringString() { + Request request = buildRequest(); + Map map = new HashMap<>(); + map.put("key1", "value1"); + map.put("key2", "value2"); + + Serializer.toString(request, "mapKey", map, ParameterType.QUERY); + assertEquals("{\"key1\":\"value1\",\"key2\":\"value2\"}", request.getQueryParams().get("mapKey").get(0)); + } + + @Test + public void testToStringWithLocalDate() { + Request request = buildRequest(); + LocalDate date = LocalDate.of(2025, 7, 1); + LocalDate dateBefore = null; + LocalDate dateAfter = null; + + Serializer.toString(request, "dateKey", date, dateBefore, dateAfter); + assertEquals("2025-07-01", request.getQueryParams().get("dateKey").get(0)); + } + + @Test + public void testToStringWithLocalDateRange() { + Request request = buildRequest(); + LocalDate date = null; + LocalDate dateBefore = LocalDate.of(2025, 7, 5); + LocalDate dateAfter = LocalDate.of(2025, 7, 1); + + Serializer.toString(request, "dateKey", date, dateBefore, dateAfter); + assertEquals("2025-07-01", request.getQueryParams().get("dateKey>").get(0)); + assertEquals("2025-07-05", request.getQueryParams().get("dateKey<").get(0)); + } + + @Test + public void testToStringWithLocalDateRangeBeforeNull() { + Request request = buildRequest(); + LocalDate date = null; + LocalDate dateBefore = null; + LocalDate dateAfter = LocalDate.of(2025, 7, 1); + + Serializer.toString(request, "dateKey", date, dateBefore, dateAfter); + assertNull(request.getQueryParams().get("dateKey<")); + assertEquals("2025-07-01", request.getQueryParams().get("dateKey>").get(0)); + } + + @Test + public void testToStringWithLocalDateRangeAfterNull() { + Request request = buildRequest(); + LocalDate date = null; + LocalDate dateBefore = LocalDate.of(2025, 7, 5); + LocalDate dateAfter = null; + + Serializer.toString(request, "dateKey", date, dateBefore, dateAfter); + assertNull(request.getQueryParams().get("dateKey>")); + assertEquals("2025-07-05", request.getQueryParams().get("dateKey<").get(0)); + } + + @Test + public void testToStringWithZonedDateTime() { + Request request = buildRequest(); + ZonedDateTime date = ZonedDateTime.parse("2025-07-01T10:15:30+05:00"); + ZonedDateTime dateBefore = null; + ZonedDateTime dateAfter = null; + + Serializer.toString(request, "dateTimeKey", date, dateBefore, dateAfter); + assertEquals("2025-07-01T10:15:30", request.getQueryParams().get("dateTimeKey").get(0)); + } + + @Test + public void testToStringWithZonedDateTimeRange() { + Request request = buildRequest(); + ZonedDateTime date = null; + ZonedDateTime dateBefore = ZonedDateTime.parse("2025-07-05T10:15:30+02:00"); + ZonedDateTime dateAfter = ZonedDateTime.parse("2025-07-01T10:15:30+02:00"); + + Serializer.toString(request, "dateTimeKey", date, dateBefore, dateAfter); + // Note the time difference. + assertEquals("2025-07-01T08:15:30", request.getQueryParams().get("dateTimeKey>").get(0)); + assertEquals("2025-07-05T08:15:30", request.getQueryParams().get("dateTimeKey<").get(0)); + } +} \ No newline at end of file From 0f88d7af43d26df945ad433d9f02958fbdbcb6b8 Mon Sep 17 00:00:00 2001 From: Manisha Singh Date: Fri, 12 Sep 2025 09:45:30 +0530 Subject: [PATCH 18/32] feat: Http5 upgrade multipart form (#877) --- README.md | 2 + pom.xml | 36 +-- src/main/java/com/twilio/http/HttpClient.java | 74 +++++- src/main/java/com/twilio/http/IRequest.java | 46 ++++ .../com/twilio/http/NetworkHttpClient.java | 125 ++++++---- src/main/java/com/twilio/http/Response.java | 2 +- .../com/twilio/http/TwilioRestClient.java | 3 +- .../com/twilio/http/ValidationClient.java | 72 +++--- .../twilio/http/ValidationInterceptor.java | 12 +- .../bearertoken/BearerTokenHttpClient.java | 11 +- .../BearerTokenNetworkHttpClient.java | 90 ++++---- .../BearerTokenTwilioRestClient.java | 2 +- .../twilio/http/noauth/NoAuthHttpClient.java | 13 +- .../http/noauth/NoAuthNetworkHttpClient.java | 99 ++++---- .../com/twilio/http/noauth/NoAuthRequest.java | 2 +- .../http/noauth/NoAuthTwilioRestClient.java | 4 +- .../jwt/validation/RequestCanonicalizer.java | 4 +- .../jwt/validation/ValidationToken.java | 21 +- .../com/twilio/rest/content/v1/Content.java | 2 - .../com/twilio/security/RequestValidator.java | 13 +- src/test/java/com/twilio/ClusterTest.java | 1 + src/test/java/com/twilio/TwilioTest.java | 2 +- src/test/java/com/twilio/base/ReaderTest.java | 2 +- .../twilio/base/ResourceSetIterationTest.java | 2 +- .../com/twilio/http/CustomHttpClient.java | 50 ++-- .../java/com/twilio/http/HttpClientTest.java | 208 +++++++++++++++++ .../java/com/twilio/http/IRequestTest.java | 138 +++++++++++ .../twilio/http/NetworkHttpClientTest.java | 214 +++++++++++++++++- .../java/com/twilio/http/ResponseTest.java | 2 +- .../com/twilio/http/TwilioRestClientTest.java | 2 +- .../com/twilio/http/ValidationClientTest.java | 127 +++++++++++ .../BearerTokenNetworkHttpClientTest.java | 213 +++++++++++++++++ .../noauth/NoAuthNetworkHttpClientTest.java | 162 +++++++++++++ .../validation/RequestCanonicalizerTest.java | 4 +- .../jwt/validation/ValidationTokenTest.java | 42 ++-- .../twilio/security/RequestValidatorTest.java | 4 +- 36 files changed, 1506 insertions(+), 300 deletions(-) create mode 100644 src/test/java/com/twilio/http/HttpClientTest.java create mode 100644 src/test/java/com/twilio/http/IRequestTest.java create mode 100644 src/test/java/com/twilio/http/bearerToken/BearerTokenNetworkHttpClientTest.java create mode 100644 src/test/java/com/twilio/http/noauth/NoAuthNetworkHttpClientTest.java diff --git a/README.md b/README.md index e498ca964c..c63cb6461a 100644 --- a/README.md +++ b/README.md @@ -366,3 +366,5 @@ If you've instead found a bug in the library or would like new features added, g [apidocs]: https://www.twilio.com/docs/api [twiml]: https://www.twilio.com/docs/api/twiml [libdocs]: https://twilio.github.io/twilio-java + + diff --git a/pom.xml b/pom.xml index fc66150cc7..7b1a9ae5e1 100644 --- a/pom.xml +++ b/pom.xml @@ -217,9 +217,9 @@ runtime - org.apache.httpcomponents - httpclient - 4.5.13 + org.apache.httpcomponents.client5 + httpclient5 + 5.5 commons-codec @@ -228,9 +228,9 @@ - org.apache.httpcomponents - httpcore - 4.4.13 + org.apache.httpcomponents.core5 + httpcore5 + 5.3.4 com.fasterxml.jackson.core @@ -260,7 +260,7 @@ org.slf4j slf4j-api - 1.7.30 + 1.7.36 junit @@ -268,12 +268,6 @@ 4.13.2 test - - org.apache.httpcomponents - httpmime - 4.5.13 - test - com.tngtech.archunit archunit @@ -316,8 +310,8 @@ org.mockito - mockito-all - 1.10.19 + mockito-core + 4.11.0 test @@ -341,6 +335,12 @@ gson 2.10.1 + + org.mockito + mockito-inline + 4.11.0 + test + @@ -440,6 +440,10 @@ + + org.apache.maven.plugins + maven-surefire-plugin + org.apache.maven.plugins maven-surefire-plugin @@ -490,4 +494,4 @@ - \ No newline at end of file + diff --git a/src/main/java/com/twilio/http/HttpClient.java b/src/main/java/com/twilio/http/HttpClient.java index 71e595ff34..fd98f445e1 100644 --- a/src/main/java/com/twilio/http/HttpClient.java +++ b/src/main/java/com/twilio/http/HttpClient.java @@ -1,26 +1,52 @@ package com.twilio.http; +import java.nio.file.Path; import lombok.Getter; import lombok.Setter; -import org.apache.http.client.RedirectStrategy; -import org.apache.http.client.config.RequestConfig; -import org.apache.http.config.SocketConfig; -import org.apache.http.impl.client.DefaultRedirectStrategy; +import org.apache.hc.client5.http.classic.methods.HttpDelete; +import org.apache.hc.client5.http.classic.methods.HttpGet; +import org.apache.hc.client5.http.classic.methods.HttpPatch; +import org.apache.hc.client5.http.classic.methods.HttpPost; +import org.apache.hc.client5.http.classic.methods.HttpPut; +import org.apache.hc.client5.http.classic.methods.HttpUriRequestBase; +import org.apache.hc.client5.http.config.RequestConfig; +import org.apache.hc.client5.http.impl.DefaultRedirectStrategy; +import org.apache.hc.client5.http.protocol.RedirectStrategy; +import org.apache.hc.core5.http.ContentType; +import org.apache.hc.core5.http.io.SocketConfig; +import org.apache.hc.core5.util.Timeout; + +/** + * Abstract class representing an HTTP client. + * This class provides methods to make reliable HTTP requests with retry logic and customizable request configurations. + */ public abstract class HttpClient { - public static final int CONNECTION_TIMEOUT = 10000; - public static final int SOCKET_TIMEOUT = 30500; + public static final Timeout CONNECTION_TIMEOUT = Timeout.ofMilliseconds(10000); // The default connection timeout is 10 seconds + public static final Timeout CONNECT_TIMEOUT = Timeout.ofMilliseconds(30500); // The default socket timeout is 30.5 seconds + public static final Timeout CONNECTION_KEEP_ALIVE = Timeout.ofMilliseconds(60000); // The default keep-alive timeout is 60 seconds + public static final Timeout SOCKET_TIMEOUT = Timeout.ofMilliseconds(30000); // The default socket timeout is 30 seconds + /** + * Default request configuration for the HTTP client. + * This configuration sets the connection request timeout, socket timeout, and connection keep-alive timeout. + */ public static final RequestConfig DEFAULT_REQUEST_CONFIG = RequestConfig .custom() - .setConnectTimeout(CONNECTION_TIMEOUT) - .setSocketTimeout(SOCKET_TIMEOUT) + .setConnectionRequestTimeout(CONNECTION_TIMEOUT) + .setConnectTimeout(CONNECT_TIMEOUT) + .setConnectionKeepAlive(CONNECTION_KEEP_ALIVE) .build(); - public static final SocketConfig DEFAULT_SOCKET_CONFIG = SocketConfig - .custom() + /** + * Default socket configuration for the HTTP client. + * This configuration sets the socket timeout and enables keep-alive. + */ + public static final SocketConfig DEFAULT_SOCKET_CONFIG = SocketConfig.custom() .setSoTimeout(SOCKET_TIMEOUT) + .setSoKeepAlive(true) .build(); + public static final int ANY_500 = -500; public static final int ANY_400 = -400; public static final int ANY_300 = -300; @@ -34,7 +60,7 @@ public abstract class HttpClient { // Default redirect strategy to not auto-redirect for any methods (empty string array). @Getter @Setter - private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy(new String[0]); + private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy(); @Getter private Response lastResponse; @@ -131,5 +157,31 @@ protected boolean shouldRetry(final Response response, final int[] retryCodes) { return false; } + public static ContentType getContentType(Path filePath) { + String fileName = filePath.getFileName().toString().toLowerCase(); + + if (fileName.endsWith(".pdf")) { + return ContentType.create("application/pdf"); + } else if (fileName.endsWith(".jpg") || fileName.endsWith(".jpeg")) { + return ContentType.create("image/jpeg"); + } else if (fileName.endsWith(".png")) { + return ContentType.create("image/png"); + } else { + return ContentType.create("application/octet-stream"); // using "application/octet-stream" for generic binary data, often used by browsers for unknown binary files to prompt the user to download them + } + } + + public static HttpUriRequestBase createHttpUriRequestBase(final IRequest request) { + HttpUriRequestBase httpUriRequestBase = null; + switch (request.getMethod().toString().toUpperCase()) { + case "POST": httpUriRequestBase = new HttpPost(request.constructURL().toString()); break; + case "PUT": httpUriRequestBase = new HttpPut(request.constructURL().toString()); break; + case "PATCH": httpUriRequestBase = new HttpPatch(request.constructURL().toString()); break; + case "DELETE": httpUriRequestBase = new HttpDelete(request.constructURL().toString()); break; + case "GET": httpUriRequestBase = new HttpGet(request.constructURL().toString()); break; + } + return httpUriRequestBase; + } + public abstract Response makeRequest(final Request request); } diff --git a/src/main/java/com/twilio/http/IRequest.java b/src/main/java/com/twilio/http/IRequest.java index 584951f34b..aff228bc57 100644 --- a/src/main/java/com/twilio/http/IRequest.java +++ b/src/main/java/com/twilio/http/IRequest.java @@ -32,6 +32,7 @@ public class IRequest { protected final Map> queryParams; protected final Map> postParams; protected final Map> headerParams; + protected List formParameters; protected String region; protected String edge; @@ -42,6 +43,34 @@ public class IRequest { private String body; + public static class FormParameters { + private String name; + private Type type; + private Object value; + + public enum Type { + TEXT, FILE + } + + public FormParameters(String name, Type type, Object value) { + this.name = name; + this.type = type; + this.value = value; + } + + public String getName() { + return name; + } + + public Type getType() { + return type; + } + + public Object getValue() { + return value; + } + } + /** * Create a new API request. * @@ -54,6 +83,7 @@ public IRequest(final HttpMethod method, final String url) { this.queryParams = new HashMap<>(); this.postParams = new HashMap<>(); this.headerParams = new HashMap<>(); + this.formParameters = new ArrayList<>(); } /** @@ -83,6 +113,7 @@ public IRequest(final HttpMethod method, final String domain, final String uri, this.queryParams = new HashMap<>(); this.postParams = new HashMap<>(); this.headerParams = new HashMap<>(); + this.formParameters = new ArrayList<>(); } public HttpMethod getMethod() { @@ -125,6 +156,21 @@ public void setBody(String body) { this.body = body; } + public List getFormParameters() { + return this.formParameters; + } + + public void addFormParameter(String name, FormParameters.Type type, Object value) { + this.formParameters.add(new FormParameters(name, type, value)); + } + + public void setFormParameters(final List formParameters) { + if (formParameters == null) { + throw new IllegalArgumentException("Form parameters cannot be null"); + } + this.formParameters.addAll(formParameters); + } + /** * Build the URL for the request. * diff --git a/src/main/java/com/twilio/http/NetworkHttpClient.java b/src/main/java/com/twilio/http/NetworkHttpClient.java index 2b557a273b..8c1b0dad85 100644 --- a/src/main/java/com/twilio/http/NetworkHttpClient.java +++ b/src/main/java/com/twilio/http/NetworkHttpClient.java @@ -4,31 +4,46 @@ import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiException; +import com.twilio.http.IRequest.FormParameters; +import com.twilio.http.IRequest.FormParameters.Type; import java.io.IOException; import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; -import java.util.Map; - -import org.apache.http.HttpEntity; -import org.apache.http.HttpHeaders; -import org.apache.http.HttpResponse; -import org.apache.http.HttpVersion; -import org.apache.http.client.config.RequestConfig; -import org.apache.http.client.methods.RequestBuilder; -import org.apache.http.client.utils.HttpClientUtils; -import org.apache.http.config.SocketConfig; -import org.apache.http.entity.BufferedHttpEntity; -import org.apache.http.entity.ContentType; -import org.apache.http.entity.StringEntity; -import org.apache.http.impl.client.HttpClientBuilder; -import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; -import org.apache.http.message.BasicHeader; +import java.util.Map.Entry; +import org.apache.hc.client5.http.classic.methods.HttpDelete; +import org.apache.hc.client5.http.classic.methods.HttpGet; +import org.apache.hc.client5.http.classic.methods.HttpPatch; +import org.apache.hc.client5.http.classic.methods.HttpPost; +import org.apache.hc.client5.http.classic.methods.HttpPut; +import org.apache.hc.client5.http.classic.methods.HttpUriRequestBase; +import org.apache.hc.client5.http.config.RequestConfig; +import org.apache.hc.client5.http.entity.UrlEncodedFormEntity; +import org.apache.hc.client5.http.entity.mime.MultipartEntityBuilder; +import org.apache.hc.client5.http.impl.classic.CloseableHttpClient; +import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse; +import org.apache.hc.client5.http.impl.classic.HttpClientBuilder; +import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager; +import org.apache.hc.core5.http.ContentType; +import org.apache.hc.core5.http.HttpEntity; +import org.apache.hc.core5.http.HttpHeaders; +import org.apache.hc.core5.http.HttpVersion; +import org.apache.hc.core5.http.NameValuePair; +import org.apache.hc.core5.http.io.SocketConfig; +import org.apache.hc.core5.http.io.entity.BufferedHttpEntity; +import org.apache.hc.core5.http.io.entity.StringEntity; +import org.apache.hc.core5.http.message.BasicHeader; +import org.apache.hc.core5.http.message.BasicNameValuePair; + public class NetworkHttpClient extends HttpClient { - protected final org.apache.http.client.HttpClient client; + protected final CloseableHttpClient client; private boolean isCustomClient; @@ -64,7 +79,7 @@ public NetworkHttpClient(final RequestConfig requestConfig, final SocketConfig s String googleAppEngineVersion = System.getProperty("com.google.appengine.runtime.version"); boolean isGoogleAppEngine = googleAppEngineVersion != null && !googleAppEngineVersion.isEmpty(); - org.apache.http.impl.client.HttpClientBuilder clientBuilder = HttpClientBuilder.create(); + HttpClientBuilder clientBuilder = HttpClientBuilder.create(); if (!isGoogleAppEngine) { clientBuilder.useSystemProperties(); @@ -113,21 +128,22 @@ public NetworkHttpClient(HttpClientBuilder clientBuilder) { * @param request request to make * @return Response of the HTTP request */ - public Response makeRequest(final Request request) { + public Response makeRequest(final Request request) { HttpMethod method = request.getMethod(); - RequestBuilder builder = RequestBuilder.create(method.toString()) - .setUri(request.constructURL().toString()) - .setVersion(HttpVersion.HTTP_1_1) - .setCharset(StandardCharsets.UTF_8); + HttpUriRequestBase httpUriRequestBase = createHttpUriRequestBase(request); + + httpUriRequestBase.setConfig(DEFAULT_REQUEST_CONFIG); + + httpUriRequestBase.setVersion(HttpVersion.HTTP_1_1); if (request.requiresAuthentication()) { - builder.addHeader(HttpHeaders.AUTHORIZATION, request.getAuthString()); + httpUriRequestBase.addHeader(HttpHeaders.AUTHORIZATION, request.getAuthString()); } - for (Map.Entry> entry : request.getHeaderParams().entrySet()) { + for (Entry> entry : request.getHeaderParams().entrySet()) { for (String value : entry.getValue()) { - builder.addHeader(entry.getKey(), value); + httpUriRequestBase.addHeader(entry.getKey(), value); } } @@ -136,40 +152,63 @@ public Response makeRequest(final Request request) { if (request.getContentType() == null) request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); if (EnumConstants.ContentType.JSON.getValue().equals(request.getContentType().getValue())) { HttpEntity entity = new StringEntity(request.getBody(), ContentType.APPLICATION_JSON); - builder.setEntity(entity); - builder.addHeader( + httpUriRequestBase.setEntity(entity); + httpUriRequestBase.addHeader( HttpHeaders.CONTENT_TYPE, EnumConstants.ContentType.JSON.getValue()); - } else { - builder.addHeader( - HttpHeaders.CONTENT_TYPE, EnumConstants.ContentType.FORM_URLENCODED.getValue()); - for (Map.Entry> entry : request.getPostParams().entrySet()) { + } else if (EnumConstants.ContentType.MULTIPART_FORM_DATA.getValue().equals(request.getContentType().getValue())) { + + MultipartEntityBuilder httpEntityBuilder = MultipartEntityBuilder.create(); + for( FormParameters formParameter: request.getFormParameters()) { + // Create a file to upload. + if ( formParameter.getType().equals(Type.TEXT) ) + httpEntityBuilder.addTextBody(formParameter.getName(), formParameter.getValue().toString()); + else if ( formParameter.getType().equals(Type.FILE) ) + { + Path path = Paths.get(formParameter.getValue().toString()); + byte[] fileBytes = null; + try{ + fileBytes = Files.readAllBytes(path); + } catch (IOException e) { + System.err.println("Failed to read file for upload: " + path + ". " + e.getMessage()); + throw new ApiException("Failed to read file for upload: " + path, e); + } + String fileName = path.getFileName().toString(); + ContentType contentType = getContentType(path); + httpEntityBuilder.addBinaryBody(formParameter.getName(), fileBytes, contentType, fileName); + } + } + httpUriRequestBase.setEntity(httpEntityBuilder.build()); + } + else { + List formParams = new ArrayList<>(); + for ( Entry> entry : request.getPostParams().entrySet()) { for (String value : entry.getValue()) { - builder.addParameter(entry.getKey(), value); + formParams.add(new BasicNameValuePair(entry.getKey(), value)); } } + + // Build the entity with URL form encoded parameters + UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(formParams, StandardCharsets.UTF_8); + // Set the entity on the request + httpUriRequestBase.setEntity(formEntity); } } - builder.addHeader(HttpHeaders.USER_AGENT, HttpUtility.getUserAgentString(request.getUserAgentExtensions(), isCustomClient)); + httpUriRequestBase.addHeader(HttpHeaders.USER_AGENT, HttpUtility.getUserAgentString(request.getUserAgentExtensions(), isCustomClient)); - HttpResponse response = null; try { - response = client.execute(builder.build()); + CloseableHttpResponse response = client.execute(httpUriRequestBase); HttpEntity entity = response.getEntity(); return new Response( // Consume the entire HTTP response before returning the stream entity == null ? null : new BufferedHttpEntity(entity).getContent(), - response.getStatusLine().getStatusCode(), - response.getAllHeaders() + response.getCode(), + response.getHeaders() ); } catch (IOException e) { throw new ApiException(e.getMessage(), e); - } finally { - - // Ensure this response is properly closed - HttpClientUtils.closeQuietly(response); - } } + } diff --git a/src/main/java/com/twilio/http/Response.java b/src/main/java/com/twilio/http/Response.java index b16098403c..05f675ab7e 100644 --- a/src/main/java/com/twilio/http/Response.java +++ b/src/main/java/com/twilio/http/Response.java @@ -1,7 +1,7 @@ package com.twilio.http; import com.twilio.exception.ApiException; -import org.apache.http.Header; +import org.apache.hc.core5.http.Header; import java.io.ByteArrayInputStream; import java.io.InputStream; diff --git a/src/main/java/com/twilio/http/TwilioRestClient.java b/src/main/java/com/twilio/http/TwilioRestClient.java index a902f0fee6..c4b8ff2b41 100644 --- a/src/main/java/com/twilio/http/TwilioRestClient.java +++ b/src/main/java/com/twilio/http/TwilioRestClient.java @@ -9,6 +9,7 @@ import java.util.Map; import java.util.function.Predicate; import lombok.Getter; +import org.apache.hc.core5.http.Header; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -114,7 +115,7 @@ public Response request(final Request request) { if (logger.isDebugEnabled()) { logger.debug("status code: {}", statusCode); - org.apache.http.Header[] responseHeaders = response.getHeaders(); + Header[] responseHeaders = response.getHeaders(); logger.debug("response headers:"); for (int i = 0; i < responseHeaders.length; i++) { logger.debug("responseHeader: {}", responseHeaders[i]); diff --git a/src/main/java/com/twilio/http/ValidationClient.java b/src/main/java/com/twilio/http/ValidationClient.java index b455db435e..439aaf98a2 100644 --- a/src/main/java/com/twilio/http/ValidationClient.java +++ b/src/main/java/com/twilio/http/ValidationClient.java @@ -4,18 +4,27 @@ import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiException; import io.jsonwebtoken.SignatureAlgorithm; -import org.apache.http.HttpEntity; -import org.apache.http.HttpHeaders; -import org.apache.http.HttpResponse; -import org.apache.http.HttpVersion; -import org.apache.http.client.config.RequestConfig; -import org.apache.http.client.methods.RequestBuilder; -import org.apache.http.config.SocketConfig; -import org.apache.http.entity.ContentType; -import org.apache.http.entity.StringEntity; -import org.apache.http.impl.client.HttpClientBuilder; -import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; -import org.apache.http.message.BasicHeader; +import java.util.ArrayList; +import java.util.Map.Entry; +import org.apache.hc.client5.http.classic.methods.HttpDelete; +import org.apache.hc.client5.http.classic.methods.HttpGet; +import org.apache.hc.client5.http.classic.methods.HttpPatch; +import org.apache.hc.client5.http.classic.methods.HttpPost; +import org.apache.hc.client5.http.classic.methods.HttpPut; +import org.apache.hc.client5.http.classic.methods.HttpUriRequestBase; +import org.apache.hc.client5.http.config.RequestConfig; +import org.apache.hc.client5.http.entity.UrlEncodedFormEntity; +import org.apache.hc.client5.http.impl.classic.CloseableHttpClient; +import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse; +import org.apache.hc.client5.http.impl.classic.HttpClientBuilder; +import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager; +import org.apache.hc.core5.http.ContentType; +import org.apache.hc.core5.http.HttpEntity; +import org.apache.hc.core5.http.HttpHeaders; +import org.apache.hc.core5.http.NameValuePair; +import org.apache.hc.core5.http.io.SocketConfig; +import org.apache.hc.core5.http.io.entity.StringEntity; +import org.apache.hc.core5.http.message.BasicHeader; import java.io.IOException; import java.nio.charset.StandardCharsets; @@ -24,12 +33,13 @@ import java.util.Collection; import java.util.List; import java.util.Map; +import org.apache.hc.core5.http.message.BasicNameValuePair; import static io.jsonwebtoken.SignatureAlgorithm.RS256; public class ValidationClient extends HttpClient { - private final org.apache.http.client.HttpClient client; + private final CloseableHttpClient client; /** * Create a new ValidationClient. @@ -158,50 +168,54 @@ public ValidationClient(final String accountSid, .setConnectionManager(connectionManager) .setDefaultRequestConfig(requestConfig) .setDefaultHeaders(headers) - .addInterceptorLast(new ValidationInterceptor(accountSid, credentialSid, signingKey, privateKey, algorithm)) + .addRequestInterceptorLast(new ValidationInterceptor(accountSid, credentialSid, signingKey, privateKey, algorithm)) .setRedirectStrategy(this.getRedirectStrategy()) .build(); } @Override public Response makeRequest(Request request) { - RequestBuilder builder = RequestBuilder.create(request.getMethod().toString()) - .setUri(request.constructURL().toString()) - .setVersion(HttpVersion.HTTP_1_1) - .setCharset(StandardCharsets.UTF_8); + HttpMethod method = request.getMethod(); + HttpUriRequestBase httpUriRequestBase = createHttpUriRequestBase(request); if (request.requiresAuthentication()) { - builder.addHeader(HttpHeaders.AUTHORIZATION, request.getAuthString()); + httpUriRequestBase.addHeader(HttpHeaders.AUTHORIZATION, request.getAuthString()); } - HttpMethod method = request.getMethod(); if (method != HttpMethod.GET) { // TODO: It will be removed after one RC Release. if (request.getContentType() == null) request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); if (EnumConstants.ContentType.JSON.getValue().equals(request.getContentType().getValue())) { HttpEntity entity = new StringEntity(request.getBody(), ContentType.APPLICATION_JSON); - builder.setEntity(entity); - builder.addHeader( + httpUriRequestBase.setEntity(entity); + httpUriRequestBase.addHeader( HttpHeaders.CONTENT_TYPE, EnumConstants.ContentType.JSON.getValue()); } else { - builder.addHeader( + httpUriRequestBase.addHeader( HttpHeaders.CONTENT_TYPE, EnumConstants.ContentType.FORM_URLENCODED.getValue()); - for (Map.Entry> entry : request.getPostParams().entrySet()) { + // Create your form parameters + List formParams = new ArrayList<>(); + for ( Entry> entry : request.getPostParams().entrySet()) { for (String value : entry.getValue()) { - builder.addParameter(entry.getKey(), value); + formParams.add(new BasicNameValuePair(entry.getKey(), value)); } } + + // Build the entity with URL form encoded parameters + UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(formParams, StandardCharsets.UTF_8); + // Set the entity on the request + httpUriRequestBase.setEntity(formEntity); } } - builder.addHeader(HttpHeaders.USER_AGENT, HttpUtility.getUserAgentString(request.getUserAgentExtensions())); + httpUriRequestBase.addHeader(HttpHeaders.USER_AGENT, HttpUtility.getUserAgentString(request.getUserAgentExtensions())); try { - HttpResponse response = client.execute(builder.build()); + CloseableHttpResponse response = client.execute(httpUriRequestBase); return new Response( response.getEntity() == null ? null : response.getEntity().getContent(), - response.getStatusLine().getStatusCode(), - response.getAllHeaders() + response.getCode(), + response.getHeaders() ); } catch (IOException e) { throw new ApiException(e.getMessage(), e); diff --git a/src/main/java/com/twilio/http/ValidationInterceptor.java b/src/main/java/com/twilio/http/ValidationInterceptor.java index 8e3cfcd441..0a7de0cbe4 100644 --- a/src/main/java/com/twilio/http/ValidationInterceptor.java +++ b/src/main/java/com/twilio/http/ValidationInterceptor.java @@ -3,15 +3,17 @@ import com.twilio.jwt.Jwt; import com.twilio.jwt.validation.ValidationToken; import io.jsonwebtoken.SignatureAlgorithm; -import org.apache.http.HttpException; -import org.apache.http.HttpRequest; -import org.apache.http.HttpRequestInterceptor; -import org.apache.http.protocol.HttpContext; +import org.apache.hc.core5.http.EntityDetails; +import org.apache.hc.core5.http.HttpEntity; +import org.apache.hc.core5.http.HttpException; +import org.apache.hc.core5.http.HttpRequest; +import org.apache.hc.core5.http.HttpRequestInterceptor; import java.io.IOException; import java.security.PrivateKey; import java.util.Arrays; import java.util.List; +import org.apache.hc.core5.http.protocol.HttpContext; public class ValidationInterceptor implements HttpRequestInterceptor { @@ -56,7 +58,7 @@ public ValidationInterceptor(String accountSid, String credentialSid, String sig } @Override - public void process(HttpRequest request, HttpContext context) throws HttpException, IOException { + public void process(HttpRequest request, EntityDetails httpEntity, HttpContext context) throws HttpException, IOException { Jwt jwt = ValidationToken.fromHttpRequest( accountSid, credentialSid, diff --git a/src/main/java/com/twilio/http/bearertoken/BearerTokenHttpClient.java b/src/main/java/com/twilio/http/bearertoken/BearerTokenHttpClient.java index 919e8b0054..0c405769bf 100644 --- a/src/main/java/com/twilio/http/bearertoken/BearerTokenHttpClient.java +++ b/src/main/java/com/twilio/http/bearertoken/BearerTokenHttpClient.java @@ -5,17 +5,16 @@ import com.twilio.http.Response; import lombok.Getter; import lombok.Setter; -import org.apache.http.client.RedirectStrategy; -import org.apache.http.client.config.RequestConfig; -import org.apache.http.config.SocketConfig; -import org.apache.http.impl.client.DefaultRedirectStrategy; +import org.apache.hc.client5.http.config.RequestConfig; +import org.apache.hc.client5.http.impl.DefaultRedirectStrategy; +import org.apache.hc.client5.http.protocol.RedirectStrategy; +import org.apache.hc.core5.http.io.SocketConfig; public abstract class BearerTokenHttpClient { // Use constants from HttpClient public static final RequestConfig DEFAULT_REQUEST_CONFIG = RequestConfig .custom() .setConnectTimeout(HttpClient.CONNECTION_TIMEOUT) - .setSocketTimeout(HttpClient.SOCKET_TIMEOUT) .build(); public static final SocketConfig DEFAULT_SOCKET_CONFIG = SocketConfig .custom() @@ -23,7 +22,7 @@ public abstract class BearerTokenHttpClient { .build(); @Getter @Setter - private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy(new String[0]); + private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy(); @Getter private Response lastResponse; diff --git a/src/main/java/com/twilio/http/bearertoken/BearerTokenNetworkHttpClient.java b/src/main/java/com/twilio/http/bearertoken/BearerTokenNetworkHttpClient.java index dbbd4b6d19..9d80666640 100644 --- a/src/main/java/com/twilio/http/bearertoken/BearerTokenNetworkHttpClient.java +++ b/src/main/java/com/twilio/http/bearertoken/BearerTokenNetworkHttpClient.java @@ -3,25 +3,26 @@ import com.twilio.Twilio; import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiException; -import com.twilio.http.HttpClient; import com.twilio.http.HttpMethod; import com.twilio.http.HttpUtility; -import com.twilio.http.Request; import com.twilio.http.Response; -import org.apache.http.HttpEntity; -import org.apache.http.HttpHeaders; -import org.apache.http.HttpResponse; -import org.apache.http.HttpVersion; -import org.apache.http.client.config.RequestConfig; -import org.apache.http.client.methods.RequestBuilder; -import org.apache.http.client.utils.HttpClientUtils; -import org.apache.http.config.SocketConfig; -import org.apache.http.entity.BufferedHttpEntity; -import org.apache.http.entity.ContentType; -import org.apache.http.entity.StringEntity; -import org.apache.http.impl.client.HttpClientBuilder; -import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; -import org.apache.http.message.BasicHeader; +import java.util.ArrayList; +import java.util.Map.Entry; +import org.apache.hc.client5.http.classic.methods.HttpUriRequestBase; +import org.apache.hc.client5.http.config.RequestConfig; +import org.apache.hc.client5.http.entity.UrlEncodedFormEntity; +import org.apache.hc.client5.http.impl.classic.CloseableHttpClient; +import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse; +import org.apache.hc.client5.http.impl.classic.HttpClientBuilder; +import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager; +import org.apache.hc.core5.http.ContentType; +import org.apache.hc.core5.http.HttpEntity; +import org.apache.hc.core5.http.HttpHeaders; +import org.apache.hc.core5.http.NameValuePair; +import org.apache.hc.core5.http.io.SocketConfig; +import org.apache.hc.core5.http.io.entity.BufferedHttpEntity; +import org.apache.hc.core5.http.io.entity.StringEntity; +import org.apache.hc.core5.http.message.BasicHeader; import java.io.IOException; import java.nio.charset.StandardCharsets; @@ -29,10 +30,12 @@ import java.util.Collection; import java.util.List; import java.util.Map; +import org.apache.hc.core5.http.message.BasicNameValuePair; +import static com.twilio.http.HttpClient.createHttpUriRequestBase; public class BearerTokenNetworkHttpClient extends BearerTokenHttpClient { - protected final org.apache.http.client.HttpClient client; + protected final CloseableHttpClient client; private boolean isCustomClient; @@ -68,7 +71,7 @@ public BearerTokenNetworkHttpClient(final RequestConfig requestConfig, final Soc String googleAppEngineVersion = System.getProperty("com.google.appengine.runtime.version"); boolean isGoogleAppEngine = googleAppEngineVersion != null && !googleAppEngineVersion.isEmpty(); - org.apache.http.impl.client.HttpClientBuilder clientBuilder = HttpClientBuilder.create(); + HttpClientBuilder clientBuilder = HttpClientBuilder.create(); if (!isGoogleAppEngine) { clientBuilder.useSystemProperties(); @@ -76,7 +79,7 @@ public BearerTokenNetworkHttpClient(final RequestConfig requestConfig, final Soc PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(); connectionManager.setDefaultSocketConfig(socketConfig); - /* + /** * Example: Lets say client has one server. * There are 4 servers on edge handling client request. * Each request takes on an average 500ms (2 request per second) @@ -106,9 +109,10 @@ public BearerTokenNetworkHttpClient(HttpClientBuilder clientBuilder) { isCustomClient = true; client = clientBuilder - .setDefaultHeaders(headers) - .setRedirectStrategy(this.getRedirectStrategy()) - .build(); + .setDefaultRequestConfig(DEFAULT_REQUEST_CONFIG) + .setDefaultHeaders(headers) + .setRedirectStrategy(this.getRedirectStrategy()) + .build(); } /** @@ -120,18 +124,16 @@ public BearerTokenNetworkHttpClient(HttpClientBuilder clientBuilder) { public Response makeRequest(final BearerTokenRequest request) { HttpMethod method = request.getMethod(); - RequestBuilder builder = RequestBuilder.create(method.toString()) - .setUri(request.constructURL().toString()) - .setVersion(HttpVersion.HTTP_1_1) - .setCharset(StandardCharsets.UTF_8); + HttpUriRequestBase httpUriRequestBase = createHttpUriRequestBase(request); + if (request.requiresAuthentication()) { - builder.addHeader(HttpHeaders.AUTHORIZATION, request.getAuthString()); + httpUriRequestBase.addHeader(HttpHeaders.AUTHORIZATION, request.getAuthString()); } for (Map.Entry> entry : request.getHeaderParams().entrySet()) { for (String value : entry.getValue()) { - builder.addHeader(entry.getKey(), value); + httpUriRequestBase.addHeader(entry.getKey(), value); } } @@ -140,40 +142,40 @@ public Response makeRequest(final BearerTokenRequest request) { if (request.getContentType() == null) request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); if (EnumConstants.ContentType.JSON.getValue().equals(request.getContentType().getValue())) { HttpEntity entity = new StringEntity(request.getBody(), ContentType.APPLICATION_JSON); - builder.setEntity(entity); - builder.addHeader( + httpUriRequestBase.setEntity(entity); + httpUriRequestBase.addHeader( HttpHeaders.CONTENT_TYPE, EnumConstants.ContentType.JSON.getValue()); } else { - builder.addHeader( + httpUriRequestBase.addHeader( HttpHeaders.CONTENT_TYPE, EnumConstants.ContentType.FORM_URLENCODED.getValue()); - for (Map.Entry> entry : request.getPostParams().entrySet()) { + // Create your form parameters + List formParams = new ArrayList<>(); + for ( Entry> entry : request.getPostParams().entrySet()) { for (String value : entry.getValue()) { - builder.addParameter(entry.getKey(), value); + formParams.add(new BasicNameValuePair(entry.getKey(), value)); } } + + // Build the entity with URL form encoded parameters + UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(formParams, StandardCharsets.UTF_8); + // Set the entity on the request + httpUriRequestBase.setEntity(formEntity); } } - builder.addHeader(HttpHeaders.USER_AGENT, HttpUtility.getUserAgentString(request.getUserAgentExtensions(), isCustomClient)); - - HttpResponse response = null; + httpUriRequestBase.addHeader(HttpHeaders.USER_AGENT, HttpUtility.getUserAgentString(request.getUserAgentExtensions(), isCustomClient)); try { - response = client.execute(builder.build()); + CloseableHttpResponse response = client.execute(httpUriRequestBase); HttpEntity entity = response.getEntity(); return new Response( // Consume the entire HTTP response before returning the stream entity == null ? null : new BufferedHttpEntity(entity).getContent(), - response.getStatusLine().getStatusCode(), - response.getAllHeaders() + response.getCode(), + response.getHeaders() ); } catch (IOException e) { throw new ApiException(e.getMessage(), e); - } finally { - - // Ensure this response is properly closed - HttpClientUtils.closeQuietly(response); - } } } diff --git a/src/main/java/com/twilio/http/bearertoken/BearerTokenTwilioRestClient.java b/src/main/java/com/twilio/http/bearertoken/BearerTokenTwilioRestClient.java index f3ba9fac59..c7da1ff2b0 100644 --- a/src/main/java/com/twilio/http/bearertoken/BearerTokenTwilioRestClient.java +++ b/src/main/java/com/twilio/http/bearertoken/BearerTokenTwilioRestClient.java @@ -140,7 +140,7 @@ public Response request(BearerTokenRequest request) { if (logger.isDebugEnabled()) { logger.debug("status code: {}", statusCode); - org.apache.http.Header[] responseHeaders = response.getHeaders(); + org.apache.hc.core5.http.Header[] responseHeaders = response.getHeaders(); logger.debug("response headers:"); for (int i = 0; i < responseHeaders.length; i++) { logger.debug("responseHeader: {}", responseHeaders[i]); diff --git a/src/main/java/com/twilio/http/noauth/NoAuthHttpClient.java b/src/main/java/com/twilio/http/noauth/NoAuthHttpClient.java index 8ae8d7d2bf..09a159bb74 100644 --- a/src/main/java/com/twilio/http/noauth/NoAuthHttpClient.java +++ b/src/main/java/com/twilio/http/noauth/NoAuthHttpClient.java @@ -4,16 +4,15 @@ import com.twilio.http.Response; import lombok.Getter; import lombok.Setter; -import org.apache.http.client.RedirectStrategy; -import org.apache.http.client.config.RequestConfig; -import org.apache.http.config.SocketConfig; -import org.apache.http.impl.client.DefaultRedirectStrategy; +import org.apache.hc.client5.http.config.RequestConfig; +import org.apache.hc.client5.http.impl.DefaultRedirectStrategy; +import org.apache.hc.client5.http.protocol.RedirectStrategy; +import org.apache.hc.core5.http.io.SocketConfig; public abstract class NoAuthHttpClient { public static final RequestConfig DEFAULT_REQUEST_CONFIG = RequestConfig .custom() .setConnectTimeout(HttpClient.CONNECTION_TIMEOUT) - .setSocketTimeout(HttpClient.SOCKET_TIMEOUT) .build(); public static final SocketConfig DEFAULT_SOCKET_CONFIG = SocketConfig .custom() @@ -21,7 +20,7 @@ public abstract class NoAuthHttpClient { .build(); @Getter @Setter - private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy(new String[0]); + private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy(); @Getter private Response lastResponse; @@ -102,6 +101,6 @@ protected boolean shouldRetry(final Response response, final int[] retryCodes) { } return false; } - + public abstract Response makeRequest(NoAuthRequest request); } diff --git a/src/main/java/com/twilio/http/noauth/NoAuthNetworkHttpClient.java b/src/main/java/com/twilio/http/noauth/NoAuthNetworkHttpClient.java index df87ef709b..a1b84a5532 100644 --- a/src/main/java/com/twilio/http/noauth/NoAuthNetworkHttpClient.java +++ b/src/main/java/com/twilio/http/noauth/NoAuthNetworkHttpClient.java @@ -1,37 +1,48 @@ package com.twilio.http.noauth; +import static com.twilio.http.HttpClient.createHttpUriRequestBase; + import com.twilio.Twilio; import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiException; import com.twilio.http.HttpMethod; import com.twilio.http.HttpUtility; -import com.twilio.http.Request; import com.twilio.http.Response; -import org.apache.http.HttpEntity; -import org.apache.http.HttpHeaders; -import org.apache.http.HttpResponse; -import org.apache.http.HttpVersion; -import org.apache.http.client.config.RequestConfig; -import org.apache.http.client.methods.RequestBuilder; -import org.apache.http.client.utils.HttpClientUtils; -import org.apache.http.config.SocketConfig; -import org.apache.http.entity.BufferedHttpEntity; -import org.apache.http.entity.ContentType; -import org.apache.http.entity.StringEntity; -import org.apache.http.impl.client.HttpClientBuilder; -import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; -import org.apache.http.message.BasicHeader; +import java.util.ArrayList; +import java.util.Map.Entry; +import org.apache.hc.client5.http.classic.methods.HttpDelete; +import org.apache.hc.client5.http.classic.methods.HttpGet; +import org.apache.hc.client5.http.classic.methods.HttpPatch; +import org.apache.hc.client5.http.classic.methods.HttpPost; +import org.apache.hc.client5.http.classic.methods.HttpPut; +import org.apache.hc.client5.http.classic.methods.HttpUriRequestBase; +import org.apache.hc.client5.http.config.RequestConfig; +import org.apache.hc.client5.http.entity.UrlEncodedFormEntity; +import org.apache.hc.client5.http.impl.classic.CloseableHttpClient; +import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse; +import org.apache.hc.client5.http.impl.classic.HttpClientBuilder; +import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager; +import org.apache.hc.core5.http.ContentType; +import org.apache.hc.core5.http.HttpEntity; +import org.apache.hc.core5.http.HttpHeaders; +import org.apache.hc.core5.http.HttpVersion; +import org.apache.hc.core5.http.NameValuePair; +import org.apache.hc.core5.http.io.SocketConfig; +import org.apache.hc.core5.http.io.entity.BufferedHttpEntity; +import org.apache.hc.core5.http.io.entity.StringEntity; +import org.apache.hc.core5.http.message.BasicHeader; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.Collection; import java.util.List; -import java.util.Map; +import org.apache.hc.core5.http.message.BasicNameValuePair; public class NoAuthNetworkHttpClient extends NoAuthHttpClient { - protected final org.apache.http.client.HttpClient client; + protected final CloseableHttpClient client; + public NoAuthNetworkHttpClient() { this(DEFAULT_REQUEST_CONFIG); } @@ -50,7 +61,7 @@ public NoAuthNetworkHttpClient(final RequestConfig requestConfig, final SocketCo String googleAppEngineVersion = System.getProperty("com.google.appengine.runtime.version"); boolean isGoogleAppEngine = googleAppEngineVersion != null && !googleAppEngineVersion.isEmpty(); - org.apache.http.impl.client.HttpClientBuilder clientBuilder = HttpClientBuilder.create(); + HttpClientBuilder clientBuilder = HttpClientBuilder.create(); if (!isGoogleAppEngine) { clientBuilder.useSystemProperties(); @@ -74,61 +85,55 @@ public NoAuthNetworkHttpClient(final RequestConfig requestConfig, final SocketCo .setRedirectStrategy(this.getRedirectStrategy()) .build(); } - + @Override public Response makeRequest(NoAuthRequest request) { HttpMethod method = request.getMethod(); - RequestBuilder builder = RequestBuilder.create(method.toString()) - .setUri(request.constructURL().toString()) - .setVersion(HttpVersion.HTTP_1_1) - .setCharset(StandardCharsets.UTF_8); - - for (Map.Entry> entry : request.getHeaderParams().entrySet()) { - for (String value : entry.getValue()) { - builder.addHeader(entry.getKey(), value); - } - } + HttpUriRequestBase httpUriRequestBase = createHttpUriRequestBase(request); + + httpUriRequestBase.setConfig(DEFAULT_REQUEST_CONFIG); + + httpUriRequestBase.setVersion(HttpVersion.HTTP_1_1); if (method != HttpMethod.GET) { // TODO: It will be removed after one RC Release. if (request.getContentType() == null) request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); if (EnumConstants.ContentType.JSON.getValue().equals(request.getContentType().getValue())) { HttpEntity entity = new StringEntity(request.getBody(), ContentType.APPLICATION_JSON); - builder.setEntity(entity); - builder.addHeader( - HttpHeaders.CONTENT_TYPE, EnumConstants.ContentType.JSON.getValue()); + httpUriRequestBase.setEntity(entity); + httpUriRequestBase.addHeader( + HttpHeaders.CONTENT_TYPE, EnumConstants.ContentType.JSON.getValue()); } else { - builder.addHeader( + httpUriRequestBase.addHeader( HttpHeaders.CONTENT_TYPE, EnumConstants.ContentType.FORM_URLENCODED.getValue()); - for (Map.Entry> entry : request.getPostParams().entrySet()) { + // Create your form parameters + List formParams = new ArrayList<>(); + for ( Entry> entry : request.getPostParams().entrySet()) { for (String value : entry.getValue()) { - builder.addParameter(entry.getKey(), value); + formParams.add(new BasicNameValuePair(entry.getKey(), value)); } } + + // Build the entity with URL form encoded parameters + UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(formParams, StandardCharsets.UTF_8); + // Set the entity on the request + httpUriRequestBase.setEntity(formEntity); } } - builder.addHeader(HttpHeaders.USER_AGENT, HttpUtility.getUserAgentString(request.getUserAgentExtensions())); - - HttpResponse response = null; + httpUriRequestBase.addHeader(HttpHeaders.USER_AGENT, HttpUtility.getUserAgentString(request.getUserAgentExtensions())); try { - response = client.execute(builder.build()); + CloseableHttpResponse response = client.execute(httpUriRequestBase); HttpEntity entity = response.getEntity(); return new Response( // Consume the entire HTTP response before returning the stream entity == null ? null : new BufferedHttpEntity(entity).getContent(), - response.getStatusLine().getStatusCode(), - response.getAllHeaders() + response.getCode(), + response.getHeaders() ); } catch (IOException e) { throw new ApiException(e.getMessage(), e); - } finally { - - // Ensure this response is properly closed - HttpClientUtils.closeQuietly(response); - } - } } diff --git a/src/main/java/com/twilio/http/noauth/NoAuthRequest.java b/src/main/java/com/twilio/http/noauth/NoAuthRequest.java index 00cc7bf140..1d216699eb 100644 --- a/src/main/java/com/twilio/http/noauth/NoAuthRequest.java +++ b/src/main/java/com/twilio/http/noauth/NoAuthRequest.java @@ -4,7 +4,7 @@ import com.twilio.http.IRequest; public class NoAuthRequest extends IRequest { - + public NoAuthRequest(HttpMethod method, String url) { super(method, url); } diff --git a/src/main/java/com/twilio/http/noauth/NoAuthTwilioRestClient.java b/src/main/java/com/twilio/http/noauth/NoAuthTwilioRestClient.java index 93da0f361a..ff2e790380 100644 --- a/src/main/java/com/twilio/http/noauth/NoAuthTwilioRestClient.java +++ b/src/main/java/com/twilio/http/noauth/NoAuthTwilioRestClient.java @@ -21,7 +21,7 @@ public class NoAuthTwilioRestClient { @Getter private final ObjectMapper objectMapper; - + @Getter private final String region; @Getter @@ -110,7 +110,7 @@ public Response request(NoAuthRequest request) { if (logger.isDebugEnabled()) { logger.debug("status code: {}", response.getStatusCode()); - org.apache.http.Header[] responseHeaders = response.getHeaders(); + org.apache.hc.core5.http.Header[] responseHeaders = response.getHeaders(); logger.debug("response headers:"); for (int i = 0; i < responseHeaders.length; i++) { logger.debug("responseHeader: {}", responseHeaders[i]); diff --git a/src/main/java/com/twilio/jwt/validation/RequestCanonicalizer.java b/src/main/java/com/twilio/jwt/validation/RequestCanonicalizer.java index 01be9e08b3..2c34f385bf 100644 --- a/src/main/java/com/twilio/jwt/validation/RequestCanonicalizer.java +++ b/src/main/java/com/twilio/jwt/validation/RequestCanonicalizer.java @@ -2,8 +2,6 @@ import com.twilio.exception.InvalidRequestException; import org.apache.commons.codec.digest.DigestUtils; -import org.apache.http.Header; -import org.apache.http.message.BasicHeader; import java.io.UnsupportedEncodingException; import java.net.URI; @@ -13,6 +11,8 @@ import java.util.function.Function; import java.util.regex.Matcher; import java.util.regex.Pattern; +import org.apache.hc.core5.http.Header; +import org.apache.hc.core5.http.message.BasicHeader; /** * Creates a canonical string out of HTTP request components. diff --git a/src/main/java/com/twilio/jwt/validation/ValidationToken.java b/src/main/java/com/twilio/jwt/validation/ValidationToken.java index 4a1f48dc60..15f25618a8 100644 --- a/src/main/java/com/twilio/jwt/validation/ValidationToken.java +++ b/src/main/java/com/twilio/jwt/validation/ValidationToken.java @@ -4,18 +4,17 @@ import io.jsonwebtoken.SignatureAlgorithm; import org.apache.commons.codec.digest.DigestUtils; import org.apache.commons.io.IOUtils; -import org.apache.http.Header; -import org.apache.http.HttpEntity; -import org.apache.http.HttpEntityEnclosingRequest; -import org.apache.http.HttpRequest; -import org.apache.http.impl.auth.UnsupportedDigestAlgorithmException; import java.io.IOException; -import java.io.UnsupportedEncodingException; import java.nio.charset.StandardCharsets; import java.security.PrivateKey; import java.util.*; import java.util.function.Function; +import org.apache.hc.client5.http.classic.methods.HttpUriRequestBase; +import org.apache.hc.core5.http.Header; +import org.apache.hc.core5.http.HttpEntity; +import org.apache.hc.core5.http.HttpRequest; +import org.apache.hc.client5.http.classic.methods.HttpPost; import static io.jsonwebtoken.SignatureAlgorithm.PS256; import static io.jsonwebtoken.SignatureAlgorithm.RS256; @@ -134,11 +133,11 @@ public static ValidationToken fromHttpRequest( ) throws IOException { Builder builder = new Builder(accountSid, credentialSid, signingKeySid, privateKey); - String method = request.getRequestLine().getMethod(); + String method = request.getMethod(); builder.method(method); builder.algorithm(algorithm); - String uri = request.getRequestLine().getUri(); + String uri = request.getRequestUri(); if (uri.contains("?")) { String[] uriParts = uri.split("\\?"); builder.uri(uriParts[0]); @@ -147,7 +146,7 @@ public static ValidationToken fromHttpRequest( builder.uri(uri); } - builder.headers(request.getAllHeaders()); + builder.headers(request.getHeaders()); builder.signedHeaders(signedHeaders); /** @@ -156,8 +155,8 @@ public static ValidationToken fromHttpRequest( * * @see org.apache.http.client.methods.RequestBuilder#build */ - if (request instanceof HttpEntityEnclosingRequest) { - HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity(); + if (request instanceof HttpUriRequestBase) { + HttpEntity entity = ((HttpUriRequestBase) request).getEntity(); builder.requestBody(IOUtils.toString(entity.getContent(), StandardCharsets.UTF_8)); } diff --git a/src/main/java/com/twilio/rest/content/v1/Content.java b/src/main/java/com/twilio/rest/content/v1/Content.java index a33471a7df..1b21e6becb 100644 --- a/src/main/java/com/twilio/rest/content/v1/Content.java +++ b/src/main/java/com/twilio/rest/content/v1/Content.java @@ -34,12 +34,10 @@ import java.time.ZonedDateTime; import java.util.List; import java.util.Map; -import java.util.Map; import java.util.Objects; import lombok.Getter; import lombok.Setter; import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString diff --git a/src/main/java/com/twilio/security/RequestValidator.java b/src/main/java/com/twilio/security/RequestValidator.java index 336291fcad..a7b7f1d3c4 100644 --- a/src/main/java/com/twilio/security/RequestValidator.java +++ b/src/main/java/com/twilio/security/RequestValidator.java @@ -1,8 +1,6 @@ package com.twilio.security; import org.apache.commons.codec.binary.Hex; -import org.apache.http.NameValuePair; -import org.apache.http.client.utils.URLEncodedUtils; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; @@ -14,6 +12,8 @@ import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.*; +import org.apache.hc.core5.http.NameValuePair; +import org.apache.hc.core5.net.URLEncodedUtils; public class RequestValidator { @@ -31,7 +31,7 @@ public boolean validate(String url, Map params, String expectedS String signatureWithPort = getValidationSignature(addPort(url), params); String signatureWithoutPort = getValidationSignature(removePort(url), params); // If either url produces a valid signature, we accept the request as valid - return secureCompare(signatureWithPort, expectedSignature) || + return secureCompare(signatureWithPort, expectedSignature) || secureCompare(signatureWithoutPort, expectedSignature); } @@ -49,9 +49,8 @@ public boolean validate(String url, String body, String expectedSignature) throw if (bodySHA256 != null) { return validate(url, empty, expectedSignature) && validateBody(body, bodySHA256.getValue()); - } else { - return false; } + return false; } public boolean validateBody(String body, String expectedSHA) { @@ -120,7 +119,7 @@ private String removePort(String url) { return url; } } - + private String addPort(String url) { try { URI parsedUrl = new URI(url); @@ -139,7 +138,7 @@ private String updatePort(URI url, int newPort) { return new URI( url.getScheme(), url.getUserInfo(), - url.getHost(), + url.getHost(), newPort, url.getPath(), url.getQuery(), diff --git a/src/test/java/com/twilio/ClusterTest.java b/src/test/java/com/twilio/ClusterTest.java index 48e0fc3f39..50062a5486 100644 --- a/src/test/java/com/twilio/ClusterTest.java +++ b/src/test/java/com/twilio/ClusterTest.java @@ -16,6 +16,7 @@ import org.hamcrest.CoreMatchers; import org.junit.Assume; import org.junit.Before; +import org.junit.Ignore; import org.junit.Test; import java.util.ArrayList; diff --git a/src/test/java/com/twilio/TwilioTest.java b/src/test/java/com/twilio/TwilioTest.java index 550f2d491f..f6f3fd3a20 100644 --- a/src/test/java/com/twilio/TwilioTest.java +++ b/src/test/java/com/twilio/TwilioTest.java @@ -47,7 +47,7 @@ public static String serialize(List list) { @Before public void init() { - MockitoAnnotations.initMocks(this); + MockitoAnnotations.openMocks(this); } @Test diff --git a/src/test/java/com/twilio/base/ReaderTest.java b/src/test/java/com/twilio/base/ReaderTest.java index ebc34675fb..0b34e65eba 100644 --- a/src/test/java/com/twilio/base/ReaderTest.java +++ b/src/test/java/com/twilio/base/ReaderTest.java @@ -23,7 +23,7 @@ public class ReaderTest { @Before public void init() { - MockitoAnnotations.initMocks(this); + MockitoAnnotations.openMocks(this); } @Test diff --git a/src/test/java/com/twilio/base/ResourceSetIterationTest.java b/src/test/java/com/twilio/base/ResourceSetIterationTest.java index 7cc7a8b80f..5d3fdc494c 100644 --- a/src/test/java/com/twilio/base/ResourceSetIterationTest.java +++ b/src/test/java/com/twilio/base/ResourceSetIterationTest.java @@ -65,7 +65,7 @@ public class ResourceSetIterationTest { @Before public void init() { - MockitoAnnotations.initMocks(this); + MockitoAnnotations.openMocks(this); } @Test diff --git a/src/test/java/com/twilio/http/CustomHttpClient.java b/src/test/java/com/twilio/http/CustomHttpClient.java index ecd6bfb14e..e8c99c6db1 100644 --- a/src/test/java/com/twilio/http/CustomHttpClient.java +++ b/src/test/java/com/twilio/http/CustomHttpClient.java @@ -1,21 +1,25 @@ package com.twilio.http; import com.twilio.exception.ApiException; -import org.apache.http.HttpEntity; -import org.apache.http.HttpHeaders; -import org.apache.http.HttpResponse; -import org.apache.http.HttpVersion; -import org.apache.http.client.methods.RequestBuilder; -import org.apache.http.client.utils.HttpClientUtils; -import org.apache.http.entity.BufferedHttpEntity; -import org.apache.http.entity.ContentType; -import org.apache.http.entity.mime.MultipartEntityBuilder; -import org.apache.http.entity.mime.content.StringBody; + import java.io.IOException; -import java.nio.charset.StandardCharsets; import java.util.List; import java.util.Map; +import org.apache.hc.client5.http.classic.methods.HttpDelete; +import org.apache.hc.client5.http.classic.methods.HttpGet; +import org.apache.hc.client5.http.classic.methods.HttpPatch; +import org.apache.hc.client5.http.classic.methods.HttpPost; +import org.apache.hc.client5.http.classic.methods.HttpPut; +import org.apache.hc.client5.http.classic.methods.HttpUriRequestBase; +import org.apache.hc.client5.http.entity.mime.MultipartEntityBuilder; +import org.apache.hc.client5.http.entity.mime.StringBody; +import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse; +import org.apache.hc.core5.http.ContentType; +import org.apache.hc.core5.http.HttpEntity; +import org.apache.hc.core5.http.HttpHeaders; +import org.apache.hc.core5.http.HttpVersion; +import org.apache.hc.core5.http.io.entity.BufferedHttpEntity; public class CustomHttpClient extends NetworkHttpClient { @@ -26,20 +30,18 @@ public CustomHttpClient() { @Override public Response makeRequest(Request request) { HttpMethod method = request.getMethod(); - RequestBuilder builder = RequestBuilder.create(method.toString()) - .setUri(request.constructURL().toString()) - .setVersion(HttpVersion.HTTP_1_1) - .setCharset(StandardCharsets.UTF_8); + HttpUriRequestBase httpUriRequestBase = createHttpUriRequestBase(request); + httpUriRequestBase.setVersion(HttpVersion.HTTP_1_1); if (request instanceof Request) { Request basicRequest = (Request) request; if (basicRequest.requiresAuthentication()) { - builder.addHeader(HttpHeaders.AUTHORIZATION, basicRequest.getAuthString()); + httpUriRequestBase.addHeader(HttpHeaders.AUTHORIZATION, basicRequest.getAuthString()); } } for (Map.Entry> entry : request.getHeaderParams().entrySet()) { for (String value : entry.getValue()) { - builder.addHeader(entry.getKey(), value); + httpUriRequestBase.addHeader(entry.getKey(), value); } } MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create(); @@ -48,23 +50,21 @@ public Response makeRequest(Request request) { multipartEntityBuilder.addPart(entry.getKey(), new StringBody(value, ContentType.TEXT_PLAIN)); } } - builder.addHeader(HttpHeaders.USER_AGENT, HttpUtility.getUserAgentString(request.getUserAgentExtensions(), true)); - builder.setEntity(multipartEntityBuilder.build()); - HttpResponse response = null; + httpUriRequestBase.addHeader(HttpHeaders.USER_AGENT, HttpUtility.getUserAgentString(request.getUserAgentExtensions(), true)); + httpUriRequestBase.setEntity(multipartEntityBuilder.build()); + CloseableHttpResponse response = null; try { - response = client.execute(builder.build()); + response = client.execute(httpUriRequestBase); HttpEntity entity = response.getEntity(); return new Response( // Consume the entire HTTP response before returning the stream entity == null ? null : new BufferedHttpEntity(entity).getContent(), - response.getStatusLine().getStatusCode(), - response.getAllHeaders() + response.getCode(), + response.getHeaders() ); } catch (IOException e) { throw new ApiException(e.getMessage(), e); - } finally { - HttpClientUtils.closeQuietly(response); } } } diff --git a/src/test/java/com/twilio/http/HttpClientTest.java b/src/test/java/com/twilio/http/HttpClientTest.java new file mode 100644 index 0000000000..be7bf31fb7 --- /dev/null +++ b/src/test/java/com/twilio/http/HttpClientTest.java @@ -0,0 +1,208 @@ +package com.twilio.http; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.nio.file.Path; +import java.nio.file.Paths; + +import org.apache.hc.core5.http.ContentType; +import org.junit.Before; +import org.junit.Test; + +public class HttpClientTest { + + private TestHttpClient client; + + @Before + public void setup() { + client = new TestHttpClient(); + } + + @Test + public void testGetContentTypePdf() { + Path path = Paths.get("document.pdf"); + ContentType contentType = HttpClient.getContentType(path); + assertEquals("application/pdf", contentType.getMimeType()); + } + + @Test + public void testGetContentTypeJpg() { + Path path = Paths.get("image.jpg"); + ContentType contentType = HttpClient.getContentType(path); + assertEquals("image/jpeg", contentType.getMimeType()); + } + + @Test + public void testGetContentTypeJpeg() { + Path path = Paths.get("image.jpeg"); + ContentType contentType = HttpClient.getContentType(path); + assertEquals("image/jpeg", contentType.getMimeType()); + } + + @Test + public void testGetContentTypePng() { + Path path = Paths.get("image.png"); + ContentType contentType = HttpClient.getContentType(path); + assertEquals("image/png", contentType.getMimeType()); + } + + @Test + public void testGetContentTypeDefaultForUnknown() { + Path path = Paths.get("file.unknown"); + ContentType contentType = HttpClient.getContentType(path); + assertEquals("application/octet-stream", contentType.getMimeType()); + } + + @Test + public void testGetContentTypeCaseInsensitive() { + Path path = Paths.get("image.PNG"); + ContentType contentType = HttpClient.getContentType(path); + assertEquals("image/png", contentType.getMimeType()); + } + + @Test + public void testGetContentTypeWithPathAndDots() { + Path path = Paths.get("/path/to/my.file.pdf"); + ContentType contentType = HttpClient.getContentType(path); + assertEquals("application/pdf", contentType.getMimeType()); + } + + @Test + public void testGetContentTypeWithoutExtension() { + Path path = Paths.get("noextension"); + ContentType contentType = HttpClient.getContentType(path); + assertEquals("application/octet-stream", contentType.getMimeType()); + } + + @Test + public void testShouldRetryWithNullResponse() { + assertTrue(client.shouldRetry(null, new int[]{HttpClient.ANY_500})); + } + + @Test + public void testShouldRetryWithSpecificStatusCode() { + Response response = mock(Response.class); + when(response.getStatusCode()).thenReturn(429); + + assertTrue(client.shouldRetry(response, new int[]{429})); + assertFalse(client.shouldRetry(response, new int[]{503})); + } + + @Test + public void testShouldRetryWithAny100StatusCode() { + Response response = mock(Response.class); + when(response.getStatusCode()).thenReturn(100); + + assertTrue(client.shouldRetry(response, new int[]{HttpClient.ANY_100})); + + when(response.getStatusCode()).thenReturn(199); + assertTrue(client.shouldRetry(response, new int[]{HttpClient.ANY_100})); + + when(response.getStatusCode()).thenReturn(200); + assertFalse(client.shouldRetry(response, new int[]{HttpClient.ANY_100})); + } + + @Test + public void testShouldRetryWithAny200StatusCode() { + Response response = mock(Response.class); + when(response.getStatusCode()).thenReturn(200); + + assertTrue(client.shouldRetry(response, new int[]{HttpClient.ANY_200})); + + when(response.getStatusCode()).thenReturn(299); + assertTrue(client.shouldRetry(response, new int[]{HttpClient.ANY_200})); + + when(response.getStatusCode()).thenReturn(300); + assertFalse(client.shouldRetry(response, new int[]{HttpClient.ANY_200})); + } + + @Test + public void testShouldRetryWithAny300StatusCode() { + Response response = mock(Response.class); + when(response.getStatusCode()).thenReturn(300); + + assertTrue(client.shouldRetry(response, new int[]{HttpClient.ANY_300})); + + when(response.getStatusCode()).thenReturn(399); + assertTrue(client.shouldRetry(response, new int[]{HttpClient.ANY_300})); + + when(response.getStatusCode()).thenReturn(400); + assertFalse(client.shouldRetry(response, new int[]{HttpClient.ANY_300})); + } + + @Test + public void testShouldRetryWithAny400StatusCode() { + Response response = mock(Response.class); + when(response.getStatusCode()).thenReturn(400); + + assertTrue(client.shouldRetry(response, new int[]{HttpClient.ANY_400})); + + when(response.getStatusCode()).thenReturn(499); + assertTrue(client.shouldRetry(response, new int[]{HttpClient.ANY_400})); + + when(response.getStatusCode()).thenReturn(500); + assertFalse(client.shouldRetry(response, new int[]{HttpClient.ANY_400})); + } + + @Test + public void testShouldRetryWithAny500StatusCode() { + Response response = mock(Response.class); + when(response.getStatusCode()).thenReturn(500); + + assertTrue(client.shouldRetry(response, new int[]{HttpClient.ANY_500})); + + when(response.getStatusCode()).thenReturn(599); + assertTrue(client.shouldRetry(response, new int[]{HttpClient.ANY_500})); + + when(response.getStatusCode()).thenReturn(600); + assertFalse(client.shouldRetry(response, new int[]{HttpClient.ANY_500})); + } + + @Test + public void testShouldRetryWithMultipleRetryCodes() { + Response response = mock(Response.class); + when(response.getStatusCode()).thenReturn(429); + + assertTrue(client.shouldRetry(response, new int[]{HttpClient.ANY_500, 429})); + + when(response.getStatusCode()).thenReturn(503); + assertTrue(client.shouldRetry(response, new int[]{HttpClient.ANY_500, 429})); + + when(response.getStatusCode()).thenReturn(200); + assertFalse(client.shouldRetry(response, new int[]{HttpClient.ANY_500, 429})); + } + + @Test + public void testShouldRetryWithDefaultRetryCodes() { + Response response = mock(Response.class); + + when(response.getStatusCode()).thenReturn(500); + assertTrue(client.shouldRetry(response, HttpClient.RETRY_CODES)); + + when(response.getStatusCode()).thenReturn(503); + assertTrue(client.shouldRetry(response, HttpClient.RETRY_CODES)); + + when(response.getStatusCode()).thenReturn(200); + assertFalse(client.shouldRetry(response, HttpClient.RETRY_CODES)); + + when(response.getStatusCode()).thenReturn(400); + assertFalse(client.shouldRetry(response, HttpClient.RETRY_CODES)); + } + + // Test HttpClient subclass to expose protected method for testing + private static class TestHttpClient extends HttpClient { + @Override + public Response makeRequest(Request request) { + return null; // Not needed for testing + } + + @Override + public boolean shouldRetry(Response response, int[] retryCodes) { + return super.shouldRetry(response, retryCodes); + } + } +} \ No newline at end of file diff --git a/src/test/java/com/twilio/http/IRequestTest.java b/src/test/java/com/twilio/http/IRequestTest.java new file mode 100644 index 0000000000..1e1e6103af --- /dev/null +++ b/src/test/java/com/twilio/http/IRequestTest.java @@ -0,0 +1,138 @@ +package com.twilio.http; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import com.twilio.http.IRequest.FormParameters; +import com.twilio.http.IRequest.FormParameters.Type; +import java.util.ArrayList; +import java.util.List; +import org.junit.Test; + +public class IRequestTest { + + @Test + public void testAddTextFormParameter() { + IRequest request = new IRequest(HttpMethod.POST, "http://example.com"); + request.addFormParameter("name", Type.TEXT, "John Doe"); + + List params = request.getFormParameters(); + assertEquals(1, params.size()); + + FormParameters param = params.get(0); + assertEquals("name", param.getName()); + assertEquals(Type.TEXT, param.getType()); + assertEquals("John Doe", param.getValue()); + } + + @Test + public void testAddFileFormParameter() { + IRequest request = new IRequest(HttpMethod.POST, "http://example.com"); + String filePath = "/path/to/file.jpg"; + request.addFormParameter("file", Type.FILE, filePath); + + List params = request.getFormParameters(); + assertEquals(1, params.size()); + + FormParameters param = params.get(0); + assertEquals("file", param.getName()); + assertEquals(Type.FILE, param.getType()); + assertEquals(filePath, param.getValue()); + } + + @Test + public void testAddMultipleFormParameters() { + IRequest request = new IRequest(HttpMethod.POST, "http://example.com"); + request.addFormParameter("name", Type.TEXT, "John Doe"); + request.addFormParameter("email", Type.TEXT, "john@example.com"); + request.addFormParameter("file", Type.FILE, "/path/to/file.jpg"); + + List params = request.getFormParameters(); + assertEquals(3, params.size()); + + // Verify parameters were added in the correct order + assertEquals("name", params.get(0).getName()); + assertEquals("email", params.get(1).getName()); + assertEquals("file", params.get(2).getName()); + } + + @Test + public void testSetFormParameters() { + IRequest request = new IRequest(HttpMethod.POST, "http://example.com"); + + List paramsList = new ArrayList<>(); + paramsList.add(new FormParameters("name", Type.TEXT, "John Doe")); + paramsList.add(new FormParameters("file", Type.FILE, "/path/to/file.jpg")); + + request.setFormParameters(paramsList); + + List params = request.getFormParameters(); + assertEquals(2, params.size()); + + assertEquals("name", params.get(0).getName()); + assertEquals(Type.TEXT, params.get(0).getType()); + assertEquals("John Doe", params.get(0).getValue()); + + assertEquals("file", params.get(1).getName()); + assertEquals(Type.FILE, params.get(1).getType()); + assertEquals("/path/to/file.jpg", params.get(1).getValue()); + } + + @Test + public void testSetFormParametersAppends() { + IRequest request = new IRequest(HttpMethod.POST, "http://example.com"); + request.addFormParameter("existing", Type.TEXT, "Existing Value"); + + List additionalParams = new ArrayList<>(); + additionalParams.add(new FormParameters("new", Type.TEXT, "New Value")); + + request.setFormParameters(additionalParams); + + List params = request.getFormParameters(); + assertEquals(2, params.size()); + + assertEquals("existing", params.get(0).getName()); + assertEquals("new", params.get(1).getName()); + } + + @Test + public void testSetFormParametersNull() { + IRequest request = new IRequest(HttpMethod.POST, "http://example.com"); + + try { + request.setFormParameters(null); + fail("Should have thrown IllegalArgumentException"); + } catch (IllegalArgumentException e) { + assertEquals("Form parameters cannot be null", e.getMessage()); + } + } + + @Test + public void testFormParametersInitializedInConstructor() { + IRequest request = new IRequest(HttpMethod.POST, "http://example.com"); + + List params = request.getFormParameters(); + assertNotNull("FormParameters should be initialized", params); + assertTrue("FormParameters should be empty initially", params.isEmpty()); + } + + @Test + public void testFormParametersDomainConstructor() { + IRequest request = new IRequest(HttpMethod.POST, "api", "/v1/resource"); + + List params = request.getFormParameters(); + assertNotNull("FormParameters should be initialized", params); + assertTrue("FormParameters should be empty initially", params.isEmpty()); + } + + @Test + public void testFormParametersRegionConstructor() { + IRequest request = new IRequest(HttpMethod.POST, "api", "/v1/resource", "us1"); + + List params = request.getFormParameters(); + assertNotNull("FormParameters should be initialized", params); + assertTrue("FormParameters should be empty initially", params.isEmpty()); + } +} diff --git a/src/test/java/com/twilio/http/NetworkHttpClientTest.java b/src/test/java/com/twilio/http/NetworkHttpClientTest.java index ee5c9050f4..21c457c921 100644 --- a/src/test/java/com/twilio/http/NetworkHttpClientTest.java +++ b/src/test/java/com/twilio/http/NetworkHttpClientTest.java @@ -2,28 +2,42 @@ import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; -import org.apache.http.HttpEntity; -import org.apache.http.StatusLine; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClientBuilder; +import com.twilio.http.IRequest.FormParameters; +import com.twilio.http.IRequest.FormParameters.Type; +import org.apache.hc.client5.http.entity.mime.MultipartEntityBuilder; +import org.apache.hc.core5.http.HttpEntity; +import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse; +import org.apache.hc.client5.http.impl.classic.CloseableHttpClient; +import org.apache.hc.client5.http.impl.classic.HttpClientBuilder; import org.junit.Before; +import org.junit.Rule; import org.junit.Test; +import org.junit.rules.TemporaryFolder; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.mockito.Spy; import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.net.URL; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; import static org.junit.Assert.*; -import static org.mockito.Matchers.any; +import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; public class NetworkHttpClientTest { + @Rule + public TemporaryFolder temporaryFolder = new TemporaryFolder(); + private NetworkHttpClient client; @Mock @@ -42,15 +56,15 @@ public class NetworkHttpClientTest { private CloseableHttpResponse mockResponse; @Mock - private StatusLine mockStatusLine; + private HttpEntity mockEntity; @Mock - private HttpEntity mockEntity; + private MultipartEntityBuilder mockMultipartEntityBuilder; @Before public void setUp() { - MockitoAnnotations.initMocks(this); + MockitoAnnotations.openMocks(this); doReturn(mockClient).when(mockBuilder).build(); client = new NetworkHttpClient(mockBuilder); } @@ -72,9 +86,8 @@ private void setup( when(mockEntity.isRepeatable()).thenReturn(true); when(mockEntity.getContentLength()).thenReturn(1L); when(mockEntity.getContent()).thenReturn(stream); - when(mockResponse.getStatusLine()).thenReturn(mockStatusLine); when(mockResponse.getEntity()).thenReturn(mockEntity); - when(mockStatusLine.getStatusCode()).thenReturn(statusCode); + when(mockResponse.getCode()).thenReturn(statusCode); } @@ -182,4 +195,183 @@ public void testErrorResponse() throws IOException { assertEquals(resp.getStatusCode(), 404); assertEquals(resp.getContent(), "womp"); } + + @Test + public void testMultipartFormDataWithTextOnly() throws IOException { + // Mock setup + setup(201, "success", HttpMethod.POST, false); + when(mockRequest.getContentType()).thenReturn(EnumConstants.ContentType.MULTIPART_FORM_DATA); + + // Create test form parameters + List formParameters = new ArrayList<>(); + formParameters.add(new FormParameters("name", Type.TEXT, "John Doe")); + formParameters.add(new FormParameters("email", Type.TEXT, "john@example.com")); + when(mockRequest.getFormParameters()).thenReturn(formParameters); + + // Make the request + Response response = client.makeRequest(mockRequest); + + // Verify + assertEquals(201, response.getStatusCode()); + assertEquals("success", response.getContent()); + + } + + @Test + public void testMultipartFormDataWithFile() throws IOException { + // Create a temporary file for testing + File testFile = temporaryFolder.newFile("test.jpg"); + try (FileWriter writer = new FileWriter(testFile)) { + writer.write("test image data"); + } + + // Mock setup + setup(201, "success", HttpMethod.POST, false); + when(mockRequest.getContentType()).thenReturn(EnumConstants.ContentType.MULTIPART_FORM_DATA); + + // Create test form parameters + List formParameters = new ArrayList<>(); + formParameters.add(new FormParameters("file", Type.FILE, testFile.getAbsolutePath())); + when(mockRequest.getFormParameters()).thenReturn(formParameters); + when(mockRequest.getContentType()).thenReturn(EnumConstants.ContentType.MULTIPART_FORM_DATA); + + // Make the request + Response response = client.makeRequest(mockRequest); + + // Verify + assertEquals(201, response.getStatusCode()); + assertEquals("success", response.getContent()); + } + + @Test + public void testMultipartFormDataWithMixedContent() throws IOException { + // Create a temporary file for testing + File testFile = temporaryFolder.newFile("test.pdf"); + try (FileWriter writer = new FileWriter(testFile)) { + writer.write("test pdf data"); + } + + // Mock setup + setup(201, "success", HttpMethod.POST, false); + when(mockRequest.getContentType()).thenReturn(EnumConstants.ContentType.MULTIPART_FORM_DATA); + + // Create test form parameters with both text and file + List formParameters = new ArrayList<>(); + formParameters.add(new FormParameters("name", Type.TEXT, "John Doe")); + formParameters.add(new FormParameters("file", Type.FILE, testFile.getAbsolutePath())); + when(mockRequest.getFormParameters()).thenReturn(formParameters); + when(mockRequest.getContentType()).thenReturn(EnumConstants.ContentType.MULTIPART_FORM_DATA); + + // Make the request + Response response = client.makeRequest(mockRequest); + + // Verify + assertEquals(201, response.getStatusCode()); + assertEquals("success", response.getContent()); + } + + @Test + public void testPutMethod() throws IOException { + // Mock setup for PUT request + setup(200, "updated", HttpMethod.PUT, false); + + // Make the request + Response response = client.makeRequest(mockRequest); + + // Verify + assertEquals(200, response.getStatusCode()); + assertEquals("updated", response.getContent()); + } + + @Test + public void testPutMethodWithBody() throws IOException { + // Mock setup for PUT request with a JSON body + setup(200, "updated", HttpMethod.PUT, false); + when(mockRequest.getContentType()).thenReturn(EnumConstants.ContentType.JSON); + String jsonBody = "{\"name\":\"New Name\",\"active\":true}"; + when(mockRequest.getBody()).thenReturn(jsonBody); + + // Make the request + Response response = client.makeRequest(mockRequest); + + // Verify + assertEquals(200, response.getStatusCode()); + assertEquals("updated", response.getContent()); + + } + + @Test + public void testPatchMethod() throws IOException { + // Mock setup for PATCH request + setup(200, "patched", HttpMethod.PATCH, false); + + // Make the request + Response response = client.makeRequest(mockRequest); + + // Verify + assertEquals(200, response.getStatusCode()); + assertEquals("patched", response.getContent()); + } + + @Test + public void testPatchMethodWithJsonBody() throws IOException { + // Mock setup for PATCH request with a JSON body + setup(200, "patched", HttpMethod.PATCH, false); + when(mockRequest.getContentType()).thenReturn(EnumConstants.ContentType.JSON); + String jsonBody = "{\"status\":\"active\"}"; + when(mockRequest.getBody()).thenReturn(jsonBody); + + // Make the request + Response response = client.makeRequest(mockRequest); + + // Verify + assertEquals(200, response.getStatusCode()); + assertEquals("patched", response.getContent()); + } + + + @Test + public void testFormUrlEncodedMultipleParameters() throws IOException { + // Mock setup + setup(201, "created", HttpMethod.POST, false); + + // Set up multiple parameters + Map> postParams = new HashMap<>(); + postParams.put("name", Arrays.asList("John Doe")); + postParams.put("email", Arrays.asList("john@example.com")); + postParams.put("age", Arrays.asList("30")); + postParams.put("tags", Arrays.asList("customer", "premium")); + when(mockRequest.getPostParams()).thenReturn(postParams); + + // Make the request + Response response = client.makeRequest(mockRequest); + + // Verify response + assertEquals(201, response.getStatusCode()); + assertEquals("created", response.getContent()); + } + + @Test + public void testRequestWithMultipleHeaders() throws IOException { + // Mock setup for POST request + setup(201, "created", HttpMethod.POST, false); + + // Set up multiple header parameters + Map> headerParams = new HashMap<>(); + headerParams.put("X-Custom-Header", Arrays.asList("CustomValue")); + headerParams.put("Accept-Language", Arrays.asList("en-US")); + headerParams.put("Cache-Control", Arrays.asList("no-cache")); + headerParams.put("X-Request-ID", Arrays.asList("abc123")); + when(mockRequest.getHeaderParams()).thenReturn(headerParams); + + + // Make the request + Response response = client.makeRequest(mockRequest); + + // Verify response + assertEquals(201, response.getStatusCode()); + assertEquals("created", response.getContent()); + + } + } diff --git a/src/test/java/com/twilio/http/ResponseTest.java b/src/test/java/com/twilio/http/ResponseTest.java index ca9b64bc31..a3b1a3e86e 100644 --- a/src/test/java/com/twilio/http/ResponseTest.java +++ b/src/test/java/com/twilio/http/ResponseTest.java @@ -3,7 +3,7 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; -import org.mockito.runners.MockitoJUnitRunner; +import org.mockito.junit.MockitoJUnitRunner; import java.io.InputStream; diff --git a/src/test/java/com/twilio/http/TwilioRestClientTest.java b/src/test/java/com/twilio/http/TwilioRestClientTest.java index f2bdfc466d..05cbcd389b 100644 --- a/src/test/java/com/twilio/http/TwilioRestClientTest.java +++ b/src/test/java/com/twilio/http/TwilioRestClientTest.java @@ -34,7 +34,7 @@ public class TwilioRestClientTest { @Before public void setUp() throws Exception { - MockitoAnnotations.initMocks(this); + MockitoAnnotations.openMocks(this); twilioRestClient = new TwilioRestClient(new TwilioRestClient.Builder("AC123", "AUTH TOKEN").httpClient(httpClient)); } diff --git a/src/test/java/com/twilio/http/ValidationClientTest.java b/src/test/java/com/twilio/http/ValidationClientTest.java index 3415786a65..c3781ecf09 100644 --- a/src/test/java/com/twilio/http/ValidationClientTest.java +++ b/src/test/java/com/twilio/http/ValidationClientTest.java @@ -1,6 +1,10 @@ package com.twilio.http; import com.twilio.constant.EnumConstants; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; import org.junit.Test; import java.security.KeyPair; @@ -15,6 +19,10 @@ import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; +import java.io.IOException; + +import com.twilio.exception.ApiException; + public class ValidationClientTest { @Test public void testHttpGet() throws Exception { @@ -32,6 +40,18 @@ public void testHttpPut() throws Exception { exerciseHttpMethod(HttpMethod.PUT); } + @Test + public void testHttpPatch() throws Exception { + exerciseHttpMethod(HttpMethod.PATCH); + testContentType(HttpMethod.PATCH); + } + + @Test + public void testHttpDelete() throws Exception { + exerciseHttpMethod(HttpMethod.DELETE); + } + + private void exerciseHttpMethod(final HttpMethod httpMethod) throws Exception { final KeyPair keyPair = generateKeyPair(); final MockWebServer server = new MockWebServer(); @@ -78,4 +98,111 @@ private static KeyPair generateKeyPair() throws Exception { keyPairGenerator.initialize(2048); return keyPairGenerator.generateKeyPair(); } + + @Test + public void testFormUrlEncodedMultipleParameters() throws Exception { + // Set up the test environment + final KeyPair keyPair = generateKeyPair(); + final MockWebServer server = new MockWebServer(); + server.enqueue(new MockResponse().setBody("success")); + + final String path = "/resource"; + final HttpUrl url = server.url(path); + final ValidationClient client = new ValidationClient( + "AC123456789", + "CR987654321", + "signing-key-123", + keyPair.getPrivate() + ); + + // Create the request with form parameters + final Request request = new Request(HttpMethod.POST, url.url().toString()); + request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + + // Add multiple form parameters, including one with multiple values + Map> postParams = new HashMap<>(); + postParams.put("name", Arrays.asList("John Doe")); + postParams.put("email", Arrays.asList("john.doe@example.com")); + postParams.put("phone", Arrays.asList("+12125551234")); + postParams.put("tags", Arrays.asList("customer", "premium", "enterprise")); // Multiple values + postParams.put("status", Arrays.asList("active")); + + // Add the parameters to the request + for (Map.Entry> entry : postParams.entrySet()) { + for (String value : entry.getValue()) { + request.addPostParam(entry.getKey(), value); + } + } + + // Make the request + final Response response = client.makeRequest(request); + + // Verify response + assertEquals(200, response.getStatusCode()); + assertEquals("success", response.getContent()); + } + + @Test + public void testRequestWithMultipleHeaders() throws Exception { + // Set up the test environment + final KeyPair keyPair = generateKeyPair(); + final MockWebServer server = new MockWebServer(); + server.enqueue(new MockResponse().setBody("success")); + + final String path = "/resource"; + final HttpUrl url = server.url(path); + final ValidationClient client = new ValidationClient( + "AC123456789", + "CR987654321", + "signing-key-123", + keyPair.getPrivate() + ); + + // Create the request with custom headers + final Request request = new Request(HttpMethod.GET, url.url().toString()); + + // Add multiple custom headers + request.addHeaderParam("X-Custom-Header", "CustomValue"); + request.addHeaderParam("Accept-Language", "en-US"); + request.addHeaderParam("Cache-Control", "no-cache"); + + // Add a header with multiple values + request.addHeaderParam("Accept", "application/json"); + request.addHeaderParam("Accept", "application/xml"); + + // Add header with special characters + request.addHeaderParam("X-Special-Chars", "value with spaces, commas; and special chars"); + + // Make the request + final Response response = client.makeRequest(request); + + // Verify response + assertEquals(200, response.getStatusCode()); + assertEquals("success", response.getContent()); + } + + @Test(expected = ApiException.class) + public void testIOExceptionHandling() throws Exception { + // Set up a key pair for validation + final KeyPair keyPair = generateKeyPair(); + + // Create a server that will immediately close the connection + final MockWebServer server = new MockWebServer(); + + // Force the server to shut down before making the request + server.shutdown(); + + // Create a request to the closed server which will cause IOException + final HttpUrl url = server.url("/resource"); + final ValidationClient client = new ValidationClient( + "AC123456789", + "CR987654321", + "signing-key-123", + keyPair.getPrivate() + ); + final Request request = new Request(HttpMethod.GET, url.url().toString()); + + // This should throw an ApiException wrapping the IOException + client.makeRequest(request); + } } diff --git a/src/test/java/com/twilio/http/bearerToken/BearerTokenNetworkHttpClientTest.java b/src/test/java/com/twilio/http/bearerToken/BearerTokenNetworkHttpClientTest.java new file mode 100644 index 0000000000..41094c2ff6 --- /dev/null +++ b/src/test/java/com/twilio/http/bearerToken/BearerTokenNetworkHttpClientTest.java @@ -0,0 +1,213 @@ +package com.twilio.http.bearerToken; + +import com.twilio.constant.EnumConstants; +import com.twilio.exception.ApiException; +import com.twilio.http.HttpMethod; +import com.twilio.http.Response; +import com.twilio.http.bearertoken.BearerTokenNetworkHttpClient; +import com.twilio.http.bearertoken.BearerTokenRequest; +import org.apache.hc.client5.http.impl.classic.CloseableHttpClient; +import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse; +import org.apache.hc.client5.http.impl.classic.HttpClientBuilder; +import org.apache.hc.core5.http.HttpEntity; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.mockito.Spy; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.net.URL; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +public class BearerTokenNetworkHttpClientTest { + + private BearerTokenNetworkHttpClient client; + + @Mock + private BearerTokenRequest mockRequest; + + @Spy + private HttpClientBuilder mockBuilder; + + @Mock + private CloseableHttpClient mockClient; + + @Mock + private CloseableHttpResponse mockResponse; + + @Mock + private HttpEntity mockEntity; + + @Before + public void setUp() { + MockitoAnnotations.openMocks(this); + doReturn(mockClient).when(mockBuilder).build(); + client = new BearerTokenNetworkHttpClient(mockBuilder); + } + + private void setup( + final int statusCode, + final String content, + final HttpMethod method, + final Boolean requiresAuthentication + ) throws IOException { + final InputStream stream = new ByteArrayInputStream(content.getBytes("UTF-8")); + + when(mockRequest.getMethod()).thenReturn(method); + when(mockRequest.constructURL()).thenReturn(new URL("http://foo.com/hello")); + when(mockRequest.requiresAuthentication()).thenReturn(requiresAuthentication); + when(mockRequest.getAuthString()).thenReturn("Bearer token123"); + when(mockRequest.getContentType()).thenReturn(EnumConstants.ContentType.FORM_URLENCODED); + when(mockClient.execute(any())).thenReturn(mockResponse); + when(mockEntity.isRepeatable()).thenReturn(true); + when(mockEntity.getContentLength()).thenReturn(1L); + when(mockEntity.getContent()).thenReturn(stream); + when(mockResponse.getEntity()).thenReturn(mockEntity); + when(mockResponse.getCode()).thenReturn(statusCode); + } + + @Test + public void testGet() throws IOException { + setup(200, "success", HttpMethod.GET, false); + + Response resp = client.makeRequest(mockRequest); + + assertEquals(200, resp.getStatusCode()); + assertEquals("success", resp.getContent()); + } + + @Test + public void testGetWithAuthentication() throws IOException { + setup(200, "authenticated", HttpMethod.GET, true); + + Response resp = client.makeRequest(mockRequest); + + assertEquals(200, resp.getStatusCode()); + assertEquals("authenticated", resp.getContent()); + } + + @Test + public void testPost() throws IOException { + setup(201, "created", HttpMethod.POST, false); + + Response resp = client.makeRequest(mockRequest); + + assertEquals(201, resp.getStatusCode()); + assertEquals("created", resp.getContent()); + } + + @Test + public void testJsonPost() throws IOException { + setup(201, "created", HttpMethod.POST, false); + when(mockRequest.getContentType()).thenReturn(EnumConstants.ContentType.JSON); + String body = "{\"name\":\"value\"}"; + when(mockRequest.getBody()).thenReturn(body); + + Response resp = client.makeRequest(mockRequest); + + assertEquals(201, resp.getStatusCode()); + assertEquals("created", resp.getContent()); + } + + @Test + public void testFormUrlEncodedPost() throws IOException { + setup(201, "form-urlencoded", HttpMethod.POST, false); + + // Set up post parameters + Map> postParams = new HashMap<>(); + postParams.put("name", Arrays.asList("John Doe")); + postParams.put("tags", Arrays.asList("customer", "premium")); + when(mockRequest.getPostParams()).thenReturn(postParams); + + Response resp = client.makeRequest(mockRequest); + + assertEquals(201, resp.getStatusCode()); + assertEquals("form-urlencoded", resp.getContent()); + } + + @Test + public void testPut() throws IOException { + setup(200, "updated", HttpMethod.PUT, false); + + Response resp = client.makeRequest(mockRequest); + + assertEquals(200, resp.getStatusCode()); + assertEquals("updated", resp.getContent()); + } + + @Test + public void testPatch() throws IOException { + setup(200, "patched", HttpMethod.PATCH, false); + + Response resp = client.makeRequest(mockRequest); + + assertEquals(200, resp.getStatusCode()); + assertEquals("patched", resp.getContent()); + } + + @Test + public void testDelete() throws IOException { + setup(204, "", HttpMethod.DELETE, false); + + Response resp = client.makeRequest(mockRequest); + + assertEquals(204, resp.getStatusCode()); + assertEquals("", resp.getContent()); + } + + @Test + public void testWithCustomHeaders() throws IOException { + setup(200, "headers", HttpMethod.GET, false); + + Map> headers = new HashMap<>(); + headers.put("X-Custom-Header", Arrays.asList("CustomValue")); + headers.put("Accept-Language", Arrays.asList("en-US")); + when(mockRequest.getHeaderParams()).thenReturn(headers); + + Response resp = client.makeRequest(mockRequest); + + assertEquals(200, resp.getStatusCode()); + assertEquals("headers", resp.getContent()); + } + + @Test(expected = ApiException.class) + public void testIOException() throws IOException { + when(mockRequest.getMethod()).thenReturn(HttpMethod.GET); + when(mockRequest.constructURL()).thenReturn(new URL("http://foo.com/hello")); + when(mockRequest.requiresAuthentication()).thenReturn(false); + when(mockClient.execute(any())).thenThrow(new IOException("Connection error")); + + client.makeRequest(mockRequest); + } + + @Test + public void testReliableRequest() { + BearerTokenRequest request = mock(BearerTokenRequest.class); + when(request.getMethod()).thenReturn(HttpMethod.GET); + + BearerTokenNetworkHttpClient clientSpy = spy(client); + doReturn(new Response("", 204)).when(clientSpy).makeRequest(request); + + clientSpy.reliableRequest(request); + + assertNotNull(clientSpy.getLastRequest()); + assertNotNull(clientSpy.getLastResponse()); + } +} diff --git a/src/test/java/com/twilio/http/noauth/NoAuthNetworkHttpClientTest.java b/src/test/java/com/twilio/http/noauth/NoAuthNetworkHttpClientTest.java new file mode 100644 index 0000000000..5007a8cb31 --- /dev/null +++ b/src/test/java/com/twilio/http/noauth/NoAuthNetworkHttpClientTest.java @@ -0,0 +1,162 @@ +package com.twilio.http.noauth; + +import com.twilio.constant.EnumConstants; +import com.twilio.exception.ApiException; +import com.twilio.http.HttpMethod; +import com.twilio.http.Response; +import org.apache.hc.client5.http.config.RequestConfig; +import org.apache.hc.client5.http.impl.classic.CloseableHttpClient; +import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse; +import org.apache.hc.client5.http.impl.classic.HttpClientBuilder; +import org.apache.hc.core5.http.HttpEntity; +import org.apache.hc.core5.http.io.SocketConfig; +import org.apache.hc.core5.util.Timeout; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.mockito.Spy; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.net.URL; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +public class NoAuthNetworkHttpClientTest { + + private NoAuthNetworkHttpClient client; + + @Mock + private NoAuthRequest mockRequest; + + @Spy + private HttpClientBuilder mockBuilder; + + @Mock + private CloseableHttpClient mockClient; + + @Mock + private CloseableHttpResponse mockResponse; + + @Mock + private HttpEntity mockEntity; + + @Before + public void setUp() { + MockitoAnnotations.openMocks(this); + doReturn(mockClient).when(mockBuilder).build(); + client = new NoAuthNetworkHttpClient(); + } + + private void setup( + final int statusCode, + final String content, + final HttpMethod method + ) throws IOException { + final InputStream stream = new ByteArrayInputStream(content.getBytes("UTF-8")); + + when(mockRequest.getMethod()).thenReturn(method); + when(mockRequest.constructURL()).thenReturn(new URL("http://foo.com/hello")); + when(mockRequest.getContentType()).thenReturn(EnumConstants.ContentType.FORM_URLENCODED); + when(mockClient.execute(any())).thenReturn(mockResponse); + when(mockEntity.isRepeatable()).thenReturn(true); + when(mockEntity.getContentLength()).thenReturn(1L); + when(mockEntity.getContent()).thenReturn(stream); + when(mockResponse.getEntity()).thenReturn(mockEntity); + when(mockResponse.getCode()).thenReturn(statusCode); + } + + + @Test + public void testReliableRequest() { + NoAuthRequest request = mock(NoAuthRequest.class); + when(request.getMethod()).thenReturn(HttpMethod.GET); + + NoAuthNetworkHttpClient clientSpy = spy(client); + doReturn(new Response("", 204)).when(clientSpy).makeRequest(request); + + clientSpy.reliableRequest(request); + + assertNotNull(clientSpy.getLastRequest()); + assertNotNull(clientSpy.getLastResponse()); + } + + @Test + public void testShouldRetry() { + Response resp = new Response("error", 500); + boolean shouldRetry = client.shouldRetry(resp, new int[]{500}); + assertEquals(true, shouldRetry); + + resp = new Response("success", 200); + shouldRetry = client.shouldRetry(resp, new int[]{500}); + assertEquals(false, shouldRetry); + + shouldRetry = client.shouldRetry(null, new int[]{500}); + assertEquals(true, shouldRetry); + } + + @Test + public void testDefaultConstructor() throws IOException { + // Create client using default constructor + NoAuthNetworkHttpClient defaultClient = new NoAuthNetworkHttpClient(); + + // Setup mock NoAuthRequest + NoAuthRequest request = mock(NoAuthRequest.class); + when(request.getMethod()).thenReturn(HttpMethod.GET); + when(request.constructURL()).thenReturn(new URL("http://example.com")); + when(request.getHeaderParams()).thenReturn(new HashMap<>()); + + // This test verifies that the default constructor creates a functional client + // We can't directly test the internals, but we can verify the client was constructed + // without exceptions and has the expected type + assertNotNull(defaultClient); + assertEquals(NoAuthNetworkHttpClient.class, defaultClient.getClass()); + } + + @Test + public void testRequestConfigConstructor() { + // Create a custom RequestConfig + RequestConfig customConfig = RequestConfig.custom() + .setConnectTimeout(Timeout.ofMilliseconds(5000)) + .build(); + + // Create client with custom RequestConfig + NoAuthNetworkHttpClient configClient = new NoAuthNetworkHttpClient(customConfig); + + // Verify client was created successfully + assertNotNull(configClient); + assertEquals(NoAuthNetworkHttpClient.class, configClient.getClass()); + } + + @Test + public void testRequestAndSocketConfigConstructor() { + // Create custom configs + RequestConfig customRequestConfig = RequestConfig.custom() + .setConnectTimeout(Timeout.ofMilliseconds(5000)) + .build(); + + SocketConfig customSocketConfig = SocketConfig.custom() + .setSoTimeout(Timeout.ofMilliseconds(5000)) + .build(); + + // Create client with both custom configs + NoAuthNetworkHttpClient fullConfigClient = new NoAuthNetworkHttpClient(customRequestConfig, customSocketConfig); + + // Verify client was created successfully + assertNotNull(fullConfigClient); + assertEquals(NoAuthNetworkHttpClient.class, fullConfigClient.getClass()); + } +} diff --git a/src/test/java/com/twilio/jwt/validation/RequestCanonicalizerTest.java b/src/test/java/com/twilio/jwt/validation/RequestCanonicalizerTest.java index 0042b32709..c484b9a795 100644 --- a/src/test/java/com/twilio/jwt/validation/RequestCanonicalizerTest.java +++ b/src/test/java/com/twilio/jwt/validation/RequestCanonicalizerTest.java @@ -1,8 +1,8 @@ package com.twilio.jwt.validation; import com.twilio.exception.InvalidRequestException; -import org.apache.http.Header; -import org.apache.http.message.BasicHeader; +import org.apache.hc.core5.http.Header; +import org.apache.hc.core5.http.message.BasicHeader; import org.junit.Assert; import org.junit.Before; import org.junit.Test; diff --git a/src/test/java/com/twilio/jwt/validation/ValidationTokenTest.java b/src/test/java/com/twilio/jwt/validation/ValidationTokenTest.java index fc312b256d..1cd4c29bd4 100644 --- a/src/test/java/com/twilio/jwt/validation/ValidationTokenTest.java +++ b/src/test/java/com/twilio/jwt/validation/ValidationTokenTest.java @@ -6,12 +6,15 @@ import io.jsonwebtoken.Claims; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; -import io.jsonwebtoken.security.InvalidKeyException; -import io.jsonwebtoken.security.Keys; -import org.apache.http.*; -import org.apache.http.client.protocol.HttpClientContext; -import org.apache.http.message.BasicHeader; -import org.apache.http.message.BasicHttpRequest; +import org.apache.hc.client5.http.classic.methods.HttpPost; +import org.apache.hc.client5.http.protocol.HttpClientContext; +import org.apache.hc.core5.http.Header; +import org.apache.hc.core5.http.HttpEntity; +import org.apache.hc.core5.http.HttpRequest; +import org.apache.hc.core5.http.message.BasicHeader; +import org.apache.hc.core5.http.message.BasicHttpRequest; +import org.apache.hc.core5.http.message.RequestLine; +import org.apache.hc.core5.net.URIAuthority; import org.junit.Assert; import org.junit.Before; import org.junit.Test; @@ -59,14 +62,14 @@ public class ValidationTokenTest { private RequestLine requestLine; @Mock - private HttpEntityEnclosingRequest requestWithEntity; + private HttpPost requestWithEntity; @Mock private HttpEntity entity; @Before public void setup() throws Exception { - MockitoAnnotations.initMocks(this); + MockitoAnnotations.openMocks(this); headers = new Header[2]; headers[0] = new BasicHeader("host", "api.twilio.com"); headers[1] = new BasicHeader("authorization", "foobar"); @@ -146,10 +149,10 @@ public void testTokenInvalidAlgorithms() throws IOException { @Test public void testTokenFromHttpRequest() throws IOException { - when(request.getRequestLine()).thenReturn(requestLine); when(requestLine.getMethod()).thenReturn("POST"); when(requestLine.getUri()).thenReturn("/Messages?PageSize=5&Limit=10"); - when(request.getAllHeaders()).thenReturn(headers); + when(request.getHeaders()).thenReturn(headers); + when(request.getRequestUri()).thenReturn("/Messages?PageSize=5&Limit=10"); Jwt jwt = ValidationToken.fromHttpRequest(ACCOUNT_SID, CREDENTIAL_SID, SIGNING_KEY_SID, privateKey, request, SIGNED_HEADERS); @@ -157,35 +160,35 @@ public void testTokenFromHttpRequest() throws IOException { this.validateToken(claims); Assert.assertEquals("authorization;host", claims.get("hrh")); - Assert.assertEquals("712fbbec9dcb4fe58ed8caecf925d2fe10889f5d3f4b48e748157a4a1113697d", claims.get("rqh")); + Assert.assertEquals("96d94b3c5b14c8f0e04a708332006c68c5b0c2c6cc25db5d0fb3d017cdf7f4ff", claims.get("rqh")); } @Test public void testTokenFromEntityRequest() throws IOException { - when(requestWithEntity.getRequestLine()).thenReturn(requestLine); - when(requestWithEntity.getAllHeaders()).thenReturn(headers); + when(requestWithEntity.getHeaders()).thenReturn(headers); when(requestWithEntity.getEntity()).thenReturn(entity); when(entity.getContent()).thenReturn( new ByteArrayInputStream("testbody".getBytes(StandardCharsets.UTF_8))); when(requestLine.getMethod()).thenReturn("POST"); when(requestLine.getUri()).thenReturn("/Messages"); + when(requestWithEntity.getRequestUri()).thenReturn("/Messages?PageSize=5&Limit=10"); Jwt jwt = ValidationToken.fromHttpRequest(ACCOUNT_SID, CREDENTIAL_SID, SIGNING_KEY_SID, privateKey, requestWithEntity, SIGNED_HEADERS); Claims claims = getClaimFromJwtToken(jwt); this.validateToken(claims); Assert.assertEquals("authorization;host", claims.get("hrh")); - Assert.assertEquals("bd792c967c20d546c738b94068f5f72758a10d26c12979677501e1eefe58c65a", claims.get("rqh")); + Assert.assertEquals("9871e786e0c77406cc78090b694593c3479a9215890c42981b4f8d5923d9511b", claims.get("rqh")); } @Test public void testTokenFromHttpRequestWithHostPort() throws IOException { headers[0] = new BasicHeader("host", "api.twilio.com:443"); - when(request.getRequestLine()).thenReturn(requestLine); when(requestLine.getMethod()).thenReturn("GET"); when(requestLine.getUri()).thenReturn("/Messages?PageSize=5&Limit=10"); - when(request.getAllHeaders()).thenReturn(headers); + when(request.getHeaders()).thenReturn(headers); + when(request.getRequestUri()).thenReturn("/Messages?PageSize=5&Limit=10"); Jwt jwt = ValidationToken.fromHttpRequest(ACCOUNT_SID, CREDENTIAL_SID, SIGNING_KEY_SID, privateKey, request, SIGNED_HEADERS); Claims claims = getClaimFromJwtToken(jwt); @@ -193,7 +196,7 @@ public void testTokenFromHttpRequestWithHostPort() throws IOException { this.validateToken(claims); Assert.assertEquals("authorization;host", claims.get("hrh")); - Assert.assertEquals("4b3d2666845a38f00259a5231a08765bb2d12564bc4469fd5b2816204c588967", claims.get("rqh")); + Assert.assertEquals("96d94b3c5b14c8f0e04a708332006c68c5b0c2c6cc25db5d0fb3d017cdf7f4ff", claims.get("rqh")); } @Test @@ -208,7 +211,7 @@ public void testMultithreadedValidations() throws InterruptedException, Executio futures.add(service.submit(new Runnable() { public void run() { try { - i.process(getBasicRequest(), new HttpClientContext()); + i.process(getBasicRequest(), null, new HttpClientContext()); } catch (Exception e) { e.printStackTrace(); Assert.fail(e.getMessage()); @@ -226,7 +229,8 @@ private BasicHttpRequest getBasicRequest() { return new BasicHttpRequest( "GET", "/some-url?with=params", - new ProtocolVersion("HTTP", 1, 1) + new URIAuthority("api.twilio.com:443"), + "" ); } diff --git a/src/test/java/com/twilio/security/RequestValidatorTest.java b/src/test/java/com/twilio/security/RequestValidatorTest.java index a97418277c..d44712178c 100644 --- a/src/test/java/com/twilio/security/RequestValidatorTest.java +++ b/src/test/java/com/twilio/security/RequestValidatorTest.java @@ -101,10 +101,10 @@ public void testValidateRemovesPortHttp() { public void testValidateAddsPortHttps() { String expectedSignature = "kvajT1Ptam85bY51eRf/AJRuM3w="; // hash of https uri with port 443 boolean isValid = validator.validate(url, params, expectedSignature); - + Assert.assertTrue("Validator did not add port 443 to https url", isValid); } - + @Test public void testValidateAddsPortHttp() { String url = this.url.replace("https", "http"); From 468bbb744d51bb97e888314ca0084a308cf2dc0d Mon Sep 17 00:00:00 2001 From: sbansla <104902068+sbansla@users.noreply.github.com> Date: Fri, 12 Sep 2025 13:19:31 +0530 Subject: [PATCH 19/32] chore: custom deserialisation (#895) * custom deserialization added * added tests for deserialization --- .../twilio/converter/ISO8601Deserializer.java | 17 ++++ .../converter/LocalDateDeserializer.java | 17 ++++ .../twilio/converter/RFC2822Deserializer.java | 17 ++++ .../ZonedDateTimeListDeserializer.java | 28 ++++++ .../converter/ISO8601DeserializerTest.java | 65 ++++++++++++++ .../converter/LocalDateDeserializerTest.java | 71 +++++++++++++++ .../converter/RFC2822DeserializerTest.java | 71 +++++++++++++++ .../ZonedDateTimeListDeserializerTest.java | 90 +++++++++++++++++++ 8 files changed, 376 insertions(+) create mode 100644 src/main/java/com/twilio/converter/ISO8601Deserializer.java create mode 100644 src/main/java/com/twilio/converter/LocalDateDeserializer.java create mode 100644 src/main/java/com/twilio/converter/RFC2822Deserializer.java create mode 100644 src/main/java/com/twilio/converter/ZonedDateTimeListDeserializer.java create mode 100644 src/test/java/com/twilio/converter/ISO8601DeserializerTest.java create mode 100644 src/test/java/com/twilio/converter/LocalDateDeserializerTest.java create mode 100644 src/test/java/com/twilio/converter/RFC2822DeserializerTest.java create mode 100644 src/test/java/com/twilio/converter/ZonedDateTimeListDeserializerTest.java diff --git a/src/main/java/com/twilio/converter/ISO8601Deserializer.java b/src/main/java/com/twilio/converter/ISO8601Deserializer.java new file mode 100644 index 0000000000..a867287b63 --- /dev/null +++ b/src/main/java/com/twilio/converter/ISO8601Deserializer.java @@ -0,0 +1,17 @@ +package com.twilio.converter; + +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.databind.DeserializationContext; +import com.fasterxml.jackson.databind.JsonDeserializer; + +import java.io.IOException; +import java.time.ZonedDateTime; + +// open-api spec "format: date-time" +public class ISO8601Deserializer extends JsonDeserializer { + @Override + public ZonedDateTime deserialize(JsonParser parser, DeserializationContext context) throws IOException { + String dateString = parser.getText(); + return DateConverter.iso8601DateTimeFromString(dateString); + } +} \ No newline at end of file diff --git a/src/main/java/com/twilio/converter/LocalDateDeserializer.java b/src/main/java/com/twilio/converter/LocalDateDeserializer.java new file mode 100644 index 0000000000..a8a2260a4d --- /dev/null +++ b/src/main/java/com/twilio/converter/LocalDateDeserializer.java @@ -0,0 +1,17 @@ +package com.twilio.converter; + +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.databind.DeserializationContext; +import com.fasterxml.jackson.databind.JsonDeserializer; + +import java.io.IOException; +import java.time.LocalDate; + +// open-api spec "format: date" +public class LocalDateDeserializer extends JsonDeserializer { + @Override + public LocalDate deserialize(JsonParser parser, DeserializationContext context) throws IOException { + String dateString = parser.getText(); + return DateConverter.localDateFromString(dateString); + } +} \ No newline at end of file diff --git a/src/main/java/com/twilio/converter/RFC2822Deserializer.java b/src/main/java/com/twilio/converter/RFC2822Deserializer.java new file mode 100644 index 0000000000..56eb3e891d --- /dev/null +++ b/src/main/java/com/twilio/converter/RFC2822Deserializer.java @@ -0,0 +1,17 @@ +package com.twilio.converter; + +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.databind.DeserializationContext; +import com.fasterxml.jackson.databind.JsonDeserializer; + +import java.io.IOException; +import java.time.ZonedDateTime; + +// open-api spec "format: date-time-rfc-2822" +public class RFC2822Deserializer extends JsonDeserializer { + @Override + public ZonedDateTime deserialize(JsonParser parser, DeserializationContext context) throws IOException { + String dateString = parser.getText(); + return DateConverter.rfc2822DateTimeFromString(dateString); + } +} \ No newline at end of file diff --git a/src/main/java/com/twilio/converter/ZonedDateTimeListDeserializer.java b/src/main/java/com/twilio/converter/ZonedDateTimeListDeserializer.java new file mode 100644 index 0000000000..2d98994219 --- /dev/null +++ b/src/main/java/com/twilio/converter/ZonedDateTimeListDeserializer.java @@ -0,0 +1,28 @@ +package com.twilio.converter; + +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.DeserializationContext; +import com.fasterxml.jackson.databind.JsonDeserializer; + +import java.io.IOException; +import java.time.ZonedDateTime; +import java.util.ArrayList; +import java.util.List; + +public class ZonedDateTimeListDeserializer extends JsonDeserializer> { + + @Override + public List deserialize(JsonParser parser, DeserializationContext context) throws IOException { + List dateStrings = parser.readValueAs(new TypeReference>() { + }); + List dates = new ArrayList<>(); + for (String dateString : dateStrings) { + ZonedDateTime date = DateConverter.rfc2822DateTimeFromString(dateString); + if (date != null) { + dates.add(date); + } + } + return dates; + } +} \ No newline at end of file diff --git a/src/test/java/com/twilio/converter/ISO8601DeserializerTest.java b/src/test/java/com/twilio/converter/ISO8601DeserializerTest.java new file mode 100644 index 0000000000..4051e0c195 --- /dev/null +++ b/src/test/java/com/twilio/converter/ISO8601DeserializerTest.java @@ -0,0 +1,65 @@ +package com.twilio.converter; + +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.databind.DeserializationContext; +import org.junit.Assert; +import org.junit.Test; +import org.mockito.Mockito; + +import java.io.IOException; +import java.time.ZonedDateTime; + +public class ISO8601DeserializerTest { + + @Test + public void testDeserializeValidDateTime() throws IOException { + // Arrange + String validDateTime = "2023-10-01T12:34:56Z"; + ZonedDateTime expectedDateTime = ZonedDateTime.parse(validDateTime); + + JsonParser mockParser = Mockito.mock(JsonParser.class); + DeserializationContext mockContext = Mockito.mock(DeserializationContext.class); + + Mockito.when(mockParser.getText()).thenReturn(validDateTime); + + ISO8601Deserializer deserializer = new ISO8601Deserializer(); + + // Act + ZonedDateTime result = deserializer.deserialize(mockParser, mockContext); + + // Assert + Assert.assertEquals(expectedDateTime, result); + } + + @Test + public void testDeserializeInvalidDateTime() throws IOException { + // Arrange + String invalidDateTime = "invalid-date-time"; + JsonParser mockParser = Mockito.mock(JsonParser.class); + DeserializationContext mockContext = Mockito.mock(DeserializationContext.class); + Mockito.when(mockParser.getText()).thenReturn(invalidDateTime); + ISO8601Deserializer deserializer = new ISO8601Deserializer(); + + // Act + ZonedDateTime result = deserializer.deserialize(mockParser, mockContext); + + // Assert + Assert.assertNull(result); + } + + @Test + public void testDeserializeNullDateTime() throws IOException { + // Arrange + String invalidDateTime = null; + JsonParser mockParser = Mockito.mock(JsonParser.class); + DeserializationContext mockContext = Mockito.mock(DeserializationContext.class); + Mockito.when(mockParser.getText()).thenReturn(invalidDateTime); + ISO8601Deserializer deserializer = new ISO8601Deserializer(); + + // Act + ZonedDateTime result = deserializer.deserialize(mockParser, mockContext); + + // Assert + Assert.assertNull(result); + } +} \ No newline at end of file diff --git a/src/test/java/com/twilio/converter/LocalDateDeserializerTest.java b/src/test/java/com/twilio/converter/LocalDateDeserializerTest.java new file mode 100644 index 0000000000..e290550ec3 --- /dev/null +++ b/src/test/java/com/twilio/converter/LocalDateDeserializerTest.java @@ -0,0 +1,71 @@ +package com.twilio.converter; + +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.databind.DeserializationContext; +import org.junit.Assert; +import org.junit.Test; +import org.mockito.Mockito; + +import java.io.IOException; +import java.time.LocalDate; + +public class LocalDateDeserializerTest { + + @Test + public void testDeserializeValidDate() throws IOException { + // Arrange + String validDate = "2023-10-01"; + LocalDate expectedDate = LocalDate.parse(validDate); + + JsonParser mockParser = Mockito.mock(JsonParser.class); + DeserializationContext mockContext = Mockito.mock(DeserializationContext.class); + + Mockito.when(mockParser.getText()).thenReturn(validDate); + + LocalDateDeserializer deserializer = new LocalDateDeserializer(); + + // Act + LocalDate result = deserializer.deserialize(mockParser, mockContext); + + // Assert + Assert.assertEquals(expectedDate, result); + } + + @Test + public void testDeserializeInvalidDate() throws IOException { + // Arrange + String invalidDate = "invalid-date"; + + JsonParser mockParser = Mockito.mock(JsonParser.class); + DeserializationContext mockContext = Mockito.mock(DeserializationContext.class); + + Mockito.when(mockParser.getText()).thenReturn(invalidDate); + + LocalDateDeserializer deserializer = new LocalDateDeserializer(); + + // Act + LocalDate result = deserializer.deserialize(mockParser, mockContext); + + // Assert + Assert.assertNull(result); + } + + @Test + public void testDeserializeEmptyDate() throws IOException { + // Arrange + String emptyDate = ""; + + JsonParser mockParser = Mockito.mock(JsonParser.class); + DeserializationContext mockContext = Mockito.mock(DeserializationContext.class); + + Mockito.when(mockParser.getText()).thenReturn(emptyDate); + + LocalDateDeserializer deserializer = new LocalDateDeserializer(); + + // Act + LocalDate result = deserializer.deserialize(mockParser, mockContext); + + // Assert + Assert.assertNull(result); + } +} \ No newline at end of file diff --git a/src/test/java/com/twilio/converter/RFC2822DeserializerTest.java b/src/test/java/com/twilio/converter/RFC2822DeserializerTest.java new file mode 100644 index 0000000000..dacee0cac1 --- /dev/null +++ b/src/test/java/com/twilio/converter/RFC2822DeserializerTest.java @@ -0,0 +1,71 @@ +package com.twilio.converter; + +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.databind.DeserializationContext; +import org.junit.Assert; +import org.junit.Test; +import org.mockito.Mockito; + +import java.io.IOException; +import java.time.ZonedDateTime; + +public class RFC2822DeserializerTest { + + @Test + public void testDeserializeValidDateTime() throws IOException { + // Arrange + String validDateTime = "Wed, 23 Jul 2025 06:18:51 +0000"; + ZonedDateTime expectedDateTime = DateConverter.rfc2822DateTimeFromString(validDateTime); + + JsonParser mockParser = Mockito.mock(JsonParser.class); + DeserializationContext mockContext = Mockito.mock(DeserializationContext.class); + + Mockito.when(mockParser.getText()).thenReturn(validDateTime); + + RFC2822Deserializer deserializer = new RFC2822Deserializer(); + + // Act + ZonedDateTime result = deserializer.deserialize(mockParser, mockContext); + + // Assert + Assert.assertEquals(expectedDateTime, result); + } + + @Test + public void testDeserializeInvalidDateTime() throws IOException { + // Arrange + String invalidDateTime = "invalid-date-time"; + + JsonParser mockParser = Mockito.mock(JsonParser.class); + DeserializationContext mockContext = Mockito.mock(DeserializationContext.class); + + Mockito.when(mockParser.getText()).thenReturn(invalidDateTime); + + RFC2822Deserializer deserializer = new RFC2822Deserializer(); + + // Act + ZonedDateTime result = deserializer.deserialize(mockParser, mockContext); + + // Assert + Assert.assertNull(result); + } + + @Test + public void testDeserializeEmptyDateTime() throws IOException { + // Arrange + String emptyDateTime = ""; + + JsonParser mockParser = Mockito.mock(JsonParser.class); + DeserializationContext mockContext = Mockito.mock(DeserializationContext.class); + + Mockito.when(mockParser.getText()).thenReturn(emptyDateTime); + + RFC2822Deserializer deserializer = new RFC2822Deserializer(); + + // Act + ZonedDateTime result = deserializer.deserialize(mockParser, mockContext); + + // Assert + Assert.assertNull(result); + } +} \ No newline at end of file diff --git a/src/test/java/com/twilio/converter/ZonedDateTimeListDeserializerTest.java b/src/test/java/com/twilio/converter/ZonedDateTimeListDeserializerTest.java new file mode 100644 index 0000000000..186bc51948 --- /dev/null +++ b/src/test/java/com/twilio/converter/ZonedDateTimeListDeserializerTest.java @@ -0,0 +1,90 @@ +package com.twilio.converter; + +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.DeserializationContext; +import org.junit.Assert; +import org.junit.Test; +import org.mockito.Mockito; + +import java.io.IOException; +import java.time.ZonedDateTime; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +public class ZonedDateTimeListDeserializerTest { + + @Test + public void testDeserializeValidDateTimeList() throws IOException { + // Arrange + List validDateTimes = Arrays.asList( + "Tue, 03 Oct 2023 14:28:00 +0000", + "Wed, 04 Oct 2023 10:15:30 +0000" + ); + List expectedDates = Arrays.asList( + DateConverter.rfc2822DateTimeFromString(validDateTimes.get(0)), + DateConverter.rfc2822DateTimeFromString(validDateTimes.get(1)) + ); + + JsonParser mockParser = Mockito.mock(JsonParser.class); + DeserializationContext mockContext = Mockito.mock(DeserializationContext.class); + + Mockito.when(mockParser.readValueAs(Mockito.>>any())) + .thenReturn(validDateTimes); + + ZonedDateTimeListDeserializer deserializer = new ZonedDateTimeListDeserializer(); + + // Act + List result = deserializer.deserialize(mockParser, mockContext); + + // Assert + Assert.assertEquals(expectedDates, result); + } + + @Test + public void testDeserializeInvalidDateTimeList() throws IOException { + // Arrange + List mixedDateTimes = Arrays.asList( + "Tue, 03 Oct 2023 14:28:00 +0000", + "invalid-date-time" + ); + List expectedDates = Collections.singletonList( + DateConverter.rfc2822DateTimeFromString(mixedDateTimes.get(0)) + ); + + JsonParser mockParser = Mockito.mock(JsonParser.class); + DeserializationContext mockContext = Mockito.mock(DeserializationContext.class); + + Mockito.when(mockParser.readValueAs(Mockito.>>any())) + .thenReturn(mixedDateTimes); + + ZonedDateTimeListDeserializer deserializer = new ZonedDateTimeListDeserializer(); + + // Act + List result = deserializer.deserialize(mockParser, mockContext); + + // Assert + Assert.assertEquals(expectedDates, result); + } + + @Test + public void testDeserializeEmptyDateTimeList() throws IOException { + // Arrange + List emptyDateTimes = Collections.emptyList(); + + JsonParser mockParser = Mockito.mock(JsonParser.class); + DeserializationContext mockContext = Mockito.mock(DeserializationContext.class); + + Mockito.when(mockParser.readValueAs(Mockito.>>any())) + .thenReturn(emptyDateTimes); + + ZonedDateTimeListDeserializer deserializer = new ZonedDateTimeListDeserializer(); + + // Act + List result = deserializer.deserialize(mockParser, mockContext); + + // Assert + Assert.assertTrue(result.isEmpty()); + } +} \ No newline at end of file From f0aa2cbc1562fdcb028d504667f37be648ba45e5 Mon Sep 17 00:00:00 2001 From: sbansla <104902068+sbansla@users.noreply.github.com> Date: Tue, 16 Sep 2025 20:59:40 +0530 Subject: [PATCH 20/32] fix: Reuse twiliorestclient for orgs api (#896) orgs api can be used just like other apis, removed orgs api rest client and related files. --- README.md | 4 +- examples/BearerTokenAuthentication.md | 26 -- examples/FetchMessageUsingOAuth.md | 21 -- examples/OrgsAPIExample.md | 34 +++ examples/PublicOAuthExample.md | 35 +++ .../java/com/twilio/TwilioOrgsTokenAuth.java | 106 ------- src/main/java/com/twilio/base/Page.java | 6 +- .../com/twilio/base/bearertoken/Creator.java | 50 ---- .../com/twilio/base/bearertoken/Deleter.java | 51 ---- .../com/twilio/base/bearertoken/Fetcher.java | 50 ---- .../com/twilio/base/bearertoken/Page.java | 270 ------------------ .../com/twilio/base/bearertoken/Reader.java | 156 ---------- .../com/twilio/base/bearertoken/Resource.java | 9 - .../twilio/base/bearertoken/ResourceSet.java | 138 --------- .../com/twilio/base/bearertoken/Updater.java | 50 ---- .../orgs/OrgsClientCredentialProvider.java | 62 +++- .../com/twilio/http/NetworkHttpClient.java | 2 +- .../bearertoken/BearerTokenHttpClient.java | 108 ------- .../BearerTokenNetworkHttpClient.java | 181 ------------ .../http/bearertoken/BearerTokenRequest.java | 38 --- .../BearerTokenTwilioRestClient.java | 186 ------------ .../previewiam/organizations/Account.java | 2 +- .../organizations/AccountFetcher.java | 12 +- .../organizations/AccountReader.java | 36 +-- .../organizations/RoleAssignment.java | 2 +- .../organizations/RoleAssignmentCreator.java | 16 +- .../organizations/RoleAssignmentDeleter.java | 12 +- .../organizations/RoleAssignmentReader.java | 36 +-- .../rest/previewiam/organizations/User.java | 2 +- .../previewiam/organizations/UserCreator.java | 16 +- .../previewiam/organizations/UserDeleter.java | 12 +- .../previewiam/organizations/UserFetcher.java | 12 +- .../previewiam/organizations/UserReader.java | 36 +-- .../previewiam/organizations/UserUpdater.java | 18 +- src/test/java/com/twilio/ClusterTest.java | 21 +- .../BearerTokenNetworkHttpClientTest.java | 213 -------------- 36 files changed, 257 insertions(+), 1772 deletions(-) delete mode 100644 examples/BearerTokenAuthentication.md delete mode 100644 examples/FetchMessageUsingOAuth.md create mode 100644 examples/OrgsAPIExample.md create mode 100644 examples/PublicOAuthExample.md delete mode 100644 src/main/java/com/twilio/TwilioOrgsTokenAuth.java delete mode 100644 src/main/java/com/twilio/base/bearertoken/Creator.java delete mode 100644 src/main/java/com/twilio/base/bearertoken/Deleter.java delete mode 100644 src/main/java/com/twilio/base/bearertoken/Fetcher.java delete mode 100644 src/main/java/com/twilio/base/bearertoken/Page.java delete mode 100644 src/main/java/com/twilio/base/bearertoken/Reader.java delete mode 100644 src/main/java/com/twilio/base/bearertoken/Resource.java delete mode 100644 src/main/java/com/twilio/base/bearertoken/ResourceSet.java delete mode 100644 src/main/java/com/twilio/base/bearertoken/Updater.java delete mode 100644 src/main/java/com/twilio/http/bearertoken/BearerTokenHttpClient.java delete mode 100644 src/main/java/com/twilio/http/bearertoken/BearerTokenNetworkHttpClient.java delete mode 100644 src/main/java/com/twilio/http/bearertoken/BearerTokenRequest.java delete mode 100644 src/main/java/com/twilio/http/bearertoken/BearerTokenTwilioRestClient.java delete mode 100644 src/test/java/com/twilio/http/bearerToken/BearerTokenNetworkHttpClientTest.java diff --git a/README.md b/README.md index c63cb6461a..c715b3a2fb 100644 --- a/README.md +++ b/README.md @@ -221,8 +221,8 @@ public class Example { We are introducing Client Credentials Flow-based OAuth 2.0 authentication. This feature is currently in `beta` and its implementation is subject to change. -- API examples [here](https://github.com/twilio/twilio-java/blob/main/examples/FetchMessageUsingOAuth.md) -- Organisation API examples [here](https://github.com/twilio/twilio-java/blob/main/examples/BearerTokenAuthentication.md) +- API examples [here](https://github.com/twilio/twilio-java/blob/main/examples/PublicOAuthExample.md) +- Organisation API examples [here](https://github.com/twilio/twilio-java/blob/main/examples/OrgsAPIExample.md) ### Iterate through records diff --git a/examples/BearerTokenAuthentication.md b/examples/BearerTokenAuthentication.md deleted file mode 100644 index 2618436b32..0000000000 --- a/examples/BearerTokenAuthentication.md +++ /dev/null @@ -1,26 +0,0 @@ - class BearerTokenAuthenticationExamples { - public static void main { - - private static final String GRANT_TYPE = "grant_type_to_be_used"; - private static final String CLIENT_SID = - "client_id_of_the_organization"; - private static final String CLIENT_SECRET = "client_secret_of_organization"; - private static final String ORGANISATION_ID = "id_of_the_organization"; - - //Getting access token - Method #1 - TwilioOrgsTokenAuth.init(GRANT_TYPE, CLIENT_ID, CLIENT_SECRET); - - //Getting access token - Method #2 - //To provide custom token manager implementation - //Need not call init method if customer token manager is passed - //TwilioOrgsTokenAuth.setTokenManager(new CustomTokenManagerImpl(GRANT_TYPE, CLIENT_ID, CLIENT_SECRET)); - - fetchAccountDetails(); - } - - private static void fetchAccountDetails() { - ResourceSet accountSet = Account.reader(ORGANISATION_ID).read(); - String accountSid = accountSet.iterator().next().getAccountSid(); - System.out.println(accountSid); - } - } \ No newline at end of file diff --git a/examples/FetchMessageUsingOAuth.md b/examples/FetchMessageUsingOAuth.md deleted file mode 100644 index ec667f1ab0..0000000000 --- a/examples/FetchMessageUsingOAuth.md +++ /dev/null @@ -1,21 +0,0 @@ -``` -import com.twilio.Twilio; -import com.twilio.credential.ClientCredentialProvider; -import com.twilio.rest.api.v2010.account.Message; - -public class FetchMessageUsingOAuth { - public static void main(String[] args) { - String clientId = "YOUR_CLIENT_ID"; - String clientSecret = "YOUR_CLIENT_SECRET"; - String accountSid = "YOUR_ACCOUNT_SID"; - Twilio.init(new ClientCredentialProvider(clientId, clientSecret), accountSid); - /* - Or use the following if accountSid is not required as a path parameter for an API or when setting accountSid in the API. - Twilio.init(new ClientCredentialProvider(clientId, clientSecret)); - */ - String messageSid = "YOUR_MESSAGE_SID"; - Message message = Message.fetcher(messageSid).fetch(); - } -} -``` - diff --git a/examples/OrgsAPIExample.md b/examples/OrgsAPIExample.md new file mode 100644 index 0000000000..b4511f88bc --- /dev/null +++ b/examples/OrgsAPIExample.md @@ -0,0 +1,34 @@ + class OrgsAPIExample { + public static void main { + + private static final String GRANT_TYPE = "grant_type_to_be_used"; + private static final String CLIENT_SID = + "client_id_of_the_organization"; + private static final String CLIENT_SECRET = "client_secret_of_organization"; + private static final String ORGANISATION_ID = "id_of_the_organization"; + + //Getting access token - Method #1 + Twilio.init(new OrgsClientCredentialProvider(CLIENT_SID, CLIENT_SECRET)); + fetchAccountDetails(); + + + //Scenario: 2 If in case one doesn't want to change the existing stored credential + // Pass Custom TwilioRestClient + // TokenManager tokenManager = new OrgsTokenManager(GRANT_TYPE, CLIENT_SID, CLIENT_SECRET); + // TokenAuthStrategy tokenAuthStrategy = new TokenAuthStrategy(tokenManager); + // TwilioRestClient client = new TwilioRestClient.Builder(tokenAuthStrategy).build(); + // fetchAccountDetailsWithClient(client); + } + + private static void fetchAccountDetails() { + ResourceSet accountSet = Account.reader(ORGANISATION_ID).read(); + String accountSid = accountSet.iterator().next().getAccountSid(); + System.out.println(accountSid); + } + + private static void fetchAccountDetailsWithClient(TwilioRestClient client) { + ResourceSet accountSet = Account.reader(ORGANISATION_ID).read(client); + String accountSid = accountSet.iterator().next().getAccountSid(); + System.out.println(accountSid); + } + } \ No newline at end of file diff --git a/examples/PublicOAuthExample.md b/examples/PublicOAuthExample.md new file mode 100644 index 0000000000..dce5027e9a --- /dev/null +++ b/examples/PublicOAuthExample.md @@ -0,0 +1,35 @@ +``` +class PublicOAuthExample { + public static void main { + + private static final String GRANT_TYPE = "grant_type_to_be_used"; + private static final String OAUTH_CLIENT_SID = "client_id"; + private static final String OAUTH_CLIENT_SECRET = "client_secret"; + private static final String ACCOUNT_SID = "account_sid"; + private static final String MESSAGE_SID = "message_sid"; + + //Getting access token - Method #1 + Twilio.init(new ClientCredentialProvider(OAUTH_CLIENT_SID, OAUTH_CLIENT_SECRET), ACCOUNT_SID); + fetchMessage(MESSAGE_SID); + + + //Scenario: 2 If in case one doesn't want to change the existing stored credential + // Pass Custom TwilioRestClient + // TokenManager tokenManager = new ApiTokenManager(GRANT_TYPE, OAUTH_CLIENT_SID, OAUTH_CLIENT_SECRET); + // TokenAuthStrategy tokenAuthStrategy = new TokenAuthStrategy(tokenManager); + // TwilioRestClient client = new TwilioRestClient.Builder(tokenAuthStrategy).accountSid(ACCOUNT_SID).build(); + // fetchMessageWithClient(MESSAGE_SID, client); + } + + public static void fetchMessage(String sid) { + Message message = Message.fetcher(sid).fetch(); + System.out.println("Fetched Message SID: " + message.getSid()); + } + + public static void fetchMessageWithClient(String sid, TwilioRestClient client) { + Message message = Message.fetcher(sid).fetch(client); + System.out.println("Fetched Message SID: " + message.getSid()); + } +} +``` + diff --git a/src/main/java/com/twilio/TwilioOrgsTokenAuth.java b/src/main/java/com/twilio/TwilioOrgsTokenAuth.java deleted file mode 100644 index 9b28d0b06f..0000000000 --- a/src/main/java/com/twilio/TwilioOrgsTokenAuth.java +++ /dev/null @@ -1,106 +0,0 @@ -package com.twilio; - -import com.twilio.annotations.Beta; -import com.twilio.exception.AuthenticationException; -import com.twilio.http.bearertoken.BearerTokenTwilioRestClient; -import lombok.Getter; -import lombok.Setter; - -import java.util.List; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import com.twilio.http.bearertoken.TokenManager; -import com.twilio.http.bearertoken.OrgsTokenManager; - -@Beta -public class TwilioOrgsTokenAuth { - private static String accessToken; - @Getter - private static List userAgentExtensions; - private static String region = System.getenv("TWILIO_REGION"); - private static String edge = System.getenv("TWILIO_EDGE"); - private static volatile BearerTokenTwilioRestClient restClient; - @Getter @Setter - private static TokenManager tokenManager; - - private static volatile ExecutorService executorService; - - private TwilioOrgsTokenAuth() { - } - - public static synchronized void init(String grantType, String clientId, String clientSecret) { - validateAuthCredentials(grantType, clientId, clientSecret); - tokenManager = new OrgsTokenManager(grantType, clientId, clientSecret); - } - public static synchronized void init(String grantType, String clientId, String clientSecret, String code, String redirectUri, String audience, String refreshToken, String scope) { - validateAuthCredentials(grantType, clientId, clientSecret); - tokenManager = new OrgsTokenManager(grantType, clientId, clientSecret, code, redirectUri, audience, refreshToken, scope); - } - - private static void validateAuthCredentials(String grantType, String clientId, String clientSecret){ - if (grantType == null) { - throw new AuthenticationException("Grant Type cannot be null"); - } - if (clientId == null) { - throw new AuthenticationException("Client Id cannot be null"); - } - if (clientSecret == null) { - throw new AuthenticationException("Client Secret cannot be null"); - } - return; - } - - public static BearerTokenTwilioRestClient getRestClient() { - if (TwilioOrgsTokenAuth.restClient == null) { - synchronized (TwilioOrgsTokenAuth.class) { - if (TwilioOrgsTokenAuth.restClient == null) { - TwilioOrgsTokenAuth.restClient = buildOAuthRestClient(); - } - } - } - return TwilioOrgsTokenAuth.restClient; - } - /** - * Returns the Twilio executor service. - * - * @return the Twilio executor service - */ - public static ExecutorService getExecutorService() { - if (TwilioOrgsTokenAuth.executorService == null) { - synchronized (TwilioOrgsTokenAuth.class) { - if (TwilioOrgsTokenAuth.executorService == null) { - TwilioOrgsTokenAuth.executorService = Executors.newCachedThreadPool(); - } - } - } - return TwilioOrgsTokenAuth.executorService; - } - - private static BearerTokenTwilioRestClient buildOAuthRestClient() { - - BearerTokenTwilioRestClient.Builder builder = new BearerTokenTwilioRestClient.Builder(); - - if (userAgentExtensions != null) { - builder.userAgentExtensions(TwilioOrgsTokenAuth.userAgentExtensions); - } - - builder.region(TwilioOrgsTokenAuth.region); - builder.edge(TwilioOrgsTokenAuth.edge); - if(TwilioOrgsTokenAuth.tokenManager == null){ - throw new AuthenticationException("Either initialize the authentications class or pass a custom token manager"); - } - builder.tokenManager(TwilioOrgsTokenAuth.tokenManager); - - return builder.build(); - } - - /** - * Invalidates the volatile state held in the Twilio singleton. - */ - private static void invalidate() { - TwilioOrgsTokenAuth.restClient = null; - TwilioOrgsTokenAuth.tokenManager = null; - } - - -} \ No newline at end of file diff --git a/src/main/java/com/twilio/base/Page.java b/src/main/java/com/twilio/base/Page.java index b03440007e..259e86e480 100644 --- a/src/main/java/com/twilio/base/Page.java +++ b/src/main/java/com/twilio/base/Page.java @@ -169,8 +169,9 @@ private static Page buildPage(JsonNode root, List results) { private static Page buildNextGenPage(JsonNode root, List results) { JsonNode meta = root.get("meta"); - Builder builder = new Builder().url(meta.get("url").asText()); - + Builder builder = new Builder<>(); + if(meta != null && meta.get("url") != null) { + builder = builder.url(meta.get("url").asText()); JsonNode nextPageNode = meta.get("next_page_url"); if (!nextPageNode.isNull()) { builder.nextPageUrl(nextPageNode.asText()); @@ -192,6 +193,7 @@ private static Page buildNextGenPage(JsonNode root, List results) { } else { builder.pageSize(results.size()); } + } return builder.records(results).build(); } diff --git a/src/main/java/com/twilio/base/bearertoken/Creator.java b/src/main/java/com/twilio/base/bearertoken/Creator.java deleted file mode 100644 index 8cb676cef6..0000000000 --- a/src/main/java/com/twilio/base/bearertoken/Creator.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.twilio.base.bearertoken; - -import com.twilio.TwilioOrgsTokenAuth; -import com.twilio.http.bearertoken.BearerTokenTwilioRestClient; - -import java.util.concurrent.CompletableFuture; - -/** - * Executor for creation of a resource. - * - * @param type of the resource - */ -public abstract class Creator { - - /** - * Execute an async request using default client. - * - * @return future that resolves to requested object - */ - public CompletableFuture createAsync() { - return createAsync(TwilioOrgsTokenAuth.getRestClient()); - } - - /** - * Execute an async request using specified client. - * - * @param client client used to make request - * @return future that resolves to requested object - */ - public CompletableFuture createAsync(final BearerTokenTwilioRestClient client) { - return CompletableFuture.supplyAsync(() -> create(client), TwilioOrgsTokenAuth.getExecutorService()); - } - - /** - * Execute a request using default client. - * - * @return Requested object - */ - public T create() { - return create(TwilioOrgsTokenAuth.getRestClient()); - } - - /** - * Execute a request using specified client. - * - * @param client client used to make request - * @return Requested object - */ - public abstract T create(final BearerTokenTwilioRestClient client); -} diff --git a/src/main/java/com/twilio/base/bearertoken/Deleter.java b/src/main/java/com/twilio/base/bearertoken/Deleter.java deleted file mode 100644 index 3b49cfd0ba..0000000000 --- a/src/main/java/com/twilio/base/bearertoken/Deleter.java +++ /dev/null @@ -1,51 +0,0 @@ -package com.twilio.base.bearertoken; - -import com.twilio.Twilio; -import com.twilio.TwilioOrgsTokenAuth; -import com.twilio.http.bearertoken.BearerTokenTwilioRestClient; - -import java.util.concurrent.CompletableFuture; - -/** - * Executor for deletes of a resource. - * - * @param type of the resource - */ -public abstract class Deleter { - - /** - * Execute an async request using default client. - * - * @return future that resolves to true if the object was deleted - */ - public CompletableFuture deleteAsync() { - return deleteAsync(TwilioOrgsTokenAuth.getRestClient()); - } - - /** - * Execute an async request using specified client. - * - * @param client client used to make request - * @return future that resolves to true if the object was deleted - */ - public CompletableFuture deleteAsync(final BearerTokenTwilioRestClient client) { - return CompletableFuture.supplyAsync(() -> delete(client), Twilio.getExecutorService()); - } - - /** - * Execute a request using default client. - * - * @return true if the object was deleted - */ - public boolean delete() { - return delete(TwilioOrgsTokenAuth.getRestClient()); - } - - /** - * Execute a request using specified client. - * - * @param client client used to make request - * @return true if the object was deleted - */ - public abstract boolean delete(final BearerTokenTwilioRestClient client); -} diff --git a/src/main/java/com/twilio/base/bearertoken/Fetcher.java b/src/main/java/com/twilio/base/bearertoken/Fetcher.java deleted file mode 100644 index 5654895a3f..0000000000 --- a/src/main/java/com/twilio/base/bearertoken/Fetcher.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.twilio.base.bearertoken; - -import com.twilio.TwilioOrgsTokenAuth; -import com.twilio.http.bearertoken.BearerTokenTwilioRestClient; - -import java.util.concurrent.CompletableFuture; - -/** - * Executor for fetches of a resource. - * - * @param type of the resource - */ -public abstract class Fetcher { - - /** - * Execute an async request using default client. - * - * @return future that resolves to requested object - */ - public CompletableFuture fetchAsync() { - return fetchAsync(TwilioOrgsTokenAuth.getRestClient()); - } - - /** - * Execute an async request using specified client. - * - * @param client client used to make request - * @return future that resolves to requested object - */ - public CompletableFuture fetchAsync(final BearerTokenTwilioRestClient client) { - return CompletableFuture.supplyAsync(() -> fetch(client), TwilioOrgsTokenAuth.getExecutorService()); - } - - /** - * Execute a request using default client. - * - * @return Requested object - */ - public T fetch() { - return fetch(TwilioOrgsTokenAuth.getRestClient()); - } - - /** - * Execute a request using specified client. - * - * @param client client used to make request - * @return Requested object - */ - public abstract T fetch(final BearerTokenTwilioRestClient client); -} diff --git a/src/main/java/com/twilio/base/bearertoken/Page.java b/src/main/java/com/twilio/base/bearertoken/Page.java deleted file mode 100644 index 204c2e98a2..0000000000 --- a/src/main/java/com/twilio/base/bearertoken/Page.java +++ /dev/null @@ -1,270 +0,0 @@ -package com.twilio.base.bearertoken; - -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.twilio.exception.ApiConnectionException; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -public class Page { - private final List records; - private final String firstPageUrl; - private final String firstPageUri; - private final String nextPageUrl; - private final String nextPageUri; - private final String previousPageUrl; - private final String previousPageUri; - private final String url; - private final String uri; - private final int pageSize; - - private Page(Builder b) { - this.records = b.records; - this.firstPageUri = b.firstPageUri; - this.firstPageUrl = b.firstPageUrl; - this.nextPageUri = b.nextPageUri; - this.nextPageUrl = b.nextPageUrl; - this.previousPageUri = b.previousPageUri; - this.previousPageUrl = b.previousPageUrl; - this.uri = b.uri; - this.url = b.url; - this.pageSize = b.pageSize; - } - - private String urlFromUri(String domain, String uri) { - return "https://" + domain + ".twilio.com" + uri; - } - - public List getRecords() { - return records; - } - - /** - * Generate first page url for a list result. - * - * @param domain domain to use - * @return the first page url - */ - public String getFirstPageUrl(String domain) { - if (firstPageUrl != null) { - return firstPageUrl; - } - - return urlFromUri(domain, firstPageUri); - } - - /** - * Generate next page url for a list result. - * - * @param domain domain to use - * @return the next page url - */ - public String getNextPageUrl(String domain) { - if (nextPageUrl != null) { - return nextPageUrl; - } - - return urlFromUri(domain, nextPageUri); - } - - /** - * Generate previous page url for a list result. - * - * @param domain domain to use - * @return the previous page url - */ - public String getPreviousPageUrl(String domain) { - if (previousPageUrl != null) { - return previousPageUrl; - } - - return urlFromUri(domain, previousPageUri); - } - - public int getPageSize() { - return pageSize; - } - - /** - * Generate page url for a list result. - * - * @param domain domain to use - * @return the page url - */ - public String getUrl(String domain) { - if (url != null) { - return url; - } - - return urlFromUri(domain, uri); - } - - public boolean hasNextPage() { - return (nextPageUri != null && !nextPageUri.isEmpty()) || (nextPageUrl != null && !nextPageUrl.isEmpty()); - } - - /** - * Create a new page of data from a json blob. - * - * @param recordKey key which holds the records - * @param json json blob - * @param recordType resource type - * @param mapper json parser - * @param record class type - * @return a page of records of type T - */ - public static Page fromJson(String recordKey, String json, Class recordType, ObjectMapper mapper) { - try { - List results = new ArrayList<>(); - JsonNode root = mapper.readTree(json); - JsonNode records = root.get(recordKey); - for (final JsonNode record : records) { - results.add(mapper.readValue(record.toString(), recordType)); - } - - JsonNode uriNode = root.get("uri"); - if (uriNode != null) { - return buildPage(root, results); - } else { - return buildNextGenPage(root, results); - } - - } catch (final IOException e) { - throw new ApiConnectionException( - "Unable to deserialize response: " + e.getMessage() + "\nJSON: " + json, e - ); - } - } - - private static Page buildPage(JsonNode root, List results) { - Builder builder = new Builder() - .uri(root.get("uri").asText()); - - JsonNode nextPageNode = root.get("next_page_uri"); - if (nextPageNode != null && !nextPageNode.isNull()) { - builder.nextPageUri(nextPageNode.asText()); - } - - JsonNode previousPageNode = root.get("previous_page_uri"); - if (previousPageNode != null && !previousPageNode.isNull()) { - builder.previousPageUri(previousPageNode.asText()); - } - - JsonNode firstPageNode = root.get("first_page_uri"); - if (firstPageNode != null && !firstPageNode.isNull()) { - builder.firstPageUri(firstPageNode.asText()); - } - - JsonNode pageSizeNode = root.get("page_size"); - if (pageSizeNode != null && !pageSizeNode.isNull()) { - builder.pageSize(pageSizeNode.asInt()); - } else { - builder.pageSize(results.size()); - } - - return builder.records(results).build(); - } - - private static Page buildNextGenPage(JsonNode root, List results) { - JsonNode meta = root.get("meta"); - Builder builder = new Builder<>(); - if(meta != null && meta.get("url") != null) { - - builder = builder.url(meta.get("url").asText()); - - - JsonNode nextPageNode = meta.get("next_page_url"); - if (!nextPageNode.isNull()) { - builder.nextPageUrl(nextPageNode.asText()); - } - - JsonNode previousPageNode = meta.get("previous_page_url"); - if (!previousPageNode.isNull()) { - builder.previousPageUrl(previousPageNode.asText()); - } - - JsonNode firstPageNode = meta.get("first_page_url"); - if (!firstPageNode.isNull()) { - builder.firstPageUrl(firstPageNode.asText()); - } - - JsonNode pageSizeNode = meta.get("page_size"); - if (!pageSizeNode.isNull()) { - builder.pageSize(pageSizeNode.asInt()); - } else { - builder.pageSize(results.size()); - } - } - - return builder.records(results).build(); - } - - private static class Builder { - private List records; - private String firstPageUrl; - private String firstPageUri; - private String nextPageUrl; - private String nextPageUri; - private String previousPageUrl; - private String previousPageUri; - private String uri; - private String url; - private int pageSize; - - public Builder records(List records) { - this.records = records; - return this; - } - - public Builder firstPageUri(String firstPageUri) { - this.firstPageUri = firstPageUri; - return this; - } - - public Builder firstPageUrl(String firstPageUrl) { - this.firstPageUrl = firstPageUrl; - return this; - } - - public Builder nextPageUri(String nextPageUri) { - this.nextPageUri = nextPageUri; - return this; - } - - public Builder nextPageUrl(String nextPageUrl) { - this.nextPageUrl = nextPageUrl; - return this; - } - - public Builder previousPageUri(String previousPageUri) { - this.previousPageUri = previousPageUri; - return this; - } - - public Builder previousPageUrl(String previousPageUrl) { - this.previousPageUrl = previousPageUrl; - return this; - } - - public Builder uri(String uri) { - this.uri = uri; - return this; - } - - public Builder url(String url) { - this.url = url; - return this; - } - - public Builder pageSize(int pageSize) { - this.pageSize = pageSize; - return this; - } - - public Page build() { - return new Page<>(this); - } - } -} diff --git a/src/main/java/com/twilio/base/bearertoken/Reader.java b/src/main/java/com/twilio/base/bearertoken/Reader.java deleted file mode 100644 index 15e221a3f9..0000000000 --- a/src/main/java/com/twilio/base/bearertoken/Reader.java +++ /dev/null @@ -1,156 +0,0 @@ -package com.twilio.base.bearertoken; - -import com.twilio.TwilioOrgsTokenAuth; -import com.twilio.http.bearertoken.BearerTokenTwilioRestClient; - -import java.util.concurrent.CompletableFuture; - -/** - * Executor for listing of a resource. - * - * @param type of the resource - */ -public abstract class Reader { - - private Integer pageSize; - private Long limit; - - /** - * Execute a request using default client. - * - * @return ResourceSet of objects - */ - public ResourceSet read() { - return read(TwilioOrgsTokenAuth.getRestClient()); - } - - /** - * Execute a request using specified client. - * - * @param client client used to make request - * @return ResourceSet of objects - */ - public abstract ResourceSet read(final BearerTokenTwilioRestClient client); - - /** - * Execute an async request using default client. - * - * @return future that resolves to the ResourceSet of objects - */ - public CompletableFuture> readAsync() { - return readAsync(TwilioOrgsTokenAuth.getRestClient()); - } - - /** - * Execute an async request using specified client. - * - * @param client client used to make request - * @return future that resolves to the ResourceSet of objects - */ - public CompletableFuture> readAsync(final BearerTokenTwilioRestClient client) { - return CompletableFuture.supplyAsync(() -> read(client), TwilioOrgsTokenAuth.getExecutorService()); - } - - /** - * Fetch the first page of resources. - * - * @return Page containing the first pageSize of resources - */ - public Page firstPage() { - return firstPage(TwilioOrgsTokenAuth.getRestClient()); - } - - /** - * Fetch the first page of resources using specified client. - * - * @param client client used to fetch - * @return Page containing the first pageSize of resources - */ - public abstract Page firstPage(final BearerTokenTwilioRestClient client); - - /** - * Retrieve the target page of resources. - * - * @param targetUrl API-generated URL for the requested results page - * @return Page containing the target pageSize of resources - */ - public Page getPage(final String targetUrl) { - return getPage(targetUrl, TwilioOrgsTokenAuth.getRestClient()); - } - - /** - * Retrieve the target page of resources. - * - * @param targetUrl API-generated URL for the requested results page - * @param client client used to fetch - * @return Page containing the target pageSize of resources - */ - public abstract Page getPage(final String targetUrl, final BearerTokenTwilioRestClient client); - - /** - * Fetch the following page of resources. - * - * @param page current page of resources - * @return Page containing the next pageSize of resources - */ - public Page nextPage(final Page page) { - return nextPage(page, TwilioOrgsTokenAuth.getRestClient()); - } - - /** - * Fetch the following page of resources using specified client. - * - * @param page current page of resources - * @param client client used to fetch - * @return Page containing the next pageSize of resources - */ - public abstract Page nextPage(final Page page, final BearerTokenTwilioRestClient client); - - /** - * Fetch the prior page of resources. - * - * @param page current page of resources - * @return Page containing the previous pageSize of resources - */ - public Page previousPage(final Page page) { - return previousPage(page, TwilioOrgsTokenAuth.getRestClient()); - } - - /** - * Fetch the prior page of resources using specified client. - * - * @param page current page of resources - * @param client client used to fetch - * @return Page containing the previous pageSize of resources - */ - public abstract Page previousPage(final Page page, final BearerTokenTwilioRestClient client); - - public Integer getPageSize() { - return pageSize; - } - - public Reader pageSize(final int pageSize) { - this.pageSize = pageSize; - return this; - } - - public Long getLimit() { - return limit; - } - - /** - * Sets the max number of records to read. - * - * @param limit max number of records to read - * @return this reader - */ - public Reader limit(final long limit) { - this.limit = limit; - - if (this.pageSize == null) { - this.pageSize = this.limit.intValue(); - } - - return this; - } -} diff --git a/src/main/java/com/twilio/base/bearertoken/Resource.java b/src/main/java/com/twilio/base/bearertoken/Resource.java deleted file mode 100644 index 08dc228556..0000000000 --- a/src/main/java/com/twilio/base/bearertoken/Resource.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.twilio.base.bearertoken; - -import java.io.Serializable; - -public abstract class Resource implements Serializable { - - private static final long serialVersionUID = -5898012691404059591L; - -} diff --git a/src/main/java/com/twilio/base/bearertoken/ResourceSet.java b/src/main/java/com/twilio/base/bearertoken/ResourceSet.java deleted file mode 100644 index 4cc09d8c2d..0000000000 --- a/src/main/java/com/twilio/base/bearertoken/ResourceSet.java +++ /dev/null @@ -1,138 +0,0 @@ -package com.twilio.base.bearertoken; - -import com.twilio.http.bearertoken.BearerTokenTwilioRestClient; - -import java.util.Iterator; -import java.util.NoSuchElementException; - -/** - * A collection of resources. - * - * @param type of the resource - */ -public class ResourceSet implements Iterable { - - private final Reader reader; - private final BearerTokenTwilioRestClient client; - private final Page firstPage; // Store reference to first page to enable multiple iterations - - private boolean autoPaging; - private long pages = 1; - private long pageLimit = Long.MAX_VALUE; - private long processed = 0; - private Page page; - private Iterator iterator; - - /** - * Initialize the resource set. - * - * @param reader reader used to fetch next page - * @param client client used to make requests - * @param page page of data - */ - public ResourceSet(final Reader reader, final BearerTokenTwilioRestClient client, final Page page) { - this.reader = reader; - this.client = client; - this.firstPage = page; // Save first page to allow resetting iterator state - this.page = page; - this.iterator = page.getRecords().iterator(); - this.autoPaging = true; - - if (reader.getLimit() != null) { - this.pageLimit = (long)(Math.ceil((double)reader.getLimit() / (double)page.getPageSize())); - } - } - - public boolean isAutoPaging() { - return autoPaging; - } - - public ResourceSet setAutoPaging(final boolean autoPaging) { - this.autoPaging = autoPaging; - return this; - } - - public Integer getPageSize() { - return page.getPageSize(); - } - - public ResourceSet setPageSize(final int pageSize) { - reader.pageSize(pageSize); - return this; - } - - public Long getLimit() { - return reader.getLimit(); - } - - public ResourceSet setLimit(final long limit) { - reader.limit(limit); - return this; - } - - public long getPageLimit() { - return pageLimit; - } - - @Override - public Iterator iterator() { - // Reset state to allow multiple iterations - this.processed = 0; - this.pages = 1; - this.page = this.firstPage; // Reset to first page for new iteration - this.iterator = this.firstPage.getRecords().iterator(); // Reset iterator to start of first page - - return new ResourceSetIterator<>(this); - } - - private void fetchNextPage() { - if (!page.hasNextPage() || pages >= pageLimit) { - return; - } - - pages++; - page = reader.nextPage(page, client); - iterator = page.getRecords().iterator(); - } - - private class ResourceSetIterator implements Iterator { - private final ResourceSet resourceSet; - - public ResourceSetIterator(final ResourceSet resourceSet) { - this.resourceSet = resourceSet; - } - - @Override - public boolean hasNext() { - if (resourceSet.getLimit() != null && resourceSet.processed >= resourceSet.getLimit()) { - return false; - } - - return resourceSet.iterator.hasNext(); - } - - @Override - public E next() { - if (resourceSet == null || resourceSet.iterator == null) { - throw new NoSuchElementException(); - } - - E element = resourceSet.iterator.next(); - if (resourceSet.isAutoPaging() && !resourceSet.iterator.hasNext()) { - resourceSet.fetchNextPage(); - } - - resourceSet.processed++; - return element; - } - - @Override - public void remove() { - if (resourceSet.iterator != null) { - resourceSet.processed++; - resourceSet.iterator.remove(); - } - } - - } -} diff --git a/src/main/java/com/twilio/base/bearertoken/Updater.java b/src/main/java/com/twilio/base/bearertoken/Updater.java deleted file mode 100644 index 690e3604c5..0000000000 --- a/src/main/java/com/twilio/base/bearertoken/Updater.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.twilio.base.bearertoken; - -import com.twilio.TwilioOrgsTokenAuth; -import com.twilio.http.bearertoken.BearerTokenTwilioRestClient; - -import java.util.concurrent.CompletableFuture; - -/** - * Executor for updates of a resource. - * - * @param type of the resource - */ -public abstract class Updater { - - /** - * Execute an async request using default client. - * - * @return future that resolves to requested object - */ - public CompletableFuture updateAsync() { - return updateAsync(TwilioOrgsTokenAuth.getRestClient()); - } - - /** - * Execute an async request using specified client. - * - * @param client client used to make request - * @return future that resolves to requested object - */ - public CompletableFuture updateAsync(final BearerTokenTwilioRestClient client) { - return CompletableFuture.supplyAsync(() -> update(client), TwilioOrgsTokenAuth.getExecutorService()); - } - - /** - * Execute a request using default client. - * - * @return Requested object - */ - public T update() { - return update(TwilioOrgsTokenAuth.getRestClient()); - } - - /** - * Execute a request using specified client. - * - * @param client client used to make request - * @return Requested object - */ - public abstract T update(final BearerTokenTwilioRestClient client); -} diff --git a/src/main/java/com/twilio/credential/orgs/OrgsClientCredentialProvider.java b/src/main/java/com/twilio/credential/orgs/OrgsClientCredentialProvider.java index 9d5687a64a..5d93404bc6 100644 --- a/src/main/java/com/twilio/credential/orgs/OrgsClientCredentialProvider.java +++ b/src/main/java/com/twilio/credential/orgs/OrgsClientCredentialProvider.java @@ -1,4 +1,64 @@ package com.twilio.credential.orgs; -public class OrgsClientCredentialProvider { +import com.twilio.auth_strategy.AuthStrategy; +import com.twilio.auth_strategy.TokenAuthStrategy; +import com.twilio.constant.EnumConstants; +import com.twilio.credential.CredentialProvider; +import com.twilio.exception.AuthenticationException; +import com.twilio.http.bearertoken.OrgsTokenManager; +import com.twilio.http.bearertoken.TokenManager; + +import java.util.Objects; + +public class OrgsClientCredentialProvider extends CredentialProvider { + private String grantType; + private String clientId; + private String clientSecret; + private TokenManager tokenManager; + + public OrgsClientCredentialProvider(String clientId, String clientSecret) { + super(EnumConstants.AuthType.CLIENT_CREDENTIALS); + if (clientId == null || clientSecret == null) { + throw new AuthenticationException("ClientId or ClientSecret can not be null"); + } + this.grantType = "client_credentials"; + this.clientId = clientId; + this.clientSecret = clientSecret; + this.tokenManager = null; + } + + public OrgsClientCredentialProvider(String clientId, String clientSecret, TokenManager tokenManager) { + super(EnumConstants.AuthType.CLIENT_CREDENTIALS); + if (clientId == null || clientSecret == null || tokenManager == null) { + throw new AuthenticationException("ClientId or ClientSecret or TokenManager can not be null"); + } + this.grantType = "client_credentials"; + this.clientId = clientId; + this.clientSecret = clientSecret; + this.tokenManager = tokenManager; + } + + @Override + public AuthStrategy toAuthStrategy() { + if (tokenManager == null) { + tokenManager = new OrgsTokenManager(grantType, clientId, clientSecret); + } + return new TokenAuthStrategy(tokenManager); + } + + @Override + public boolean equals(final Object o) { + if (this == o) { + return true; + } + + if (o == null || getClass() != o.getClass()) { + return false; + } + + OrgsClientCredentialProvider other = (OrgsClientCredentialProvider) o; + return Objects.equals(clientId, other.clientId) && + Objects.equals(clientSecret, other.clientSecret) && + Objects.equals(tokenManager, other.tokenManager); + } } diff --git a/src/main/java/com/twilio/http/NetworkHttpClient.java b/src/main/java/com/twilio/http/NetworkHttpClient.java index 8c1b0dad85..0d40e4cb8c 100644 --- a/src/main/java/com/twilio/http/NetworkHttpClient.java +++ b/src/main/java/com/twilio/http/NetworkHttpClient.java @@ -72,7 +72,7 @@ public NetworkHttpClient(final RequestConfig requestConfig) { public NetworkHttpClient(final RequestConfig requestConfig, final SocketConfig socketConfig) { Collection headers = Arrays.asList( new BasicHeader("X-Twilio-Client", "java-" + Twilio.VERSION), - new BasicHeader(HttpHeaders.ACCEPT, "application/json"), + // The Accept header is intentionally omitted to support both SCIM and JSON content types. new BasicHeader(HttpHeaders.ACCEPT_ENCODING, "utf-8") ); diff --git a/src/main/java/com/twilio/http/bearertoken/BearerTokenHttpClient.java b/src/main/java/com/twilio/http/bearertoken/BearerTokenHttpClient.java deleted file mode 100644 index 0c405769bf..0000000000 --- a/src/main/java/com/twilio/http/bearertoken/BearerTokenHttpClient.java +++ /dev/null @@ -1,108 +0,0 @@ -package com.twilio.http.bearertoken; - -import com.twilio.http.HttpClient; -import com.twilio.http.Request; -import com.twilio.http.Response; -import lombok.Getter; -import lombok.Setter; -import org.apache.hc.client5.http.config.RequestConfig; -import org.apache.hc.client5.http.impl.DefaultRedirectStrategy; -import org.apache.hc.client5.http.protocol.RedirectStrategy; -import org.apache.hc.core5.http.io.SocketConfig; - -public abstract class BearerTokenHttpClient { - // Use constants from HttpClient - public static final RequestConfig DEFAULT_REQUEST_CONFIG = RequestConfig - .custom() - .setConnectTimeout(HttpClient.CONNECTION_TIMEOUT) - .build(); - public static final SocketConfig DEFAULT_SOCKET_CONFIG = SocketConfig - .custom() - .setSoTimeout(HttpClient.SOCKET_TIMEOUT) - .build(); - @Getter - @Setter - private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy(); - - @Getter - private Response lastResponse; - @Getter - private BearerTokenRequest lastRequest; - - public Response reliableRequest(final BearerTokenRequest request) { - return reliableRequest(request, HttpClient.RETRY_CODES, HttpClient.RETRIES, HttpClient.DELAY_MILLIS); - } - - public Response reliableRequest(final BearerTokenRequest request, final int[] retryCodes, int retries, - final long delayMillis) { - lastRequest = request; - Response response = null; - while (retries > 0) { - response = makeRequest(request); - - if (!shouldRetry(response, retryCodes)) { - break; - } - - try { - Thread.sleep(delayMillis); - } catch (final InterruptedException e) { - // Delay failed, continue - } - - // Decrement retries - retries--; - } - - lastResponse = response; - - return response; - } - - protected boolean shouldRetry(final Response response, final int[] retryCodes) { - if (response == null) { - return true; - } - - int statusCode = response.getStatusCode(); - int category = (int) Math.floor(statusCode / 100.0); - - for (final int retryCode : retryCodes) { - switch (retryCode) { - case HttpClient.ANY_100: - if (category == 1) { - return true; - } - break; - case HttpClient.ANY_200: - if (category == 2) { - return true; - } - break; - case HttpClient.ANY_300: - if (category == 3) { - return true; - } - break; - case HttpClient.ANY_400: - if (category == 4) { - return true; - } - break; - case HttpClient.ANY_500: - if (category == 5) { - return true; - } - break; - default: - if (statusCode == retryCode) { - return true; - } - break; - } - } - return false; - } - - public abstract Response makeRequest(final BearerTokenRequest request); -} diff --git a/src/main/java/com/twilio/http/bearertoken/BearerTokenNetworkHttpClient.java b/src/main/java/com/twilio/http/bearertoken/BearerTokenNetworkHttpClient.java deleted file mode 100644 index 9d80666640..0000000000 --- a/src/main/java/com/twilio/http/bearertoken/BearerTokenNetworkHttpClient.java +++ /dev/null @@ -1,181 +0,0 @@ -package com.twilio.http.bearertoken; - -import com.twilio.Twilio; -import com.twilio.constant.EnumConstants; -import com.twilio.exception.ApiException; -import com.twilio.http.HttpMethod; -import com.twilio.http.HttpUtility; -import com.twilio.http.Response; -import java.util.ArrayList; -import java.util.Map.Entry; -import org.apache.hc.client5.http.classic.methods.HttpUriRequestBase; -import org.apache.hc.client5.http.config.RequestConfig; -import org.apache.hc.client5.http.entity.UrlEncodedFormEntity; -import org.apache.hc.client5.http.impl.classic.CloseableHttpClient; -import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse; -import org.apache.hc.client5.http.impl.classic.HttpClientBuilder; -import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager; -import org.apache.hc.core5.http.ContentType; -import org.apache.hc.core5.http.HttpEntity; -import org.apache.hc.core5.http.HttpHeaders; -import org.apache.hc.core5.http.NameValuePair; -import org.apache.hc.core5.http.io.SocketConfig; -import org.apache.hc.core5.http.io.entity.BufferedHttpEntity; -import org.apache.hc.core5.http.io.entity.StringEntity; -import org.apache.hc.core5.http.message.BasicHeader; - -import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.util.Arrays; -import java.util.Collection; -import java.util.List; -import java.util.Map; -import org.apache.hc.core5.http.message.BasicNameValuePair; -import static com.twilio.http.HttpClient.createHttpUriRequestBase; - -public class BearerTokenNetworkHttpClient extends BearerTokenHttpClient { - - protected final CloseableHttpClient client; - - private boolean isCustomClient; - - /** - * Create a new HTTP Client. - */ - public BearerTokenNetworkHttpClient() { - this(DEFAULT_REQUEST_CONFIG); - } - - /** - * Create a new HTTP Client with a custom request config. - * - * @param requestConfig a RequestConfig. - */ - public BearerTokenNetworkHttpClient(final RequestConfig requestConfig) { - this(requestConfig, DEFAULT_SOCKET_CONFIG); - } - - /** - * Create a new HTTP Client with a custom request and socket config. - * - * @param requestConfig a RequestConfig. - * @param socketConfig a SocketConfig. - */ - public BearerTokenNetworkHttpClient(final RequestConfig requestConfig, final SocketConfig socketConfig) { - Collection headers = Arrays.asList( - new BasicHeader("X-Twilio-Client", "java-" + Twilio.VERSION), - //new BasicHeader(HttpHeaders.ACCEPT, "application/json"), Orgs API has scim or json support. - new BasicHeader(HttpHeaders.ACCEPT_ENCODING, "utf-8") - ); - - String googleAppEngineVersion = System.getProperty("com.google.appengine.runtime.version"); - boolean isGoogleAppEngine = googleAppEngineVersion != null && !googleAppEngineVersion.isEmpty(); - - HttpClientBuilder clientBuilder = HttpClientBuilder.create(); - - if (!isGoogleAppEngine) { - clientBuilder.useSystemProperties(); - } - - PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(); - connectionManager.setDefaultSocketConfig(socketConfig); - /** - * Example: Lets say client has one server. - * There are 4 servers on edge handling client request. - * Each request takes on an average 500ms (2 request per second) - * Total number request can be server in a second from a route: 20 * 4 * 2 (DefaultMaxPerRoute * edge servers * request per second) - */ - connectionManager.setDefaultMaxPerRoute(20); - connectionManager.setMaxTotal(100); - - client = clientBuilder - .setConnectionManager(connectionManager) - .setDefaultRequestConfig(requestConfig) - .setDefaultHeaders(headers) - .setRedirectStrategy(this.getRedirectStrategy()) - .build(); - } - - /** - * Create a new HTTP Client using custom configuration. - * @param clientBuilder an HttpClientBuilder. - */ - public BearerTokenNetworkHttpClient(HttpClientBuilder clientBuilder) { - Collection headers = Arrays.asList( - new BasicHeader("X-Twilio-Client", "java-" + Twilio.VERSION), - //new BasicHeader(HttpHeaders.ACCEPT, "application/json"), Orgs API has scim or json support. - new BasicHeader(HttpHeaders.ACCEPT_ENCODING, "utf-8") - ); - isCustomClient = true; - - client = clientBuilder - .setDefaultRequestConfig(DEFAULT_REQUEST_CONFIG) - .setDefaultHeaders(headers) - .setRedirectStrategy(this.getRedirectStrategy()) - .build(); - } - - /** - * Make a request. - * - * @param request request to make - * @return Response of the HTTP request - */ - public Response makeRequest(final BearerTokenRequest request) { - - HttpMethod method = request.getMethod(); - HttpUriRequestBase httpUriRequestBase = createHttpUriRequestBase(request); - - - if (request.requiresAuthentication()) { - httpUriRequestBase.addHeader(HttpHeaders.AUTHORIZATION, request.getAuthString()); - } - - for (Map.Entry> entry : request.getHeaderParams().entrySet()) { - for (String value : entry.getValue()) { - httpUriRequestBase.addHeader(entry.getKey(), value); - } - } - - if (method != HttpMethod.GET) { - // TODO: It will be removed after one RC Release. - if (request.getContentType() == null) request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); - if (EnumConstants.ContentType.JSON.getValue().equals(request.getContentType().getValue())) { - HttpEntity entity = new StringEntity(request.getBody(), ContentType.APPLICATION_JSON); - httpUriRequestBase.setEntity(entity); - httpUriRequestBase.addHeader( - HttpHeaders.CONTENT_TYPE, EnumConstants.ContentType.JSON.getValue()); - } else { - httpUriRequestBase.addHeader( - HttpHeaders.CONTENT_TYPE, EnumConstants.ContentType.FORM_URLENCODED.getValue()); - // Create your form parameters - List formParams = new ArrayList<>(); - for ( Entry> entry : request.getPostParams().entrySet()) { - for (String value : entry.getValue()) { - formParams.add(new BasicNameValuePair(entry.getKey(), value)); - } - } - - // Build the entity with URL form encoded parameters - UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(formParams, StandardCharsets.UTF_8); - // Set the entity on the request - httpUriRequestBase.setEntity(formEntity); - } - - } - httpUriRequestBase.addHeader(HttpHeaders.USER_AGENT, HttpUtility.getUserAgentString(request.getUserAgentExtensions(), isCustomClient)); - - try { - CloseableHttpResponse response = client.execute(httpUriRequestBase); - HttpEntity entity = response.getEntity(); - return new Response( - // Consume the entire HTTP response before returning the stream - entity == null ? null : new BufferedHttpEntity(entity).getContent(), - response.getCode(), - response.getHeaders() - ); - } catch (IOException e) { - throw new ApiException(e.getMessage(), e); - } - } -} diff --git a/src/main/java/com/twilio/http/bearertoken/BearerTokenRequest.java b/src/main/java/com/twilio/http/bearertoken/BearerTokenRequest.java deleted file mode 100644 index 83976c2e45..0000000000 --- a/src/main/java/com/twilio/http/bearertoken/BearerTokenRequest.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.twilio.http.bearertoken; - -import com.twilio.http.HttpMethod; -import com.twilio.http.IRequest; - -public class BearerTokenRequest extends IRequest { - - private String accessToken; - - public BearerTokenRequest(HttpMethod method, String url) { - super(method, url); - } - - public BearerTokenRequest(HttpMethod method, String domain, String uri) { - super(method, domain, uri); - } - - public BearerTokenRequest(HttpMethod method, String domain, String uri, String region) { - super(method, domain, uri, region); - } - - /** - * Create auth string from accessToken. - * - * @return basic authentication string - */ - public String getAuthString() { - return "Bearer " + accessToken; - } - - public boolean requiresAuthentication() { - return accessToken != null; - } - - public void setAuth(String accessToken) { - this.accessToken = accessToken; - } -} diff --git a/src/main/java/com/twilio/http/bearertoken/BearerTokenTwilioRestClient.java b/src/main/java/com/twilio/http/bearertoken/BearerTokenTwilioRestClient.java deleted file mode 100644 index c7da1ff2b0..0000000000 --- a/src/main/java/com/twilio/http/bearertoken/BearerTokenTwilioRestClient.java +++ /dev/null @@ -1,186 +0,0 @@ -package com.twilio.http.bearertoken; - -import com.auth0.jwt.JWT; -import com.auth0.jwt.interfaces.DecodedJWT; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; -import com.twilio.http.Response; -import lombok.Getter; -import lombok.Setter; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.ArrayList; -import java.util.Date; -import java.util.List; -import java.util.Map; -import java.util.function.Predicate; - - -/* - * Use this BearerToken Rest Client if no authentication is involved in an API. - */ -public class BearerTokenTwilioRestClient { - public static final int HTTP_STATUS_CODE_CREATED = 201; - public static final int HTTP_STATUS_CODE_NO_CONTENT = 204; - public static final int HTTP_STATUS_CODE_OK = 200; - public static final Predicate SUCCESS = i -> i != null && i >= 200 && i < 400; - @Getter - private final ObjectMapper objectMapper; - private String accessToken; - @Getter - private final String region; - @Getter - private final String edge; - @Getter - private final BearerTokenHttpClient httpClient; - @Getter - private final List userAgentExtensions; - @Setter - private final TokenManager tokenManager; - private static final Logger logger = LoggerFactory.getLogger(BearerTokenTwilioRestClient.class); - - private BearerTokenTwilioRestClient(BearerTokenTwilioRestClient.Builder b) { - this.region = b.region; - this.edge = b.edge; - this.httpClient = b.httpClient; - this.objectMapper = b.objectMapper; - this.userAgentExtensions = b.userAgentExtensions; - this.tokenManager = b.tokenManager; - } - - public static class Builder { - // This module configures the ObjectMapper to use - // public API methods for manipulating java.time.* - // classes. The alternative is to use reflection which - // generates warnings from the module system on Java 9+ - private static final ObjectMapper DEFAULT_OBJECT_MAPPER = new ObjectMapper() - .registerModule(new JavaTimeModule()); - - private String region; - private String edge; - private BearerTokenHttpClient httpClient; - private List userAgentExtensions; - private TokenManager tokenManager; - private ObjectMapper objectMapper = DEFAULT_OBJECT_MAPPER; - - public Builder() { - this.region = System.getenv("TWILIO_REGION"); - this.edge = System.getenv("TWILIO_EDGE"); - userAgentExtensions = new ArrayList<>(); - } - - public BearerTokenTwilioRestClient.Builder region(final String region) { - this.region = region; - return this; - } - - public BearerTokenTwilioRestClient.Builder edge(final String edge) { - this.edge = edge; - return this; - } - - public BearerTokenTwilioRestClient.Builder tokenManager(final TokenManager tokenManager) { - this.tokenManager = tokenManager; - return this; - } - - public BearerTokenTwilioRestClient.Builder httpClient(final BearerTokenHttpClient httpClient) { - this.httpClient = httpClient; - return this; - } - - public BearerTokenTwilioRestClient.Builder userAgentExtensions(final List userAgentExtensions) { - if (userAgentExtensions != null && !userAgentExtensions.isEmpty()) { - this.userAgentExtensions = new ArrayList<>(userAgentExtensions); - } - return this; - } - - public BearerTokenTwilioRestClient.Builder objectMapper(final ObjectMapper objectMapper) { - this.objectMapper = objectMapper; - return this; - } - - public BearerTokenTwilioRestClient build() { - if (this.httpClient == null) { - this.httpClient = new BearerTokenNetworkHttpClient(); - } - return new BearerTokenTwilioRestClient(this); - } - } - public Response request(BearerTokenRequest request) { - - if (accessToken == null || accessToken.isEmpty() || isTokenExpired(this.accessToken)) { - synchronized (BearerTokenTwilioRestClient.class){ - if (accessToken == null || accessToken.isEmpty() || isTokenExpired(this.accessToken)) { - this.accessToken = tokenManager.fetchAccessToken(); - } - } - } - - request.setAuth(accessToken); - if (region != null) - request.setRegion(region); - if (edge != null) - request.setEdge(edge); - - if (userAgentExtensions != null && !userAgentExtensions.isEmpty()) { - request.setUserAgentExtensions(userAgentExtensions); - } - logRequest(request); - Response response = httpClient.reliableRequest(request); - if(response != null) { - int statusCode = response.getStatusCode(); - if (statusCode == 401) { - this.accessToken = tokenManager.fetchAccessToken(); - request.setAuth(accessToken); - response = httpClient.reliableRequest(request); - } - - if (logger.isDebugEnabled()) { - logger.debug("status code: {}", statusCode); - org.apache.hc.core5.http.Header[] responseHeaders = response.getHeaders(); - logger.debug("response headers:"); - for (int i = 0; i < responseHeaders.length; i++) { - logger.debug("responseHeader: {}", responseHeaders[i]); - } - } - } - - return response; - } - - public boolean isTokenExpired(String token) { - DecodedJWT jwt = JWT.decode(token); - Date expiresAt = jwt.getExpiresAt(); - // Add a buffer of 30 seconds - long bufferMilliseconds = 30 * 1000; - Date bufferExpiresAt = new Date(expiresAt.getTime() - bufferMilliseconds); - return bufferExpiresAt.before(new Date()); - } - - public void logRequest(final BearerTokenRequest request) { - if (logger.isDebugEnabled()) { - logger.debug("-- BEGIN Twilio API BearerTokenRequest --"); - logger.debug("request method: " + request.getMethod()); - logger.debug("request URL: " + request.constructURL().toString()); - final Map> queryParams = request.getQueryParams(); - final Map> headerParams = request.getHeaderParams(); - - if (queryParams != null && !queryParams.isEmpty()) { - logger.debug("query parameters: " + queryParams); - } - - if (headerParams != null && !headerParams.isEmpty()) { - logger.debug("header parameters: "); - for (String key : headerParams.keySet()) { - if (!key.toLowerCase().contains("authorization")) { - logger.debug(key + ": " + headerParams.get(key)); - } - } - } - logger.debug("-- END Twilio API BearerTokenRequest --"); - } - } -} diff --git a/src/main/java/com/twilio/rest/previewiam/organizations/Account.java b/src/main/java/com/twilio/rest/previewiam/organizations/Account.java index 388b31fa34..bffd937287 100644 --- a/src/main/java/com/twilio/rest/previewiam/organizations/Account.java +++ b/src/main/java/com/twilio/rest/previewiam/organizations/Account.java @@ -20,7 +20,7 @@ import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; -import com.twilio.base.bearertoken.Resource; +import com.twilio.base.Resource; import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; diff --git a/src/main/java/com/twilio/rest/previewiam/organizations/AccountFetcher.java b/src/main/java/com/twilio/rest/previewiam/organizations/AccountFetcher.java index 57dc7b088e..1949891f1d 100644 --- a/src/main/java/com/twilio/rest/previewiam/organizations/AccountFetcher.java +++ b/src/main/java/com/twilio/rest/previewiam/organizations/AccountFetcher.java @@ -14,15 +14,15 @@ package com.twilio.rest.previewiam.organizations; -import com.twilio.base.bearertoken.Fetcher; +import com.twilio.base.Fetcher; import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; import com.twilio.http.HttpMethod; +import com.twilio.http.Request; import com.twilio.http.Response; -import com.twilio.http.bearertoken.BearerTokenRequest; -import com.twilio.http.bearertoken.BearerTokenTwilioRestClient; +import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; public class AccountFetcher extends Fetcher { @@ -39,7 +39,7 @@ public AccountFetcher( } @Override - public Account fetch(final BearerTokenTwilioRestClient client) { + public Account fetch(final TwilioRestClient client) { String path = "/Organizations/{OrganizationSid}/Accounts/{AccountSid}"; path = @@ -53,7 +53,7 @@ public Account fetch(final BearerTokenTwilioRestClient client) { this.pathAccountSid.toString() ); - BearerTokenRequest request = new BearerTokenRequest( + Request request = new Request( HttpMethod.GET, Domains.PREVIEWIAM.toString(), path @@ -66,7 +66,7 @@ public Account fetch(final BearerTokenTwilioRestClient client) { "Account fetch failed: Unable to connect to server" ); } else if ( - !BearerTokenTwilioRestClient.SUCCESS.test(response.getStatusCode()) + !TwilioRestClient.SUCCESS.test(response.getStatusCode()) ) { RestException restException = RestException.fromJson( response.getStream(), diff --git a/src/main/java/com/twilio/rest/previewiam/organizations/AccountReader.java b/src/main/java/com/twilio/rest/previewiam/organizations/AccountReader.java index 5ad736ac13..7c2a384f3f 100644 --- a/src/main/java/com/twilio/rest/previewiam/organizations/AccountReader.java +++ b/src/main/java/com/twilio/rest/previewiam/organizations/AccountReader.java @@ -14,17 +14,17 @@ package com.twilio.rest.previewiam.organizations; -import com.twilio.base.bearertoken.Page; -import com.twilio.base.bearertoken.Reader; -import com.twilio.base.bearertoken.ResourceSet; +import com.twilio.base.Page; +import com.twilio.base.Reader; +import com.twilio.base.ResourceSet; import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; import com.twilio.http.HttpMethod; +import com.twilio.http.Request; import com.twilio.http.Response; -import com.twilio.http.bearertoken.BearerTokenRequest; -import com.twilio.http.bearertoken.BearerTokenTwilioRestClient; +import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; public class AccountReader extends Reader { @@ -42,11 +42,11 @@ public AccountReader setPageSize(final Integer pageSize) { } @Override - public ResourceSet read(final BearerTokenTwilioRestClient client) { + public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } - public Page firstPage(final BearerTokenTwilioRestClient client) { + public Page firstPage(final TwilioRestClient client) { String path = "/Organizations/{OrganizationSid}/Accounts"; path = path.replace( @@ -54,7 +54,7 @@ public Page firstPage(final BearerTokenTwilioRestClient client) { this.pathOrganizationSid.toString() ); - BearerTokenRequest request = new BearerTokenRequest( + Request request = new Request( HttpMethod.GET, Domains.PREVIEWIAM.toString(), path @@ -66,8 +66,8 @@ public Page firstPage(final BearerTokenTwilioRestClient client) { } private Page pageForRequest( - final BearerTokenTwilioRestClient client, - final BearerTokenRequest request + final TwilioRestClient client, + final Request request ) { Response response = client.request(request); @@ -76,7 +76,7 @@ private Page pageForRequest( "Account read failed: Unable to connect to server" ); } else if ( - !BearerTokenTwilioRestClient.SUCCESS.test(response.getStatusCode()) + !TwilioRestClient.SUCCESS.test(response.getStatusCode()) ) { RestException restException = RestException.fromJson( response.getStream(), @@ -102,9 +102,9 @@ private Page pageForRequest( @Override public Page previousPage( final Page page, - final BearerTokenTwilioRestClient client + final TwilioRestClient client ) { - BearerTokenRequest request = new BearerTokenRequest( + Request request = new Request( HttpMethod.GET, page.getPreviousPageUrl(Domains.PREVIEWIAM.toString()) ); @@ -114,9 +114,9 @@ public Page previousPage( @Override public Page nextPage( final Page page, - final BearerTokenTwilioRestClient client + final TwilioRestClient client ) { - BearerTokenRequest request = new BearerTokenRequest( + Request request = new Request( HttpMethod.GET, page.getNextPageUrl(Domains.PREVIEWIAM.toString()) ); @@ -126,9 +126,9 @@ public Page nextPage( @Override public Page getPage( final String targetUrl, - final BearerTokenTwilioRestClient client + final TwilioRestClient client ) { - BearerTokenRequest request = new BearerTokenRequest( + Request request = new Request( HttpMethod.GET, targetUrl ); @@ -136,7 +136,7 @@ public Page getPage( return pageForRequest(client, request); } - private void addQueryParams(final BearerTokenRequest request) { + private void addQueryParams(final Request request) { if (pageSize != null) { request.addQueryParam("PageSize", pageSize.toString()); } diff --git a/src/main/java/com/twilio/rest/previewiam/organizations/RoleAssignment.java b/src/main/java/com/twilio/rest/previewiam/organizations/RoleAssignment.java index 875068a004..882781fe09 100644 --- a/src/main/java/com/twilio/rest/previewiam/organizations/RoleAssignment.java +++ b/src/main/java/com/twilio/rest/previewiam/organizations/RoleAssignment.java @@ -22,7 +22,7 @@ import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; -import com.twilio.base.bearertoken.Resource; +import com.twilio.base.Resource; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import java.io.IOException; diff --git a/src/main/java/com/twilio/rest/previewiam/organizations/RoleAssignmentCreator.java b/src/main/java/com/twilio/rest/previewiam/organizations/RoleAssignmentCreator.java index e95e19a4b1..1a22c181ed 100644 --- a/src/main/java/com/twilio/rest/previewiam/organizations/RoleAssignmentCreator.java +++ b/src/main/java/com/twilio/rest/previewiam/organizations/RoleAssignmentCreator.java @@ -15,15 +15,15 @@ package com.twilio.rest.previewiam.organizations; import com.fasterxml.jackson.databind.ObjectMapper; -import com.twilio.base.bearertoken.Creator; +import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; import com.twilio.http.HttpMethod; +import com.twilio.http.Request; import com.twilio.http.Response; -import com.twilio.http.bearertoken.BearerTokenRequest; -import com.twilio.http.bearertoken.BearerTokenTwilioRestClient; +import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; public class RoleAssignmentCreator extends Creator { @@ -49,7 +49,7 @@ public RoleAssignmentCreator setPublicApiCreateRoleAssignmentRequest( } @Override - public RoleAssignment create(final BearerTokenTwilioRestClient client) { + public RoleAssignment create(final TwilioRestClient client) { String path = "/Organizations/{OrganizationSid}/RoleAssignments"; path = @@ -63,7 +63,7 @@ public RoleAssignment create(final BearerTokenTwilioRestClient client) { this.publicApiCreateRoleAssignmentRequest.toString() ); - BearerTokenRequest request = new BearerTokenRequest( + Request request = new Request( HttpMethod.POST, Domains.PREVIEWIAM.toString(), path @@ -76,7 +76,7 @@ public RoleAssignment create(final BearerTokenTwilioRestClient client) { "RoleAssignment creation failed: Unable to connect to server" ); } else if ( - !BearerTokenTwilioRestClient.SUCCESS.test(response.getStatusCode()) + !TwilioRestClient.SUCCESS.test(response.getStatusCode()) ) { RestException restException = RestException.fromJson( response.getStream(), @@ -98,8 +98,8 @@ public RoleAssignment create(final BearerTokenTwilioRestClient client) { } private void addPostParams( - final BearerTokenRequest request, - BearerTokenTwilioRestClient client + final Request request, + TwilioRestClient client ) { ObjectMapper objectMapper = client.getObjectMapper(); if (publicApiCreateRoleAssignmentRequest != null) { diff --git a/src/main/java/com/twilio/rest/previewiam/organizations/RoleAssignmentDeleter.java b/src/main/java/com/twilio/rest/previewiam/organizations/RoleAssignmentDeleter.java index 43cc107708..514bacadf6 100644 --- a/src/main/java/com/twilio/rest/previewiam/organizations/RoleAssignmentDeleter.java +++ b/src/main/java/com/twilio/rest/previewiam/organizations/RoleAssignmentDeleter.java @@ -14,15 +14,15 @@ package com.twilio.rest.previewiam.organizations; -import com.twilio.base.bearertoken.Deleter; +import com.twilio.base.Deleter; import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; import com.twilio.http.HttpMethod; import com.twilio.http.Response; -import com.twilio.http.bearertoken.BearerTokenRequest; -import com.twilio.http.bearertoken.BearerTokenTwilioRestClient; +import com.twilio.http.Request; +import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; public class RoleAssignmentDeleter extends Deleter { @@ -39,7 +39,7 @@ public RoleAssignmentDeleter( } @Override - public boolean delete(final BearerTokenTwilioRestClient client) { + public boolean delete(final TwilioRestClient client) { String path = "/Organizations/{OrganizationSid}/RoleAssignments/{RoleAssignmentSid}"; @@ -54,7 +54,7 @@ public boolean delete(final BearerTokenTwilioRestClient client) { this.pathRoleAssignmentSid.toString() ); - BearerTokenRequest request = new BearerTokenRequest( + Request request = new Request( HttpMethod.DELETE, Domains.PREVIEWIAM.toString(), path @@ -67,7 +67,7 @@ public boolean delete(final BearerTokenTwilioRestClient client) { "RoleAssignment delete failed: Unable to connect to server" ); } else if ( - !BearerTokenTwilioRestClient.SUCCESS.test(response.getStatusCode()) + !TwilioRestClient.SUCCESS.test(response.getStatusCode()) ) { RestException restException = RestException.fromJson( response.getStream(), diff --git a/src/main/java/com/twilio/rest/previewiam/organizations/RoleAssignmentReader.java b/src/main/java/com/twilio/rest/previewiam/organizations/RoleAssignmentReader.java index 05bb8e8b81..e10fca0991 100644 --- a/src/main/java/com/twilio/rest/previewiam/organizations/RoleAssignmentReader.java +++ b/src/main/java/com/twilio/rest/previewiam/organizations/RoleAssignmentReader.java @@ -14,17 +14,17 @@ package com.twilio.rest.previewiam.organizations; -import com.twilio.base.bearertoken.Page; -import com.twilio.base.bearertoken.Reader; -import com.twilio.base.bearertoken.ResourceSet; +import com.twilio.base.Page; +import com.twilio.base.Reader; +import com.twilio.base.ResourceSet; import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; import com.twilio.http.HttpMethod; import com.twilio.http.Response; -import com.twilio.http.bearertoken.BearerTokenRequest; -import com.twilio.http.bearertoken.BearerTokenTwilioRestClient; +import com.twilio.http.Request; +import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; public class RoleAssignmentReader extends Reader { @@ -55,13 +55,13 @@ public RoleAssignmentReader setScope(final String scope) { @Override public ResourceSet read( - final BearerTokenTwilioRestClient client + final TwilioRestClient client ) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage( - final BearerTokenTwilioRestClient client + final TwilioRestClient client ) { String path = "/Organizations/{OrganizationSid}/RoleAssignments"; path = @@ -70,7 +70,7 @@ public Page firstPage( this.pathOrganizationSid.toString() ); - BearerTokenRequest request = new BearerTokenRequest( + Request request = new Request( HttpMethod.GET, Domains.PREVIEWIAM.toString(), path @@ -82,8 +82,8 @@ public Page firstPage( } private Page pageForRequest( - final BearerTokenTwilioRestClient client, - final BearerTokenRequest request + final TwilioRestClient client, + final Request request ) { Response response = client.request(request); @@ -92,7 +92,7 @@ private Page pageForRequest( "RoleAssignment read failed: Unable to connect to server" ); } else if ( - !BearerTokenTwilioRestClient.SUCCESS.test(response.getStatusCode()) + !TwilioRestClient.SUCCESS.test(response.getStatusCode()) ) { RestException restException = RestException.fromJson( response.getStream(), @@ -118,9 +118,9 @@ private Page pageForRequest( @Override public Page previousPage( final Page page, - final BearerTokenTwilioRestClient client + final TwilioRestClient client ) { - BearerTokenRequest request = new BearerTokenRequest( + Request request = new Request( HttpMethod.GET, page.getPreviousPageUrl(Domains.PREVIEWIAM.toString()) ); @@ -130,9 +130,9 @@ public Page previousPage( @Override public Page nextPage( final Page page, - final BearerTokenTwilioRestClient client + final TwilioRestClient client ) { - BearerTokenRequest request = new BearerTokenRequest( + Request request = new Request( HttpMethod.GET, page.getNextPageUrl(Domains.PREVIEWIAM.toString()) ); @@ -142,9 +142,9 @@ public Page nextPage( @Override public Page getPage( final String targetUrl, - final BearerTokenTwilioRestClient client + final TwilioRestClient client ) { - BearerTokenRequest request = new BearerTokenRequest( + Request request = new Request( HttpMethod.GET, targetUrl ); @@ -152,7 +152,7 @@ public Page getPage( return pageForRequest(client, request); } - private void addQueryParams(final BearerTokenRequest request) { + private void addQueryParams(final Request request) { if (pageSize != null) { request.addQueryParam("PageSize", pageSize.toString()); } diff --git a/src/main/java/com/twilio/rest/previewiam/organizations/User.java b/src/main/java/com/twilio/rest/previewiam/organizations/User.java index 2e3a501701..94359dbbbf 100644 --- a/src/main/java/com/twilio/rest/previewiam/organizations/User.java +++ b/src/main/java/com/twilio/rest/previewiam/organizations/User.java @@ -22,7 +22,7 @@ import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; -import com.twilio.base.bearertoken.Resource; +import com.twilio.base.Resource; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import java.io.IOException; diff --git a/src/main/java/com/twilio/rest/previewiam/organizations/UserCreator.java b/src/main/java/com/twilio/rest/previewiam/organizations/UserCreator.java index 92d390ed29..e768088a50 100644 --- a/src/main/java/com/twilio/rest/previewiam/organizations/UserCreator.java +++ b/src/main/java/com/twilio/rest/previewiam/organizations/UserCreator.java @@ -15,15 +15,15 @@ package com.twilio.rest.previewiam.organizations; import com.fasterxml.jackson.databind.ObjectMapper; -import com.twilio.base.bearertoken.Creator; +import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; import com.twilio.http.HttpMethod; import com.twilio.http.Response; -import com.twilio.http.bearertoken.BearerTokenRequest; -import com.twilio.http.bearertoken.BearerTokenTwilioRestClient; +import com.twilio.http.TwilioRestClient; +import com.twilio.http.Request; import com.twilio.rest.Domains; public class UserCreator extends Creator { @@ -45,7 +45,7 @@ public UserCreator setScimUser(final User.ScimUser scimUser) { } @Override - public User create(final BearerTokenTwilioRestClient client) { + public User create(final TwilioRestClient client) { String path = "/Organizations/{OrganizationSid}/scim/Users"; path = @@ -55,7 +55,7 @@ public User create(final BearerTokenTwilioRestClient client) { ); path = path.replace("{" + "ScimUser" + "}", this.scimUser.toString()); - BearerTokenRequest request = new BearerTokenRequest( + Request request = new Request( HttpMethod.POST, Domains.PREVIEWIAM.toString(), path @@ -68,7 +68,7 @@ public User create(final BearerTokenTwilioRestClient client) { "User creation failed: Unable to connect to server" ); } else if ( - !BearerTokenTwilioRestClient.SUCCESS.test(response.getStatusCode()) + !TwilioRestClient.SUCCESS.test(response.getStatusCode()) ) { RestException restException = RestException.fromJson( response.getStream(), @@ -87,8 +87,8 @@ public User create(final BearerTokenTwilioRestClient client) { } private void addPostParams( - final BearerTokenRequest request, - BearerTokenTwilioRestClient client + final Request request, + TwilioRestClient client ) { ObjectMapper objectMapper = client.getObjectMapper(); if (scimUser != null) { diff --git a/src/main/java/com/twilio/rest/previewiam/organizations/UserDeleter.java b/src/main/java/com/twilio/rest/previewiam/organizations/UserDeleter.java index 6f44db1c69..dcb8c56787 100644 --- a/src/main/java/com/twilio/rest/previewiam/organizations/UserDeleter.java +++ b/src/main/java/com/twilio/rest/previewiam/organizations/UserDeleter.java @@ -14,15 +14,15 @@ package com.twilio.rest.previewiam.organizations; -import com.twilio.base.bearertoken.Deleter; +import com.twilio.base.Deleter; import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; import com.twilio.http.HttpMethod; import com.twilio.http.Response; -import com.twilio.http.bearertoken.BearerTokenRequest; -import com.twilio.http.bearertoken.BearerTokenTwilioRestClient; +import com.twilio.http.Request; +import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; public class UserDeleter extends Deleter { @@ -39,7 +39,7 @@ public UserDeleter( } @Override - public boolean delete(final BearerTokenTwilioRestClient client) { + public boolean delete(final TwilioRestClient client) { String path = "/Organizations/{OrganizationSid}/scim/Users/{UserSid}"; path = @@ -49,7 +49,7 @@ public boolean delete(final BearerTokenTwilioRestClient client) { ); path = path.replace("{" + "UserSid" + "}", this.pathUserSid.toString()); - BearerTokenRequest request = new BearerTokenRequest( + Request request = new Request( HttpMethod.DELETE, Domains.PREVIEWIAM.toString(), path @@ -62,7 +62,7 @@ public boolean delete(final BearerTokenTwilioRestClient client) { "User delete failed: Unable to connect to server" ); } else if ( - !BearerTokenTwilioRestClient.SUCCESS.test(response.getStatusCode()) + !TwilioRestClient.SUCCESS.test(response.getStatusCode()) ) { RestException restException = RestException.fromJson( response.getStream(), diff --git a/src/main/java/com/twilio/rest/previewiam/organizations/UserFetcher.java b/src/main/java/com/twilio/rest/previewiam/organizations/UserFetcher.java index 3abc3e86eb..0270ac88dc 100644 --- a/src/main/java/com/twilio/rest/previewiam/organizations/UserFetcher.java +++ b/src/main/java/com/twilio/rest/previewiam/organizations/UserFetcher.java @@ -14,15 +14,15 @@ package com.twilio.rest.previewiam.organizations; -import com.twilio.base.bearertoken.Fetcher; +import com.twilio.base.Fetcher; import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; import com.twilio.http.HttpMethod; import com.twilio.http.Response; -import com.twilio.http.bearertoken.BearerTokenRequest; -import com.twilio.http.bearertoken.BearerTokenTwilioRestClient; +import com.twilio.http.Request; +import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; public class UserFetcher extends Fetcher { @@ -39,7 +39,7 @@ public UserFetcher( } @Override - public User fetch(final BearerTokenTwilioRestClient client) { + public User fetch(final TwilioRestClient client) { String path = "/Organizations/{OrganizationSid}/scim/Users/{UserSid}"; path = @@ -49,7 +49,7 @@ public User fetch(final BearerTokenTwilioRestClient client) { ); path = path.replace("{" + "UserSid" + "}", this.pathUserSid.toString()); - BearerTokenRequest request = new BearerTokenRequest( + Request request = new Request( HttpMethod.GET, Domains.PREVIEWIAM.toString(), path @@ -62,7 +62,7 @@ public User fetch(final BearerTokenTwilioRestClient client) { "User fetch failed: Unable to connect to server" ); } else if ( - !BearerTokenTwilioRestClient.SUCCESS.test(response.getStatusCode()) + !TwilioRestClient.SUCCESS.test(response.getStatusCode()) ) { RestException restException = RestException.fromJson( response.getStream(), diff --git a/src/main/java/com/twilio/rest/previewiam/organizations/UserReader.java b/src/main/java/com/twilio/rest/previewiam/organizations/UserReader.java index 2ebdb45da6..c6bb6a57eb 100644 --- a/src/main/java/com/twilio/rest/previewiam/organizations/UserReader.java +++ b/src/main/java/com/twilio/rest/previewiam/organizations/UserReader.java @@ -14,17 +14,17 @@ package com.twilio.rest.previewiam.organizations; -import com.twilio.base.bearertoken.Page; -import com.twilio.base.bearertoken.Reader; -import com.twilio.base.bearertoken.ResourceSet; +import com.twilio.base.Page; +import com.twilio.base.Reader; +import com.twilio.base.ResourceSet; import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; import com.twilio.http.HttpMethod; import com.twilio.http.Response; -import com.twilio.http.bearertoken.BearerTokenRequest; -import com.twilio.http.bearertoken.BearerTokenTwilioRestClient; +import com.twilio.http.Request; +import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; public class UserReader extends Reader { @@ -42,11 +42,11 @@ public UserReader setFilter(final String filter) { } @Override - public ResourceSet read(final BearerTokenTwilioRestClient client) { + public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } - public Page firstPage(final BearerTokenTwilioRestClient client) { + public Page firstPage(final TwilioRestClient client) { String path = "/Organizations/{OrganizationSid}/scim/Users"; path = path.replace( @@ -54,7 +54,7 @@ public Page firstPage(final BearerTokenTwilioRestClient client) { this.pathOrganizationSid.toString() ); - BearerTokenRequest request = new BearerTokenRequest( + Request request = new Request( HttpMethod.GET, Domains.PREVIEWIAM.toString(), path @@ -66,8 +66,8 @@ public Page firstPage(final BearerTokenTwilioRestClient client) { } private Page pageForRequest( - final BearerTokenTwilioRestClient client, - final BearerTokenRequest request + final TwilioRestClient client, + final Request request ) { Response response = client.request(request); @@ -76,7 +76,7 @@ private Page pageForRequest( "User read failed: Unable to connect to server" ); } else if ( - !BearerTokenTwilioRestClient.SUCCESS.test(response.getStatusCode()) + !TwilioRestClient.SUCCESS.test(response.getStatusCode()) ) { RestException restException = RestException.fromJson( response.getStream(), @@ -102,9 +102,9 @@ private Page pageForRequest( @Override public Page previousPage( final Page page, - final BearerTokenTwilioRestClient client + final TwilioRestClient client ) { - BearerTokenRequest request = new BearerTokenRequest( + Request request = new Request( HttpMethod.GET, page.getPreviousPageUrl(Domains.PREVIEWIAM.toString()) ); @@ -114,9 +114,9 @@ public Page previousPage( @Override public Page nextPage( final Page page, - final BearerTokenTwilioRestClient client + final TwilioRestClient client ) { - BearerTokenRequest request = new BearerTokenRequest( + Request request = new Request( HttpMethod.GET, page.getNextPageUrl(Domains.PREVIEWIAM.toString()) ); @@ -126,9 +126,9 @@ public Page nextPage( @Override public Page getPage( final String targetUrl, - final BearerTokenTwilioRestClient client + final TwilioRestClient client ) { - BearerTokenRequest request = new BearerTokenRequest( + Request request = new Request( HttpMethod.GET, targetUrl ); @@ -136,7 +136,7 @@ public Page getPage( return pageForRequest(client, request); } - private void addQueryParams(final BearerTokenRequest request) { + private void addQueryParams(final Request request) { if (filter != null) { request.addQueryParam("filter", filter); } diff --git a/src/main/java/com/twilio/rest/previewiam/organizations/UserUpdater.java b/src/main/java/com/twilio/rest/previewiam/organizations/UserUpdater.java index b68b8557f0..9b3c2a0d4b 100644 --- a/src/main/java/com/twilio/rest/previewiam/organizations/UserUpdater.java +++ b/src/main/java/com/twilio/rest/previewiam/organizations/UserUpdater.java @@ -15,15 +15,15 @@ package com.twilio.rest.previewiam.organizations; import com.fasterxml.jackson.databind.ObjectMapper; -import com.twilio.base.bearertoken.Updater; +import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; import com.twilio.http.HttpMethod; import com.twilio.http.Response; -import com.twilio.http.bearertoken.BearerTokenRequest; -import com.twilio.http.bearertoken.BearerTokenTwilioRestClient; +import com.twilio.http.Request; +import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; public class UserUpdater extends Updater { @@ -54,7 +54,7 @@ public UserUpdater setIfMatch(final String ifMatch) { } @Override - public User update(final BearerTokenTwilioRestClient client) { + public User update(final TwilioRestClient client) { String path = "/Organizations/{OrganizationSid}/scim/Users/{UserSid}"; path = @@ -65,7 +65,7 @@ public User update(final BearerTokenTwilioRestClient client) { path = path.replace("{" + "UserSid" + "}", this.pathUserSid.toString()); path = path.replace("{" + "ScimUser" + "}", this.scimUser.toString()); - BearerTokenRequest request = new BearerTokenRequest( + Request request = new Request( HttpMethod.PUT, Domains.PREVIEWIAM.toString(), path @@ -79,7 +79,7 @@ public User update(final BearerTokenTwilioRestClient client) { "User update failed: Unable to connect to server" ); } else if ( - !BearerTokenTwilioRestClient.SUCCESS.test(response.getStatusCode()) + !TwilioRestClient.SUCCESS.test(response.getStatusCode()) ) { RestException restException = RestException.fromJson( response.getStream(), @@ -98,8 +98,8 @@ public User update(final BearerTokenTwilioRestClient client) { } private void addPostParams( - final BearerTokenRequest request, - BearerTokenTwilioRestClient client + final Request request, + TwilioRestClient client ) { ObjectMapper objectMapper = client.getObjectMapper(); if (scimUser != null) { @@ -107,7 +107,7 @@ private void addPostParams( } } - private void addHeaderParams(final BearerTokenRequest request) { + private void addHeaderParams(final Request request) { if (ifMatch != null) { request.addHeaderParam("If-Match", ifMatch); } diff --git a/src/test/java/com/twilio/ClusterTest.java b/src/test/java/com/twilio/ClusterTest.java index 50062a5486..e21df98c3a 100644 --- a/src/test/java/com/twilio/ClusterTest.java +++ b/src/test/java/com/twilio/ClusterTest.java @@ -1,10 +1,12 @@ package com.twilio; +import com.twilio.auth_strategy.TokenAuthStrategy; import com.twilio.base.Page; -import com.twilio.base.bearertoken.ResourceSet; -import com.twilio.credential.ClientCredentialProvider; +import com.twilio.base.ResourceSet; import com.twilio.http.CustomHttpClient; import com.twilio.http.TwilioRestClient; +import com.twilio.http.bearertoken.OrgsTokenManager; +import com.twilio.http.bearertoken.TokenManager; import com.twilio.rest.api.v2010.account.IncomingPhoneNumber; import com.twilio.rest.api.v2010.account.IncomingPhoneNumberReader; import com.twilio.rest.api.v2010.account.Message; @@ -57,8 +59,7 @@ public void setUp() { orgsClientId = System.getenv("TWILIO_ORGS_CLIENT_ID"); orgsClientSecret = System.getenv("TWILIO_ORGS_CLIENT_SECRET"); organisationSid = System.getenv("TWILIO_ORG_SID"); - TwilioOrgsTokenAuth.init(grantType, orgsClientId, orgsClientSecret); - + clientId = System.getenv("TWILIO_CLIENT_ID"); clientSecret = System.getenv("TWILIO_CLIENT_SECRET"); messageSid = System.getenv("TWILIO_MESSAGE_SID"); @@ -140,19 +141,25 @@ public void testListParams() { @Test public void testOrgsApi(){ + //Twilio.init(new OrgsClientCredentialProvider(orgsClientId, orgsClientSecret)); + + TokenManager tokenManager = new OrgsTokenManager("client_credentials", orgsClientId, orgsClientSecret); + TokenAuthStrategy tokenAuthStrategy = new TokenAuthStrategy(tokenManager); + TwilioRestClient client = new TwilioRestClient.Builder(tokenAuthStrategy) + .build(); //Fetching the account information - ResourceSet accountSet = Account.reader(organisationSid).read(); + ResourceSet accountSet = Account.reader(organisationSid).read(client); String accountSid = accountSet.iterator().next().getAccountSid(); assertNotNull(accountSid); //Fetching specific account - Account account = Account.fetcher(organisationSid, accountSid).fetch(); + Account account = Account.fetcher(organisationSid, accountSid).fetch(client); assertNotNull(account.getAccountSid()); //Fetching users of this organisation ResourceSet - userSet = com.twilio.rest.previewiam.organizations.User.reader(organisationSid).read(); + userSet = com.twilio.rest.previewiam.organizations.User.reader(organisationSid).read(client); assertNotNull(userSet); String userId = userSet.iterator().next().getId().toString(); assertNotNull(userId); diff --git a/src/test/java/com/twilio/http/bearerToken/BearerTokenNetworkHttpClientTest.java b/src/test/java/com/twilio/http/bearerToken/BearerTokenNetworkHttpClientTest.java deleted file mode 100644 index 41094c2ff6..0000000000 --- a/src/test/java/com/twilio/http/bearerToken/BearerTokenNetworkHttpClientTest.java +++ /dev/null @@ -1,213 +0,0 @@ -package com.twilio.http.bearerToken; - -import com.twilio.constant.EnumConstants; -import com.twilio.exception.ApiException; -import com.twilio.http.HttpMethod; -import com.twilio.http.Response; -import com.twilio.http.bearertoken.BearerTokenNetworkHttpClient; -import com.twilio.http.bearertoken.BearerTokenRequest; -import org.apache.hc.client5.http.impl.classic.CloseableHttpClient; -import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse; -import org.apache.hc.client5.http.impl.classic.HttpClientBuilder; -import org.apache.hc.core5.http.HttpEntity; -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.mockito.Spy; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.net.URL; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -public class BearerTokenNetworkHttpClientTest { - - private BearerTokenNetworkHttpClient client; - - @Mock - private BearerTokenRequest mockRequest; - - @Spy - private HttpClientBuilder mockBuilder; - - @Mock - private CloseableHttpClient mockClient; - - @Mock - private CloseableHttpResponse mockResponse; - - @Mock - private HttpEntity mockEntity; - - @Before - public void setUp() { - MockitoAnnotations.openMocks(this); - doReturn(mockClient).when(mockBuilder).build(); - client = new BearerTokenNetworkHttpClient(mockBuilder); - } - - private void setup( - final int statusCode, - final String content, - final HttpMethod method, - final Boolean requiresAuthentication - ) throws IOException { - final InputStream stream = new ByteArrayInputStream(content.getBytes("UTF-8")); - - when(mockRequest.getMethod()).thenReturn(method); - when(mockRequest.constructURL()).thenReturn(new URL("http://foo.com/hello")); - when(mockRequest.requiresAuthentication()).thenReturn(requiresAuthentication); - when(mockRequest.getAuthString()).thenReturn("Bearer token123"); - when(mockRequest.getContentType()).thenReturn(EnumConstants.ContentType.FORM_URLENCODED); - when(mockClient.execute(any())).thenReturn(mockResponse); - when(mockEntity.isRepeatable()).thenReturn(true); - when(mockEntity.getContentLength()).thenReturn(1L); - when(mockEntity.getContent()).thenReturn(stream); - when(mockResponse.getEntity()).thenReturn(mockEntity); - when(mockResponse.getCode()).thenReturn(statusCode); - } - - @Test - public void testGet() throws IOException { - setup(200, "success", HttpMethod.GET, false); - - Response resp = client.makeRequest(mockRequest); - - assertEquals(200, resp.getStatusCode()); - assertEquals("success", resp.getContent()); - } - - @Test - public void testGetWithAuthentication() throws IOException { - setup(200, "authenticated", HttpMethod.GET, true); - - Response resp = client.makeRequest(mockRequest); - - assertEquals(200, resp.getStatusCode()); - assertEquals("authenticated", resp.getContent()); - } - - @Test - public void testPost() throws IOException { - setup(201, "created", HttpMethod.POST, false); - - Response resp = client.makeRequest(mockRequest); - - assertEquals(201, resp.getStatusCode()); - assertEquals("created", resp.getContent()); - } - - @Test - public void testJsonPost() throws IOException { - setup(201, "created", HttpMethod.POST, false); - when(mockRequest.getContentType()).thenReturn(EnumConstants.ContentType.JSON); - String body = "{\"name\":\"value\"}"; - when(mockRequest.getBody()).thenReturn(body); - - Response resp = client.makeRequest(mockRequest); - - assertEquals(201, resp.getStatusCode()); - assertEquals("created", resp.getContent()); - } - - @Test - public void testFormUrlEncodedPost() throws IOException { - setup(201, "form-urlencoded", HttpMethod.POST, false); - - // Set up post parameters - Map> postParams = new HashMap<>(); - postParams.put("name", Arrays.asList("John Doe")); - postParams.put("tags", Arrays.asList("customer", "premium")); - when(mockRequest.getPostParams()).thenReturn(postParams); - - Response resp = client.makeRequest(mockRequest); - - assertEquals(201, resp.getStatusCode()); - assertEquals("form-urlencoded", resp.getContent()); - } - - @Test - public void testPut() throws IOException { - setup(200, "updated", HttpMethod.PUT, false); - - Response resp = client.makeRequest(mockRequest); - - assertEquals(200, resp.getStatusCode()); - assertEquals("updated", resp.getContent()); - } - - @Test - public void testPatch() throws IOException { - setup(200, "patched", HttpMethod.PATCH, false); - - Response resp = client.makeRequest(mockRequest); - - assertEquals(200, resp.getStatusCode()); - assertEquals("patched", resp.getContent()); - } - - @Test - public void testDelete() throws IOException { - setup(204, "", HttpMethod.DELETE, false); - - Response resp = client.makeRequest(mockRequest); - - assertEquals(204, resp.getStatusCode()); - assertEquals("", resp.getContent()); - } - - @Test - public void testWithCustomHeaders() throws IOException { - setup(200, "headers", HttpMethod.GET, false); - - Map> headers = new HashMap<>(); - headers.put("X-Custom-Header", Arrays.asList("CustomValue")); - headers.put("Accept-Language", Arrays.asList("en-US")); - when(mockRequest.getHeaderParams()).thenReturn(headers); - - Response resp = client.makeRequest(mockRequest); - - assertEquals(200, resp.getStatusCode()); - assertEquals("headers", resp.getContent()); - } - - @Test(expected = ApiException.class) - public void testIOException() throws IOException { - when(mockRequest.getMethod()).thenReturn(HttpMethod.GET); - when(mockRequest.constructURL()).thenReturn(new URL("http://foo.com/hello")); - when(mockRequest.requiresAuthentication()).thenReturn(false); - when(mockClient.execute(any())).thenThrow(new IOException("Connection error")); - - client.makeRequest(mockRequest); - } - - @Test - public void testReliableRequest() { - BearerTokenRequest request = mock(BearerTokenRequest.class); - when(request.getMethod()).thenReturn(HttpMethod.GET); - - BearerTokenNetworkHttpClient clientSpy = spy(client); - doReturn(new Response("", 204)).when(clientSpy).makeRequest(request); - - clientSpy.reliableRequest(request); - - assertNotNull(clientSpy.getLastRequest()); - assertNotNull(clientSpy.getLastResponse()); - } -} From 15ca86044c13c140989ff88e5c198adf6b784c05 Mon Sep 17 00:00:00 2001 From: Shubham Date: Wed, 17 Sep 2025 02:52:43 +0530 Subject: [PATCH 21/32] chore: Revert "fix: Reuse twiliorestclient for orgs api" (#898) --- README.md | 4 +- examples/BearerTokenAuthentication.md | 26 ++ examples/FetchMessageUsingOAuth.md | 21 ++ examples/OrgsAPIExample.md | 34 --- examples/PublicOAuthExample.md | 35 --- .../java/com/twilio/TwilioOrgsTokenAuth.java | 106 +++++++ src/main/java/com/twilio/base/Page.java | 6 +- .../com/twilio/base/bearertoken/Creator.java | 50 ++++ .../com/twilio/base/bearertoken/Deleter.java | 51 ++++ .../com/twilio/base/bearertoken/Fetcher.java | 50 ++++ .../com/twilio/base/bearertoken/Page.java | 270 ++++++++++++++++++ .../com/twilio/base/bearertoken/Reader.java | 156 ++++++++++ .../com/twilio/base/bearertoken/Resource.java | 9 + .../twilio/base/bearertoken/ResourceSet.java | 138 +++++++++ .../com/twilio/base/bearertoken/Updater.java | 50 ++++ .../orgs/OrgsClientCredentialProvider.java | 62 +--- .../com/twilio/http/NetworkHttpClient.java | 2 +- .../bearertoken/BearerTokenHttpClient.java | 108 +++++++ .../BearerTokenNetworkHttpClient.java | 181 ++++++++++++ .../http/bearertoken/BearerTokenRequest.java | 38 +++ .../BearerTokenTwilioRestClient.java | 186 ++++++++++++ .../previewiam/organizations/Account.java | 2 +- .../organizations/AccountFetcher.java | 12 +- .../organizations/AccountReader.java | 36 +-- .../organizations/RoleAssignment.java | 2 +- .../organizations/RoleAssignmentCreator.java | 16 +- .../organizations/RoleAssignmentDeleter.java | 12 +- .../organizations/RoleAssignmentReader.java | 36 +-- .../rest/previewiam/organizations/User.java | 2 +- .../previewiam/organizations/UserCreator.java | 16 +- .../previewiam/organizations/UserDeleter.java | 12 +- .../previewiam/organizations/UserFetcher.java | 12 +- .../previewiam/organizations/UserReader.java | 36 +-- .../previewiam/organizations/UserUpdater.java | 18 +- src/test/java/com/twilio/ClusterTest.java | 21 +- .../BearerTokenNetworkHttpClientTest.java | 213 ++++++++++++++ 36 files changed, 1772 insertions(+), 257 deletions(-) create mode 100644 examples/BearerTokenAuthentication.md create mode 100644 examples/FetchMessageUsingOAuth.md delete mode 100644 examples/OrgsAPIExample.md delete mode 100644 examples/PublicOAuthExample.md create mode 100644 src/main/java/com/twilio/TwilioOrgsTokenAuth.java create mode 100644 src/main/java/com/twilio/base/bearertoken/Creator.java create mode 100644 src/main/java/com/twilio/base/bearertoken/Deleter.java create mode 100644 src/main/java/com/twilio/base/bearertoken/Fetcher.java create mode 100644 src/main/java/com/twilio/base/bearertoken/Page.java create mode 100644 src/main/java/com/twilio/base/bearertoken/Reader.java create mode 100644 src/main/java/com/twilio/base/bearertoken/Resource.java create mode 100644 src/main/java/com/twilio/base/bearertoken/ResourceSet.java create mode 100644 src/main/java/com/twilio/base/bearertoken/Updater.java create mode 100644 src/main/java/com/twilio/http/bearertoken/BearerTokenHttpClient.java create mode 100644 src/main/java/com/twilio/http/bearertoken/BearerTokenNetworkHttpClient.java create mode 100644 src/main/java/com/twilio/http/bearertoken/BearerTokenRequest.java create mode 100644 src/main/java/com/twilio/http/bearertoken/BearerTokenTwilioRestClient.java create mode 100644 src/test/java/com/twilio/http/bearerToken/BearerTokenNetworkHttpClientTest.java diff --git a/README.md b/README.md index c715b3a2fb..c63cb6461a 100644 --- a/README.md +++ b/README.md @@ -221,8 +221,8 @@ public class Example { We are introducing Client Credentials Flow-based OAuth 2.0 authentication. This feature is currently in `beta` and its implementation is subject to change. -- API examples [here](https://github.com/twilio/twilio-java/blob/main/examples/PublicOAuthExample.md) -- Organisation API examples [here](https://github.com/twilio/twilio-java/blob/main/examples/OrgsAPIExample.md) +- API examples [here](https://github.com/twilio/twilio-java/blob/main/examples/FetchMessageUsingOAuth.md) +- Organisation API examples [here](https://github.com/twilio/twilio-java/blob/main/examples/BearerTokenAuthentication.md) ### Iterate through records diff --git a/examples/BearerTokenAuthentication.md b/examples/BearerTokenAuthentication.md new file mode 100644 index 0000000000..2618436b32 --- /dev/null +++ b/examples/BearerTokenAuthentication.md @@ -0,0 +1,26 @@ + class BearerTokenAuthenticationExamples { + public static void main { + + private static final String GRANT_TYPE = "grant_type_to_be_used"; + private static final String CLIENT_SID = + "client_id_of_the_organization"; + private static final String CLIENT_SECRET = "client_secret_of_organization"; + private static final String ORGANISATION_ID = "id_of_the_organization"; + + //Getting access token - Method #1 + TwilioOrgsTokenAuth.init(GRANT_TYPE, CLIENT_ID, CLIENT_SECRET); + + //Getting access token - Method #2 + //To provide custom token manager implementation + //Need not call init method if customer token manager is passed + //TwilioOrgsTokenAuth.setTokenManager(new CustomTokenManagerImpl(GRANT_TYPE, CLIENT_ID, CLIENT_SECRET)); + + fetchAccountDetails(); + } + + private static void fetchAccountDetails() { + ResourceSet accountSet = Account.reader(ORGANISATION_ID).read(); + String accountSid = accountSet.iterator().next().getAccountSid(); + System.out.println(accountSid); + } + } \ No newline at end of file diff --git a/examples/FetchMessageUsingOAuth.md b/examples/FetchMessageUsingOAuth.md new file mode 100644 index 0000000000..ec667f1ab0 --- /dev/null +++ b/examples/FetchMessageUsingOAuth.md @@ -0,0 +1,21 @@ +``` +import com.twilio.Twilio; +import com.twilio.credential.ClientCredentialProvider; +import com.twilio.rest.api.v2010.account.Message; + +public class FetchMessageUsingOAuth { + public static void main(String[] args) { + String clientId = "YOUR_CLIENT_ID"; + String clientSecret = "YOUR_CLIENT_SECRET"; + String accountSid = "YOUR_ACCOUNT_SID"; + Twilio.init(new ClientCredentialProvider(clientId, clientSecret), accountSid); + /* + Or use the following if accountSid is not required as a path parameter for an API or when setting accountSid in the API. + Twilio.init(new ClientCredentialProvider(clientId, clientSecret)); + */ + String messageSid = "YOUR_MESSAGE_SID"; + Message message = Message.fetcher(messageSid).fetch(); + } +} +``` + diff --git a/examples/OrgsAPIExample.md b/examples/OrgsAPIExample.md deleted file mode 100644 index b4511f88bc..0000000000 --- a/examples/OrgsAPIExample.md +++ /dev/null @@ -1,34 +0,0 @@ - class OrgsAPIExample { - public static void main { - - private static final String GRANT_TYPE = "grant_type_to_be_used"; - private static final String CLIENT_SID = - "client_id_of_the_organization"; - private static final String CLIENT_SECRET = "client_secret_of_organization"; - private static final String ORGANISATION_ID = "id_of_the_organization"; - - //Getting access token - Method #1 - Twilio.init(new OrgsClientCredentialProvider(CLIENT_SID, CLIENT_SECRET)); - fetchAccountDetails(); - - - //Scenario: 2 If in case one doesn't want to change the existing stored credential - // Pass Custom TwilioRestClient - // TokenManager tokenManager = new OrgsTokenManager(GRANT_TYPE, CLIENT_SID, CLIENT_SECRET); - // TokenAuthStrategy tokenAuthStrategy = new TokenAuthStrategy(tokenManager); - // TwilioRestClient client = new TwilioRestClient.Builder(tokenAuthStrategy).build(); - // fetchAccountDetailsWithClient(client); - } - - private static void fetchAccountDetails() { - ResourceSet accountSet = Account.reader(ORGANISATION_ID).read(); - String accountSid = accountSet.iterator().next().getAccountSid(); - System.out.println(accountSid); - } - - private static void fetchAccountDetailsWithClient(TwilioRestClient client) { - ResourceSet accountSet = Account.reader(ORGANISATION_ID).read(client); - String accountSid = accountSet.iterator().next().getAccountSid(); - System.out.println(accountSid); - } - } \ No newline at end of file diff --git a/examples/PublicOAuthExample.md b/examples/PublicOAuthExample.md deleted file mode 100644 index dce5027e9a..0000000000 --- a/examples/PublicOAuthExample.md +++ /dev/null @@ -1,35 +0,0 @@ -``` -class PublicOAuthExample { - public static void main { - - private static final String GRANT_TYPE = "grant_type_to_be_used"; - private static final String OAUTH_CLIENT_SID = "client_id"; - private static final String OAUTH_CLIENT_SECRET = "client_secret"; - private static final String ACCOUNT_SID = "account_sid"; - private static final String MESSAGE_SID = "message_sid"; - - //Getting access token - Method #1 - Twilio.init(new ClientCredentialProvider(OAUTH_CLIENT_SID, OAUTH_CLIENT_SECRET), ACCOUNT_SID); - fetchMessage(MESSAGE_SID); - - - //Scenario: 2 If in case one doesn't want to change the existing stored credential - // Pass Custom TwilioRestClient - // TokenManager tokenManager = new ApiTokenManager(GRANT_TYPE, OAUTH_CLIENT_SID, OAUTH_CLIENT_SECRET); - // TokenAuthStrategy tokenAuthStrategy = new TokenAuthStrategy(tokenManager); - // TwilioRestClient client = new TwilioRestClient.Builder(tokenAuthStrategy).accountSid(ACCOUNT_SID).build(); - // fetchMessageWithClient(MESSAGE_SID, client); - } - - public static void fetchMessage(String sid) { - Message message = Message.fetcher(sid).fetch(); - System.out.println("Fetched Message SID: " + message.getSid()); - } - - public static void fetchMessageWithClient(String sid, TwilioRestClient client) { - Message message = Message.fetcher(sid).fetch(client); - System.out.println("Fetched Message SID: " + message.getSid()); - } -} -``` - diff --git a/src/main/java/com/twilio/TwilioOrgsTokenAuth.java b/src/main/java/com/twilio/TwilioOrgsTokenAuth.java new file mode 100644 index 0000000000..9b28d0b06f --- /dev/null +++ b/src/main/java/com/twilio/TwilioOrgsTokenAuth.java @@ -0,0 +1,106 @@ +package com.twilio; + +import com.twilio.annotations.Beta; +import com.twilio.exception.AuthenticationException; +import com.twilio.http.bearertoken.BearerTokenTwilioRestClient; +import lombok.Getter; +import lombok.Setter; + +import java.util.List; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import com.twilio.http.bearertoken.TokenManager; +import com.twilio.http.bearertoken.OrgsTokenManager; + +@Beta +public class TwilioOrgsTokenAuth { + private static String accessToken; + @Getter + private static List userAgentExtensions; + private static String region = System.getenv("TWILIO_REGION"); + private static String edge = System.getenv("TWILIO_EDGE"); + private static volatile BearerTokenTwilioRestClient restClient; + @Getter @Setter + private static TokenManager tokenManager; + + private static volatile ExecutorService executorService; + + private TwilioOrgsTokenAuth() { + } + + public static synchronized void init(String grantType, String clientId, String clientSecret) { + validateAuthCredentials(grantType, clientId, clientSecret); + tokenManager = new OrgsTokenManager(grantType, clientId, clientSecret); + } + public static synchronized void init(String grantType, String clientId, String clientSecret, String code, String redirectUri, String audience, String refreshToken, String scope) { + validateAuthCredentials(grantType, clientId, clientSecret); + tokenManager = new OrgsTokenManager(grantType, clientId, clientSecret, code, redirectUri, audience, refreshToken, scope); + } + + private static void validateAuthCredentials(String grantType, String clientId, String clientSecret){ + if (grantType == null) { + throw new AuthenticationException("Grant Type cannot be null"); + } + if (clientId == null) { + throw new AuthenticationException("Client Id cannot be null"); + } + if (clientSecret == null) { + throw new AuthenticationException("Client Secret cannot be null"); + } + return; + } + + public static BearerTokenTwilioRestClient getRestClient() { + if (TwilioOrgsTokenAuth.restClient == null) { + synchronized (TwilioOrgsTokenAuth.class) { + if (TwilioOrgsTokenAuth.restClient == null) { + TwilioOrgsTokenAuth.restClient = buildOAuthRestClient(); + } + } + } + return TwilioOrgsTokenAuth.restClient; + } + /** + * Returns the Twilio executor service. + * + * @return the Twilio executor service + */ + public static ExecutorService getExecutorService() { + if (TwilioOrgsTokenAuth.executorService == null) { + synchronized (TwilioOrgsTokenAuth.class) { + if (TwilioOrgsTokenAuth.executorService == null) { + TwilioOrgsTokenAuth.executorService = Executors.newCachedThreadPool(); + } + } + } + return TwilioOrgsTokenAuth.executorService; + } + + private static BearerTokenTwilioRestClient buildOAuthRestClient() { + + BearerTokenTwilioRestClient.Builder builder = new BearerTokenTwilioRestClient.Builder(); + + if (userAgentExtensions != null) { + builder.userAgentExtensions(TwilioOrgsTokenAuth.userAgentExtensions); + } + + builder.region(TwilioOrgsTokenAuth.region); + builder.edge(TwilioOrgsTokenAuth.edge); + if(TwilioOrgsTokenAuth.tokenManager == null){ + throw new AuthenticationException("Either initialize the authentications class or pass a custom token manager"); + } + builder.tokenManager(TwilioOrgsTokenAuth.tokenManager); + + return builder.build(); + } + + /** + * Invalidates the volatile state held in the Twilio singleton. + */ + private static void invalidate() { + TwilioOrgsTokenAuth.restClient = null; + TwilioOrgsTokenAuth.tokenManager = null; + } + + +} \ No newline at end of file diff --git a/src/main/java/com/twilio/base/Page.java b/src/main/java/com/twilio/base/Page.java index 259e86e480..b03440007e 100644 --- a/src/main/java/com/twilio/base/Page.java +++ b/src/main/java/com/twilio/base/Page.java @@ -169,9 +169,8 @@ private static Page buildPage(JsonNode root, List results) { private static Page buildNextGenPage(JsonNode root, List results) { JsonNode meta = root.get("meta"); - Builder builder = new Builder<>(); - if(meta != null && meta.get("url") != null) { - builder = builder.url(meta.get("url").asText()); + Builder builder = new Builder().url(meta.get("url").asText()); + JsonNode nextPageNode = meta.get("next_page_url"); if (!nextPageNode.isNull()) { builder.nextPageUrl(nextPageNode.asText()); @@ -193,7 +192,6 @@ private static Page buildNextGenPage(JsonNode root, List results) { } else { builder.pageSize(results.size()); } - } return builder.records(results).build(); } diff --git a/src/main/java/com/twilio/base/bearertoken/Creator.java b/src/main/java/com/twilio/base/bearertoken/Creator.java new file mode 100644 index 0000000000..8cb676cef6 --- /dev/null +++ b/src/main/java/com/twilio/base/bearertoken/Creator.java @@ -0,0 +1,50 @@ +package com.twilio.base.bearertoken; + +import com.twilio.TwilioOrgsTokenAuth; +import com.twilio.http.bearertoken.BearerTokenTwilioRestClient; + +import java.util.concurrent.CompletableFuture; + +/** + * Executor for creation of a resource. + * + * @param type of the resource + */ +public abstract class Creator { + + /** + * Execute an async request using default client. + * + * @return future that resolves to requested object + */ + public CompletableFuture createAsync() { + return createAsync(TwilioOrgsTokenAuth.getRestClient()); + } + + /** + * Execute an async request using specified client. + * + * @param client client used to make request + * @return future that resolves to requested object + */ + public CompletableFuture createAsync(final BearerTokenTwilioRestClient client) { + return CompletableFuture.supplyAsync(() -> create(client), TwilioOrgsTokenAuth.getExecutorService()); + } + + /** + * Execute a request using default client. + * + * @return Requested object + */ + public T create() { + return create(TwilioOrgsTokenAuth.getRestClient()); + } + + /** + * Execute a request using specified client. + * + * @param client client used to make request + * @return Requested object + */ + public abstract T create(final BearerTokenTwilioRestClient client); +} diff --git a/src/main/java/com/twilio/base/bearertoken/Deleter.java b/src/main/java/com/twilio/base/bearertoken/Deleter.java new file mode 100644 index 0000000000..3b49cfd0ba --- /dev/null +++ b/src/main/java/com/twilio/base/bearertoken/Deleter.java @@ -0,0 +1,51 @@ +package com.twilio.base.bearertoken; + +import com.twilio.Twilio; +import com.twilio.TwilioOrgsTokenAuth; +import com.twilio.http.bearertoken.BearerTokenTwilioRestClient; + +import java.util.concurrent.CompletableFuture; + +/** + * Executor for deletes of a resource. + * + * @param type of the resource + */ +public abstract class Deleter { + + /** + * Execute an async request using default client. + * + * @return future that resolves to true if the object was deleted + */ + public CompletableFuture deleteAsync() { + return deleteAsync(TwilioOrgsTokenAuth.getRestClient()); + } + + /** + * Execute an async request using specified client. + * + * @param client client used to make request + * @return future that resolves to true if the object was deleted + */ + public CompletableFuture deleteAsync(final BearerTokenTwilioRestClient client) { + return CompletableFuture.supplyAsync(() -> delete(client), Twilio.getExecutorService()); + } + + /** + * Execute a request using default client. + * + * @return true if the object was deleted + */ + public boolean delete() { + return delete(TwilioOrgsTokenAuth.getRestClient()); + } + + /** + * Execute a request using specified client. + * + * @param client client used to make request + * @return true if the object was deleted + */ + public abstract boolean delete(final BearerTokenTwilioRestClient client); +} diff --git a/src/main/java/com/twilio/base/bearertoken/Fetcher.java b/src/main/java/com/twilio/base/bearertoken/Fetcher.java new file mode 100644 index 0000000000..5654895a3f --- /dev/null +++ b/src/main/java/com/twilio/base/bearertoken/Fetcher.java @@ -0,0 +1,50 @@ +package com.twilio.base.bearertoken; + +import com.twilio.TwilioOrgsTokenAuth; +import com.twilio.http.bearertoken.BearerTokenTwilioRestClient; + +import java.util.concurrent.CompletableFuture; + +/** + * Executor for fetches of a resource. + * + * @param type of the resource + */ +public abstract class Fetcher { + + /** + * Execute an async request using default client. + * + * @return future that resolves to requested object + */ + public CompletableFuture fetchAsync() { + return fetchAsync(TwilioOrgsTokenAuth.getRestClient()); + } + + /** + * Execute an async request using specified client. + * + * @param client client used to make request + * @return future that resolves to requested object + */ + public CompletableFuture fetchAsync(final BearerTokenTwilioRestClient client) { + return CompletableFuture.supplyAsync(() -> fetch(client), TwilioOrgsTokenAuth.getExecutorService()); + } + + /** + * Execute a request using default client. + * + * @return Requested object + */ + public T fetch() { + return fetch(TwilioOrgsTokenAuth.getRestClient()); + } + + /** + * Execute a request using specified client. + * + * @param client client used to make request + * @return Requested object + */ + public abstract T fetch(final BearerTokenTwilioRestClient client); +} diff --git a/src/main/java/com/twilio/base/bearertoken/Page.java b/src/main/java/com/twilio/base/bearertoken/Page.java new file mode 100644 index 0000000000..204c2e98a2 --- /dev/null +++ b/src/main/java/com/twilio/base/bearertoken/Page.java @@ -0,0 +1,270 @@ +package com.twilio.base.bearertoken; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.twilio.exception.ApiConnectionException; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +public class Page { + private final List records; + private final String firstPageUrl; + private final String firstPageUri; + private final String nextPageUrl; + private final String nextPageUri; + private final String previousPageUrl; + private final String previousPageUri; + private final String url; + private final String uri; + private final int pageSize; + + private Page(Builder b) { + this.records = b.records; + this.firstPageUri = b.firstPageUri; + this.firstPageUrl = b.firstPageUrl; + this.nextPageUri = b.nextPageUri; + this.nextPageUrl = b.nextPageUrl; + this.previousPageUri = b.previousPageUri; + this.previousPageUrl = b.previousPageUrl; + this.uri = b.uri; + this.url = b.url; + this.pageSize = b.pageSize; + } + + private String urlFromUri(String domain, String uri) { + return "https://" + domain + ".twilio.com" + uri; + } + + public List getRecords() { + return records; + } + + /** + * Generate first page url for a list result. + * + * @param domain domain to use + * @return the first page url + */ + public String getFirstPageUrl(String domain) { + if (firstPageUrl != null) { + return firstPageUrl; + } + + return urlFromUri(domain, firstPageUri); + } + + /** + * Generate next page url for a list result. + * + * @param domain domain to use + * @return the next page url + */ + public String getNextPageUrl(String domain) { + if (nextPageUrl != null) { + return nextPageUrl; + } + + return urlFromUri(domain, nextPageUri); + } + + /** + * Generate previous page url for a list result. + * + * @param domain domain to use + * @return the previous page url + */ + public String getPreviousPageUrl(String domain) { + if (previousPageUrl != null) { + return previousPageUrl; + } + + return urlFromUri(domain, previousPageUri); + } + + public int getPageSize() { + return pageSize; + } + + /** + * Generate page url for a list result. + * + * @param domain domain to use + * @return the page url + */ + public String getUrl(String domain) { + if (url != null) { + return url; + } + + return urlFromUri(domain, uri); + } + + public boolean hasNextPage() { + return (nextPageUri != null && !nextPageUri.isEmpty()) || (nextPageUrl != null && !nextPageUrl.isEmpty()); + } + + /** + * Create a new page of data from a json blob. + * + * @param recordKey key which holds the records + * @param json json blob + * @param recordType resource type + * @param mapper json parser + * @param record class type + * @return a page of records of type T + */ + public static Page fromJson(String recordKey, String json, Class recordType, ObjectMapper mapper) { + try { + List results = new ArrayList<>(); + JsonNode root = mapper.readTree(json); + JsonNode records = root.get(recordKey); + for (final JsonNode record : records) { + results.add(mapper.readValue(record.toString(), recordType)); + } + + JsonNode uriNode = root.get("uri"); + if (uriNode != null) { + return buildPage(root, results); + } else { + return buildNextGenPage(root, results); + } + + } catch (final IOException e) { + throw new ApiConnectionException( + "Unable to deserialize response: " + e.getMessage() + "\nJSON: " + json, e + ); + } + } + + private static Page buildPage(JsonNode root, List results) { + Builder builder = new Builder() + .uri(root.get("uri").asText()); + + JsonNode nextPageNode = root.get("next_page_uri"); + if (nextPageNode != null && !nextPageNode.isNull()) { + builder.nextPageUri(nextPageNode.asText()); + } + + JsonNode previousPageNode = root.get("previous_page_uri"); + if (previousPageNode != null && !previousPageNode.isNull()) { + builder.previousPageUri(previousPageNode.asText()); + } + + JsonNode firstPageNode = root.get("first_page_uri"); + if (firstPageNode != null && !firstPageNode.isNull()) { + builder.firstPageUri(firstPageNode.asText()); + } + + JsonNode pageSizeNode = root.get("page_size"); + if (pageSizeNode != null && !pageSizeNode.isNull()) { + builder.pageSize(pageSizeNode.asInt()); + } else { + builder.pageSize(results.size()); + } + + return builder.records(results).build(); + } + + private static Page buildNextGenPage(JsonNode root, List results) { + JsonNode meta = root.get("meta"); + Builder builder = new Builder<>(); + if(meta != null && meta.get("url") != null) { + + builder = builder.url(meta.get("url").asText()); + + + JsonNode nextPageNode = meta.get("next_page_url"); + if (!nextPageNode.isNull()) { + builder.nextPageUrl(nextPageNode.asText()); + } + + JsonNode previousPageNode = meta.get("previous_page_url"); + if (!previousPageNode.isNull()) { + builder.previousPageUrl(previousPageNode.asText()); + } + + JsonNode firstPageNode = meta.get("first_page_url"); + if (!firstPageNode.isNull()) { + builder.firstPageUrl(firstPageNode.asText()); + } + + JsonNode pageSizeNode = meta.get("page_size"); + if (!pageSizeNode.isNull()) { + builder.pageSize(pageSizeNode.asInt()); + } else { + builder.pageSize(results.size()); + } + } + + return builder.records(results).build(); + } + + private static class Builder { + private List records; + private String firstPageUrl; + private String firstPageUri; + private String nextPageUrl; + private String nextPageUri; + private String previousPageUrl; + private String previousPageUri; + private String uri; + private String url; + private int pageSize; + + public Builder records(List records) { + this.records = records; + return this; + } + + public Builder firstPageUri(String firstPageUri) { + this.firstPageUri = firstPageUri; + return this; + } + + public Builder firstPageUrl(String firstPageUrl) { + this.firstPageUrl = firstPageUrl; + return this; + } + + public Builder nextPageUri(String nextPageUri) { + this.nextPageUri = nextPageUri; + return this; + } + + public Builder nextPageUrl(String nextPageUrl) { + this.nextPageUrl = nextPageUrl; + return this; + } + + public Builder previousPageUri(String previousPageUri) { + this.previousPageUri = previousPageUri; + return this; + } + + public Builder previousPageUrl(String previousPageUrl) { + this.previousPageUrl = previousPageUrl; + return this; + } + + public Builder uri(String uri) { + this.uri = uri; + return this; + } + + public Builder url(String url) { + this.url = url; + return this; + } + + public Builder pageSize(int pageSize) { + this.pageSize = pageSize; + return this; + } + + public Page build() { + return new Page<>(this); + } + } +} diff --git a/src/main/java/com/twilio/base/bearertoken/Reader.java b/src/main/java/com/twilio/base/bearertoken/Reader.java new file mode 100644 index 0000000000..15e221a3f9 --- /dev/null +++ b/src/main/java/com/twilio/base/bearertoken/Reader.java @@ -0,0 +1,156 @@ +package com.twilio.base.bearertoken; + +import com.twilio.TwilioOrgsTokenAuth; +import com.twilio.http.bearertoken.BearerTokenTwilioRestClient; + +import java.util.concurrent.CompletableFuture; + +/** + * Executor for listing of a resource. + * + * @param type of the resource + */ +public abstract class Reader { + + private Integer pageSize; + private Long limit; + + /** + * Execute a request using default client. + * + * @return ResourceSet of objects + */ + public ResourceSet read() { + return read(TwilioOrgsTokenAuth.getRestClient()); + } + + /** + * Execute a request using specified client. + * + * @param client client used to make request + * @return ResourceSet of objects + */ + public abstract ResourceSet read(final BearerTokenTwilioRestClient client); + + /** + * Execute an async request using default client. + * + * @return future that resolves to the ResourceSet of objects + */ + public CompletableFuture> readAsync() { + return readAsync(TwilioOrgsTokenAuth.getRestClient()); + } + + /** + * Execute an async request using specified client. + * + * @param client client used to make request + * @return future that resolves to the ResourceSet of objects + */ + public CompletableFuture> readAsync(final BearerTokenTwilioRestClient client) { + return CompletableFuture.supplyAsync(() -> read(client), TwilioOrgsTokenAuth.getExecutorService()); + } + + /** + * Fetch the first page of resources. + * + * @return Page containing the first pageSize of resources + */ + public Page firstPage() { + return firstPage(TwilioOrgsTokenAuth.getRestClient()); + } + + /** + * Fetch the first page of resources using specified client. + * + * @param client client used to fetch + * @return Page containing the first pageSize of resources + */ + public abstract Page firstPage(final BearerTokenTwilioRestClient client); + + /** + * Retrieve the target page of resources. + * + * @param targetUrl API-generated URL for the requested results page + * @return Page containing the target pageSize of resources + */ + public Page getPage(final String targetUrl) { + return getPage(targetUrl, TwilioOrgsTokenAuth.getRestClient()); + } + + /** + * Retrieve the target page of resources. + * + * @param targetUrl API-generated URL for the requested results page + * @param client client used to fetch + * @return Page containing the target pageSize of resources + */ + public abstract Page getPage(final String targetUrl, final BearerTokenTwilioRestClient client); + + /** + * Fetch the following page of resources. + * + * @param page current page of resources + * @return Page containing the next pageSize of resources + */ + public Page nextPage(final Page page) { + return nextPage(page, TwilioOrgsTokenAuth.getRestClient()); + } + + /** + * Fetch the following page of resources using specified client. + * + * @param page current page of resources + * @param client client used to fetch + * @return Page containing the next pageSize of resources + */ + public abstract Page nextPage(final Page page, final BearerTokenTwilioRestClient client); + + /** + * Fetch the prior page of resources. + * + * @param page current page of resources + * @return Page containing the previous pageSize of resources + */ + public Page previousPage(final Page page) { + return previousPage(page, TwilioOrgsTokenAuth.getRestClient()); + } + + /** + * Fetch the prior page of resources using specified client. + * + * @param page current page of resources + * @param client client used to fetch + * @return Page containing the previous pageSize of resources + */ + public abstract Page previousPage(final Page page, final BearerTokenTwilioRestClient client); + + public Integer getPageSize() { + return pageSize; + } + + public Reader pageSize(final int pageSize) { + this.pageSize = pageSize; + return this; + } + + public Long getLimit() { + return limit; + } + + /** + * Sets the max number of records to read. + * + * @param limit max number of records to read + * @return this reader + */ + public Reader limit(final long limit) { + this.limit = limit; + + if (this.pageSize == null) { + this.pageSize = this.limit.intValue(); + } + + return this; + } +} diff --git a/src/main/java/com/twilio/base/bearertoken/Resource.java b/src/main/java/com/twilio/base/bearertoken/Resource.java new file mode 100644 index 0000000000..08dc228556 --- /dev/null +++ b/src/main/java/com/twilio/base/bearertoken/Resource.java @@ -0,0 +1,9 @@ +package com.twilio.base.bearertoken; + +import java.io.Serializable; + +public abstract class Resource implements Serializable { + + private static final long serialVersionUID = -5898012691404059591L; + +} diff --git a/src/main/java/com/twilio/base/bearertoken/ResourceSet.java b/src/main/java/com/twilio/base/bearertoken/ResourceSet.java new file mode 100644 index 0000000000..4cc09d8c2d --- /dev/null +++ b/src/main/java/com/twilio/base/bearertoken/ResourceSet.java @@ -0,0 +1,138 @@ +package com.twilio.base.bearertoken; + +import com.twilio.http.bearertoken.BearerTokenTwilioRestClient; + +import java.util.Iterator; +import java.util.NoSuchElementException; + +/** + * A collection of resources. + * + * @param type of the resource + */ +public class ResourceSet implements Iterable { + + private final Reader reader; + private final BearerTokenTwilioRestClient client; + private final Page firstPage; // Store reference to first page to enable multiple iterations + + private boolean autoPaging; + private long pages = 1; + private long pageLimit = Long.MAX_VALUE; + private long processed = 0; + private Page page; + private Iterator iterator; + + /** + * Initialize the resource set. + * + * @param reader reader used to fetch next page + * @param client client used to make requests + * @param page page of data + */ + public ResourceSet(final Reader reader, final BearerTokenTwilioRestClient client, final Page page) { + this.reader = reader; + this.client = client; + this.firstPage = page; // Save first page to allow resetting iterator state + this.page = page; + this.iterator = page.getRecords().iterator(); + this.autoPaging = true; + + if (reader.getLimit() != null) { + this.pageLimit = (long)(Math.ceil((double)reader.getLimit() / (double)page.getPageSize())); + } + } + + public boolean isAutoPaging() { + return autoPaging; + } + + public ResourceSet setAutoPaging(final boolean autoPaging) { + this.autoPaging = autoPaging; + return this; + } + + public Integer getPageSize() { + return page.getPageSize(); + } + + public ResourceSet setPageSize(final int pageSize) { + reader.pageSize(pageSize); + return this; + } + + public Long getLimit() { + return reader.getLimit(); + } + + public ResourceSet setLimit(final long limit) { + reader.limit(limit); + return this; + } + + public long getPageLimit() { + return pageLimit; + } + + @Override + public Iterator iterator() { + // Reset state to allow multiple iterations + this.processed = 0; + this.pages = 1; + this.page = this.firstPage; // Reset to first page for new iteration + this.iterator = this.firstPage.getRecords().iterator(); // Reset iterator to start of first page + + return new ResourceSetIterator<>(this); + } + + private void fetchNextPage() { + if (!page.hasNextPage() || pages >= pageLimit) { + return; + } + + pages++; + page = reader.nextPage(page, client); + iterator = page.getRecords().iterator(); + } + + private class ResourceSetIterator implements Iterator { + private final ResourceSet resourceSet; + + public ResourceSetIterator(final ResourceSet resourceSet) { + this.resourceSet = resourceSet; + } + + @Override + public boolean hasNext() { + if (resourceSet.getLimit() != null && resourceSet.processed >= resourceSet.getLimit()) { + return false; + } + + return resourceSet.iterator.hasNext(); + } + + @Override + public E next() { + if (resourceSet == null || resourceSet.iterator == null) { + throw new NoSuchElementException(); + } + + E element = resourceSet.iterator.next(); + if (resourceSet.isAutoPaging() && !resourceSet.iterator.hasNext()) { + resourceSet.fetchNextPage(); + } + + resourceSet.processed++; + return element; + } + + @Override + public void remove() { + if (resourceSet.iterator != null) { + resourceSet.processed++; + resourceSet.iterator.remove(); + } + } + + } +} diff --git a/src/main/java/com/twilio/base/bearertoken/Updater.java b/src/main/java/com/twilio/base/bearertoken/Updater.java new file mode 100644 index 0000000000..690e3604c5 --- /dev/null +++ b/src/main/java/com/twilio/base/bearertoken/Updater.java @@ -0,0 +1,50 @@ +package com.twilio.base.bearertoken; + +import com.twilio.TwilioOrgsTokenAuth; +import com.twilio.http.bearertoken.BearerTokenTwilioRestClient; + +import java.util.concurrent.CompletableFuture; + +/** + * Executor for updates of a resource. + * + * @param type of the resource + */ +public abstract class Updater { + + /** + * Execute an async request using default client. + * + * @return future that resolves to requested object + */ + public CompletableFuture updateAsync() { + return updateAsync(TwilioOrgsTokenAuth.getRestClient()); + } + + /** + * Execute an async request using specified client. + * + * @param client client used to make request + * @return future that resolves to requested object + */ + public CompletableFuture updateAsync(final BearerTokenTwilioRestClient client) { + return CompletableFuture.supplyAsync(() -> update(client), TwilioOrgsTokenAuth.getExecutorService()); + } + + /** + * Execute a request using default client. + * + * @return Requested object + */ + public T update() { + return update(TwilioOrgsTokenAuth.getRestClient()); + } + + /** + * Execute a request using specified client. + * + * @param client client used to make request + * @return Requested object + */ + public abstract T update(final BearerTokenTwilioRestClient client); +} diff --git a/src/main/java/com/twilio/credential/orgs/OrgsClientCredentialProvider.java b/src/main/java/com/twilio/credential/orgs/OrgsClientCredentialProvider.java index 5d93404bc6..9d5687a64a 100644 --- a/src/main/java/com/twilio/credential/orgs/OrgsClientCredentialProvider.java +++ b/src/main/java/com/twilio/credential/orgs/OrgsClientCredentialProvider.java @@ -1,64 +1,4 @@ package com.twilio.credential.orgs; -import com.twilio.auth_strategy.AuthStrategy; -import com.twilio.auth_strategy.TokenAuthStrategy; -import com.twilio.constant.EnumConstants; -import com.twilio.credential.CredentialProvider; -import com.twilio.exception.AuthenticationException; -import com.twilio.http.bearertoken.OrgsTokenManager; -import com.twilio.http.bearertoken.TokenManager; - -import java.util.Objects; - -public class OrgsClientCredentialProvider extends CredentialProvider { - private String grantType; - private String clientId; - private String clientSecret; - private TokenManager tokenManager; - - public OrgsClientCredentialProvider(String clientId, String clientSecret) { - super(EnumConstants.AuthType.CLIENT_CREDENTIALS); - if (clientId == null || clientSecret == null) { - throw new AuthenticationException("ClientId or ClientSecret can not be null"); - } - this.grantType = "client_credentials"; - this.clientId = clientId; - this.clientSecret = clientSecret; - this.tokenManager = null; - } - - public OrgsClientCredentialProvider(String clientId, String clientSecret, TokenManager tokenManager) { - super(EnumConstants.AuthType.CLIENT_CREDENTIALS); - if (clientId == null || clientSecret == null || tokenManager == null) { - throw new AuthenticationException("ClientId or ClientSecret or TokenManager can not be null"); - } - this.grantType = "client_credentials"; - this.clientId = clientId; - this.clientSecret = clientSecret; - this.tokenManager = tokenManager; - } - - @Override - public AuthStrategy toAuthStrategy() { - if (tokenManager == null) { - tokenManager = new OrgsTokenManager(grantType, clientId, clientSecret); - } - return new TokenAuthStrategy(tokenManager); - } - - @Override - public boolean equals(final Object o) { - if (this == o) { - return true; - } - - if (o == null || getClass() != o.getClass()) { - return false; - } - - OrgsClientCredentialProvider other = (OrgsClientCredentialProvider) o; - return Objects.equals(clientId, other.clientId) && - Objects.equals(clientSecret, other.clientSecret) && - Objects.equals(tokenManager, other.tokenManager); - } +public class OrgsClientCredentialProvider { } diff --git a/src/main/java/com/twilio/http/NetworkHttpClient.java b/src/main/java/com/twilio/http/NetworkHttpClient.java index 0d40e4cb8c..8c1b0dad85 100644 --- a/src/main/java/com/twilio/http/NetworkHttpClient.java +++ b/src/main/java/com/twilio/http/NetworkHttpClient.java @@ -72,7 +72,7 @@ public NetworkHttpClient(final RequestConfig requestConfig) { public NetworkHttpClient(final RequestConfig requestConfig, final SocketConfig socketConfig) { Collection headers = Arrays.asList( new BasicHeader("X-Twilio-Client", "java-" + Twilio.VERSION), - // The Accept header is intentionally omitted to support both SCIM and JSON content types. + new BasicHeader(HttpHeaders.ACCEPT, "application/json"), new BasicHeader(HttpHeaders.ACCEPT_ENCODING, "utf-8") ); diff --git a/src/main/java/com/twilio/http/bearertoken/BearerTokenHttpClient.java b/src/main/java/com/twilio/http/bearertoken/BearerTokenHttpClient.java new file mode 100644 index 0000000000..0c405769bf --- /dev/null +++ b/src/main/java/com/twilio/http/bearertoken/BearerTokenHttpClient.java @@ -0,0 +1,108 @@ +package com.twilio.http.bearertoken; + +import com.twilio.http.HttpClient; +import com.twilio.http.Request; +import com.twilio.http.Response; +import lombok.Getter; +import lombok.Setter; +import org.apache.hc.client5.http.config.RequestConfig; +import org.apache.hc.client5.http.impl.DefaultRedirectStrategy; +import org.apache.hc.client5.http.protocol.RedirectStrategy; +import org.apache.hc.core5.http.io.SocketConfig; + +public abstract class BearerTokenHttpClient { + // Use constants from HttpClient + public static final RequestConfig DEFAULT_REQUEST_CONFIG = RequestConfig + .custom() + .setConnectTimeout(HttpClient.CONNECTION_TIMEOUT) + .build(); + public static final SocketConfig DEFAULT_SOCKET_CONFIG = SocketConfig + .custom() + .setSoTimeout(HttpClient.SOCKET_TIMEOUT) + .build(); + @Getter + @Setter + private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy(); + + @Getter + private Response lastResponse; + @Getter + private BearerTokenRequest lastRequest; + + public Response reliableRequest(final BearerTokenRequest request) { + return reliableRequest(request, HttpClient.RETRY_CODES, HttpClient.RETRIES, HttpClient.DELAY_MILLIS); + } + + public Response reliableRequest(final BearerTokenRequest request, final int[] retryCodes, int retries, + final long delayMillis) { + lastRequest = request; + Response response = null; + while (retries > 0) { + response = makeRequest(request); + + if (!shouldRetry(response, retryCodes)) { + break; + } + + try { + Thread.sleep(delayMillis); + } catch (final InterruptedException e) { + // Delay failed, continue + } + + // Decrement retries + retries--; + } + + lastResponse = response; + + return response; + } + + protected boolean shouldRetry(final Response response, final int[] retryCodes) { + if (response == null) { + return true; + } + + int statusCode = response.getStatusCode(); + int category = (int) Math.floor(statusCode / 100.0); + + for (final int retryCode : retryCodes) { + switch (retryCode) { + case HttpClient.ANY_100: + if (category == 1) { + return true; + } + break; + case HttpClient.ANY_200: + if (category == 2) { + return true; + } + break; + case HttpClient.ANY_300: + if (category == 3) { + return true; + } + break; + case HttpClient.ANY_400: + if (category == 4) { + return true; + } + break; + case HttpClient.ANY_500: + if (category == 5) { + return true; + } + break; + default: + if (statusCode == retryCode) { + return true; + } + break; + } + } + return false; + } + + public abstract Response makeRequest(final BearerTokenRequest request); +} diff --git a/src/main/java/com/twilio/http/bearertoken/BearerTokenNetworkHttpClient.java b/src/main/java/com/twilio/http/bearertoken/BearerTokenNetworkHttpClient.java new file mode 100644 index 0000000000..9d80666640 --- /dev/null +++ b/src/main/java/com/twilio/http/bearertoken/BearerTokenNetworkHttpClient.java @@ -0,0 +1,181 @@ +package com.twilio.http.bearertoken; + +import com.twilio.Twilio; +import com.twilio.constant.EnumConstants; +import com.twilio.exception.ApiException; +import com.twilio.http.HttpMethod; +import com.twilio.http.HttpUtility; +import com.twilio.http.Response; +import java.util.ArrayList; +import java.util.Map.Entry; +import org.apache.hc.client5.http.classic.methods.HttpUriRequestBase; +import org.apache.hc.client5.http.config.RequestConfig; +import org.apache.hc.client5.http.entity.UrlEncodedFormEntity; +import org.apache.hc.client5.http.impl.classic.CloseableHttpClient; +import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse; +import org.apache.hc.client5.http.impl.classic.HttpClientBuilder; +import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager; +import org.apache.hc.core5.http.ContentType; +import org.apache.hc.core5.http.HttpEntity; +import org.apache.hc.core5.http.HttpHeaders; +import org.apache.hc.core5.http.NameValuePair; +import org.apache.hc.core5.http.io.SocketConfig; +import org.apache.hc.core5.http.io.entity.BufferedHttpEntity; +import org.apache.hc.core5.http.io.entity.StringEntity; +import org.apache.hc.core5.http.message.BasicHeader; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; +import java.util.Map; +import org.apache.hc.core5.http.message.BasicNameValuePair; +import static com.twilio.http.HttpClient.createHttpUriRequestBase; + +public class BearerTokenNetworkHttpClient extends BearerTokenHttpClient { + + protected final CloseableHttpClient client; + + private boolean isCustomClient; + + /** + * Create a new HTTP Client. + */ + public BearerTokenNetworkHttpClient() { + this(DEFAULT_REQUEST_CONFIG); + } + + /** + * Create a new HTTP Client with a custom request config. + * + * @param requestConfig a RequestConfig. + */ + public BearerTokenNetworkHttpClient(final RequestConfig requestConfig) { + this(requestConfig, DEFAULT_SOCKET_CONFIG); + } + + /** + * Create a new HTTP Client with a custom request and socket config. + * + * @param requestConfig a RequestConfig. + * @param socketConfig a SocketConfig. + */ + public BearerTokenNetworkHttpClient(final RequestConfig requestConfig, final SocketConfig socketConfig) { + Collection headers = Arrays.asList( + new BasicHeader("X-Twilio-Client", "java-" + Twilio.VERSION), + //new BasicHeader(HttpHeaders.ACCEPT, "application/json"), Orgs API has scim or json support. + new BasicHeader(HttpHeaders.ACCEPT_ENCODING, "utf-8") + ); + + String googleAppEngineVersion = System.getProperty("com.google.appengine.runtime.version"); + boolean isGoogleAppEngine = googleAppEngineVersion != null && !googleAppEngineVersion.isEmpty(); + + HttpClientBuilder clientBuilder = HttpClientBuilder.create(); + + if (!isGoogleAppEngine) { + clientBuilder.useSystemProperties(); + } + + PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(); + connectionManager.setDefaultSocketConfig(socketConfig); + /** + * Example: Lets say client has one server. + * There are 4 servers on edge handling client request. + * Each request takes on an average 500ms (2 request per second) + * Total number request can be server in a second from a route: 20 * 4 * 2 (DefaultMaxPerRoute * edge servers * request per second) + */ + connectionManager.setDefaultMaxPerRoute(20); + connectionManager.setMaxTotal(100); + + client = clientBuilder + .setConnectionManager(connectionManager) + .setDefaultRequestConfig(requestConfig) + .setDefaultHeaders(headers) + .setRedirectStrategy(this.getRedirectStrategy()) + .build(); + } + + /** + * Create a new HTTP Client using custom configuration. + * @param clientBuilder an HttpClientBuilder. + */ + public BearerTokenNetworkHttpClient(HttpClientBuilder clientBuilder) { + Collection headers = Arrays.asList( + new BasicHeader("X-Twilio-Client", "java-" + Twilio.VERSION), + //new BasicHeader(HttpHeaders.ACCEPT, "application/json"), Orgs API has scim or json support. + new BasicHeader(HttpHeaders.ACCEPT_ENCODING, "utf-8") + ); + isCustomClient = true; + + client = clientBuilder + .setDefaultRequestConfig(DEFAULT_REQUEST_CONFIG) + .setDefaultHeaders(headers) + .setRedirectStrategy(this.getRedirectStrategy()) + .build(); + } + + /** + * Make a request. + * + * @param request request to make + * @return Response of the HTTP request + */ + public Response makeRequest(final BearerTokenRequest request) { + + HttpMethod method = request.getMethod(); + HttpUriRequestBase httpUriRequestBase = createHttpUriRequestBase(request); + + + if (request.requiresAuthentication()) { + httpUriRequestBase.addHeader(HttpHeaders.AUTHORIZATION, request.getAuthString()); + } + + for (Map.Entry> entry : request.getHeaderParams().entrySet()) { + for (String value : entry.getValue()) { + httpUriRequestBase.addHeader(entry.getKey(), value); + } + } + + if (method != HttpMethod.GET) { + // TODO: It will be removed after one RC Release. + if (request.getContentType() == null) request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + if (EnumConstants.ContentType.JSON.getValue().equals(request.getContentType().getValue())) { + HttpEntity entity = new StringEntity(request.getBody(), ContentType.APPLICATION_JSON); + httpUriRequestBase.setEntity(entity); + httpUriRequestBase.addHeader( + HttpHeaders.CONTENT_TYPE, EnumConstants.ContentType.JSON.getValue()); + } else { + httpUriRequestBase.addHeader( + HttpHeaders.CONTENT_TYPE, EnumConstants.ContentType.FORM_URLENCODED.getValue()); + // Create your form parameters + List formParams = new ArrayList<>(); + for ( Entry> entry : request.getPostParams().entrySet()) { + for (String value : entry.getValue()) { + formParams.add(new BasicNameValuePair(entry.getKey(), value)); + } + } + + // Build the entity with URL form encoded parameters + UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(formParams, StandardCharsets.UTF_8); + // Set the entity on the request + httpUriRequestBase.setEntity(formEntity); + } + + } + httpUriRequestBase.addHeader(HttpHeaders.USER_AGENT, HttpUtility.getUserAgentString(request.getUserAgentExtensions(), isCustomClient)); + + try { + CloseableHttpResponse response = client.execute(httpUriRequestBase); + HttpEntity entity = response.getEntity(); + return new Response( + // Consume the entire HTTP response before returning the stream + entity == null ? null : new BufferedHttpEntity(entity).getContent(), + response.getCode(), + response.getHeaders() + ); + } catch (IOException e) { + throw new ApiException(e.getMessage(), e); + } + } +} diff --git a/src/main/java/com/twilio/http/bearertoken/BearerTokenRequest.java b/src/main/java/com/twilio/http/bearertoken/BearerTokenRequest.java new file mode 100644 index 0000000000..83976c2e45 --- /dev/null +++ b/src/main/java/com/twilio/http/bearertoken/BearerTokenRequest.java @@ -0,0 +1,38 @@ +package com.twilio.http.bearertoken; + +import com.twilio.http.HttpMethod; +import com.twilio.http.IRequest; + +public class BearerTokenRequest extends IRequest { + + private String accessToken; + + public BearerTokenRequest(HttpMethod method, String url) { + super(method, url); + } + + public BearerTokenRequest(HttpMethod method, String domain, String uri) { + super(method, domain, uri); + } + + public BearerTokenRequest(HttpMethod method, String domain, String uri, String region) { + super(method, domain, uri, region); + } + + /** + * Create auth string from accessToken. + * + * @return basic authentication string + */ + public String getAuthString() { + return "Bearer " + accessToken; + } + + public boolean requiresAuthentication() { + return accessToken != null; + } + + public void setAuth(String accessToken) { + this.accessToken = accessToken; + } +} diff --git a/src/main/java/com/twilio/http/bearertoken/BearerTokenTwilioRestClient.java b/src/main/java/com/twilio/http/bearertoken/BearerTokenTwilioRestClient.java new file mode 100644 index 0000000000..c7da1ff2b0 --- /dev/null +++ b/src/main/java/com/twilio/http/bearertoken/BearerTokenTwilioRestClient.java @@ -0,0 +1,186 @@ +package com.twilio.http.bearertoken; + +import com.auth0.jwt.JWT; +import com.auth0.jwt.interfaces.DecodedJWT; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; +import com.twilio.http.Response; +import lombok.Getter; +import lombok.Setter; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.Map; +import java.util.function.Predicate; + + +/* + * Use this BearerToken Rest Client if no authentication is involved in an API. + */ +public class BearerTokenTwilioRestClient { + public static final int HTTP_STATUS_CODE_CREATED = 201; + public static final int HTTP_STATUS_CODE_NO_CONTENT = 204; + public static final int HTTP_STATUS_CODE_OK = 200; + public static final Predicate SUCCESS = i -> i != null && i >= 200 && i < 400; + @Getter + private final ObjectMapper objectMapper; + private String accessToken; + @Getter + private final String region; + @Getter + private final String edge; + @Getter + private final BearerTokenHttpClient httpClient; + @Getter + private final List userAgentExtensions; + @Setter + private final TokenManager tokenManager; + private static final Logger logger = LoggerFactory.getLogger(BearerTokenTwilioRestClient.class); + + private BearerTokenTwilioRestClient(BearerTokenTwilioRestClient.Builder b) { + this.region = b.region; + this.edge = b.edge; + this.httpClient = b.httpClient; + this.objectMapper = b.objectMapper; + this.userAgentExtensions = b.userAgentExtensions; + this.tokenManager = b.tokenManager; + } + + public static class Builder { + // This module configures the ObjectMapper to use + // public API methods for manipulating java.time.* + // classes. The alternative is to use reflection which + // generates warnings from the module system on Java 9+ + private static final ObjectMapper DEFAULT_OBJECT_MAPPER = new ObjectMapper() + .registerModule(new JavaTimeModule()); + + private String region; + private String edge; + private BearerTokenHttpClient httpClient; + private List userAgentExtensions; + private TokenManager tokenManager; + private ObjectMapper objectMapper = DEFAULT_OBJECT_MAPPER; + + public Builder() { + this.region = System.getenv("TWILIO_REGION"); + this.edge = System.getenv("TWILIO_EDGE"); + userAgentExtensions = new ArrayList<>(); + } + + public BearerTokenTwilioRestClient.Builder region(final String region) { + this.region = region; + return this; + } + + public BearerTokenTwilioRestClient.Builder edge(final String edge) { + this.edge = edge; + return this; + } + + public BearerTokenTwilioRestClient.Builder tokenManager(final TokenManager tokenManager) { + this.tokenManager = tokenManager; + return this; + } + + public BearerTokenTwilioRestClient.Builder httpClient(final BearerTokenHttpClient httpClient) { + this.httpClient = httpClient; + return this; + } + + public BearerTokenTwilioRestClient.Builder userAgentExtensions(final List userAgentExtensions) { + if (userAgentExtensions != null && !userAgentExtensions.isEmpty()) { + this.userAgentExtensions = new ArrayList<>(userAgentExtensions); + } + return this; + } + + public BearerTokenTwilioRestClient.Builder objectMapper(final ObjectMapper objectMapper) { + this.objectMapper = objectMapper; + return this; + } + + public BearerTokenTwilioRestClient build() { + if (this.httpClient == null) { + this.httpClient = new BearerTokenNetworkHttpClient(); + } + return new BearerTokenTwilioRestClient(this); + } + } + public Response request(BearerTokenRequest request) { + + if (accessToken == null || accessToken.isEmpty() || isTokenExpired(this.accessToken)) { + synchronized (BearerTokenTwilioRestClient.class){ + if (accessToken == null || accessToken.isEmpty() || isTokenExpired(this.accessToken)) { + this.accessToken = tokenManager.fetchAccessToken(); + } + } + } + + request.setAuth(accessToken); + if (region != null) + request.setRegion(region); + if (edge != null) + request.setEdge(edge); + + if (userAgentExtensions != null && !userAgentExtensions.isEmpty()) { + request.setUserAgentExtensions(userAgentExtensions); + } + logRequest(request); + Response response = httpClient.reliableRequest(request); + if(response != null) { + int statusCode = response.getStatusCode(); + if (statusCode == 401) { + this.accessToken = tokenManager.fetchAccessToken(); + request.setAuth(accessToken); + response = httpClient.reliableRequest(request); + } + + if (logger.isDebugEnabled()) { + logger.debug("status code: {}", statusCode); + org.apache.hc.core5.http.Header[] responseHeaders = response.getHeaders(); + logger.debug("response headers:"); + for (int i = 0; i < responseHeaders.length; i++) { + logger.debug("responseHeader: {}", responseHeaders[i]); + } + } + } + + return response; + } + + public boolean isTokenExpired(String token) { + DecodedJWT jwt = JWT.decode(token); + Date expiresAt = jwt.getExpiresAt(); + // Add a buffer of 30 seconds + long bufferMilliseconds = 30 * 1000; + Date bufferExpiresAt = new Date(expiresAt.getTime() - bufferMilliseconds); + return bufferExpiresAt.before(new Date()); + } + + public void logRequest(final BearerTokenRequest request) { + if (logger.isDebugEnabled()) { + logger.debug("-- BEGIN Twilio API BearerTokenRequest --"); + logger.debug("request method: " + request.getMethod()); + logger.debug("request URL: " + request.constructURL().toString()); + final Map> queryParams = request.getQueryParams(); + final Map> headerParams = request.getHeaderParams(); + + if (queryParams != null && !queryParams.isEmpty()) { + logger.debug("query parameters: " + queryParams); + } + + if (headerParams != null && !headerParams.isEmpty()) { + logger.debug("header parameters: "); + for (String key : headerParams.keySet()) { + if (!key.toLowerCase().contains("authorization")) { + logger.debug(key + ": " + headerParams.get(key)); + } + } + } + logger.debug("-- END Twilio API BearerTokenRequest --"); + } + } +} diff --git a/src/main/java/com/twilio/rest/previewiam/organizations/Account.java b/src/main/java/com/twilio/rest/previewiam/organizations/Account.java index bffd937287..388b31fa34 100644 --- a/src/main/java/com/twilio/rest/previewiam/organizations/Account.java +++ b/src/main/java/com/twilio/rest/previewiam/organizations/Account.java @@ -20,7 +20,7 @@ import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; -import com.twilio.base.Resource; +import com.twilio.base.bearertoken.Resource; import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; diff --git a/src/main/java/com/twilio/rest/previewiam/organizations/AccountFetcher.java b/src/main/java/com/twilio/rest/previewiam/organizations/AccountFetcher.java index 1949891f1d..57dc7b088e 100644 --- a/src/main/java/com/twilio/rest/previewiam/organizations/AccountFetcher.java +++ b/src/main/java/com/twilio/rest/previewiam/organizations/AccountFetcher.java @@ -14,15 +14,15 @@ package com.twilio.rest.previewiam.organizations; -import com.twilio.base.Fetcher; +import com.twilio.base.bearertoken.Fetcher; import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; import com.twilio.http.HttpMethod; -import com.twilio.http.Request; import com.twilio.http.Response; -import com.twilio.http.TwilioRestClient; +import com.twilio.http.bearertoken.BearerTokenRequest; +import com.twilio.http.bearertoken.BearerTokenTwilioRestClient; import com.twilio.rest.Domains; public class AccountFetcher extends Fetcher { @@ -39,7 +39,7 @@ public AccountFetcher( } @Override - public Account fetch(final TwilioRestClient client) { + public Account fetch(final BearerTokenTwilioRestClient client) { String path = "/Organizations/{OrganizationSid}/Accounts/{AccountSid}"; path = @@ -53,7 +53,7 @@ public Account fetch(final TwilioRestClient client) { this.pathAccountSid.toString() ); - Request request = new Request( + BearerTokenRequest request = new BearerTokenRequest( HttpMethod.GET, Domains.PREVIEWIAM.toString(), path @@ -66,7 +66,7 @@ public Account fetch(final TwilioRestClient client) { "Account fetch failed: Unable to connect to server" ); } else if ( - !TwilioRestClient.SUCCESS.test(response.getStatusCode()) + !BearerTokenTwilioRestClient.SUCCESS.test(response.getStatusCode()) ) { RestException restException = RestException.fromJson( response.getStream(), diff --git a/src/main/java/com/twilio/rest/previewiam/organizations/AccountReader.java b/src/main/java/com/twilio/rest/previewiam/organizations/AccountReader.java index 7c2a384f3f..5ad736ac13 100644 --- a/src/main/java/com/twilio/rest/previewiam/organizations/AccountReader.java +++ b/src/main/java/com/twilio/rest/previewiam/organizations/AccountReader.java @@ -14,17 +14,17 @@ package com.twilio.rest.previewiam.organizations; -import com.twilio.base.Page; -import com.twilio.base.Reader; -import com.twilio.base.ResourceSet; +import com.twilio.base.bearertoken.Page; +import com.twilio.base.bearertoken.Reader; +import com.twilio.base.bearertoken.ResourceSet; import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; import com.twilio.http.HttpMethod; -import com.twilio.http.Request; import com.twilio.http.Response; -import com.twilio.http.TwilioRestClient; +import com.twilio.http.bearertoken.BearerTokenRequest; +import com.twilio.http.bearertoken.BearerTokenTwilioRestClient; import com.twilio.rest.Domains; public class AccountReader extends Reader { @@ -42,11 +42,11 @@ public AccountReader setPageSize(final Integer pageSize) { } @Override - public ResourceSet read(final TwilioRestClient client) { + public ResourceSet read(final BearerTokenTwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } - public Page firstPage(final TwilioRestClient client) { + public Page firstPage(final BearerTokenTwilioRestClient client) { String path = "/Organizations/{OrganizationSid}/Accounts"; path = path.replace( @@ -54,7 +54,7 @@ public Page firstPage(final TwilioRestClient client) { this.pathOrganizationSid.toString() ); - Request request = new Request( + BearerTokenRequest request = new BearerTokenRequest( HttpMethod.GET, Domains.PREVIEWIAM.toString(), path @@ -66,8 +66,8 @@ public Page firstPage(final TwilioRestClient client) { } private Page pageForRequest( - final TwilioRestClient client, - final Request request + final BearerTokenTwilioRestClient client, + final BearerTokenRequest request ) { Response response = client.request(request); @@ -76,7 +76,7 @@ private Page pageForRequest( "Account read failed: Unable to connect to server" ); } else if ( - !TwilioRestClient.SUCCESS.test(response.getStatusCode()) + !BearerTokenTwilioRestClient.SUCCESS.test(response.getStatusCode()) ) { RestException restException = RestException.fromJson( response.getStream(), @@ -102,9 +102,9 @@ private Page pageForRequest( @Override public Page previousPage( final Page page, - final TwilioRestClient client + final BearerTokenTwilioRestClient client ) { - Request request = new Request( + BearerTokenRequest request = new BearerTokenRequest( HttpMethod.GET, page.getPreviousPageUrl(Domains.PREVIEWIAM.toString()) ); @@ -114,9 +114,9 @@ public Page previousPage( @Override public Page nextPage( final Page page, - final TwilioRestClient client + final BearerTokenTwilioRestClient client ) { - Request request = new Request( + BearerTokenRequest request = new BearerTokenRequest( HttpMethod.GET, page.getNextPageUrl(Domains.PREVIEWIAM.toString()) ); @@ -126,9 +126,9 @@ public Page nextPage( @Override public Page getPage( final String targetUrl, - final TwilioRestClient client + final BearerTokenTwilioRestClient client ) { - Request request = new Request( + BearerTokenRequest request = new BearerTokenRequest( HttpMethod.GET, targetUrl ); @@ -136,7 +136,7 @@ public Page getPage( return pageForRequest(client, request); } - private void addQueryParams(final Request request) { + private void addQueryParams(final BearerTokenRequest request) { if (pageSize != null) { request.addQueryParam("PageSize", pageSize.toString()); } diff --git a/src/main/java/com/twilio/rest/previewiam/organizations/RoleAssignment.java b/src/main/java/com/twilio/rest/previewiam/organizations/RoleAssignment.java index 882781fe09..875068a004 100644 --- a/src/main/java/com/twilio/rest/previewiam/organizations/RoleAssignment.java +++ b/src/main/java/com/twilio/rest/previewiam/organizations/RoleAssignment.java @@ -22,7 +22,7 @@ import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; -import com.twilio.base.Resource; +import com.twilio.base.bearertoken.Resource; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import java.io.IOException; diff --git a/src/main/java/com/twilio/rest/previewiam/organizations/RoleAssignmentCreator.java b/src/main/java/com/twilio/rest/previewiam/organizations/RoleAssignmentCreator.java index 1a22c181ed..e95e19a4b1 100644 --- a/src/main/java/com/twilio/rest/previewiam/organizations/RoleAssignmentCreator.java +++ b/src/main/java/com/twilio/rest/previewiam/organizations/RoleAssignmentCreator.java @@ -15,15 +15,15 @@ package com.twilio.rest.previewiam.organizations; import com.fasterxml.jackson.databind.ObjectMapper; -import com.twilio.base.Creator; +import com.twilio.base.bearertoken.Creator; import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; import com.twilio.http.HttpMethod; -import com.twilio.http.Request; import com.twilio.http.Response; -import com.twilio.http.TwilioRestClient; +import com.twilio.http.bearertoken.BearerTokenRequest; +import com.twilio.http.bearertoken.BearerTokenTwilioRestClient; import com.twilio.rest.Domains; public class RoleAssignmentCreator extends Creator { @@ -49,7 +49,7 @@ public RoleAssignmentCreator setPublicApiCreateRoleAssignmentRequest( } @Override - public RoleAssignment create(final TwilioRestClient client) { + public RoleAssignment create(final BearerTokenTwilioRestClient client) { String path = "/Organizations/{OrganizationSid}/RoleAssignments"; path = @@ -63,7 +63,7 @@ public RoleAssignment create(final TwilioRestClient client) { this.publicApiCreateRoleAssignmentRequest.toString() ); - Request request = new Request( + BearerTokenRequest request = new BearerTokenRequest( HttpMethod.POST, Domains.PREVIEWIAM.toString(), path @@ -76,7 +76,7 @@ public RoleAssignment create(final TwilioRestClient client) { "RoleAssignment creation failed: Unable to connect to server" ); } else if ( - !TwilioRestClient.SUCCESS.test(response.getStatusCode()) + !BearerTokenTwilioRestClient.SUCCESS.test(response.getStatusCode()) ) { RestException restException = RestException.fromJson( response.getStream(), @@ -98,8 +98,8 @@ public RoleAssignment create(final TwilioRestClient client) { } private void addPostParams( - final Request request, - TwilioRestClient client + final BearerTokenRequest request, + BearerTokenTwilioRestClient client ) { ObjectMapper objectMapper = client.getObjectMapper(); if (publicApiCreateRoleAssignmentRequest != null) { diff --git a/src/main/java/com/twilio/rest/previewiam/organizations/RoleAssignmentDeleter.java b/src/main/java/com/twilio/rest/previewiam/organizations/RoleAssignmentDeleter.java index 514bacadf6..43cc107708 100644 --- a/src/main/java/com/twilio/rest/previewiam/organizations/RoleAssignmentDeleter.java +++ b/src/main/java/com/twilio/rest/previewiam/organizations/RoleAssignmentDeleter.java @@ -14,15 +14,15 @@ package com.twilio.rest.previewiam.organizations; -import com.twilio.base.Deleter; +import com.twilio.base.bearertoken.Deleter; import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; import com.twilio.http.HttpMethod; import com.twilio.http.Response; -import com.twilio.http.Request; -import com.twilio.http.TwilioRestClient; +import com.twilio.http.bearertoken.BearerTokenRequest; +import com.twilio.http.bearertoken.BearerTokenTwilioRestClient; import com.twilio.rest.Domains; public class RoleAssignmentDeleter extends Deleter { @@ -39,7 +39,7 @@ public RoleAssignmentDeleter( } @Override - public boolean delete(final TwilioRestClient client) { + public boolean delete(final BearerTokenTwilioRestClient client) { String path = "/Organizations/{OrganizationSid}/RoleAssignments/{RoleAssignmentSid}"; @@ -54,7 +54,7 @@ public boolean delete(final TwilioRestClient client) { this.pathRoleAssignmentSid.toString() ); - Request request = new Request( + BearerTokenRequest request = new BearerTokenRequest( HttpMethod.DELETE, Domains.PREVIEWIAM.toString(), path @@ -67,7 +67,7 @@ public boolean delete(final TwilioRestClient client) { "RoleAssignment delete failed: Unable to connect to server" ); } else if ( - !TwilioRestClient.SUCCESS.test(response.getStatusCode()) + !BearerTokenTwilioRestClient.SUCCESS.test(response.getStatusCode()) ) { RestException restException = RestException.fromJson( response.getStream(), diff --git a/src/main/java/com/twilio/rest/previewiam/organizations/RoleAssignmentReader.java b/src/main/java/com/twilio/rest/previewiam/organizations/RoleAssignmentReader.java index e10fca0991..05bb8e8b81 100644 --- a/src/main/java/com/twilio/rest/previewiam/organizations/RoleAssignmentReader.java +++ b/src/main/java/com/twilio/rest/previewiam/organizations/RoleAssignmentReader.java @@ -14,17 +14,17 @@ package com.twilio.rest.previewiam.organizations; -import com.twilio.base.Page; -import com.twilio.base.Reader; -import com.twilio.base.ResourceSet; +import com.twilio.base.bearertoken.Page; +import com.twilio.base.bearertoken.Reader; +import com.twilio.base.bearertoken.ResourceSet; import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; import com.twilio.http.HttpMethod; import com.twilio.http.Response; -import com.twilio.http.Request; -import com.twilio.http.TwilioRestClient; +import com.twilio.http.bearertoken.BearerTokenRequest; +import com.twilio.http.bearertoken.BearerTokenTwilioRestClient; import com.twilio.rest.Domains; public class RoleAssignmentReader extends Reader { @@ -55,13 +55,13 @@ public RoleAssignmentReader setScope(final String scope) { @Override public ResourceSet read( - final TwilioRestClient client + final BearerTokenTwilioRestClient client ) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage( - final TwilioRestClient client + final BearerTokenTwilioRestClient client ) { String path = "/Organizations/{OrganizationSid}/RoleAssignments"; path = @@ -70,7 +70,7 @@ public Page firstPage( this.pathOrganizationSid.toString() ); - Request request = new Request( + BearerTokenRequest request = new BearerTokenRequest( HttpMethod.GET, Domains.PREVIEWIAM.toString(), path @@ -82,8 +82,8 @@ public Page firstPage( } private Page pageForRequest( - final TwilioRestClient client, - final Request request + final BearerTokenTwilioRestClient client, + final BearerTokenRequest request ) { Response response = client.request(request); @@ -92,7 +92,7 @@ private Page pageForRequest( "RoleAssignment read failed: Unable to connect to server" ); } else if ( - !TwilioRestClient.SUCCESS.test(response.getStatusCode()) + !BearerTokenTwilioRestClient.SUCCESS.test(response.getStatusCode()) ) { RestException restException = RestException.fromJson( response.getStream(), @@ -118,9 +118,9 @@ private Page pageForRequest( @Override public Page previousPage( final Page page, - final TwilioRestClient client + final BearerTokenTwilioRestClient client ) { - Request request = new Request( + BearerTokenRequest request = new BearerTokenRequest( HttpMethod.GET, page.getPreviousPageUrl(Domains.PREVIEWIAM.toString()) ); @@ -130,9 +130,9 @@ public Page previousPage( @Override public Page nextPage( final Page page, - final TwilioRestClient client + final BearerTokenTwilioRestClient client ) { - Request request = new Request( + BearerTokenRequest request = new BearerTokenRequest( HttpMethod.GET, page.getNextPageUrl(Domains.PREVIEWIAM.toString()) ); @@ -142,9 +142,9 @@ public Page nextPage( @Override public Page getPage( final String targetUrl, - final TwilioRestClient client + final BearerTokenTwilioRestClient client ) { - Request request = new Request( + BearerTokenRequest request = new BearerTokenRequest( HttpMethod.GET, targetUrl ); @@ -152,7 +152,7 @@ public Page getPage( return pageForRequest(client, request); } - private void addQueryParams(final Request request) { + private void addQueryParams(final BearerTokenRequest request) { if (pageSize != null) { request.addQueryParam("PageSize", pageSize.toString()); } diff --git a/src/main/java/com/twilio/rest/previewiam/organizations/User.java b/src/main/java/com/twilio/rest/previewiam/organizations/User.java index 94359dbbbf..2e3a501701 100644 --- a/src/main/java/com/twilio/rest/previewiam/organizations/User.java +++ b/src/main/java/com/twilio/rest/previewiam/organizations/User.java @@ -22,7 +22,7 @@ import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; -import com.twilio.base.Resource; +import com.twilio.base.bearertoken.Resource; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import java.io.IOException; diff --git a/src/main/java/com/twilio/rest/previewiam/organizations/UserCreator.java b/src/main/java/com/twilio/rest/previewiam/organizations/UserCreator.java index e768088a50..92d390ed29 100644 --- a/src/main/java/com/twilio/rest/previewiam/organizations/UserCreator.java +++ b/src/main/java/com/twilio/rest/previewiam/organizations/UserCreator.java @@ -15,15 +15,15 @@ package com.twilio.rest.previewiam.organizations; import com.fasterxml.jackson.databind.ObjectMapper; -import com.twilio.base.Creator; +import com.twilio.base.bearertoken.Creator; import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; import com.twilio.http.HttpMethod; import com.twilio.http.Response; -import com.twilio.http.TwilioRestClient; -import com.twilio.http.Request; +import com.twilio.http.bearertoken.BearerTokenRequest; +import com.twilio.http.bearertoken.BearerTokenTwilioRestClient; import com.twilio.rest.Domains; public class UserCreator extends Creator { @@ -45,7 +45,7 @@ public UserCreator setScimUser(final User.ScimUser scimUser) { } @Override - public User create(final TwilioRestClient client) { + public User create(final BearerTokenTwilioRestClient client) { String path = "/Organizations/{OrganizationSid}/scim/Users"; path = @@ -55,7 +55,7 @@ public User create(final TwilioRestClient client) { ); path = path.replace("{" + "ScimUser" + "}", this.scimUser.toString()); - Request request = new Request( + BearerTokenRequest request = new BearerTokenRequest( HttpMethod.POST, Domains.PREVIEWIAM.toString(), path @@ -68,7 +68,7 @@ public User create(final TwilioRestClient client) { "User creation failed: Unable to connect to server" ); } else if ( - !TwilioRestClient.SUCCESS.test(response.getStatusCode()) + !BearerTokenTwilioRestClient.SUCCESS.test(response.getStatusCode()) ) { RestException restException = RestException.fromJson( response.getStream(), @@ -87,8 +87,8 @@ public User create(final TwilioRestClient client) { } private void addPostParams( - final Request request, - TwilioRestClient client + final BearerTokenRequest request, + BearerTokenTwilioRestClient client ) { ObjectMapper objectMapper = client.getObjectMapper(); if (scimUser != null) { diff --git a/src/main/java/com/twilio/rest/previewiam/organizations/UserDeleter.java b/src/main/java/com/twilio/rest/previewiam/organizations/UserDeleter.java index dcb8c56787..6f44db1c69 100644 --- a/src/main/java/com/twilio/rest/previewiam/organizations/UserDeleter.java +++ b/src/main/java/com/twilio/rest/previewiam/organizations/UserDeleter.java @@ -14,15 +14,15 @@ package com.twilio.rest.previewiam.organizations; -import com.twilio.base.Deleter; +import com.twilio.base.bearertoken.Deleter; import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; import com.twilio.http.HttpMethod; import com.twilio.http.Response; -import com.twilio.http.Request; -import com.twilio.http.TwilioRestClient; +import com.twilio.http.bearertoken.BearerTokenRequest; +import com.twilio.http.bearertoken.BearerTokenTwilioRestClient; import com.twilio.rest.Domains; public class UserDeleter extends Deleter { @@ -39,7 +39,7 @@ public UserDeleter( } @Override - public boolean delete(final TwilioRestClient client) { + public boolean delete(final BearerTokenTwilioRestClient client) { String path = "/Organizations/{OrganizationSid}/scim/Users/{UserSid}"; path = @@ -49,7 +49,7 @@ public boolean delete(final TwilioRestClient client) { ); path = path.replace("{" + "UserSid" + "}", this.pathUserSid.toString()); - Request request = new Request( + BearerTokenRequest request = new BearerTokenRequest( HttpMethod.DELETE, Domains.PREVIEWIAM.toString(), path @@ -62,7 +62,7 @@ public boolean delete(final TwilioRestClient client) { "User delete failed: Unable to connect to server" ); } else if ( - !TwilioRestClient.SUCCESS.test(response.getStatusCode()) + !BearerTokenTwilioRestClient.SUCCESS.test(response.getStatusCode()) ) { RestException restException = RestException.fromJson( response.getStream(), diff --git a/src/main/java/com/twilio/rest/previewiam/organizations/UserFetcher.java b/src/main/java/com/twilio/rest/previewiam/organizations/UserFetcher.java index 0270ac88dc..3abc3e86eb 100644 --- a/src/main/java/com/twilio/rest/previewiam/organizations/UserFetcher.java +++ b/src/main/java/com/twilio/rest/previewiam/organizations/UserFetcher.java @@ -14,15 +14,15 @@ package com.twilio.rest.previewiam.organizations; -import com.twilio.base.Fetcher; +import com.twilio.base.bearertoken.Fetcher; import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; import com.twilio.http.HttpMethod; import com.twilio.http.Response; -import com.twilio.http.Request; -import com.twilio.http.TwilioRestClient; +import com.twilio.http.bearertoken.BearerTokenRequest; +import com.twilio.http.bearertoken.BearerTokenTwilioRestClient; import com.twilio.rest.Domains; public class UserFetcher extends Fetcher { @@ -39,7 +39,7 @@ public UserFetcher( } @Override - public User fetch(final TwilioRestClient client) { + public User fetch(final BearerTokenTwilioRestClient client) { String path = "/Organizations/{OrganizationSid}/scim/Users/{UserSid}"; path = @@ -49,7 +49,7 @@ public User fetch(final TwilioRestClient client) { ); path = path.replace("{" + "UserSid" + "}", this.pathUserSid.toString()); - Request request = new Request( + BearerTokenRequest request = new BearerTokenRequest( HttpMethod.GET, Domains.PREVIEWIAM.toString(), path @@ -62,7 +62,7 @@ public User fetch(final TwilioRestClient client) { "User fetch failed: Unable to connect to server" ); } else if ( - !TwilioRestClient.SUCCESS.test(response.getStatusCode()) + !BearerTokenTwilioRestClient.SUCCESS.test(response.getStatusCode()) ) { RestException restException = RestException.fromJson( response.getStream(), diff --git a/src/main/java/com/twilio/rest/previewiam/organizations/UserReader.java b/src/main/java/com/twilio/rest/previewiam/organizations/UserReader.java index c6bb6a57eb..2ebdb45da6 100644 --- a/src/main/java/com/twilio/rest/previewiam/organizations/UserReader.java +++ b/src/main/java/com/twilio/rest/previewiam/organizations/UserReader.java @@ -14,17 +14,17 @@ package com.twilio.rest.previewiam.organizations; -import com.twilio.base.Page; -import com.twilio.base.Reader; -import com.twilio.base.ResourceSet; +import com.twilio.base.bearertoken.Page; +import com.twilio.base.bearertoken.Reader; +import com.twilio.base.bearertoken.ResourceSet; import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; import com.twilio.http.HttpMethod; import com.twilio.http.Response; -import com.twilio.http.Request; -import com.twilio.http.TwilioRestClient; +import com.twilio.http.bearertoken.BearerTokenRequest; +import com.twilio.http.bearertoken.BearerTokenTwilioRestClient; import com.twilio.rest.Domains; public class UserReader extends Reader { @@ -42,11 +42,11 @@ public UserReader setFilter(final String filter) { } @Override - public ResourceSet read(final TwilioRestClient client) { + public ResourceSet read(final BearerTokenTwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } - public Page firstPage(final TwilioRestClient client) { + public Page firstPage(final BearerTokenTwilioRestClient client) { String path = "/Organizations/{OrganizationSid}/scim/Users"; path = path.replace( @@ -54,7 +54,7 @@ public Page firstPage(final TwilioRestClient client) { this.pathOrganizationSid.toString() ); - Request request = new Request( + BearerTokenRequest request = new BearerTokenRequest( HttpMethod.GET, Domains.PREVIEWIAM.toString(), path @@ -66,8 +66,8 @@ public Page firstPage(final TwilioRestClient client) { } private Page pageForRequest( - final TwilioRestClient client, - final Request request + final BearerTokenTwilioRestClient client, + final BearerTokenRequest request ) { Response response = client.request(request); @@ -76,7 +76,7 @@ private Page pageForRequest( "User read failed: Unable to connect to server" ); } else if ( - !TwilioRestClient.SUCCESS.test(response.getStatusCode()) + !BearerTokenTwilioRestClient.SUCCESS.test(response.getStatusCode()) ) { RestException restException = RestException.fromJson( response.getStream(), @@ -102,9 +102,9 @@ private Page pageForRequest( @Override public Page previousPage( final Page page, - final TwilioRestClient client + final BearerTokenTwilioRestClient client ) { - Request request = new Request( + BearerTokenRequest request = new BearerTokenRequest( HttpMethod.GET, page.getPreviousPageUrl(Domains.PREVIEWIAM.toString()) ); @@ -114,9 +114,9 @@ public Page previousPage( @Override public Page nextPage( final Page page, - final TwilioRestClient client + final BearerTokenTwilioRestClient client ) { - Request request = new Request( + BearerTokenRequest request = new BearerTokenRequest( HttpMethod.GET, page.getNextPageUrl(Domains.PREVIEWIAM.toString()) ); @@ -126,9 +126,9 @@ public Page nextPage( @Override public Page getPage( final String targetUrl, - final TwilioRestClient client + final BearerTokenTwilioRestClient client ) { - Request request = new Request( + BearerTokenRequest request = new BearerTokenRequest( HttpMethod.GET, targetUrl ); @@ -136,7 +136,7 @@ public Page getPage( return pageForRequest(client, request); } - private void addQueryParams(final Request request) { + private void addQueryParams(final BearerTokenRequest request) { if (filter != null) { request.addQueryParam("filter", filter); } diff --git a/src/main/java/com/twilio/rest/previewiam/organizations/UserUpdater.java b/src/main/java/com/twilio/rest/previewiam/organizations/UserUpdater.java index 9b3c2a0d4b..b68b8557f0 100644 --- a/src/main/java/com/twilio/rest/previewiam/organizations/UserUpdater.java +++ b/src/main/java/com/twilio/rest/previewiam/organizations/UserUpdater.java @@ -15,15 +15,15 @@ package com.twilio.rest.previewiam.organizations; import com.fasterxml.jackson.databind.ObjectMapper; -import com.twilio.base.Updater; +import com.twilio.base.bearertoken.Updater; import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; import com.twilio.http.HttpMethod; import com.twilio.http.Response; -import com.twilio.http.Request; -import com.twilio.http.TwilioRestClient; +import com.twilio.http.bearertoken.BearerTokenRequest; +import com.twilio.http.bearertoken.BearerTokenTwilioRestClient; import com.twilio.rest.Domains; public class UserUpdater extends Updater { @@ -54,7 +54,7 @@ public UserUpdater setIfMatch(final String ifMatch) { } @Override - public User update(final TwilioRestClient client) { + public User update(final BearerTokenTwilioRestClient client) { String path = "/Organizations/{OrganizationSid}/scim/Users/{UserSid}"; path = @@ -65,7 +65,7 @@ public User update(final TwilioRestClient client) { path = path.replace("{" + "UserSid" + "}", this.pathUserSid.toString()); path = path.replace("{" + "ScimUser" + "}", this.scimUser.toString()); - Request request = new Request( + BearerTokenRequest request = new BearerTokenRequest( HttpMethod.PUT, Domains.PREVIEWIAM.toString(), path @@ -79,7 +79,7 @@ public User update(final TwilioRestClient client) { "User update failed: Unable to connect to server" ); } else if ( - !TwilioRestClient.SUCCESS.test(response.getStatusCode()) + !BearerTokenTwilioRestClient.SUCCESS.test(response.getStatusCode()) ) { RestException restException = RestException.fromJson( response.getStream(), @@ -98,8 +98,8 @@ public User update(final TwilioRestClient client) { } private void addPostParams( - final Request request, - TwilioRestClient client + final BearerTokenRequest request, + BearerTokenTwilioRestClient client ) { ObjectMapper objectMapper = client.getObjectMapper(); if (scimUser != null) { @@ -107,7 +107,7 @@ private void addPostParams( } } - private void addHeaderParams(final Request request) { + private void addHeaderParams(final BearerTokenRequest request) { if (ifMatch != null) { request.addHeaderParam("If-Match", ifMatch); } diff --git a/src/test/java/com/twilio/ClusterTest.java b/src/test/java/com/twilio/ClusterTest.java index e21df98c3a..50062a5486 100644 --- a/src/test/java/com/twilio/ClusterTest.java +++ b/src/test/java/com/twilio/ClusterTest.java @@ -1,12 +1,10 @@ package com.twilio; -import com.twilio.auth_strategy.TokenAuthStrategy; import com.twilio.base.Page; -import com.twilio.base.ResourceSet; +import com.twilio.base.bearertoken.ResourceSet; +import com.twilio.credential.ClientCredentialProvider; import com.twilio.http.CustomHttpClient; import com.twilio.http.TwilioRestClient; -import com.twilio.http.bearertoken.OrgsTokenManager; -import com.twilio.http.bearertoken.TokenManager; import com.twilio.rest.api.v2010.account.IncomingPhoneNumber; import com.twilio.rest.api.v2010.account.IncomingPhoneNumberReader; import com.twilio.rest.api.v2010.account.Message; @@ -59,7 +57,8 @@ public void setUp() { orgsClientId = System.getenv("TWILIO_ORGS_CLIENT_ID"); orgsClientSecret = System.getenv("TWILIO_ORGS_CLIENT_SECRET"); organisationSid = System.getenv("TWILIO_ORG_SID"); - + TwilioOrgsTokenAuth.init(grantType, orgsClientId, orgsClientSecret); + clientId = System.getenv("TWILIO_CLIENT_ID"); clientSecret = System.getenv("TWILIO_CLIENT_SECRET"); messageSid = System.getenv("TWILIO_MESSAGE_SID"); @@ -141,25 +140,19 @@ public void testListParams() { @Test public void testOrgsApi(){ - //Twilio.init(new OrgsClientCredentialProvider(orgsClientId, orgsClientSecret)); - - TokenManager tokenManager = new OrgsTokenManager("client_credentials", orgsClientId, orgsClientSecret); - TokenAuthStrategy tokenAuthStrategy = new TokenAuthStrategy(tokenManager); - TwilioRestClient client = new TwilioRestClient.Builder(tokenAuthStrategy) - .build(); //Fetching the account information - ResourceSet accountSet = Account.reader(organisationSid).read(client); + ResourceSet accountSet = Account.reader(organisationSid).read(); String accountSid = accountSet.iterator().next().getAccountSid(); assertNotNull(accountSid); //Fetching specific account - Account account = Account.fetcher(organisationSid, accountSid).fetch(client); + Account account = Account.fetcher(organisationSid, accountSid).fetch(); assertNotNull(account.getAccountSid()); //Fetching users of this organisation ResourceSet - userSet = com.twilio.rest.previewiam.organizations.User.reader(organisationSid).read(client); + userSet = com.twilio.rest.previewiam.organizations.User.reader(organisationSid).read(); assertNotNull(userSet); String userId = userSet.iterator().next().getId().toString(); assertNotNull(userId); diff --git a/src/test/java/com/twilio/http/bearerToken/BearerTokenNetworkHttpClientTest.java b/src/test/java/com/twilio/http/bearerToken/BearerTokenNetworkHttpClientTest.java new file mode 100644 index 0000000000..41094c2ff6 --- /dev/null +++ b/src/test/java/com/twilio/http/bearerToken/BearerTokenNetworkHttpClientTest.java @@ -0,0 +1,213 @@ +package com.twilio.http.bearerToken; + +import com.twilio.constant.EnumConstants; +import com.twilio.exception.ApiException; +import com.twilio.http.HttpMethod; +import com.twilio.http.Response; +import com.twilio.http.bearertoken.BearerTokenNetworkHttpClient; +import com.twilio.http.bearertoken.BearerTokenRequest; +import org.apache.hc.client5.http.impl.classic.CloseableHttpClient; +import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse; +import org.apache.hc.client5.http.impl.classic.HttpClientBuilder; +import org.apache.hc.core5.http.HttpEntity; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.mockito.Spy; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.net.URL; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +public class BearerTokenNetworkHttpClientTest { + + private BearerTokenNetworkHttpClient client; + + @Mock + private BearerTokenRequest mockRequest; + + @Spy + private HttpClientBuilder mockBuilder; + + @Mock + private CloseableHttpClient mockClient; + + @Mock + private CloseableHttpResponse mockResponse; + + @Mock + private HttpEntity mockEntity; + + @Before + public void setUp() { + MockitoAnnotations.openMocks(this); + doReturn(mockClient).when(mockBuilder).build(); + client = new BearerTokenNetworkHttpClient(mockBuilder); + } + + private void setup( + final int statusCode, + final String content, + final HttpMethod method, + final Boolean requiresAuthentication + ) throws IOException { + final InputStream stream = new ByteArrayInputStream(content.getBytes("UTF-8")); + + when(mockRequest.getMethod()).thenReturn(method); + when(mockRequest.constructURL()).thenReturn(new URL("http://foo.com/hello")); + when(mockRequest.requiresAuthentication()).thenReturn(requiresAuthentication); + when(mockRequest.getAuthString()).thenReturn("Bearer token123"); + when(mockRequest.getContentType()).thenReturn(EnumConstants.ContentType.FORM_URLENCODED); + when(mockClient.execute(any())).thenReturn(mockResponse); + when(mockEntity.isRepeatable()).thenReturn(true); + when(mockEntity.getContentLength()).thenReturn(1L); + when(mockEntity.getContent()).thenReturn(stream); + when(mockResponse.getEntity()).thenReturn(mockEntity); + when(mockResponse.getCode()).thenReturn(statusCode); + } + + @Test + public void testGet() throws IOException { + setup(200, "success", HttpMethod.GET, false); + + Response resp = client.makeRequest(mockRequest); + + assertEquals(200, resp.getStatusCode()); + assertEquals("success", resp.getContent()); + } + + @Test + public void testGetWithAuthentication() throws IOException { + setup(200, "authenticated", HttpMethod.GET, true); + + Response resp = client.makeRequest(mockRequest); + + assertEquals(200, resp.getStatusCode()); + assertEquals("authenticated", resp.getContent()); + } + + @Test + public void testPost() throws IOException { + setup(201, "created", HttpMethod.POST, false); + + Response resp = client.makeRequest(mockRequest); + + assertEquals(201, resp.getStatusCode()); + assertEquals("created", resp.getContent()); + } + + @Test + public void testJsonPost() throws IOException { + setup(201, "created", HttpMethod.POST, false); + when(mockRequest.getContentType()).thenReturn(EnumConstants.ContentType.JSON); + String body = "{\"name\":\"value\"}"; + when(mockRequest.getBody()).thenReturn(body); + + Response resp = client.makeRequest(mockRequest); + + assertEquals(201, resp.getStatusCode()); + assertEquals("created", resp.getContent()); + } + + @Test + public void testFormUrlEncodedPost() throws IOException { + setup(201, "form-urlencoded", HttpMethod.POST, false); + + // Set up post parameters + Map> postParams = new HashMap<>(); + postParams.put("name", Arrays.asList("John Doe")); + postParams.put("tags", Arrays.asList("customer", "premium")); + when(mockRequest.getPostParams()).thenReturn(postParams); + + Response resp = client.makeRequest(mockRequest); + + assertEquals(201, resp.getStatusCode()); + assertEquals("form-urlencoded", resp.getContent()); + } + + @Test + public void testPut() throws IOException { + setup(200, "updated", HttpMethod.PUT, false); + + Response resp = client.makeRequest(mockRequest); + + assertEquals(200, resp.getStatusCode()); + assertEquals("updated", resp.getContent()); + } + + @Test + public void testPatch() throws IOException { + setup(200, "patched", HttpMethod.PATCH, false); + + Response resp = client.makeRequest(mockRequest); + + assertEquals(200, resp.getStatusCode()); + assertEquals("patched", resp.getContent()); + } + + @Test + public void testDelete() throws IOException { + setup(204, "", HttpMethod.DELETE, false); + + Response resp = client.makeRequest(mockRequest); + + assertEquals(204, resp.getStatusCode()); + assertEquals("", resp.getContent()); + } + + @Test + public void testWithCustomHeaders() throws IOException { + setup(200, "headers", HttpMethod.GET, false); + + Map> headers = new HashMap<>(); + headers.put("X-Custom-Header", Arrays.asList("CustomValue")); + headers.put("Accept-Language", Arrays.asList("en-US")); + when(mockRequest.getHeaderParams()).thenReturn(headers); + + Response resp = client.makeRequest(mockRequest); + + assertEquals(200, resp.getStatusCode()); + assertEquals("headers", resp.getContent()); + } + + @Test(expected = ApiException.class) + public void testIOException() throws IOException { + when(mockRequest.getMethod()).thenReturn(HttpMethod.GET); + when(mockRequest.constructURL()).thenReturn(new URL("http://foo.com/hello")); + when(mockRequest.requiresAuthentication()).thenReturn(false); + when(mockClient.execute(any())).thenThrow(new IOException("Connection error")); + + client.makeRequest(mockRequest); + } + + @Test + public void testReliableRequest() { + BearerTokenRequest request = mock(BearerTokenRequest.class); + when(request.getMethod()).thenReturn(HttpMethod.GET); + + BearerTokenNetworkHttpClient clientSpy = spy(client); + doReturn(new Response("", 204)).when(clientSpy).makeRequest(request); + + clientSpy.reliableRequest(request); + + assertNotNull(clientSpy.getLastRequest()); + assertNotNull(clientSpy.getLastResponse()); + } +} From 303bf6da9125c606c6091908048057a28679874d Mon Sep 17 00:00:00 2001 From: sbansla <104902068+sbansla@users.noreply.github.com> Date: Thu, 18 Sep 2025 15:34:52 +0530 Subject: [PATCH 22/32] chore: Reuse twiliorestclient for orgs api (#900) * removed bearer token files used for Orgs API and reusing twiliorestclient --- README.md | 4 +- examples/BearerTokenAuthentication.md | 26 -- examples/FetchMessageUsingOAuth.md | 21 -- examples/OrgsAPIExample.md | 34 +++ examples/PublicOAuthExample.md | 35 +++ .../java/com/twilio/TwilioOrgsTokenAuth.java | 106 ------- src/main/java/com/twilio/base/Page.java | 6 +- .../com/twilio/base/bearertoken/Creator.java | 50 ---- .../com/twilio/base/bearertoken/Deleter.java | 51 ---- .../com/twilio/base/bearertoken/Fetcher.java | 50 ---- .../com/twilio/base/bearertoken/Page.java | 270 ------------------ .../com/twilio/base/bearertoken/Reader.java | 156 ---------- .../com/twilio/base/bearertoken/Resource.java | 9 - .../twilio/base/bearertoken/ResourceSet.java | 138 --------- .../com/twilio/base/bearertoken/Updater.java | 50 ---- .../orgs/OrgsClientCredentialProvider.java | 62 +++- .../com/twilio/http/NetworkHttpClient.java | 2 +- .../bearertoken/BearerTokenHttpClient.java | 108 ------- .../BearerTokenNetworkHttpClient.java | 181 ------------ .../http/bearertoken/BearerTokenRequest.java | 38 --- .../BearerTokenTwilioRestClient.java | 186 ------------ .../previewiam/organizations/Account.java | 2 +- .../organizations/AccountFetcher.java | 12 +- .../organizations/AccountReader.java | 36 +-- .../organizations/RoleAssignment.java | 2 +- .../organizations/RoleAssignmentCreator.java | 16 +- .../organizations/RoleAssignmentDeleter.java | 12 +- .../organizations/RoleAssignmentReader.java | 36 +-- .../rest/previewiam/organizations/User.java | 2 +- .../previewiam/organizations/UserCreator.java | 16 +- .../previewiam/organizations/UserDeleter.java | 12 +- .../previewiam/organizations/UserFetcher.java | 12 +- .../previewiam/organizations/UserReader.java | 36 +-- .../previewiam/organizations/UserUpdater.java | 18 +- src/test/java/com/twilio/ClusterTest.java | 21 +- .../BearerTokenNetworkHttpClientTest.java | 213 -------------- 36 files changed, 257 insertions(+), 1772 deletions(-) delete mode 100644 examples/BearerTokenAuthentication.md delete mode 100644 examples/FetchMessageUsingOAuth.md create mode 100644 examples/OrgsAPIExample.md create mode 100644 examples/PublicOAuthExample.md delete mode 100644 src/main/java/com/twilio/TwilioOrgsTokenAuth.java delete mode 100644 src/main/java/com/twilio/base/bearertoken/Creator.java delete mode 100644 src/main/java/com/twilio/base/bearertoken/Deleter.java delete mode 100644 src/main/java/com/twilio/base/bearertoken/Fetcher.java delete mode 100644 src/main/java/com/twilio/base/bearertoken/Page.java delete mode 100644 src/main/java/com/twilio/base/bearertoken/Reader.java delete mode 100644 src/main/java/com/twilio/base/bearertoken/Resource.java delete mode 100644 src/main/java/com/twilio/base/bearertoken/ResourceSet.java delete mode 100644 src/main/java/com/twilio/base/bearertoken/Updater.java delete mode 100644 src/main/java/com/twilio/http/bearertoken/BearerTokenHttpClient.java delete mode 100644 src/main/java/com/twilio/http/bearertoken/BearerTokenNetworkHttpClient.java delete mode 100644 src/main/java/com/twilio/http/bearertoken/BearerTokenRequest.java delete mode 100644 src/main/java/com/twilio/http/bearertoken/BearerTokenTwilioRestClient.java delete mode 100644 src/test/java/com/twilio/http/bearerToken/BearerTokenNetworkHttpClientTest.java diff --git a/README.md b/README.md index c63cb6461a..c715b3a2fb 100644 --- a/README.md +++ b/README.md @@ -221,8 +221,8 @@ public class Example { We are introducing Client Credentials Flow-based OAuth 2.0 authentication. This feature is currently in `beta` and its implementation is subject to change. -- API examples [here](https://github.com/twilio/twilio-java/blob/main/examples/FetchMessageUsingOAuth.md) -- Organisation API examples [here](https://github.com/twilio/twilio-java/blob/main/examples/BearerTokenAuthentication.md) +- API examples [here](https://github.com/twilio/twilio-java/blob/main/examples/PublicOAuthExample.md) +- Organisation API examples [here](https://github.com/twilio/twilio-java/blob/main/examples/OrgsAPIExample.md) ### Iterate through records diff --git a/examples/BearerTokenAuthentication.md b/examples/BearerTokenAuthentication.md deleted file mode 100644 index 2618436b32..0000000000 --- a/examples/BearerTokenAuthentication.md +++ /dev/null @@ -1,26 +0,0 @@ - class BearerTokenAuthenticationExamples { - public static void main { - - private static final String GRANT_TYPE = "grant_type_to_be_used"; - private static final String CLIENT_SID = - "client_id_of_the_organization"; - private static final String CLIENT_SECRET = "client_secret_of_organization"; - private static final String ORGANISATION_ID = "id_of_the_organization"; - - //Getting access token - Method #1 - TwilioOrgsTokenAuth.init(GRANT_TYPE, CLIENT_ID, CLIENT_SECRET); - - //Getting access token - Method #2 - //To provide custom token manager implementation - //Need not call init method if customer token manager is passed - //TwilioOrgsTokenAuth.setTokenManager(new CustomTokenManagerImpl(GRANT_TYPE, CLIENT_ID, CLIENT_SECRET)); - - fetchAccountDetails(); - } - - private static void fetchAccountDetails() { - ResourceSet accountSet = Account.reader(ORGANISATION_ID).read(); - String accountSid = accountSet.iterator().next().getAccountSid(); - System.out.println(accountSid); - } - } \ No newline at end of file diff --git a/examples/FetchMessageUsingOAuth.md b/examples/FetchMessageUsingOAuth.md deleted file mode 100644 index ec667f1ab0..0000000000 --- a/examples/FetchMessageUsingOAuth.md +++ /dev/null @@ -1,21 +0,0 @@ -``` -import com.twilio.Twilio; -import com.twilio.credential.ClientCredentialProvider; -import com.twilio.rest.api.v2010.account.Message; - -public class FetchMessageUsingOAuth { - public static void main(String[] args) { - String clientId = "YOUR_CLIENT_ID"; - String clientSecret = "YOUR_CLIENT_SECRET"; - String accountSid = "YOUR_ACCOUNT_SID"; - Twilio.init(new ClientCredentialProvider(clientId, clientSecret), accountSid); - /* - Or use the following if accountSid is not required as a path parameter for an API or when setting accountSid in the API. - Twilio.init(new ClientCredentialProvider(clientId, clientSecret)); - */ - String messageSid = "YOUR_MESSAGE_SID"; - Message message = Message.fetcher(messageSid).fetch(); - } -} -``` - diff --git a/examples/OrgsAPIExample.md b/examples/OrgsAPIExample.md new file mode 100644 index 0000000000..b4511f88bc --- /dev/null +++ b/examples/OrgsAPIExample.md @@ -0,0 +1,34 @@ + class OrgsAPIExample { + public static void main { + + private static final String GRANT_TYPE = "grant_type_to_be_used"; + private static final String CLIENT_SID = + "client_id_of_the_organization"; + private static final String CLIENT_SECRET = "client_secret_of_organization"; + private static final String ORGANISATION_ID = "id_of_the_organization"; + + //Getting access token - Method #1 + Twilio.init(new OrgsClientCredentialProvider(CLIENT_SID, CLIENT_SECRET)); + fetchAccountDetails(); + + + //Scenario: 2 If in case one doesn't want to change the existing stored credential + // Pass Custom TwilioRestClient + // TokenManager tokenManager = new OrgsTokenManager(GRANT_TYPE, CLIENT_SID, CLIENT_SECRET); + // TokenAuthStrategy tokenAuthStrategy = new TokenAuthStrategy(tokenManager); + // TwilioRestClient client = new TwilioRestClient.Builder(tokenAuthStrategy).build(); + // fetchAccountDetailsWithClient(client); + } + + private static void fetchAccountDetails() { + ResourceSet accountSet = Account.reader(ORGANISATION_ID).read(); + String accountSid = accountSet.iterator().next().getAccountSid(); + System.out.println(accountSid); + } + + private static void fetchAccountDetailsWithClient(TwilioRestClient client) { + ResourceSet accountSet = Account.reader(ORGANISATION_ID).read(client); + String accountSid = accountSet.iterator().next().getAccountSid(); + System.out.println(accountSid); + } + } \ No newline at end of file diff --git a/examples/PublicOAuthExample.md b/examples/PublicOAuthExample.md new file mode 100644 index 0000000000..dce5027e9a --- /dev/null +++ b/examples/PublicOAuthExample.md @@ -0,0 +1,35 @@ +``` +class PublicOAuthExample { + public static void main { + + private static final String GRANT_TYPE = "grant_type_to_be_used"; + private static final String OAUTH_CLIENT_SID = "client_id"; + private static final String OAUTH_CLIENT_SECRET = "client_secret"; + private static final String ACCOUNT_SID = "account_sid"; + private static final String MESSAGE_SID = "message_sid"; + + //Getting access token - Method #1 + Twilio.init(new ClientCredentialProvider(OAUTH_CLIENT_SID, OAUTH_CLIENT_SECRET), ACCOUNT_SID); + fetchMessage(MESSAGE_SID); + + + //Scenario: 2 If in case one doesn't want to change the existing stored credential + // Pass Custom TwilioRestClient + // TokenManager tokenManager = new ApiTokenManager(GRANT_TYPE, OAUTH_CLIENT_SID, OAUTH_CLIENT_SECRET); + // TokenAuthStrategy tokenAuthStrategy = new TokenAuthStrategy(tokenManager); + // TwilioRestClient client = new TwilioRestClient.Builder(tokenAuthStrategy).accountSid(ACCOUNT_SID).build(); + // fetchMessageWithClient(MESSAGE_SID, client); + } + + public static void fetchMessage(String sid) { + Message message = Message.fetcher(sid).fetch(); + System.out.println("Fetched Message SID: " + message.getSid()); + } + + public static void fetchMessageWithClient(String sid, TwilioRestClient client) { + Message message = Message.fetcher(sid).fetch(client); + System.out.println("Fetched Message SID: " + message.getSid()); + } +} +``` + diff --git a/src/main/java/com/twilio/TwilioOrgsTokenAuth.java b/src/main/java/com/twilio/TwilioOrgsTokenAuth.java deleted file mode 100644 index 9b28d0b06f..0000000000 --- a/src/main/java/com/twilio/TwilioOrgsTokenAuth.java +++ /dev/null @@ -1,106 +0,0 @@ -package com.twilio; - -import com.twilio.annotations.Beta; -import com.twilio.exception.AuthenticationException; -import com.twilio.http.bearertoken.BearerTokenTwilioRestClient; -import lombok.Getter; -import lombok.Setter; - -import java.util.List; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import com.twilio.http.bearertoken.TokenManager; -import com.twilio.http.bearertoken.OrgsTokenManager; - -@Beta -public class TwilioOrgsTokenAuth { - private static String accessToken; - @Getter - private static List userAgentExtensions; - private static String region = System.getenv("TWILIO_REGION"); - private static String edge = System.getenv("TWILIO_EDGE"); - private static volatile BearerTokenTwilioRestClient restClient; - @Getter @Setter - private static TokenManager tokenManager; - - private static volatile ExecutorService executorService; - - private TwilioOrgsTokenAuth() { - } - - public static synchronized void init(String grantType, String clientId, String clientSecret) { - validateAuthCredentials(grantType, clientId, clientSecret); - tokenManager = new OrgsTokenManager(grantType, clientId, clientSecret); - } - public static synchronized void init(String grantType, String clientId, String clientSecret, String code, String redirectUri, String audience, String refreshToken, String scope) { - validateAuthCredentials(grantType, clientId, clientSecret); - tokenManager = new OrgsTokenManager(grantType, clientId, clientSecret, code, redirectUri, audience, refreshToken, scope); - } - - private static void validateAuthCredentials(String grantType, String clientId, String clientSecret){ - if (grantType == null) { - throw new AuthenticationException("Grant Type cannot be null"); - } - if (clientId == null) { - throw new AuthenticationException("Client Id cannot be null"); - } - if (clientSecret == null) { - throw new AuthenticationException("Client Secret cannot be null"); - } - return; - } - - public static BearerTokenTwilioRestClient getRestClient() { - if (TwilioOrgsTokenAuth.restClient == null) { - synchronized (TwilioOrgsTokenAuth.class) { - if (TwilioOrgsTokenAuth.restClient == null) { - TwilioOrgsTokenAuth.restClient = buildOAuthRestClient(); - } - } - } - return TwilioOrgsTokenAuth.restClient; - } - /** - * Returns the Twilio executor service. - * - * @return the Twilio executor service - */ - public static ExecutorService getExecutorService() { - if (TwilioOrgsTokenAuth.executorService == null) { - synchronized (TwilioOrgsTokenAuth.class) { - if (TwilioOrgsTokenAuth.executorService == null) { - TwilioOrgsTokenAuth.executorService = Executors.newCachedThreadPool(); - } - } - } - return TwilioOrgsTokenAuth.executorService; - } - - private static BearerTokenTwilioRestClient buildOAuthRestClient() { - - BearerTokenTwilioRestClient.Builder builder = new BearerTokenTwilioRestClient.Builder(); - - if (userAgentExtensions != null) { - builder.userAgentExtensions(TwilioOrgsTokenAuth.userAgentExtensions); - } - - builder.region(TwilioOrgsTokenAuth.region); - builder.edge(TwilioOrgsTokenAuth.edge); - if(TwilioOrgsTokenAuth.tokenManager == null){ - throw new AuthenticationException("Either initialize the authentications class or pass a custom token manager"); - } - builder.tokenManager(TwilioOrgsTokenAuth.tokenManager); - - return builder.build(); - } - - /** - * Invalidates the volatile state held in the Twilio singleton. - */ - private static void invalidate() { - TwilioOrgsTokenAuth.restClient = null; - TwilioOrgsTokenAuth.tokenManager = null; - } - - -} \ No newline at end of file diff --git a/src/main/java/com/twilio/base/Page.java b/src/main/java/com/twilio/base/Page.java index b03440007e..259e86e480 100644 --- a/src/main/java/com/twilio/base/Page.java +++ b/src/main/java/com/twilio/base/Page.java @@ -169,8 +169,9 @@ private static Page buildPage(JsonNode root, List results) { private static Page buildNextGenPage(JsonNode root, List results) { JsonNode meta = root.get("meta"); - Builder builder = new Builder().url(meta.get("url").asText()); - + Builder builder = new Builder<>(); + if(meta != null && meta.get("url") != null) { + builder = builder.url(meta.get("url").asText()); JsonNode nextPageNode = meta.get("next_page_url"); if (!nextPageNode.isNull()) { builder.nextPageUrl(nextPageNode.asText()); @@ -192,6 +193,7 @@ private static Page buildNextGenPage(JsonNode root, List results) { } else { builder.pageSize(results.size()); } + } return builder.records(results).build(); } diff --git a/src/main/java/com/twilio/base/bearertoken/Creator.java b/src/main/java/com/twilio/base/bearertoken/Creator.java deleted file mode 100644 index 8cb676cef6..0000000000 --- a/src/main/java/com/twilio/base/bearertoken/Creator.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.twilio.base.bearertoken; - -import com.twilio.TwilioOrgsTokenAuth; -import com.twilio.http.bearertoken.BearerTokenTwilioRestClient; - -import java.util.concurrent.CompletableFuture; - -/** - * Executor for creation of a resource. - * - * @param type of the resource - */ -public abstract class Creator { - - /** - * Execute an async request using default client. - * - * @return future that resolves to requested object - */ - public CompletableFuture createAsync() { - return createAsync(TwilioOrgsTokenAuth.getRestClient()); - } - - /** - * Execute an async request using specified client. - * - * @param client client used to make request - * @return future that resolves to requested object - */ - public CompletableFuture createAsync(final BearerTokenTwilioRestClient client) { - return CompletableFuture.supplyAsync(() -> create(client), TwilioOrgsTokenAuth.getExecutorService()); - } - - /** - * Execute a request using default client. - * - * @return Requested object - */ - public T create() { - return create(TwilioOrgsTokenAuth.getRestClient()); - } - - /** - * Execute a request using specified client. - * - * @param client client used to make request - * @return Requested object - */ - public abstract T create(final BearerTokenTwilioRestClient client); -} diff --git a/src/main/java/com/twilio/base/bearertoken/Deleter.java b/src/main/java/com/twilio/base/bearertoken/Deleter.java deleted file mode 100644 index 3b49cfd0ba..0000000000 --- a/src/main/java/com/twilio/base/bearertoken/Deleter.java +++ /dev/null @@ -1,51 +0,0 @@ -package com.twilio.base.bearertoken; - -import com.twilio.Twilio; -import com.twilio.TwilioOrgsTokenAuth; -import com.twilio.http.bearertoken.BearerTokenTwilioRestClient; - -import java.util.concurrent.CompletableFuture; - -/** - * Executor for deletes of a resource. - * - * @param type of the resource - */ -public abstract class Deleter { - - /** - * Execute an async request using default client. - * - * @return future that resolves to true if the object was deleted - */ - public CompletableFuture deleteAsync() { - return deleteAsync(TwilioOrgsTokenAuth.getRestClient()); - } - - /** - * Execute an async request using specified client. - * - * @param client client used to make request - * @return future that resolves to true if the object was deleted - */ - public CompletableFuture deleteAsync(final BearerTokenTwilioRestClient client) { - return CompletableFuture.supplyAsync(() -> delete(client), Twilio.getExecutorService()); - } - - /** - * Execute a request using default client. - * - * @return true if the object was deleted - */ - public boolean delete() { - return delete(TwilioOrgsTokenAuth.getRestClient()); - } - - /** - * Execute a request using specified client. - * - * @param client client used to make request - * @return true if the object was deleted - */ - public abstract boolean delete(final BearerTokenTwilioRestClient client); -} diff --git a/src/main/java/com/twilio/base/bearertoken/Fetcher.java b/src/main/java/com/twilio/base/bearertoken/Fetcher.java deleted file mode 100644 index 5654895a3f..0000000000 --- a/src/main/java/com/twilio/base/bearertoken/Fetcher.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.twilio.base.bearertoken; - -import com.twilio.TwilioOrgsTokenAuth; -import com.twilio.http.bearertoken.BearerTokenTwilioRestClient; - -import java.util.concurrent.CompletableFuture; - -/** - * Executor for fetches of a resource. - * - * @param type of the resource - */ -public abstract class Fetcher { - - /** - * Execute an async request using default client. - * - * @return future that resolves to requested object - */ - public CompletableFuture fetchAsync() { - return fetchAsync(TwilioOrgsTokenAuth.getRestClient()); - } - - /** - * Execute an async request using specified client. - * - * @param client client used to make request - * @return future that resolves to requested object - */ - public CompletableFuture fetchAsync(final BearerTokenTwilioRestClient client) { - return CompletableFuture.supplyAsync(() -> fetch(client), TwilioOrgsTokenAuth.getExecutorService()); - } - - /** - * Execute a request using default client. - * - * @return Requested object - */ - public T fetch() { - return fetch(TwilioOrgsTokenAuth.getRestClient()); - } - - /** - * Execute a request using specified client. - * - * @param client client used to make request - * @return Requested object - */ - public abstract T fetch(final BearerTokenTwilioRestClient client); -} diff --git a/src/main/java/com/twilio/base/bearertoken/Page.java b/src/main/java/com/twilio/base/bearertoken/Page.java deleted file mode 100644 index 204c2e98a2..0000000000 --- a/src/main/java/com/twilio/base/bearertoken/Page.java +++ /dev/null @@ -1,270 +0,0 @@ -package com.twilio.base.bearertoken; - -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.twilio.exception.ApiConnectionException; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -public class Page { - private final List records; - private final String firstPageUrl; - private final String firstPageUri; - private final String nextPageUrl; - private final String nextPageUri; - private final String previousPageUrl; - private final String previousPageUri; - private final String url; - private final String uri; - private final int pageSize; - - private Page(Builder b) { - this.records = b.records; - this.firstPageUri = b.firstPageUri; - this.firstPageUrl = b.firstPageUrl; - this.nextPageUri = b.nextPageUri; - this.nextPageUrl = b.nextPageUrl; - this.previousPageUri = b.previousPageUri; - this.previousPageUrl = b.previousPageUrl; - this.uri = b.uri; - this.url = b.url; - this.pageSize = b.pageSize; - } - - private String urlFromUri(String domain, String uri) { - return "https://" + domain + ".twilio.com" + uri; - } - - public List getRecords() { - return records; - } - - /** - * Generate first page url for a list result. - * - * @param domain domain to use - * @return the first page url - */ - public String getFirstPageUrl(String domain) { - if (firstPageUrl != null) { - return firstPageUrl; - } - - return urlFromUri(domain, firstPageUri); - } - - /** - * Generate next page url for a list result. - * - * @param domain domain to use - * @return the next page url - */ - public String getNextPageUrl(String domain) { - if (nextPageUrl != null) { - return nextPageUrl; - } - - return urlFromUri(domain, nextPageUri); - } - - /** - * Generate previous page url for a list result. - * - * @param domain domain to use - * @return the previous page url - */ - public String getPreviousPageUrl(String domain) { - if (previousPageUrl != null) { - return previousPageUrl; - } - - return urlFromUri(domain, previousPageUri); - } - - public int getPageSize() { - return pageSize; - } - - /** - * Generate page url for a list result. - * - * @param domain domain to use - * @return the page url - */ - public String getUrl(String domain) { - if (url != null) { - return url; - } - - return urlFromUri(domain, uri); - } - - public boolean hasNextPage() { - return (nextPageUri != null && !nextPageUri.isEmpty()) || (nextPageUrl != null && !nextPageUrl.isEmpty()); - } - - /** - * Create a new page of data from a json blob. - * - * @param recordKey key which holds the records - * @param json json blob - * @param recordType resource type - * @param mapper json parser - * @param record class type - * @return a page of records of type T - */ - public static Page fromJson(String recordKey, String json, Class recordType, ObjectMapper mapper) { - try { - List results = new ArrayList<>(); - JsonNode root = mapper.readTree(json); - JsonNode records = root.get(recordKey); - for (final JsonNode record : records) { - results.add(mapper.readValue(record.toString(), recordType)); - } - - JsonNode uriNode = root.get("uri"); - if (uriNode != null) { - return buildPage(root, results); - } else { - return buildNextGenPage(root, results); - } - - } catch (final IOException e) { - throw new ApiConnectionException( - "Unable to deserialize response: " + e.getMessage() + "\nJSON: " + json, e - ); - } - } - - private static Page buildPage(JsonNode root, List results) { - Builder builder = new Builder() - .uri(root.get("uri").asText()); - - JsonNode nextPageNode = root.get("next_page_uri"); - if (nextPageNode != null && !nextPageNode.isNull()) { - builder.nextPageUri(nextPageNode.asText()); - } - - JsonNode previousPageNode = root.get("previous_page_uri"); - if (previousPageNode != null && !previousPageNode.isNull()) { - builder.previousPageUri(previousPageNode.asText()); - } - - JsonNode firstPageNode = root.get("first_page_uri"); - if (firstPageNode != null && !firstPageNode.isNull()) { - builder.firstPageUri(firstPageNode.asText()); - } - - JsonNode pageSizeNode = root.get("page_size"); - if (pageSizeNode != null && !pageSizeNode.isNull()) { - builder.pageSize(pageSizeNode.asInt()); - } else { - builder.pageSize(results.size()); - } - - return builder.records(results).build(); - } - - private static Page buildNextGenPage(JsonNode root, List results) { - JsonNode meta = root.get("meta"); - Builder builder = new Builder<>(); - if(meta != null && meta.get("url") != null) { - - builder = builder.url(meta.get("url").asText()); - - - JsonNode nextPageNode = meta.get("next_page_url"); - if (!nextPageNode.isNull()) { - builder.nextPageUrl(nextPageNode.asText()); - } - - JsonNode previousPageNode = meta.get("previous_page_url"); - if (!previousPageNode.isNull()) { - builder.previousPageUrl(previousPageNode.asText()); - } - - JsonNode firstPageNode = meta.get("first_page_url"); - if (!firstPageNode.isNull()) { - builder.firstPageUrl(firstPageNode.asText()); - } - - JsonNode pageSizeNode = meta.get("page_size"); - if (!pageSizeNode.isNull()) { - builder.pageSize(pageSizeNode.asInt()); - } else { - builder.pageSize(results.size()); - } - } - - return builder.records(results).build(); - } - - private static class Builder { - private List records; - private String firstPageUrl; - private String firstPageUri; - private String nextPageUrl; - private String nextPageUri; - private String previousPageUrl; - private String previousPageUri; - private String uri; - private String url; - private int pageSize; - - public Builder records(List records) { - this.records = records; - return this; - } - - public Builder firstPageUri(String firstPageUri) { - this.firstPageUri = firstPageUri; - return this; - } - - public Builder firstPageUrl(String firstPageUrl) { - this.firstPageUrl = firstPageUrl; - return this; - } - - public Builder nextPageUri(String nextPageUri) { - this.nextPageUri = nextPageUri; - return this; - } - - public Builder nextPageUrl(String nextPageUrl) { - this.nextPageUrl = nextPageUrl; - return this; - } - - public Builder previousPageUri(String previousPageUri) { - this.previousPageUri = previousPageUri; - return this; - } - - public Builder previousPageUrl(String previousPageUrl) { - this.previousPageUrl = previousPageUrl; - return this; - } - - public Builder uri(String uri) { - this.uri = uri; - return this; - } - - public Builder url(String url) { - this.url = url; - return this; - } - - public Builder pageSize(int pageSize) { - this.pageSize = pageSize; - return this; - } - - public Page build() { - return new Page<>(this); - } - } -} diff --git a/src/main/java/com/twilio/base/bearertoken/Reader.java b/src/main/java/com/twilio/base/bearertoken/Reader.java deleted file mode 100644 index 15e221a3f9..0000000000 --- a/src/main/java/com/twilio/base/bearertoken/Reader.java +++ /dev/null @@ -1,156 +0,0 @@ -package com.twilio.base.bearertoken; - -import com.twilio.TwilioOrgsTokenAuth; -import com.twilio.http.bearertoken.BearerTokenTwilioRestClient; - -import java.util.concurrent.CompletableFuture; - -/** - * Executor for listing of a resource. - * - * @param type of the resource - */ -public abstract class Reader { - - private Integer pageSize; - private Long limit; - - /** - * Execute a request using default client. - * - * @return ResourceSet of objects - */ - public ResourceSet read() { - return read(TwilioOrgsTokenAuth.getRestClient()); - } - - /** - * Execute a request using specified client. - * - * @param client client used to make request - * @return ResourceSet of objects - */ - public abstract ResourceSet read(final BearerTokenTwilioRestClient client); - - /** - * Execute an async request using default client. - * - * @return future that resolves to the ResourceSet of objects - */ - public CompletableFuture> readAsync() { - return readAsync(TwilioOrgsTokenAuth.getRestClient()); - } - - /** - * Execute an async request using specified client. - * - * @param client client used to make request - * @return future that resolves to the ResourceSet of objects - */ - public CompletableFuture> readAsync(final BearerTokenTwilioRestClient client) { - return CompletableFuture.supplyAsync(() -> read(client), TwilioOrgsTokenAuth.getExecutorService()); - } - - /** - * Fetch the first page of resources. - * - * @return Page containing the first pageSize of resources - */ - public Page firstPage() { - return firstPage(TwilioOrgsTokenAuth.getRestClient()); - } - - /** - * Fetch the first page of resources using specified client. - * - * @param client client used to fetch - * @return Page containing the first pageSize of resources - */ - public abstract Page firstPage(final BearerTokenTwilioRestClient client); - - /** - * Retrieve the target page of resources. - * - * @param targetUrl API-generated URL for the requested results page - * @return Page containing the target pageSize of resources - */ - public Page getPage(final String targetUrl) { - return getPage(targetUrl, TwilioOrgsTokenAuth.getRestClient()); - } - - /** - * Retrieve the target page of resources. - * - * @param targetUrl API-generated URL for the requested results page - * @param client client used to fetch - * @return Page containing the target pageSize of resources - */ - public abstract Page getPage(final String targetUrl, final BearerTokenTwilioRestClient client); - - /** - * Fetch the following page of resources. - * - * @param page current page of resources - * @return Page containing the next pageSize of resources - */ - public Page nextPage(final Page page) { - return nextPage(page, TwilioOrgsTokenAuth.getRestClient()); - } - - /** - * Fetch the following page of resources using specified client. - * - * @param page current page of resources - * @param client client used to fetch - * @return Page containing the next pageSize of resources - */ - public abstract Page nextPage(final Page page, final BearerTokenTwilioRestClient client); - - /** - * Fetch the prior page of resources. - * - * @param page current page of resources - * @return Page containing the previous pageSize of resources - */ - public Page previousPage(final Page page) { - return previousPage(page, TwilioOrgsTokenAuth.getRestClient()); - } - - /** - * Fetch the prior page of resources using specified client. - * - * @param page current page of resources - * @param client client used to fetch - * @return Page containing the previous pageSize of resources - */ - public abstract Page previousPage(final Page page, final BearerTokenTwilioRestClient client); - - public Integer getPageSize() { - return pageSize; - } - - public Reader pageSize(final int pageSize) { - this.pageSize = pageSize; - return this; - } - - public Long getLimit() { - return limit; - } - - /** - * Sets the max number of records to read. - * - * @param limit max number of records to read - * @return this reader - */ - public Reader limit(final long limit) { - this.limit = limit; - - if (this.pageSize == null) { - this.pageSize = this.limit.intValue(); - } - - return this; - } -} diff --git a/src/main/java/com/twilio/base/bearertoken/Resource.java b/src/main/java/com/twilio/base/bearertoken/Resource.java deleted file mode 100644 index 08dc228556..0000000000 --- a/src/main/java/com/twilio/base/bearertoken/Resource.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.twilio.base.bearertoken; - -import java.io.Serializable; - -public abstract class Resource implements Serializable { - - private static final long serialVersionUID = -5898012691404059591L; - -} diff --git a/src/main/java/com/twilio/base/bearertoken/ResourceSet.java b/src/main/java/com/twilio/base/bearertoken/ResourceSet.java deleted file mode 100644 index 4cc09d8c2d..0000000000 --- a/src/main/java/com/twilio/base/bearertoken/ResourceSet.java +++ /dev/null @@ -1,138 +0,0 @@ -package com.twilio.base.bearertoken; - -import com.twilio.http.bearertoken.BearerTokenTwilioRestClient; - -import java.util.Iterator; -import java.util.NoSuchElementException; - -/** - * A collection of resources. - * - * @param type of the resource - */ -public class ResourceSet implements Iterable { - - private final Reader reader; - private final BearerTokenTwilioRestClient client; - private final Page firstPage; // Store reference to first page to enable multiple iterations - - private boolean autoPaging; - private long pages = 1; - private long pageLimit = Long.MAX_VALUE; - private long processed = 0; - private Page page; - private Iterator iterator; - - /** - * Initialize the resource set. - * - * @param reader reader used to fetch next page - * @param client client used to make requests - * @param page page of data - */ - public ResourceSet(final Reader reader, final BearerTokenTwilioRestClient client, final Page page) { - this.reader = reader; - this.client = client; - this.firstPage = page; // Save first page to allow resetting iterator state - this.page = page; - this.iterator = page.getRecords().iterator(); - this.autoPaging = true; - - if (reader.getLimit() != null) { - this.pageLimit = (long)(Math.ceil((double)reader.getLimit() / (double)page.getPageSize())); - } - } - - public boolean isAutoPaging() { - return autoPaging; - } - - public ResourceSet setAutoPaging(final boolean autoPaging) { - this.autoPaging = autoPaging; - return this; - } - - public Integer getPageSize() { - return page.getPageSize(); - } - - public ResourceSet setPageSize(final int pageSize) { - reader.pageSize(pageSize); - return this; - } - - public Long getLimit() { - return reader.getLimit(); - } - - public ResourceSet setLimit(final long limit) { - reader.limit(limit); - return this; - } - - public long getPageLimit() { - return pageLimit; - } - - @Override - public Iterator iterator() { - // Reset state to allow multiple iterations - this.processed = 0; - this.pages = 1; - this.page = this.firstPage; // Reset to first page for new iteration - this.iterator = this.firstPage.getRecords().iterator(); // Reset iterator to start of first page - - return new ResourceSetIterator<>(this); - } - - private void fetchNextPage() { - if (!page.hasNextPage() || pages >= pageLimit) { - return; - } - - pages++; - page = reader.nextPage(page, client); - iterator = page.getRecords().iterator(); - } - - private class ResourceSetIterator implements Iterator { - private final ResourceSet resourceSet; - - public ResourceSetIterator(final ResourceSet resourceSet) { - this.resourceSet = resourceSet; - } - - @Override - public boolean hasNext() { - if (resourceSet.getLimit() != null && resourceSet.processed >= resourceSet.getLimit()) { - return false; - } - - return resourceSet.iterator.hasNext(); - } - - @Override - public E next() { - if (resourceSet == null || resourceSet.iterator == null) { - throw new NoSuchElementException(); - } - - E element = resourceSet.iterator.next(); - if (resourceSet.isAutoPaging() && !resourceSet.iterator.hasNext()) { - resourceSet.fetchNextPage(); - } - - resourceSet.processed++; - return element; - } - - @Override - public void remove() { - if (resourceSet.iterator != null) { - resourceSet.processed++; - resourceSet.iterator.remove(); - } - } - - } -} diff --git a/src/main/java/com/twilio/base/bearertoken/Updater.java b/src/main/java/com/twilio/base/bearertoken/Updater.java deleted file mode 100644 index 690e3604c5..0000000000 --- a/src/main/java/com/twilio/base/bearertoken/Updater.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.twilio.base.bearertoken; - -import com.twilio.TwilioOrgsTokenAuth; -import com.twilio.http.bearertoken.BearerTokenTwilioRestClient; - -import java.util.concurrent.CompletableFuture; - -/** - * Executor for updates of a resource. - * - * @param type of the resource - */ -public abstract class Updater { - - /** - * Execute an async request using default client. - * - * @return future that resolves to requested object - */ - public CompletableFuture updateAsync() { - return updateAsync(TwilioOrgsTokenAuth.getRestClient()); - } - - /** - * Execute an async request using specified client. - * - * @param client client used to make request - * @return future that resolves to requested object - */ - public CompletableFuture updateAsync(final BearerTokenTwilioRestClient client) { - return CompletableFuture.supplyAsync(() -> update(client), TwilioOrgsTokenAuth.getExecutorService()); - } - - /** - * Execute a request using default client. - * - * @return Requested object - */ - public T update() { - return update(TwilioOrgsTokenAuth.getRestClient()); - } - - /** - * Execute a request using specified client. - * - * @param client client used to make request - * @return Requested object - */ - public abstract T update(final BearerTokenTwilioRestClient client); -} diff --git a/src/main/java/com/twilio/credential/orgs/OrgsClientCredentialProvider.java b/src/main/java/com/twilio/credential/orgs/OrgsClientCredentialProvider.java index 9d5687a64a..5d93404bc6 100644 --- a/src/main/java/com/twilio/credential/orgs/OrgsClientCredentialProvider.java +++ b/src/main/java/com/twilio/credential/orgs/OrgsClientCredentialProvider.java @@ -1,4 +1,64 @@ package com.twilio.credential.orgs; -public class OrgsClientCredentialProvider { +import com.twilio.auth_strategy.AuthStrategy; +import com.twilio.auth_strategy.TokenAuthStrategy; +import com.twilio.constant.EnumConstants; +import com.twilio.credential.CredentialProvider; +import com.twilio.exception.AuthenticationException; +import com.twilio.http.bearertoken.OrgsTokenManager; +import com.twilio.http.bearertoken.TokenManager; + +import java.util.Objects; + +public class OrgsClientCredentialProvider extends CredentialProvider { + private String grantType; + private String clientId; + private String clientSecret; + private TokenManager tokenManager; + + public OrgsClientCredentialProvider(String clientId, String clientSecret) { + super(EnumConstants.AuthType.CLIENT_CREDENTIALS); + if (clientId == null || clientSecret == null) { + throw new AuthenticationException("ClientId or ClientSecret can not be null"); + } + this.grantType = "client_credentials"; + this.clientId = clientId; + this.clientSecret = clientSecret; + this.tokenManager = null; + } + + public OrgsClientCredentialProvider(String clientId, String clientSecret, TokenManager tokenManager) { + super(EnumConstants.AuthType.CLIENT_CREDENTIALS); + if (clientId == null || clientSecret == null || tokenManager == null) { + throw new AuthenticationException("ClientId or ClientSecret or TokenManager can not be null"); + } + this.grantType = "client_credentials"; + this.clientId = clientId; + this.clientSecret = clientSecret; + this.tokenManager = tokenManager; + } + + @Override + public AuthStrategy toAuthStrategy() { + if (tokenManager == null) { + tokenManager = new OrgsTokenManager(grantType, clientId, clientSecret); + } + return new TokenAuthStrategy(tokenManager); + } + + @Override + public boolean equals(final Object o) { + if (this == o) { + return true; + } + + if (o == null || getClass() != o.getClass()) { + return false; + } + + OrgsClientCredentialProvider other = (OrgsClientCredentialProvider) o; + return Objects.equals(clientId, other.clientId) && + Objects.equals(clientSecret, other.clientSecret) && + Objects.equals(tokenManager, other.tokenManager); + } } diff --git a/src/main/java/com/twilio/http/NetworkHttpClient.java b/src/main/java/com/twilio/http/NetworkHttpClient.java index 8c1b0dad85..0d40e4cb8c 100644 --- a/src/main/java/com/twilio/http/NetworkHttpClient.java +++ b/src/main/java/com/twilio/http/NetworkHttpClient.java @@ -72,7 +72,7 @@ public NetworkHttpClient(final RequestConfig requestConfig) { public NetworkHttpClient(final RequestConfig requestConfig, final SocketConfig socketConfig) { Collection headers = Arrays.asList( new BasicHeader("X-Twilio-Client", "java-" + Twilio.VERSION), - new BasicHeader(HttpHeaders.ACCEPT, "application/json"), + // The Accept header is intentionally omitted to support both SCIM and JSON content types. new BasicHeader(HttpHeaders.ACCEPT_ENCODING, "utf-8") ); diff --git a/src/main/java/com/twilio/http/bearertoken/BearerTokenHttpClient.java b/src/main/java/com/twilio/http/bearertoken/BearerTokenHttpClient.java deleted file mode 100644 index 0c405769bf..0000000000 --- a/src/main/java/com/twilio/http/bearertoken/BearerTokenHttpClient.java +++ /dev/null @@ -1,108 +0,0 @@ -package com.twilio.http.bearertoken; - -import com.twilio.http.HttpClient; -import com.twilio.http.Request; -import com.twilio.http.Response; -import lombok.Getter; -import lombok.Setter; -import org.apache.hc.client5.http.config.RequestConfig; -import org.apache.hc.client5.http.impl.DefaultRedirectStrategy; -import org.apache.hc.client5.http.protocol.RedirectStrategy; -import org.apache.hc.core5.http.io.SocketConfig; - -public abstract class BearerTokenHttpClient { - // Use constants from HttpClient - public static final RequestConfig DEFAULT_REQUEST_CONFIG = RequestConfig - .custom() - .setConnectTimeout(HttpClient.CONNECTION_TIMEOUT) - .build(); - public static final SocketConfig DEFAULT_SOCKET_CONFIG = SocketConfig - .custom() - .setSoTimeout(HttpClient.SOCKET_TIMEOUT) - .build(); - @Getter - @Setter - private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy(); - - @Getter - private Response lastResponse; - @Getter - private BearerTokenRequest lastRequest; - - public Response reliableRequest(final BearerTokenRequest request) { - return reliableRequest(request, HttpClient.RETRY_CODES, HttpClient.RETRIES, HttpClient.DELAY_MILLIS); - } - - public Response reliableRequest(final BearerTokenRequest request, final int[] retryCodes, int retries, - final long delayMillis) { - lastRequest = request; - Response response = null; - while (retries > 0) { - response = makeRequest(request); - - if (!shouldRetry(response, retryCodes)) { - break; - } - - try { - Thread.sleep(delayMillis); - } catch (final InterruptedException e) { - // Delay failed, continue - } - - // Decrement retries - retries--; - } - - lastResponse = response; - - return response; - } - - protected boolean shouldRetry(final Response response, final int[] retryCodes) { - if (response == null) { - return true; - } - - int statusCode = response.getStatusCode(); - int category = (int) Math.floor(statusCode / 100.0); - - for (final int retryCode : retryCodes) { - switch (retryCode) { - case HttpClient.ANY_100: - if (category == 1) { - return true; - } - break; - case HttpClient.ANY_200: - if (category == 2) { - return true; - } - break; - case HttpClient.ANY_300: - if (category == 3) { - return true; - } - break; - case HttpClient.ANY_400: - if (category == 4) { - return true; - } - break; - case HttpClient.ANY_500: - if (category == 5) { - return true; - } - break; - default: - if (statusCode == retryCode) { - return true; - } - break; - } - } - return false; - } - - public abstract Response makeRequest(final BearerTokenRequest request); -} diff --git a/src/main/java/com/twilio/http/bearertoken/BearerTokenNetworkHttpClient.java b/src/main/java/com/twilio/http/bearertoken/BearerTokenNetworkHttpClient.java deleted file mode 100644 index 9d80666640..0000000000 --- a/src/main/java/com/twilio/http/bearertoken/BearerTokenNetworkHttpClient.java +++ /dev/null @@ -1,181 +0,0 @@ -package com.twilio.http.bearertoken; - -import com.twilio.Twilio; -import com.twilio.constant.EnumConstants; -import com.twilio.exception.ApiException; -import com.twilio.http.HttpMethod; -import com.twilio.http.HttpUtility; -import com.twilio.http.Response; -import java.util.ArrayList; -import java.util.Map.Entry; -import org.apache.hc.client5.http.classic.methods.HttpUriRequestBase; -import org.apache.hc.client5.http.config.RequestConfig; -import org.apache.hc.client5.http.entity.UrlEncodedFormEntity; -import org.apache.hc.client5.http.impl.classic.CloseableHttpClient; -import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse; -import org.apache.hc.client5.http.impl.classic.HttpClientBuilder; -import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager; -import org.apache.hc.core5.http.ContentType; -import org.apache.hc.core5.http.HttpEntity; -import org.apache.hc.core5.http.HttpHeaders; -import org.apache.hc.core5.http.NameValuePair; -import org.apache.hc.core5.http.io.SocketConfig; -import org.apache.hc.core5.http.io.entity.BufferedHttpEntity; -import org.apache.hc.core5.http.io.entity.StringEntity; -import org.apache.hc.core5.http.message.BasicHeader; - -import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.util.Arrays; -import java.util.Collection; -import java.util.List; -import java.util.Map; -import org.apache.hc.core5.http.message.BasicNameValuePair; -import static com.twilio.http.HttpClient.createHttpUriRequestBase; - -public class BearerTokenNetworkHttpClient extends BearerTokenHttpClient { - - protected final CloseableHttpClient client; - - private boolean isCustomClient; - - /** - * Create a new HTTP Client. - */ - public BearerTokenNetworkHttpClient() { - this(DEFAULT_REQUEST_CONFIG); - } - - /** - * Create a new HTTP Client with a custom request config. - * - * @param requestConfig a RequestConfig. - */ - public BearerTokenNetworkHttpClient(final RequestConfig requestConfig) { - this(requestConfig, DEFAULT_SOCKET_CONFIG); - } - - /** - * Create a new HTTP Client with a custom request and socket config. - * - * @param requestConfig a RequestConfig. - * @param socketConfig a SocketConfig. - */ - public BearerTokenNetworkHttpClient(final RequestConfig requestConfig, final SocketConfig socketConfig) { - Collection headers = Arrays.asList( - new BasicHeader("X-Twilio-Client", "java-" + Twilio.VERSION), - //new BasicHeader(HttpHeaders.ACCEPT, "application/json"), Orgs API has scim or json support. - new BasicHeader(HttpHeaders.ACCEPT_ENCODING, "utf-8") - ); - - String googleAppEngineVersion = System.getProperty("com.google.appengine.runtime.version"); - boolean isGoogleAppEngine = googleAppEngineVersion != null && !googleAppEngineVersion.isEmpty(); - - HttpClientBuilder clientBuilder = HttpClientBuilder.create(); - - if (!isGoogleAppEngine) { - clientBuilder.useSystemProperties(); - } - - PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(); - connectionManager.setDefaultSocketConfig(socketConfig); - /** - * Example: Lets say client has one server. - * There are 4 servers on edge handling client request. - * Each request takes on an average 500ms (2 request per second) - * Total number request can be server in a second from a route: 20 * 4 * 2 (DefaultMaxPerRoute * edge servers * request per second) - */ - connectionManager.setDefaultMaxPerRoute(20); - connectionManager.setMaxTotal(100); - - client = clientBuilder - .setConnectionManager(connectionManager) - .setDefaultRequestConfig(requestConfig) - .setDefaultHeaders(headers) - .setRedirectStrategy(this.getRedirectStrategy()) - .build(); - } - - /** - * Create a new HTTP Client using custom configuration. - * @param clientBuilder an HttpClientBuilder. - */ - public BearerTokenNetworkHttpClient(HttpClientBuilder clientBuilder) { - Collection headers = Arrays.asList( - new BasicHeader("X-Twilio-Client", "java-" + Twilio.VERSION), - //new BasicHeader(HttpHeaders.ACCEPT, "application/json"), Orgs API has scim or json support. - new BasicHeader(HttpHeaders.ACCEPT_ENCODING, "utf-8") - ); - isCustomClient = true; - - client = clientBuilder - .setDefaultRequestConfig(DEFAULT_REQUEST_CONFIG) - .setDefaultHeaders(headers) - .setRedirectStrategy(this.getRedirectStrategy()) - .build(); - } - - /** - * Make a request. - * - * @param request request to make - * @return Response of the HTTP request - */ - public Response makeRequest(final BearerTokenRequest request) { - - HttpMethod method = request.getMethod(); - HttpUriRequestBase httpUriRequestBase = createHttpUriRequestBase(request); - - - if (request.requiresAuthentication()) { - httpUriRequestBase.addHeader(HttpHeaders.AUTHORIZATION, request.getAuthString()); - } - - for (Map.Entry> entry : request.getHeaderParams().entrySet()) { - for (String value : entry.getValue()) { - httpUriRequestBase.addHeader(entry.getKey(), value); - } - } - - if (method != HttpMethod.GET) { - // TODO: It will be removed after one RC Release. - if (request.getContentType() == null) request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); - if (EnumConstants.ContentType.JSON.getValue().equals(request.getContentType().getValue())) { - HttpEntity entity = new StringEntity(request.getBody(), ContentType.APPLICATION_JSON); - httpUriRequestBase.setEntity(entity); - httpUriRequestBase.addHeader( - HttpHeaders.CONTENT_TYPE, EnumConstants.ContentType.JSON.getValue()); - } else { - httpUriRequestBase.addHeader( - HttpHeaders.CONTENT_TYPE, EnumConstants.ContentType.FORM_URLENCODED.getValue()); - // Create your form parameters - List formParams = new ArrayList<>(); - for ( Entry> entry : request.getPostParams().entrySet()) { - for (String value : entry.getValue()) { - formParams.add(new BasicNameValuePair(entry.getKey(), value)); - } - } - - // Build the entity with URL form encoded parameters - UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(formParams, StandardCharsets.UTF_8); - // Set the entity on the request - httpUriRequestBase.setEntity(formEntity); - } - - } - httpUriRequestBase.addHeader(HttpHeaders.USER_AGENT, HttpUtility.getUserAgentString(request.getUserAgentExtensions(), isCustomClient)); - - try { - CloseableHttpResponse response = client.execute(httpUriRequestBase); - HttpEntity entity = response.getEntity(); - return new Response( - // Consume the entire HTTP response before returning the stream - entity == null ? null : new BufferedHttpEntity(entity).getContent(), - response.getCode(), - response.getHeaders() - ); - } catch (IOException e) { - throw new ApiException(e.getMessage(), e); - } - } -} diff --git a/src/main/java/com/twilio/http/bearertoken/BearerTokenRequest.java b/src/main/java/com/twilio/http/bearertoken/BearerTokenRequest.java deleted file mode 100644 index 83976c2e45..0000000000 --- a/src/main/java/com/twilio/http/bearertoken/BearerTokenRequest.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.twilio.http.bearertoken; - -import com.twilio.http.HttpMethod; -import com.twilio.http.IRequest; - -public class BearerTokenRequest extends IRequest { - - private String accessToken; - - public BearerTokenRequest(HttpMethod method, String url) { - super(method, url); - } - - public BearerTokenRequest(HttpMethod method, String domain, String uri) { - super(method, domain, uri); - } - - public BearerTokenRequest(HttpMethod method, String domain, String uri, String region) { - super(method, domain, uri, region); - } - - /** - * Create auth string from accessToken. - * - * @return basic authentication string - */ - public String getAuthString() { - return "Bearer " + accessToken; - } - - public boolean requiresAuthentication() { - return accessToken != null; - } - - public void setAuth(String accessToken) { - this.accessToken = accessToken; - } -} diff --git a/src/main/java/com/twilio/http/bearertoken/BearerTokenTwilioRestClient.java b/src/main/java/com/twilio/http/bearertoken/BearerTokenTwilioRestClient.java deleted file mode 100644 index c7da1ff2b0..0000000000 --- a/src/main/java/com/twilio/http/bearertoken/BearerTokenTwilioRestClient.java +++ /dev/null @@ -1,186 +0,0 @@ -package com.twilio.http.bearertoken; - -import com.auth0.jwt.JWT; -import com.auth0.jwt.interfaces.DecodedJWT; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; -import com.twilio.http.Response; -import lombok.Getter; -import lombok.Setter; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.ArrayList; -import java.util.Date; -import java.util.List; -import java.util.Map; -import java.util.function.Predicate; - - -/* - * Use this BearerToken Rest Client if no authentication is involved in an API. - */ -public class BearerTokenTwilioRestClient { - public static final int HTTP_STATUS_CODE_CREATED = 201; - public static final int HTTP_STATUS_CODE_NO_CONTENT = 204; - public static final int HTTP_STATUS_CODE_OK = 200; - public static final Predicate SUCCESS = i -> i != null && i >= 200 && i < 400; - @Getter - private final ObjectMapper objectMapper; - private String accessToken; - @Getter - private final String region; - @Getter - private final String edge; - @Getter - private final BearerTokenHttpClient httpClient; - @Getter - private final List userAgentExtensions; - @Setter - private final TokenManager tokenManager; - private static final Logger logger = LoggerFactory.getLogger(BearerTokenTwilioRestClient.class); - - private BearerTokenTwilioRestClient(BearerTokenTwilioRestClient.Builder b) { - this.region = b.region; - this.edge = b.edge; - this.httpClient = b.httpClient; - this.objectMapper = b.objectMapper; - this.userAgentExtensions = b.userAgentExtensions; - this.tokenManager = b.tokenManager; - } - - public static class Builder { - // This module configures the ObjectMapper to use - // public API methods for manipulating java.time.* - // classes. The alternative is to use reflection which - // generates warnings from the module system on Java 9+ - private static final ObjectMapper DEFAULT_OBJECT_MAPPER = new ObjectMapper() - .registerModule(new JavaTimeModule()); - - private String region; - private String edge; - private BearerTokenHttpClient httpClient; - private List userAgentExtensions; - private TokenManager tokenManager; - private ObjectMapper objectMapper = DEFAULT_OBJECT_MAPPER; - - public Builder() { - this.region = System.getenv("TWILIO_REGION"); - this.edge = System.getenv("TWILIO_EDGE"); - userAgentExtensions = new ArrayList<>(); - } - - public BearerTokenTwilioRestClient.Builder region(final String region) { - this.region = region; - return this; - } - - public BearerTokenTwilioRestClient.Builder edge(final String edge) { - this.edge = edge; - return this; - } - - public BearerTokenTwilioRestClient.Builder tokenManager(final TokenManager tokenManager) { - this.tokenManager = tokenManager; - return this; - } - - public BearerTokenTwilioRestClient.Builder httpClient(final BearerTokenHttpClient httpClient) { - this.httpClient = httpClient; - return this; - } - - public BearerTokenTwilioRestClient.Builder userAgentExtensions(final List userAgentExtensions) { - if (userAgentExtensions != null && !userAgentExtensions.isEmpty()) { - this.userAgentExtensions = new ArrayList<>(userAgentExtensions); - } - return this; - } - - public BearerTokenTwilioRestClient.Builder objectMapper(final ObjectMapper objectMapper) { - this.objectMapper = objectMapper; - return this; - } - - public BearerTokenTwilioRestClient build() { - if (this.httpClient == null) { - this.httpClient = new BearerTokenNetworkHttpClient(); - } - return new BearerTokenTwilioRestClient(this); - } - } - public Response request(BearerTokenRequest request) { - - if (accessToken == null || accessToken.isEmpty() || isTokenExpired(this.accessToken)) { - synchronized (BearerTokenTwilioRestClient.class){ - if (accessToken == null || accessToken.isEmpty() || isTokenExpired(this.accessToken)) { - this.accessToken = tokenManager.fetchAccessToken(); - } - } - } - - request.setAuth(accessToken); - if (region != null) - request.setRegion(region); - if (edge != null) - request.setEdge(edge); - - if (userAgentExtensions != null && !userAgentExtensions.isEmpty()) { - request.setUserAgentExtensions(userAgentExtensions); - } - logRequest(request); - Response response = httpClient.reliableRequest(request); - if(response != null) { - int statusCode = response.getStatusCode(); - if (statusCode == 401) { - this.accessToken = tokenManager.fetchAccessToken(); - request.setAuth(accessToken); - response = httpClient.reliableRequest(request); - } - - if (logger.isDebugEnabled()) { - logger.debug("status code: {}", statusCode); - org.apache.hc.core5.http.Header[] responseHeaders = response.getHeaders(); - logger.debug("response headers:"); - for (int i = 0; i < responseHeaders.length; i++) { - logger.debug("responseHeader: {}", responseHeaders[i]); - } - } - } - - return response; - } - - public boolean isTokenExpired(String token) { - DecodedJWT jwt = JWT.decode(token); - Date expiresAt = jwt.getExpiresAt(); - // Add a buffer of 30 seconds - long bufferMilliseconds = 30 * 1000; - Date bufferExpiresAt = new Date(expiresAt.getTime() - bufferMilliseconds); - return bufferExpiresAt.before(new Date()); - } - - public void logRequest(final BearerTokenRequest request) { - if (logger.isDebugEnabled()) { - logger.debug("-- BEGIN Twilio API BearerTokenRequest --"); - logger.debug("request method: " + request.getMethod()); - logger.debug("request URL: " + request.constructURL().toString()); - final Map> queryParams = request.getQueryParams(); - final Map> headerParams = request.getHeaderParams(); - - if (queryParams != null && !queryParams.isEmpty()) { - logger.debug("query parameters: " + queryParams); - } - - if (headerParams != null && !headerParams.isEmpty()) { - logger.debug("header parameters: "); - for (String key : headerParams.keySet()) { - if (!key.toLowerCase().contains("authorization")) { - logger.debug(key + ": " + headerParams.get(key)); - } - } - } - logger.debug("-- END Twilio API BearerTokenRequest --"); - } - } -} diff --git a/src/main/java/com/twilio/rest/previewiam/organizations/Account.java b/src/main/java/com/twilio/rest/previewiam/organizations/Account.java index 388b31fa34..bffd937287 100644 --- a/src/main/java/com/twilio/rest/previewiam/organizations/Account.java +++ b/src/main/java/com/twilio/rest/previewiam/organizations/Account.java @@ -20,7 +20,7 @@ import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; -import com.twilio.base.bearertoken.Resource; +import com.twilio.base.Resource; import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; diff --git a/src/main/java/com/twilio/rest/previewiam/organizations/AccountFetcher.java b/src/main/java/com/twilio/rest/previewiam/organizations/AccountFetcher.java index 57dc7b088e..1949891f1d 100644 --- a/src/main/java/com/twilio/rest/previewiam/organizations/AccountFetcher.java +++ b/src/main/java/com/twilio/rest/previewiam/organizations/AccountFetcher.java @@ -14,15 +14,15 @@ package com.twilio.rest.previewiam.organizations; -import com.twilio.base.bearertoken.Fetcher; +import com.twilio.base.Fetcher; import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; import com.twilio.http.HttpMethod; +import com.twilio.http.Request; import com.twilio.http.Response; -import com.twilio.http.bearertoken.BearerTokenRequest; -import com.twilio.http.bearertoken.BearerTokenTwilioRestClient; +import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; public class AccountFetcher extends Fetcher { @@ -39,7 +39,7 @@ public AccountFetcher( } @Override - public Account fetch(final BearerTokenTwilioRestClient client) { + public Account fetch(final TwilioRestClient client) { String path = "/Organizations/{OrganizationSid}/Accounts/{AccountSid}"; path = @@ -53,7 +53,7 @@ public Account fetch(final BearerTokenTwilioRestClient client) { this.pathAccountSid.toString() ); - BearerTokenRequest request = new BearerTokenRequest( + Request request = new Request( HttpMethod.GET, Domains.PREVIEWIAM.toString(), path @@ -66,7 +66,7 @@ public Account fetch(final BearerTokenTwilioRestClient client) { "Account fetch failed: Unable to connect to server" ); } else if ( - !BearerTokenTwilioRestClient.SUCCESS.test(response.getStatusCode()) + !TwilioRestClient.SUCCESS.test(response.getStatusCode()) ) { RestException restException = RestException.fromJson( response.getStream(), diff --git a/src/main/java/com/twilio/rest/previewiam/organizations/AccountReader.java b/src/main/java/com/twilio/rest/previewiam/organizations/AccountReader.java index 5ad736ac13..7c2a384f3f 100644 --- a/src/main/java/com/twilio/rest/previewiam/organizations/AccountReader.java +++ b/src/main/java/com/twilio/rest/previewiam/organizations/AccountReader.java @@ -14,17 +14,17 @@ package com.twilio.rest.previewiam.organizations; -import com.twilio.base.bearertoken.Page; -import com.twilio.base.bearertoken.Reader; -import com.twilio.base.bearertoken.ResourceSet; +import com.twilio.base.Page; +import com.twilio.base.Reader; +import com.twilio.base.ResourceSet; import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; import com.twilio.http.HttpMethod; +import com.twilio.http.Request; import com.twilio.http.Response; -import com.twilio.http.bearertoken.BearerTokenRequest; -import com.twilio.http.bearertoken.BearerTokenTwilioRestClient; +import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; public class AccountReader extends Reader { @@ -42,11 +42,11 @@ public AccountReader setPageSize(final Integer pageSize) { } @Override - public ResourceSet read(final BearerTokenTwilioRestClient client) { + public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } - public Page firstPage(final BearerTokenTwilioRestClient client) { + public Page firstPage(final TwilioRestClient client) { String path = "/Organizations/{OrganizationSid}/Accounts"; path = path.replace( @@ -54,7 +54,7 @@ public Page firstPage(final BearerTokenTwilioRestClient client) { this.pathOrganizationSid.toString() ); - BearerTokenRequest request = new BearerTokenRequest( + Request request = new Request( HttpMethod.GET, Domains.PREVIEWIAM.toString(), path @@ -66,8 +66,8 @@ public Page firstPage(final BearerTokenTwilioRestClient client) { } private Page pageForRequest( - final BearerTokenTwilioRestClient client, - final BearerTokenRequest request + final TwilioRestClient client, + final Request request ) { Response response = client.request(request); @@ -76,7 +76,7 @@ private Page pageForRequest( "Account read failed: Unable to connect to server" ); } else if ( - !BearerTokenTwilioRestClient.SUCCESS.test(response.getStatusCode()) + !TwilioRestClient.SUCCESS.test(response.getStatusCode()) ) { RestException restException = RestException.fromJson( response.getStream(), @@ -102,9 +102,9 @@ private Page pageForRequest( @Override public Page previousPage( final Page page, - final BearerTokenTwilioRestClient client + final TwilioRestClient client ) { - BearerTokenRequest request = new BearerTokenRequest( + Request request = new Request( HttpMethod.GET, page.getPreviousPageUrl(Domains.PREVIEWIAM.toString()) ); @@ -114,9 +114,9 @@ public Page previousPage( @Override public Page nextPage( final Page page, - final BearerTokenTwilioRestClient client + final TwilioRestClient client ) { - BearerTokenRequest request = new BearerTokenRequest( + Request request = new Request( HttpMethod.GET, page.getNextPageUrl(Domains.PREVIEWIAM.toString()) ); @@ -126,9 +126,9 @@ public Page nextPage( @Override public Page getPage( final String targetUrl, - final BearerTokenTwilioRestClient client + final TwilioRestClient client ) { - BearerTokenRequest request = new BearerTokenRequest( + Request request = new Request( HttpMethod.GET, targetUrl ); @@ -136,7 +136,7 @@ public Page getPage( return pageForRequest(client, request); } - private void addQueryParams(final BearerTokenRequest request) { + private void addQueryParams(final Request request) { if (pageSize != null) { request.addQueryParam("PageSize", pageSize.toString()); } diff --git a/src/main/java/com/twilio/rest/previewiam/organizations/RoleAssignment.java b/src/main/java/com/twilio/rest/previewiam/organizations/RoleAssignment.java index 875068a004..882781fe09 100644 --- a/src/main/java/com/twilio/rest/previewiam/organizations/RoleAssignment.java +++ b/src/main/java/com/twilio/rest/previewiam/organizations/RoleAssignment.java @@ -22,7 +22,7 @@ import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; -import com.twilio.base.bearertoken.Resource; +import com.twilio.base.Resource; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import java.io.IOException; diff --git a/src/main/java/com/twilio/rest/previewiam/organizations/RoleAssignmentCreator.java b/src/main/java/com/twilio/rest/previewiam/organizations/RoleAssignmentCreator.java index e95e19a4b1..1a22c181ed 100644 --- a/src/main/java/com/twilio/rest/previewiam/organizations/RoleAssignmentCreator.java +++ b/src/main/java/com/twilio/rest/previewiam/organizations/RoleAssignmentCreator.java @@ -15,15 +15,15 @@ package com.twilio.rest.previewiam.organizations; import com.fasterxml.jackson.databind.ObjectMapper; -import com.twilio.base.bearertoken.Creator; +import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; import com.twilio.http.HttpMethod; +import com.twilio.http.Request; import com.twilio.http.Response; -import com.twilio.http.bearertoken.BearerTokenRequest; -import com.twilio.http.bearertoken.BearerTokenTwilioRestClient; +import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; public class RoleAssignmentCreator extends Creator { @@ -49,7 +49,7 @@ public RoleAssignmentCreator setPublicApiCreateRoleAssignmentRequest( } @Override - public RoleAssignment create(final BearerTokenTwilioRestClient client) { + public RoleAssignment create(final TwilioRestClient client) { String path = "/Organizations/{OrganizationSid}/RoleAssignments"; path = @@ -63,7 +63,7 @@ public RoleAssignment create(final BearerTokenTwilioRestClient client) { this.publicApiCreateRoleAssignmentRequest.toString() ); - BearerTokenRequest request = new BearerTokenRequest( + Request request = new Request( HttpMethod.POST, Domains.PREVIEWIAM.toString(), path @@ -76,7 +76,7 @@ public RoleAssignment create(final BearerTokenTwilioRestClient client) { "RoleAssignment creation failed: Unable to connect to server" ); } else if ( - !BearerTokenTwilioRestClient.SUCCESS.test(response.getStatusCode()) + !TwilioRestClient.SUCCESS.test(response.getStatusCode()) ) { RestException restException = RestException.fromJson( response.getStream(), @@ -98,8 +98,8 @@ public RoleAssignment create(final BearerTokenTwilioRestClient client) { } private void addPostParams( - final BearerTokenRequest request, - BearerTokenTwilioRestClient client + final Request request, + TwilioRestClient client ) { ObjectMapper objectMapper = client.getObjectMapper(); if (publicApiCreateRoleAssignmentRequest != null) { diff --git a/src/main/java/com/twilio/rest/previewiam/organizations/RoleAssignmentDeleter.java b/src/main/java/com/twilio/rest/previewiam/organizations/RoleAssignmentDeleter.java index 43cc107708..514bacadf6 100644 --- a/src/main/java/com/twilio/rest/previewiam/organizations/RoleAssignmentDeleter.java +++ b/src/main/java/com/twilio/rest/previewiam/organizations/RoleAssignmentDeleter.java @@ -14,15 +14,15 @@ package com.twilio.rest.previewiam.organizations; -import com.twilio.base.bearertoken.Deleter; +import com.twilio.base.Deleter; import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; import com.twilio.http.HttpMethod; import com.twilio.http.Response; -import com.twilio.http.bearertoken.BearerTokenRequest; -import com.twilio.http.bearertoken.BearerTokenTwilioRestClient; +import com.twilio.http.Request; +import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; public class RoleAssignmentDeleter extends Deleter { @@ -39,7 +39,7 @@ public RoleAssignmentDeleter( } @Override - public boolean delete(final BearerTokenTwilioRestClient client) { + public boolean delete(final TwilioRestClient client) { String path = "/Organizations/{OrganizationSid}/RoleAssignments/{RoleAssignmentSid}"; @@ -54,7 +54,7 @@ public boolean delete(final BearerTokenTwilioRestClient client) { this.pathRoleAssignmentSid.toString() ); - BearerTokenRequest request = new BearerTokenRequest( + Request request = new Request( HttpMethod.DELETE, Domains.PREVIEWIAM.toString(), path @@ -67,7 +67,7 @@ public boolean delete(final BearerTokenTwilioRestClient client) { "RoleAssignment delete failed: Unable to connect to server" ); } else if ( - !BearerTokenTwilioRestClient.SUCCESS.test(response.getStatusCode()) + !TwilioRestClient.SUCCESS.test(response.getStatusCode()) ) { RestException restException = RestException.fromJson( response.getStream(), diff --git a/src/main/java/com/twilio/rest/previewiam/organizations/RoleAssignmentReader.java b/src/main/java/com/twilio/rest/previewiam/organizations/RoleAssignmentReader.java index 05bb8e8b81..e10fca0991 100644 --- a/src/main/java/com/twilio/rest/previewiam/organizations/RoleAssignmentReader.java +++ b/src/main/java/com/twilio/rest/previewiam/organizations/RoleAssignmentReader.java @@ -14,17 +14,17 @@ package com.twilio.rest.previewiam.organizations; -import com.twilio.base.bearertoken.Page; -import com.twilio.base.bearertoken.Reader; -import com.twilio.base.bearertoken.ResourceSet; +import com.twilio.base.Page; +import com.twilio.base.Reader; +import com.twilio.base.ResourceSet; import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; import com.twilio.http.HttpMethod; import com.twilio.http.Response; -import com.twilio.http.bearertoken.BearerTokenRequest; -import com.twilio.http.bearertoken.BearerTokenTwilioRestClient; +import com.twilio.http.Request; +import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; public class RoleAssignmentReader extends Reader { @@ -55,13 +55,13 @@ public RoleAssignmentReader setScope(final String scope) { @Override public ResourceSet read( - final BearerTokenTwilioRestClient client + final TwilioRestClient client ) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage( - final BearerTokenTwilioRestClient client + final TwilioRestClient client ) { String path = "/Organizations/{OrganizationSid}/RoleAssignments"; path = @@ -70,7 +70,7 @@ public Page firstPage( this.pathOrganizationSid.toString() ); - BearerTokenRequest request = new BearerTokenRequest( + Request request = new Request( HttpMethod.GET, Domains.PREVIEWIAM.toString(), path @@ -82,8 +82,8 @@ public Page firstPage( } private Page pageForRequest( - final BearerTokenTwilioRestClient client, - final BearerTokenRequest request + final TwilioRestClient client, + final Request request ) { Response response = client.request(request); @@ -92,7 +92,7 @@ private Page pageForRequest( "RoleAssignment read failed: Unable to connect to server" ); } else if ( - !BearerTokenTwilioRestClient.SUCCESS.test(response.getStatusCode()) + !TwilioRestClient.SUCCESS.test(response.getStatusCode()) ) { RestException restException = RestException.fromJson( response.getStream(), @@ -118,9 +118,9 @@ private Page pageForRequest( @Override public Page previousPage( final Page page, - final BearerTokenTwilioRestClient client + final TwilioRestClient client ) { - BearerTokenRequest request = new BearerTokenRequest( + Request request = new Request( HttpMethod.GET, page.getPreviousPageUrl(Domains.PREVIEWIAM.toString()) ); @@ -130,9 +130,9 @@ public Page previousPage( @Override public Page nextPage( final Page page, - final BearerTokenTwilioRestClient client + final TwilioRestClient client ) { - BearerTokenRequest request = new BearerTokenRequest( + Request request = new Request( HttpMethod.GET, page.getNextPageUrl(Domains.PREVIEWIAM.toString()) ); @@ -142,9 +142,9 @@ public Page nextPage( @Override public Page getPage( final String targetUrl, - final BearerTokenTwilioRestClient client + final TwilioRestClient client ) { - BearerTokenRequest request = new BearerTokenRequest( + Request request = new Request( HttpMethod.GET, targetUrl ); @@ -152,7 +152,7 @@ public Page getPage( return pageForRequest(client, request); } - private void addQueryParams(final BearerTokenRequest request) { + private void addQueryParams(final Request request) { if (pageSize != null) { request.addQueryParam("PageSize", pageSize.toString()); } diff --git a/src/main/java/com/twilio/rest/previewiam/organizations/User.java b/src/main/java/com/twilio/rest/previewiam/organizations/User.java index 2e3a501701..94359dbbbf 100644 --- a/src/main/java/com/twilio/rest/previewiam/organizations/User.java +++ b/src/main/java/com/twilio/rest/previewiam/organizations/User.java @@ -22,7 +22,7 @@ import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; -import com.twilio.base.bearertoken.Resource; +import com.twilio.base.Resource; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import java.io.IOException; diff --git a/src/main/java/com/twilio/rest/previewiam/organizations/UserCreator.java b/src/main/java/com/twilio/rest/previewiam/organizations/UserCreator.java index 92d390ed29..e768088a50 100644 --- a/src/main/java/com/twilio/rest/previewiam/organizations/UserCreator.java +++ b/src/main/java/com/twilio/rest/previewiam/organizations/UserCreator.java @@ -15,15 +15,15 @@ package com.twilio.rest.previewiam.organizations; import com.fasterxml.jackson.databind.ObjectMapper; -import com.twilio.base.bearertoken.Creator; +import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; import com.twilio.http.HttpMethod; import com.twilio.http.Response; -import com.twilio.http.bearertoken.BearerTokenRequest; -import com.twilio.http.bearertoken.BearerTokenTwilioRestClient; +import com.twilio.http.TwilioRestClient; +import com.twilio.http.Request; import com.twilio.rest.Domains; public class UserCreator extends Creator { @@ -45,7 +45,7 @@ public UserCreator setScimUser(final User.ScimUser scimUser) { } @Override - public User create(final BearerTokenTwilioRestClient client) { + public User create(final TwilioRestClient client) { String path = "/Organizations/{OrganizationSid}/scim/Users"; path = @@ -55,7 +55,7 @@ public User create(final BearerTokenTwilioRestClient client) { ); path = path.replace("{" + "ScimUser" + "}", this.scimUser.toString()); - BearerTokenRequest request = new BearerTokenRequest( + Request request = new Request( HttpMethod.POST, Domains.PREVIEWIAM.toString(), path @@ -68,7 +68,7 @@ public User create(final BearerTokenTwilioRestClient client) { "User creation failed: Unable to connect to server" ); } else if ( - !BearerTokenTwilioRestClient.SUCCESS.test(response.getStatusCode()) + !TwilioRestClient.SUCCESS.test(response.getStatusCode()) ) { RestException restException = RestException.fromJson( response.getStream(), @@ -87,8 +87,8 @@ public User create(final BearerTokenTwilioRestClient client) { } private void addPostParams( - final BearerTokenRequest request, - BearerTokenTwilioRestClient client + final Request request, + TwilioRestClient client ) { ObjectMapper objectMapper = client.getObjectMapper(); if (scimUser != null) { diff --git a/src/main/java/com/twilio/rest/previewiam/organizations/UserDeleter.java b/src/main/java/com/twilio/rest/previewiam/organizations/UserDeleter.java index 6f44db1c69..dcb8c56787 100644 --- a/src/main/java/com/twilio/rest/previewiam/organizations/UserDeleter.java +++ b/src/main/java/com/twilio/rest/previewiam/organizations/UserDeleter.java @@ -14,15 +14,15 @@ package com.twilio.rest.previewiam.organizations; -import com.twilio.base.bearertoken.Deleter; +import com.twilio.base.Deleter; import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; import com.twilio.http.HttpMethod; import com.twilio.http.Response; -import com.twilio.http.bearertoken.BearerTokenRequest; -import com.twilio.http.bearertoken.BearerTokenTwilioRestClient; +import com.twilio.http.Request; +import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; public class UserDeleter extends Deleter { @@ -39,7 +39,7 @@ public UserDeleter( } @Override - public boolean delete(final BearerTokenTwilioRestClient client) { + public boolean delete(final TwilioRestClient client) { String path = "/Organizations/{OrganizationSid}/scim/Users/{UserSid}"; path = @@ -49,7 +49,7 @@ public boolean delete(final BearerTokenTwilioRestClient client) { ); path = path.replace("{" + "UserSid" + "}", this.pathUserSid.toString()); - BearerTokenRequest request = new BearerTokenRequest( + Request request = new Request( HttpMethod.DELETE, Domains.PREVIEWIAM.toString(), path @@ -62,7 +62,7 @@ public boolean delete(final BearerTokenTwilioRestClient client) { "User delete failed: Unable to connect to server" ); } else if ( - !BearerTokenTwilioRestClient.SUCCESS.test(response.getStatusCode()) + !TwilioRestClient.SUCCESS.test(response.getStatusCode()) ) { RestException restException = RestException.fromJson( response.getStream(), diff --git a/src/main/java/com/twilio/rest/previewiam/organizations/UserFetcher.java b/src/main/java/com/twilio/rest/previewiam/organizations/UserFetcher.java index 3abc3e86eb..0270ac88dc 100644 --- a/src/main/java/com/twilio/rest/previewiam/organizations/UserFetcher.java +++ b/src/main/java/com/twilio/rest/previewiam/organizations/UserFetcher.java @@ -14,15 +14,15 @@ package com.twilio.rest.previewiam.organizations; -import com.twilio.base.bearertoken.Fetcher; +import com.twilio.base.Fetcher; import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; import com.twilio.http.HttpMethod; import com.twilio.http.Response; -import com.twilio.http.bearertoken.BearerTokenRequest; -import com.twilio.http.bearertoken.BearerTokenTwilioRestClient; +import com.twilio.http.Request; +import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; public class UserFetcher extends Fetcher { @@ -39,7 +39,7 @@ public UserFetcher( } @Override - public User fetch(final BearerTokenTwilioRestClient client) { + public User fetch(final TwilioRestClient client) { String path = "/Organizations/{OrganizationSid}/scim/Users/{UserSid}"; path = @@ -49,7 +49,7 @@ public User fetch(final BearerTokenTwilioRestClient client) { ); path = path.replace("{" + "UserSid" + "}", this.pathUserSid.toString()); - BearerTokenRequest request = new BearerTokenRequest( + Request request = new Request( HttpMethod.GET, Domains.PREVIEWIAM.toString(), path @@ -62,7 +62,7 @@ public User fetch(final BearerTokenTwilioRestClient client) { "User fetch failed: Unable to connect to server" ); } else if ( - !BearerTokenTwilioRestClient.SUCCESS.test(response.getStatusCode()) + !TwilioRestClient.SUCCESS.test(response.getStatusCode()) ) { RestException restException = RestException.fromJson( response.getStream(), diff --git a/src/main/java/com/twilio/rest/previewiam/organizations/UserReader.java b/src/main/java/com/twilio/rest/previewiam/organizations/UserReader.java index 2ebdb45da6..c6bb6a57eb 100644 --- a/src/main/java/com/twilio/rest/previewiam/organizations/UserReader.java +++ b/src/main/java/com/twilio/rest/previewiam/organizations/UserReader.java @@ -14,17 +14,17 @@ package com.twilio.rest.previewiam.organizations; -import com.twilio.base.bearertoken.Page; -import com.twilio.base.bearertoken.Reader; -import com.twilio.base.bearertoken.ResourceSet; +import com.twilio.base.Page; +import com.twilio.base.Reader; +import com.twilio.base.ResourceSet; import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; import com.twilio.http.HttpMethod; import com.twilio.http.Response; -import com.twilio.http.bearertoken.BearerTokenRequest; -import com.twilio.http.bearertoken.BearerTokenTwilioRestClient; +import com.twilio.http.Request; +import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; public class UserReader extends Reader { @@ -42,11 +42,11 @@ public UserReader setFilter(final String filter) { } @Override - public ResourceSet read(final BearerTokenTwilioRestClient client) { + public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } - public Page firstPage(final BearerTokenTwilioRestClient client) { + public Page firstPage(final TwilioRestClient client) { String path = "/Organizations/{OrganizationSid}/scim/Users"; path = path.replace( @@ -54,7 +54,7 @@ public Page firstPage(final BearerTokenTwilioRestClient client) { this.pathOrganizationSid.toString() ); - BearerTokenRequest request = new BearerTokenRequest( + Request request = new Request( HttpMethod.GET, Domains.PREVIEWIAM.toString(), path @@ -66,8 +66,8 @@ public Page firstPage(final BearerTokenTwilioRestClient client) { } private Page pageForRequest( - final BearerTokenTwilioRestClient client, - final BearerTokenRequest request + final TwilioRestClient client, + final Request request ) { Response response = client.request(request); @@ -76,7 +76,7 @@ private Page pageForRequest( "User read failed: Unable to connect to server" ); } else if ( - !BearerTokenTwilioRestClient.SUCCESS.test(response.getStatusCode()) + !TwilioRestClient.SUCCESS.test(response.getStatusCode()) ) { RestException restException = RestException.fromJson( response.getStream(), @@ -102,9 +102,9 @@ private Page pageForRequest( @Override public Page previousPage( final Page page, - final BearerTokenTwilioRestClient client + final TwilioRestClient client ) { - BearerTokenRequest request = new BearerTokenRequest( + Request request = new Request( HttpMethod.GET, page.getPreviousPageUrl(Domains.PREVIEWIAM.toString()) ); @@ -114,9 +114,9 @@ public Page previousPage( @Override public Page nextPage( final Page page, - final BearerTokenTwilioRestClient client + final TwilioRestClient client ) { - BearerTokenRequest request = new BearerTokenRequest( + Request request = new Request( HttpMethod.GET, page.getNextPageUrl(Domains.PREVIEWIAM.toString()) ); @@ -126,9 +126,9 @@ public Page nextPage( @Override public Page getPage( final String targetUrl, - final BearerTokenTwilioRestClient client + final TwilioRestClient client ) { - BearerTokenRequest request = new BearerTokenRequest( + Request request = new Request( HttpMethod.GET, targetUrl ); @@ -136,7 +136,7 @@ public Page getPage( return pageForRequest(client, request); } - private void addQueryParams(final BearerTokenRequest request) { + private void addQueryParams(final Request request) { if (filter != null) { request.addQueryParam("filter", filter); } diff --git a/src/main/java/com/twilio/rest/previewiam/organizations/UserUpdater.java b/src/main/java/com/twilio/rest/previewiam/organizations/UserUpdater.java index b68b8557f0..9b3c2a0d4b 100644 --- a/src/main/java/com/twilio/rest/previewiam/organizations/UserUpdater.java +++ b/src/main/java/com/twilio/rest/previewiam/organizations/UserUpdater.java @@ -15,15 +15,15 @@ package com.twilio.rest.previewiam.organizations; import com.fasterxml.jackson.databind.ObjectMapper; -import com.twilio.base.bearertoken.Updater; +import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; import com.twilio.http.HttpMethod; import com.twilio.http.Response; -import com.twilio.http.bearertoken.BearerTokenRequest; -import com.twilio.http.bearertoken.BearerTokenTwilioRestClient; +import com.twilio.http.Request; +import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; public class UserUpdater extends Updater { @@ -54,7 +54,7 @@ public UserUpdater setIfMatch(final String ifMatch) { } @Override - public User update(final BearerTokenTwilioRestClient client) { + public User update(final TwilioRestClient client) { String path = "/Organizations/{OrganizationSid}/scim/Users/{UserSid}"; path = @@ -65,7 +65,7 @@ public User update(final BearerTokenTwilioRestClient client) { path = path.replace("{" + "UserSid" + "}", this.pathUserSid.toString()); path = path.replace("{" + "ScimUser" + "}", this.scimUser.toString()); - BearerTokenRequest request = new BearerTokenRequest( + Request request = new Request( HttpMethod.PUT, Domains.PREVIEWIAM.toString(), path @@ -79,7 +79,7 @@ public User update(final BearerTokenTwilioRestClient client) { "User update failed: Unable to connect to server" ); } else if ( - !BearerTokenTwilioRestClient.SUCCESS.test(response.getStatusCode()) + !TwilioRestClient.SUCCESS.test(response.getStatusCode()) ) { RestException restException = RestException.fromJson( response.getStream(), @@ -98,8 +98,8 @@ public User update(final BearerTokenTwilioRestClient client) { } private void addPostParams( - final BearerTokenRequest request, - BearerTokenTwilioRestClient client + final Request request, + TwilioRestClient client ) { ObjectMapper objectMapper = client.getObjectMapper(); if (scimUser != null) { @@ -107,7 +107,7 @@ private void addPostParams( } } - private void addHeaderParams(final BearerTokenRequest request) { + private void addHeaderParams(final Request request) { if (ifMatch != null) { request.addHeaderParam("If-Match", ifMatch); } diff --git a/src/test/java/com/twilio/ClusterTest.java b/src/test/java/com/twilio/ClusterTest.java index 50062a5486..e21df98c3a 100644 --- a/src/test/java/com/twilio/ClusterTest.java +++ b/src/test/java/com/twilio/ClusterTest.java @@ -1,10 +1,12 @@ package com.twilio; +import com.twilio.auth_strategy.TokenAuthStrategy; import com.twilio.base.Page; -import com.twilio.base.bearertoken.ResourceSet; -import com.twilio.credential.ClientCredentialProvider; +import com.twilio.base.ResourceSet; import com.twilio.http.CustomHttpClient; import com.twilio.http.TwilioRestClient; +import com.twilio.http.bearertoken.OrgsTokenManager; +import com.twilio.http.bearertoken.TokenManager; import com.twilio.rest.api.v2010.account.IncomingPhoneNumber; import com.twilio.rest.api.v2010.account.IncomingPhoneNumberReader; import com.twilio.rest.api.v2010.account.Message; @@ -57,8 +59,7 @@ public void setUp() { orgsClientId = System.getenv("TWILIO_ORGS_CLIENT_ID"); orgsClientSecret = System.getenv("TWILIO_ORGS_CLIENT_SECRET"); organisationSid = System.getenv("TWILIO_ORG_SID"); - TwilioOrgsTokenAuth.init(grantType, orgsClientId, orgsClientSecret); - + clientId = System.getenv("TWILIO_CLIENT_ID"); clientSecret = System.getenv("TWILIO_CLIENT_SECRET"); messageSid = System.getenv("TWILIO_MESSAGE_SID"); @@ -140,19 +141,25 @@ public void testListParams() { @Test public void testOrgsApi(){ + //Twilio.init(new OrgsClientCredentialProvider(orgsClientId, orgsClientSecret)); + + TokenManager tokenManager = new OrgsTokenManager("client_credentials", orgsClientId, orgsClientSecret); + TokenAuthStrategy tokenAuthStrategy = new TokenAuthStrategy(tokenManager); + TwilioRestClient client = new TwilioRestClient.Builder(tokenAuthStrategy) + .build(); //Fetching the account information - ResourceSet accountSet = Account.reader(organisationSid).read(); + ResourceSet accountSet = Account.reader(organisationSid).read(client); String accountSid = accountSet.iterator().next().getAccountSid(); assertNotNull(accountSid); //Fetching specific account - Account account = Account.fetcher(organisationSid, accountSid).fetch(); + Account account = Account.fetcher(organisationSid, accountSid).fetch(client); assertNotNull(account.getAccountSid()); //Fetching users of this organisation ResourceSet - userSet = com.twilio.rest.previewiam.organizations.User.reader(organisationSid).read(); + userSet = com.twilio.rest.previewiam.organizations.User.reader(organisationSid).read(client); assertNotNull(userSet); String userId = userSet.iterator().next().getId().toString(); assertNotNull(userId); diff --git a/src/test/java/com/twilio/http/bearerToken/BearerTokenNetworkHttpClientTest.java b/src/test/java/com/twilio/http/bearerToken/BearerTokenNetworkHttpClientTest.java deleted file mode 100644 index 41094c2ff6..0000000000 --- a/src/test/java/com/twilio/http/bearerToken/BearerTokenNetworkHttpClientTest.java +++ /dev/null @@ -1,213 +0,0 @@ -package com.twilio.http.bearerToken; - -import com.twilio.constant.EnumConstants; -import com.twilio.exception.ApiException; -import com.twilio.http.HttpMethod; -import com.twilio.http.Response; -import com.twilio.http.bearertoken.BearerTokenNetworkHttpClient; -import com.twilio.http.bearertoken.BearerTokenRequest; -import org.apache.hc.client5.http.impl.classic.CloseableHttpClient; -import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse; -import org.apache.hc.client5.http.impl.classic.HttpClientBuilder; -import org.apache.hc.core5.http.HttpEntity; -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.mockito.Spy; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.net.URL; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -public class BearerTokenNetworkHttpClientTest { - - private BearerTokenNetworkHttpClient client; - - @Mock - private BearerTokenRequest mockRequest; - - @Spy - private HttpClientBuilder mockBuilder; - - @Mock - private CloseableHttpClient mockClient; - - @Mock - private CloseableHttpResponse mockResponse; - - @Mock - private HttpEntity mockEntity; - - @Before - public void setUp() { - MockitoAnnotations.openMocks(this); - doReturn(mockClient).when(mockBuilder).build(); - client = new BearerTokenNetworkHttpClient(mockBuilder); - } - - private void setup( - final int statusCode, - final String content, - final HttpMethod method, - final Boolean requiresAuthentication - ) throws IOException { - final InputStream stream = new ByteArrayInputStream(content.getBytes("UTF-8")); - - when(mockRequest.getMethod()).thenReturn(method); - when(mockRequest.constructURL()).thenReturn(new URL("http://foo.com/hello")); - when(mockRequest.requiresAuthentication()).thenReturn(requiresAuthentication); - when(mockRequest.getAuthString()).thenReturn("Bearer token123"); - when(mockRequest.getContentType()).thenReturn(EnumConstants.ContentType.FORM_URLENCODED); - when(mockClient.execute(any())).thenReturn(mockResponse); - when(mockEntity.isRepeatable()).thenReturn(true); - when(mockEntity.getContentLength()).thenReturn(1L); - when(mockEntity.getContent()).thenReturn(stream); - when(mockResponse.getEntity()).thenReturn(mockEntity); - when(mockResponse.getCode()).thenReturn(statusCode); - } - - @Test - public void testGet() throws IOException { - setup(200, "success", HttpMethod.GET, false); - - Response resp = client.makeRequest(mockRequest); - - assertEquals(200, resp.getStatusCode()); - assertEquals("success", resp.getContent()); - } - - @Test - public void testGetWithAuthentication() throws IOException { - setup(200, "authenticated", HttpMethod.GET, true); - - Response resp = client.makeRequest(mockRequest); - - assertEquals(200, resp.getStatusCode()); - assertEquals("authenticated", resp.getContent()); - } - - @Test - public void testPost() throws IOException { - setup(201, "created", HttpMethod.POST, false); - - Response resp = client.makeRequest(mockRequest); - - assertEquals(201, resp.getStatusCode()); - assertEquals("created", resp.getContent()); - } - - @Test - public void testJsonPost() throws IOException { - setup(201, "created", HttpMethod.POST, false); - when(mockRequest.getContentType()).thenReturn(EnumConstants.ContentType.JSON); - String body = "{\"name\":\"value\"}"; - when(mockRequest.getBody()).thenReturn(body); - - Response resp = client.makeRequest(mockRequest); - - assertEquals(201, resp.getStatusCode()); - assertEquals("created", resp.getContent()); - } - - @Test - public void testFormUrlEncodedPost() throws IOException { - setup(201, "form-urlencoded", HttpMethod.POST, false); - - // Set up post parameters - Map> postParams = new HashMap<>(); - postParams.put("name", Arrays.asList("John Doe")); - postParams.put("tags", Arrays.asList("customer", "premium")); - when(mockRequest.getPostParams()).thenReturn(postParams); - - Response resp = client.makeRequest(mockRequest); - - assertEquals(201, resp.getStatusCode()); - assertEquals("form-urlencoded", resp.getContent()); - } - - @Test - public void testPut() throws IOException { - setup(200, "updated", HttpMethod.PUT, false); - - Response resp = client.makeRequest(mockRequest); - - assertEquals(200, resp.getStatusCode()); - assertEquals("updated", resp.getContent()); - } - - @Test - public void testPatch() throws IOException { - setup(200, "patched", HttpMethod.PATCH, false); - - Response resp = client.makeRequest(mockRequest); - - assertEquals(200, resp.getStatusCode()); - assertEquals("patched", resp.getContent()); - } - - @Test - public void testDelete() throws IOException { - setup(204, "", HttpMethod.DELETE, false); - - Response resp = client.makeRequest(mockRequest); - - assertEquals(204, resp.getStatusCode()); - assertEquals("", resp.getContent()); - } - - @Test - public void testWithCustomHeaders() throws IOException { - setup(200, "headers", HttpMethod.GET, false); - - Map> headers = new HashMap<>(); - headers.put("X-Custom-Header", Arrays.asList("CustomValue")); - headers.put("Accept-Language", Arrays.asList("en-US")); - when(mockRequest.getHeaderParams()).thenReturn(headers); - - Response resp = client.makeRequest(mockRequest); - - assertEquals(200, resp.getStatusCode()); - assertEquals("headers", resp.getContent()); - } - - @Test(expected = ApiException.class) - public void testIOException() throws IOException { - when(mockRequest.getMethod()).thenReturn(HttpMethod.GET); - when(mockRequest.constructURL()).thenReturn(new URL("http://foo.com/hello")); - when(mockRequest.requiresAuthentication()).thenReturn(false); - when(mockClient.execute(any())).thenThrow(new IOException("Connection error")); - - client.makeRequest(mockRequest); - } - - @Test - public void testReliableRequest() { - BearerTokenRequest request = mock(BearerTokenRequest.class); - when(request.getMethod()).thenReturn(HttpMethod.GET); - - BearerTokenNetworkHttpClient clientSpy = spy(client); - doReturn(new Response("", 204)).when(clientSpy).makeRequest(request); - - clientSpy.reliableRequest(request); - - assertNotNull(clientSpy.getLastRequest()); - assertNotNull(clientSpy.getLastResponse()); - } -} From 7e98bc341a968c56f1627a8053ffab7501ebbaf9 Mon Sep 17 00:00:00 2001 From: sbansla <104902068+sbansla@users.noreply.github.com> Date: Thu, 18 Sep 2025 18:05:28 +0530 Subject: [PATCH 23/32] fix: removed noauth flow (#899) * removed noauth flow * added noauth test --- src/main/java/com/twilio/TwilioNoAuth.java | 48 ------ .../twilio/auth_strategy/NoAuthStrategy.java | 17 +- .../java/com/twilio/base/noauth/Creator.java | 51 ------ .../java/com/twilio/base/noauth/Deleter.java | 51 ------ .../java/com/twilio/base/noauth/Fetcher.java | 52 ------ .../java/com/twilio/base/noauth/Resource.java | 9 - .../java/com/twilio/base/noauth/Updater.java | 51 ------ .../com/twilio/http/TwilioRestClient.java | 11 +- .../twilio/http/noauth/NoAuthHttpClient.java | 106 ------------ .../http/noauth/NoAuthNetworkHttpClient.java | 139 --------------- .../com/twilio/http/noauth/NoAuthRequest.java | 19 -- .../http/noauth/NoAuthTwilioRestClient.java | 147 ---------------- .../java/com/twilio/rest/iam/v1/Token.java | 2 +- .../com/twilio/rest/iam/v1/TokenCreator.java | 16 +- .../com/twilio/rest/oauth/v1/Authorize.java | 2 +- .../rest/oauth/v1/AuthorizeFetcher.java | 16 +- .../java/com/twilio/rest/oauth/v1/Token.java | 2 +- .../twilio/rest/oauth/v1/TokenCreator.java | 16 +- .../twilio/rest/previewiam/v1/Authorize.java | 2 +- .../rest/previewiam/v1/AuthorizeFetcher.java | 16 +- .../com/twilio/rest/previewiam/v1/Token.java | 2 +- .../rest/previewiam/v1/TokenCreator.java | 18 +- .../com/twilio/http/TwilioRestClientTest.java | 38 ++++ .../noauth/NoAuthNetworkHttpClientTest.java | 162 ------------------ 24 files changed, 113 insertions(+), 880 deletions(-) delete mode 100644 src/main/java/com/twilio/TwilioNoAuth.java delete mode 100644 src/main/java/com/twilio/base/noauth/Creator.java delete mode 100644 src/main/java/com/twilio/base/noauth/Deleter.java delete mode 100644 src/main/java/com/twilio/base/noauth/Fetcher.java delete mode 100644 src/main/java/com/twilio/base/noauth/Resource.java delete mode 100644 src/main/java/com/twilio/base/noauth/Updater.java delete mode 100644 src/main/java/com/twilio/http/noauth/NoAuthHttpClient.java delete mode 100644 src/main/java/com/twilio/http/noauth/NoAuthNetworkHttpClient.java delete mode 100644 src/main/java/com/twilio/http/noauth/NoAuthRequest.java delete mode 100644 src/main/java/com/twilio/http/noauth/NoAuthTwilioRestClient.java delete mode 100644 src/test/java/com/twilio/http/noauth/NoAuthNetworkHttpClientTest.java diff --git a/src/main/java/com/twilio/TwilioNoAuth.java b/src/main/java/com/twilio/TwilioNoAuth.java deleted file mode 100644 index e18e69fad5..0000000000 --- a/src/main/java/com/twilio/TwilioNoAuth.java +++ /dev/null @@ -1,48 +0,0 @@ -package com.twilio; - -import com.twilio.annotations.Beta; -import com.twilio.http.noauth.NoAuthTwilioRestClient; -import lombok.Getter; - -import java.util.List; -import com.twilio.exception.AuthenticationException; - -@Beta -public class TwilioNoAuth { - @Getter - private static List userAgentExtensions; - private static String region = System.getenv("TWILIO_REGION"); - private static String edge = System.getenv("TWILIO_EDGE"); - - private static volatile NoAuthTwilioRestClient noAuthTwilioRestClient; - - private TwilioNoAuth() { - } - - public static NoAuthTwilioRestClient getRestClient() { - if (TwilioNoAuth.noAuthTwilioRestClient == null) { - synchronized (TwilioNoAuth.class) { - if (TwilioNoAuth.noAuthTwilioRestClient == null) { - TwilioNoAuth.noAuthTwilioRestClient = buildOAuthRestClient(); - } - } - } - return TwilioNoAuth.noAuthTwilioRestClient; - } - - private static NoAuthTwilioRestClient buildOAuthRestClient() { - - NoAuthTwilioRestClient.Builder builder = new NoAuthTwilioRestClient.Builder(); - - if (userAgentExtensions != null) { - builder.userAgentExtensions(TwilioNoAuth.userAgentExtensions); - } - - builder.region(TwilioNoAuth.region); - builder.edge(TwilioNoAuth.edge); - - return builder.build(); - } - - -} diff --git a/src/main/java/com/twilio/auth_strategy/NoAuthStrategy.java b/src/main/java/com/twilio/auth_strategy/NoAuthStrategy.java index e53014e556..99941fa0fc 100644 --- a/src/main/java/com/twilio/auth_strategy/NoAuthStrategy.java +++ b/src/main/java/com/twilio/auth_strategy/NoAuthStrategy.java @@ -2,9 +2,24 @@ import com.twilio.constant.EnumConstants; +// Does not have any state thus thread safe. public class NoAuthStrategy extends AuthStrategy { + private static volatile NoAuthStrategy INSTANCE; - public NoAuthStrategy(String token) { + private static volatile NoAuthStrategy instance; + + public static NoAuthStrategy getInstance() { + if (instance == null) { + synchronized (NoAuthStrategy.class) { + if (instance == null) { + instance = new NoAuthStrategy(); + } + } + } + return instance; + } + + private NoAuthStrategy() { super(EnumConstants.AuthType.NO_AUTH); } diff --git a/src/main/java/com/twilio/base/noauth/Creator.java b/src/main/java/com/twilio/base/noauth/Creator.java deleted file mode 100644 index f4860ca592..0000000000 --- a/src/main/java/com/twilio/base/noauth/Creator.java +++ /dev/null @@ -1,51 +0,0 @@ -package com.twilio.base.noauth; - -import com.twilio.Twilio; -import com.twilio.TwilioNoAuth; -import com.twilio.http.noauth.NoAuthTwilioRestClient; - -import java.util.concurrent.CompletableFuture; - -/** - * Executor for creation of a resource. - * - * @param type of the resource - */ -public abstract class Creator { - - /** - * Execute an async request using default client. - * - * @return future that resolves to requested object - */ - public CompletableFuture createAsync() { - return createAsync(TwilioNoAuth.getRestClient()); - } - - /** - * Execute an async request using specified client. - * - * @param client client used to make request - * @return future that resolves to requested object - */ - public CompletableFuture createAsync(final NoAuthTwilioRestClient client) { - return CompletableFuture.supplyAsync(() -> create(client), Twilio.getExecutorService()); - } - - /** - * Execute a request using default client. - * - * @return Requested object - */ - public T create() { - return create(TwilioNoAuth.getRestClient()); - } - - /** - * Execute a request using specified client. - * - * @param client client used to make request - * @return Requested object - */ - public abstract T create(final NoAuthTwilioRestClient client); -} diff --git a/src/main/java/com/twilio/base/noauth/Deleter.java b/src/main/java/com/twilio/base/noauth/Deleter.java deleted file mode 100644 index 59e0f6ed04..0000000000 --- a/src/main/java/com/twilio/base/noauth/Deleter.java +++ /dev/null @@ -1,51 +0,0 @@ -package com.twilio.base.noauth; - -import com.twilio.Twilio; -import com.twilio.TwilioNoAuth; -import com.twilio.http.noauth.NoAuthTwilioRestClient; - -import java.util.concurrent.CompletableFuture; - -/** - * Executor for deletes of a resource. - * - * @param type of the resource - */ -public abstract class Deleter { - - /** - * Execute an async request using default client. - * - * @return future that resolves to true if the object was deleted - */ - public CompletableFuture deleteAsync() { - return deleteAsync(TwilioNoAuth.getRestClient()); - } - - /** - * Execute an async request using specified client. - * - * @param client client used to make request - * @return future that resolves to true if the object was deleted - */ - public CompletableFuture deleteAsync(final NoAuthTwilioRestClient client) { - return CompletableFuture.supplyAsync(() -> delete(client), Twilio.getExecutorService()); - } - - /** - * Execute a request using default client. - * - * @return true if the object was deleted - */ - public boolean delete() { - return delete(TwilioNoAuth.getRestClient()); - } - - /** - * Execute a request using specified client. - * - * @param client client used to make request - * @return true if the object was deleted - */ - public abstract boolean delete(final NoAuthTwilioRestClient client); -} diff --git a/src/main/java/com/twilio/base/noauth/Fetcher.java b/src/main/java/com/twilio/base/noauth/Fetcher.java deleted file mode 100644 index 27ef356c36..0000000000 --- a/src/main/java/com/twilio/base/noauth/Fetcher.java +++ /dev/null @@ -1,52 +0,0 @@ -package com.twilio.base.noauth; - -import com.twilio.Twilio; - -import com.twilio.TwilioNoAuth; -import com.twilio.http.noauth.NoAuthTwilioRestClient; - -import java.util.concurrent.CompletableFuture; - -/** - * Executor for fetches of a resource. - * - * @param type of the resource - */ -public abstract class Fetcher { - - /** - * Execute an async request using default client. - * - * @return future that resolves to requested object - */ - public CompletableFuture fetchAsync() { - return fetchAsync(TwilioNoAuth.getRestClient()); - } - - /** - * Execute an async request using specified client. - * - * @param client client used to make request - * @return future that resolves to requested object - */ - public CompletableFuture fetchAsync(final NoAuthTwilioRestClient client) { - return CompletableFuture.supplyAsync(() -> fetch(client), Twilio.getExecutorService()); - } - - /** - * Execute a request using default client. - * - * @return Requested object - */ - public T fetch() { - return fetch(TwilioNoAuth.getRestClient()); - } - - /** - * Execute a request using specified client. - * - * @param client client used to make request - * @return Requested object - */ - public abstract T fetch(final NoAuthTwilioRestClient client); -} diff --git a/src/main/java/com/twilio/base/noauth/Resource.java b/src/main/java/com/twilio/base/noauth/Resource.java deleted file mode 100644 index 88e316899f..0000000000 --- a/src/main/java/com/twilio/base/noauth/Resource.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.twilio.base.noauth; - -import java.io.Serializable; - -public abstract class Resource implements Serializable { - - private static final long serialVersionUID = -5898012691404059592L; - -} diff --git a/src/main/java/com/twilio/base/noauth/Updater.java b/src/main/java/com/twilio/base/noauth/Updater.java deleted file mode 100644 index f85536e002..0000000000 --- a/src/main/java/com/twilio/base/noauth/Updater.java +++ /dev/null @@ -1,51 +0,0 @@ -package com.twilio.base.noauth; - -import com.twilio.Twilio; -import com.twilio.TwilioNoAuth; -import com.twilio.http.noauth.NoAuthTwilioRestClient; - -import java.util.concurrent.CompletableFuture; - -/** - * Executor for updates of a resource. - * - * @param type of the resource - */ -public abstract class Updater { - - /** - * Execute an async request using default client. - * - * @return future that resolves to requested object - */ - public CompletableFuture updateAsync() { - return updateAsync(TwilioNoAuth.getRestClient()); - } - - /** - * Execute an async request using specified client. - * - * @param client client used to make request - * @return future that resolves to requested object - */ - public CompletableFuture updateAsync(final NoAuthTwilioRestClient client) { - return CompletableFuture.supplyAsync(() -> update(client), Twilio.getExecutorService()); - } - - /** - * Execute a request using default client. - * - * @return Requested object - */ - public T update() { - return update(TwilioNoAuth.getRestClient()); - } - - /** - * Execute a request using specified client. - * - * @param client client used to make request - * @return Requested object - */ - public abstract T update(final NoAuthTwilioRestClient client); -} diff --git a/src/main/java/com/twilio/http/TwilioRestClient.java b/src/main/java/com/twilio/http/TwilioRestClient.java index c4b8ff2b41..92e1abca2f 100644 --- a/src/main/java/com/twilio/http/TwilioRestClient.java +++ b/src/main/java/com/twilio/http/TwilioRestClient.java @@ -89,10 +89,13 @@ protected TwilioRestClient(Builder b) { * @return Response object */ public Response request(final Request request) { - if (username != null && password != null) { - request.setAuth(username, password); - } else if (authStrategy != null) { - request.setAuth(authStrategy); + // If authStrategy is passed from NoAuth API, no need to set authStrategy (ex TokenCreator). + if (request.getAuthStrategy() == null) { + if (username != null && password != null) { + request.setAuth(username, password); + } else if (authStrategy != null) { + request.setAuth(authStrategy); + } } if (region != null) diff --git a/src/main/java/com/twilio/http/noauth/NoAuthHttpClient.java b/src/main/java/com/twilio/http/noauth/NoAuthHttpClient.java deleted file mode 100644 index 09a159bb74..0000000000 --- a/src/main/java/com/twilio/http/noauth/NoAuthHttpClient.java +++ /dev/null @@ -1,106 +0,0 @@ -package com.twilio.http.noauth; - -import com.twilio.http.HttpClient; -import com.twilio.http.Response; -import lombok.Getter; -import lombok.Setter; -import org.apache.hc.client5.http.config.RequestConfig; -import org.apache.hc.client5.http.impl.DefaultRedirectStrategy; -import org.apache.hc.client5.http.protocol.RedirectStrategy; -import org.apache.hc.core5.http.io.SocketConfig; - -public abstract class NoAuthHttpClient { - public static final RequestConfig DEFAULT_REQUEST_CONFIG = RequestConfig - .custom() - .setConnectTimeout(HttpClient.CONNECTION_TIMEOUT) - .build(); - public static final SocketConfig DEFAULT_SOCKET_CONFIG = SocketConfig - .custom() - .setSoTimeout(HttpClient.SOCKET_TIMEOUT) - .build(); - @Getter - @Setter - private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy(); - - @Getter - private Response lastResponse; - @Getter - private NoAuthRequest lastRequest; - - public Response reliableRequest(final NoAuthRequest request) { - return reliableRequest(request, HttpClient.RETRY_CODES, HttpClient.RETRIES, HttpClient.DELAY_MILLIS); - } - - public Response reliableRequest(final NoAuthRequest request, final int[] retryCodes, int retries, - final long delayMillis) { - lastRequest = request; - Response response = null; - while (retries > 0) { - response = makeRequest(request); - - if (!shouldRetry(response, retryCodes)) { - break; - } - - try { - Thread.sleep(delayMillis); - } catch (final InterruptedException e) { - // Delay failed, continue - } - - // Decrement retries - retries--; - } - - lastResponse = response; - - return response; - } - - protected boolean shouldRetry(final Response response, final int[] retryCodes) { - if (response == null) { - return true; - } - - int statusCode = response.getStatusCode(); - int category = (int) Math.floor(statusCode / 100.0); - - for (final int retryCode : retryCodes) { - switch (retryCode) { - case HttpClient.ANY_100: - if (category == 1) { - return true; - } - break; - case HttpClient.ANY_200: - if (category == 2) { - return true; - } - break; - case HttpClient.ANY_300: - if (category == 3) { - return true; - } - break; - case HttpClient.ANY_400: - if (category == 4) { - return true; - } - break; - case HttpClient.ANY_500: - if (category == 5) { - return true; - } - break; - default: - if (statusCode == retryCode) { - return true; - } - break; - } - } - return false; - } - - public abstract Response makeRequest(NoAuthRequest request); -} diff --git a/src/main/java/com/twilio/http/noauth/NoAuthNetworkHttpClient.java b/src/main/java/com/twilio/http/noauth/NoAuthNetworkHttpClient.java deleted file mode 100644 index a1b84a5532..0000000000 --- a/src/main/java/com/twilio/http/noauth/NoAuthNetworkHttpClient.java +++ /dev/null @@ -1,139 +0,0 @@ -package com.twilio.http.noauth; - -import static com.twilio.http.HttpClient.createHttpUriRequestBase; - -import com.twilio.Twilio; -import com.twilio.constant.EnumConstants; -import com.twilio.exception.ApiException; -import com.twilio.http.HttpMethod; -import com.twilio.http.HttpUtility; -import com.twilio.http.Response; -import java.util.ArrayList; -import java.util.Map.Entry; -import org.apache.hc.client5.http.classic.methods.HttpDelete; -import org.apache.hc.client5.http.classic.methods.HttpGet; -import org.apache.hc.client5.http.classic.methods.HttpPatch; -import org.apache.hc.client5.http.classic.methods.HttpPost; -import org.apache.hc.client5.http.classic.methods.HttpPut; -import org.apache.hc.client5.http.classic.methods.HttpUriRequestBase; -import org.apache.hc.client5.http.config.RequestConfig; -import org.apache.hc.client5.http.entity.UrlEncodedFormEntity; -import org.apache.hc.client5.http.impl.classic.CloseableHttpClient; -import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse; -import org.apache.hc.client5.http.impl.classic.HttpClientBuilder; -import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager; -import org.apache.hc.core5.http.ContentType; -import org.apache.hc.core5.http.HttpEntity; -import org.apache.hc.core5.http.HttpHeaders; -import org.apache.hc.core5.http.HttpVersion; -import org.apache.hc.core5.http.NameValuePair; -import org.apache.hc.core5.http.io.SocketConfig; -import org.apache.hc.core5.http.io.entity.BufferedHttpEntity; -import org.apache.hc.core5.http.io.entity.StringEntity; -import org.apache.hc.core5.http.message.BasicHeader; - -import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.util.Arrays; -import java.util.Collection; -import java.util.List; -import org.apache.hc.core5.http.message.BasicNameValuePair; - -public class NoAuthNetworkHttpClient extends NoAuthHttpClient { - - protected final CloseableHttpClient client; - - public NoAuthNetworkHttpClient() { - this(DEFAULT_REQUEST_CONFIG); - } - - public NoAuthNetworkHttpClient(final RequestConfig requestConfig) { - this(requestConfig, DEFAULT_SOCKET_CONFIG); - } - - public NoAuthNetworkHttpClient(final RequestConfig requestConfig, final SocketConfig socketConfig) { - Collection headers = Arrays.asList( - new BasicHeader("X-Twilio-Client", "java-" + Twilio.VERSION), - new BasicHeader(HttpHeaders.ACCEPT, "application/json"), - new BasicHeader(HttpHeaders.ACCEPT_ENCODING, "utf-8") - ); - - String googleAppEngineVersion = System.getProperty("com.google.appengine.runtime.version"); - boolean isGoogleAppEngine = googleAppEngineVersion != null && !googleAppEngineVersion.isEmpty(); - - HttpClientBuilder clientBuilder = HttpClientBuilder.create(); - - if (!isGoogleAppEngine) { - clientBuilder.useSystemProperties(); - } - - PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(); - connectionManager.setDefaultSocketConfig(socketConfig); - /* - * Example: Lets say client has one server. - * There are 4 servers on edge handling client request. - * Each request takes on an average 500ms (2 request per second) - * Total number request can be server in a second from a route: 20 * 4 * 2 (DefaultMaxPerRoute * edge servers * request per second) - */ - connectionManager.setDefaultMaxPerRoute(20); - connectionManager.setMaxTotal(100); - - client = clientBuilder - .setConnectionManager(connectionManager) - .setDefaultRequestConfig(requestConfig) - .setDefaultHeaders(headers) - .setRedirectStrategy(this.getRedirectStrategy()) - .build(); - } - - @Override - public Response makeRequest(NoAuthRequest request) { - HttpMethod method = request.getMethod(); - HttpUriRequestBase httpUriRequestBase = createHttpUriRequestBase(request); - - httpUriRequestBase.setConfig(DEFAULT_REQUEST_CONFIG); - - httpUriRequestBase.setVersion(HttpVersion.HTTP_1_1); - - if (method != HttpMethod.GET) { - // TODO: It will be removed after one RC Release. - if (request.getContentType() == null) request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); - if (EnumConstants.ContentType.JSON.getValue().equals(request.getContentType().getValue())) { - HttpEntity entity = new StringEntity(request.getBody(), ContentType.APPLICATION_JSON); - httpUriRequestBase.setEntity(entity); - httpUriRequestBase.addHeader( - HttpHeaders.CONTENT_TYPE, EnumConstants.ContentType.JSON.getValue()); - } else { - httpUriRequestBase.addHeader( - HttpHeaders.CONTENT_TYPE, EnumConstants.ContentType.FORM_URLENCODED.getValue()); - // Create your form parameters - List formParams = new ArrayList<>(); - for ( Entry> entry : request.getPostParams().entrySet()) { - for (String value : entry.getValue()) { - formParams.add(new BasicNameValuePair(entry.getKey(), value)); - } - } - - // Build the entity with URL form encoded parameters - UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(formParams, StandardCharsets.UTF_8); - // Set the entity on the request - httpUriRequestBase.setEntity(formEntity); - } - - } - httpUriRequestBase.addHeader(HttpHeaders.USER_AGENT, HttpUtility.getUserAgentString(request.getUserAgentExtensions())); - - try { - CloseableHttpResponse response = client.execute(httpUriRequestBase); - HttpEntity entity = response.getEntity(); - return new Response( - // Consume the entire HTTP response before returning the stream - entity == null ? null : new BufferedHttpEntity(entity).getContent(), - response.getCode(), - response.getHeaders() - ); - } catch (IOException e) { - throw new ApiException(e.getMessage(), e); - } - } -} diff --git a/src/main/java/com/twilio/http/noauth/NoAuthRequest.java b/src/main/java/com/twilio/http/noauth/NoAuthRequest.java deleted file mode 100644 index 1d216699eb..0000000000 --- a/src/main/java/com/twilio/http/noauth/NoAuthRequest.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.twilio.http.noauth; - -import com.twilio.http.HttpMethod; -import com.twilio.http.IRequest; - -public class NoAuthRequest extends IRequest { - - public NoAuthRequest(HttpMethod method, String url) { - super(method, url); - } - - public NoAuthRequest(HttpMethod method, String domain, String uri) { - super(method, domain, uri, null); - } - - public NoAuthRequest(HttpMethod method, String domain, String uri, String region) { - super(method, domain, uri, region); - } -} diff --git a/src/main/java/com/twilio/http/noauth/NoAuthTwilioRestClient.java b/src/main/java/com/twilio/http/noauth/NoAuthTwilioRestClient.java deleted file mode 100644 index ff2e790380..0000000000 --- a/src/main/java/com/twilio/http/noauth/NoAuthTwilioRestClient.java +++ /dev/null @@ -1,147 +0,0 @@ -package com.twilio.http.noauth; - -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; -import com.twilio.http.HttpClient; -import com.twilio.http.NetworkHttpClient; -import com.twilio.http.Response; -import lombok.Getter; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.function.Predicate; - - -/* - * Use this NoAuth Rest Client if no authentication is involved in an API. - */ -public class NoAuthTwilioRestClient { - @Getter - private final ObjectMapper objectMapper; - - @Getter - private final String region; - @Getter - private final String edge; - @Getter - private final NoAuthNetworkHttpClient httpClient; - @Getter - private final List userAgentExtensions; - private static final Logger logger = LoggerFactory.getLogger(NoAuthTwilioRestClient.class); - - public static final Predicate SUCCESS = i -> i != null && i >= 200 && i < 400; - - private NoAuthTwilioRestClient(NoAuthTwilioRestClient.Builder b) { - this.region = b.region; - this.edge = b.edge; - this.httpClient = b.httpClient; - this.objectMapper = b.objectMapper; - this.userAgentExtensions = b.userAgentExtensions; - } - - public static class Builder { - // This module configures the ObjectMapper to use - // public API methods for manipulating java.time.* - // classes. The alternative is to use reflection which - // generates warnings from the module system on Java 9+ - private static final ObjectMapper DEFAULT_OBJECT_MAPPER = new ObjectMapper() - .registerModule(new JavaTimeModule()); - - private String region; - private String edge; - private NoAuthNetworkHttpClient httpClient; - private List userAgentExtensions; - private ObjectMapper objectMapper = DEFAULT_OBJECT_MAPPER; - - public Builder() { - this.region = System.getenv("TWILIO_REGION"); - this.edge = System.getenv("TWILIO_EDGE"); - userAgentExtensions = new ArrayList<>(); - } - - public NoAuthTwilioRestClient.Builder region(final String region) { - this.region = region; - return this; - } - - public NoAuthTwilioRestClient.Builder edge(final String edge) { - this.edge = edge; - return this; - } - - public NoAuthTwilioRestClient.Builder httpClient(final NoAuthNetworkHttpClient httpClient) { - this.httpClient = httpClient; - return this; - } - - public NoAuthTwilioRestClient.Builder userAgentExtensions(final List userAgentExtensions) { - if (userAgentExtensions != null && !userAgentExtensions.isEmpty()) { - this.userAgentExtensions = new ArrayList<>(userAgentExtensions); - } - return this; - } - - public NoAuthTwilioRestClient.Builder objectMapper(final ObjectMapper objectMapper) { - this.objectMapper = objectMapper; - return this; - } - - public NoAuthTwilioRestClient build() { - if (this.httpClient == null) { - this.httpClient = new NoAuthNetworkHttpClient(); - } - return new NoAuthTwilioRestClient(this); - } - } - public Response request(NoAuthRequest request) { - if (region != null) - request.setRegion(region); - if (edge != null) - request.setEdge(edge); - - if (userAgentExtensions != null && !userAgentExtensions.isEmpty()) { - request.setUserAgentExtensions(userAgentExtensions); - } - logRequest(request); - Response response = httpClient.reliableRequest(request); - - if (logger.isDebugEnabled()) { - logger.debug("status code: {}", response.getStatusCode()); - org.apache.hc.core5.http.Header[] responseHeaders = response.getHeaders(); - logger.debug("response headers:"); - for (int i = 0; i < responseHeaders.length; i++) { - logger.debug("responseHeader: {}", responseHeaders[i]); - } - } - - return response; - } - - public void logRequest(final NoAuthRequest request) { - if (logger.isDebugEnabled()) { - logger.debug("-- BEGIN Twilio API NoAuthRequest --"); - logger.debug("request method: " + request.getMethod()); - logger.debug("request URL: " + request.constructURL().toString()); - final Map> queryParams = request.getQueryParams(); - final Map> headerParams = request.getHeaderParams(); - - if (queryParams != null && !queryParams.isEmpty()) { - logger.debug("query parameters: " + queryParams); - } - - if (headerParams != null && !headerParams.isEmpty()) { - logger.debug("header parameters: "); - for (String key : headerParams.keySet()) { - if (!key.toLowerCase().contains("authorization")) { - logger.debug(key + ": " + headerParams.get(key)); - } - } - } - - logger.debug("-- END Twilio API NoAuthRequest --"); - } - } -} diff --git a/src/main/java/com/twilio/rest/iam/v1/Token.java b/src/main/java/com/twilio/rest/iam/v1/Token.java index c3d454f14a..e81303e1db 100644 --- a/src/main/java/com/twilio/rest/iam/v1/Token.java +++ b/src/main/java/com/twilio/rest/iam/v1/Token.java @@ -20,7 +20,7 @@ import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; -import com.twilio.base.noauth.Resource; +import com.twilio.base.Resource; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import java.io.IOException; diff --git a/src/main/java/com/twilio/rest/iam/v1/TokenCreator.java b/src/main/java/com/twilio/rest/iam/v1/TokenCreator.java index eed268b64f..66b5f2e181 100644 --- a/src/main/java/com/twilio/rest/iam/v1/TokenCreator.java +++ b/src/main/java/com/twilio/rest/iam/v1/TokenCreator.java @@ -14,15 +14,16 @@ package com.twilio.rest.iam.v1; -import com.twilio.base.noauth.Creator; +import com.twilio.auth_strategy.NoAuthStrategy; +import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; import com.twilio.http.HttpMethod; +import com.twilio.http.Request; import com.twilio.http.Response; -import com.twilio.http.noauth.NoAuthRequest; -import com.twilio.http.noauth.NoAuthTwilioRestClient; +import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; public class TokenCreator extends Creator { @@ -82,19 +83,20 @@ public TokenCreator setScope(final String scope) { } @Override - public Token create(final NoAuthTwilioRestClient client) { + public Token create(final TwilioRestClient client) { String path = "/v1/token"; path = path.replace("{" + "grant_type" + "}", this.grantType.toString()); path = path.replace("{" + "client_id" + "}", this.clientId.toString()); - NoAuthRequest request = new NoAuthRequest( + Request request = new Request( HttpMethod.POST, Domains.IAM.toString(), path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + request.setAuth(NoAuthStrategy.getInstance()); addPostParams(request); Response response = client.request(request); if (response == null) { @@ -102,7 +104,7 @@ public Token create(final NoAuthTwilioRestClient client) { "Token creation failed: Unable to connect to server" ); } else if ( - !NoAuthTwilioRestClient.SUCCESS.test(response.getStatusCode()) + !TwilioRestClient.SUCCESS.test(response.getStatusCode()) ) { RestException restException = RestException.fromJson( response.getStream(), @@ -120,7 +122,7 @@ public Token create(final NoAuthTwilioRestClient client) { return Token.fromJson(response.getStream(), client.getObjectMapper()); } - private void addPostParams(final NoAuthRequest request) { + private void addPostParams(final Request request) { if (grantType != null) { request.addPostParam("grant_type", grantType); } diff --git a/src/main/java/com/twilio/rest/oauth/v1/Authorize.java b/src/main/java/com/twilio/rest/oauth/v1/Authorize.java index 9b0025da6a..4a1c0e6a06 100644 --- a/src/main/java/com/twilio/rest/oauth/v1/Authorize.java +++ b/src/main/java/com/twilio/rest/oauth/v1/Authorize.java @@ -20,7 +20,7 @@ import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; -import com.twilio.base.noauth.Resource; +import com.twilio.base.Resource; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import java.io.IOException; diff --git a/src/main/java/com/twilio/rest/oauth/v1/AuthorizeFetcher.java b/src/main/java/com/twilio/rest/oauth/v1/AuthorizeFetcher.java index c6c1afd09f..6b66ab822a 100644 --- a/src/main/java/com/twilio/rest/oauth/v1/AuthorizeFetcher.java +++ b/src/main/java/com/twilio/rest/oauth/v1/AuthorizeFetcher.java @@ -14,15 +14,16 @@ package com.twilio.rest.oauth.v1; -import com.twilio.base.noauth.Fetcher; +import com.twilio.auth_strategy.NoAuthStrategy; +import com.twilio.base.Fetcher; import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; import com.twilio.http.HttpMethod; import com.twilio.http.Response; -import com.twilio.http.noauth.NoAuthRequest; -import com.twilio.http.noauth.NoAuthTwilioRestClient; +import com.twilio.http.Request; +import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; public class AuthorizeFetcher extends Fetcher { @@ -61,16 +62,17 @@ public AuthorizeFetcher setState(final String state) { } @Override - public Authorize fetch(final NoAuthTwilioRestClient client) { + public Authorize fetch(final TwilioRestClient client) { String path = "/v1/authorize"; - NoAuthRequest request = new NoAuthRequest( + Request request = new Request( HttpMethod.GET, Domains.OAUTH.toString(), path ); addQueryParams(request); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + request.setAuth(NoAuthStrategy.getInstance()); Response response = client.request(request); if (response == null) { @@ -78,7 +80,7 @@ public Authorize fetch(final NoAuthTwilioRestClient client) { "Authorize fetch failed: Unable to connect to server" ); } else if ( - !NoAuthTwilioRestClient.SUCCESS.test(response.getStatusCode()) + !TwilioRestClient.SUCCESS.test(response.getStatusCode()) ) { RestException restException = RestException.fromJson( response.getStream(), @@ -99,7 +101,7 @@ public Authorize fetch(final NoAuthTwilioRestClient client) { ); } - private void addQueryParams(final NoAuthRequest request) { + private void addQueryParams(final Request request) { if (responseType != null) { request.addQueryParam("ResponseType", responseType); } diff --git a/src/main/java/com/twilio/rest/oauth/v1/Token.java b/src/main/java/com/twilio/rest/oauth/v1/Token.java index ece191a8d8..0914298465 100644 --- a/src/main/java/com/twilio/rest/oauth/v1/Token.java +++ b/src/main/java/com/twilio/rest/oauth/v1/Token.java @@ -20,7 +20,7 @@ import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; -import com.twilio.base.noauth.Resource; +import com.twilio.base.Resource; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import java.io.IOException; diff --git a/src/main/java/com/twilio/rest/oauth/v1/TokenCreator.java b/src/main/java/com/twilio/rest/oauth/v1/TokenCreator.java index b6321d16e3..edc3882649 100644 --- a/src/main/java/com/twilio/rest/oauth/v1/TokenCreator.java +++ b/src/main/java/com/twilio/rest/oauth/v1/TokenCreator.java @@ -14,15 +14,16 @@ package com.twilio.rest.oauth.v1; -import com.twilio.base.noauth.Creator; +import com.twilio.auth_strategy.NoAuthStrategy; +import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; import com.twilio.http.HttpMethod; import com.twilio.http.Response; -import com.twilio.http.noauth.NoAuthRequest; -import com.twilio.http.noauth.NoAuthTwilioRestClient; +import com.twilio.http.TwilioRestClient; +import com.twilio.http.Request; import com.twilio.rest.Domains; public class TokenCreator extends Creator { @@ -82,18 +83,19 @@ public TokenCreator setScope(final String scope) { } @Override - public Token create(final NoAuthTwilioRestClient client) { + public Token create(final TwilioRestClient client) { String path = "/v1/token"; path = path.replace("{" + "GrantType" + "}", this.grantType.toString()); path = path.replace("{" + "ClientId" + "}", this.clientId.toString()); - NoAuthRequest request = new NoAuthRequest( + Request request = new Request( HttpMethod.POST, Domains.OAUTH.toString(), path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + request.setAuth(NoAuthStrategy.getInstance()); addPostParams(request); Response response = client.request(request); if (response == null) { @@ -101,7 +103,7 @@ public Token create(final NoAuthTwilioRestClient client) { "Token creation failed: Unable to connect to server" ); } else if ( - !NoAuthTwilioRestClient.SUCCESS.test(response.getStatusCode()) + !TwilioRestClient.SUCCESS.test(response.getStatusCode()) ) { RestException restException = RestException.fromJson( response.getStream(), @@ -119,7 +121,7 @@ public Token create(final NoAuthTwilioRestClient client) { return Token.fromJson(response.getStream(), client.getObjectMapper()); } - private void addPostParams(final NoAuthRequest request) { + private void addPostParams(final Request request) { if (grantType != null) { request.addPostParam("GrantType", grantType); } diff --git a/src/main/java/com/twilio/rest/previewiam/v1/Authorize.java b/src/main/java/com/twilio/rest/previewiam/v1/Authorize.java index 3ac5cada23..7c41e281bc 100644 --- a/src/main/java/com/twilio/rest/previewiam/v1/Authorize.java +++ b/src/main/java/com/twilio/rest/previewiam/v1/Authorize.java @@ -20,7 +20,7 @@ import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; -import com.twilio.base.noauth.Resource; +import com.twilio.base.Resource; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import java.io.IOException; diff --git a/src/main/java/com/twilio/rest/previewiam/v1/AuthorizeFetcher.java b/src/main/java/com/twilio/rest/previewiam/v1/AuthorizeFetcher.java index 66d1fe0e88..ff85651635 100644 --- a/src/main/java/com/twilio/rest/previewiam/v1/AuthorizeFetcher.java +++ b/src/main/java/com/twilio/rest/previewiam/v1/AuthorizeFetcher.java @@ -14,15 +14,16 @@ package com.twilio.rest.previewiam.v1; -import com.twilio.base.noauth.Fetcher; +import com.twilio.auth_strategy.NoAuthStrategy; +import com.twilio.base.Fetcher; import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; import com.twilio.http.HttpMethod; import com.twilio.http.Response; -import com.twilio.http.noauth.NoAuthRequest; -import com.twilio.http.noauth.NoAuthTwilioRestClient; +import com.twilio.http.TwilioRestClient; +import com.twilio.http.Request; import com.twilio.rest.Domains; public class AuthorizeFetcher extends Fetcher { @@ -61,16 +62,17 @@ public AuthorizeFetcher setState(final String state) { } @Override - public Authorize fetch(final NoAuthTwilioRestClient client) { + public Authorize fetch(final TwilioRestClient client) { String path = "/v1/authorize"; - NoAuthRequest request = new NoAuthRequest( + Request request = new Request( HttpMethod.GET, Domains.PREVIEWIAM.toString(), path ); addQueryParams(request); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + request.setAuth(NoAuthStrategy.getInstance()); Response response = client.request(request); if (response == null) { @@ -78,7 +80,7 @@ public Authorize fetch(final NoAuthTwilioRestClient client) { "Authorize fetch failed: Unable to connect to server" ); } else if ( - !NoAuthTwilioRestClient.SUCCESS.test(response.getStatusCode()) + !TwilioRestClient.SUCCESS.test(response.getStatusCode()) ) { RestException restException = RestException.fromJson( response.getStream(), @@ -99,7 +101,7 @@ public Authorize fetch(final NoAuthTwilioRestClient client) { ); } - private void addQueryParams(final NoAuthRequest request) { + private void addQueryParams(final Request request) { if (responseType != null) { request.addQueryParam("response_type", responseType); } diff --git a/src/main/java/com/twilio/rest/previewiam/v1/Token.java b/src/main/java/com/twilio/rest/previewiam/v1/Token.java index ca25985b40..99349efcdc 100644 --- a/src/main/java/com/twilio/rest/previewiam/v1/Token.java +++ b/src/main/java/com/twilio/rest/previewiam/v1/Token.java @@ -20,7 +20,7 @@ import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; -import com.twilio.base.noauth.Resource; +import com.twilio.base.Resource; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import java.io.IOException; diff --git a/src/main/java/com/twilio/rest/previewiam/v1/TokenCreator.java b/src/main/java/com/twilio/rest/previewiam/v1/TokenCreator.java index 68ff95c296..74e8715b2c 100644 --- a/src/main/java/com/twilio/rest/previewiam/v1/TokenCreator.java +++ b/src/main/java/com/twilio/rest/previewiam/v1/TokenCreator.java @@ -14,15 +14,18 @@ package com.twilio.rest.previewiam.v1; -import com.twilio.base.noauth.Creator; +import com.twilio.auth_strategy.NoAuthStrategy; +import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; import com.twilio.http.HttpMethod; import com.twilio.http.Response; -import com.twilio.http.noauth.NoAuthRequest; -import com.twilio.http.noauth.NoAuthTwilioRestClient; +import com.twilio.http.TwilioRestClient; +import com.twilio.http.Request; +import com.twilio.http.TwilioRestClient; +import com.twilio.http.Request; import com.twilio.rest.Domains; public class TokenCreator extends Creator { @@ -82,19 +85,20 @@ public TokenCreator setScope(final String scope) { } @Override - public Token create(final NoAuthTwilioRestClient client) { + public Token create(final TwilioRestClient client) { String path = "/v1/token"; path = path.replace("{" + "grant_type" + "}", this.grantType.toString()); path = path.replace("{" + "client_id" + "}", this.clientId.toString()); - NoAuthRequest request = new NoAuthRequest( + Request request = new Request( HttpMethod.POST, Domains.PREVIEWIAM.toString(), path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + request.setAuth(NoAuthStrategy.getInstance()); addPostParams(request); Response response = client.request(request); if (response == null) { @@ -102,7 +106,7 @@ public Token create(final NoAuthTwilioRestClient client) { "Token creation failed: Unable to connect to server" ); } else if ( - !NoAuthTwilioRestClient.SUCCESS.test(response.getStatusCode()) + !TwilioRestClient.SUCCESS.test(response.getStatusCode()) ) { RestException restException = RestException.fromJson( response.getStream(), @@ -120,7 +124,7 @@ public Token create(final NoAuthTwilioRestClient client) { return Token.fromJson(response.getStream(), client.getObjectMapper()); } - private void addPostParams(final NoAuthRequest request) { + private void addPostParams(final Request request) { if (grantType != null) { request.addPostParam("grant_type", grantType); } diff --git a/src/test/java/com/twilio/http/TwilioRestClientTest.java b/src/test/java/com/twilio/http/TwilioRestClientTest.java index 05cbcd389b..16baf5faeb 100644 --- a/src/test/java/com/twilio/http/TwilioRestClientTest.java +++ b/src/test/java/com/twilio/http/TwilioRestClientTest.java @@ -8,6 +8,8 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; +import com.twilio.auth_strategy.BasicAuthStrategy; +import com.twilio.auth_strategy.NoAuthStrategy; import com.twilio.rest.Domains; import java.util.Arrays; import java.util.Collections; @@ -123,4 +125,40 @@ public void testRequestWithExtensionNull() { twilioRestClientExtension.request(request); assertNull(request.getUserAgentExtensions()); } + + @Test + public void testRequestWithNoAuthStrategy() { + Request request = new Request( + HttpMethod.GET, + Domains.API.toString(), + URI + ); + request.setAuth(NoAuthStrategy.getInstance()); + twilioRestClientExtension = new TwilioRestClient.Builder(USER_NAME, TOKEN) + .userAgentExtensions(Collections.emptyList()) + .httpClient(httpClient) + .build(); + twilioRestClientExtension.request(request); + assertNull(twilioRestClientExtension.getAuthStrategy()); + // AuthStrategy of Request not changing by TwilioRestClient + assertEquals(NoAuthStrategy.getInstance(), request.getAuthStrategy()); + } + + @Test + public void testRequestWithNoAuthStrategyWithAuthStrategy() { + Request request = new Request( + HttpMethod.GET, + Domains.API.toString(), + URI + ); + request.setAuth(NoAuthStrategy.getInstance()); + twilioRestClientExtension = new TwilioRestClient.Builder(new BasicAuthStrategy(USER_NAME, TOKEN)) + .userAgentExtensions(Collections.emptyList()) + .httpClient(httpClient) + .build(); + twilioRestClientExtension.request(request); + assertNotNull(twilioRestClientExtension.getAuthStrategy()); + // AuthStrategy of Request not changing by TwilioRestClient + assertEquals(NoAuthStrategy.getInstance(), request.getAuthStrategy()); + } } diff --git a/src/test/java/com/twilio/http/noauth/NoAuthNetworkHttpClientTest.java b/src/test/java/com/twilio/http/noauth/NoAuthNetworkHttpClientTest.java deleted file mode 100644 index 5007a8cb31..0000000000 --- a/src/test/java/com/twilio/http/noauth/NoAuthNetworkHttpClientTest.java +++ /dev/null @@ -1,162 +0,0 @@ -package com.twilio.http.noauth; - -import com.twilio.constant.EnumConstants; -import com.twilio.exception.ApiException; -import com.twilio.http.HttpMethod; -import com.twilio.http.Response; -import org.apache.hc.client5.http.config.RequestConfig; -import org.apache.hc.client5.http.impl.classic.CloseableHttpClient; -import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse; -import org.apache.hc.client5.http.impl.classic.HttpClientBuilder; -import org.apache.hc.core5.http.HttpEntity; -import org.apache.hc.core5.http.io.SocketConfig; -import org.apache.hc.core5.util.Timeout; -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.mockito.Spy; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.net.URL; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -public class NoAuthNetworkHttpClientTest { - - private NoAuthNetworkHttpClient client; - - @Mock - private NoAuthRequest mockRequest; - - @Spy - private HttpClientBuilder mockBuilder; - - @Mock - private CloseableHttpClient mockClient; - - @Mock - private CloseableHttpResponse mockResponse; - - @Mock - private HttpEntity mockEntity; - - @Before - public void setUp() { - MockitoAnnotations.openMocks(this); - doReturn(mockClient).when(mockBuilder).build(); - client = new NoAuthNetworkHttpClient(); - } - - private void setup( - final int statusCode, - final String content, - final HttpMethod method - ) throws IOException { - final InputStream stream = new ByteArrayInputStream(content.getBytes("UTF-8")); - - when(mockRequest.getMethod()).thenReturn(method); - when(mockRequest.constructURL()).thenReturn(new URL("http://foo.com/hello")); - when(mockRequest.getContentType()).thenReturn(EnumConstants.ContentType.FORM_URLENCODED); - when(mockClient.execute(any())).thenReturn(mockResponse); - when(mockEntity.isRepeatable()).thenReturn(true); - when(mockEntity.getContentLength()).thenReturn(1L); - when(mockEntity.getContent()).thenReturn(stream); - when(mockResponse.getEntity()).thenReturn(mockEntity); - when(mockResponse.getCode()).thenReturn(statusCode); - } - - - @Test - public void testReliableRequest() { - NoAuthRequest request = mock(NoAuthRequest.class); - when(request.getMethod()).thenReturn(HttpMethod.GET); - - NoAuthNetworkHttpClient clientSpy = spy(client); - doReturn(new Response("", 204)).when(clientSpy).makeRequest(request); - - clientSpy.reliableRequest(request); - - assertNotNull(clientSpy.getLastRequest()); - assertNotNull(clientSpy.getLastResponse()); - } - - @Test - public void testShouldRetry() { - Response resp = new Response("error", 500); - boolean shouldRetry = client.shouldRetry(resp, new int[]{500}); - assertEquals(true, shouldRetry); - - resp = new Response("success", 200); - shouldRetry = client.shouldRetry(resp, new int[]{500}); - assertEquals(false, shouldRetry); - - shouldRetry = client.shouldRetry(null, new int[]{500}); - assertEquals(true, shouldRetry); - } - - @Test - public void testDefaultConstructor() throws IOException { - // Create client using default constructor - NoAuthNetworkHttpClient defaultClient = new NoAuthNetworkHttpClient(); - - // Setup mock NoAuthRequest - NoAuthRequest request = mock(NoAuthRequest.class); - when(request.getMethod()).thenReturn(HttpMethod.GET); - when(request.constructURL()).thenReturn(new URL("http://example.com")); - when(request.getHeaderParams()).thenReturn(new HashMap<>()); - - // This test verifies that the default constructor creates a functional client - // We can't directly test the internals, but we can verify the client was constructed - // without exceptions and has the expected type - assertNotNull(defaultClient); - assertEquals(NoAuthNetworkHttpClient.class, defaultClient.getClass()); - } - - @Test - public void testRequestConfigConstructor() { - // Create a custom RequestConfig - RequestConfig customConfig = RequestConfig.custom() - .setConnectTimeout(Timeout.ofMilliseconds(5000)) - .build(); - - // Create client with custom RequestConfig - NoAuthNetworkHttpClient configClient = new NoAuthNetworkHttpClient(customConfig); - - // Verify client was created successfully - assertNotNull(configClient); - assertEquals(NoAuthNetworkHttpClient.class, configClient.getClass()); - } - - @Test - public void testRequestAndSocketConfigConstructor() { - // Create custom configs - RequestConfig customRequestConfig = RequestConfig.custom() - .setConnectTimeout(Timeout.ofMilliseconds(5000)) - .build(); - - SocketConfig customSocketConfig = SocketConfig.custom() - .setSoTimeout(Timeout.ofMilliseconds(5000)) - .build(); - - // Create client with both custom configs - NoAuthNetworkHttpClient fullConfigClient = new NoAuthNetworkHttpClient(customRequestConfig, customSocketConfig); - - // Verify client was created successfully - assertNotNull(fullConfigClient); - assertEquals(NoAuthNetworkHttpClient.class, fullConfigClient.getClass()); - } -} From 8fdf86bf7cfab5e9525a499b639f5594e0332413 Mon Sep 17 00:00:00 2001 From: Manisha Singh Date: Thu, 18 Sep 2025 18:18:19 +0530 Subject: [PATCH 24/32] chore: Add comprehensive test cases for RequestValidator to improve coverage and debugging #902 (#904) --- .../twilio/security/RequestValidatorTest.java | 176 ++++++++++++++++++ 1 file changed, 176 insertions(+) diff --git a/src/test/java/com/twilio/security/RequestValidatorTest.java b/src/test/java/com/twilio/security/RequestValidatorTest.java index d44712178c..af2d13ef81 100644 --- a/src/test/java/com/twilio/security/RequestValidatorTest.java +++ b/src/test/java/com/twilio/security/RequestValidatorTest.java @@ -114,4 +114,180 @@ public void testValidateAddsPortHttp() { Assert.assertTrue("Validator did not add port 80 to http url", isValid); } + + @Test + public void testValidateWithEmptyParams() { + // Test with no form parameters - empty map + Map emptyParams = new HashMap<>(); + String expectedSignature = "zYQTYrRWXE7LtzbG4PfP7/bkkGo="; // hash of URL only + boolean isValid = validator.validate(url, emptyParams, expectedSignature); + + Assert.assertTrue("Validation should succeed with empty parameters", isValid); + } + + @Test + public void testValidateWithNullParams() { + // Test with null parameters + String expectedSignature = "zYQTYrRWXE7LtzbG4PfP7/bkkGo="; // hash of URL only + boolean isValid = validator.validate(url, (Map) null, expectedSignature); + + Assert.assertTrue("Validation should succeed with null parameters", isValid); + } + + @Test + public void testValidateWithNoQueryParams() { + // Test with URL that has no query parameters + String urlNoQuery = "https://mycompany.com/myapp.php"; + String expectedSignature = "1xaxFBvyzXYvWplzNOSs28HWO94="; + boolean isValid = validator.validate(urlNoQuery, params, expectedSignature); + + Assert.assertTrue("Validation should succeed with URL without query parameters", isValid); + } + + @Test + public void testValidateIgnoresNonTwilioQueryParams() { + // Test that non-Twilio query parameters in the URL are included in signature generation + // (they are NOT ignored - they're part of the URL that gets signed) + String urlWithExtraParams = "https://mycompany.com/myapp.php?foo=1&bar=2&type=thiswontbeusedinthesignaturegeneratorandsoshouldbeignored"; + String expectedSignature = "hYkNsTBttoNGkyCS0p+wWmQoRTg="; + boolean isValid = validator.validate(urlWithExtraParams, params, expectedSignature); + + Assert.assertTrue("Validation should succeed - query params are part of URL signature", isValid); + } + + @Test + public void testValidateWithUrlEncodedQueryParams() { + // Test with URL encoded query parameters + String urlEncoded = "https://mycompany.com/myapp.php?foo=hello%20world&bar=test%2Bvalue"; + String expectedSignature = "er2tvAP1Wx+iuTTE2BPgvEaN1cs="; + boolean isValid = validator.validate(urlEncoded, params, expectedSignature); + + Assert.assertTrue("Validation should succeed with URL encoded query parameters", isValid); + } + + @Test + public void testValidateWithSpecialCharactersInParams() { + // Test with special characters in parameter values + Map specialParams = new HashMap<>(); + specialParams.put("Message", "Hello & goodbye! @#$%^*()"); + specialParams.put("From", "+1 (415) 867-5309"); + specialParams.put("Special", "unicode: ñáéíóú"); + + String expectedSignature = "dCPiR4WtQ6QFN6pJh81CtlCcWLQ="; + boolean isValid = validator.validate(url, specialParams, expectedSignature); + + Assert.assertTrue("Validation should succeed with special characters in parameters", isValid); + } + + @Test + public void testValidateWithEmptyParameterValues() { + // Test with empty string parameter values + Map emptyValueParams = new HashMap<>(); + emptyValueParams.put("Digits", ""); + emptyValueParams.put("CallSid", "CA1234567890ABCDE"); + emptyValueParams.put("EmptyParam", ""); + + String expectedSignature = "9HHp/OqQMEwdrVebHDdA/+tqjX8="; + boolean isValid = validator.validate(url, emptyValueParams, expectedSignature); + + Assert.assertTrue("Validation should succeed with empty parameter values", isValid); + } + + @Test + public void testValidateWithNullParameterValues() { + // Test with null parameter values (treated as empty strings) + Map nullValueParams = new HashMap<>(); + nullValueParams.put("Digits", null); + nullValueParams.put("CallSid", "CA1234567890ABCDE"); + nullValueParams.put("NullParam", null); + + String expectedSignature = "L9lTTwIlxM1xGAtLRwhOSZggRhM="; + boolean isValid = validator.validate(url, nullValueParams, expectedSignature); + + Assert.assertTrue("Validation should succeed with null parameter values", isValid); + } + + @Test + public void testValidateParameterKeySorting() { + // Test that parameter keys are properly sorted alphabetically + Map unsortedParams = new HashMap<>(); + unsortedParams.put("Zebra", "last"); + unsortedParams.put("Alpha", "first"); + unsortedParams.put("Beta", "second"); + unsortedParams.put("Gamma", "third"); + + String expectedSignature = "enveUe73ZTVLAekHxez3Qx6JuuQ="; + boolean isValid = validator.validate(url, unsortedParams, expectedSignature); + + Assert.assertTrue("Validation should succeed with alphabetically sorted parameters", isValid); + } + + @Test + public void testValidateWithInternationalCharactersInUrl() { + // Test with international characters in URL + String intlUrl = "https://mycompany.com/webhook/España?año=2023"; + String expectedSignature = "G/Hx6mqqnjUNlPAoi2Sp9bGst0g="; + boolean isValid = validator.validate(intlUrl, params, expectedSignature); + + Assert.assertTrue("Validation should succeed with international characters in URL", isValid); + } + + @Test + public void testValidateWithCaseSensitiveParameterKeys() { + // Test that parameter keys are case sensitive + Map caseParams = new HashMap<>(); + caseParams.put("callSid", "lowercase"); + caseParams.put("CallSid", "uppercase"); // Different from callSid + caseParams.put("CALLSID", "allcaps"); + + String expectedSignature = "jDK7WKT8wiNrwggd4ceTv4e1MJ4="; + boolean isValid = validator.validate(url, caseParams, expectedSignature); + + Assert.assertTrue("Validation should succeed with case-sensitive parameter keys", isValid); + } + + @Test + public void testValidateWithMalformedUrlStillWorks() { + // Test that validation handles URLs gracefully even with unusual formatting + String malformedUrl = "https://mycompany.com:443//myapp.php?foo=1&bar=2"; + String expectedSignature = "A9lH3u16NjyiiM/+wylw5rirFUs="; // Signature for the malformed URL as-is + boolean isValid = validator.validate(malformedUrl, params, expectedSignature); + + Assert.assertTrue("Validation should handle malformed URLs gracefully", isValid); + } + + @Test + public void testValidateWithDifferentProtocols() { + // Test validation with different protocols + String httpUrl = url.replace("https", "http"); + String expectedSignature = "0ZXoZLH/DfblKGATFgpif+LLRf4="; + boolean isValid = validator.validate(httpUrl, params, expectedSignature); + + Assert.assertTrue("Validation should work with HTTP protocol", isValid); + } + + @Test + public void testValidateFailsWithWrongSignature() { + // Test that validation properly fails with incorrect signature + String wrongSignature = "IncorrectSignatureValue123="; + boolean isValid = validator.validate(url, params, wrongSignature); + + Assert.assertFalse("Validation should fail with incorrect signature", isValid); + } + + @Test + public void testValidateFailsWithNullSignature() { + // Test that validation properly fails with null signature + boolean isValid = validator.validate(url, params, null); + + Assert.assertFalse("Validation should fail with null signature", isValid); + } + + @Test + public void testValidateFailsWithEmptySignature() { + // Test that validation properly fails with empty signature + boolean isValid = validator.validate(url, params, ""); + Assert.assertFalse("Validation should fail with empty signature", isValid); + } + } From b7718a2e1837c95438ca73b2db744835bb9f2378 Mon Sep 17 00:00:00 2001 From: sbansla Date: Thu, 18 Sep 2025 19:51:55 +0530 Subject: [PATCH 25/32] [Librarian] Regenerated @ 556cffc21d7318f27d71e40146d324df61aba54f 0d6654ebfab8c5a41c8454374cbb1c93d806bfae --- .../rest/accounts/v1/AuthTokenPromotion.java | 106 +- .../v1/AuthTokenPromotionUpdater.java | 34 +- .../twilio/rest/accounts/v1/BulkConsents.java | 62 +- .../rest/accounts/v1/BulkConsentsCreator.java | 43 +- .../twilio/rest/accounts/v1/BulkContacts.java | 62 +- .../rest/accounts/v1/BulkContactsCreator.java | 43 +- .../com/twilio/rest/accounts/v1/Safelist.java | 80 +- .../rest/accounts/v1/SafelistCreator.java | 42 +- .../rest/accounts/v1/SafelistDeleter.java | 37 +- .../rest/accounts/v1/SafelistFetcher.java | 43 +- .../rest/accounts/v1/SecondaryAuthToken.java | 111 +- .../v1/SecondaryAuthTokenCreator.java | 36 +- .../v1/SecondaryAuthTokenDeleter.java | 29 +- .../rest/accounts/v1/credential/Aws.java | 149 +- .../accounts/v1/credential/AwsCreator.java | 47 +- .../accounts/v1/credential/AwsDeleter.java | 33 +- .../accounts/v1/credential/AwsFetcher.java | 34 +- .../accounts/v1/credential/AwsReader.java | 83 +- .../accounts/v1/credential/AwsUpdater.java | 41 +- .../accounts/v1/credential/PublicKey.java | 149 +- .../v1/credential/PublicKeyCreator.java | 48 +- .../v1/credential/PublicKeyDeleter.java | 33 +- .../v1/credential/PublicKeyFetcher.java | 39 +- .../v1/credential/PublicKeyReader.java | 83 +- .../v1/credential/PublicKeyUpdater.java | 46 +- .../com/twilio/rest/api/v2010/Account.java | 273 ++-- .../twilio/rest/api/v2010/AccountCreator.java | 36 +- .../twilio/rest/api/v2010/AccountFetcher.java | 40 +- .../twilio/rest/api/v2010/AccountReader.java | 93 +- .../twilio/rest/api/v2010/AccountUpdater.java | 52 +- .../rest/api/v2010/account/Address.java | 329 ++--- .../api/v2010/account/AddressCreator.java | 134 +- .../api/v2010/account/AddressDeleter.java | 52 +- .../api/v2010/account/AddressFetcher.java | 53 +- .../rest/api/v2010/account/AddressReader.java | 123 +- .../api/v2010/account/AddressUpdater.java | 110 +- .../rest/api/v2010/account/Application.java | 372 +++-- .../api/v2010/account/ApplicationCreator.java | 210 ++- .../api/v2010/account/ApplicationDeleter.java | 58 +- .../api/v2010/account/ApplicationFetcher.java | 64 +- .../api/v2010/account/ApplicationReader.java | 105 +- .../api/v2010/account/ApplicationUpdater.java | 224 ++- .../v2010/account/AuthorizedConnectApp.java | 279 ++-- .../account/AuthorizedConnectAppFetcher.java | 68 +- .../account/AuthorizedConnectAppReader.java | 107 +- .../account/AvailablePhoneNumberCountry.java | 149 +- .../AvailablePhoneNumberCountryFetcher.java | 71 +- .../AvailablePhoneNumberCountryReader.java | 114 +- .../rest/api/v2010/account/Balance.java | 83 +- .../api/v2010/account/BalanceFetcher.java | 46 +- .../twilio/rest/api/v2010/account/Call.java | 626 ++++---- .../rest/api/v2010/account/CallCreator.java | 379 +++-- .../rest/api/v2010/account/CallDeleter.java | 52 +- .../rest/api/v2010/account/CallFetcher.java | 53 +- .../rest/api/v2010/account/CallReader.java | 180 ++- .../rest/api/v2010/account/CallUpdater.java | 118 +- .../rest/api/v2010/account/Conference.java | 382 +++-- .../api/v2010/account/ConferenceFetcher.java | 64 +- .../api/v2010/account/ConferenceReader.java | 188 ++- .../api/v2010/account/ConferenceUpdater.java | 91 +- .../rest/api/v2010/account/ConnectApp.java | 373 +++-- .../api/v2010/account/ConnectAppDeleter.java | 58 +- .../api/v2010/account/ConnectAppFetcher.java | 64 +- .../api/v2010/account/ConnectAppReader.java | 100 +- .../api/v2010/account/ConnectAppUpdater.java | 152 +- .../v2010/account/IncomingPhoneNumber.java | 744 +++++----- .../account/IncomingPhoneNumberCreator.java | 284 ++-- .../account/IncomingPhoneNumberDeleter.java | 58 +- .../account/IncomingPhoneNumberFetcher.java | 64 +- .../account/IncomingPhoneNumberReader.java | 134 +- .../account/IncomingPhoneNumberUpdater.java | 275 ++-- .../twilio/rest/api/v2010/account/Key.java | 158 +- .../rest/api/v2010/account/KeyDeleter.java | 52 +- .../rest/api/v2010/account/KeyFetcher.java | 53 +- .../rest/api/v2010/account/KeyReader.java | 100 +- .../rest/api/v2010/account/KeyUpdater.java | 60 +- .../rest/api/v2010/account/Message.java | 692 ++++----- .../api/v2010/account/MessageCreator.java | 262 ++-- .../api/v2010/account/MessageDeleter.java | 52 +- .../api/v2010/account/MessageFetcher.java | 53 +- .../rest/api/v2010/account/MessageReader.java | 140 +- .../api/v2010/account/MessageUpdater.java | 65 +- .../twilio/rest/api/v2010/account/NewKey.java | 119 +- .../rest/api/v2010/account/NewKeyCreator.java | 53 +- .../rest/api/v2010/account/NewSigningKey.java | 119 +- .../v2010/account/NewSigningKeyCreator.java | 58 +- .../rest/api/v2010/account/Notification.java | 265 ++-- .../v2010/account/NotificationFetcher.java | 64 +- .../api/v2010/account/NotificationReader.java | 145 +- .../api/v2010/account/OutgoingCallerId.java | 196 +-- .../account/OutgoingCallerIdDeleter.java | 58 +- .../account/OutgoingCallerIdFetcher.java | 64 +- .../v2010/account/OutgoingCallerIdReader.java | 116 +- .../account/OutgoingCallerIdUpdater.java | 73 +- .../twilio/rest/api/v2010/account/Queue.java | 241 +-- .../rest/api/v2010/account/QueueCreator.java | 63 +- .../rest/api/v2010/account/QueueDeleter.java | 52 +- .../rest/api/v2010/account/QueueFetcher.java | 53 +- .../rest/api/v2010/account/QueueReader.java | 100 +- .../rest/api/v2010/account/QueueUpdater.java | 65 +- .../rest/api/v2010/account/Recording.java | 438 +++--- .../api/v2010/account/RecordingDeleter.java | 52 +- .../api/v2010/account/RecordingFetcher.java | 74 +- .../api/v2010/account/RecordingReader.java | 162 +-- .../rest/api/v2010/account/ShortCode.java | 224 ++- .../api/v2010/account/ShortCodeFetcher.java | 61 +- .../api/v2010/account/ShortCodeReader.java | 110 +- .../api/v2010/account/ShortCodeUpdater.java | 108 +- .../rest/api/v2010/account/SigningKey.java | 158 +- .../api/v2010/account/SigningKeyDeleter.java | 58 +- .../api/v2010/account/SigningKeyFetcher.java | 64 +- .../api/v2010/account/SigningKeyReader.java | 100 +- .../api/v2010/account/SigningKeyUpdater.java | 73 +- .../twilio/rest/api/v2010/account/Token.java | 135 +- .../rest/api/v2010/account/TokenCreator.java | 53 +- .../rest/api/v2010/account/Transcription.java | 277 ++-- .../v2010/account/TranscriptionDeleter.java | 58 +- .../v2010/account/TranscriptionFetcher.java | 64 +- .../v2010/account/TranscriptionReader.java | 100 +- .../api/v2010/account/ValidationRequest.java | 114 +- .../account/ValidationRequestCreator.java | 117 +- .../account/address/DependentPhoneNumber.java | 502 +++---- .../address/DependentPhoneNumberReader.java | 121 +- .../availablephonenumbercountry/Local.java | 234 ++- .../LocalReader.java | 231 ++- .../MachineToMachine.java | 234 ++- .../MachineToMachineReader.java | 231 ++- .../availablephonenumbercountry/Mobile.java | 234 ++- .../MobileReader.java | 231 ++- .../availablephonenumbercountry/National.java | 234 ++- .../NationalReader.java | 231 ++- .../SharedCost.java | 234 ++- .../SharedCostReader.java | 231 ++- .../availablephonenumbercountry/TollFree.java | 234 ++- .../TollFreeReader.java | 231 ++- .../availablephonenumbercountry/Voip.java | 234 ++- .../VoipReader.java | 231 ++- .../rest/api/v2010/account/call/Event.java | 84 +- .../api/v2010/account/call/EventReader.java | 110 +- .../api/v2010/account/call/Notification.java | 274 ++-- .../account/call/NotificationFetcher.java | 73 +- .../account/call/NotificationReader.java | 158 +- .../rest/api/v2010/account/call/Payment.java | 335 ++--- .../v2010/account/call/PaymentCreator.java | 185 +-- .../v2010/account/call/PaymentUpdater.java | 113 +- .../api/v2010/account/call/Recording.java | 476 +++--- .../v2010/account/call/RecordingCreator.java | 139 +- .../v2010/account/call/RecordingDeleter.java | 67 +- .../v2010/account/call/RecordingFetcher.java | 73 +- .../v2010/account/call/RecordingReader.java | 153 +- .../v2010/account/call/RecordingUpdater.java | 93 +- .../rest/api/v2010/account/call/Siprec.java | 283 ++-- .../api/v2010/account/call/SiprecCreator.java | 1090 ++++++++++---- .../api/v2010/account/call/SiprecUpdater.java | 85 +- .../rest/api/v2010/account/call/Stream.java | 287 ++-- .../api/v2010/account/call/StreamCreator.java | 1094 ++++++++++---- .../api/v2010/account/call/StreamUpdater.java | 85 +- .../api/v2010/account/call/Transcription.java | 284 ++-- .../account/call/TranscriptionCreator.java | 190 ++- .../account/call/TranscriptionUpdater.java | 94 +- .../account/call/UserDefinedMessage.java | 109 +- .../call/UserDefinedMessageCreator.java | 87 +- .../call/UserDefinedMessageSubscription.java | 153 +- ...UserDefinedMessageSubscriptionCreator.java | 114 +- ...UserDefinedMessageSubscriptionDeleter.java | 73 +- .../v2010/account/conference/Participant.java | 380 +++-- .../conference/ParticipantCreator.java | 546 ++++--- .../conference/ParticipantDeleter.java | 74 +- .../conference/ParticipantFetcher.java | 80 +- .../account/conference/ParticipantReader.java | 132 +- .../conference/ParticipantUpdater.java | 163 +-- .../v2010/account/conference/Recording.java | 444 +++--- .../account/conference/RecordingDeleter.java | 74 +- .../account/conference/RecordingFetcher.java | 80 +- .../account/conference/RecordingReader.java | 157 +- .../account/conference/RecordingUpdater.java | 97 +- .../incomingphonenumber/AssignedAddOn.java | 275 ++-- .../AssignedAddOnCreator.java | 90 +- .../AssignedAddOnDeleter.java | 74 +- .../AssignedAddOnFetcher.java | 80 +- .../AssignedAddOnReader.java | 117 +- .../account/incomingphonenumber/Local.java | 676 ++++----- .../incomingphonenumber/LocalCreator.java | 238 +-- .../incomingphonenumber/LocalReader.java | 126 +- .../account/incomingphonenumber/Mobile.java | 676 ++++----- .../incomingphonenumber/MobileCreator.java | 238 +-- .../incomingphonenumber/MobileReader.java | 126 +- .../account/incomingphonenumber/TollFree.java | 676 ++++----- .../incomingphonenumber/TollFreeCreator.java | 247 ++-- .../incomingphonenumber/TollFreeReader.java | 126 +- .../assignedaddon/AssignedAddOnExtension.java | 193 +-- .../AssignedAddOnExtensionFetcher.java | 97 +- .../AssignedAddOnExtensionReader.java | 144 +- .../api/v2010/account/message/Feedback.java | 170 ++- .../account/message/FeedbackCreator.java | 77 +- .../rest/api/v2010/account/message/Media.java | 182 ++- .../v2010/account/message/MediaDeleter.java | 71 +- .../v2010/account/message/MediaFetcher.java | 72 +- .../v2010/account/message/MediaReader.java | 157 +- .../rest/api/v2010/account/queue/Member.java | 176 ++- .../v2010/account/queue/MemberFetcher.java | 69 +- .../api/v2010/account/queue/MemberReader.java | 114 +- .../v2010/account/queue/MemberUpdater.java | 93 +- .../v2010/account/recording/AddOnResult.java | 291 ++-- .../account/recording/AddOnResultDeleter.java | 74 +- .../account/recording/AddOnResultFetcher.java | 80 +- .../account/recording/AddOnResultReader.java | 117 +- .../account/recording/Transcription.java | 290 ++-- .../recording/TranscriptionDeleter.java | 74 +- .../recording/TranscriptionFetcher.java | 80 +- .../recording/TranscriptionReader.java | 117 +- .../recording/addonresult/Payload.java | 261 ++-- .../recording/addonresult/PayloadDeleter.java | 88 +- .../recording/addonresult/PayloadFetcher.java | 89 +- .../recording/addonresult/PayloadReader.java | 133 +- .../recording/addonresult/payload/Data.java | 79 +- .../addonresult/payload/DataFetcher.java | 93 +- .../api/v2010/account/sip/CredentialList.java | 209 +-- .../account/sip/CredentialListCreator.java | 68 +- .../account/sip/CredentialListDeleter.java | 58 +- .../account/sip/CredentialListFetcher.java | 64 +- .../account/sip/CredentialListReader.java | 103 +- .../account/sip/CredentialListUpdater.java | 82 +- .../rest/api/v2010/account/sip/Domain.java | 400 +++-- .../api/v2010/account/sip/DomainCreator.java | 160 +- .../api/v2010/account/sip/DomainDeleter.java | 55 +- .../api/v2010/account/sip/DomainFetcher.java | 56 +- .../api/v2010/account/sip/DomainReader.java | 100 +- .../api/v2010/account/sip/DomainUpdater.java | 172 ++- .../account/sip/IpAccessControlList.java | 221 ++- .../sip/IpAccessControlListCreator.java | 72 +- .../sip/IpAccessControlListDeleter.java | 58 +- .../sip/IpAccessControlListFetcher.java | 64 +- .../sip/IpAccessControlListReader.java | 107 +- .../sip/IpAccessControlListUpdater.java | 86 +- .../sip/credentiallist/Credential.java | 235 ++- .../sip/credentiallist/CredentialCreator.java | 92 +- .../sip/credentiallist/CredentialDeleter.java | 74 +- .../sip/credentiallist/CredentialFetcher.java | 80 +- .../sip/credentiallist/CredentialReader.java | 117 +- .../sip/credentiallist/CredentialUpdater.java | 89 +- .../sip/domain/CredentialListMapping.java | 204 ++- .../domain/CredentialListMappingCreator.java | 93 +- .../domain/CredentialListMappingDeleter.java | 77 +- .../domain/CredentialListMappingFetcher.java | 83 +- .../domain/CredentialListMappingReader.java | 125 +- .../domain/IpAccessControlListMapping.java | 213 ++- .../IpAccessControlListMappingCreator.java | 96 +- .../IpAccessControlListMappingDeleter.java | 77 +- .../IpAccessControlListMappingFetcher.java | 83 +- .../IpAccessControlListMappingReader.java | 128 +- .../AuthCallsCredentialListMapping.java | 192 +-- ...AuthCallsCredentialListMappingCreator.java | 97 +- ...AuthCallsCredentialListMappingDeleter.java | 77 +- ...AuthCallsCredentialListMappingFetcher.java | 83 +- .../AuthCallsCredentialListMappingReader.java | 132 +- .../AuthCallsIpAccessControlListMapping.java | 192 +-- ...allsIpAccessControlListMappingCreator.java | 100 +- ...allsIpAccessControlListMappingDeleter.java | 77 +- ...allsIpAccessControlListMappingFetcher.java | 87 +- ...CallsIpAccessControlListMappingReader.java | 134 +- ...uthRegistrationsCredentialListMapping.java | 192 +-- ...strationsCredentialListMappingCreator.java | 97 +- ...strationsCredentialListMappingDeleter.java | 77 +- ...strationsCredentialListMappingFetcher.java | 87 +- ...istrationsCredentialListMappingReader.java | 134 +- .../sip/ipaccesscontrollist/IpAddress.java | 270 ++-- .../ipaccesscontrollist/IpAddressCreator.java | 106 +- .../ipaccesscontrollist/IpAddressDeleter.java | 74 +- .../ipaccesscontrollist/IpAddressFetcher.java | 80 +- .../ipaccesscontrollist/IpAddressReader.java | 117 +- .../ipaccesscontrollist/IpAddressUpdater.java | 106 +- .../rest/api/v2010/account/usage/Record.java | 230 ++- .../api/v2010/account/usage/RecordReader.java | 133 +- .../rest/api/v2010/account/usage/Trigger.java | 395 +++-- .../v2010/account/usage/TriggerCreator.java | 111 +- .../v2010/account/usage/TriggerDeleter.java | 55 +- .../v2010/account/usage/TriggerFetcher.java | 56 +- .../v2010/account/usage/TriggerReader.java | 115 +- .../v2010/account/usage/TriggerUpdater.java | 79 +- .../v2010/account/usage/record/AllTime.java | 230 ++- .../account/usage/record/AllTimeReader.java | 136 +- .../api/v2010/account/usage/record/Daily.java | 230 ++- .../account/usage/record/DailyReader.java | 132 +- .../v2010/account/usage/record/LastMonth.java | 230 ++- .../account/usage/record/LastMonthReader.java | 136 +- .../v2010/account/usage/record/Monthly.java | 230 ++- .../account/usage/record/MonthlyReader.java | 136 +- .../v2010/account/usage/record/ThisMonth.java | 230 ++- .../account/usage/record/ThisMonthReader.java | 136 +- .../api/v2010/account/usage/record/Today.java | 230 ++- .../account/usage/record/TodayReader.java | 132 +- .../v2010/account/usage/record/Yearly.java | 230 ++- .../account/usage/record/YearlyReader.java | 136 +- .../v2010/account/usage/record/Yesterday.java | 230 ++- .../account/usage/record/YesterdayReader.java | 136 +- .../twilio/rest/assistants/v1/Assistant.java | 509 +++---- .../rest/assistants/v1/AssistantCreator.java | 55 +- .../rest/assistants/v1/AssistantDeleter.java | 33 +- .../rest/assistants/v1/AssistantFetcher.java | 39 +- .../rest/assistants/v1/AssistantReader.java | 83 +- .../rest/assistants/v1/AssistantUpdater.java | 53 +- .../twilio/rest/assistants/v1/Knowledge.java | 330 ++--- .../rest/assistants/v1/KnowledgeCreator.java | 55 +- .../rest/assistants/v1/KnowledgeDeleter.java | 33 +- .../rest/assistants/v1/KnowledgeFetcher.java | 39 +- .../rest/assistants/v1/KnowledgeReader.java | 88 +- .../rest/assistants/v1/KnowledgeUpdater.java | 53 +- .../com/twilio/rest/assistants/v1/Policy.java | 172 +-- .../rest/assistants/v1/PolicyReader.java | 93 +- .../twilio/rest/assistants/v1/Session.java | 145 +- .../rest/assistants/v1/SessionFetcher.java | 34 +- .../rest/assistants/v1/SessionReader.java | 83 +- .../com/twilio/rest/assistants/v1/Tool.java | 333 ++--- .../rest/assistants/v1/ToolCreator.java | 47 +- .../rest/assistants/v1/ToolDeleter.java | 33 +- .../rest/assistants/v1/ToolFetcher.java | 34 +- .../twilio/rest/assistants/v1/ToolReader.java | 88 +- .../rest/assistants/v1/ToolUpdater.java | 45 +- .../v1/assistant/AssistantsKnowledge.java | 218 ++- .../assistant/AssistantsKnowledgeCreator.java | 53 +- .../assistant/AssistantsKnowledgeDeleter.java | 46 +- .../assistant/AssistantsKnowledgeReader.java | 96 +- .../v1/assistant/AssistantsTool.java | 202 ++- .../v1/assistant/AssistantsToolCreator.java | 53 +- .../v1/assistant/AssistantsToolDeleter.java | 46 +- .../v1/assistant/AssistantsToolReader.java | 92 +- .../assistants/v1/assistant/Feedback.java | 206 ++- .../v1/assistant/FeedbackCreator.java | 63 +- .../v1/assistant/FeedbackReader.java | 88 +- .../rest/assistants/v1/assistant/Message.java | 157 +- .../v1/assistant/MessageCreator.java | 58 +- .../rest/assistants/v1/knowledge/Chunk.java | 112 +- .../assistants/v1/knowledge/ChunkReader.java | 88 +- .../v1/knowledge/KnowledgeStatus.java | 99 +- .../v1/knowledge/KnowledgeStatusFetcher.java | 39 +- .../rest/assistants/v1/session/Message.java | 185 ++- .../assistants/v1/session/MessageReader.java | 92 +- .../twilio/rest/bulkexports/v1/Export.java | 83 +- .../bulkexports/v1/ExportConfiguration.java | 119 +- .../v1/ExportConfigurationFetcher.java | 43 +- .../v1/ExportConfigurationUpdater.java | 68 +- .../rest/bulkexports/v1/ExportFetcher.java | 38 +- .../rest/bulkexports/v1/export/Day.java | 133 +- .../bulkexports/v1/export/DayFetcher.java | 44 +- .../rest/bulkexports/v1/export/DayReader.java | 92 +- .../v1/export/ExportCustomJob.java | 214 ++- .../v1/export/ExportCustomJobCreator.java | 87 +- .../v1/export/ExportCustomJobReader.java | 92 +- .../rest/bulkexports/v1/export/Job.java | 225 ++- .../bulkexports/v1/export/JobDeleter.java | 33 +- .../bulkexports/v1/export/JobFetcher.java | 34 +- .../com/twilio/rest/chat/v1/Credential.java | 216 +-- .../rest/chat/v1/CredentialCreator.java | 68 +- .../rest/chat/v1/CredentialDeleter.java | 33 +- .../rest/chat/v1/CredentialFetcher.java | 39 +- .../twilio/rest/chat/v1/CredentialReader.java | 83 +- .../rest/chat/v1/CredentialUpdater.java | 71 +- .../java/com/twilio/rest/chat/v1/Service.java | 390 +++-- .../twilio/rest/chat/v1/ServiceCreator.java | 37 +- .../twilio/rest/chat/v1/ServiceDeleter.java | 33 +- .../twilio/rest/chat/v1/ServiceFetcher.java | 34 +- .../twilio/rest/chat/v1/ServiceReader.java | 83 +- .../twilio/rest/chat/v1/ServiceUpdater.java | 772 ++++------ .../twilio/rest/chat/v1/service/Channel.java | 308 ++-- .../rest/chat/v1/service/ChannelCreator.java | 60 +- .../rest/chat/v1/service/ChannelDeleter.java | 43 +- .../rest/chat/v1/service/ChannelFetcher.java | 44 +- .../rest/chat/v1/service/ChannelReader.java | 99 +- .../rest/chat/v1/service/ChannelUpdater.java | 61 +- .../com/twilio/rest/chat/v1/service/Role.java | 248 ++-- .../rest/chat/v1/service/RoleCreator.java | 70 +- .../rest/chat/v1/service/RoleDeleter.java | 43 +- .../rest/chat/v1/service/RoleFetcher.java | 44 +- .../rest/chat/v1/service/RoleReader.java | 92 +- .../rest/chat/v1/service/RoleUpdater.java | 59 +- .../com/twilio/rest/chat/v1/service/User.java | 270 ++-- .../rest/chat/v1/service/UserCreator.java | 61 +- .../rest/chat/v1/service/UserDeleter.java | 43 +- .../rest/chat/v1/service/UserFetcher.java | 44 +- .../rest/chat/v1/service/UserReader.java | 92 +- .../rest/chat/v1/service/UserUpdater.java | 61 +- .../rest/chat/v1/service/channel/Invite.java | 213 ++- .../v1/service/channel/InviteCreator.java | 65 +- .../v1/service/channel/InviteDeleter.java | 60 +- .../v1/service/channel/InviteFetcher.java | 61 +- .../chat/v1/service/channel/InviteReader.java | 112 +- .../rest/chat/v1/service/channel/Member.java | 249 ++-- .../v1/service/channel/MemberCreator.java | 65 +- .../v1/service/channel/MemberDeleter.java | 60 +- .../v1/service/channel/MemberFetcher.java | 61 +- .../chat/v1/service/channel/MemberReader.java | 112 +- .../v1/service/channel/MemberUpdater.java | 80 +- .../rest/chat/v1/service/channel/Message.java | 300 ++-- .../v1/service/channel/MessageCreator.java | 73 +- .../v1/service/channel/MessageDeleter.java | 60 +- .../v1/service/channel/MessageFetcher.java | 61 +- .../v1/service/channel/MessageReader.java | 113 +- .../v1/service/channel/MessageUpdater.java | 73 +- .../chat/v1/service/user/UserChannel.java | 195 ++- .../v1/service/user/UserChannelReader.java | 101 +- .../com/twilio/rest/chat/v2/Credential.java | 216 +-- .../rest/chat/v2/CredentialCreator.java | 68 +- .../rest/chat/v2/CredentialDeleter.java | 33 +- .../rest/chat/v2/CredentialFetcher.java | 39 +- .../twilio/rest/chat/v2/CredentialReader.java | 83 +- .../rest/chat/v2/CredentialUpdater.java | 71 +- .../java/com/twilio/rest/chat/v2/Service.java | 425 +++--- .../twilio/rest/chat/v2/ServiceCreator.java | 37 +- .../twilio/rest/chat/v2/ServiceDeleter.java | 33 +- .../twilio/rest/chat/v2/ServiceFetcher.java | 34 +- .../twilio/rest/chat/v2/ServiceReader.java | 83 +- .../twilio/rest/chat/v2/ServiceUpdater.java | 409 +++--- .../twilio/rest/chat/v2/service/Binding.java | 265 ++-- .../rest/chat/v2/service/BindingDeleter.java | 43 +- .../rest/chat/v2/service/BindingFetcher.java | 44 +- .../rest/chat/v2/service/BindingReader.java | 109 +- .../twilio/rest/chat/v2/service/Channel.java | 348 +++-- .../rest/chat/v2/service/ChannelCreator.java | 102 +- .../rest/chat/v2/service/ChannelDeleter.java | 57 +- .../rest/chat/v2/service/ChannelFetcher.java | 44 +- .../rest/chat/v2/service/ChannelReader.java | 99 +- .../rest/chat/v2/service/ChannelUpdater.java | 103 +- .../com/twilio/rest/chat/v2/service/Role.java | 248 ++-- .../rest/chat/v2/service/RoleCreator.java | 70 +- .../rest/chat/v2/service/RoleDeleter.java | 43 +- .../rest/chat/v2/service/RoleFetcher.java | 44 +- .../rest/chat/v2/service/RoleReader.java | 92 +- .../rest/chat/v2/service/RoleUpdater.java | 59 +- .../com/twilio/rest/chat/v2/service/User.java | 307 ++-- .../rest/chat/v2/service/UserCreator.java | 83 +- .../rest/chat/v2/service/UserDeleter.java | 43 +- .../rest/chat/v2/service/UserFetcher.java | 44 +- .../rest/chat/v2/service/UserReader.java | 92 +- .../rest/chat/v2/service/UserUpdater.java | 81 +- .../rest/chat/v2/service/channel/Invite.java | 213 ++- .../v2/service/channel/InviteCreator.java | 65 +- .../v2/service/channel/InviteDeleter.java | 60 +- .../v2/service/channel/InviteFetcher.java | 61 +- .../chat/v2/service/channel/InviteReader.java | 112 +- .../rest/chat/v2/service/channel/Member.java | 301 ++-- .../v2/service/channel/MemberCreator.java | 133 +- .../v2/service/channel/MemberDeleter.java | 74 +- .../v2/service/channel/MemberFetcher.java | 61 +- .../chat/v2/service/channel/MemberReader.java | 112 +- .../v2/service/channel/MemberUpdater.java | 134 +- .../rest/chat/v2/service/channel/Message.java | 382 +++-- .../v2/service/channel/MessageCreator.java | 118 +- .../v2/service/channel/MessageDeleter.java | 74 +- .../v2/service/channel/MessageFetcher.java | 61 +- .../v2/service/channel/MessageReader.java | 113 +- .../v2/service/channel/MessageUpdater.java | 120 +- .../rest/chat/v2/service/channel/Webhook.java | 296 ++-- .../v2/service/channel/WebhookCreator.java | 139 +- .../v2/service/channel/WebhookDeleter.java | 60 +- .../v2/service/channel/WebhookFetcher.java | 61 +- .../v2/service/channel/WebhookReader.java | 108 +- .../v2/service/channel/WebhookUpdater.java | 138 +- .../chat/v2/service/user/UserBinding.java | 269 ++-- .../v2/service/user/UserBindingDeleter.java | 56 +- .../v2/service/user/UserBindingFetcher.java | 62 +- .../v2/service/user/UserBindingReader.java | 116 +- .../chat/v2/service/user/UserChannel.java | 351 ++--- .../v2/service/user/UserChannelDeleter.java | 74 +- .../v2/service/user/UserChannelFetcher.java | 66 +- .../v2/service/user/UserChannelReader.java | 101 +- .../v2/service/user/UserChannelUpdater.java | 105 +- .../java/com/twilio/rest/chat/v3/Channel.java | 309 ++-- .../twilio/rest/chat/v3/ChannelUpdater.java | 80 +- .../com/twilio/rest/content/v1/Content.java | 1288 +++++++++-------- .../rest/content/v1/ContentAndApprovals.java | 171 +-- .../content/v1/ContentAndApprovalsReader.java | 87 +- .../rest/content/v1/ContentCreator.java | 37 +- .../rest/content/v1/ContentDeleter.java | 33 +- .../rest/content/v1/ContentFetcher.java | 34 +- .../twilio/rest/content/v1/ContentReader.java | 83 +- .../twilio/rest/content/v1/LegacyContent.java | 192 ++- .../rest/content/v1/LegacyContentReader.java | 83 +- .../content/v1/content/ApprovalCreate.java | 143 +- .../v1/content/ApprovalCreateCreator.java | 58 +- .../content/v1/content/ApprovalFetch.java | 98 +- .../v1/content/ApprovalFetchFetcher.java | 39 +- .../com/twilio/rest/content/v2/Content.java | 178 ++- .../rest/content/v2/ContentAndApprovals.java | 171 +-- .../content/v2/ContentAndApprovalsReader.java | 163 +-- .../twilio/rest/content/v2/ContentReader.java | 151 +- .../v1/AddressConfiguration.java | 343 +++-- .../v1/AddressConfigurationCreator.java | 178 +-- .../v1/AddressConfigurationDeleter.java | 33 +- .../v1/AddressConfigurationFetcher.java | 39 +- .../v1/AddressConfigurationReader.java | 92 +- .../v1/AddressConfigurationUpdater.java | 156 +- .../rest/conversations/v1/Configuration.java | 150 +- .../v1/ConfigurationFetcher.java | 35 +- .../v1/ConfigurationUpdater.java | 78 +- .../rest/conversations/v1/Conversation.java | 339 +++-- .../conversations/v1/ConversationCreator.java | 133 +- .../conversations/v1/ConversationDeleter.java | 47 +- .../conversations/v1/ConversationFetcher.java | 39 +- .../conversations/v1/ConversationReader.java | 98 +- .../conversations/v1/ConversationUpdater.java | 138 +- .../v1/ConversationWithParticipants.java | 323 ++--- .../ConversationWithParticipantsCreator.java | 182 ++- .../rest/conversations/v1/Credential.java | 216 +-- .../conversations/v1/CredentialCreator.java | 68 +- .../conversations/v1/CredentialDeleter.java | 33 +- .../conversations/v1/CredentialFetcher.java | 39 +- .../conversations/v1/CredentialReader.java | 83 +- .../conversations/v1/CredentialUpdater.java | 76 +- .../v1/ParticipantConversation.java | 342 ++--- .../v1/ParticipantConversationReader.java | 104 +- .../twilio/rest/conversations/v1/Role.java | 234 ++- .../rest/conversations/v1/RoleCreator.java | 58 +- .../rest/conversations/v1/RoleDeleter.java | 33 +- .../rest/conversations/v1/RoleFetcher.java | 34 +- .../rest/conversations/v1/RoleReader.java | 83 +- .../rest/conversations/v1/RoleUpdater.java | 45 +- .../twilio/rest/conversations/v1/Service.java | 158 +- .../rest/conversations/v1/ServiceCreator.java | 37 +- .../rest/conversations/v1/ServiceDeleter.java | 33 +- .../rest/conversations/v1/ServiceFetcher.java | 34 +- .../rest/conversations/v1/ServiceReader.java | 83 +- .../twilio/rest/conversations/v1/User.java | 286 ++-- .../rest/conversations/v1/UserCreator.java | 70 +- .../rest/conversations/v1/UserDeleter.java | 47 +- .../rest/conversations/v1/UserFetcher.java | 34 +- .../rest/conversations/v1/UserReader.java | 83 +- .../rest/conversations/v1/UserUpdater.java | 71 +- .../v1/configuration/Webhook.java | 210 ++- .../v1/configuration/WebhookFetcher.java | 30 +- .../v1/configuration/WebhookUpdater.java | 58 +- .../v1/conversation/Message.java | 365 +++-- .../v1/conversation/MessageCreator.java | 112 +- .../v1/conversation/MessageDeleter.java | 60 +- .../v1/conversation/MessageFetcher.java | 47 +- .../v1/conversation/MessageReader.java | 97 +- .../v1/conversation/MessageUpdater.java | 106 +- .../v1/conversation/Participant.java | 286 ++-- .../v1/conversation/ParticipantCreator.java | 136 +- .../v1/conversation/ParticipantDeleter.java | 60 +- .../v1/conversation/ParticipantFetcher.java | 52 +- .../v1/conversation/ParticipantReader.java | 92 +- .../v1/conversation/ParticipantUpdater.java | 154 +- .../v1/conversation/Webhook.java | 274 ++-- .../v1/conversation/WebhookCreator.java | 125 +- .../v1/conversation/WebhookDeleter.java | 46 +- .../v1/conversation/WebhookFetcher.java | 47 +- .../v1/conversation/WebhookReader.java | 92 +- .../v1/conversation/WebhookUpdater.java | 112 +- .../conversation/message/DeliveryReceipt.java | 247 ++-- .../message/DeliveryReceiptFetcher.java | 66 +- .../message/DeliveryReceiptReader.java | 108 +- .../conversations/v1/service/Binding.java | 241 ++- .../v1/service/BindingDeleter.java | 46 +- .../v1/service/BindingFetcher.java | 47 +- .../v1/service/BindingReader.java | 109 +- .../v1/service/Configuration.java | 160 +- .../v1/service/ConfigurationFetcher.java | 43 +- .../v1/service/ConfigurationUpdater.java | 96 +- .../v1/service/Conversation.java | 350 +++-- .../v1/service/ConversationCreator.java | 142 +- .../v1/service/ConversationDeleter.java | 60 +- .../v1/service/ConversationFetcher.java | 52 +- .../v1/service/ConversationReader.java | 107 +- .../v1/service/ConversationUpdater.java | 151 +- .../service/ConversationWithParticipants.java | 327 ++--- .../ConversationWithParticipantsCreator.java | 196 ++- .../v1/service/ParticipantConversation.java | 346 ++--- .../ParticipantConversationReader.java | 113 +- .../rest/conversations/v1/service/Role.java | 245 ++-- .../conversations/v1/service/RoleCreator.java | 70 +- .../conversations/v1/service/RoleDeleter.java | 43 +- .../conversations/v1/service/RoleFetcher.java | 44 +- .../conversations/v1/service/RoleReader.java | 92 +- .../conversations/v1/service/RoleUpdater.java | 59 +- .../rest/conversations/v1/service/User.java | 302 ++-- .../conversations/v1/service/UserCreator.java | 83 +- .../conversations/v1/service/UserDeleter.java | 57 +- .../conversations/v1/service/UserFetcher.java | 44 +- .../conversations/v1/service/UserReader.java | 92 +- .../conversations/v1/service/UserUpdater.java | 81 +- .../service/configuration/Notification.java | 150 +- .../configuration/NotificationFetcher.java | 46 +- .../configuration/NotificationUpdater.java | 191 ++- .../v1/service/configuration/Webhook.java | 174 ++- .../service/configuration/WebhookFetcher.java | 38 +- .../service/configuration/WebhookUpdater.java | 66 +- .../v1/service/conversation/Message.java | 387 +++-- .../service/conversation/MessageCreator.java | 128 +- .../service/conversation/MessageDeleter.java | 74 +- .../service/conversation/MessageFetcher.java | 61 +- .../service/conversation/MessageReader.java | 113 +- .../service/conversation/MessageUpdater.java | 120 +- .../v1/service/conversation/Participant.java | 306 ++-- .../conversation/ParticipantCreator.java | 152 +- .../conversation/ParticipantDeleter.java | 74 +- .../conversation/ParticipantFetcher.java | 66 +- .../conversation/ParticipantReader.java | 108 +- .../conversation/ParticipantUpdater.java | 168 +-- .../v1/service/conversation/Webhook.java | 292 ++-- .../service/conversation/WebhookCreator.java | 139 +- .../service/conversation/WebhookDeleter.java | 60 +- .../service/conversation/WebhookFetcher.java | 61 +- .../service/conversation/WebhookReader.java | 108 +- .../service/conversation/WebhookUpdater.java | 126 +- .../conversation/message/DeliveryReceipt.java | 261 ++-- .../message/DeliveryReceiptFetcher.java | 77 +- .../message/DeliveryReceiptReader.java | 119 +- .../v1/service/user/UserConversation.java | 409 +++--- .../service/user/UserConversationDeleter.java | 60 +- .../service/user/UserConversationFetcher.java | 66 +- .../service/user/UserConversationReader.java | 104 +- .../service/user/UserConversationUpdater.java | 105 +- .../v1/user/UserConversation.java | 403 +++--- .../v1/user/UserConversationDeleter.java | 46 +- .../v1/user/UserConversationFetcher.java | 52 +- .../v1/user/UserConversationReader.java | 88 +- .../v1/user/UserConversationUpdater.java | 91 +- .../com/twilio/rest/events/v1/EventType.java | 174 ++- .../rest/events/v1/EventTypeFetcher.java | 39 +- .../rest/events/v1/EventTypeReader.java | 88 +- .../com/twilio/rest/events/v1/Schema.java | 122 +- .../twilio/rest/events/v1/SchemaFetcher.java | 34 +- .../java/com/twilio/rest/events/v1/Sink.java | 280 ++-- .../twilio/rest/events/v1/SinkCreator.java | 64 +- .../twilio/rest/events/v1/SinkDeleter.java | 33 +- .../twilio/rest/events/v1/SinkFetcher.java | 34 +- .../com/twilio/rest/events/v1/SinkReader.java | 93 +- .../twilio/rest/events/v1/SinkUpdater.java | 46 +- .../twilio/rest/events/v1/Subscription.java | 180 ++- .../rest/events/v1/SubscriptionCreator.java | 64 +- .../rest/events/v1/SubscriptionDeleter.java | 33 +- .../rest/events/v1/SubscriptionFetcher.java | 39 +- .../rest/events/v1/SubscriptionReader.java | 88 +- .../rest/events/v1/SubscriptionUpdater.java | 46 +- .../rest/events/v1/schema/SchemaVersion.java | 119 +- .../v1/schema/SchemaVersionFetcher.java | 52 +- .../events/v1/schema/SchemaVersionReader.java | 88 +- .../twilio/rest/events/v1/sink/SinkTest.java | 62 +- .../rest/events/v1/sink/SinkTestCreator.java | 40 +- .../rest/events/v1/sink/SinkValidate.java | 65 +- .../events/v1/sink/SinkValidateCreator.java | 47 +- .../v1/subscription/SubscribedEvent.java | 146 +- .../subscription/SubscribedEventCreator.java | 63 +- .../subscription/SubscribedEventDeleter.java | 49 +- .../subscription/SubscribedEventFetcher.java | 55 +- .../subscription/SubscribedEventReader.java | 92 +- .../subscription/SubscribedEventUpdater.java | 66 +- .../twilio/rest/flexapi/v1/Assessments.java | 265 ++-- .../rest/flexapi/v1/AssessmentsCreator.java | 134 +- .../rest/flexapi/v1/AssessmentsReader.java | 111 +- .../rest/flexapi/v1/AssessmentsUpdater.java | 82 +- .../com/twilio/rest/flexapi/v1/Channel.java | 174 ++- .../rest/flexapi/v1/ChannelCreator.java | 104 +- .../rest/flexapi/v1/ChannelDeleter.java | 33 +- .../rest/flexapi/v1/ChannelFetcher.java | 34 +- .../twilio/rest/flexapi/v1/ChannelReader.java | 83 +- .../twilio/rest/flexapi/v1/Configuration.java | 889 ++++-------- .../rest/flexapi/v1/ConfigurationFetcher.java | 43 +- .../rest/flexapi/v1/ConfigurationUpdater.java | 34 +- .../com/twilio/rest/flexapi/v1/FlexFlow.java | 352 +++-- .../rest/flexapi/v1/FlexFlowCreator.java | 201 ++- .../rest/flexapi/v1/FlexFlowDeleter.java | 33 +- .../rest/flexapi/v1/FlexFlowFetcher.java | 39 +- .../rest/flexapi/v1/FlexFlowReader.java | 88 +- .../rest/flexapi/v1/FlexFlowUpdater.java | 188 +-- .../v1/InsightsAssessmentsComment.java | 222 ++- .../v1/InsightsAssessmentsCommentCreator.java | 116 +- .../v1/InsightsAssessmentsCommentReader.java | 133 +- .../flexapi/v1/InsightsConversations.java | 90 +- .../v1/InsightsConversationsReader.java | 121 +- .../flexapi/v1/InsightsQuestionnaires.java | 169 ++- .../v1/InsightsQuestionnairesCategory.java | 127 +- ...InsightsQuestionnairesCategoryCreator.java | 58 +- ...InsightsQuestionnairesCategoryDeleter.java | 51 +- .../InsightsQuestionnairesCategoryReader.java | 121 +- ...InsightsQuestionnairesCategoryUpdater.java | 74 +- .../v1/InsightsQuestionnairesCreator.java | 89 +- .../v1/InsightsQuestionnairesDeleter.java | 54 +- .../v1/InsightsQuestionnairesFetcher.java | 60 +- .../v1/InsightsQuestionnairesQuestion.java | 225 ++- ...InsightsQuestionnairesQuestionCreator.java | 120 +- ...InsightsQuestionnairesQuestionDeleter.java | 51 +- .../InsightsQuestionnairesQuestionReader.java | 138 +- ...InsightsQuestionnairesQuestionUpdater.java | 120 +- .../v1/InsightsQuestionnairesReader.java | 131 +- .../v1/InsightsQuestionnairesUpdater.java | 107 +- .../rest/flexapi/v1/InsightsSegments.java | 364 ++--- .../flexapi/v1/InsightsSegmentsReader.java | 122 +- .../rest/flexapi/v1/InsightsSession.java | 106 +- .../flexapi/v1/InsightsSessionCreator.java | 42 +- .../v1/InsightsSettingsAnswerSets.java | 121 +- .../v1/InsightsSettingsAnswerSetsFetcher.java | 48 +- .../flexapi/v1/InsightsSettingsComment.java | 80 +- .../v1/InsightsSettingsCommentFetcher.java | 48 +- .../rest/flexapi/v1/InsightsUserRoles.java | 65 +- .../flexapi/v1/InsightsUserRolesFetcher.java | 45 +- .../twilio/rest/flexapi/v1/Interaction.java | 154 +- .../rest/flexapi/v1/InteractionCreator.java | 62 +- .../rest/flexapi/v1/InteractionFetcher.java | 39 +- .../rest/flexapi/v1/InteractionUpdater.java | 46 +- .../com/twilio/rest/flexapi/v1/Plugin.java | 201 ++- .../twilio/rest/flexapi/v1/PluginArchive.java | 168 +-- .../rest/flexapi/v1/PluginArchiveUpdater.java | 47 +- .../rest/flexapi/v1/PluginConfiguration.java | 165 +-- .../v1/PluginConfigurationArchive.java | 151 +- .../v1/PluginConfigurationArchiveUpdater.java | 54 +- .../v1/PluginConfigurationCreator.java | 72 +- .../v1/PluginConfigurationFetcher.java | 50 +- .../flexapi/v1/PluginConfigurationReader.java | 112 +- .../twilio/rest/flexapi/v1/PluginCreator.java | 61 +- .../twilio/rest/flexapi/v1/PluginFetcher.java | 41 +- .../twilio/rest/flexapi/v1/PluginReader.java | 106 +- .../twilio/rest/flexapi/v1/PluginRelease.java | 119 +- .../rest/flexapi/v1/PluginReleaseCreator.java | 55 +- .../rest/flexapi/v1/PluginReleaseFetcher.java | 46 +- .../rest/flexapi/v1/PluginReleaseReader.java | 106 +- .../twilio/rest/flexapi/v1/PluginUpdater.java | 61 +- .../rest/flexapi/v1/PluginVersionArchive.java | 185 ++- .../v1/PluginVersionArchiveUpdater.java | 67 +- .../rest/flexapi/v1/ProvisioningStatus.java | 107 +- .../flexapi/v1/ProvisioningStatusFetcher.java | 35 +- .../twilio/rest/flexapi/v1/WebChannel.java | 190 +-- .../rest/flexapi/v1/WebChannelCreator.java | 97 +- .../rest/flexapi/v1/WebChannelDeleter.java | 33 +- .../rest/flexapi/v1/WebChannelFetcher.java | 39 +- .../rest/flexapi/v1/WebChannelReader.java | 83 +- .../rest/flexapi/v1/WebChannelUpdater.java | 59 +- .../v1/interaction/InteractionChannel.java | 313 ++-- .../InteractionChannelFetcher.java | 52 +- .../interaction/InteractionChannelReader.java | 92 +- .../InteractionChannelUpdater.java | 71 +- .../InteractionChannelInvite.java | 123 +- .../InteractionChannelInviteCreator.java | 73 +- .../InteractionChannelInviteReader.java | 119 +- .../InteractionChannelParticipant.java | 249 ++-- .../InteractionChannelParticipantCreator.java | 107 +- .../InteractionChannelParticipantReader.java | 123 +- .../InteractionChannelParticipantUpdater.java | 82 +- .../InteractionTransfer.java | 338 ++--- .../InteractionTransferCreator.java | 58 +- .../InteractionTransferFetcher.java | 66 +- .../InteractionTransferUpdater.java | 66 +- .../flexapi/v1/plugin/PluginVersions.java | 218 ++- .../v1/plugin/PluginVersionsCreator.java | 109 +- .../v1/plugin/PluginVersionsFetcher.java | 59 +- .../v1/plugin/PluginVersionsReader.java | 115 +- .../pluginconfiguration/ConfiguredPlugin.java | 277 ++-- .../ConfiguredPluginFetcher.java | 66 +- .../ConfiguredPluginReader.java | 118 +- .../com/twilio/rest/flexapi/v2/FlexUser.java | 265 ++-- .../rest/flexapi/v2/FlexUserFetcher.java | 56 +- .../rest/flexapi/v2/FlexUserUpdater.java | 73 +- .../twilio/rest/flexapi/v2/WebChannels.java | 66 +- .../rest/flexapi/v2/WebChannelsCreator.java | 88 +- .../com/twilio/rest/frontlineapi/v1/User.java | 182 ++- .../rest/frontlineapi/v1/UserFetcher.java | 34 +- .../rest/frontlineapi/v1/UserUpdater.java | 56 +- .../java/com/twilio/rest/iam/v1/ApiKey.java | 132 +- .../com/twilio/rest/iam/v1/ApiKeyDeleter.java | 33 +- .../com/twilio/rest/iam/v1/ApiKeyFetcher.java | 34 +- .../com/twilio/rest/iam/v1/ApiKeyUpdater.java | 47 +- .../com/twilio/rest/iam/v1/GetApiKeys.java | 112 +- .../twilio/rest/iam/v1/GetApiKeysReader.java | 87 +- .../com/twilio/rest/iam/v1/NewApiKey.java | 164 +-- .../twilio/rest/iam/v1/NewApiKeyCreator.java | 56 +- .../java/com/twilio/rest/iam/v1/Token.java | 111 +- .../com/twilio/rest/iam/v1/TokenCreator.java | 74 +- .../com/twilio/rest/insights/v1/Call.java | 83 +- .../twilio/rest/insights/v1/CallFetcher.java | 34 +- .../rest/insights/v1/CallSummaries.java | 555 ++++--- .../rest/insights/v1/CallSummariesReader.java | 361 ++--- .../twilio/rest/insights/v1/Conference.java | 641 ++++---- .../rest/insights/v1/ConferenceFetcher.java | 43 +- .../rest/insights/v1/ConferenceReader.java | 133 +- .../com/twilio/rest/insights/v1/Room.java | 711 +++++---- .../twilio/rest/insights/v1/RoomFetcher.java | 34 +- .../twilio/rest/insights/v1/RoomReader.java | 115 +- .../com/twilio/rest/insights/v1/Setting.java | 95 +- .../rest/insights/v1/SettingFetcher.java | 38 +- .../rest/insights/v1/SettingUpdater.java | 49 +- .../rest/insights/v1/call/Annotation.java | 267 ++-- .../insights/v1/call/AnnotationFetcher.java | 39 +- .../insights/v1/call/AnnotationUpdater.java | 87 +- .../rest/insights/v1/call/CallSummary.java | 516 +++---- .../insights/v1/call/CallSummaryFetcher.java | 55 +- .../twilio/rest/insights/v1/call/Event.java | 279 ++-- .../rest/insights/v1/call/EventReader.java | 93 +- .../twilio/rest/insights/v1/call/Metric.java | 259 ++-- .../rest/insights/v1/call/MetricReader.java | 98 +- .../v1/conference/ConferenceParticipant.java | 690 ++++----- .../ConferenceParticipantFetcher.java | 76 +- .../ConferenceParticipantReader.java | 119 +- .../rest/insights/v1/room/Participant.java | 485 ++++--- .../insights/v1/room/ParticipantFetcher.java | 52 +- .../insights/v1/room/ParticipantReader.java | 88 +- .../rest/intelligence/v2/CustomOperator.java | 286 ++-- .../v2/CustomOperatorCreator.java | 66 +- .../v2/CustomOperatorDeleter.java | 33 +- .../v2/CustomOperatorFetcher.java | 39 +- .../intelligence/v2/CustomOperatorReader.java | 97 +- .../v2/CustomOperatorUpdater.java | 71 +- .../twilio/rest/intelligence/v2/Operator.java | 255 ++-- .../intelligence/v2/OperatorAttachment.java | 95 +- .../v2/OperatorAttachmentCreator.java | 57 +- .../v2/OperatorAttachmentDeleter.java | 50 +- .../intelligence/v2/OperatorAttachments.java | 84 +- .../v2/OperatorAttachmentsFetcher.java | 43 +- .../rest/intelligence/v2/OperatorFetcher.java | 39 +- .../rest/intelligence/v2/OperatorReader.java | 97 +- .../rest/intelligence/v2/OperatorType.java | 379 +++-- .../intelligence/v2/OperatorTypeFetcher.java | 39 +- .../intelligence/v2/OperatorTypeReader.java | 83 +- .../intelligence/v2/PrebuiltOperator.java | 257 ++-- .../v2/PrebuiltOperatorFetcher.java | 39 +- .../v2/PrebuiltOperatorReader.java | 97 +- .../twilio/rest/intelligence/v2/Service.java | 322 ++--- .../rest/intelligence/v2/ServiceCreator.java | 93 +- .../rest/intelligence/v2/ServiceDeleter.java | 33 +- .../rest/intelligence/v2/ServiceFetcher.java | 34 +- .../rest/intelligence/v2/ServiceReader.java | 83 +- .../rest/intelligence/v2/ServiceUpdater.java | 110 +- .../rest/intelligence/v2/Transcript.java | 326 ++--- .../intelligence/v2/TranscriptCreator.java | 65 +- .../intelligence/v2/TranscriptDeleter.java | 33 +- .../intelligence/v2/TranscriptFetcher.java | 39 +- .../intelligence/v2/TranscriptReader.java | 127 +- .../transcript/EncryptedOperatorResults.java | 145 ++ .../EncryptedOperatorResultsFetcher.java | 86 ++ .../v2/transcript/EncryptedSentences.java | 144 ++ .../transcript/EncryptedSentencesFetcher.java | 86 ++ .../intelligence/v2/transcript/Media.java | 98 +- .../v2/transcript/MediaFetcher.java | 43 +- .../v2/transcript/OperatorResult.java | 332 ++--- .../v2/transcript/OperatorResultFetcher.java | 68 +- .../v2/transcript/OperatorResultReader.java | 97 +- .../intelligence/v2/transcript/Sentence.java | 149 +- .../v2/transcript/SentenceReader.java | 102 +- .../rest/ipmessaging/v1/Credential.java | 216 +-- .../ipmessaging/v1/CredentialCreator.java | 68 +- .../ipmessaging/v1/CredentialDeleter.java | 33 +- .../ipmessaging/v1/CredentialFetcher.java | 39 +- .../rest/ipmessaging/v1/CredentialReader.java | 83 +- .../ipmessaging/v1/CredentialUpdater.java | 71 +- .../twilio/rest/ipmessaging/v1/Service.java | 390 +++-- .../rest/ipmessaging/v1/ServiceCreator.java | 37 +- .../rest/ipmessaging/v1/ServiceDeleter.java | 33 +- .../rest/ipmessaging/v1/ServiceFetcher.java | 34 +- .../rest/ipmessaging/v1/ServiceReader.java | 83 +- .../rest/ipmessaging/v1/ServiceUpdater.java | 772 ++++------ .../rest/ipmessaging/v1/service/Channel.java | 308 ++-- .../v1/service/ChannelCreator.java | 60 +- .../v1/service/ChannelDeleter.java | 43 +- .../v1/service/ChannelFetcher.java | 44 +- .../ipmessaging/v1/service/ChannelReader.java | 99 +- .../v1/service/ChannelUpdater.java | 61 +- .../rest/ipmessaging/v1/service/Role.java | 248 ++-- .../ipmessaging/v1/service/RoleCreator.java | 70 +- .../ipmessaging/v1/service/RoleDeleter.java | 43 +- .../ipmessaging/v1/service/RoleFetcher.java | 44 +- .../ipmessaging/v1/service/RoleReader.java | 92 +- .../ipmessaging/v1/service/RoleUpdater.java | 59 +- .../rest/ipmessaging/v1/service/User.java | 270 ++-- .../ipmessaging/v1/service/UserCreator.java | 61 +- .../ipmessaging/v1/service/UserDeleter.java | 43 +- .../ipmessaging/v1/service/UserFetcher.java | 44 +- .../ipmessaging/v1/service/UserReader.java | 92 +- .../ipmessaging/v1/service/UserUpdater.java | 61 +- .../v1/service/channel/Invite.java | 213 ++- .../v1/service/channel/InviteCreator.java | 65 +- .../v1/service/channel/InviteDeleter.java | 60 +- .../v1/service/channel/InviteFetcher.java | 61 +- .../v1/service/channel/InviteReader.java | 112 +- .../v1/service/channel/Member.java | 249 ++-- .../v1/service/channel/MemberCreator.java | 65 +- .../v1/service/channel/MemberDeleter.java | 60 +- .../v1/service/channel/MemberFetcher.java | 61 +- .../v1/service/channel/MemberReader.java | 112 +- .../v1/service/channel/MemberUpdater.java | 80 +- .../v1/service/channel/Message.java | 300 ++-- .../v1/service/channel/MessageCreator.java | 73 +- .../v1/service/channel/MessageDeleter.java | 60 +- .../v1/service/channel/MessageFetcher.java | 61 +- .../v1/service/channel/MessageReader.java | 113 +- .../v1/service/channel/MessageUpdater.java | 73 +- .../v1/service/user/UserChannel.java | 195 ++- .../v1/service/user/UserChannelReader.java | 101 +- .../rest/ipmessaging/v2/Credential.java | 216 +-- .../ipmessaging/v2/CredentialCreator.java | 68 +- .../ipmessaging/v2/CredentialDeleter.java | 33 +- .../ipmessaging/v2/CredentialFetcher.java | 39 +- .../rest/ipmessaging/v2/CredentialReader.java | 83 +- .../ipmessaging/v2/CredentialUpdater.java | 71 +- .../twilio/rest/ipmessaging/v2/Service.java | 425 +++--- .../rest/ipmessaging/v2/ServiceCreator.java | 37 +- .../rest/ipmessaging/v2/ServiceDeleter.java | 33 +- .../rest/ipmessaging/v2/ServiceFetcher.java | 34 +- .../rest/ipmessaging/v2/ServiceReader.java | 83 +- .../rest/ipmessaging/v2/ServiceUpdater.java | 409 +++--- .../rest/ipmessaging/v2/service/Binding.java | 265 ++-- .../v2/service/BindingDeleter.java | 43 +- .../v2/service/BindingFetcher.java | 44 +- .../ipmessaging/v2/service/BindingReader.java | 109 +- .../rest/ipmessaging/v2/service/Channel.java | 348 +++-- .../v2/service/ChannelCreator.java | 102 +- .../v2/service/ChannelDeleter.java | 57 +- .../v2/service/ChannelFetcher.java | 44 +- .../ipmessaging/v2/service/ChannelReader.java | 99 +- .../v2/service/ChannelUpdater.java | 103 +- .../rest/ipmessaging/v2/service/Role.java | 248 ++-- .../ipmessaging/v2/service/RoleCreator.java | 70 +- .../ipmessaging/v2/service/RoleDeleter.java | 43 +- .../ipmessaging/v2/service/RoleFetcher.java | 44 +- .../ipmessaging/v2/service/RoleReader.java | 92 +- .../ipmessaging/v2/service/RoleUpdater.java | 59 +- .../rest/ipmessaging/v2/service/User.java | 307 ++-- .../ipmessaging/v2/service/UserCreator.java | 83 +- .../ipmessaging/v2/service/UserDeleter.java | 43 +- .../ipmessaging/v2/service/UserFetcher.java | 44 +- .../ipmessaging/v2/service/UserReader.java | 92 +- .../ipmessaging/v2/service/UserUpdater.java | 81 +- .../v2/service/channel/Invite.java | 213 ++- .../v2/service/channel/InviteCreator.java | 65 +- .../v2/service/channel/InviteDeleter.java | 60 +- .../v2/service/channel/InviteFetcher.java | 61 +- .../v2/service/channel/InviteReader.java | 112 +- .../v2/service/channel/Member.java | 301 ++-- .../v2/service/channel/MemberCreator.java | 133 +- .../v2/service/channel/MemberDeleter.java | 74 +- .../v2/service/channel/MemberFetcher.java | 61 +- .../v2/service/channel/MemberReader.java | 112 +- .../v2/service/channel/MemberUpdater.java | 134 +- .../v2/service/channel/Message.java | 382 +++-- .../v2/service/channel/MessageCreator.java | 118 +- .../v2/service/channel/MessageDeleter.java | 74 +- .../v2/service/channel/MessageFetcher.java | 61 +- .../v2/service/channel/MessageReader.java | 113 +- .../v2/service/channel/MessageUpdater.java | 120 +- .../v2/service/channel/Webhook.java | 296 ++-- .../v2/service/channel/WebhookCreator.java | 139 +- .../v2/service/channel/WebhookDeleter.java | 60 +- .../v2/service/channel/WebhookFetcher.java | 61 +- .../v2/service/channel/WebhookReader.java | 108 +- .../v2/service/channel/WebhookUpdater.java | 138 +- .../v2/service/user/UserBinding.java | 269 ++-- .../v2/service/user/UserBindingDeleter.java | 56 +- .../v2/service/user/UserBindingFetcher.java | 62 +- .../v2/service/user/UserBindingReader.java | 116 +- .../v2/service/user/UserChannel.java | 311 ++-- .../v2/service/user/UserChannelDeleter.java | 60 +- .../v2/service/user/UserChannelFetcher.java | 66 +- .../v2/service/user/UserChannelReader.java | 101 +- .../v2/service/user/UserChannelUpdater.java | 105 +- .../twilio/rest/lookups/v1/PhoneNumber.java | 140 +- .../rest/lookups/v1/PhoneNumberFetcher.java | 81 +- .../com/twilio/rest/lookups/v2/Bucket.java | 137 +- .../twilio/rest/lookups/v2/BucketDeleter.java | 39 +- .../twilio/rest/lookups/v2/BucketFetcher.java | 40 +- .../twilio/rest/lookups/v2/BucketUpdater.java | 44 +- .../rest/lookups/v2/LookupOverride.java | 369 +++-- .../lookups/v2/LookupOverrideCreator.java | 59 +- .../lookups/v2/LookupOverrideDeleter.java | 46 +- .../lookups/v2/LookupOverrideFetcher.java | 52 +- .../lookups/v2/LookupOverrideUpdater.java | 60 +- .../twilio/rest/lookups/v2/PhoneNumber.java | 371 +++-- .../rest/lookups/v2/PhoneNumberFetcher.java | 130 +- .../com/twilio/rest/lookups/v2/Query.java | 609 ++++---- .../twilio/rest/lookups/v2/QueryCreator.java | 32 +- .../com/twilio/rest/lookups/v2/RateLimit.java | 75 +- .../rest/lookups/v2/RateLimitFetcher.java | 44 +- .../rest/marketplace/v1/AvailableAddOn.java | 147 +- .../marketplace/v1/AvailableAddOnFetcher.java | 39 +- .../marketplace/v1/AvailableAddOnReader.java | 83 +- .../rest/marketplace/v1/InstalledAddOn.java | 212 ++- .../marketplace/v1/InstalledAddOnCreator.java | 83 +- .../marketplace/v1/InstalledAddOnDeleter.java | 33 +- .../marketplace/v1/InstalledAddOnFetcher.java | 39 +- .../marketplace/v1/InstalledAddOnReader.java | 83 +- .../marketplace/v1/InstalledAddOnUpdater.java | 55 +- .../rest/marketplace/v1/ModuleData.java | 192 ++- .../marketplace/v1/ModuleDataCreator.java | 46 +- .../marketplace/v1/ModuleDataFetcher.java | 35 +- .../marketplace/v1/ModuleDataManagement.java | 181 ++- .../v1/ModuleDataManagementFetcher.java | 39 +- .../v1/ModuleDataManagementUpdater.java | 88 +- .../marketplace/v1/ReferralConversion.java | 69 +- .../v1/ReferralConversionCreator.java | 49 +- .../AvailableAddOnExtension.java | 126 +- .../AvailableAddOnExtensionFetcher.java | 58 +- .../AvailableAddOnExtensionReader.java | 103 +- .../InstalledAddOnExtension.java | 156 +- .../InstalledAddOnExtensionFetcher.java | 58 +- .../InstalledAddOnExtensionReader.java | 103 +- .../InstalledAddOnExtensionUpdater.java | 67 +- .../installedaddon/InstalledAddOnUsage.java | 147 +- .../InstalledAddOnUsageCreator.java | 67 +- .../rest/messaging/v1/BrandRegistration.java | 633 ++++---- .../v1/BrandRegistrationCreator.java | 90 +- .../v1/BrandRegistrationFetcher.java | 39 +- .../messaging/v1/BrandRegistrationReader.java | 83 +- .../v1/BrandRegistrationUpdater.java | 40 +- .../rest/messaging/v1/Deactivations.java | 60 +- .../messaging/v1/DeactivationsFetcher.java | 48 +- .../twilio/rest/messaging/v1/DomainCerts.java | 182 ++- .../rest/messaging/v1/DomainCertsDeleter.java | 37 +- .../rest/messaging/v1/DomainCertsFetcher.java | 43 +- .../rest/messaging/v1/DomainCertsUpdater.java | 54 +- .../rest/messaging/v1/DomainConfig.java | 175 ++- .../messaging/v1/DomainConfigFetcher.java | 43 +- .../v1/DomainConfigMessagingService.java | 180 +-- .../DomainConfigMessagingServiceFetcher.java | 51 +- .../messaging/v1/DomainConfigUpdater.java | 78 +- .../rest/messaging/v1/ExternalCampaign.java | 114 +- .../messaging/v1/ExternalCampaignCreator.java | 63 +- .../v1/LinkshorteningMessagingService.java | 102 +- ...LinkshorteningMessagingServiceCreator.java | 67 +- ...LinkshorteningMessagingServiceDeleter.java | 56 +- ...ningMessagingServiceDomainAssociation.java | 91 +- ...sagingServiceDomainAssociationFetcher.java | 55 +- .../rest/messaging/v1/RequestManagedCert.java | 171 +-- .../v1/RequestManagedCertUpdater.java | 47 +- .../com/twilio/rest/messaging/v1/Service.java | 437 +++--- .../rest/messaging/v1/ServiceCreator.java | 155 +- .../rest/messaging/v1/ServiceDeleter.java | 33 +- .../rest/messaging/v1/ServiceFetcher.java | 34 +- .../rest/messaging/v1/ServiceReader.java | 83 +- .../rest/messaging/v1/ServiceUpdater.java | 158 +- .../messaging/v1/TollfreeVerification.java | 753 ++++------ .../v1/TollfreeVerificationCreator.java | 344 ++--- .../v1/TollfreeVerificationDeleter.java | 33 +- .../v1/TollfreeVerificationFetcher.java | 39 +- .../v1/TollfreeVerificationReader.java | 129 +- .../v1/TollfreeVerificationUpdater.java | 268 ++-- .../com/twilio/rest/messaging/v1/Usecase.java | 62 +- .../rest/messaging/v1/UsecaseFetcher.java | 30 +- .../BrandRegistrationOtp.java | 72 +- .../BrandRegistrationOtpCreator.java | 47 +- .../v1/brandregistration/BrandVetting.java | 236 ++- .../BrandVettingCreator.java | 64 +- .../BrandVettingFetcher.java | 56 +- .../brandregistration/BrandVettingReader.java | 96 +- .../messaging/v1/service/AlphaSender.java | 183 ++- .../v1/service/AlphaSenderCreator.java | 58 +- .../v1/service/AlphaSenderDeleter.java | 46 +- .../v1/service/AlphaSenderFetcher.java | 52 +- .../v1/service/AlphaSenderReader.java | 92 +- .../messaging/v1/service/ChannelSender.java | 196 ++- .../v1/service/ChannelSenderCreator.java | 54 +- .../v1/service/ChannelSenderDeleter.java | 46 +- .../v1/service/ChannelSenderFetcher.java | 52 +- .../v1/service/ChannelSenderReader.java | 92 +- .../v1/service/DestinationAlphaSender.java | 200 ++- .../DestinationAlphaSenderCreator.java | 74 +- .../DestinationAlphaSenderDeleter.java | 49 +- .../DestinationAlphaSenderFetcher.java | 55 +- .../service/DestinationAlphaSenderReader.java | 112 +- .../messaging/v1/service/PhoneNumber.java | 200 ++- .../v1/service/PhoneNumberCreator.java | 58 +- .../v1/service/PhoneNumberDeleter.java | 46 +- .../v1/service/PhoneNumberFetcher.java | 52 +- .../v1/service/PhoneNumberReader.java | 92 +- .../rest/messaging/v1/service/ShortCode.java | 196 ++- .../v1/service/ShortCodeCreator.java | 58 +- .../v1/service/ShortCodeDeleter.java | 43 +- .../v1/service/ShortCodeFetcher.java | 49 +- .../messaging/v1/service/ShortCodeReader.java | 92 +- .../messaging/v1/service/UsAppToPerson.java | 506 +++---- .../v1/service/UsAppToPersonCreator.java | 217 ++- .../v1/service/UsAppToPersonDeleter.java | 49 +- .../v1/service/UsAppToPersonFetcher.java | 55 +- .../v1/service/UsAppToPersonReader.java | 92 +- .../v1/service/UsAppToPersonUpdater.java | 150 +- .../v1/service/UsAppToPersonUsecase.java | 69 +- .../service/UsAppToPersonUsecaseFetcher.java | 59 +- .../rest/messaging/v2/ChannelsSender.java | 957 ++++++------ .../messaging/v2/ChannelsSenderCreator.java | 55 +- .../messaging/v2/ChannelsSenderDeleter.java | 33 +- .../messaging/v2/ChannelsSenderFetcher.java | 39 +- .../messaging/v2/ChannelsSenderReader.java | 86 +- .../messaging/v2/ChannelsSenderUpdater.java | 53 +- .../com/twilio/rest/monitor/v1/Alert.java | 279 ++-- .../twilio/rest/monitor/v1/AlertFetcher.java | 34 +- .../twilio/rest/monitor/v1/AlertReader.java | 100 +- .../com/twilio/rest/monitor/v1/Event.java | 216 ++- .../twilio/rest/monitor/v1/EventFetcher.java | 34 +- .../twilio/rest/monitor/v1/EventReader.java | 115 +- .../com/twilio/rest/notify/v1/Credential.java | 216 +-- .../rest/notify/v1/CredentialCreator.java | 68 +- .../rest/notify/v1/CredentialDeleter.java | 33 +- .../rest/notify/v1/CredentialFetcher.java | 39 +- .../rest/notify/v1/CredentialReader.java | 83 +- .../rest/notify/v1/CredentialUpdater.java | 71 +- .../com/twilio/rest/notify/v1/Service.java | 384 ++--- .../twilio/rest/notify/v1/ServiceCreator.java | 163 ++- .../twilio/rest/notify/v1/ServiceDeleter.java | 33 +- .../twilio/rest/notify/v1/ServiceFetcher.java | 34 +- .../twilio/rest/notify/v1/ServiceReader.java | 88 +- .../twilio/rest/notify/v1/ServiceUpdater.java | 168 +-- .../rest/notify/v1/service/Binding.java | 315 ++-- .../notify/v1/service/BindingCreator.java | 101 +- .../notify/v1/service/BindingDeleter.java | 43 +- .../notify/v1/service/BindingFetcher.java | 44 +- .../rest/notify/v1/service/BindingReader.java | 120 +- .../rest/notify/v1/service/Notification.java | 370 ++--- .../v1/service/NotificationCreator.java | 157 +- .../rest/numbers/v1/BulkEligibility.java | 139 +- .../numbers/v1/BulkEligibilityCreator.java | 33 +- .../numbers/v1/BulkEligibilityFetcher.java | 43 +- .../twilio/rest/numbers/v1/Eligibility.java | 49 +- .../rest/numbers/v1/EligibilityCreator.java | 33 +- .../twilio/rest/numbers/v1/PortingPortIn.java | 296 ++-- .../rest/numbers/v1/PortingPortInCreator.java | 33 +- .../rest/numbers/v1/PortingPortInDeleter.java | 37 +- .../rest/numbers/v1/PortingPortInFetcher.java | 43 +- .../numbers/v1/PortingPortInPhoneNumber.java | 316 ++-- .../v1/PortingPortInPhoneNumberDeleter.java | 56 +- .../v1/PortingPortInPhoneNumberFetcher.java | 62 +- .../rest/numbers/v1/PortingPortability.java | 217 ++- .../numbers/v1/PortingPortabilityFetcher.java | 63 +- .../v1/PortingWebhookConfiguration.java | 92 +- .../PortingWebhookConfigurationCreator.java | 40 +- .../v1/PortingWebhookConfigurationDelete.java | 95 +- ...tingWebhookConfigurationDeleteDeleter.java | 42 +- .../v1/SigningRequestConfiguration.java | 153 +- .../SigningRequestConfigurationCreator.java | 40 +- .../v1/SigningRequestConfigurationReader.java | 104 +- .../com/twilio/rest/numbers/v1/Webhook.java | 139 +- .../rest/numbers/v1/WebhookFetcher.java | 30 +- .../numbers/v2/AuthorizationDocument.java | 237 ++- .../v2/AuthorizationDocumentCreator.java | 122 +- .../v2/AuthorizationDocumentDeleter.java | 36 +- .../v2/AuthorizationDocumentFetcher.java | 42 +- .../v2/AuthorizationDocumentReader.java | 105 +- .../numbers/v2/BulkHostedNumberOrder.java | 206 ++- .../v2/BulkHostedNumberOrderCreator.java | 36 +- .../v2/BulkHostedNumberOrderFetcher.java | 59 +- .../twilio/rest/numbers/v2/BundleClone.java | 243 ++-- .../rest/numbers/v2/BundleCloneCreator.java | 72 +- .../rest/numbers/v2/HostedNumberOrder.java | 536 +++---- .../numbers/v2/HostedNumberOrderCreator.java | 196 ++- .../numbers/v2/HostedNumberOrderDeleter.java | 33 +- .../numbers/v2/HostedNumberOrderFetcher.java | 39 +- .../numbers/v2/HostedNumberOrderReader.java | 126 +- .../numbers/v2/HostedNumberOrderUpdater.java | 78 +- .../DependentHostedNumberOrder.java | 372 ++--- .../DependentHostedNumberOrderReader.java | 150 +- .../v2/regulatorycompliance/Bundle.java | 405 +++--- .../regulatorycompliance/BundleCreator.java | 78 +- .../regulatorycompliance/BundleDeleter.java | 33 +- .../regulatorycompliance/BundleFetcher.java | 34 +- .../v2/regulatorycompliance/BundleReader.java | 172 ++- .../regulatorycompliance/BundleUpdater.java | 60 +- .../v2/regulatorycompliance/EndUser.java | 221 ++- .../regulatorycompliance/EndUserCreator.java | 53 +- .../regulatorycompliance/EndUserDeleter.java | 33 +- .../regulatorycompliance/EndUserFetcher.java | 34 +- .../regulatorycompliance/EndUserReader.java | 83 +- .../v2/regulatorycompliance/EndUserType.java | 113 +- .../EndUserTypeFetcher.java | 39 +- .../EndUserTypeReader.java | 83 +- .../regulatorycompliance/EndUserUpdater.java | 50 +- .../v2/regulatorycompliance/Regulation.java | 176 ++- .../RegulationFetcher.java | 55 +- .../RegulationReader.java | 114 +- .../SupportingDocument.java | 281 ++-- .../SupportingDocumentCreator.java | 67 +- .../SupportingDocumentDeleter.java | 33 +- .../SupportingDocumentFetcher.java | 39 +- .../SupportingDocumentReader.java | 83 +- .../SupportingDocumentType.java | 113 +- .../SupportingDocumentTypeFetcher.java | 42 +- .../SupportingDocumentTypeReader.java | 94 +- .../SupportingDocumentUpdater.java | 59 +- .../bundle/BundleCopy.java | 236 ++- .../bundle/BundleCopyCreator.java | 50 +- .../bundle/BundleCopyReader.java | 92 +- .../bundle/Evaluation.java | 208 ++- .../bundle/EvaluationCreator.java | 47 +- .../bundle/EvaluationFetcher.java | 52 +- .../bundle/EvaluationReader.java | 95 +- .../bundle/ItemAssignment.java | 156 +- .../bundle/ItemAssignmentCreator.java | 57 +- .../bundle/ItemAssignmentDeleter.java | 49 +- .../bundle/ItemAssignmentFetcher.java | 55 +- .../bundle/ItemAssignmentReader.java | 95 +- .../bundle/ReplaceItems.java | 232 ++- .../bundle/ReplaceItemsCreator.java | 61 +- .../rest/numbers/v3/HostedNumberOrder.java | 340 +++++ .../numbers/v3/HostedNumberOrderCreator.java | 291 ++++ .../com/twilio/rest/oauth/v1/Authorize.java | 60 +- .../rest/oauth/v1/AuthorizeFetcher.java | 71 +- .../java/com/twilio/rest/oauth/v1/Token.java | 111 +- .../twilio/rest/oauth/v1/TokenCreator.java | 75 +- .../java/com/twilio/rest/oauth/v2/Token.java | 155 ++ .../twilio/rest/oauth/v2/TokenCreator.java | 173 +++ .../hostedNumbers/AuthorizationDocument.java | 239 ++- .../AuthorizationDocumentCreator.java | 119 +- .../AuthorizationDocumentFetcher.java | 42 +- .../AuthorizationDocumentReader.java | 105 +- .../AuthorizationDocumentUpdater.java | 111 +- .../hostedNumbers/HostedNumberOrder.java | 504 +++---- .../HostedNumberOrderCreator.java | 196 ++- .../HostedNumberOrderDeleter.java | 33 +- .../HostedNumberOrderFetcher.java | 39 +- .../HostedNumberOrderReader.java | 122 +- .../HostedNumberOrderUpdater.java | 115 +- .../DependentHostedNumberOrder.java | 472 +++--- .../DependentHostedNumberOrderReader.java | 159 +- .../preview/marketplace/AvailableAddOn.java | 147 +- .../marketplace/AvailableAddOnFetcher.java | 39 +- .../marketplace/AvailableAddOnReader.java | 83 +- .../preview/marketplace/InstalledAddOn.java | 212 ++- .../marketplace/InstalledAddOnCreator.java | 83 +- .../marketplace/InstalledAddOnDeleter.java | 33 +- .../marketplace/InstalledAddOnFetcher.java | 39 +- .../marketplace/InstalledAddOnReader.java | 83 +- .../marketplace/InstalledAddOnUpdater.java | 55 +- .../AvailableAddOnExtension.java | 126 +- .../AvailableAddOnExtensionFetcher.java | 58 +- .../AvailableAddOnExtensionReader.java | 106 +- .../InstalledAddOnExtension.java | 156 +- .../InstalledAddOnExtensionFetcher.java | 58 +- .../InstalledAddOnExtensionReader.java | 106 +- .../InstalledAddOnExtensionUpdater.java | 67 +- .../twilio/rest/preview/wireless/Command.java | 202 ++- .../rest/preview/wireless/CommandCreator.java | 68 +- .../rest/preview/wireless/CommandFetcher.java | 34 +- .../rest/preview/wireless/CommandReader.java | 103 +- .../rest/preview/wireless/RatePlan.java | 266 ++-- .../preview/wireless/RatePlanCreator.java | 110 +- .../preview/wireless/RatePlanDeleter.java | 33 +- .../preview/wireless/RatePlanFetcher.java | 39 +- .../rest/preview/wireless/RatePlanReader.java | 83 +- .../preview/wireless/RatePlanUpdater.java | 51 +- .../com/twilio/rest/preview/wireless/Sim.java | 355 ++--- .../rest/preview/wireless/SimFetcher.java | 34 +- .../rest/preview/wireless/SimReader.java | 108 +- .../rest/preview/wireless/SimUpdater.java | 155 +- .../rest/preview/wireless/sim/Usage.java | 168 +-- .../preview/wireless/sim/UsageFetcher.java | 48 +- .../previewiam/organizations/Account.java | 162 +-- .../organizations/AccountFetcher.java | 55 +- .../organizations/AccountReader.java | 101 +- .../organizations/RoleAssignment.java | 152 +- .../organizations/RoleAssignmentCreator.java | 76 +- .../organizations/RoleAssignmentDeleter.java | 59 +- .../organizations/RoleAssignmentReader.java | 121 +- .../rest/previewiam/organizations/User.java | 387 +++-- .../previewiam/organizations/UserCreator.java | 52 +- .../previewiam/organizations/UserDeleter.java | 52 +- .../previewiam/organizations/UserFetcher.java | 53 +- .../previewiam/organizations/UserReader.java | 103 +- .../previewiam/organizations/UserUpdater.java | 81 +- .../twilio/rest/previewiam/v1/Authorize.java | 60 +- .../rest/previewiam/v1/AuthorizeFetcher.java | 71 +- .../com/twilio/rest/previewiam/v1/Token.java | 111 +- .../rest/previewiam/v1/TokenCreator.java | 78 +- .../rest/pricing/v1/messaging/Country.java | 128 +- .../pricing/v1/messaging/CountryFetcher.java | 38 +- .../pricing/v1/messaging/CountryReader.java | 83 +- .../rest/pricing/v1/phonenumber/Country.java | 111 +- .../v1/phonenumber/CountryFetcher.java | 38 +- .../pricing/v1/phonenumber/CountryReader.java | 83 +- .../twilio/rest/pricing/v1/voice/Country.java | 128 +- .../rest/pricing/v1/voice/CountryFetcher.java | 38 +- .../rest/pricing/v1/voice/CountryReader.java | 83 +- .../twilio/rest/pricing/v1/voice/Number.java | 140 +- .../rest/pricing/v1/voice/NumberFetcher.java | 34 +- .../com/twilio/rest/pricing/v2/Country.java | 136 +- .../rest/pricing/v2/CountryFetcher.java | 38 +- .../twilio/rest/pricing/v2/CountryReader.java | 83 +- .../com/twilio/rest/pricing/v2/Number.java | 164 +-- .../twilio/rest/pricing/v2/NumberFetcher.java | 59 +- .../twilio/rest/pricing/v2/voice/Country.java | 128 +- .../rest/pricing/v2/voice/CountryFetcher.java | 38 +- .../rest/pricing/v2/voice/CountryReader.java | 83 +- .../twilio/rest/pricing/v2/voice/Number.java | 159 +- .../rest/pricing/v2/voice/NumberFetcher.java | 59 +- .../com/twilio/rest/proxy/v1/Service.java | 352 +++-- .../twilio/rest/proxy/v1/ServiceCreator.java | 111 +- .../twilio/rest/proxy/v1/ServiceDeleter.java | 33 +- .../twilio/rest/proxy/v1/ServiceFetcher.java | 34 +- .../twilio/rest/proxy/v1/ServiceReader.java | 83 +- .../twilio/rest/proxy/v1/ServiceUpdater.java | 117 +- .../rest/proxy/v1/service/PhoneNumber.java | 250 ++-- .../proxy/v1/service/PhoneNumberCreator.java | 63 +- .../proxy/v1/service/PhoneNumberDeleter.java | 46 +- .../proxy/v1/service/PhoneNumberFetcher.java | 52 +- .../proxy/v1/service/PhoneNumberReader.java | 92 +- .../proxy/v1/service/PhoneNumberUpdater.java | 59 +- .../twilio/rest/proxy/v1/service/Session.java | 397 +++-- .../rest/proxy/v1/service/SessionCreator.java | 80 +- .../rest/proxy/v1/service/SessionDeleter.java | 43 +- .../rest/proxy/v1/service/SessionFetcher.java | 44 +- .../rest/proxy/v1/service/SessionReader.java | 92 +- .../rest/proxy/v1/service/SessionUpdater.java | 65 +- .../proxy/v1/service/session/Interaction.java | 446 +++--- .../service/session/InteractionDeleter.java | 60 +- .../service/session/InteractionFetcher.java | 66 +- .../v1/service/session/InteractionReader.java | 108 +- .../proxy/v1/service/session/Participant.java | 258 ++-- .../service/session/ParticipantCreator.java | 88 +- .../service/session/ParticipantDeleter.java | 60 +- .../service/session/ParticipantFetcher.java | 66 +- .../v1/service/session/ParticipantReader.java | 108 +- .../participant/MessageInteraction.java | 479 +++--- .../MessageInteractionCreator.java | 103 +- .../MessageInteractionFetcher.java | 77 +- .../participant/MessageInteractionReader.java | 119 +- .../twilio/rest/routes/v2/PhoneNumber.java | 164 +-- .../rest/routes/v2/PhoneNumberFetcher.java | 43 +- .../rest/routes/v2/PhoneNumberUpdater.java | 55 +- .../com/twilio/rest/routes/v2/SipDomain.java | 164 +-- .../rest/routes/v2/SipDomainFetcher.java | 43 +- .../rest/routes/v2/SipDomainUpdater.java | 55 +- .../java/com/twilio/rest/routes/v2/Trunk.java | 164 +-- .../twilio/rest/routes/v2/TrunkFetcher.java | 38 +- .../twilio/rest/routes/v2/TrunkUpdater.java | 50 +- .../twilio/rest/serverless/v1/Service.java | 224 ++- .../rest/serverless/v1/ServiceCreator.java | 61 +- .../rest/serverless/v1/ServiceDeleter.java | 33 +- .../rest/serverless/v1/ServiceFetcher.java | 34 +- .../rest/serverless/v1/ServiceReader.java | 83 +- .../rest/serverless/v1/ServiceUpdater.java | 58 +- .../rest/serverless/v1/service/Asset.java | 197 ++- .../serverless/v1/service/AssetCreator.java | 53 +- .../serverless/v1/service/AssetDeleter.java | 43 +- .../serverless/v1/service/AssetFetcher.java | 44 +- .../serverless/v1/service/AssetReader.java | 92 +- .../serverless/v1/service/AssetUpdater.java | 60 +- .../rest/serverless/v1/service/Build.java | 336 ++--- .../serverless/v1/service/BuildCreator.java | 69 +- .../serverless/v1/service/BuildDeleter.java | 43 +- .../serverless/v1/service/BuildFetcher.java | 44 +- .../serverless/v1/service/BuildReader.java | 92 +- .../serverless/v1/service/Environment.java | 227 ++- .../v1/service/EnvironmentCreator.java | 60 +- .../v1/service/EnvironmentDeleter.java | 46 +- .../v1/service/EnvironmentFetcher.java | 52 +- .../v1/service/EnvironmentReader.java | 92 +- .../rest/serverless/v1/service/Function.java | 197 ++- .../v1/service/FunctionCreator.java | 58 +- .../v1/service/FunctionDeleter.java | 43 +- .../v1/service/FunctionFetcher.java | 49 +- .../serverless/v1/service/FunctionReader.java | 92 +- .../v1/service/FunctionUpdater.java | 65 +- .../v1/service/asset/AssetVersion.java | 205 ++- .../v1/service/asset/AssetVersionFetcher.java | 63 +- .../v1/service/asset/AssetVersionReader.java | 102 +- .../v1/service/build/BuildStatus.java | 144 +- .../v1/service/build/BuildStatusFetcher.java | 52 +- .../v1/service/environment/Deployment.java | 177 +-- .../environment/DeploymentCreator.java | 71 +- .../environment/DeploymentFetcher.java | 66 +- .../service/environment/DeploymentReader.java | 108 +- .../v1/service/environment/Log.java | 214 ++- .../v1/service/environment/LogFetcher.java | 61 +- .../v1/service/environment/LogReader.java | 125 +- .../v1/service/environment/Variable.java | 217 ++- .../service/environment/VariableCreator.java | 75 +- .../service/environment/VariableDeleter.java | 60 +- .../service/environment/VariableFetcher.java | 66 +- .../service/environment/VariableReader.java | 108 +- .../service/environment/VariableUpdater.java | 78 +- .../v1/service/function/FunctionVersion.java | 221 ++- .../function/FunctionVersionFetcher.java | 66 +- .../function/FunctionVersionReader.java | 108 +- .../FunctionVersionContent.java | 127 +- .../FunctionVersionContentFetcher.java | 69 +- .../java/com/twilio/rest/studio/v1/Flow.java | 218 ++- .../twilio/rest/studio/v1/FlowDeleter.java | 33 +- .../twilio/rest/studio/v1/FlowFetcher.java | 34 +- .../com/twilio/rest/studio/v1/FlowReader.java | 83 +- .../rest/studio/v1/flow/Engagement.java | 268 ++-- .../studio/v1/flow/EngagementCreator.java | 65 +- .../studio/v1/flow/EngagementDeleter.java | 39 +- .../studio/v1/flow/EngagementFetcher.java | 45 +- .../rest/studio/v1/flow/EngagementReader.java | 88 +- .../twilio/rest/studio/v1/flow/Execution.java | 279 ++-- .../rest/studio/v1/flow/ExecutionCreator.java | 65 +- .../rest/studio/v1/flow/ExecutionDeleter.java | 39 +- .../rest/studio/v1/flow/ExecutionFetcher.java | 45 +- .../rest/studio/v1/flow/ExecutionReader.java | 107 +- .../rest/studio/v1/flow/ExecutionUpdater.java | 57 +- .../v1/flow/engagement/EngagementContext.java | 105 +- .../engagement/EngagementContextFetcher.java | 52 +- .../rest/studio/v1/flow/engagement/Step.java | 242 ++-- .../v1/flow/engagement/StepFetcher.java | 57 +- .../studio/v1/flow/engagement/StepReader.java | 101 +- .../v1/flow/engagement/step/StepContext.java | 119 +- .../engagement/step/StepContextFetcher.java | 62 +- .../v1/flow/execution/ExecutionContext.java | 109 +- .../execution/ExecutionContextFetcher.java | 52 +- .../v1/flow/execution/ExecutionStep.java | 246 ++-- .../flow/execution/ExecutionStepFetcher.java | 62 +- .../flow/execution/ExecutionStepReader.java | 101 +- .../executionstep/ExecutionStepContext.java | 119 +- .../ExecutionStepContextFetcher.java | 62 +- .../java/com/twilio/rest/studio/v2/Flow.java | 323 ++--- .../twilio/rest/studio/v2/FlowCreator.java | 66 +- .../twilio/rest/studio/v2/FlowDeleter.java | 33 +- .../twilio/rest/studio/v2/FlowFetcher.java | 34 +- .../com/twilio/rest/studio/v2/FlowReader.java | 83 +- .../twilio/rest/studio/v2/FlowUpdater.java | 61 +- .../twilio/rest/studio/v2/FlowValidate.java | 103 +- .../rest/studio/v2/FlowValidateUpdater.java | 70 +- .../twilio/rest/studio/v2/flow/Execution.java | 264 ++-- .../rest/studio/v2/flow/ExecutionCreator.java | 65 +- .../rest/studio/v2/flow/ExecutionDeleter.java | 39 +- .../rest/studio/v2/flow/ExecutionFetcher.java | 45 +- .../rest/studio/v2/flow/ExecutionReader.java | 107 +- .../rest/studio/v2/flow/ExecutionUpdater.java | 57 +- .../rest/studio/v2/flow/FlowRevision.java | 260 ++-- .../studio/v2/flow/FlowRevisionFetcher.java | 49 +- .../studio/v2/flow/FlowRevisionReader.java | 88 +- .../rest/studio/v2/flow/FlowTestUser.java | 88 +- .../studio/v2/flow/FlowTestUserFetcher.java | 39 +- .../studio/v2/flow/FlowTestUserUpdater.java | 52 +- .../v2/flow/execution/ExecutionContext.java | 109 +- .../execution/ExecutionContextFetcher.java | 52 +- .../v2/flow/execution/ExecutionStep.java | 246 ++-- .../flow/execution/ExecutionStepFetcher.java | 62 +- .../flow/execution/ExecutionStepReader.java | 101 +- .../executionstep/ExecutionStepContext.java | 119 +- .../ExecutionStepContextFetcher.java | 62 +- .../twilio/rest/supersim/v1/EsimProfile.java | 294 ++-- .../rest/supersim/v1/EsimProfileCreator.java | 67 +- .../rest/supersim/v1/EsimProfileFetcher.java | 39 +- .../rest/supersim/v1/EsimProfileReader.java | 98 +- .../com/twilio/rest/supersim/v1/Fleet.java | 307 ++-- .../twilio/rest/supersim/v1/FleetCreator.java | 105 +- .../twilio/rest/supersim/v1/FleetFetcher.java | 34 +- .../twilio/rest/supersim/v1/FleetReader.java | 92 +- .../twilio/rest/supersim/v1/FleetUpdater.java | 91 +- .../twilio/rest/supersim/v1/IpCommand.java | 361 +++-- .../rest/supersim/v1/IpCommandCreator.java | 81 +- .../rest/supersim/v1/IpCommandFetcher.java | 39 +- .../rest/supersim/v1/IpCommandReader.java | 103 +- .../com/twilio/rest/supersim/v1/Network.java | 117 +- .../supersim/v1/NetworkAccessProfile.java | 158 +- .../v1/NetworkAccessProfileCreator.java | 52 +- .../v1/NetworkAccessProfileFetcher.java | 39 +- .../v1/NetworkAccessProfileReader.java | 87 +- .../v1/NetworkAccessProfileUpdater.java | 46 +- .../rest/supersim/v1/NetworkFetcher.java | 34 +- .../rest/supersim/v1/NetworkReader.java | 98 +- .../rest/supersim/v1/SettingsUpdate.java | 200 ++- .../supersim/v1/SettingsUpdateReader.java | 93 +- .../java/com/twilio/rest/supersim/v1/Sim.java | 291 ++-- .../twilio/rest/supersim/v1/SimCreator.java | 43 +- .../twilio/rest/supersim/v1/SimFetcher.java | 34 +- .../twilio/rest/supersim/v1/SimReader.java | 98 +- .../twilio/rest/supersim/v1/SimUpdater.java | 70 +- .../twilio/rest/supersim/v1/SmsCommand.java | 266 ++-- .../rest/supersim/v1/SmsCommandCreator.java | 63 +- .../rest/supersim/v1/SmsCommandFetcher.java | 39 +- .../rest/supersim/v1/SmsCommandReader.java | 98 +- .../twilio/rest/supersim/v1/UsageRecord.java | 281 ++-- .../rest/supersim/v1/UsageRecordReader.java | 129 +- .../NetworkAccessProfileNetwork.java | 169 +-- .../NetworkAccessProfileNetworkCreator.java | 60 +- .../NetworkAccessProfileNetworkDeleter.java | 52 +- .../NetworkAccessProfileNetworkFetcher.java | 58 +- .../NetworkAccessProfileNetworkReader.java | 108 +- .../rest/supersim/v1/sim/BillingPeriod.java | 198 ++- .../supersim/v1/sim/BillingPeriodReader.java | 88 +- .../rest/supersim/v1/sim/SimIpAddress.java | 107 +- .../supersim/v1/sim/SimIpAddressReader.java | 88 +- .../java/com/twilio/rest/sync/v1/Service.java | 282 ++-- .../twilio/rest/sync/v1/ServiceCreator.java | 99 +- .../twilio/rest/sync/v1/ServiceDeleter.java | 33 +- .../twilio/rest/sync/v1/ServiceFetcher.java | 34 +- .../twilio/rest/sync/v1/ServiceReader.java | 83 +- .../twilio/rest/sync/v1/ServiceUpdater.java | 103 +- .../twilio/rest/sync/v1/service/Document.java | 256 ++-- .../rest/sync/v1/service/DocumentCreator.java | 62 +- .../rest/sync/v1/service/DocumentDeleter.java | 43 +- .../rest/sync/v1/service/DocumentFetcher.java | 49 +- .../rest/sync/v1/service/DocumentReader.java | 92 +- .../rest/sync/v1/service/DocumentUpdater.java | 77 +- .../twilio/rest/sync/v1/service/SyncList.java | 241 ++- .../rest/sync/v1/service/SyncListCreator.java | 60 +- .../rest/sync/v1/service/SyncListDeleter.java | 43 +- .../rest/sync/v1/service/SyncListFetcher.java | 49 +- .../rest/sync/v1/service/SyncListReader.java | 92 +- .../rest/sync/v1/service/SyncListUpdater.java | 61 +- .../twilio/rest/sync/v1/service/SyncMap.java | 241 ++- .../rest/sync/v1/service/SyncMapCreator.java | 55 +- .../rest/sync/v1/service/SyncMapDeleter.java | 43 +- .../rest/sync/v1/service/SyncMapFetcher.java | 44 +- .../rest/sync/v1/service/SyncMapReader.java | 92 +- .../rest/sync/v1/service/SyncMapUpdater.java | 56 +- .../rest/sync/v1/service/SyncStream.java | 226 ++- .../sync/v1/service/SyncStreamCreator.java | 55 +- .../sync/v1/service/SyncStreamDeleter.java | 46 +- .../sync/v1/service/SyncStreamFetcher.java | 52 +- .../sync/v1/service/SyncStreamReader.java | 92 +- .../sync/v1/service/SyncStreamUpdater.java | 59 +- .../service/document/DocumentPermission.java | 187 +-- .../document/DocumentPermissionDeleter.java | 61 +- .../document/DocumentPermissionFetcher.java | 67 +- .../document/DocumentPermissionReader.java | 108 +- .../document/DocumentPermissionUpdater.java | 90 +- .../v1/service/synclist/SyncListItem.java | 329 ++--- .../service/synclist/SyncListItemCreator.java | 78 +- .../service/synclist/SyncListItemDeleter.java | 60 +- .../service/synclist/SyncListItemFetcher.java | 59 +- .../service/synclist/SyncListItemReader.java | 124 +- .../service/synclist/SyncListItemUpdater.java | 97 +- .../service/synclist/SyncListPermission.java | 191 +-- .../synclist/SyncListPermissionDeleter.java | 57 +- .../synclist/SyncListPermissionFetcher.java | 63 +- .../synclist/SyncListPermissionReader.java | 101 +- .../synclist/SyncListPermissionUpdater.java | 86 +- .../sync/v1/service/syncmap/SyncMapItem.java | 330 ++--- .../service/syncmap/SyncMapItemCreator.java | 85 +- .../service/syncmap/SyncMapItemDeleter.java | 60 +- .../service/syncmap/SyncMapItemFetcher.java | 59 +- .../v1/service/syncmap/SyncMapItemReader.java | 124 +- .../service/syncmap/SyncMapItemUpdater.java | 97 +- .../v1/service/syncmap/SyncMapPermission.java | 191 +-- .../syncmap/SyncMapPermissionDeleter.java | 57 +- .../syncmap/SyncMapPermissionFetcher.java | 63 +- .../syncmap/SyncMapPermissionReader.java | 101 +- .../syncmap/SyncMapPermissionUpdater.java | 86 +- .../v1/service/syncstream/StreamMessage.java | 77 +- .../syncstream/StreamMessageCreator.java | 67 +- .../twilio/rest/taskrouter/v1/Workspace.java | 290 ++-- .../rest/taskrouter/v1/WorkspaceCreator.java | 89 +- .../rest/taskrouter/v1/WorkspaceDeleter.java | 33 +- .../rest/taskrouter/v1/WorkspaceFetcher.java | 39 +- .../rest/taskrouter/v1/WorkspaceReader.java | 88 +- .../rest/taskrouter/v1/WorkspaceUpdater.java | 105 +- .../taskrouter/v1/workspace/Activity.java | 201 ++- .../v1/workspace/ActivityCreator.java | 63 +- .../v1/workspace/ActivityDeleter.java | 46 +- .../v1/workspace/ActivityFetcher.java | 52 +- .../v1/workspace/ActivityReader.java | 102 +- .../v1/workspace/ActivityUpdater.java | 59 +- .../rest/taskrouter/v1/workspace/Event.java | 251 ++-- .../taskrouter/v1/workspace/EventFetcher.java | 44 +- .../taskrouter/v1/workspace/EventReader.java | 149 +- .../rest/taskrouter/v1/workspace/Task.java | 458 +++--- .../taskrouter/v1/workspace/TaskChannel.java | 222 ++- .../v1/workspace/TaskChannelCreator.java | 78 +- .../v1/workspace/TaskChannelDeleter.java | 46 +- .../v1/workspace/TaskChannelFetcher.java | 52 +- .../v1/workspace/TaskChannelReader.java | 92 +- .../v1/workspace/TaskChannelUpdater.java | 71 +- .../taskrouter/v1/workspace/TaskCreator.java | 93 +- .../taskrouter/v1/workspace/TaskDeleter.java | 50 +- .../taskrouter/v1/workspace/TaskFetcher.java | 44 +- .../taskrouter/v1/workspace/TaskQueue.java | 328 ++--- .../v1/workspace/TaskQueueCreator.java | 104 +- .../v1/workspace/TaskQueueDeleter.java | 46 +- .../v1/workspace/TaskQueueFetcher.java | 52 +- .../v1/workspace/TaskQueueReader.java | 119 +- .../v1/workspace/TaskQueueUpdater.java | 105 +- .../taskrouter/v1/workspace/TaskReader.java | 151 +- .../taskrouter/v1/workspace/TaskUpdater.java | 102 +- .../rest/taskrouter/v1/workspace/Worker.java | 249 ++-- .../v1/workspace/WorkerCreator.java | 63 +- .../v1/workspace/WorkerDeleter.java | 50 +- .../v1/workspace/WorkerFetcher.java | 44 +- .../taskrouter/v1/workspace/WorkerReader.java | 139 +- .../v1/workspace/WorkerUpdater.java | 88 +- .../taskrouter/v1/workspace/Workflow.java | 261 ++-- .../v1/workspace/WorkflowCreator.java | 120 +- .../v1/workspace/WorkflowDeleter.java | 46 +- .../v1/workspace/WorkflowFetcher.java | 52 +- .../v1/workspace/WorkflowReader.java | 97 +- .../v1/workspace/WorkflowUpdater.java | 119 +- .../WorkspaceCumulativeStatistics.java | 364 ++--- .../WorkspaceCumulativeStatisticsFetcher.java | 97 +- .../WorkspaceRealTimeStatistics.java | 197 +-- .../WorkspaceRealTimeStatisticsFetcher.java | 59 +- .../v1/workspace/WorkspaceStatistics.java | 116 +- .../workspace/WorkspaceStatisticsFetcher.java | 82 +- .../v1/workspace/task/Reservation.java | 389 +++-- .../v1/workspace/task/ReservationFetcher.java | 62 +- .../v1/workspace/task/ReservationReader.java | 121 +- .../v1/workspace/task/ReservationUpdater.java | 565 ++++---- .../TaskQueueBulkRealTimeStatistics.java | 117 +- ...askQueueBulkRealTimeStatisticsCreator.java | 60 +- .../TaskQueueCumulativeStatistics.java | 381 ++--- .../TaskQueueCumulativeStatisticsFetcher.java | 113 +- .../TaskQueueRealTimeStatistics.java | 266 ++-- .../TaskQueueRealTimeStatisticsFetcher.java | 75 +- .../taskqueue/TaskQueueStatistics.java | 123 +- .../taskqueue/TaskQueueStatisticsFetcher.java | 98 +- .../taskqueue/TaskQueuesStatistics.java | 108 +- .../taskqueue/TaskQueuesStatisticsReader.java | 140 +- .../v1/workspace/worker/Reservation.java | 353 +++-- .../workspace/worker/ReservationFetcher.java | 66 +- .../workspace/worker/ReservationReader.java | 120 +- .../workspace/worker/ReservationUpdater.java | 555 ++++--- .../v1/workspace/worker/WorkerChannel.java | 235 ++- .../worker/WorkerChannelFetcher.java | 66 +- .../workspace/worker/WorkerChannelReader.java | 108 +- .../worker/WorkerChannelUpdater.java | 78 +- .../v1/workspace/worker/WorkerStatistics.java | 111 +- .../worker/WorkerStatisticsFetcher.java | 85 +- .../worker/WorkersCumulativeStatistics.java | 234 ++- .../WorkersCumulativeStatisticsFetcher.java | 91 +- .../worker/WorkersRealTimeStatistics.java | 122 +- .../WorkersRealTimeStatisticsFetcher.java | 62 +- .../workspace/worker/WorkersStatistics.java | 116 +- .../worker/WorkersStatisticsFetcher.java | 92 +- .../WorkflowCumulativeStatistics.java | 379 ++--- .../WorkflowCumulativeStatisticsFetcher.java | 113 +- .../workflow/WorkflowRealTimeStatistics.java | 182 +-- .../WorkflowRealTimeStatisticsFetcher.java | 75 +- .../workflow/WorkflowStatistics.java | 124 +- .../workflow/WorkflowStatisticsFetcher.java | 98 +- .../com/twilio/rest/trunking/v1/Trunk.java | 404 +++--- .../twilio/rest/trunking/v1/TrunkCreator.java | 104 +- .../twilio/rest/trunking/v1/TrunkDeleter.java | 33 +- .../twilio/rest/trunking/v1/TrunkFetcher.java | 34 +- .../twilio/rest/trunking/v1/TrunkReader.java | 83 +- .../twilio/rest/trunking/v1/TrunkUpdater.java | 108 +- .../trunking/v1/trunk/CredentialList.java | 168 ++- .../v1/trunk/CredentialListCreator.java | 59 +- .../v1/trunk/CredentialListDeleter.java | 43 +- .../v1/trunk/CredentialListFetcher.java | 49 +- .../v1/trunk/CredentialListReader.java | 89 +- .../v1/trunk/IpAccessControlList.java | 167 +-- .../v1/trunk/IpAccessControlListCreator.java | 62 +- .../v1/trunk/IpAccessControlListDeleter.java | 43 +- .../v1/trunk/IpAccessControlListFetcher.java | 49 +- .../v1/trunk/IpAccessControlListReader.java | 93 +- .../trunking/v1/trunk/OriginationUrl.java | 241 ++- .../v1/trunk/OriginationUrlCreator.java | 88 +- .../v1/trunk/OriginationUrlDeleter.java | 43 +- .../v1/trunk/OriginationUrlFetcher.java | 49 +- .../v1/trunk/OriginationUrlReader.java | 89 +- .../v1/trunk/OriginationUrlUpdater.java | 80 +- .../rest/trunking/v1/trunk/PhoneNumber.java | 421 +++--- .../trunking/v1/trunk/PhoneNumberCreator.java | 55 +- .../trunking/v1/trunk/PhoneNumberDeleter.java | 40 +- .../trunking/v1/trunk/PhoneNumberFetcher.java | 46 +- .../trunking/v1/trunk/PhoneNumberReader.java | 89 +- .../rest/trunking/v1/trunk/Recording.java | 157 +- .../trunking/v1/trunk/RecordingFetcher.java | 40 +- .../trunking/v1/trunk/RecordingUpdater.java | 52 +- .../rest/trusthub/v1/ComplianceInquiries.java | 103 +- .../v1/ComplianceInquiriesCreator.java | 60 +- .../v1/ComplianceInquiriesUpdater.java | 70 +- .../v1/ComplianceRegistrationInquiries.java | 288 ++-- ...omplianceRegistrationInquiriesCreator.java | 466 +++--- ...omplianceRegistrationInquiriesUpdater.java | 77 +- .../v1/ComplianceTollfreeInquiries.java | 144 +- .../ComplianceTollfreeInquiriesCreator.java | 313 ++-- .../rest/trusthub/v1/CustomerProfiles.java | 299 ++-- .../trusthub/v1/CustomerProfilesCreator.java | 72 +- .../trusthub/v1/CustomerProfilesDeleter.java | 33 +- .../trusthub/v1/CustomerProfilesFetcher.java | 39 +- .../trusthub/v1/CustomerProfilesReader.java | 102 +- .../trusthub/v1/CustomerProfilesUpdater.java | 71 +- .../com/twilio/rest/trusthub/v1/EndUser.java | 184 ++- .../rest/trusthub/v1/EndUserCreator.java | 53 +- .../rest/trusthub/v1/EndUserDeleter.java | 33 +- .../rest/trusthub/v1/EndUserFetcher.java | 34 +- .../rest/trusthub/v1/EndUserReader.java | 83 +- .../twilio/rest/trusthub/v1/EndUserType.java | 113 +- .../rest/trusthub/v1/EndUserTypeFetcher.java | 39 +- .../rest/trusthub/v1/EndUserTypeReader.java | 83 +- .../rest/trusthub/v1/EndUserUpdater.java | 50 +- .../com/twilio/rest/trusthub/v1/Policies.java | 101 +- .../rest/trusthub/v1/PoliciesFetcher.java | 39 +- .../rest/trusthub/v1/PoliciesReader.java | 83 +- .../rest/trusthub/v1/SupportingDocument.java | 251 ++-- .../v1/SupportingDocumentCreator.java | 67 +- .../v1/SupportingDocumentDeleter.java | 33 +- .../v1/SupportingDocumentFetcher.java | 39 +- .../trusthub/v1/SupportingDocumentReader.java | 83 +- .../trusthub/v1/SupportingDocumentType.java | 113 +- .../v1/SupportingDocumentTypeFetcher.java | 42 +- .../v1/SupportingDocumentTypeReader.java | 94 +- .../v1/SupportingDocumentUpdater.java | 59 +- .../rest/trusthub/v1/TrustProducts.java | 299 ++-- .../trusthub/v1/TrustProductsCreator.java | 70 +- .../trusthub/v1/TrustProductsDeleter.java | 33 +- .../trusthub/v1/TrustProductsFetcher.java | 39 +- .../rest/trusthub/v1/TrustProductsReader.java | 98 +- .../trusthub/v1/TrustProductsUpdater.java | 65 +- ...omerProfilesChannelEndpointAssignment.java | 181 +-- ...filesChannelEndpointAssignmentCreator.java | 89 +- ...filesChannelEndpointAssignmentDeleter.java | 52 +- ...filesChannelEndpointAssignmentFetcher.java | 62 +- ...ofilesChannelEndpointAssignmentReader.java | 130 +- .../CustomerProfilesEntityAssignments.java | 166 +-- ...tomerProfilesEntityAssignmentsCreator.java | 70 +- ...tomerProfilesEntityAssignmentsDeleter.java | 52 +- ...tomerProfilesEntityAssignmentsFetcher.java | 62 +- ...stomerProfilesEntityAssignmentsReader.java | 121 +- .../CustomerProfilesEvaluations.java | 221 ++- .../CustomerProfilesEvaluationsCreator.java | 61 +- .../CustomerProfilesEvaluationsFetcher.java | 58 +- .../CustomerProfilesEvaluationsReader.java | 105 +- ...rustProductsChannelEndpointAssignment.java | 181 +-- ...ductsChannelEndpointAssignmentCreator.java | 89 +- ...ductsChannelEndpointAssignmentDeleter.java | 52 +- ...ductsChannelEndpointAssignmentFetcher.java | 62 +- ...oductsChannelEndpointAssignmentReader.java | 130 +- .../TrustProductsEntityAssignments.java | 168 +-- ...TrustProductsEntityAssignmentsCreator.java | 65 +- ...TrustProductsEntityAssignmentsDeleter.java | 52 +- ...TrustProductsEntityAssignmentsFetcher.java | 58 +- .../TrustProductsEntityAssignmentsReader.java | 118 +- .../TrustProductsEvaluations.java | 211 ++- .../TrustProductsEvaluationsCreator.java | 61 +- .../TrustProductsEvaluationsFetcher.java | 55 +- .../TrustProductsEvaluationsReader.java | 103 +- .../java/com/twilio/rest/verify/v2/Form.java | 131 +- .../twilio/rest/verify/v2/FormFetcher.java | 34 +- .../twilio/rest/verify/v2/NewChallenge.java | 334 +++++ .../rest/verify/v2/NewChallengeCreator.java | 86 ++ .../com/twilio/rest/verify/v2/Safelist.java | 94 +- .../rest/verify/v2/SafelistCreator.java | 42 +- .../rest/verify/v2/SafelistDeleter.java | 37 +- .../rest/verify/v2/SafelistFetcher.java | 43 +- .../com/twilio/rest/verify/v2/Service.java | 371 +++-- .../twilio/rest/verify/v2/ServiceCreator.java | 261 ++-- .../twilio/rest/verify/v2/ServiceDeleter.java | 33 +- .../twilio/rest/verify/v2/ServiceFetcher.java | 34 +- .../twilio/rest/verify/v2/ServiceReader.java | 83 +- .../twilio/rest/verify/v2/ServiceUpdater.java | 265 ++-- .../com/twilio/rest/verify/v2/Template.java | 110 +- .../twilio/rest/verify/v2/TemplateReader.java | 88 +- .../rest/verify/v2/VerificationAttempt.java | 290 ++-- .../verify/v2/VerificationAttemptFetcher.java | 39 +- .../verify/v2/VerificationAttemptReader.java | 160 +- .../v2/VerificationAttemptsSummary.java | 160 +- .../VerificationAttemptsSummaryFetcher.java | 96 +- .../rest/verify/v2/service/AccessToken.java | 227 ++- .../verify/v2/service/AccessTokenCreator.java | 80 +- .../verify/v2/service/AccessTokenFetcher.java | 52 +- .../twilio/rest/verify/v2/service/Entity.java | 186 ++- .../rest/verify/v2/service/EntityCreator.java | 46 +- .../rest/verify/v2/service/EntityDeleter.java | 47 +- .../rest/verify/v2/service/EntityFetcher.java | 48 +- .../rest/verify/v2/service/EntityReader.java | 92 +- .../v2/service/MessagingConfiguration.java | 180 ++- .../MessagingConfigurationCreator.java | 72 +- .../MessagingConfigurationDeleter.java | 52 +- .../MessagingConfigurationFetcher.java | 58 +- .../service/MessagingConfigurationReader.java | 103 +- .../MessagingConfigurationUpdater.java | 75 +- .../rest/verify/v2/service/NewFactor.java | 414 ++++++ .../verify/v2/service/NewFactorCreator.java | 86 ++ .../rest/verify/v2/service/RateLimit.java | 211 ++- .../verify/v2/service/RateLimitCreator.java | 60 +- .../verify/v2/service/RateLimitDeleter.java | 43 +- .../verify/v2/service/RateLimitFetcher.java | 49 +- .../verify/v2/service/RateLimitReader.java | 92 +- .../verify/v2/service/RateLimitUpdater.java | 56 +- .../rest/verify/v2/service/Verification.java | 402 +++-- .../verify/v2/service/VerificationCheck.java | 262 ++-- .../v2/service/VerificationCheckCreator.java | 83 +- .../v2/service/VerificationCreator.java | 175 ++- .../v2/service/VerificationFetcher.java | 52 +- .../v2/service/VerificationUpdater.java | 61 +- .../rest/verify/v2/service/Webhook.java | 369 +++-- .../verify/v2/service/WebhookCreator.java | 82 +- .../verify/v2/service/WebhookDeleter.java | 43 +- .../verify/v2/service/WebhookFetcher.java | 44 +- .../rest/verify/v2/service/WebhookReader.java | 92 +- .../verify/v2/service/WebhookUpdater.java | 73 +- .../verify/v2/service/entity/Challenge.java | 503 +++---- .../v2/service/entity/ChallengeCreator.java | 108 +- .../v2/service/entity/ChallengeFetcher.java | 63 +- .../v2/service/entity/ChallengeReader.java | 120 +- .../v2/service/entity/ChallengeUpdater.java | 76 +- .../rest/verify/v2/service/entity/Factor.java | 381 +++-- .../v2/service/entity/FactorDeleter.java | 57 +- .../v2/service/entity/FactorFetcher.java | 58 +- .../v2/service/entity/FactorReader.java | 102 +- .../v2/service/entity/FactorUpdater.java | 122 +- .../verify/v2/service/entity/NewFactor.java | 424 +++--- .../v2/service/entity/NewFactorCreator.java | 165 ++- .../entity/challenge/Notification.java | 167 +-- .../entity/challenge/NotificationCreator.java | 74 +- .../verify/v2/service/ratelimit/Bucket.java | 219 ++- .../v2/service/ratelimit/BucketCreator.java | 70 +- .../v2/service/ratelimit/BucketDeleter.java | 60 +- .../v2/service/ratelimit/BucketFetcher.java | 61 +- .../v2/service/ratelimit/BucketReader.java | 108 +- .../v2/service/ratelimit/BucketUpdater.java | 73 +- .../com/twilio/rest/video/v1/Composition.java | 440 +++--- .../rest/video/v1/CompositionCreator.java | 109 +- .../rest/video/v1/CompositionDeleter.java | 33 +- .../rest/video/v1/CompositionFetcher.java | 39 +- .../twilio/rest/video/v1/CompositionHook.java | 316 ++-- .../rest/video/v1/CompositionHookCreator.java | 128 +- .../rest/video/v1/CompositionHookDeleter.java | 33 +- .../rest/video/v1/CompositionHookFetcher.java | 39 +- .../rest/video/v1/CompositionHookReader.java | 116 +- .../rest/video/v1/CompositionHookUpdater.java | 137 +- .../rest/video/v1/CompositionReader.java | 116 +- .../rest/video/v1/CompositionSettings.java | 148 +- .../video/v1/CompositionSettingsCreator.java | 98 +- .../video/v1/CompositionSettingsFetcher.java | 35 +- .../com/twilio/rest/video/v1/Recording.java | 453 +++--- .../rest/video/v1/RecordingDeleter.java | 33 +- .../rest/video/v1/RecordingFetcher.java | 39 +- .../twilio/rest/video/v1/RecordingReader.java | 127 +- .../rest/video/v1/RecordingSettings.java | 144 +- .../video/v1/RecordingSettingsCreator.java | 94 +- .../video/v1/RecordingSettingsFetcher.java | 35 +- .../java/com/twilio/rest/video/v1/Room.java | 661 +++++---- .../com/twilio/rest/video/v1/RoomCreator.java | 172 ++- .../com/twilio/rest/video/v1/RoomFetcher.java | 34 +- .../com/twilio/rest/video/v1/RoomReader.java | 116 +- .../com/twilio/rest/video/v1/RoomUpdater.java | 42 +- .../rest/video/v1/room/Participant.java | 275 ++-- .../video/v1/room/ParticipantFetcher.java | 45 +- .../rest/video/v1/room/ParticipantReader.java | 121 +- .../video/v1/room/ParticipantUpdater.java | 52 +- .../rest/video/v1/room/RecordingRules.java | 107 +- .../video/v1/room/RecordingRulesFetcher.java | 39 +- .../video/v1/room/RecordingRulesUpdater.java | 47 +- .../rest/video/v1/room/RoomRecording.java | 456 +++--- .../video/v1/room/RoomRecordingDeleter.java | 42 +- .../video/v1/room/RoomRecordingFetcher.java | 48 +- .../video/v1/room/RoomRecordingReader.java | 121 +- .../rest/video/v1/room/Transcriptions.java | 266 ++-- .../video/v1/room/TranscriptionsCreator.java | 59 +- .../video/v1/room/TranscriptionsFetcher.java | 48 +- .../video/v1/room/TranscriptionsReader.java | 88 +- .../video/v1/room/TranscriptionsUpdater.java | 55 +- .../video/v1/room/participant/Anonymize.java | 240 ++- .../v1/room/participant/AnonymizeUpdater.java | 46 +- .../v1/room/participant/PublishedTrack.java | 221 ++- .../participant/PublishedTrackFetcher.java | 62 +- .../participant/PublishedTrackReader.java | 104 +- .../v1/room/participant/SubscribeRules.java | 125 +- .../participant/SubscribeRulesFetcher.java | 55 +- .../participant/SubscribeRulesUpdater.java | 65 +- .../v1/room/participant/SubscribedTrack.java | 234 ++- .../participant/SubscribedTrackFetcher.java | 62 +- .../participant/SubscribedTrackReader.java | 104 +- .../twilio/rest/voice/v1/ArchivedCall.java | 47 +- .../rest/voice/v1/ArchivedCallDeleter.java | 40 +- .../com/twilio/rest/voice/v1/ByocTrunk.java | 280 ++-- .../rest/voice/v1/ByocTrunkCreator.java | 128 +- .../rest/voice/v1/ByocTrunkDeleter.java | 33 +- .../rest/voice/v1/ByocTrunkFetcher.java | 39 +- .../twilio/rest/voice/v1/ByocTrunkReader.java | 83 +- .../rest/voice/v1/ByocTrunkUpdater.java | 132 +- .../rest/voice/v1/ConnectionPolicy.java | 165 ++- .../voice/v1/ConnectionPolicyCreator.java | 41 +- .../voice/v1/ConnectionPolicyDeleter.java | 33 +- .../voice/v1/ConnectionPolicyFetcher.java | 39 +- .../rest/voice/v1/ConnectionPolicyReader.java | 83 +- .../voice/v1/ConnectionPolicyUpdater.java | 46 +- .../com/twilio/rest/voice/v1/IpRecord.java | 175 +-- .../twilio/rest/voice/v1/IpRecordCreator.java | 51 +- .../twilio/rest/voice/v1/IpRecordDeleter.java | 33 +- .../twilio/rest/voice/v1/IpRecordFetcher.java | 39 +- .../twilio/rest/voice/v1/IpRecordReader.java | 83 +- .../twilio/rest/voice/v1/IpRecordUpdater.java | 46 +- .../twilio/rest/voice/v1/SourceIpMapping.java | 159 +- .../rest/voice/v1/SourceIpMappingCreator.java | 57 +- .../rest/voice/v1/SourceIpMappingDeleter.java | 33 +- .../rest/voice/v1/SourceIpMappingFetcher.java | 39 +- .../rest/voice/v1/SourceIpMappingReader.java | 83 +- .../rest/voice/v1/SourceIpMappingUpdater.java | 54 +- .../ConnectionPolicyTarget.java | 232 ++- .../ConnectionPolicyTargetCreator.java | 86 +- .../ConnectionPolicyTargetDeleter.java | 52 +- .../ConnectionPolicyTargetFetcher.java | 58 +- .../ConnectionPolicyTargetReader.java | 103 +- .../ConnectionPolicyTargetUpdater.java | 93 +- .../dialingpermissions/BulkCountryUpdate.java | 66 +- .../BulkCountryUpdateCreator.java | 46 +- .../voice/v1/dialingpermissions/Country.java | 181 +-- .../v1/dialingpermissions/CountryFetcher.java | 34 +- .../v1/dialingpermissions/CountryReader.java | 134 +- .../voice/v1/dialingpermissions/Settings.java | 76 +- .../dialingpermissions/SettingsFetcher.java | 35 +- .../dialingpermissions/SettingsUpdater.java | 48 +- .../country/HighriskSpecialPrefix.java | 62 +- .../country/HighriskSpecialPrefixReader.java | 99 +- .../com/twilio/rest/wireless/v1/Command.java | 390 +++-- .../rest/wireless/v1/CommandCreator.java | 79 +- .../rest/wireless/v1/CommandDeleter.java | 33 +- .../rest/wireless/v1/CommandFetcher.java | 34 +- .../rest/wireless/v1/CommandReader.java | 103 +- .../com/twilio/rest/wireless/v1/RatePlan.java | 343 ++--- .../rest/wireless/v1/RatePlanCreator.java | 142 +- .../rest/wireless/v1/RatePlanDeleter.java | 33 +- .../rest/wireless/v1/RatePlanFetcher.java | 39 +- .../rest/wireless/v1/RatePlanReader.java | 83 +- .../rest/wireless/v1/RatePlanUpdater.java | 51 +- .../java/com/twilio/rest/wireless/v1/Sim.java | 475 +++--- .../twilio/rest/wireless/v1/SimDeleter.java | 33 +- .../twilio/rest/wireless/v1/SimFetcher.java | 34 +- .../twilio/rest/wireless/v1/SimReader.java | 108 +- .../twilio/rest/wireless/v1/SimUpdater.java | 165 ++- .../twilio/rest/wireless/v1/UsageRecord.java | 135 +- .../rest/wireless/v1/UsageRecordReader.java | 101 +- .../rest/wireless/v1/sim/DataSession.java | 273 ++-- .../wireless/v1/sim/DataSessionReader.java | 88 +- .../rest/wireless/v1/sim/UsageRecord.java | 151 +- .../wireless/v1/sim/UsageRecordReader.java | 106 +- 1905 files changed, 106538 insertions(+), 129752 deletions(-) create mode 100644 src/main/java/com/twilio/rest/intelligence/v2/transcript/EncryptedOperatorResults.java create mode 100644 src/main/java/com/twilio/rest/intelligence/v2/transcript/EncryptedOperatorResultsFetcher.java create mode 100644 src/main/java/com/twilio/rest/intelligence/v2/transcript/EncryptedSentences.java create mode 100644 src/main/java/com/twilio/rest/intelligence/v2/transcript/EncryptedSentencesFetcher.java create mode 100644 src/main/java/com/twilio/rest/numbers/v3/HostedNumberOrder.java create mode 100644 src/main/java/com/twilio/rest/numbers/v3/HostedNumberOrderCreator.java create mode 100644 src/main/java/com/twilio/rest/oauth/v2/Token.java create mode 100644 src/main/java/com/twilio/rest/oauth/v2/TokenCreator.java create mode 100644 src/main/java/com/twilio/rest/verify/v2/NewChallenge.java create mode 100644 src/main/java/com/twilio/rest/verify/v2/NewChallengeCreator.java create mode 100644 src/main/java/com/twilio/rest/verify/v2/service/NewFactor.java create mode 100644 src/main/java/com/twilio/rest/verify/v2/service/NewFactorCreator.java diff --git a/src/main/java/com/twilio/rest/accounts/v1/AuthTokenPromotion.java b/src/main/java/com/twilio/rest/accounts/v1/AuthTokenPromotion.java index b351cf2f6c..1ac00006c1 100644 --- a/src/main/java/com/twilio/rest/accounts/v1/AuthTokenPromotion.java +++ b/src/main/java/com/twilio/rest/accounts/v1/AuthTokenPromotion.java @@ -18,41 +18,42 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class AuthTokenPromotion extends Resource { - private static final long serialVersionUID = 77507843877589L; public static AuthTokenPromotionUpdater updater() { - return new AuthTokenPromotionUpdater(); + return new AuthTokenPromotionUpdater( + + ); } + /** * Converts a JSON String into a AuthTokenPromotion object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return AuthTokenPromotion object represented by the provided JSON */ - public static AuthTokenPromotion fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static AuthTokenPromotion fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, AuthTokenPromotion.class); @@ -67,14 +68,11 @@ public static AuthTokenPromotion fromJson( * Converts a JSON InputStream into a AuthTokenPromotion object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return AuthTokenPromotion object represented by the provided JSON */ - public static AuthTokenPromotion fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static AuthTokenPromotion fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, AuthTokenPromotion.class); @@ -85,47 +83,47 @@ public static AuthTokenPromotion fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; + @Getter private final String authToken; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; + @Getter private final URI url; @JsonCreator private AuthTokenPromotion( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("auth_token") final String authToken, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("url") final URI url + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("auth_token") final String authToken, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("url") final URI url ) { this.accountSid = accountSid; this.authToken = authToken; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.url = url; } - public final String getAccountSid() { - return this.accountSid; - } - - public final String getAuthToken() { - return this.authToken; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final URI getUrl() { - return this.url; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -137,24 +135,26 @@ public boolean equals(final Object o) { } AuthTokenPromotion other = (AuthTokenPromotion) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(authToken, other.authToken) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(url, other.url) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(authToken, other.authToken) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - accountSid, - authToken, - dateCreated, - dateUpdated, - url + accountSid, + authToken, + dateCreated, + dateUpdated, + url ); } + + } + diff --git a/src/main/java/com/twilio/rest/accounts/v1/AuthTokenPromotionUpdater.java b/src/main/java/com/twilio/rest/accounts/v1/AuthTokenPromotionUpdater.java index fda630c49d..f35701e330 100644 --- a/src/main/java/com/twilio/rest/accounts/v1/AuthTokenPromotionUpdater.java +++ b/src/main/java/com/twilio/rest/accounts/v1/AuthTokenPromotionUpdater.java @@ -15,7 +15,6 @@ package com.twilio.rest.accounts.v1; import com.twilio.base.Updater; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,40 +26,37 @@ public class AuthTokenPromotionUpdater extends Updater { - public AuthTokenPromotionUpdater() {} + public AuthTokenPromotionUpdater() { + } + @Override public AuthTokenPromotion update(final TwilioRestClient client) { + String path = "/v1/AuthTokens/Promote"; + Request request = new Request( - HttpMethod.POST, - Domains.ACCOUNTS.toString(), - path + HttpMethod.POST, + Domains.ACCOUNTS.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "AuthTokenPromotion update failed: Unable to connect to server" - ); + throw new ApiConnectionException("AuthTokenPromotion update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return AuthTokenPromotion.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return AuthTokenPromotion.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/accounts/v1/BulkConsents.java b/src/main/java/com/twilio/rest/accounts/v1/BulkConsents.java index 8c8eee79da..669a1bd015 100644 --- a/src/main/java/com/twilio/rest/accounts/v1/BulkConsents.java +++ b/src/main/java/com/twilio/rest/accounts/v1/BulkConsents.java @@ -18,41 +18,40 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.util.List; -import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class BulkConsents extends Resource { - private static final long serialVersionUID = 126137950684284L; public static BulkConsentsCreator creator(final List items) { - return new BulkConsentsCreator(items); + return new BulkConsentsCreator( + items + ); } + /** * Converts a JSON String into a BulkConsents object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return BulkConsents object represented by the provided JSON */ - public static BulkConsents fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static BulkConsents fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, BulkConsents.class); @@ -67,14 +66,11 @@ public static BulkConsents fromJson( * Converts a JSON InputStream into a BulkConsents object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return BulkConsents object represented by the provided JSON */ - public static BulkConsents fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static BulkConsents fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, BulkConsents.class); @@ -85,19 +81,29 @@ public static BulkConsents fromJson( } } - private final Map items; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter + private final Object items; @JsonCreator private BulkConsents( - @JsonProperty("items") final Map items + @JsonProperty("items") final Object items ) { this.items = items; } - public final Map getItems() { - return this.items; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -109,12 +115,18 @@ public boolean equals(final Object o) { } BulkConsents other = (BulkConsents) o; - - return Objects.equals(items, other.items); + return ( + Objects.equals(items, other.items) + ); } @Override public int hashCode() { - return Objects.hash(items); + return Objects.hash( + items + ); } + + } + diff --git a/src/main/java/com/twilio/rest/accounts/v1/BulkConsentsCreator.java b/src/main/java/com/twilio/rest/accounts/v1/BulkConsentsCreator.java index 1155c9fd32..23ead28871 100644 --- a/src/main/java/com/twilio/rest/accounts/v1/BulkConsentsCreator.java +++ b/src/main/java/com/twilio/rest/accounts/v1/BulkConsentsCreator.java @@ -14,11 +14,12 @@ package com.twilio.rest.accounts.v1; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; -import com.twilio.converter.Converter; -import com.twilio.converter.Converter; +import com.twilio.constant.EnumConstants.ParameterType; import com.twilio.converter.Promoter; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,7 +28,7 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -import java.util.List; + import java.util.List; public class BulkConsentsCreator extends Creator { @@ -38,6 +39,7 @@ public BulkConsentsCreator(final List items) { this.items = items; } + public BulkConsentsCreator setItems(final List items) { this.items = items; return this; @@ -49,47 +51,44 @@ public BulkConsentsCreator setItems(final Object items) { @Override public BulkConsents create(final TwilioRestClient client) { + String path = "/v1/Consents/Bulk"; - path = path.replace("{" + "Items" + "}", this.items.toString()); Request request = new Request( - HttpMethod.POST, - Domains.ACCOUNTS.toString(), - path + HttpMethod.POST, + Domains.ACCOUNTS.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "BulkConsents creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("BulkConsents creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return BulkConsents.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return BulkConsents.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + + if (items != null) { - for (Object prop : items) { - request.addPostParam("Items", Converter.objectToJson(prop)); + for (Object param : items) { + Serializer.toString(request, "Items", param, ParameterType.URLENCODED); } } + } } diff --git a/src/main/java/com/twilio/rest/accounts/v1/BulkContacts.java b/src/main/java/com/twilio/rest/accounts/v1/BulkContacts.java index b4ff307a19..006b923596 100644 --- a/src/main/java/com/twilio/rest/accounts/v1/BulkContacts.java +++ b/src/main/java/com/twilio/rest/accounts/v1/BulkContacts.java @@ -18,41 +18,40 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.util.List; -import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class BulkContacts extends Resource { - private static final long serialVersionUID = 126137950684284L; public static BulkContactsCreator creator(final List items) { - return new BulkContactsCreator(items); + return new BulkContactsCreator( + items + ); } + /** * Converts a JSON String into a BulkContacts object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return BulkContacts object represented by the provided JSON */ - public static BulkContacts fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static BulkContacts fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, BulkContacts.class); @@ -67,14 +66,11 @@ public static BulkContacts fromJson( * Converts a JSON InputStream into a BulkContacts object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return BulkContacts object represented by the provided JSON */ - public static BulkContacts fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static BulkContacts fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, BulkContacts.class); @@ -85,19 +81,29 @@ public static BulkContacts fromJson( } } - private final Map items; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter + private final Object items; @JsonCreator private BulkContacts( - @JsonProperty("items") final Map items + @JsonProperty("items") final Object items ) { this.items = items; } - public final Map getItems() { - return this.items; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -109,12 +115,18 @@ public boolean equals(final Object o) { } BulkContacts other = (BulkContacts) o; - - return Objects.equals(items, other.items); + return ( + Objects.equals(items, other.items) + ); } @Override public int hashCode() { - return Objects.hash(items); + return Objects.hash( + items + ); } + + } + diff --git a/src/main/java/com/twilio/rest/accounts/v1/BulkContactsCreator.java b/src/main/java/com/twilio/rest/accounts/v1/BulkContactsCreator.java index 7dc970c184..5fae32c7df 100644 --- a/src/main/java/com/twilio/rest/accounts/v1/BulkContactsCreator.java +++ b/src/main/java/com/twilio/rest/accounts/v1/BulkContactsCreator.java @@ -14,11 +14,12 @@ package com.twilio.rest.accounts.v1; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; -import com.twilio.converter.Converter; -import com.twilio.converter.Converter; +import com.twilio.constant.EnumConstants.ParameterType; import com.twilio.converter.Promoter; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,7 +28,7 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -import java.util.List; + import java.util.List; public class BulkContactsCreator extends Creator { @@ -38,6 +39,7 @@ public BulkContactsCreator(final List items) { this.items = items; } + public BulkContactsCreator setItems(final List items) { this.items = items; return this; @@ -49,47 +51,44 @@ public BulkContactsCreator setItems(final Object items) { @Override public BulkContacts create(final TwilioRestClient client) { + String path = "/v1/Contacts/Bulk"; - path = path.replace("{" + "Items" + "}", this.items.toString()); Request request = new Request( - HttpMethod.POST, - Domains.ACCOUNTS.toString(), - path + HttpMethod.POST, + Domains.ACCOUNTS.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "BulkContacts creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("BulkContacts creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return BulkContacts.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return BulkContacts.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + + if (items != null) { - for (Object prop : items) { - request.addPostParam("Items", Converter.objectToJson(prop)); + for (Object param : items) { + Serializer.toString(request, "Items", param, ParameterType.URLENCODED); } } + } } diff --git a/src/main/java/com/twilio/rest/accounts/v1/Safelist.java b/src/main/java/com/twilio/rest/accounts/v1/Safelist.java index 8eb668198c..08c0c8d0d4 100644 --- a/src/main/java/com/twilio/rest/accounts/v1/Safelist.java +++ b/src/main/java/com/twilio/rest/accounts/v1/Safelist.java @@ -18,46 +18,53 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Safelist extends Resource { - private static final long serialVersionUID = 179274993739L; public static SafelistCreator creator(final String phoneNumber) { - return new SafelistCreator(phoneNumber); + return new SafelistCreator( + phoneNumber + ); } + public static SafelistDeleter deleter() { - return new SafelistDeleter(); + return new SafelistDeleter( + + ); } + public static SafelistFetcher fetcher() { - return new SafelistFetcher(); + return new SafelistFetcher( + + ); } + /** * Converts a JSON String into a Safelist object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Safelist object represented by the provided JSON */ - public static Safelist fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Safelist fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Safelist.class); @@ -72,14 +79,11 @@ public static Safelist fromJson( * Converts a JSON InputStream into a Safelist object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Safelist object represented by the provided JSON */ - public static Safelist fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Safelist fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Safelist.class); @@ -90,24 +94,31 @@ public static Safelist fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String phoneNumber; + @Getter + private final String sid; @JsonCreator private Safelist( - @JsonProperty("sid") final String sid, - @JsonProperty("phone_number") final String phoneNumber + @JsonProperty("phone_number") final String phoneNumber, + @JsonProperty("sid") final String sid ) { - this.sid = sid; this.phoneNumber = phoneNumber; - } - - public final String getSid() { - return this.sid; - } - - public final String getPhoneNumber() { - return this.phoneNumber; + this.sid = sid; } @Override @@ -121,15 +132,20 @@ public boolean equals(final Object o) { } Safelist other = (Safelist) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(phoneNumber, other.phoneNumber) + Objects.equals(phoneNumber, other.phoneNumber) && + Objects.equals(sid, other.sid) ); } @Override public int hashCode() { - return Objects.hash(sid, phoneNumber); + return Objects.hash( + phoneNumber, + sid + ); } + + } + diff --git a/src/main/java/com/twilio/rest/accounts/v1/SafelistCreator.java b/src/main/java/com/twilio/rest/accounts/v1/SafelistCreator.java index 83dfbcb4fe..b8f4b4cfd5 100644 --- a/src/main/java/com/twilio/rest/accounts/v1/SafelistCreator.java +++ b/src/main/java/com/twilio/rest/accounts/v1/SafelistCreator.java @@ -14,8 +14,11 @@ package com.twilio.rest.accounts.v1; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -33,56 +36,51 @@ public SafelistCreator(final String phoneNumber) { this.phoneNumber = phoneNumber; } + public SafelistCreator setPhoneNumber(final String phoneNumber) { this.phoneNumber = phoneNumber; return this; } + @Override public Safelist create(final TwilioRestClient client) { + String path = "/v1/SafeList/Numbers"; - path = - path.replace( - "{" + "PhoneNumber" + "}", - this.phoneNumber.toString() - ); Request request = new Request( - HttpMethod.POST, - Domains.ACCOUNTS.toString(), - path + HttpMethod.POST, + Domains.ACCOUNTS.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Safelist creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("Safelist creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Safelist.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Safelist.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (phoneNumber != null) { - request.addPostParam("PhoneNumber", phoneNumber); + Serializer.toString(request, "PhoneNumber", phoneNumber, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/accounts/v1/SafelistDeleter.java b/src/main/java/com/twilio/rest/accounts/v1/SafelistDeleter.java index 91cd88eb46..bfe9133a9d 100644 --- a/src/main/java/com/twilio/rest/accounts/v1/SafelistDeleter.java +++ b/src/main/java/com/twilio/rest/accounts/v1/SafelistDeleter.java @@ -15,7 +15,8 @@ package com.twilio.rest.accounts.v1; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,40 +30,40 @@ public class SafelistDeleter extends Deleter { private String phoneNumber; - public SafelistDeleter() {} + public SafelistDeleter() { + } + public SafelistDeleter setPhoneNumber(final String phoneNumber) { this.phoneNumber = phoneNumber; return this; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/v1/SafeList/Numbers"; + Request request = new Request( - HttpMethod.DELETE, - Domains.ACCOUNTS.toString(), - path + HttpMethod.DELETE, + Domains.ACCOUNTS.toString(), + path ); addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Safelist delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("Safelist delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -70,8 +71,12 @@ public boolean delete(final TwilioRestClient client) { } private void addQueryParams(final Request request) { + + if (phoneNumber != null) { - request.addQueryParam("PhoneNumber", phoneNumber); + Serializer.toString(request, "PhoneNumber", phoneNumber, ParameterType.QUERY); } + + } } diff --git a/src/main/java/com/twilio/rest/accounts/v1/SafelistFetcher.java b/src/main/java/com/twilio/rest/accounts/v1/SafelistFetcher.java index d31cff1385..08e2d18ab4 100644 --- a/src/main/java/com/twilio/rest/accounts/v1/SafelistFetcher.java +++ b/src/main/java/com/twilio/rest/accounts/v1/SafelistFetcher.java @@ -15,7 +15,8 @@ package com.twilio.rest.accounts.v1; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,53 +30,53 @@ public class SafelistFetcher extends Fetcher { private String phoneNumber; - public SafelistFetcher() {} + public SafelistFetcher() { + } + public SafelistFetcher setPhoneNumber(final String phoneNumber) { this.phoneNumber = phoneNumber; return this; } + @Override public Safelist fetch(final TwilioRestClient client) { + String path = "/v1/SafeList/Numbers"; + Request request = new Request( - HttpMethod.GET, - Domains.ACCOUNTS.toString(), - path + HttpMethod.GET, + Domains.ACCOUNTS.toString(), + path ); addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Safelist fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Safelist fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return Safelist.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Safelist.fromJson(response.getStream(), client.getObjectMapper()); } private void addQueryParams(final Request request) { + + if (phoneNumber != null) { - request.addQueryParam("PhoneNumber", phoneNumber); + Serializer.toString(request, "PhoneNumber", phoneNumber, ParameterType.QUERY); } + + } } diff --git a/src/main/java/com/twilio/rest/accounts/v1/SecondaryAuthToken.java b/src/main/java/com/twilio/rest/accounts/v1/SecondaryAuthToken.java index 0d6a66035f..55121660a4 100644 --- a/src/main/java/com/twilio/rest/accounts/v1/SecondaryAuthToken.java +++ b/src/main/java/com/twilio/rest/accounts/v1/SecondaryAuthToken.java @@ -18,45 +18,49 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class SecondaryAuthToken extends Resource { - private static final long serialVersionUID = 191219471550314L; public static SecondaryAuthTokenCreator creator() { - return new SecondaryAuthTokenCreator(); + return new SecondaryAuthTokenCreator( + + ); } + public static SecondaryAuthTokenDeleter deleter() { - return new SecondaryAuthTokenDeleter(); + return new SecondaryAuthTokenDeleter( + + ); } + /** * Converts a JSON String into a SecondaryAuthToken object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return SecondaryAuthToken object represented by the provided JSON */ - public static SecondaryAuthToken fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static SecondaryAuthToken fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, SecondaryAuthToken.class); @@ -71,14 +75,11 @@ public static SecondaryAuthToken fromJson( * Converts a JSON InputStream into a SecondaryAuthToken object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return SecondaryAuthToken object represented by the provided JSON */ - public static SecondaryAuthToken fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static SecondaryAuthToken fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, SecondaryAuthToken.class); @@ -89,47 +90,47 @@ public static SecondaryAuthToken fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; + @Getter private final String secondaryAuthToken; + @Getter private final URI url; @JsonCreator private SecondaryAuthToken( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("secondary_auth_token") final String secondaryAuthToken, - @JsonProperty("url") final URI url + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("secondary_auth_token") final String secondaryAuthToken, + @JsonProperty("url") final URI url ) { this.accountSid = accountSid; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.secondaryAuthToken = secondaryAuthToken; this.url = url; } - public final String getAccountSid() { - return this.accountSid; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final String getSecondaryAuthToken() { - return this.secondaryAuthToken; - } - - public final URI getUrl() { - return this.url; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -141,24 +142,26 @@ public boolean equals(final Object o) { } SecondaryAuthToken other = (SecondaryAuthToken) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(secondaryAuthToken, other.secondaryAuthToken) && - Objects.equals(url, other.url) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(secondaryAuthToken, other.secondaryAuthToken) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - accountSid, - dateCreated, - dateUpdated, - secondaryAuthToken, - url + accountSid, + dateCreated, + dateUpdated, + secondaryAuthToken, + url ); } + + } + diff --git a/src/main/java/com/twilio/rest/accounts/v1/SecondaryAuthTokenCreator.java b/src/main/java/com/twilio/rest/accounts/v1/SecondaryAuthTokenCreator.java index f6607054d4..40172766c9 100644 --- a/src/main/java/com/twilio/rest/accounts/v1/SecondaryAuthTokenCreator.java +++ b/src/main/java/com/twilio/rest/accounts/v1/SecondaryAuthTokenCreator.java @@ -14,8 +14,8 @@ package com.twilio.rest.accounts.v1; + import com.twilio.base.Creator; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,40 +27,38 @@ public class SecondaryAuthTokenCreator extends Creator { - public SecondaryAuthTokenCreator() {} + + public SecondaryAuthTokenCreator() { + } + @Override public SecondaryAuthToken create(final TwilioRestClient client) { + String path = "/v1/AuthTokens/Secondary"; + Request request = new Request( - HttpMethod.POST, - Domains.ACCOUNTS.toString(), - path + HttpMethod.POST, + Domains.ACCOUNTS.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "SecondaryAuthToken creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("SecondaryAuthToken creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return SecondaryAuthToken.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return SecondaryAuthToken.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/accounts/v1/SecondaryAuthTokenDeleter.java b/src/main/java/com/twilio/rest/accounts/v1/SecondaryAuthTokenDeleter.java index 8f25f80fb9..5ea7a8dc6c 100644 --- a/src/main/java/com/twilio/rest/accounts/v1/SecondaryAuthTokenDeleter.java +++ b/src/main/java/com/twilio/rest/accounts/v1/SecondaryAuthTokenDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.accounts.v1; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,34 +26,34 @@ public class SecondaryAuthTokenDeleter extends Deleter { - public SecondaryAuthTokenDeleter() {} + + public SecondaryAuthTokenDeleter() { + } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/v1/AuthTokens/Secondary"; + Request request = new Request( - HttpMethod.DELETE, - Domains.ACCOUNTS.toString(), - path + HttpMethod.DELETE, + Domains.ACCOUNTS.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "SecondaryAuthToken delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("SecondaryAuthToken delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/accounts/v1/credential/Aws.java b/src/main/java/com/twilio/rest/accounts/v1/credential/Aws.java index 7f6af0e434..4bdd9c25f2 100644 --- a/src/main/java/com/twilio/rest/accounts/v1/credential/Aws.java +++ b/src/main/java/com/twilio/rest/accounts/v1/credential/Aws.java @@ -18,57 +18,70 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Aws extends Resource { - private static final long serialVersionUID = 255841368009036L; public static AwsCreator creator(final String credentials) { - return new AwsCreator(credentials); + return new AwsCreator( + credentials + ); } - public static AwsDeleter deleter(final String pathSid) { - return new AwsDeleter(pathSid); + + public static AwsDeleter deleter(final String pathsid) { + return new AwsDeleter( + pathsid + ); } - public static AwsFetcher fetcher(final String pathSid) { - return new AwsFetcher(pathSid); + + public static AwsFetcher fetcher(final String pathsid) { + return new AwsFetcher( + pathsid + ); } + public static AwsReader reader() { - return new AwsReader(); + return new AwsReader( + + ); } - public static AwsUpdater updater(final String pathSid) { - return new AwsUpdater(pathSid); + + public static AwsUpdater updater(final String pathsid) { + return new AwsUpdater( + pathsid + ); } + /** * Converts a JSON String into a Aws object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Aws object represented by the provided JSON */ - public static Aws fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Aws fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Aws.class); @@ -83,14 +96,11 @@ public static Aws fromJson( * Converts a JSON InputStream into a Aws object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Aws object represented by the provided JSON */ - public static Aws fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Aws fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Aws.class); @@ -101,54 +111,51 @@ public static Aws fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String friendlyName; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; + @Getter + private final String friendlyName; + @Getter + private final String sid; + @Getter private final URI url; @JsonCreator private Aws( - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("url") final URI url + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("sid") final String sid, + @JsonProperty("url") final URI url ) { - this.sid = sid; this.accountSid = accountSid; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.friendlyName = friendlyName; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); + this.sid = sid; this.url = url; } - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final URI getUrl() { - return this.url; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -160,26 +167,28 @@ public boolean equals(final Object o) { } Aws other = (Aws) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(url, other.url) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(sid, other.sid) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - sid, - accountSid, - friendlyName, - dateCreated, - dateUpdated, - url + accountSid, + dateCreated, + dateUpdated, + friendlyName, + sid, + url ); } + + } + diff --git a/src/main/java/com/twilio/rest/accounts/v1/credential/AwsCreator.java b/src/main/java/com/twilio/rest/accounts/v1/credential/AwsCreator.java index cb16ac166d..2b2437f395 100644 --- a/src/main/java/com/twilio/rest/accounts/v1/credential/AwsCreator.java +++ b/src/main/java/com/twilio/rest/accounts/v1/credential/AwsCreator.java @@ -14,8 +14,11 @@ package com.twilio.rest.accounts.v1.credential; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -35,53 +38,50 @@ public AwsCreator(final String credentials) { this.credentials = credentials; } + public AwsCreator setCredentials(final String credentials) { this.credentials = credentials; return this; } + public AwsCreator setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + public AwsCreator setAccountSid(final String accountSid) { this.accountSid = accountSid; return this; } + @Override public Aws create(final TwilioRestClient client) { + String path = "/v1/Credentials/AWS"; - path = - path.replace( - "{" + "Credentials" + "}", - this.credentials.toString() - ); Request request = new Request( - HttpMethod.POST, - Domains.ACCOUNTS.toString(), - path + HttpMethod.POST, + Domains.ACCOUNTS.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Aws creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("Aws creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -90,14 +90,21 @@ public Aws create(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (credentials != null) { - request.addPostParam("Credentials", credentials); + Serializer.toString(request, "Credentials", credentials, ParameterType.URLENCODED); } + + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + if (accountSid != null) { - request.addPostParam("AccountSid", accountSid); + Serializer.toString(request, "AccountSid", accountSid, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/accounts/v1/credential/AwsDeleter.java b/src/main/java/com/twilio/rest/accounts/v1/credential/AwsDeleter.java index eb612e6321..f4a9d1d72c 100644 --- a/src/main/java/com/twilio/rest/accounts/v1/credential/AwsDeleter.java +++ b/src/main/java/com/twilio/rest/accounts/v1/credential/AwsDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.accounts.v1.credential; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,40 +26,38 @@ public class AwsDeleter extends Deleter { - private String pathSid; + private String pathsid; - public AwsDeleter(final String pathSid) { - this.pathSid = pathSid; + public AwsDeleter(final String pathsid) { + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/v1/Credentials/AWS/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.ACCOUNTS.toString(), - path + HttpMethod.DELETE, + Domains.ACCOUNTS.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Aws delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("Aws delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/accounts/v1/credential/AwsFetcher.java b/src/main/java/com/twilio/rest/accounts/v1/credential/AwsFetcher.java index 33ca4d5f2e..2472d11ce4 100644 --- a/src/main/java/com/twilio/rest/accounts/v1/credential/AwsFetcher.java +++ b/src/main/java/com/twilio/rest/accounts/v1/credential/AwsFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.accounts.v1.credential; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,44 +26,41 @@ public class AwsFetcher extends Fetcher { - private String pathSid; + private String pathsid; - public AwsFetcher(final String pathSid) { - this.pathSid = pathSid; + public AwsFetcher(final String pathsid) { + this.pathsid = pathsid; } + @Override public Aws fetch(final TwilioRestClient client) { + String path = "/v1/Credentials/AWS/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.ACCOUNTS.toString(), - path + HttpMethod.GET, + Domains.ACCOUNTS.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Aws fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Aws fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Aws.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/accounts/v1/credential/AwsReader.java b/src/main/java/com/twilio/rest/accounts/v1/credential/AwsReader.java index 4f1bf8ceaf..4be621467a 100644 --- a/src/main/java/com/twilio/rest/accounts/v1/credential/AwsReader.java +++ b/src/main/java/com/twilio/rest/accounts/v1/credential/AwsReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -31,105 +32,83 @@ public class AwsReader extends Reader { private Long pageSize; - public AwsReader() {} + public AwsReader() { + } + public AwsReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/Credentials/AWS"; + Request request = new Request( - HttpMethod.GET, - Domains.ACCOUNTS.toString(), - path + HttpMethod.GET, + Domains.ACCOUNTS.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Aws read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Aws read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "credentials", - response.getContent(), - Aws.class, - client.getObjectMapper() - ); + "credentials", + response.getContent(), + Aws.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.ACCOUNTS.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.ACCOUNTS.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/accounts/v1/credential/AwsUpdater.java b/src/main/java/com/twilio/rest/accounts/v1/credential/AwsUpdater.java index 73a98ba85a..a62dcd2979 100644 --- a/src/main/java/com/twilio/rest/accounts/v1/credential/AwsUpdater.java +++ b/src/main/java/com/twilio/rest/accounts/v1/credential/AwsUpdater.java @@ -16,6 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -26,47 +28,47 @@ import com.twilio.rest.Domains; public class AwsUpdater extends Updater { - - private String pathSid; + private String pathsid; private String friendlyName; - public AwsUpdater(final String pathSid) { - this.pathSid = pathSid; + public AwsUpdater(final String pathsid) { + this.pathsid = pathsid; } + public AwsUpdater setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + @Override public Aws update(final TwilioRestClient client) { + String path = "/v1/Credentials/AWS/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.ACCOUNTS.toString(), - path + HttpMethod.POST, + Domains.ACCOUNTS.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Aws update failed: Unable to connect to server" - ); + throw new ApiConnectionException("Aws update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -75,8 +77,11 @@ public Aws update(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/accounts/v1/credential/PublicKey.java b/src/main/java/com/twilio/rest/accounts/v1/credential/PublicKey.java index f77b6851d1..99251ab679 100644 --- a/src/main/java/com/twilio/rest/accounts/v1/credential/PublicKey.java +++ b/src/main/java/com/twilio/rest/accounts/v1/credential/PublicKey.java @@ -18,57 +18,70 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class PublicKey extends Resource { - private static final long serialVersionUID = 255841368009036L; public static PublicKeyCreator creator(final String publicKey) { - return new PublicKeyCreator(publicKey); + return new PublicKeyCreator( + publicKey + ); } - public static PublicKeyDeleter deleter(final String pathSid) { - return new PublicKeyDeleter(pathSid); + + public static PublicKeyDeleter deleter(final String pathsid) { + return new PublicKeyDeleter( + pathsid + ); } - public static PublicKeyFetcher fetcher(final String pathSid) { - return new PublicKeyFetcher(pathSid); + + public static PublicKeyFetcher fetcher(final String pathsid) { + return new PublicKeyFetcher( + pathsid + ); } + public static PublicKeyReader reader() { - return new PublicKeyReader(); + return new PublicKeyReader( + + ); } - public static PublicKeyUpdater updater(final String pathSid) { - return new PublicKeyUpdater(pathSid); + + public static PublicKeyUpdater updater(final String pathsid) { + return new PublicKeyUpdater( + pathsid + ); } + /** * Converts a JSON String into a PublicKey object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return PublicKey object represented by the provided JSON */ - public static PublicKey fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static PublicKey fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, PublicKey.class); @@ -83,14 +96,11 @@ public static PublicKey fromJson( * Converts a JSON InputStream into a PublicKey object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return PublicKey object represented by the provided JSON */ - public static PublicKey fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static PublicKey fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, PublicKey.class); @@ -101,54 +111,51 @@ public static PublicKey fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String friendlyName; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; + @Getter + private final String friendlyName; + @Getter + private final String sid; + @Getter private final URI url; @JsonCreator private PublicKey( - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("url") final URI url + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("sid") final String sid, + @JsonProperty("url") final URI url ) { - this.sid = sid; this.accountSid = accountSid; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.friendlyName = friendlyName; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); + this.sid = sid; this.url = url; } - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final URI getUrl() { - return this.url; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -160,26 +167,28 @@ public boolean equals(final Object o) { } PublicKey other = (PublicKey) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(url, other.url) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(sid, other.sid) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - sid, - accountSid, - friendlyName, - dateCreated, - dateUpdated, - url + accountSid, + dateCreated, + dateUpdated, + friendlyName, + sid, + url ); } + + } + diff --git a/src/main/java/com/twilio/rest/accounts/v1/credential/PublicKeyCreator.java b/src/main/java/com/twilio/rest/accounts/v1/credential/PublicKeyCreator.java index faded3ed3e..14e24e16e1 100644 --- a/src/main/java/com/twilio/rest/accounts/v1/credential/PublicKeyCreator.java +++ b/src/main/java/com/twilio/rest/accounts/v1/credential/PublicKeyCreator.java @@ -14,8 +14,11 @@ package com.twilio.rest.accounts.v1.credential; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -35,68 +38,73 @@ public PublicKeyCreator(final String publicKey) { this.publicKey = publicKey; } + public PublicKeyCreator setPublicKey(final String publicKey) { this.publicKey = publicKey; return this; } + public PublicKeyCreator setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + public PublicKeyCreator setAccountSid(final String accountSid) { this.accountSid = accountSid; return this; } + @Override public PublicKey create(final TwilioRestClient client) { + String path = "/v1/Credentials/PublicKeys"; - path = path.replace("{" + "PublicKey" + "}", this.publicKey.toString()); Request request = new Request( - HttpMethod.POST, - Domains.ACCOUNTS.toString(), - path + HttpMethod.POST, + Domains.ACCOUNTS.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "PublicKey creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("PublicKey creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return PublicKey.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return PublicKey.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (publicKey != null) { - request.addPostParam("PublicKey", publicKey); + Serializer.toString(request, "PublicKey", publicKey, ParameterType.URLENCODED); } + + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + if (accountSid != null) { - request.addPostParam("AccountSid", accountSid); + Serializer.toString(request, "AccountSid", accountSid, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/accounts/v1/credential/PublicKeyDeleter.java b/src/main/java/com/twilio/rest/accounts/v1/credential/PublicKeyDeleter.java index 3b4f32a9d9..ea656033d6 100644 --- a/src/main/java/com/twilio/rest/accounts/v1/credential/PublicKeyDeleter.java +++ b/src/main/java/com/twilio/rest/accounts/v1/credential/PublicKeyDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.accounts.v1.credential; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,40 +26,38 @@ public class PublicKeyDeleter extends Deleter { - private String pathSid; + private String pathsid; - public PublicKeyDeleter(final String pathSid) { - this.pathSid = pathSid; + public PublicKeyDeleter(final String pathsid) { + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/v1/Credentials/PublicKeys/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.ACCOUNTS.toString(), - path + HttpMethod.DELETE, + Domains.ACCOUNTS.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "PublicKey delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("PublicKey delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/accounts/v1/credential/PublicKeyFetcher.java b/src/main/java/com/twilio/rest/accounts/v1/credential/PublicKeyFetcher.java index ab52aced34..24f005a90e 100644 --- a/src/main/java/com/twilio/rest/accounts/v1/credential/PublicKeyFetcher.java +++ b/src/main/java/com/twilio/rest/accounts/v1/credential/PublicKeyFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.accounts.v1.credential; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,47 +26,41 @@ public class PublicKeyFetcher extends Fetcher { - private String pathSid; + private String pathsid; - public PublicKeyFetcher(final String pathSid) { - this.pathSid = pathSid; + public PublicKeyFetcher(final String pathsid) { + this.pathsid = pathsid; } + @Override public PublicKey fetch(final TwilioRestClient client) { + String path = "/v1/Credentials/PublicKeys/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.ACCOUNTS.toString(), - path + HttpMethod.GET, + Domains.ACCOUNTS.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "PublicKey fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("PublicKey fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return PublicKey.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return PublicKey.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/accounts/v1/credential/PublicKeyReader.java b/src/main/java/com/twilio/rest/accounts/v1/credential/PublicKeyReader.java index 8260d33584..5bbe52e284 100644 --- a/src/main/java/com/twilio/rest/accounts/v1/credential/PublicKeyReader.java +++ b/src/main/java/com/twilio/rest/accounts/v1/credential/PublicKeyReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -31,105 +32,83 @@ public class PublicKeyReader extends Reader { private Long pageSize; - public PublicKeyReader() {} + public PublicKeyReader() { + } + public PublicKeyReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/Credentials/PublicKeys"; + Request request = new Request( - HttpMethod.GET, - Domains.ACCOUNTS.toString(), - path + HttpMethod.GET, + Domains.ACCOUNTS.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "PublicKey read failed: Unable to connect to server" - ); + throw new ApiConnectionException("PublicKey read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "credentials", - response.getContent(), - PublicKey.class, - client.getObjectMapper() - ); + "credentials", + response.getContent(), + PublicKey.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.ACCOUNTS.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.ACCOUNTS.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/accounts/v1/credential/PublicKeyUpdater.java b/src/main/java/com/twilio/rest/accounts/v1/credential/PublicKeyUpdater.java index 4a49e782d3..7c89435a63 100644 --- a/src/main/java/com/twilio/rest/accounts/v1/credential/PublicKeyUpdater.java +++ b/src/main/java/com/twilio/rest/accounts/v1/credential/PublicKeyUpdater.java @@ -16,6 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -26,60 +28,60 @@ import com.twilio.rest.Domains; public class PublicKeyUpdater extends Updater { - - private String pathSid; + private String pathsid; private String friendlyName; - public PublicKeyUpdater(final String pathSid) { - this.pathSid = pathSid; + public PublicKeyUpdater(final String pathsid) { + this.pathsid = pathsid; } + public PublicKeyUpdater setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + @Override public PublicKey update(final TwilioRestClient client) { + String path = "/v1/Credentials/PublicKeys/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.ACCOUNTS.toString(), - path + HttpMethod.POST, + Domains.ACCOUNTS.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "PublicKey update failed: Unable to connect to server" - ); + throw new ApiConnectionException("PublicKey update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return PublicKey.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return PublicKey.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/api/v2010/Account.java b/src/main/java/com/twilio/rest/api/v2010/Account.java index 7ab47a5b18..2622da1dcb 100644 --- a/src/main/java/com/twilio/rest/api/v2010/Account.java +++ b/src/main/java/com/twilio/rest/api/v2010/Account.java @@ -18,63 +18,120 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.time.ZonedDateTime; import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Account extends Resource { - private static final long serialVersionUID = 224328589339754L; public static AccountCreator creator() { - return new AccountCreator(); + return new AccountCreator( + + ); } + public static AccountFetcher fetcher() { - return new AccountFetcher(); + return new AccountFetcher( + + ); } - public static AccountFetcher fetcher(final String pathSid) { - return new AccountFetcher(pathSid); + + public static AccountFetcher fetcher(final String pathsid) { + return new AccountFetcher( + pathsid + ); } + public static AccountReader reader() { - return new AccountReader(); + return new AccountReader( + + ); } + public static AccountUpdater updater() { - return new AccountUpdater(); + return new AccountUpdater( + + ); + } + + + public static AccountUpdater updater(final String pathsid) { + return new AccountUpdater( + pathsid + ); + } + + + public enum Status { + ACTIVE("active"), + SUSPENDED("suspended"), + CLOSED("closed"); + + private final String value; + + private Status(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static Status forValue(final String value) { + return Promoter.enumFromString(value, Status.values()); + } } - public static AccountUpdater updater(final String pathSid) { - return new AccountUpdater(pathSid); + public enum Type { + TRIAL("Trial"), + FULL("Full"); + + private final String value; + + private Type(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static Type forValue(final String value) { + return Promoter.enumFromString(value, Type.values()); + } } + /** * Converts a JSON String into a Account object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Account object represented by the provided JSON */ - public static Account fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Account fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Account.class); @@ -89,14 +146,11 @@ public static Account fromJson( * Converts a JSON InputStream into a Account object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Account object represented by the provided JSON */ - public static Account fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Account fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Account.class); @@ -107,36 +161,58 @@ public static Account fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String authToken; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; + @Getter private final String friendlyName; + @Getter private final String ownerAccountSid; + @Getter private final String sid; + @Getter private final Account.Status status; + @Getter private final Map subresourceUris; + @Getter private final Account.Type type; + @Getter private final String uri; @JsonCreator private Account( - @JsonProperty("auth_token") final String authToken, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("owner_account_sid") final String ownerAccountSid, - @JsonProperty("sid") final String sid, - @JsonProperty("status") final Account.Status status, - @JsonProperty("subresource_uris") final Map< - String, - String - > subresourceUris, - @JsonProperty("type") final Account.Type type, - @JsonProperty("uri") final String uri + @JsonProperty("auth_token") final String authToken, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.RFC2822Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.RFC2822Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("owner_account_sid") final String ownerAccountSid, + @JsonProperty("sid") final String sid, + @JsonProperty("status") final Account.Status status, + @JsonProperty("subresource_uris") final Map subresourceUris, + @JsonProperty("type") final Account.Type type, + @JsonProperty("uri") final String uri ) { this.authToken = authToken; - this.dateCreated = DateConverter.rfc2822DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.rfc2822DateTimeFromString(dateUpdated); + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.friendlyName = friendlyName; this.ownerAccountSid = ownerAccountSid; this.sid = sid; @@ -146,46 +222,6 @@ private Account( this.uri = uri; } - public final String getAuthToken() { - return this.authToken; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final String getOwnerAccountSid() { - return this.ownerAccountSid; - } - - public final String getSid() { - return this.sid; - } - - public final Account.Status getStatus() { - return this.status; - } - - public final Map getSubresourceUris() { - return this.subresourceUris; - } - - public final Account.Type getType() { - return this.type; - } - - public final String getUri() { - return this.uri; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -197,75 +233,36 @@ public boolean equals(final Object o) { } Account other = (Account) o; - return ( - Objects.equals(authToken, other.authToken) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(ownerAccountSid, other.ownerAccountSid) && - Objects.equals(sid, other.sid) && - Objects.equals(status, other.status) && - Objects.equals(subresourceUris, other.subresourceUris) && - Objects.equals(type, other.type) && - Objects.equals(uri, other.uri) + Objects.equals(authToken, other.authToken) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(ownerAccountSid, other.ownerAccountSid) && + Objects.equals(sid, other.sid) && + Objects.equals(status, other.status) && + Objects.equals(subresourceUris, other.subresourceUris) && + Objects.equals(type, other.type) && + Objects.equals(uri, other.uri) ); } @Override public int hashCode() { return Objects.hash( - authToken, - dateCreated, - dateUpdated, - friendlyName, - ownerAccountSid, - sid, - status, - subresourceUris, - type, - uri + authToken, + dateCreated, + dateUpdated, + friendlyName, + ownerAccountSid, + sid, + status, + subresourceUris, + type, + uri ); } - public enum Status { - ACTIVE("active"), - SUSPENDED("suspended"), - CLOSED("closed"); - - private final String value; - private Status(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static Status forValue(final String value) { - return Promoter.enumFromString(value, Status.values()); - } - } - - public enum Type { - TRIAL("Trial"), - FULL("Full"); - - private final String value; - - private Type(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static Type forValue(final String value) { - return Promoter.enumFromString(value, Type.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/api/v2010/AccountCreator.java b/src/main/java/com/twilio/rest/api/v2010/AccountCreator.java index d98a43a6c5..a2649c7093 100644 --- a/src/main/java/com/twilio/rest/api/v2010/AccountCreator.java +++ b/src/main/java/com/twilio/rest/api/v2010/AccountCreator.java @@ -14,8 +14,11 @@ package com.twilio.rest.api.v2010; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,39 +32,41 @@ public class AccountCreator extends Creator { private String friendlyName; - public AccountCreator() {} + public AccountCreator() { + } + public AccountCreator setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + @Override public Account create(final TwilioRestClient client) { + String path = "/2010-04-01/Accounts.json"; + Request request = new Request( - HttpMethod.POST, - Domains.API.toString(), - path + HttpMethod.POST, + Domains.API.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Account creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("Account creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -70,8 +75,11 @@ public Account create(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/api/v2010/AccountFetcher.java b/src/main/java/com/twilio/rest/api/v2010/AccountFetcher.java index 0240bdc071..3c6aa67425 100644 --- a/src/main/java/com/twilio/rest/api/v2010/AccountFetcher.java +++ b/src/main/java/com/twilio/rest/api/v2010/AccountFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.api.v2010; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,48 +26,45 @@ public class AccountFetcher extends Fetcher { - private String pathSid; + private String pathsid; - public AccountFetcher() {} + public AccountFetcher() { + } - public AccountFetcher(final String pathSid) { - this.pathSid = pathSid; + public AccountFetcher(final String pathsid) { + this.pathsid = pathsid; } + @Override public Account fetch(final TwilioRestClient client) { + String path = "/2010-04-01/Accounts/{Sid}.json"; - this.pathSid = - this.pathSid == null ? client.getAccountSid() : this.pathSid; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + this.pathsid = this.pathsid == null ? client.getAccountSid() : this.pathsid; + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.API.toString(), - path + HttpMethod.GET, + Domains.API.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Account fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Account fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Account.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/api/v2010/AccountReader.java b/src/main/java/com/twilio/rest/api/v2010/AccountReader.java index 41419f0d38..c176473a8b 100644 --- a/src/main/java/com/twilio/rest/api/v2010/AccountReader.java +++ b/src/main/java/com/twilio/rest/api/v2010/AccountReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -33,121 +34,105 @@ public class AccountReader extends Reader { private Account.Status status; private Long pageSize; - public AccountReader() {} + public AccountReader() { + } + public AccountReader setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + public AccountReader setStatus(final Account.Status status) { this.status = status; return this; } + public AccountReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/2010-04-01/Accounts.json"; + Request request = new Request( - HttpMethod.GET, - Domains.API.toString(), - path + HttpMethod.GET, + Domains.API.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Account read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Account read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "accounts", - response.getContent(), - Account.class, - client.getObjectMapper() - ); + "accounts", + response.getContent(), + Account.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.API.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.API.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (friendlyName != null) { - request.addQueryParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.QUERY); } + + if (status != null) { - request.addQueryParam("Status", status.toString()); + Serializer.toString(request, "Status", status, ParameterType.QUERY); } + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/api/v2010/AccountUpdater.java b/src/main/java/com/twilio/rest/api/v2010/AccountUpdater.java index 838f34b793..edb3e3a04e 100644 --- a/src/main/java/com/twilio/rest/api/v2010/AccountUpdater.java +++ b/src/main/java/com/twilio/rest/api/v2010/AccountUpdater.java @@ -16,6 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -26,57 +28,58 @@ import com.twilio.rest.Domains; public class AccountUpdater extends Updater { - - private String pathSid; + private String pathsid; private String friendlyName; private Account.Status status; - public AccountUpdater() {} + public AccountUpdater() { + } - public AccountUpdater(final String pathSid) { - this.pathSid = pathSid; + public AccountUpdater(final String pathsid) { + this.pathsid = pathsid; } + public AccountUpdater setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + public AccountUpdater setStatus(final Account.Status status) { this.status = status; return this; } + @Override public Account update(final TwilioRestClient client) { + String path = "/2010-04-01/Accounts/{Sid}.json"; - this.pathSid = - this.pathSid == null ? client.getAccountSid() : this.pathSid; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + this.pathsid = this.pathsid == null ? client.getAccountSid() : this.pathsid; + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.API.toString(), - path + HttpMethod.POST, + Domains.API.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Account update failed: Unable to connect to server" - ); + throw new ApiConnectionException("Account update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -85,11 +88,16 @@ public Account update(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + if (status != null) { - request.addPostParam("Status", status.toString()); + Serializer.toString(request, "Status", status, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/Address.java b/src/main/java/com/twilio/rest/api/v2010/account/Address.java index 8a53321f3c..7cd236ec5f 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/Address.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/Address.java @@ -18,115 +18,104 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.time.ZonedDateTime; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Address extends Resource { - private static final long serialVersionUID = 73808189531379L; - public static AddressCreator creator( - final String customerName, - final String street, - final String city, - final String region, - final String postalCode, - final String isoCountry - ) { + public static AddressCreator creator(final String customerName, final String street, final String city, final String region, final String postalCode, final String isoCountry) { return new AddressCreator( - customerName, - street, - city, - region, - postalCode, - isoCountry + customerName, street, city, region, postalCode, isoCountry ); } - public static AddressCreator creator( - final String pathAccountSid, - final String customerName, - final String street, - final String city, - final String region, - final String postalCode, - final String isoCountry - ) { + + public static AddressCreator creator(final String pathaccountSid, final String customerName, final String street, final String city, final String region, final String postalCode, final String isoCountry) { return new AddressCreator( - pathAccountSid, - customerName, - street, - city, - region, - postalCode, - isoCountry + pathaccountSid, customerName, street, city, region, postalCode, isoCountry ); } - public static AddressDeleter deleter(final String pathSid) { - return new AddressDeleter(pathSid); + + public static AddressDeleter deleter(final String pathsid) { + return new AddressDeleter( + pathsid + ); } - public static AddressDeleter deleter( - final String pathAccountSid, - final String pathSid - ) { - return new AddressDeleter(pathAccountSid, pathSid); + + public static AddressDeleter deleter(final String pathaccountSid, final String pathsid) { + return new AddressDeleter( + pathaccountSid, pathsid + ); } - public static AddressFetcher fetcher(final String pathSid) { - return new AddressFetcher(pathSid); + + public static AddressFetcher fetcher(final String pathsid) { + return new AddressFetcher( + pathsid + ); } - public static AddressFetcher fetcher( - final String pathAccountSid, - final String pathSid - ) { - return new AddressFetcher(pathAccountSid, pathSid); + + public static AddressFetcher fetcher(final String pathaccountSid, final String pathsid) { + return new AddressFetcher( + pathaccountSid, pathsid + ); } + public static AddressReader reader() { - return new AddressReader(); + return new AddressReader( + + ); } - public static AddressReader reader(final String pathAccountSid) { - return new AddressReader(pathAccountSid); + + public static AddressReader reader(final String pathaccountSid) { + return new AddressReader( + pathaccountSid + ); } - public static AddressUpdater updater(final String pathSid) { - return new AddressUpdater(pathSid); + + public static AddressUpdater updater(final String pathsid) { + return new AddressUpdater( + pathsid + ); } - public static AddressUpdater updater( - final String pathAccountSid, - final String pathSid - ) { - return new AddressUpdater(pathAccountSid, pathSid); + + public static AddressUpdater updater(final String pathaccountSid, final String pathsid) { + return new AddressUpdater( + pathaccountSid, pathsid + ); } + /** * Converts a JSON String into a Address object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Address object represented by the provided JSON */ - public static Address fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Address fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Address.class); @@ -141,14 +130,11 @@ public static Address fromJson( * Converts a JSON InputStream into a Address object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Address object represented by the provided JSON */ - public static Address fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Address fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Address.class); @@ -159,122 +145,89 @@ public static Address fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; + @Getter private final String city; + @Getter private final String customerName; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; + @Getter + private final Boolean emergencyEnabled; + @Getter private final String friendlyName; + @Getter private final String isoCountry; + @Getter private final String postalCode; + @Getter private final String region; + @Getter private final String sid; + @Getter private final String street; + @Getter + private final String streetSecondary; + @Getter private final String uri; - private final Boolean emergencyEnabled; + @Getter private final Boolean validated; + @Getter private final Boolean verified; - private final String streetSecondary; @JsonCreator private Address( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("city") final String city, - @JsonProperty("customer_name") final String customerName, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("iso_country") final String isoCountry, - @JsonProperty("postal_code") final String postalCode, - @JsonProperty("region") final String region, - @JsonProperty("sid") final String sid, - @JsonProperty("street") final String street, - @JsonProperty("uri") final String uri, - @JsonProperty("emergency_enabled") final Boolean emergencyEnabled, - @JsonProperty("validated") final Boolean validated, - @JsonProperty("verified") final Boolean verified, - @JsonProperty("street_secondary") final String streetSecondary + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("city") final String city, + @JsonProperty("customer_name") final String customerName, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.RFC2822Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.RFC2822Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("emergency_enabled") final Boolean emergencyEnabled, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("iso_country") final String isoCountry, + @JsonProperty("postal_code") final String postalCode, + @JsonProperty("region") final String region, + @JsonProperty("sid") final String sid, + @JsonProperty("street") final String street, + @JsonProperty("street_secondary") final String streetSecondary, + @JsonProperty("uri") final String uri, + @JsonProperty("validated") final Boolean validated, + @JsonProperty("verified") final Boolean verified ) { this.accountSid = accountSid; this.city = city; this.customerName = customerName; - this.dateCreated = DateConverter.rfc2822DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.rfc2822DateTimeFromString(dateUpdated); + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; + this.emergencyEnabled = emergencyEnabled; this.friendlyName = friendlyName; this.isoCountry = isoCountry; this.postalCode = postalCode; this.region = region; this.sid = sid; this.street = street; + this.streetSecondary = streetSecondary; this.uri = uri; - this.emergencyEnabled = emergencyEnabled; this.validated = validated; this.verified = verified; - this.streetSecondary = streetSecondary; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getCity() { - return this.city; - } - - public final String getCustomerName() { - return this.customerName; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final String getIsoCountry() { - return this.isoCountry; - } - - public final String getPostalCode() { - return this.postalCode; - } - - public final String getRegion() { - return this.region; - } - - public final String getSid() { - return this.sid; - } - - public final String getStreet() { - return this.street; - } - - public final String getUri() { - return this.uri; - } - - public final Boolean getEmergencyEnabled() { - return this.emergencyEnabled; - } - - public final Boolean getValidated() { - return this.validated; - } - - public final Boolean getVerified() { - return this.verified; - } - - public final String getStreetSecondary() { - return this.streetSecondary; } @Override @@ -288,46 +241,48 @@ public boolean equals(final Object o) { } Address other = (Address) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(city, other.city) && - Objects.equals(customerName, other.customerName) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(isoCountry, other.isoCountry) && - Objects.equals(postalCode, other.postalCode) && - Objects.equals(region, other.region) && - Objects.equals(sid, other.sid) && - Objects.equals(street, other.street) && - Objects.equals(uri, other.uri) && - Objects.equals(emergencyEnabled, other.emergencyEnabled) && - Objects.equals(validated, other.validated) && - Objects.equals(verified, other.verified) && - Objects.equals(streetSecondary, other.streetSecondary) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(city, other.city) && + Objects.equals(customerName, other.customerName) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(emergencyEnabled, other.emergencyEnabled) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(isoCountry, other.isoCountry) && + Objects.equals(postalCode, other.postalCode) && + Objects.equals(region, other.region) && + Objects.equals(sid, other.sid) && + Objects.equals(street, other.street) && + Objects.equals(streetSecondary, other.streetSecondary) && + Objects.equals(uri, other.uri) && + Objects.equals(validated, other.validated) && + Objects.equals(verified, other.verified) ); } @Override public int hashCode() { return Objects.hash( - accountSid, - city, - customerName, - dateCreated, - dateUpdated, - friendlyName, - isoCountry, - postalCode, - region, - sid, - street, - uri, - emergencyEnabled, - validated, - verified, - streetSecondary + accountSid, + city, + customerName, + dateCreated, + dateUpdated, + emergencyEnabled, + friendlyName, + isoCountry, + postalCode, + region, + sid, + street, + streetSecondary, + uri, + validated, + verified ); } + + } + diff --git a/src/main/java/com/twilio/rest/api/v2010/account/AddressCreator.java b/src/main/java/com/twilio/rest/api/v2010/account/AddressCreator.java index 682ce3e562..af6e0efa02 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/AddressCreator.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/AddressCreator.java @@ -14,8 +14,11 @@ package com.twilio.rest.api.v2010.account; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,26 +30,19 @@ public class AddressCreator extends Creator
{ + private String pathaccountSid; private String customerName; private String street; private String city; private String region; private String postalCode; private String isoCountry; - private String pathAccountSid; private String friendlyName; private Boolean emergencyEnabled; private Boolean autoCorrectAddress; private String streetSecondary; - public AddressCreator( - final String customerName, - final String street, - final String city, - final String region, - final String postalCode, - final String isoCountry - ) { + public AddressCreator(final String customerName, final String street, final String city, final String region, final String postalCode, final String isoCountry) { this.customerName = customerName; this.street = street; this.city = city; @@ -55,16 +51,8 @@ public AddressCreator( this.isoCountry = isoCountry; } - public AddressCreator( - final String pathAccountSid, - final String customerName, - final String street, - final String city, - final String region, - final String postalCode, - final String isoCountry - ) { - this.pathAccountSid = pathAccountSid; + public AddressCreator(final String pathaccountSid, final String customerName, final String street, final String city, final String region, final String postalCode, final String isoCountry) { + this.pathaccountSid = pathaccountSid; this.customerName = customerName; this.street = street; this.city = city; @@ -73,106 +61,95 @@ public AddressCreator( this.isoCountry = isoCountry; } + public AddressCreator setCustomerName(final String customerName) { this.customerName = customerName; return this; } + public AddressCreator setStreet(final String street) { this.street = street; return this; } + public AddressCreator setCity(final String city) { this.city = city; return this; } + public AddressCreator setRegion(final String region) { this.region = region; return this; } + public AddressCreator setPostalCode(final String postalCode) { this.postalCode = postalCode; return this; } + public AddressCreator setIsoCountry(final String isoCountry) { this.isoCountry = isoCountry; return this; } + public AddressCreator setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + public AddressCreator setEmergencyEnabled(final Boolean emergencyEnabled) { this.emergencyEnabled = emergencyEnabled; return this; } - public AddressCreator setAutoCorrectAddress( - final Boolean autoCorrectAddress - ) { + + public AddressCreator setAutoCorrectAddress(final Boolean autoCorrectAddress) { this.autoCorrectAddress = autoCorrectAddress; return this; } + public AddressCreator setStreetSecondary(final String streetSecondary) { this.streetSecondary = streetSecondary; return this; } + @Override public Address create(final TwilioRestClient client) { + String path = "/2010-04-01/Accounts/{AccountSid}/Addresses.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = - path.replace( - "{" + "CustomerName" + "}", - this.customerName.toString() - ); - path = path.replace("{" + "Street" + "}", this.street.toString()); - path = path.replace("{" + "City" + "}", this.city.toString()); - path = path.replace("{" + "Region" + "}", this.region.toString()); - path = - path.replace("{" + "PostalCode" + "}", this.postalCode.toString()); - path = - path.replace("{" + "IsoCountry" + "}", this.isoCountry.toString()); + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.API.toString(), - path + HttpMethod.POST, + Domains.API.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Address creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("Address creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -181,41 +158,56 @@ public Address create(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (customerName != null) { - request.addPostParam("CustomerName", customerName); + Serializer.toString(request, "CustomerName", customerName, ParameterType.URLENCODED); } + + if (street != null) { - request.addPostParam("Street", street); + Serializer.toString(request, "Street", street, ParameterType.URLENCODED); } + + if (city != null) { - request.addPostParam("City", city); + Serializer.toString(request, "City", city, ParameterType.URLENCODED); } + + if (region != null) { - request.addPostParam("Region", region); + Serializer.toString(request, "Region", region, ParameterType.URLENCODED); } + + if (postalCode != null) { - request.addPostParam("PostalCode", postalCode); + Serializer.toString(request, "PostalCode", postalCode, ParameterType.URLENCODED); } + + if (isoCountry != null) { - request.addPostParam("IsoCountry", isoCountry); + Serializer.toString(request, "IsoCountry", isoCountry, ParameterType.URLENCODED); } + + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + if (emergencyEnabled != null) { - request.addPostParam( - "EmergencyEnabled", - emergencyEnabled.toString() - ); + Serializer.toString(request, "EmergencyEnabled", emergencyEnabled, ParameterType.URLENCODED); } + + if (autoCorrectAddress != null) { - request.addPostParam( - "AutoCorrectAddress", - autoCorrectAddress.toString() - ); + Serializer.toString(request, "AutoCorrectAddress", autoCorrectAddress, ParameterType.URLENCODED); } + + if (streetSecondary != null) { - request.addPostParam("StreetSecondary", streetSecondary); + Serializer.toString(request, "StreetSecondary", streetSecondary, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/AddressDeleter.java b/src/main/java/com/twilio/rest/api/v2010/account/AddressDeleter.java index 5bf0c43296..9e87d8353b 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/AddressDeleter.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/AddressDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.api.v2010.account; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,55 +26,46 @@ public class AddressDeleter extends Deleter
{ - private String pathSid; - private String pathAccountSid; + private String pathaccountSid; + private String pathsid; - public AddressDeleter(final String pathSid) { - this.pathSid = pathSid; + public AddressDeleter(final String pathsid) { + this.pathsid = pathsid; } - public AddressDeleter(final String pathAccountSid, final String pathSid) { - this.pathAccountSid = pathAccountSid; - this.pathSid = pathSid; + public AddressDeleter(final String pathaccountSid, final String pathsid) { + this.pathaccountSid = pathaccountSid; + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/2010-04-01/Accounts/{AccountSid}/Addresses/{Sid}.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.API.toString(), - path + HttpMethod.DELETE, + Domains.API.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Address delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("Address delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/AddressFetcher.java b/src/main/java/com/twilio/rest/api/v2010/account/AddressFetcher.java index 50e8149ded..2cbb068aa8 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/AddressFetcher.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/AddressFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.api.v2010.account; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,59 +26,49 @@ public class AddressFetcher extends Fetcher
{ - private String pathSid; - private String pathAccountSid; + private String pathaccountSid; + private String pathsid; - public AddressFetcher(final String pathSid) { - this.pathSid = pathSid; + public AddressFetcher(final String pathsid) { + this.pathsid = pathsid; } - public AddressFetcher(final String pathAccountSid, final String pathSid) { - this.pathAccountSid = pathAccountSid; - this.pathSid = pathSid; + public AddressFetcher(final String pathaccountSid, final String pathsid) { + this.pathaccountSid = pathaccountSid; + this.pathsid = pathsid; } + @Override public Address fetch(final TwilioRestClient client) { + String path = "/2010-04-01/Accounts/{AccountSid}/Addresses/{Sid}.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.API.toString(), - path + HttpMethod.GET, + Domains.API.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Address fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Address fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Address.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/AddressReader.java b/src/main/java/com/twilio/rest/api/v2010/account/AddressReader.java index 951b4aac16..1feb2c9d5b 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/AddressReader.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/AddressReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,160 +30,140 @@ public class AddressReader extends Reader
{ - private String pathAccountSid; + private String pathaccountSid; private String customerName; private String friendlyName; private Boolean emergencyEnabled; private String isoCountry; private Long pageSize; - public AddressReader() {} + public AddressReader() { + } - public AddressReader(final String pathAccountSid) { - this.pathAccountSid = pathAccountSid; + public AddressReader(final String pathaccountSid) { + this.pathaccountSid = pathaccountSid; } + public AddressReader setCustomerName(final String customerName) { this.customerName = customerName; return this; } + public AddressReader setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + public AddressReader setEmergencyEnabled(final Boolean emergencyEnabled) { this.emergencyEnabled = emergencyEnabled; return this; } + public AddressReader setIsoCountry(final String isoCountry) { this.isoCountry = isoCountry; return this; } + public AddressReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet
read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page
firstPage(final TwilioRestClient client) { + String path = "/2010-04-01/Accounts/{AccountSid}/Addresses.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.API.toString(), - path + HttpMethod.GET, + Domains.API.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page
pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page
pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Address read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Address read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "addresses", - response.getContent(), - Address.class, - client.getObjectMapper() - ); + "addresses", + response.getContent(), + Address.class, + client.getObjectMapper()); } @Override - public Page
previousPage( - final Page
page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.API.toString()) - ); + public Page
previousPage(final Page
page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page
nextPage( - final Page
page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.API.toString()) - ); + public Page
nextPage(final Page
page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page
getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page
getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (customerName != null) { - request.addQueryParam("CustomerName", customerName); + Serializer.toString(request, "CustomerName", customerName, ParameterType.QUERY); } + + if (friendlyName != null) { - request.addQueryParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.QUERY); } + + if (emergencyEnabled != null) { - request.addQueryParam( - "EmergencyEnabled", - emergencyEnabled.toString() - ); + Serializer.toString(request, "EmergencyEnabled", emergencyEnabled, ParameterType.QUERY); } + + if (isoCountry != null) { - request.addQueryParam("IsoCountry", isoCountry); + Serializer.toString(request, "IsoCountry", isoCountry, ParameterType.QUERY); } + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/AddressUpdater.java b/src/main/java/com/twilio/rest/api/v2010/account/AddressUpdater.java index 87bca4bc48..f2f5431739 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/AddressUpdater.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/AddressUpdater.java @@ -16,6 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -26,9 +28,8 @@ import com.twilio.rest.Domains; public class AddressUpdater extends Updater
{ - - private String pathSid; - private String pathAccountSid; + private String pathaccountSid; + private String pathsid; private String friendlyName; private String customerName; private String street; @@ -39,99 +40,99 @@ public class AddressUpdater extends Updater
{ private Boolean autoCorrectAddress; private String streetSecondary; - public AddressUpdater(final String pathSid) { - this.pathSid = pathSid; + public AddressUpdater(final String pathsid) { + this.pathsid = pathsid; } - public AddressUpdater(final String pathAccountSid, final String pathSid) { - this.pathAccountSid = pathAccountSid; - this.pathSid = pathSid; + public AddressUpdater(final String pathaccountSid, final String pathsid) { + this.pathaccountSid = pathaccountSid; + this.pathsid = pathsid; } + public AddressUpdater setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + public AddressUpdater setCustomerName(final String customerName) { this.customerName = customerName; return this; } + public AddressUpdater setStreet(final String street) { this.street = street; return this; } + public AddressUpdater setCity(final String city) { this.city = city; return this; } + public AddressUpdater setRegion(final String region) { this.region = region; return this; } + public AddressUpdater setPostalCode(final String postalCode) { this.postalCode = postalCode; return this; } + public AddressUpdater setEmergencyEnabled(final Boolean emergencyEnabled) { this.emergencyEnabled = emergencyEnabled; return this; } - public AddressUpdater setAutoCorrectAddress( - final Boolean autoCorrectAddress - ) { + + public AddressUpdater setAutoCorrectAddress(final Boolean autoCorrectAddress) { this.autoCorrectAddress = autoCorrectAddress; return this; } + public AddressUpdater setStreetSecondary(final String streetSecondary) { this.streetSecondary = streetSecondary; return this; } + @Override public Address update(final TwilioRestClient client) { + String path = "/2010-04-01/Accounts/{AccountSid}/Addresses/{Sid}.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.API.toString(), - path + HttpMethod.POST, + Domains.API.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Address update failed: Unable to connect to server" - ); + throw new ApiConnectionException("Address update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -140,38 +141,51 @@ public Address update(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + if (customerName != null) { - request.addPostParam("CustomerName", customerName); + Serializer.toString(request, "CustomerName", customerName, ParameterType.URLENCODED); } + + if (street != null) { - request.addPostParam("Street", street); + Serializer.toString(request, "Street", street, ParameterType.URLENCODED); } + + if (city != null) { - request.addPostParam("City", city); + Serializer.toString(request, "City", city, ParameterType.URLENCODED); } + + if (region != null) { - request.addPostParam("Region", region); + Serializer.toString(request, "Region", region, ParameterType.URLENCODED); } + + if (postalCode != null) { - request.addPostParam("PostalCode", postalCode); + Serializer.toString(request, "PostalCode", postalCode, ParameterType.URLENCODED); } + + if (emergencyEnabled != null) { - request.addPostParam( - "EmergencyEnabled", - emergencyEnabled.toString() - ); + Serializer.toString(request, "EmergencyEnabled", emergencyEnabled, ParameterType.URLENCODED); } + + if (autoCorrectAddress != null) { - request.addPostParam( - "AutoCorrectAddress", - autoCorrectAddress.toString() - ); + Serializer.toString(request, "AutoCorrectAddress", autoCorrectAddress, ParameterType.URLENCODED); } + + if (streetSecondary != null) { - request.addPostParam("StreetSecondary", streetSecondary); + Serializer.toString(request, "StreetSecondary", streetSecondary, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/Application.java b/src/main/java/com/twilio/rest/api/v2010/account/Application.java index d9e76250e5..e6eff176ed 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/Application.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/Application.java @@ -18,87 +18,106 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.http.HttpMethod; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Application extends Resource { - private static final long serialVersionUID = 38146741905668L; public static ApplicationCreator creator() { - return new ApplicationCreator(); + return new ApplicationCreator( + + ); } - public static ApplicationCreator creator(final String pathAccountSid) { - return new ApplicationCreator(pathAccountSid); + + public static ApplicationCreator creator(final String pathaccountSid) { + return new ApplicationCreator( + pathaccountSid + ); } - public static ApplicationDeleter deleter(final String pathSid) { - return new ApplicationDeleter(pathSid); + + public static ApplicationDeleter deleter(final String pathsid) { + return new ApplicationDeleter( + pathsid + ); } - public static ApplicationDeleter deleter( - final String pathAccountSid, - final String pathSid - ) { - return new ApplicationDeleter(pathAccountSid, pathSid); + + public static ApplicationDeleter deleter(final String pathaccountSid, final String pathsid) { + return new ApplicationDeleter( + pathaccountSid, pathsid + ); } - public static ApplicationFetcher fetcher(final String pathSid) { - return new ApplicationFetcher(pathSid); + + public static ApplicationFetcher fetcher(final String pathsid) { + return new ApplicationFetcher( + pathsid + ); } - public static ApplicationFetcher fetcher( - final String pathAccountSid, - final String pathSid - ) { - return new ApplicationFetcher(pathAccountSid, pathSid); + + public static ApplicationFetcher fetcher(final String pathaccountSid, final String pathsid) { + return new ApplicationFetcher( + pathaccountSid, pathsid + ); } + public static ApplicationReader reader() { - return new ApplicationReader(); + return new ApplicationReader( + + ); } - public static ApplicationReader reader(final String pathAccountSid) { - return new ApplicationReader(pathAccountSid); + + public static ApplicationReader reader(final String pathaccountSid) { + return new ApplicationReader( + pathaccountSid + ); } - public static ApplicationUpdater updater(final String pathSid) { - return new ApplicationUpdater(pathSid); + + public static ApplicationUpdater updater(final String pathsid) { + return new ApplicationUpdater( + pathsid + ); } - public static ApplicationUpdater updater( - final String pathAccountSid, - final String pathSid - ) { - return new ApplicationUpdater(pathAccountSid, pathSid); + + public static ApplicationUpdater updater(final String pathaccountSid, final String pathsid) { + return new ApplicationUpdater( + pathaccountSid, pathsid + ); } + /** * Converts a JSON String into a Application object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Application object represented by the provided JSON */ - public static Application fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Application fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Application.class); @@ -113,14 +132,11 @@ public static Application fromJson( * Converts a JSON InputStream into a Application object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Application object represented by the provided JSON */ - public static Application fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Application fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Application.class); @@ -131,68 +147,95 @@ public static Application fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; + @Getter private final String apiVersion; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; + @Getter private final String friendlyName; + @Getter private final URI messageStatusCallback; + @Getter + private final Boolean publicApplicationConnectEnabled; + @Getter private final String sid; + @Getter private final HttpMethod smsFallbackMethod; + @Getter private final URI smsFallbackUrl; + @Getter private final HttpMethod smsMethod; + @Getter private final URI smsStatusCallback; + @Getter private final URI smsUrl; + @Getter private final URI statusCallback; + @Getter private final HttpMethod statusCallbackMethod; + @Getter private final String uri; + @Getter private final Boolean voiceCallerIdLookup; + @Getter private final HttpMethod voiceFallbackMethod; + @Getter private final URI voiceFallbackUrl; + @Getter private final HttpMethod voiceMethod; + @Getter private final URI voiceUrl; - private final Boolean publicApplicationConnectEnabled; @JsonCreator private Application( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("api_version") final String apiVersion, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty( - "message_status_callback" - ) final URI messageStatusCallback, - @JsonProperty("sid") final String sid, - @JsonProperty("sms_fallback_method") final HttpMethod smsFallbackMethod, - @JsonProperty("sms_fallback_url") final URI smsFallbackUrl, - @JsonProperty("sms_method") final HttpMethod smsMethod, - @JsonProperty("sms_status_callback") final URI smsStatusCallback, - @JsonProperty("sms_url") final URI smsUrl, - @JsonProperty("status_callback") final URI statusCallback, - @JsonProperty( - "status_callback_method" - ) final HttpMethod statusCallbackMethod, - @JsonProperty("uri") final String uri, - @JsonProperty( - "voice_caller_id_lookup" - ) final Boolean voiceCallerIdLookup, - @JsonProperty( - "voice_fallback_method" - ) final HttpMethod voiceFallbackMethod, - @JsonProperty("voice_fallback_url") final URI voiceFallbackUrl, - @JsonProperty("voice_method") final HttpMethod voiceMethod, - @JsonProperty("voice_url") final URI voiceUrl, - @JsonProperty( - "public_application_connect_enabled" - ) final Boolean publicApplicationConnectEnabled + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("api_version") final String apiVersion, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.RFC2822Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.RFC2822Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("message_status_callback") final URI messageStatusCallback, + @JsonProperty("public_application_connect_enabled") final Boolean publicApplicationConnectEnabled, + @JsonProperty("sid") final String sid, + @JsonProperty("sms_fallback_method") final HttpMethod smsFallbackMethod, + @JsonProperty("sms_fallback_url") final URI smsFallbackUrl, + @JsonProperty("sms_method") final HttpMethod smsMethod, + @JsonProperty("sms_status_callback") final URI smsStatusCallback, + @JsonProperty("sms_url") final URI smsUrl, + @JsonProperty("status_callback") final URI statusCallback, + @JsonProperty("status_callback_method") final HttpMethod statusCallbackMethod, + @JsonProperty("uri") final String uri, + @JsonProperty("voice_caller_id_lookup") final Boolean voiceCallerIdLookup, + @JsonProperty("voice_fallback_method") final HttpMethod voiceFallbackMethod, + @JsonProperty("voice_fallback_url") final URI voiceFallbackUrl, + @JsonProperty("voice_method") final HttpMethod voiceMethod, + @JsonProperty("voice_url") final URI voiceUrl ) { this.accountSid = accountSid; this.apiVersion = apiVersion; - this.dateCreated = DateConverter.rfc2822DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.rfc2822DateTimeFromString(dateUpdated); + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.friendlyName = friendlyName; this.messageStatusCallback = messageStatusCallback; + this.publicApplicationConnectEnabled = publicApplicationConnectEnabled; this.sid = sid; this.smsFallbackMethod = smsFallbackMethod; this.smsFallbackUrl = smsFallbackUrl; @@ -207,91 +250,6 @@ private Application( this.voiceFallbackUrl = voiceFallbackUrl; this.voiceMethod = voiceMethod; this.voiceUrl = voiceUrl; - this.publicApplicationConnectEnabled = publicApplicationConnectEnabled; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getApiVersion() { - return this.apiVersion; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final URI getMessageStatusCallback() { - return this.messageStatusCallback; - } - - public final String getSid() { - return this.sid; - } - - public final HttpMethod getSmsFallbackMethod() { - return this.smsFallbackMethod; - } - - public final URI getSmsFallbackUrl() { - return this.smsFallbackUrl; - } - - public final HttpMethod getSmsMethod() { - return this.smsMethod; - } - - public final URI getSmsStatusCallback() { - return this.smsStatusCallback; - } - - public final URI getSmsUrl() { - return this.smsUrl; - } - - public final URI getStatusCallback() { - return this.statusCallback; - } - - public final HttpMethod getStatusCallbackMethod() { - return this.statusCallbackMethod; - } - - public final String getUri() { - return this.uri; - } - - public final Boolean getVoiceCallerIdLookup() { - return this.voiceCallerIdLookup; - } - - public final HttpMethod getVoiceFallbackMethod() { - return this.voiceFallbackMethod; - } - - public final URI getVoiceFallbackUrl() { - return this.voiceFallbackUrl; - } - - public final HttpMethod getVoiceMethod() { - return this.voiceMethod; - } - - public final URI getVoiceUrl() { - return this.voiceUrl; - } - - public final Boolean getPublicApplicationConnectEnabled() { - return this.publicApplicationConnectEnabled; } @Override @@ -305,62 +263,58 @@ public boolean equals(final Object o) { } Application other = (Application) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(apiVersion, other.apiVersion) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals( - messageStatusCallback, - other.messageStatusCallback - ) && - Objects.equals(sid, other.sid) && - Objects.equals(smsFallbackMethod, other.smsFallbackMethod) && - Objects.equals(smsFallbackUrl, other.smsFallbackUrl) && - Objects.equals(smsMethod, other.smsMethod) && - Objects.equals(smsStatusCallback, other.smsStatusCallback) && - Objects.equals(smsUrl, other.smsUrl) && - Objects.equals(statusCallback, other.statusCallback) && - Objects.equals(statusCallbackMethod, other.statusCallbackMethod) && - Objects.equals(uri, other.uri) && - Objects.equals(voiceCallerIdLookup, other.voiceCallerIdLookup) && - Objects.equals(voiceFallbackMethod, other.voiceFallbackMethod) && - Objects.equals(voiceFallbackUrl, other.voiceFallbackUrl) && - Objects.equals(voiceMethod, other.voiceMethod) && - Objects.equals(voiceUrl, other.voiceUrl) && - Objects.equals( - publicApplicationConnectEnabled, - other.publicApplicationConnectEnabled - ) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(apiVersion, other.apiVersion) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(messageStatusCallback, other.messageStatusCallback) && + Objects.equals(publicApplicationConnectEnabled, other.publicApplicationConnectEnabled) && + Objects.equals(sid, other.sid) && + Objects.equals(smsFallbackMethod, other.smsFallbackMethod) && + Objects.equals(smsFallbackUrl, other.smsFallbackUrl) && + Objects.equals(smsMethod, other.smsMethod) && + Objects.equals(smsStatusCallback, other.smsStatusCallback) && + Objects.equals(smsUrl, other.smsUrl) && + Objects.equals(statusCallback, other.statusCallback) && + Objects.equals(statusCallbackMethod, other.statusCallbackMethod) && + Objects.equals(uri, other.uri) && + Objects.equals(voiceCallerIdLookup, other.voiceCallerIdLookup) && + Objects.equals(voiceFallbackMethod, other.voiceFallbackMethod) && + Objects.equals(voiceFallbackUrl, other.voiceFallbackUrl) && + Objects.equals(voiceMethod, other.voiceMethod) && + Objects.equals(voiceUrl, other.voiceUrl) ); } @Override public int hashCode() { return Objects.hash( - accountSid, - apiVersion, - dateCreated, - dateUpdated, - friendlyName, - messageStatusCallback, - sid, - smsFallbackMethod, - smsFallbackUrl, - smsMethod, - smsStatusCallback, - smsUrl, - statusCallback, - statusCallbackMethod, - uri, - voiceCallerIdLookup, - voiceFallbackMethod, - voiceFallbackUrl, - voiceMethod, - voiceUrl, - publicApplicationConnectEnabled + accountSid, + apiVersion, + dateCreated, + dateUpdated, + friendlyName, + messageStatusCallback, + publicApplicationConnectEnabled, + sid, + smsFallbackMethod, + smsFallbackUrl, + smsMethod, + smsStatusCallback, + smsUrl, + statusCallback, + statusCallbackMethod, + uri, + voiceCallerIdLookup, + voiceFallbackMethod, + voiceFallbackUrl, + voiceMethod, + voiceUrl ); } + + } + diff --git a/src/main/java/com/twilio/rest/api/v2010/account/ApplicationCreator.java b/src/main/java/com/twilio/rest/api/v2010/account/ApplicationCreator.java index 7fae4fc326..d59be44cf2 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/ApplicationCreator.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/ApplicationCreator.java @@ -14,9 +14,11 @@ package com.twilio.rest.api.v2010.account; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; -import com.twilio.converter.Promoter; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,12 +27,12 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -import java.net.URI; + import java.net.URI; public class ApplicationCreator extends Creator { - private String pathAccountSid; + private String pathaccountSid; private String apiVersion; private URI voiceUrl; private HttpMethod voiceMethod; @@ -48,260 +50,226 @@ public class ApplicationCreator extends Creator { private String friendlyName; private Boolean publicApplicationConnectEnabled; - public ApplicationCreator() {} + public ApplicationCreator() { + } - public ApplicationCreator(final String pathAccountSid) { - this.pathAccountSid = pathAccountSid; + public ApplicationCreator(final String pathaccountSid) { + this.pathaccountSid = pathaccountSid; } + public ApplicationCreator setApiVersion(final String apiVersion) { this.apiVersion = apiVersion; return this; } + public ApplicationCreator setVoiceUrl(final URI voiceUrl) { this.voiceUrl = voiceUrl; return this; } - public ApplicationCreator setVoiceUrl(final String voiceUrl) { - return setVoiceUrl(Promoter.uriFromString(voiceUrl)); - } public ApplicationCreator setVoiceMethod(final HttpMethod voiceMethod) { this.voiceMethod = voiceMethod; return this; } + public ApplicationCreator setVoiceFallbackUrl(final URI voiceFallbackUrl) { this.voiceFallbackUrl = voiceFallbackUrl; return this; } - public ApplicationCreator setVoiceFallbackUrl( - final String voiceFallbackUrl - ) { - return setVoiceFallbackUrl(Promoter.uriFromString(voiceFallbackUrl)); - } - public ApplicationCreator setVoiceFallbackMethod( - final HttpMethod voiceFallbackMethod - ) { + public ApplicationCreator setVoiceFallbackMethod(final HttpMethod voiceFallbackMethod) { this.voiceFallbackMethod = voiceFallbackMethod; return this; } + public ApplicationCreator setStatusCallback(final URI statusCallback) { this.statusCallback = statusCallback; return this; } - public ApplicationCreator setStatusCallback(final String statusCallback) { - return setStatusCallback(Promoter.uriFromString(statusCallback)); - } - public ApplicationCreator setStatusCallbackMethod( - final HttpMethod statusCallbackMethod - ) { + public ApplicationCreator setStatusCallbackMethod(final HttpMethod statusCallbackMethod) { this.statusCallbackMethod = statusCallbackMethod; return this; } - public ApplicationCreator setVoiceCallerIdLookup( - final Boolean voiceCallerIdLookup - ) { + + public ApplicationCreator setVoiceCallerIdLookup(final Boolean voiceCallerIdLookup) { this.voiceCallerIdLookup = voiceCallerIdLookup; return this; } + public ApplicationCreator setSmsUrl(final URI smsUrl) { this.smsUrl = smsUrl; return this; } - public ApplicationCreator setSmsUrl(final String smsUrl) { - return setSmsUrl(Promoter.uriFromString(smsUrl)); - } public ApplicationCreator setSmsMethod(final HttpMethod smsMethod) { this.smsMethod = smsMethod; return this; } + public ApplicationCreator setSmsFallbackUrl(final URI smsFallbackUrl) { this.smsFallbackUrl = smsFallbackUrl; return this; } - public ApplicationCreator setSmsFallbackUrl(final String smsFallbackUrl) { - return setSmsFallbackUrl(Promoter.uriFromString(smsFallbackUrl)); - } - public ApplicationCreator setSmsFallbackMethod( - final HttpMethod smsFallbackMethod - ) { + public ApplicationCreator setSmsFallbackMethod(final HttpMethod smsFallbackMethod) { this.smsFallbackMethod = smsFallbackMethod; return this; } - public ApplicationCreator setSmsStatusCallback( - final URI smsStatusCallback - ) { + + public ApplicationCreator setSmsStatusCallback(final URI smsStatusCallback) { this.smsStatusCallback = smsStatusCallback; return this; } - public ApplicationCreator setSmsStatusCallback( - final String smsStatusCallback - ) { - return setSmsStatusCallback(Promoter.uriFromString(smsStatusCallback)); - } - public ApplicationCreator setMessageStatusCallback( - final URI messageStatusCallback - ) { + public ApplicationCreator setMessageStatusCallback(final URI messageStatusCallback) { this.messageStatusCallback = messageStatusCallback; return this; } - public ApplicationCreator setMessageStatusCallback( - final String messageStatusCallback - ) { - return setMessageStatusCallback( - Promoter.uriFromString(messageStatusCallback) - ); - } public ApplicationCreator setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } - public ApplicationCreator setPublicApplicationConnectEnabled( - final Boolean publicApplicationConnectEnabled - ) { + + public ApplicationCreator setPublicApplicationConnectEnabled(final Boolean publicApplicationConnectEnabled) { this.publicApplicationConnectEnabled = publicApplicationConnectEnabled; return this; } + @Override public Application create(final TwilioRestClient client) { + String path = "/2010-04-01/Accounts/{AccountSid}/Applications.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.API.toString(), - path + HttpMethod.POST, + Domains.API.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Application creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("Application creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Application.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Application.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (apiVersion != null) { - request.addPostParam("ApiVersion", apiVersion); + Serializer.toString(request, "ApiVersion", apiVersion, ParameterType.URLENCODED); } + + if (voiceUrl != null) { - request.addPostParam("VoiceUrl", voiceUrl.toString()); + Serializer.toString(request, "VoiceUrl", voiceUrl, ParameterType.URLENCODED); } + + if (voiceMethod != null) { - request.addPostParam("VoiceMethod", voiceMethod.toString()); + Serializer.toString(request, "VoiceMethod", voiceMethod, ParameterType.URLENCODED); } + + if (voiceFallbackUrl != null) { - request.addPostParam( - "VoiceFallbackUrl", - voiceFallbackUrl.toString() - ); + Serializer.toString(request, "VoiceFallbackUrl", voiceFallbackUrl, ParameterType.URLENCODED); } + + if (voiceFallbackMethod != null) { - request.addPostParam( - "VoiceFallbackMethod", - voiceFallbackMethod.toString() - ); + Serializer.toString(request, "VoiceFallbackMethod", voiceFallbackMethod, ParameterType.URLENCODED); } + + if (statusCallback != null) { - request.addPostParam("StatusCallback", statusCallback.toString()); + Serializer.toString(request, "StatusCallback", statusCallback, ParameterType.URLENCODED); } + + if (statusCallbackMethod != null) { - request.addPostParam( - "StatusCallbackMethod", - statusCallbackMethod.toString() - ); + Serializer.toString(request, "StatusCallbackMethod", statusCallbackMethod, ParameterType.URLENCODED); } + + if (voiceCallerIdLookup != null) { - request.addPostParam( - "VoiceCallerIdLookup", - voiceCallerIdLookup.toString() - ); + Serializer.toString(request, "VoiceCallerIdLookup", voiceCallerIdLookup, ParameterType.URLENCODED); } + + if (smsUrl != null) { - request.addPostParam("SmsUrl", smsUrl.toString()); + Serializer.toString(request, "SmsUrl", smsUrl, ParameterType.URLENCODED); } + + if (smsMethod != null) { - request.addPostParam("SmsMethod", smsMethod.toString()); + Serializer.toString(request, "SmsMethod", smsMethod, ParameterType.URLENCODED); } + + if (smsFallbackUrl != null) { - request.addPostParam("SmsFallbackUrl", smsFallbackUrl.toString()); + Serializer.toString(request, "SmsFallbackUrl", smsFallbackUrl, ParameterType.URLENCODED); } + + if (smsFallbackMethod != null) { - request.addPostParam( - "SmsFallbackMethod", - smsFallbackMethod.toString() - ); + Serializer.toString(request, "SmsFallbackMethod", smsFallbackMethod, ParameterType.URLENCODED); } + + if (smsStatusCallback != null) { - request.addPostParam( - "SmsStatusCallback", - smsStatusCallback.toString() - ); + Serializer.toString(request, "SmsStatusCallback", smsStatusCallback, ParameterType.URLENCODED); } + + if (messageStatusCallback != null) { - request.addPostParam( - "MessageStatusCallback", - messageStatusCallback.toString() - ); + Serializer.toString(request, "MessageStatusCallback", messageStatusCallback, ParameterType.URLENCODED); } + + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + if (publicApplicationConnectEnabled != null) { - request.addPostParam( - "PublicApplicationConnectEnabled", - publicApplicationConnectEnabled.toString() - ); + Serializer.toString(request, "PublicApplicationConnectEnabled", publicApplicationConnectEnabled, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/ApplicationDeleter.java b/src/main/java/com/twilio/rest/api/v2010/account/ApplicationDeleter.java index 6bd943479e..ceb8011e59 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/ApplicationDeleter.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/ApplicationDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.api.v2010.account; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,59 +26,46 @@ public class ApplicationDeleter extends Deleter { - private String pathSid; - private String pathAccountSid; + private String pathaccountSid; + private String pathsid; - public ApplicationDeleter(final String pathSid) { - this.pathSid = pathSid; + public ApplicationDeleter(final String pathsid) { + this.pathsid = pathsid; } - public ApplicationDeleter( - final String pathAccountSid, - final String pathSid - ) { - this.pathAccountSid = pathAccountSid; - this.pathSid = pathSid; + public ApplicationDeleter(final String pathaccountSid, final String pathsid) { + this.pathaccountSid = pathaccountSid; + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/Applications/{Sid}.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/2010-04-01/Accounts/{AccountSid}/Applications/{Sid}.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.API.toString(), - path + HttpMethod.DELETE, + Domains.API.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Application delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("Application delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/ApplicationFetcher.java b/src/main/java/com/twilio/rest/api/v2010/account/ApplicationFetcher.java index a54d67313f..8f7daa14fc 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/ApplicationFetcher.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/ApplicationFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.api.v2010.account; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,66 +26,49 @@ public class ApplicationFetcher extends Fetcher { - private String pathSid; - private String pathAccountSid; + private String pathaccountSid; + private String pathsid; - public ApplicationFetcher(final String pathSid) { - this.pathSid = pathSid; + public ApplicationFetcher(final String pathsid) { + this.pathsid = pathsid; } - public ApplicationFetcher( - final String pathAccountSid, - final String pathSid - ) { - this.pathAccountSid = pathAccountSid; - this.pathSid = pathSid; + public ApplicationFetcher(final String pathaccountSid, final String pathsid) { + this.pathaccountSid = pathaccountSid; + this.pathsid = pathsid; } + @Override public Application fetch(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/Applications/{Sid}.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/2010-04-01/Accounts/{AccountSid}/Applications/{Sid}.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.API.toString(), - path + HttpMethod.GET, + Domains.API.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Application fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Application fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return Application.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Application.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/ApplicationReader.java b/src/main/java/com/twilio/rest/api/v2010/account/ApplicationReader.java index ba8a65eee1..a1554c33e7 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/ApplicationReader.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/ApplicationReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,130 +30,104 @@ public class ApplicationReader extends Reader { - private String pathAccountSid; + private String pathaccountSid; private String friendlyName; private Long pageSize; - public ApplicationReader() {} + public ApplicationReader() { + } - public ApplicationReader(final String pathAccountSid) { - this.pathAccountSid = pathAccountSid; + public ApplicationReader(final String pathaccountSid) { + this.pathaccountSid = pathaccountSid; } + public ApplicationReader setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + public ApplicationReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/2010-04-01/Accounts/{AccountSid}/Applications.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.API.toString(), - path + HttpMethod.GET, + Domains.API.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Application read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Application read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "applications", - response.getContent(), - Application.class, - client.getObjectMapper() - ); + "applications", + response.getContent(), + Application.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.API.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.API.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (friendlyName != null) { - request.addQueryParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.QUERY); } + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/ApplicationUpdater.java b/src/main/java/com/twilio/rest/api/v2010/account/ApplicationUpdater.java index 22e599588d..f379abbcd6 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/ApplicationUpdater.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/ApplicationUpdater.java @@ -16,7 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; -import com.twilio.converter.Promoter; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,12 +26,12 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.net.URI; public class ApplicationUpdater extends Updater { - - private String pathSid; - private String pathAccountSid; + private String pathaccountSid; + private String pathsid; private String friendlyName; private String apiVersion; private URI voiceUrl; @@ -48,268 +49,229 @@ public class ApplicationUpdater extends Updater { private URI messageStatusCallback; private Boolean publicApplicationConnectEnabled; - public ApplicationUpdater(final String pathSid) { - this.pathSid = pathSid; + public ApplicationUpdater(final String pathsid) { + this.pathsid = pathsid; } - public ApplicationUpdater( - final String pathAccountSid, - final String pathSid - ) { - this.pathAccountSid = pathAccountSid; - this.pathSid = pathSid; + public ApplicationUpdater(final String pathaccountSid, final String pathsid) { + this.pathaccountSid = pathaccountSid; + this.pathsid = pathsid; } + public ApplicationUpdater setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + public ApplicationUpdater setApiVersion(final String apiVersion) { this.apiVersion = apiVersion; return this; } + public ApplicationUpdater setVoiceUrl(final URI voiceUrl) { this.voiceUrl = voiceUrl; return this; } - public ApplicationUpdater setVoiceUrl(final String voiceUrl) { - return setVoiceUrl(Promoter.uriFromString(voiceUrl)); - } public ApplicationUpdater setVoiceMethod(final HttpMethod voiceMethod) { this.voiceMethod = voiceMethod; return this; } + public ApplicationUpdater setVoiceFallbackUrl(final URI voiceFallbackUrl) { this.voiceFallbackUrl = voiceFallbackUrl; return this; } - public ApplicationUpdater setVoiceFallbackUrl( - final String voiceFallbackUrl - ) { - return setVoiceFallbackUrl(Promoter.uriFromString(voiceFallbackUrl)); - } - public ApplicationUpdater setVoiceFallbackMethod( - final HttpMethod voiceFallbackMethod - ) { + public ApplicationUpdater setVoiceFallbackMethod(final HttpMethod voiceFallbackMethod) { this.voiceFallbackMethod = voiceFallbackMethod; return this; } + public ApplicationUpdater setStatusCallback(final URI statusCallback) { this.statusCallback = statusCallback; return this; } - public ApplicationUpdater setStatusCallback(final String statusCallback) { - return setStatusCallback(Promoter.uriFromString(statusCallback)); - } - public ApplicationUpdater setStatusCallbackMethod( - final HttpMethod statusCallbackMethod - ) { + public ApplicationUpdater setStatusCallbackMethod(final HttpMethod statusCallbackMethod) { this.statusCallbackMethod = statusCallbackMethod; return this; } - public ApplicationUpdater setVoiceCallerIdLookup( - final Boolean voiceCallerIdLookup - ) { + + public ApplicationUpdater setVoiceCallerIdLookup(final Boolean voiceCallerIdLookup) { this.voiceCallerIdLookup = voiceCallerIdLookup; return this; } + public ApplicationUpdater setSmsUrl(final URI smsUrl) { this.smsUrl = smsUrl; return this; } - public ApplicationUpdater setSmsUrl(final String smsUrl) { - return setSmsUrl(Promoter.uriFromString(smsUrl)); - } public ApplicationUpdater setSmsMethod(final HttpMethod smsMethod) { this.smsMethod = smsMethod; return this; } + public ApplicationUpdater setSmsFallbackUrl(final URI smsFallbackUrl) { this.smsFallbackUrl = smsFallbackUrl; return this; } - public ApplicationUpdater setSmsFallbackUrl(final String smsFallbackUrl) { - return setSmsFallbackUrl(Promoter.uriFromString(smsFallbackUrl)); - } - public ApplicationUpdater setSmsFallbackMethod( - final HttpMethod smsFallbackMethod - ) { + public ApplicationUpdater setSmsFallbackMethod(final HttpMethod smsFallbackMethod) { this.smsFallbackMethod = smsFallbackMethod; return this; } - public ApplicationUpdater setSmsStatusCallback( - final URI smsStatusCallback - ) { + + public ApplicationUpdater setSmsStatusCallback(final URI smsStatusCallback) { this.smsStatusCallback = smsStatusCallback; return this; } - public ApplicationUpdater setSmsStatusCallback( - final String smsStatusCallback - ) { - return setSmsStatusCallback(Promoter.uriFromString(smsStatusCallback)); - } - public ApplicationUpdater setMessageStatusCallback( - final URI messageStatusCallback - ) { + public ApplicationUpdater setMessageStatusCallback(final URI messageStatusCallback) { this.messageStatusCallback = messageStatusCallback; return this; } - public ApplicationUpdater setMessageStatusCallback( - final String messageStatusCallback - ) { - return setMessageStatusCallback( - Promoter.uriFromString(messageStatusCallback) - ); - } - public ApplicationUpdater setPublicApplicationConnectEnabled( - final Boolean publicApplicationConnectEnabled - ) { + public ApplicationUpdater setPublicApplicationConnectEnabled(final Boolean publicApplicationConnectEnabled) { this.publicApplicationConnectEnabled = publicApplicationConnectEnabled; return this; } + @Override public Application update(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/Applications/{Sid}.json"; - - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + + String path = "/2010-04-01/Accounts/{AccountSid}/Applications/{Sid}.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.API.toString(), - path + HttpMethod.POST, + Domains.API.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Application update failed: Unable to connect to server" - ); + throw new ApiConnectionException("Application update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Application.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Application.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + if (apiVersion != null) { - request.addPostParam("ApiVersion", apiVersion); + Serializer.toString(request, "ApiVersion", apiVersion, ParameterType.URLENCODED); } + + if (voiceUrl != null) { - request.addPostParam("VoiceUrl", voiceUrl.toString()); + Serializer.toString(request, "VoiceUrl", voiceUrl, ParameterType.URLENCODED); } + + if (voiceMethod != null) { - request.addPostParam("VoiceMethod", voiceMethod.toString()); + Serializer.toString(request, "VoiceMethod", voiceMethod, ParameterType.URLENCODED); } + + if (voiceFallbackUrl != null) { - request.addPostParam( - "VoiceFallbackUrl", - voiceFallbackUrl.toString() - ); + Serializer.toString(request, "VoiceFallbackUrl", voiceFallbackUrl, ParameterType.URLENCODED); } + + if (voiceFallbackMethod != null) { - request.addPostParam( - "VoiceFallbackMethod", - voiceFallbackMethod.toString() - ); + Serializer.toString(request, "VoiceFallbackMethod", voiceFallbackMethod, ParameterType.URLENCODED); } + + if (statusCallback != null) { - request.addPostParam("StatusCallback", statusCallback.toString()); + Serializer.toString(request, "StatusCallback", statusCallback, ParameterType.URLENCODED); } + + if (statusCallbackMethod != null) { - request.addPostParam( - "StatusCallbackMethod", - statusCallbackMethod.toString() - ); + Serializer.toString(request, "StatusCallbackMethod", statusCallbackMethod, ParameterType.URLENCODED); } + + if (voiceCallerIdLookup != null) { - request.addPostParam( - "VoiceCallerIdLookup", - voiceCallerIdLookup.toString() - ); + Serializer.toString(request, "VoiceCallerIdLookup", voiceCallerIdLookup, ParameterType.URLENCODED); } + + if (smsUrl != null) { - request.addPostParam("SmsUrl", smsUrl.toString()); + Serializer.toString(request, "SmsUrl", smsUrl, ParameterType.URLENCODED); } + + if (smsMethod != null) { - request.addPostParam("SmsMethod", smsMethod.toString()); + Serializer.toString(request, "SmsMethod", smsMethod, ParameterType.URLENCODED); } + + if (smsFallbackUrl != null) { - request.addPostParam("SmsFallbackUrl", smsFallbackUrl.toString()); + Serializer.toString(request, "SmsFallbackUrl", smsFallbackUrl, ParameterType.URLENCODED); } + + if (smsFallbackMethod != null) { - request.addPostParam( - "SmsFallbackMethod", - smsFallbackMethod.toString() - ); + Serializer.toString(request, "SmsFallbackMethod", smsFallbackMethod, ParameterType.URLENCODED); } + + if (smsStatusCallback != null) { - request.addPostParam( - "SmsStatusCallback", - smsStatusCallback.toString() - ); + Serializer.toString(request, "SmsStatusCallback", smsStatusCallback, ParameterType.URLENCODED); } + + if (messageStatusCallback != null) { - request.addPostParam( - "MessageStatusCallback", - messageStatusCallback.toString() - ); + Serializer.toString(request, "MessageStatusCallback", messageStatusCallback, ParameterType.URLENCODED); } + + if (publicApplicationConnectEnabled != null) { - request.addPostParam( - "PublicApplicationConnectEnabled", - publicApplicationConnectEnabled.toString() - ); + Serializer.toString(request, "PublicApplicationConnectEnabled", publicApplicationConnectEnabled, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/AuthorizedConnectApp.java b/src/main/java/com/twilio/rest/api/v2010/account/AuthorizedConnectApp.java index f7e1d9f67f..b56e754a69 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/AuthorizedConnectApp.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/AuthorizedConnectApp.java @@ -18,63 +18,144 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.util.List; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class AuthorizedConnectApp extends Resource { - private static final long serialVersionUID = 156350222502843L; - public static AuthorizedConnectAppFetcher fetcher( - final String pathConnectAppSid - ) { - return new AuthorizedConnectAppFetcher(pathConnectAppSid); + public static AuthorizedConnectAppFetcher fetcher(final String pathconnectAppSid) { + return new AuthorizedConnectAppFetcher( + pathconnectAppSid + ); } - public static AuthorizedConnectAppFetcher fetcher( - final String pathAccountSid, - final String pathConnectAppSid - ) { + + public static AuthorizedConnectAppFetcher fetcher(final String pathaccountSid, final String pathconnectAppSid) { return new AuthorizedConnectAppFetcher( - pathAccountSid, - pathConnectAppSid + pathaccountSid, pathconnectAppSid ); } + public static AuthorizedConnectAppReader reader() { - return new AuthorizedConnectAppReader(); + return new AuthorizedConnectAppReader( + + ); } - public static AuthorizedConnectAppReader reader( - final String pathAccountSid - ) { - return new AuthorizedConnectAppReader(pathAccountSid); + + public static AuthorizedConnectAppReader reader(final String pathaccountSid) { + return new AuthorizedConnectAppReader( + pathaccountSid + ); + } + + + public enum AuthorizedConnectAppAuthorizedConnectAppPermission { + GET_ALL("get-all"), + POST_ALL("post-all"); + + private final String value; + + private AuthorizedConnectAppAuthorizedConnectAppPermission(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static AuthorizedConnectAppAuthorizedConnectAppPermission forValue(final String value) { + return Promoter.enumFromString(value, AuthorizedConnectAppAuthorizedConnectAppPermission.values()); + } + } + + public enum Permission { + GET_ALL("get-all"), + POST_ALL("post-all"); + + private final String value; + + private Permission(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static Permission forValue(final String value) { + return Promoter.enumFromString(value, Permission.values()); + } + } + + public enum AuthorizedConnectAppPermission { + GET_ALL("get-all"), + POST_ALL("post-all"); + + private final String value; + + private AuthorizedConnectAppPermission(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static AuthorizedConnectAppPermission forValue(final String value) { + return Promoter.enumFromString(value, AuthorizedConnectAppPermission.values()); + } + } + + public enum AuthorizedConnectAppAuthorizedConnectAppAuthorizedConnectAppPermission { + GET_ALL("get-all"), + POST_ALL("post-all"); + + private final String value; + + private AuthorizedConnectAppAuthorizedConnectAppAuthorizedConnectAppPermission(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static AuthorizedConnectAppAuthorizedConnectAppAuthorizedConnectAppPermission forValue(final String value) { + return Promoter.enumFromString(value, AuthorizedConnectAppAuthorizedConnectAppAuthorizedConnectAppPermission.values()); + } } + /** * Converts a JSON String into a AuthorizedConnectApp object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return AuthorizedConnectApp object represented by the provided JSON */ - public static AuthorizedConnectApp fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static AuthorizedConnectApp fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, AuthorizedConnectApp.class); @@ -89,14 +170,11 @@ public static AuthorizedConnectApp fromJson( * Converts a JSON InputStream into a AuthorizedConnectApp object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return AuthorizedConnectApp object represented by the provided JSON */ - public static AuthorizedConnectApp fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static AuthorizedConnectApp fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, AuthorizedConnectApp.class); @@ -107,35 +185,46 @@ public static AuthorizedConnectApp fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; + @Getter private final String connectAppCompanyName; + @Getter private final String connectAppDescription; + @Getter private final String connectAppFriendlyName; + @Getter private final URI connectAppHomepageUrl; + @Getter private final String connectAppSid; - private final List permissions; + @Getter + private final List permissions; + @Getter private final String uri; @JsonCreator private AuthorizedConnectApp( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty( - "connect_app_company_name" - ) final String connectAppCompanyName, - @JsonProperty( - "connect_app_description" - ) final String connectAppDescription, - @JsonProperty( - "connect_app_friendly_name" - ) final String connectAppFriendlyName, - @JsonProperty( - "connect_app_homepage_url" - ) final URI connectAppHomepageUrl, - @JsonProperty("connect_app_sid") final String connectAppSid, - @JsonProperty("permissions") final List< - AuthorizedConnectApp.Permission - > permissions, - @JsonProperty("uri") final String uri + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("connect_app_company_name") final String connectAppCompanyName, + @JsonProperty("connect_app_description") final String connectAppDescription, + @JsonProperty("connect_app_friendly_name") final String connectAppFriendlyName, + @JsonProperty("connect_app_homepage_url") final URI connectAppHomepageUrl, + @JsonProperty("connect_app_sid") final String connectAppSid, + @JsonProperty("permissions") final List permissions, + @JsonProperty("uri") final String uri ) { this.accountSid = accountSid; this.connectAppCompanyName = connectAppCompanyName; @@ -147,38 +236,6 @@ private AuthorizedConnectApp( this.uri = uri; } - public final String getAccountSid() { - return this.accountSid; - } - - public final String getConnectAppCompanyName() { - return this.connectAppCompanyName; - } - - public final String getConnectAppDescription() { - return this.connectAppDescription; - } - - public final String getConnectAppFriendlyName() { - return this.connectAppFriendlyName; - } - - public final URI getConnectAppHomepageUrl() { - return this.connectAppHomepageUrl; - } - - public final String getConnectAppSid() { - return this.connectAppSid; - } - - public final List getPermissions() { - return this.permissions; - } - - public final String getUri() { - return this.uri; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -190,62 +247,32 @@ public boolean equals(final Object o) { } AuthorizedConnectApp other = (AuthorizedConnectApp) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals( - connectAppCompanyName, - other.connectAppCompanyName - ) && - Objects.equals( - connectAppDescription, - other.connectAppDescription - ) && - Objects.equals( - connectAppFriendlyName, - other.connectAppFriendlyName - ) && - Objects.equals( - connectAppHomepageUrl, - other.connectAppHomepageUrl - ) && - Objects.equals(connectAppSid, other.connectAppSid) && - Objects.equals(permissions, other.permissions) && - Objects.equals(uri, other.uri) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(connectAppCompanyName, other.connectAppCompanyName) && + Objects.equals(connectAppDescription, other.connectAppDescription) && + Objects.equals(connectAppFriendlyName, other.connectAppFriendlyName) && + Objects.equals(connectAppHomepageUrl, other.connectAppHomepageUrl) && + Objects.equals(connectAppSid, other.connectAppSid) && + Objects.equals(permissions, other.permissions) && + Objects.equals(uri, other.uri) ); } @Override public int hashCode() { return Objects.hash( - accountSid, - connectAppCompanyName, - connectAppDescription, - connectAppFriendlyName, - connectAppHomepageUrl, - connectAppSid, - permissions, - uri + accountSid, + connectAppCompanyName, + connectAppDescription, + connectAppFriendlyName, + connectAppHomepageUrl, + connectAppSid, + permissions, + uri ); } - public enum Permission { - GET_ALL("get-all"), - POST_ALL("post-all"); - - private final String value; - private Permission(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static Permission forValue(final String value) { - return Promoter.enumFromString(value, Permission.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/api/v2010/account/AuthorizedConnectAppFetcher.java b/src/main/java/com/twilio/rest/api/v2010/account/AuthorizedConnectAppFetcher.java index 92ccf515c5..04bba6e691 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/AuthorizedConnectAppFetcher.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/AuthorizedConnectAppFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.api.v2010.account; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,70 +26,49 @@ public class AuthorizedConnectAppFetcher extends Fetcher { - private String pathConnectAppSid; - private String pathAccountSid; + private String pathaccountSid; + private String pathconnectAppSid; - public AuthorizedConnectAppFetcher(final String pathConnectAppSid) { - this.pathConnectAppSid = pathConnectAppSid; + public AuthorizedConnectAppFetcher(final String pathconnectAppSid) { + this.pathconnectAppSid = pathconnectAppSid; } - public AuthorizedConnectAppFetcher( - final String pathAccountSid, - final String pathConnectAppSid - ) { - this.pathAccountSid = pathAccountSid; - this.pathConnectAppSid = pathConnectAppSid; + public AuthorizedConnectAppFetcher(final String pathaccountSid, final String pathconnectAppSid) { + this.pathaccountSid = pathaccountSid; + this.pathconnectAppSid = pathconnectAppSid; } + @Override public AuthorizedConnectApp fetch(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/AuthorizedConnectApps/{ConnectAppSid}.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = - path.replace( - "{" + "ConnectAppSid" + "}", - this.pathConnectAppSid.toString() - ); + String path = "/2010-04-01/Accounts/{AccountSid}/AuthorizedConnectApps/{ConnectAppSid}.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "ConnectAppSid" + "}", this.pathconnectAppSid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.API.toString(), - path + HttpMethod.GET, + Domains.API.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "AuthorizedConnectApp fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("AuthorizedConnectApp fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return AuthorizedConnectApp.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return AuthorizedConnectApp.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/AuthorizedConnectAppReader.java b/src/main/java/com/twilio/rest/api/v2010/account/AuthorizedConnectAppReader.java index 15ac33d398..4d96217148 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/AuthorizedConnectAppReader.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/AuthorizedConnectAppReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,124 +30,92 @@ public class AuthorizedConnectAppReader extends Reader { - private String pathAccountSid; + private String pathaccountSid; private Long pageSize; - public AuthorizedConnectAppReader() {} + public AuthorizedConnectAppReader() { + } - public AuthorizedConnectAppReader(final String pathAccountSid) { - this.pathAccountSid = pathAccountSid; + public AuthorizedConnectAppReader(final String pathaccountSid) { + this.pathaccountSid = pathaccountSid; } + public AuthorizedConnectAppReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override - public ResourceSet read( - final TwilioRestClient client - ) { + public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/AuthorizedConnectApps.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); + + String path = "/2010-04-01/Accounts/{AccountSid}/AuthorizedConnectApps.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.API.toString(), - path + HttpMethod.GET, + Domains.API.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "AuthorizedConnectApp read failed: Unable to connect to server" - ); + throw new ApiConnectionException("AuthorizedConnectApp read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "authorized_connect_apps", - response.getContent(), - AuthorizedConnectApp.class, - client.getObjectMapper() - ); + "authorized_connect_apps", + response.getContent(), + AuthorizedConnectApp.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.API.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.API.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/AvailablePhoneNumberCountry.java b/src/main/java/com/twilio/rest/api/v2010/account/AvailablePhoneNumberCountry.java index 9e27b5176b..a9383900a2 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/AvailablePhoneNumberCountry.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/AvailablePhoneNumberCountry.java @@ -18,69 +18,65 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class AvailablePhoneNumberCountry extends Resource { - private static final long serialVersionUID = 173167903952303L; - public static AvailablePhoneNumberCountryFetcher fetcher( - final String pathCountryCode - ) { - return new AvailablePhoneNumberCountryFetcher(pathCountryCode); + public static AvailablePhoneNumberCountryFetcher fetcher(final String pathcountryCode) { + return new AvailablePhoneNumberCountryFetcher( + pathcountryCode + ); } - public static AvailablePhoneNumberCountryFetcher fetcher( - final String pathAccountSid, - final String pathCountryCode - ) { + + public static AvailablePhoneNumberCountryFetcher fetcher(final String pathaccountSid, final String pathcountryCode) { return new AvailablePhoneNumberCountryFetcher( - pathAccountSid, - pathCountryCode + pathaccountSid, pathcountryCode ); } + public static AvailablePhoneNumberCountryReader reader() { - return new AvailablePhoneNumberCountryReader(); + return new AvailablePhoneNumberCountryReader( + + ); } - public static AvailablePhoneNumberCountryReader reader( - final String pathAccountSid - ) { - return new AvailablePhoneNumberCountryReader(pathAccountSid); + + public static AvailablePhoneNumberCountryReader reader(final String pathaccountSid) { + return new AvailablePhoneNumberCountryReader( + pathaccountSid + ); } + /** * Converts a JSON String into a AvailablePhoneNumberCountry object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return AvailablePhoneNumberCountry object represented by the provided JSON */ - public static AvailablePhoneNumberCountry fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static AvailablePhoneNumberCountry fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { - return objectMapper.readValue( - json, - AvailablePhoneNumberCountry.class - ); + return objectMapper.readValue(json, AvailablePhoneNumberCountry.class); } catch (final JsonMappingException | JsonParseException e) { throw new ApiException(e.getMessage(), e); } catch (final IOException e) { @@ -92,20 +88,14 @@ public static AvailablePhoneNumberCountry fromJson( * Converts a JSON InputStream into a AvailablePhoneNumberCountry object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return AvailablePhoneNumberCountry object represented by the provided JSON */ - public static AvailablePhoneNumberCountry fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static AvailablePhoneNumberCountry fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { - return objectMapper.readValue( - json, - AvailablePhoneNumberCountry.class - ); + return objectMapper.readValue(json, AvailablePhoneNumberCountry.class); } catch (final JsonMappingException | JsonParseException e) { throw new ApiException(e.getMessage(), e); } catch (final IOException e) { @@ -113,48 +103,43 @@ public static AvailablePhoneNumberCountry fromJson( } } - private final String countryCode; - private final String country; - private final URI uri; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final Boolean beta; + @Getter + private final String country; + @Getter + private final String countryCode; + @Getter private final Map subresourceUris; + @Getter + private final URI uri; @JsonCreator private AvailablePhoneNumberCountry( - @JsonProperty("country_code") final String countryCode, - @JsonProperty("country") final String country, - @JsonProperty("uri") final URI uri, - @JsonProperty("beta") final Boolean beta, - @JsonProperty("subresource_uris") final Map< - String, - String - > subresourceUris + @JsonProperty("beta") final Boolean beta, + @JsonProperty("country") final String country, + @JsonProperty("country_code") final String countryCode, + @JsonProperty("subresource_uris") final Map subresourceUris, + @JsonProperty("uri") final URI uri ) { - this.countryCode = countryCode; - this.country = country; - this.uri = uri; this.beta = beta; + this.country = country; + this.countryCode = countryCode; this.subresourceUris = subresourceUris; - } - - public final String getCountryCode() { - return this.countryCode; - } - - public final String getCountry() { - return this.country; - } - - public final URI getUri() { - return this.uri; - } - - public final Boolean getBeta() { - return this.beta; - } - - public final Map getSubresourceUris() { - return this.subresourceUris; + this.uri = uri; } @Override @@ -168,18 +153,26 @@ public boolean equals(final Object o) { } AvailablePhoneNumberCountry other = (AvailablePhoneNumberCountry) o; - return ( - Objects.equals(countryCode, other.countryCode) && - Objects.equals(country, other.country) && - Objects.equals(uri, other.uri) && - Objects.equals(beta, other.beta) && - Objects.equals(subresourceUris, other.subresourceUris) + Objects.equals(beta, other.beta) && + Objects.equals(country, other.country) && + Objects.equals(countryCode, other.countryCode) && + Objects.equals(subresourceUris, other.subresourceUris) && + Objects.equals(uri, other.uri) ); } @Override public int hashCode() { - return Objects.hash(countryCode, country, uri, beta, subresourceUris); + return Objects.hash( + beta, + country, + countryCode, + subresourceUris, + uri + ); } + + } + diff --git a/src/main/java/com/twilio/rest/api/v2010/account/AvailablePhoneNumberCountryFetcher.java b/src/main/java/com/twilio/rest/api/v2010/account/AvailablePhoneNumberCountryFetcher.java index 6b1a9d1105..3e3d061319 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/AvailablePhoneNumberCountryFetcher.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/AvailablePhoneNumberCountryFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.api.v2010.account; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,73 +24,51 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class AvailablePhoneNumberCountryFetcher - extends Fetcher { +public class AvailablePhoneNumberCountryFetcher extends Fetcher { - private String pathCountryCode; - private String pathAccountSid; + private String pathaccountSid; + private String pathcountryCode; - public AvailablePhoneNumberCountryFetcher(final String pathCountryCode) { - this.pathCountryCode = pathCountryCode; + public AvailablePhoneNumberCountryFetcher(final String pathcountryCode) { + this.pathcountryCode = pathcountryCode; } - public AvailablePhoneNumberCountryFetcher( - final String pathAccountSid, - final String pathCountryCode - ) { - this.pathAccountSid = pathAccountSid; - this.pathCountryCode = pathCountryCode; + public AvailablePhoneNumberCountryFetcher(final String pathaccountSid, final String pathcountryCode) { + this.pathaccountSid = pathaccountSid; + this.pathcountryCode = pathcountryCode; } + @Override public AvailablePhoneNumberCountry fetch(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/AvailablePhoneNumbers/{CountryCode}.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = - path.replace( - "{" + "CountryCode" + "}", - this.pathCountryCode.toString() - ); + String path = "/2010-04-01/Accounts/{AccountSid}/AvailablePhoneNumbers/{CountryCode}.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "CountryCode" + "}", this.pathcountryCode.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.API.toString(), - path + HttpMethod.GET, + Domains.API.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "AvailablePhoneNumberCountry fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("AvailablePhoneNumberCountry fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return AvailablePhoneNumberCountry.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return AvailablePhoneNumberCountry.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/AvailablePhoneNumberCountryReader.java b/src/main/java/com/twilio/rest/api/v2010/account/AvailablePhoneNumberCountryReader.java index 8d4a08613b..af2027c8ee 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/AvailablePhoneNumberCountryReader.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/AvailablePhoneNumberCountryReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,129 +28,94 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class AvailablePhoneNumberCountryReader - extends Reader { +public class AvailablePhoneNumberCountryReader extends Reader { - private String pathAccountSid; + private String pathaccountSid; private Long pageSize; - public AvailablePhoneNumberCountryReader() {} + public AvailablePhoneNumberCountryReader() { + } - public AvailablePhoneNumberCountryReader(final String pathAccountSid) { - this.pathAccountSid = pathAccountSid; + public AvailablePhoneNumberCountryReader(final String pathaccountSid) { + this.pathaccountSid = pathaccountSid; } + public AvailablePhoneNumberCountryReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override - public ResourceSet read( - final TwilioRestClient client - ) { + public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } - public Page firstPage( - final TwilioRestClient client - ) { - String path = - "/2010-04-01/Accounts/{AccountSid}/AvailablePhoneNumbers.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); + public Page firstPage(final TwilioRestClient client) { + + String path = "/2010-04-01/Accounts/{AccountSid}/AvailablePhoneNumbers.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.API.toString(), - path + HttpMethod.GET, + Domains.API.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "AvailablePhoneNumberCountry read failed: Unable to connect to server" - ); + throw new ApiConnectionException("AvailablePhoneNumberCountry read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "countries", - response.getContent(), - AvailablePhoneNumberCountry.class, - client.getObjectMapper() - ); + "countries", + response.getContent(), + AvailablePhoneNumberCountry.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.API.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.API.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/Balance.java b/src/main/java/com/twilio/rest/api/v2010/account/Balance.java index 5fb120031a..924394106d 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/Balance.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/Balance.java @@ -18,42 +18,46 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Balance extends Resource { - private static final long serialVersionUID = 101388429668677L; public static BalanceFetcher fetcher() { - return new BalanceFetcher(); + return new BalanceFetcher( + + ); } - public static BalanceFetcher fetcher(final String pathAccountSid) { - return new BalanceFetcher(pathAccountSid); + + public static BalanceFetcher fetcher(final String pathaccountSid) { + return new BalanceFetcher( + pathaccountSid + ); } + /** * Converts a JSON String into a Balance object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Balance object represented by the provided JSON */ - public static Balance fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Balance fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Balance.class); @@ -68,14 +72,11 @@ public static Balance fromJson( * Converts a JSON InputStream into a Balance object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Balance object represented by the provided JSON */ - public static Balance fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Balance fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Balance.class); @@ -86,33 +87,37 @@ public static Balance fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; + @Getter private final String balance; + @Getter private final String currency; @JsonCreator private Balance( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("balance") final String balance, - @JsonProperty("currency") final String currency + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("balance") final String balance, + @JsonProperty("currency") final String currency ) { this.accountSid = accountSid; this.balance = balance; this.currency = currency; } - public final String getAccountSid() { - return this.accountSid; - } - - public final String getBalance() { - return this.balance; - } - - public final String getCurrency() { - return this.currency; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -124,16 +129,22 @@ public boolean equals(final Object o) { } Balance other = (Balance) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(balance, other.balance) && - Objects.equals(currency, other.currency) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(balance, other.balance) && + Objects.equals(currency, other.currency) ); } @Override public int hashCode() { - return Objects.hash(accountSid, balance, currency); + return Objects.hash( + accountSid, + balance, + currency + ); } + + } + diff --git a/src/main/java/com/twilio/rest/api/v2010/account/BalanceFetcher.java b/src/main/java/com/twilio/rest/api/v2010/account/BalanceFetcher.java index 660d55c3a2..f95badcc82 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/BalanceFetcher.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/BalanceFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.api.v2010.account; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,54 +26,45 @@ public class BalanceFetcher extends Fetcher { - private String pathAccountSid; + private String pathaccountSid; - public BalanceFetcher() {} + public BalanceFetcher() { + } - public BalanceFetcher(final String pathAccountSid) { - this.pathAccountSid = pathAccountSid; + public BalanceFetcher(final String pathaccountSid) { + this.pathaccountSid = pathaccountSid; } + @Override public Balance fetch(final TwilioRestClient client) { + String path = "/2010-04-01/Accounts/{AccountSid}/Balance.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.API.toString(), - path + HttpMethod.GET, + Domains.API.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Balance fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Balance fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Balance.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/Call.java b/src/main/java/com/twilio/rest/api/v2010/account/Call.java index 8eaf7c203d..251368bcb5 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/Call.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/Call.java @@ -18,135 +18,185 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.CurrencyDeserializer; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import com.twilio.type.Endpoint; +import com.twilio.type.Twiml; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Currency; import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Call extends Resource { - private static final long serialVersionUID = 229062317637234L; - public static CallCreator creator( - final com.twilio.type.Endpoint to, - final com.twilio.type.Endpoint from, - final URI url - ) { - return new CallCreator(to, from, url); + public static CallCreator creator(final Endpoint to, final Endpoint from, final URI url) { + return new CallCreator( + to, from, url + ); } - public static CallCreator creator( - final String pathAccountSid, - final com.twilio.type.Endpoint to, - final com.twilio.type.Endpoint from, - final URI url - ) { - return new CallCreator(pathAccountSid, to, from, url); + + public static CallCreator creator(final String pathaccountSid, final Endpoint to, final Endpoint from, final URI url) { + return new CallCreator( + pathaccountSid, to, from, url + ); } - public static CallCreator creator( - final com.twilio.type.Endpoint to, - final com.twilio.type.Endpoint from, - final com.twilio.type.Twiml twiml - ) { - return new CallCreator(to, from, twiml); + + public static CallCreator creator(final Endpoint to, final Endpoint from, final Twiml twiml) { + return new CallCreator( + to, from, twiml + ); } - public static CallCreator creator( - final String pathAccountSid, - final com.twilio.type.Endpoint to, - final com.twilio.type.Endpoint from, - final com.twilio.type.Twiml twiml - ) { - return new CallCreator(pathAccountSid, to, from, twiml); + + public static CallCreator creator(final String pathaccountSid, final Endpoint to, final Endpoint from, final Twiml twiml) { + return new CallCreator( + pathaccountSid, to, from, twiml + ); } - public static CallCreator creator( - final com.twilio.type.Endpoint to, - final com.twilio.type.Endpoint from, - final String applicationSid - ) { - return new CallCreator(to, from, applicationSid); + + public static CallCreator creator(final Endpoint to, final Endpoint from, final String applicationSid) { + return new CallCreator( + to, from, applicationSid + ); } - public static CallCreator creator( - final String pathAccountSid, - final com.twilio.type.Endpoint to, - final com.twilio.type.Endpoint from, - final String applicationSid - ) { - return new CallCreator(pathAccountSid, to, from, applicationSid); + + public static CallCreator creator(final String pathaccountSid, final Endpoint to, final Endpoint from, final String applicationSid) { + return new CallCreator( + pathaccountSid, to, from, applicationSid + ); } - public static CallDeleter deleter(final String pathSid) { - return new CallDeleter(pathSid); + + public static CallDeleter deleter(final String pathsid) { + return new CallDeleter( + pathsid + ); } - public static CallDeleter deleter( - final String pathAccountSid, - final String pathSid - ) { - return new CallDeleter(pathAccountSid, pathSid); + + public static CallDeleter deleter(final String pathaccountSid, final String pathsid) { + return new CallDeleter( + pathaccountSid, pathsid + ); } - public static CallFetcher fetcher(final String pathSid) { - return new CallFetcher(pathSid); + + public static CallFetcher fetcher(final String pathsid) { + return new CallFetcher( + pathsid + ); } - public static CallFetcher fetcher( - final String pathAccountSid, - final String pathSid - ) { - return new CallFetcher(pathAccountSid, pathSid); + + public static CallFetcher fetcher(final String pathaccountSid, final String pathsid) { + return new CallFetcher( + pathaccountSid, pathsid + ); } + public static CallReader reader() { - return new CallReader(); + return new CallReader( + + ); } - public static CallReader reader(final String pathAccountSid) { - return new CallReader(pathAccountSid); + + public static CallReader reader(final String pathaccountSid) { + return new CallReader( + pathaccountSid + ); } - public static CallUpdater updater(final String pathSid) { - return new CallUpdater(pathSid); + + public static CallUpdater updater(final String pathsid) { + return new CallUpdater( + pathsid + ); } - public static CallUpdater updater( - final String pathAccountSid, - final String pathSid - ) { - return new CallUpdater(pathAccountSid, pathSid); + + public static CallUpdater updater(final String pathaccountSid, final String pathsid) { + return new CallUpdater( + pathaccountSid, pathsid + ); } + + public enum Status { + QUEUED("queued"), + RINGING("ringing"), + IN_PROGRESS("in-progress"), + COMPLETED("completed"), + BUSY("busy"), + FAILED("failed"), + NO_ANSWER("no-answer"), + CANCELED("canceled"); + + private final String value; + + private Status(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static Status forValue(final String value) { + return Promoter.enumFromString(value, Status.values()); + } + } + + public enum UpdateStatus { + CANCELED("canceled"), + COMPLETED("completed"); + + private final String value; + + private UpdateStatus(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static UpdateStatus forValue(final String value) { + return Promoter.enumFromString(value, UpdateStatus.values()); + } + } + + /** * Converts a JSON String into a Call object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Call object represented by the provided JSON */ - public static Call fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Call fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Call.class); @@ -161,14 +211,11 @@ public static Call fromJson( * Converts a JSON InputStream into a Call object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Call object represented by the provided JSON */ - public static Call fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Call fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Call.class); @@ -179,197 +226,132 @@ public static Call fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter + private final String accountSid; + @Getter + private final String answeredBy; + @Getter + private final String apiVersion; + @Getter + private final String callerName; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; - private final String parentCallSid; - private final String accountSid; - private final String to; - private final String toFormatted; + @Getter + private final String direction; + @Getter + private final String duration; + @Getter + private final ZonedDateTime endTime; + @Getter + private final String forwardedFrom; + @Getter private final String from; + @Getter private final String fromFormatted; + @Getter + private final String groupSid; + @Getter + private final String parentCallSid; + @Getter private final String phoneNumberSid; - private final Call.Status status; - private final ZonedDateTime startTime; - private final ZonedDateTime endTime; - private final String duration; + @Getter private final String price; + @Getter private final Currency priceUnit; - private final String direction; - private final String answeredBy; - private final String apiVersion; - private final String forwardedFrom; - private final String groupSid; - private final String callerName; + @Getter private final String queueTime; + @Getter + private final String sid; + @Getter + private final ZonedDateTime startTime; + @Getter + private final Call.Status status; + @Getter + private final Map subresourceUris; + @Getter + private final String to; + @Getter + private final String toFormatted; + @Getter private final String trunkSid; + @Getter private final String uri; - private final Map subresourceUris; @JsonCreator private Call( - @JsonProperty("sid") final String sid, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("parent_call_sid") final String parentCallSid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("to") final String to, - @JsonProperty("to_formatted") final String toFormatted, - @JsonProperty("from") final String from, - @JsonProperty("from_formatted") final String fromFormatted, - @JsonProperty("phone_number_sid") final String phoneNumberSid, - @JsonProperty("status") final Call.Status status, - @JsonProperty("start_time") final String startTime, - @JsonProperty("end_time") final String endTime, - @JsonProperty("duration") final String duration, - @JsonProperty("price") final String price, - @JsonProperty("price_unit") @JsonDeserialize( - using = com.twilio.converter.CurrencyDeserializer.class - ) final Currency priceUnit, - @JsonProperty("direction") final String direction, - @JsonProperty("answered_by") final String answeredBy, - @JsonProperty("api_version") final String apiVersion, - @JsonProperty("forwarded_from") final String forwardedFrom, - @JsonProperty("group_sid") final String groupSid, - @JsonProperty("caller_name") final String callerName, - @JsonProperty("queue_time") final String queueTime, - @JsonProperty("trunk_sid") final String trunkSid, - @JsonProperty("uri") final String uri, - @JsonProperty("subresource_uris") final Map< - String, - String - > subresourceUris + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("answered_by") final String answeredBy, + @JsonProperty("api_version") final String apiVersion, + @JsonProperty("caller_name") final String callerName, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.RFC2822Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.RFC2822Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("direction") final String direction, + @JsonProperty("duration") final String duration, + @JsonProperty("end_time") + @JsonDeserialize(using = com.twilio.converter.RFC2822Deserializer.class) final ZonedDateTime endTime, + @JsonProperty("forwarded_from") final String forwardedFrom, + @JsonProperty("from") final String from, + @JsonProperty("from_formatted") final String fromFormatted, + @JsonProperty("group_sid") final String groupSid, + @JsonProperty("parent_call_sid") final String parentCallSid, + @JsonProperty("phone_number_sid") final String phoneNumberSid, + @JsonProperty("price") final String price, + @JsonProperty("price_unit") + @JsonDeserialize(using = com.twilio.converter.CurrencyDeserializer.class) final Currency priceUnit, + @JsonProperty("queue_time") final String queueTime, + @JsonProperty("sid") final String sid, + @JsonProperty("start_time") + @JsonDeserialize(using = com.twilio.converter.RFC2822Deserializer.class) final ZonedDateTime startTime, + @JsonProperty("status") final Call.Status status, + @JsonProperty("subresource_uris") final Map subresourceUris, + @JsonProperty("to") final String to, + @JsonProperty("to_formatted") final String toFormatted, + @JsonProperty("trunk_sid") final String trunkSid, + @JsonProperty("uri") final String uri ) { - this.sid = sid; - this.dateCreated = DateConverter.rfc2822DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.rfc2822DateTimeFromString(dateUpdated); - this.parentCallSid = parentCallSid; this.accountSid = accountSid; - this.to = to; - this.toFormatted = toFormatted; + this.answeredBy = answeredBy; + this.apiVersion = apiVersion; + this.callerName = callerName; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; + this.direction = direction; + this.duration = duration; + this.endTime = endTime; + this.forwardedFrom = forwardedFrom; this.from = from; this.fromFormatted = fromFormatted; + this.groupSid = groupSid; + this.parentCallSid = parentCallSid; this.phoneNumberSid = phoneNumberSid; - this.status = status; - this.startTime = DateConverter.rfc2822DateTimeFromString(startTime); - this.endTime = DateConverter.rfc2822DateTimeFromString(endTime); - this.duration = duration; this.price = price; this.priceUnit = priceUnit; - this.direction = direction; - this.answeredBy = answeredBy; - this.apiVersion = apiVersion; - this.forwardedFrom = forwardedFrom; - this.groupSid = groupSid; - this.callerName = callerName; this.queueTime = queueTime; + this.sid = sid; + this.startTime = startTime; + this.status = status; + this.subresourceUris = subresourceUris; + this.to = to; + this.toFormatted = toFormatted; this.trunkSid = trunkSid; this.uri = uri; - this.subresourceUris = subresourceUris; - } - - public final String getSid() { - return this.sid; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final String getParentCallSid() { - return this.parentCallSid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getTo() { - return this.to; - } - - public final String getToFormatted() { - return this.toFormatted; - } - - public final String getFrom() { - return this.from; - } - - public final String getFromFormatted() { - return this.fromFormatted; - } - - public final String getPhoneNumberSid() { - return this.phoneNumberSid; - } - - public final Call.Status getStatus() { - return this.status; - } - - public final ZonedDateTime getStartTime() { - return this.startTime; - } - - public final ZonedDateTime getEndTime() { - return this.endTime; - } - - public final String getDuration() { - return this.duration; - } - - public final String getPrice() { - return this.price; - } - - public final Currency getPriceUnit() { - return this.priceUnit; - } - - public final String getDirection() { - return this.direction; - } - - public final String getAnsweredBy() { - return this.answeredBy; - } - - public final String getApiVersion() { - return this.apiVersion; - } - - public final String getForwardedFrom() { - return this.forwardedFrom; - } - - public final String getGroupSid() { - return this.groupSid; - } - - public final String getCallerName() { - return this.callerName; - } - - public final String getQueueTime() { - return this.queueTime; - } - - public final String getTrunkSid() { - return this.trunkSid; - } - - public final String getUri() { - return this.uri; - } - - public final Map getSubresourceUris() { - return this.subresourceUris; } @Override @@ -383,112 +365,68 @@ public boolean equals(final Object o) { } Call other = (Call) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(parentCallSid, other.parentCallSid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(to, other.to) && - Objects.equals(toFormatted, other.toFormatted) && - Objects.equals(from, other.from) && - Objects.equals(fromFormatted, other.fromFormatted) && - Objects.equals(phoneNumberSid, other.phoneNumberSid) && - Objects.equals(status, other.status) && - Objects.equals(startTime, other.startTime) && - Objects.equals(endTime, other.endTime) && - Objects.equals(duration, other.duration) && - Objects.equals(price, other.price) && - Objects.equals(priceUnit, other.priceUnit) && - Objects.equals(direction, other.direction) && - Objects.equals(answeredBy, other.answeredBy) && - Objects.equals(apiVersion, other.apiVersion) && - Objects.equals(forwardedFrom, other.forwardedFrom) && - Objects.equals(groupSid, other.groupSid) && - Objects.equals(callerName, other.callerName) && - Objects.equals(queueTime, other.queueTime) && - Objects.equals(trunkSid, other.trunkSid) && - Objects.equals(uri, other.uri) && - Objects.equals(subresourceUris, other.subresourceUris) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(answeredBy, other.answeredBy) && + Objects.equals(apiVersion, other.apiVersion) && + Objects.equals(callerName, other.callerName) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(direction, other.direction) && + Objects.equals(duration, other.duration) && + Objects.equals(endTime, other.endTime) && + Objects.equals(forwardedFrom, other.forwardedFrom) && + Objects.equals(from, other.from) && + Objects.equals(fromFormatted, other.fromFormatted) && + Objects.equals(groupSid, other.groupSid) && + Objects.equals(parentCallSid, other.parentCallSid) && + Objects.equals(phoneNumberSid, other.phoneNumberSid) && + Objects.equals(price, other.price) && + Objects.equals(priceUnit, other.priceUnit) && + Objects.equals(queueTime, other.queueTime) && + Objects.equals(sid, other.sid) && + Objects.equals(startTime, other.startTime) && + Objects.equals(status, other.status) && + Objects.equals(subresourceUris, other.subresourceUris) && + Objects.equals(to, other.to) && + Objects.equals(toFormatted, other.toFormatted) && + Objects.equals(trunkSid, other.trunkSid) && + Objects.equals(uri, other.uri) ); } @Override public int hashCode() { return Objects.hash( - sid, - dateCreated, - dateUpdated, - parentCallSid, - accountSid, - to, - toFormatted, - from, - fromFormatted, - phoneNumberSid, - status, - startTime, - endTime, - duration, - price, - priceUnit, - direction, - answeredBy, - apiVersion, - forwardedFrom, - groupSid, - callerName, - queueTime, - trunkSid, - uri, - subresourceUris + accountSid, + answeredBy, + apiVersion, + callerName, + dateCreated, + dateUpdated, + direction, + duration, + endTime, + forwardedFrom, + from, + fromFormatted, + groupSid, + parentCallSid, + phoneNumberSid, + price, + priceUnit, + queueTime, + sid, + startTime, + status, + subresourceUris, + to, + toFormatted, + trunkSid, + uri ); } - public enum Status { - QUEUED("queued"), - RINGING("ringing"), - IN_PROGRESS("in-progress"), - COMPLETED("completed"), - BUSY("busy"), - FAILED("failed"), - NO_ANSWER("no-answer"), - CANCELED("canceled"); - - private final String value; - - private Status(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static Status forValue(final String value) { - return Promoter.enumFromString(value, Status.values()); - } - } - - public enum UpdateStatus { - CANCELED("canceled"), - COMPLETED("completed"); - - private final String value; - - private UpdateStatus(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - @JsonCreator - public static UpdateStatus forValue(final String value) { - return Promoter.enumFromString(value, UpdateStatus.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/api/v2010/account/CallCreator.java b/src/main/java/com/twilio/rest/api/v2010/account/CallCreator.java index a1eb6dc461..1af1044a2b 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/CallCreator.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/CallCreator.java @@ -14,9 +14,12 @@ package com.twilio.rest.api.v2010.account; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; import com.twilio.converter.Promoter; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,16 +28,17 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; +import com.twilio.type.Endpoint; +import com.twilio.type.Twiml; + import java.net.URI; -import java.net.URI; -import java.util.List; import java.util.List; public class CallCreator extends Creator { - private com.twilio.type.Endpoint to; - private com.twilio.type.Endpoint from; - private String pathAccountSid; + private String pathaccountSid; + private Endpoint to; + private Endpoint from; private HttpMethod method; private URI fallbackUrl; private HttpMethod fallbackMethod; @@ -66,202 +70,167 @@ public class CallCreator extends Creator { private String recordingTrack; private Integer timeLimit; private URI url; - private com.twilio.type.Twiml twiml; + private Twiml twiml; private String applicationSid; - public CallCreator( - final com.twilio.type.Endpoint to, - final com.twilio.type.Endpoint from, - final URI url - ) { + public CallCreator(final Endpoint to, final Endpoint from, final URI url) { this.to = to; this.from = from; this.url = url; } - public CallCreator( - final String pathAccountSid, - final com.twilio.type.Endpoint to, - final com.twilio.type.Endpoint from, - final URI url - ) { - this.pathAccountSid = pathAccountSid; + public CallCreator(final String pathaccountSid, final Endpoint to, final Endpoint from, final URI url) { + this.pathaccountSid = pathaccountSid; this.to = to; this.from = from; this.url = url; } - public CallCreator( - final com.twilio.type.Endpoint to, - final com.twilio.type.Endpoint from, - final com.twilio.type.Twiml twiml - ) { + public CallCreator(final Endpoint to, final Endpoint from, final Twiml twiml) { this.to = to; this.from = from; this.twiml = twiml; } - public CallCreator( - final String pathAccountSid, - final com.twilio.type.Endpoint to, - final com.twilio.type.Endpoint from, - final com.twilio.type.Twiml twiml - ) { - this.pathAccountSid = pathAccountSid; + public CallCreator(final String pathaccountSid, final Endpoint to, final Endpoint from, final Twiml twiml) { + this.pathaccountSid = pathaccountSid; this.to = to; this.from = from; this.twiml = twiml; } - public CallCreator( - final com.twilio.type.Endpoint to, - final com.twilio.type.Endpoint from, - final String applicationSid - ) { + public CallCreator(final Endpoint to, final Endpoint from, final String applicationSid) { this.to = to; this.from = from; this.applicationSid = applicationSid; } - public CallCreator( - final String pathAccountSid, - final com.twilio.type.Endpoint to, - final com.twilio.type.Endpoint from, - final String applicationSid - ) { - this.pathAccountSid = pathAccountSid; + public CallCreator(final String pathaccountSid, final Endpoint to, final Endpoint from, final String applicationSid) { + this.pathaccountSid = pathaccountSid; this.to = to; this.from = from; this.applicationSid = applicationSid; } - public CallCreator setTo(final com.twilio.type.Endpoint to) { + + public CallCreator setTo(final Endpoint to) { this.to = to; return this; } - public CallCreator setFrom(final com.twilio.type.Endpoint from) { + + public CallCreator setFrom(final Endpoint from) { this.from = from; return this; } + public CallCreator setMethod(final HttpMethod method) { this.method = method; return this; } + public CallCreator setFallbackUrl(final URI fallbackUrl) { this.fallbackUrl = fallbackUrl; return this; } - public CallCreator setFallbackUrl(final String fallbackUrl) { - return setFallbackUrl(Promoter.uriFromString(fallbackUrl)); - } public CallCreator setFallbackMethod(final HttpMethod fallbackMethod) { this.fallbackMethod = fallbackMethod; return this; } + public CallCreator setStatusCallback(final URI statusCallback) { this.statusCallback = statusCallback; return this; } - public CallCreator setStatusCallback(final String statusCallback) { - return setStatusCallback(Promoter.uriFromString(statusCallback)); - } - public CallCreator setStatusCallbackEvent( - final List statusCallbackEvent - ) { + public CallCreator setStatusCallbackEvent(final List statusCallbackEvent) { this.statusCallbackEvent = statusCallbackEvent; return this; } - public CallCreator setStatusCallbackEvent( - final String statusCallbackEvent - ) { + public CallCreator setStatusCallbackEvent(final String statusCallbackEvent) { return setStatusCallbackEvent(Promoter.listOfOne(statusCallbackEvent)); } - public CallCreator setStatusCallbackMethod( - final HttpMethod statusCallbackMethod - ) { + public CallCreator setStatusCallbackMethod(final HttpMethod statusCallbackMethod) { this.statusCallbackMethod = statusCallbackMethod; return this; } + public CallCreator setSendDigits(final String sendDigits) { this.sendDigits = sendDigits; return this; } + public CallCreator setTimeout(final Integer timeout) { this.timeout = timeout; return this; } + public CallCreator setRecord(final Boolean record) { this.record = record; return this; } + public CallCreator setRecordingChannels(final String recordingChannels) { this.recordingChannels = recordingChannels; return this; } - public CallCreator setRecordingStatusCallback( - final String recordingStatusCallback - ) { + + public CallCreator setRecordingStatusCallback(final String recordingStatusCallback) { this.recordingStatusCallback = recordingStatusCallback; return this; } - public CallCreator setRecordingStatusCallbackMethod( - final HttpMethod recordingStatusCallbackMethod - ) { + + public CallCreator setRecordingStatusCallbackMethod(final HttpMethod recordingStatusCallbackMethod) { this.recordingStatusCallbackMethod = recordingStatusCallbackMethod; return this; } + public CallCreator setSipAuthUsername(final String sipAuthUsername) { this.sipAuthUsername = sipAuthUsername; return this; } + public CallCreator setSipAuthPassword(final String sipAuthPassword) { this.sipAuthPassword = sipAuthPassword; return this; } + public CallCreator setMachineDetection(final String machineDetection) { this.machineDetection = machineDetection; return this; } - public CallCreator setMachineDetectionTimeout( - final Integer machineDetectionTimeout - ) { + + public CallCreator setMachineDetectionTimeout(final Integer machineDetectionTimeout) { this.machineDetectionTimeout = machineDetectionTimeout; return this; } - public CallCreator setRecordingStatusCallbackEvent( - final List recordingStatusCallbackEvent - ) { + + public CallCreator setRecordingStatusCallbackEvent(final List recordingStatusCallbackEvent) { this.recordingStatusCallbackEvent = recordingStatusCallbackEvent; return this; } - public CallCreator setRecordingStatusCallbackEvent( - final String recordingStatusCallbackEvent - ) { - return setRecordingStatusCallbackEvent( - Promoter.listOfOne(recordingStatusCallbackEvent) - ); + public CallCreator setRecordingStatusCallbackEvent(final String recordingStatusCallbackEvent) { + return setRecordingStatusCallbackEvent(Promoter.listOfOne(recordingStatusCallbackEvent)); } public CallCreator setTrim(final String trim) { @@ -269,95 +238,86 @@ public CallCreator setTrim(final String trim) { return this; } + public CallCreator setCallerId(final String callerId) { this.callerId = callerId; return this; } - public CallCreator setMachineDetectionSpeechThreshold( - final Integer machineDetectionSpeechThreshold - ) { + + public CallCreator setMachineDetectionSpeechThreshold(final Integer machineDetectionSpeechThreshold) { this.machineDetectionSpeechThreshold = machineDetectionSpeechThreshold; return this; } - public CallCreator setMachineDetectionSpeechEndThreshold( - final Integer machineDetectionSpeechEndThreshold - ) { - this.machineDetectionSpeechEndThreshold = - machineDetectionSpeechEndThreshold; + + public CallCreator setMachineDetectionSpeechEndThreshold(final Integer machineDetectionSpeechEndThreshold) { + this.machineDetectionSpeechEndThreshold = machineDetectionSpeechEndThreshold; return this; } - public CallCreator setMachineDetectionSilenceTimeout( - final Integer machineDetectionSilenceTimeout - ) { + + public CallCreator setMachineDetectionSilenceTimeout(final Integer machineDetectionSilenceTimeout) { this.machineDetectionSilenceTimeout = machineDetectionSilenceTimeout; return this; } + public CallCreator setAsyncAmd(final String asyncAmd) { this.asyncAmd = asyncAmd; return this; } - public CallCreator setAsyncAmdStatusCallback( - final URI asyncAmdStatusCallback - ) { + + public CallCreator setAsyncAmdStatusCallback(final URI asyncAmdStatusCallback) { this.asyncAmdStatusCallback = asyncAmdStatusCallback; return this; } - public CallCreator setAsyncAmdStatusCallback( - final String asyncAmdStatusCallback - ) { - return setAsyncAmdStatusCallback( - Promoter.uriFromString(asyncAmdStatusCallback) - ); - } - public CallCreator setAsyncAmdStatusCallbackMethod( - final HttpMethod asyncAmdStatusCallbackMethod - ) { + public CallCreator setAsyncAmdStatusCallbackMethod(final HttpMethod asyncAmdStatusCallbackMethod) { this.asyncAmdStatusCallbackMethod = asyncAmdStatusCallbackMethod; return this; } + public CallCreator setByoc(final String byoc) { this.byoc = byoc; return this; } + public CallCreator setCallReason(final String callReason) { this.callReason = callReason; return this; } + public CallCreator setCallToken(final String callToken) { this.callToken = callToken; return this; } + public CallCreator setRecordingTrack(final String recordingTrack) { this.recordingTrack = recordingTrack; return this; } + public CallCreator setTimeLimit(final Integer timeLimit) { this.timeLimit = timeLimit; return this; } + public CallCreator setUrl(final URI url) { this.url = url; return this; } - public CallCreator setUrl(final String url) { - return setUrl(Promoter.uriFromString(url)); - } - public CallCreator setTwiml(final com.twilio.type.Twiml twiml) { + public CallCreator setTwiml(final Twiml twiml) { this.twiml = twiml; return this; } @@ -371,44 +331,35 @@ public CallCreator setApplicationSid(final String applicationSid) { return this; } + @Override public Call create(final TwilioRestClient client) { + String path = "/2010-04-01/Accounts/{AccountSid}/Calls.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = path.replace("{" + "To" + "}", this.to.toString()); - path = path.replace("{" + "From" + "}", this.from.toString()); + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.API.toString(), - path + HttpMethod.POST, + Domains.API.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Call creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("Call creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -417,141 +368,185 @@ public Call create(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (to != null) { - request.addPostParam("To", to.toString()); + Serializer.toString(request, "To", to, ParameterType.URLENCODED); } + + if (from != null) { - request.addPostParam("From", from.toString()); + Serializer.toString(request, "From", from, ParameterType.URLENCODED); } + + if (method != null) { - request.addPostParam("Method", method.toString()); + Serializer.toString(request, "Method", method, ParameterType.URLENCODED); } + + if (fallbackUrl != null) { - request.addPostParam("FallbackUrl", fallbackUrl.toString()); + Serializer.toString(request, "FallbackUrl", fallbackUrl, ParameterType.URLENCODED); } + + if (fallbackMethod != null) { - request.addPostParam("FallbackMethod", fallbackMethod.toString()); + Serializer.toString(request, "FallbackMethod", fallbackMethod, ParameterType.URLENCODED); } + + if (statusCallback != null) { - request.addPostParam("StatusCallback", statusCallback.toString()); + Serializer.toString(request, "StatusCallback", statusCallback, ParameterType.URLENCODED); } + + if (statusCallbackEvent != null) { - for (String prop : statusCallbackEvent) { - request.addPostParam("StatusCallbackEvent", prop); + for (String param : statusCallbackEvent) { + Serializer.toString(request, "StatusCallbackEvent", param, ParameterType.URLENCODED); } } + + if (statusCallbackMethod != null) { - request.addPostParam( - "StatusCallbackMethod", - statusCallbackMethod.toString() - ); + Serializer.toString(request, "StatusCallbackMethod", statusCallbackMethod, ParameterType.URLENCODED); } + + if (sendDigits != null) { - request.addPostParam("SendDigits", sendDigits); + Serializer.toString(request, "SendDigits", sendDigits, ParameterType.URLENCODED); } + + if (timeout != null) { - request.addPostParam("Timeout", timeout.toString()); + Serializer.toString(request, "Timeout", timeout, ParameterType.URLENCODED); } + + if (record != null) { - request.addPostParam("Record", record.toString()); + Serializer.toString(request, "Record", record, ParameterType.URLENCODED); } + + if (recordingChannels != null) { - request.addPostParam("RecordingChannels", recordingChannels); + Serializer.toString(request, "RecordingChannels", recordingChannels, ParameterType.URLENCODED); } + + if (recordingStatusCallback != null) { - request.addPostParam( - "RecordingStatusCallback", - recordingStatusCallback - ); + Serializer.toString(request, "RecordingStatusCallback", recordingStatusCallback, ParameterType.URLENCODED); } + + if (recordingStatusCallbackMethod != null) { - request.addPostParam( - "RecordingStatusCallbackMethod", - recordingStatusCallbackMethod.toString() - ); + Serializer.toString(request, "RecordingStatusCallbackMethod", recordingStatusCallbackMethod, ParameterType.URLENCODED); } + + if (sipAuthUsername != null) { - request.addPostParam("SipAuthUsername", sipAuthUsername); + Serializer.toString(request, "SipAuthUsername", sipAuthUsername, ParameterType.URLENCODED); } + + if (sipAuthPassword != null) { - request.addPostParam("SipAuthPassword", sipAuthPassword); + Serializer.toString(request, "SipAuthPassword", sipAuthPassword, ParameterType.URLENCODED); } + + if (machineDetection != null) { - request.addPostParam("MachineDetection", machineDetection); + Serializer.toString(request, "MachineDetection", machineDetection, ParameterType.URLENCODED); } + + if (machineDetectionTimeout != null) { - request.addPostParam( - "MachineDetectionTimeout", - machineDetectionTimeout.toString() - ); + Serializer.toString(request, "MachineDetectionTimeout", machineDetectionTimeout, ParameterType.URLENCODED); } + + if (recordingStatusCallbackEvent != null) { - for (String prop : recordingStatusCallbackEvent) { - request.addPostParam("RecordingStatusCallbackEvent", prop); + for (String param : recordingStatusCallbackEvent) { + Serializer.toString(request, "RecordingStatusCallbackEvent", param, ParameterType.URLENCODED); } } + + if (trim != null) { - request.addPostParam("Trim", trim); + Serializer.toString(request, "Trim", trim, ParameterType.URLENCODED); } + + if (callerId != null) { - request.addPostParam("CallerId", callerId); + Serializer.toString(request, "CallerId", callerId, ParameterType.URLENCODED); } + + if (machineDetectionSpeechThreshold != null) { - request.addPostParam( - "MachineDetectionSpeechThreshold", - machineDetectionSpeechThreshold.toString() - ); + Serializer.toString(request, "MachineDetectionSpeechThreshold", machineDetectionSpeechThreshold, ParameterType.URLENCODED); } + + if (machineDetectionSpeechEndThreshold != null) { - request.addPostParam( - "MachineDetectionSpeechEndThreshold", - machineDetectionSpeechEndThreshold.toString() - ); + Serializer.toString(request, "MachineDetectionSpeechEndThreshold", machineDetectionSpeechEndThreshold, ParameterType.URLENCODED); } + + if (machineDetectionSilenceTimeout != null) { - request.addPostParam( - "MachineDetectionSilenceTimeout", - machineDetectionSilenceTimeout.toString() - ); + Serializer.toString(request, "MachineDetectionSilenceTimeout", machineDetectionSilenceTimeout, ParameterType.URLENCODED); } + + if (asyncAmd != null) { - request.addPostParam("AsyncAmd", asyncAmd); + Serializer.toString(request, "AsyncAmd", asyncAmd, ParameterType.URLENCODED); } + + if (asyncAmdStatusCallback != null) { - request.addPostParam( - "AsyncAmdStatusCallback", - asyncAmdStatusCallback.toString() - ); + Serializer.toString(request, "AsyncAmdStatusCallback", asyncAmdStatusCallback, ParameterType.URLENCODED); } + + if (asyncAmdStatusCallbackMethod != null) { - request.addPostParam( - "AsyncAmdStatusCallbackMethod", - asyncAmdStatusCallbackMethod.toString() - ); + Serializer.toString(request, "AsyncAmdStatusCallbackMethod", asyncAmdStatusCallbackMethod, ParameterType.URLENCODED); } + + if (byoc != null) { - request.addPostParam("Byoc", byoc); + Serializer.toString(request, "Byoc", byoc, ParameterType.URLENCODED); } + + if (callReason != null) { - request.addPostParam("CallReason", callReason); + Serializer.toString(request, "CallReason", callReason, ParameterType.URLENCODED); } + + if (callToken != null) { - request.addPostParam("CallToken", callToken); + Serializer.toString(request, "CallToken", callToken, ParameterType.URLENCODED); } + + if (recordingTrack != null) { - request.addPostParam("RecordingTrack", recordingTrack); + Serializer.toString(request, "RecordingTrack", recordingTrack, ParameterType.URLENCODED); } + + if (timeLimit != null) { - request.addPostParam("TimeLimit", timeLimit.toString()); + Serializer.toString(request, "TimeLimit", timeLimit, ParameterType.URLENCODED); } + + if (url != null) { - request.addPostParam("Url", url.toString()); + Serializer.toString(request, "Url", url, ParameterType.URLENCODED); } + + if (twiml != null) { - request.addPostParam("Twiml", twiml.toString()); + Serializer.toString(request, "Twiml", twiml, ParameterType.URLENCODED); } + + if (applicationSid != null) { - request.addPostParam("ApplicationSid", applicationSid); + Serializer.toString(request, "ApplicationSid", applicationSid, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/CallDeleter.java b/src/main/java/com/twilio/rest/api/v2010/account/CallDeleter.java index ce7654c757..f91fa603c9 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/CallDeleter.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/CallDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.api.v2010.account; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,55 +26,46 @@ public class CallDeleter extends Deleter { - private String pathSid; - private String pathAccountSid; + private String pathaccountSid; + private String pathsid; - public CallDeleter(final String pathSid) { - this.pathSid = pathSid; + public CallDeleter(final String pathsid) { + this.pathsid = pathsid; } - public CallDeleter(final String pathAccountSid, final String pathSid) { - this.pathAccountSid = pathAccountSid; - this.pathSid = pathSid; + public CallDeleter(final String pathaccountSid, final String pathsid) { + this.pathaccountSid = pathaccountSid; + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/2010-04-01/Accounts/{AccountSid}/Calls/{Sid}.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.API.toString(), - path + HttpMethod.DELETE, + Domains.API.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Call delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("Call delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/CallFetcher.java b/src/main/java/com/twilio/rest/api/v2010/account/CallFetcher.java index fd124d1eb5..23d1823c05 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/CallFetcher.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/CallFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.api.v2010.account; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,59 +26,49 @@ public class CallFetcher extends Fetcher { - private String pathSid; - private String pathAccountSid; + private String pathaccountSid; + private String pathsid; - public CallFetcher(final String pathSid) { - this.pathSid = pathSid; + public CallFetcher(final String pathsid) { + this.pathsid = pathsid; } - public CallFetcher(final String pathAccountSid, final String pathSid) { - this.pathAccountSid = pathAccountSid; - this.pathSid = pathSid; + public CallFetcher(final String pathaccountSid, final String pathsid) { + this.pathaccountSid = pathaccountSid; + this.pathsid = pathsid; } + @Override public Call fetch(final TwilioRestClient client) { + String path = "/2010-04-01/Accounts/{AccountSid}/Calls/{Sid}.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.API.toString(), - path + HttpMethod.GET, + Domains.API.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Call fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Call fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Call.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/CallReader.java b/src/main/java/com/twilio/rest/api/v2010/account/CallReader.java index 67d2f9b375..8a98ce4a2c 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/CallReader.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/CallReader.java @@ -17,8 +17,9 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; import com.twilio.converter.Promoter; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,12 +28,12 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.time.ZonedDateTime; -import java.time.format.DateTimeFormatter; public class CallReader extends Reader { - private String pathAccountSid; + private String pathaccountSid; private com.twilio.type.PhoneNumber to; private com.twilio.type.PhoneNumber from; private String parentCallSid; @@ -45,12 +46,14 @@ public class CallReader extends Reader { private ZonedDateTime endTimeAfter; private Long pageSize; - public CallReader() {} + public CallReader() { + } - public CallReader(final String pathAccountSid) { - this.pathAccountSid = pathAccountSid; + public CallReader(final String pathaccountSid) { + this.pathaccountSid = pathaccountSid; } + public CallReader setTo(final com.twilio.type.PhoneNumber to) { this.to = to; return this; @@ -74,191 +77,174 @@ public CallReader setParentCallSid(final String parentCallSid) { return this; } + public CallReader setStatus(final Call.Status status) { this.status = status; return this; } + public CallReader setStartTime(final ZonedDateTime startTime) { this.startTime = startTime; return this; } + public CallReader setStartTimeBefore(final ZonedDateTime startTimeBefore) { this.startTimeBefore = startTimeBefore; return this; } + public CallReader setStartTimeAfter(final ZonedDateTime startTimeAfter) { this.startTimeAfter = startTimeAfter; return this; } + public CallReader setEndTime(final ZonedDateTime endTime) { this.endTime = endTime; return this; } + public CallReader setEndTimeBefore(final ZonedDateTime endTimeBefore) { this.endTimeBefore = endTimeBefore; return this; } + public CallReader setEndTimeAfter(final ZonedDateTime endTimeAfter) { this.endTimeAfter = endTimeAfter; return this; } + public CallReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/2010-04-01/Accounts/{AccountSid}/Calls.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.API.toString(), - path + HttpMethod.GET, + Domains.API.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Call read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Call read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "calls", - response.getContent(), - Call.class, - client.getObjectMapper() - ); + "calls", + response.getContent(), + Call.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.API.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.API.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (to != null) { - request.addQueryParam("To", to.toString()); + Serializer.toString(request, "To", to, ParameterType.QUERY); } + + if (from != null) { - request.addQueryParam("From", from.toString()); + Serializer.toString(request, "From", from, ParameterType.QUERY); } + + if (parentCallSid != null) { - request.addQueryParam("ParentCallSid", parentCallSid); + Serializer.toString(request, "ParentCallSid", parentCallSid, ParameterType.QUERY); } + + if (status != null) { - request.addQueryParam("Status", status.toString()); + Serializer.toString(request, "Status", status, ParameterType.QUERY); } + + if (startTime != null) { - request.addQueryParam( - "StartTime", - startTime.format( - DateTimeFormatter.ofPattern( - Request.QUERY_STRING_DATE_TIME_FORMAT - ) - ) - ); - } else if (startTimeAfter != null || startTimeBefore != null) { - request.addQueryDateTimeRange( - "StartTime", - startTimeAfter, - startTimeBefore - ); + Serializer.toString(request, "StartTime", startTime, ParameterType.QUERY); + } + + + if (startTimeBefore != null) { + Serializer.toString(request, "StartTime<", startTimeBefore, ParameterType.QUERY); + } + + + if (startTimeAfter != null) { + Serializer.toString(request, "StartTime>", startTimeAfter, ParameterType.QUERY); } + + if (endTime != null) { - request.addQueryParam( - "EndTime", - endTime.format( - DateTimeFormatter.ofPattern( - Request.QUERY_STRING_DATE_TIME_FORMAT - ) - ) - ); - } else if (endTimeAfter != null || endTimeBefore != null) { - request.addQueryDateTimeRange( - "EndTime", - endTimeAfter, - endTimeBefore - ); + Serializer.toString(request, "EndTime", endTime, ParameterType.QUERY); } - if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + + + if (endTimeBefore != null) { + Serializer.toString(request, "EndTime<", endTimeBefore, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); + + if (endTimeAfter != null) { + Serializer.toString(request, "EndTime>", endTimeAfter, ParameterType.QUERY); } + + + if (pageSize != null) { + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); + } + + } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/CallUpdater.java b/src/main/java/com/twilio/rest/api/v2010/account/CallUpdater.java index e0f461315e..72254714bb 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/CallUpdater.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/CallUpdater.java @@ -16,7 +16,9 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; import com.twilio.converter.Promoter; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,12 +27,13 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; +import com.twilio.type.Twiml; + import java.net.URI; public class CallUpdater extends Updater { - - private String pathSid; - private String pathAccountSid; + private String pathaccountSid; + private String pathsid; private URI url; private HttpMethod method; private Call.UpdateStatus status; @@ -38,68 +41,62 @@ public class CallUpdater extends Updater { private HttpMethod fallbackMethod; private URI statusCallback; private HttpMethod statusCallbackMethod; - private com.twilio.type.Twiml twiml; + private Twiml twiml; private Integer timeLimit; - public CallUpdater(final String pathSid) { - this.pathSid = pathSid; + public CallUpdater(final String pathsid) { + this.pathsid = pathsid; } - public CallUpdater(final String pathAccountSid, final String pathSid) { - this.pathAccountSid = pathAccountSid; - this.pathSid = pathSid; + public CallUpdater(final String pathaccountSid, final String pathsid) { + this.pathaccountSid = pathaccountSid; + this.pathsid = pathsid; } + public CallUpdater setUrl(final URI url) { this.url = url; return this; } - public CallUpdater setUrl(final String url) { - return setUrl(Promoter.uriFromString(url)); - } public CallUpdater setMethod(final HttpMethod method) { this.method = method; return this; } + public CallUpdater setStatus(final Call.UpdateStatus status) { this.status = status; return this; } + public CallUpdater setFallbackUrl(final URI fallbackUrl) { this.fallbackUrl = fallbackUrl; return this; } - public CallUpdater setFallbackUrl(final String fallbackUrl) { - return setFallbackUrl(Promoter.uriFromString(fallbackUrl)); - } public CallUpdater setFallbackMethod(final HttpMethod fallbackMethod) { this.fallbackMethod = fallbackMethod; return this; } + public CallUpdater setStatusCallback(final URI statusCallback) { this.statusCallback = statusCallback; return this; } - public CallUpdater setStatusCallback(final String statusCallback) { - return setStatusCallback(Promoter.uriFromString(statusCallback)); - } - public CallUpdater setStatusCallbackMethod( - final HttpMethod statusCallbackMethod - ) { + public CallUpdater setStatusCallbackMethod(final HttpMethod statusCallbackMethod) { this.statusCallbackMethod = statusCallbackMethod; return this; } - public CallUpdater setTwiml(final com.twilio.type.Twiml twiml) { + + public CallUpdater setTwiml(final Twiml twiml) { this.twiml = twiml; return this; } @@ -113,43 +110,36 @@ public CallUpdater setTimeLimit(final Integer timeLimit) { return this; } + @Override public Call update(final TwilioRestClient client) { + String path = "/2010-04-01/Accounts/{AccountSid}/Calls/{Sid}.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.API.toString(), - path + HttpMethod.POST, + Domains.API.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Call update failed: Unable to connect to server" - ); + throw new ApiConnectionException("Call update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -158,35 +148,51 @@ public Call update(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (url != null) { - request.addPostParam("Url", url.toString()); + Serializer.toString(request, "Url", url, ParameterType.URLENCODED); } + + if (method != null) { - request.addPostParam("Method", method.toString()); + Serializer.toString(request, "Method", method, ParameterType.URLENCODED); } + + if (status != null) { - request.addPostParam("Status", status.toString()); + Serializer.toString(request, "Status", status, ParameterType.URLENCODED); } + + if (fallbackUrl != null) { - request.addPostParam("FallbackUrl", fallbackUrl.toString()); + Serializer.toString(request, "FallbackUrl", fallbackUrl, ParameterType.URLENCODED); } + + if (fallbackMethod != null) { - request.addPostParam("FallbackMethod", fallbackMethod.toString()); + Serializer.toString(request, "FallbackMethod", fallbackMethod, ParameterType.URLENCODED); } + + if (statusCallback != null) { - request.addPostParam("StatusCallback", statusCallback.toString()); + Serializer.toString(request, "StatusCallback", statusCallback, ParameterType.URLENCODED); } + + if (statusCallbackMethod != null) { - request.addPostParam( - "StatusCallbackMethod", - statusCallbackMethod.toString() - ); + Serializer.toString(request, "StatusCallbackMethod", statusCallbackMethod, ParameterType.URLENCODED); } + + if (twiml != null) { - request.addPostParam("Twiml", twiml.toString()); + Serializer.toString(request, "Twiml", twiml, ParameterType.URLENCODED); } + + if (timeLimit != null) { - request.addPostParam("TimeLimit", timeLimit.toString()); + Serializer.toString(request, "TimeLimit", timeLimit, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/Conference.java b/src/main/java/com/twilio/rest/api/v2010/account/Conference.java index bcb13ce3df..9e9f9a682c 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/Conference.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/Conference.java @@ -18,69 +18,142 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.time.ZonedDateTime; import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Conference extends Resource { - private static final long serialVersionUID = 143481327355997L; - public static ConferenceFetcher fetcher(final String pathSid) { - return new ConferenceFetcher(pathSid); + public static ConferenceFetcher fetcher(final String pathsid) { + return new ConferenceFetcher( + pathsid + ); } - public static ConferenceFetcher fetcher( - final String pathAccountSid, - final String pathSid - ) { - return new ConferenceFetcher(pathAccountSid, pathSid); + + public static ConferenceFetcher fetcher(final String pathaccountSid, final String pathsid) { + return new ConferenceFetcher( + pathaccountSid, pathsid + ); } + public static ConferenceReader reader() { - return new ConferenceReader(); + return new ConferenceReader( + + ); } - public static ConferenceReader reader(final String pathAccountSid) { - return new ConferenceReader(pathAccountSid); + + public static ConferenceReader reader(final String pathaccountSid) { + return new ConferenceReader( + pathaccountSid + ); } - public static ConferenceUpdater updater(final String pathSid) { - return new ConferenceUpdater(pathSid); + + public static ConferenceUpdater updater(final String pathsid) { + return new ConferenceUpdater( + pathsid + ); } - public static ConferenceUpdater updater( - final String pathAccountSid, - final String pathSid - ) { - return new ConferenceUpdater(pathAccountSid, pathSid); + + public static ConferenceUpdater updater(final String pathaccountSid, final String pathsid) { + return new ConferenceUpdater( + pathaccountSid, pathsid + ); } + + public enum Status { + INIT("init"), + IN_PROGRESS("in-progress"), + COMPLETED("completed"); + + private final String value; + + private Status(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static Status forValue(final String value) { + return Promoter.enumFromString(value, Status.values()); + } + } + + public enum UpdateStatus { + COMPLETED("completed"); + + private final String value; + + private UpdateStatus(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static UpdateStatus forValue(final String value) { + return Promoter.enumFromString(value, UpdateStatus.values()); + } + } + + public enum ReasonConferenceEnded { + CONFERENCE_ENDED_VIA_API("conference-ended-via-api"), + PARTICIPANT_WITH_END_CONFERENCE_ON_EXIT_LEFT("participant-with-end-conference-on-exit-left"), + PARTICIPANT_WITH_END_CONFERENCE_ON_EXIT_KICKED("participant-with-end-conference-on-exit-kicked"), + LAST_PARTICIPANT_KICKED("last-participant-kicked"), + LAST_PARTICIPANT_LEFT("last-participant-left"); + + private final String value; + + private ReasonConferenceEnded(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static ReasonConferenceEnded forValue(final String value) { + return Promoter.enumFromString(value, ReasonConferenceEnded.values()); + } + } + + /** * Converts a JSON String into a Conference object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Conference object represented by the provided JSON */ - public static Conference fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Conference fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Conference.class); @@ -95,14 +168,11 @@ public static Conference fromJson( * Converts a JSON InputStream into a Conference object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Conference object represented by the provided JSON */ - public static Conference fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Conference fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Conference.class); @@ -113,101 +183,73 @@ public static Conference fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; + @Getter + private final String apiVersion; + @Getter + private final String callSidEndingConference; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; - private final String apiVersion; + @Getter private final String friendlyName; + @Getter + private final Conference.ReasonConferenceEnded reasonConferenceEnded; + @Getter private final String region; + @Getter private final String sid; + @Getter private final Conference.Status status; - private final String uri; + @Getter private final Map subresourceUris; - private final Conference.ReasonConferenceEnded reasonConferenceEnded; - private final String callSidEndingConference; + @Getter + private final String uri; @JsonCreator private Conference( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("api_version") final String apiVersion, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("region") final String region, - @JsonProperty("sid") final String sid, - @JsonProperty("status") final Conference.Status status, - @JsonProperty("uri") final String uri, - @JsonProperty("subresource_uris") final Map< - String, - String - > subresourceUris, - @JsonProperty( - "reason_conference_ended" - ) final Conference.ReasonConferenceEnded reasonConferenceEnded, - @JsonProperty( - "call_sid_ending_conference" - ) final String callSidEndingConference + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("api_version") final String apiVersion, + @JsonProperty("call_sid_ending_conference") final String callSidEndingConference, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.RFC2822Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.RFC2822Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("reason_conference_ended") final Conference.ReasonConferenceEnded reasonConferenceEnded, + @JsonProperty("region") final String region, + @JsonProperty("sid") final String sid, + @JsonProperty("status") final Conference.Status status, + @JsonProperty("subresource_uris") final Map subresourceUris, + @JsonProperty("uri") final String uri ) { this.accountSid = accountSid; - this.dateCreated = DateConverter.rfc2822DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.rfc2822DateTimeFromString(dateUpdated); this.apiVersion = apiVersion; + this.callSidEndingConference = callSidEndingConference; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.friendlyName = friendlyName; + this.reasonConferenceEnded = reasonConferenceEnded; this.region = region; this.sid = sid; this.status = status; - this.uri = uri; this.subresourceUris = subresourceUris; - this.reasonConferenceEnded = reasonConferenceEnded; - this.callSidEndingConference = callSidEndingConference; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final String getApiVersion() { - return this.apiVersion; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final String getRegion() { - return this.region; - } - - public final String getSid() { - return this.sid; - } - - public final Conference.Status getStatus() { - return this.status; - } - - public final String getUri() { - return this.uri; - } - - public final Map getSubresourceUris() { - return this.subresourceUris; - } - - public final Conference.ReasonConferenceEnded getReasonConferenceEnded() { - return this.reasonConferenceEnded; - } - - public final String getCallSidEndingConference() { - return this.callSidEndingConference; + this.uri = uri; } @Override @@ -221,114 +263,40 @@ public boolean equals(final Object o) { } Conference other = (Conference) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(apiVersion, other.apiVersion) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(region, other.region) && - Objects.equals(sid, other.sid) && - Objects.equals(status, other.status) && - Objects.equals(uri, other.uri) && - Objects.equals(subresourceUris, other.subresourceUris) && - Objects.equals( - reasonConferenceEnded, - other.reasonConferenceEnded - ) && - Objects.equals( - callSidEndingConference, - other.callSidEndingConference - ) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(apiVersion, other.apiVersion) && + Objects.equals(callSidEndingConference, other.callSidEndingConference) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(reasonConferenceEnded, other.reasonConferenceEnded) && + Objects.equals(region, other.region) && + Objects.equals(sid, other.sid) && + Objects.equals(status, other.status) && + Objects.equals(subresourceUris, other.subresourceUris) && + Objects.equals(uri, other.uri) ); } @Override public int hashCode() { return Objects.hash( - accountSid, - dateCreated, - dateUpdated, - apiVersion, - friendlyName, - region, - sid, - status, - uri, - subresourceUris, - reasonConferenceEnded, - callSidEndingConference + accountSid, + apiVersion, + callSidEndingConference, + dateCreated, + dateUpdated, + friendlyName, + reasonConferenceEnded, + region, + sid, + status, + subresourceUris, + uri ); } - public enum UpdateStatus { - COMPLETED("completed"); - - private final String value; - - private UpdateStatus(final String value) { - this.value = value; - } - public String toString() { - return value; - } - - @JsonCreator - public static UpdateStatus forValue(final String value) { - return Promoter.enumFromString(value, UpdateStatus.values()); - } - } - - public enum ReasonConferenceEnded { - CONFERENCE_ENDED_VIA_API("conference-ended-via-api"), - PARTICIPANT_WITH_END_CONFERENCE_ON_EXIT_LEFT( - "participant-with-end-conference-on-exit-left" - ), - PARTICIPANT_WITH_END_CONFERENCE_ON_EXIT_KICKED( - "participant-with-end-conference-on-exit-kicked" - ), - LAST_PARTICIPANT_KICKED("last-participant-kicked"), - LAST_PARTICIPANT_LEFT("last-participant-left"); - - private final String value; - - private ReasonConferenceEnded(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static ReasonConferenceEnded forValue(final String value) { - return Promoter.enumFromString( - value, - ReasonConferenceEnded.values() - ); - } - } - - public enum Status { - INIT("init"), - IN_PROGRESS("in-progress"), - COMPLETED("completed"); - - private final String value; - - private Status(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static Status forValue(final String value) { - return Promoter.enumFromString(value, Status.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/api/v2010/account/ConferenceFetcher.java b/src/main/java/com/twilio/rest/api/v2010/account/ConferenceFetcher.java index 2617e1e25b..87382c635d 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/ConferenceFetcher.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/ConferenceFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.api.v2010.account; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,66 +26,49 @@ public class ConferenceFetcher extends Fetcher { - private String pathSid; - private String pathAccountSid; + private String pathaccountSid; + private String pathsid; - public ConferenceFetcher(final String pathSid) { - this.pathSid = pathSid; + public ConferenceFetcher(final String pathsid) { + this.pathsid = pathsid; } - public ConferenceFetcher( - final String pathAccountSid, - final String pathSid - ) { - this.pathAccountSid = pathAccountSid; - this.pathSid = pathSid; + public ConferenceFetcher(final String pathaccountSid, final String pathsid) { + this.pathaccountSid = pathaccountSid; + this.pathsid = pathsid; } + @Override public Conference fetch(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/Conferences/{Sid}.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/2010-04-01/Accounts/{AccountSid}/Conferences/{Sid}.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.API.toString(), - path + HttpMethod.GET, + Domains.API.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Conference fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Conference fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return Conference.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Conference.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/ConferenceReader.java b/src/main/java/com/twilio/rest/api/v2010/account/ConferenceReader.java index d7f4076e7a..e1f5e3ac3d 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/ConferenceReader.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/ConferenceReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -26,12 +27,12 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.time.LocalDate; -import java.time.format.DateTimeFormatter; public class ConferenceReader extends Reader { - private String pathAccountSid; + private String pathaccountSid; private LocalDate dateCreated; private LocalDate dateCreatedBefore; private LocalDate dateCreatedAfter; @@ -42,204 +43,177 @@ public class ConferenceReader extends Reader { private Conference.Status status; private Long pageSize; - public ConferenceReader() {} + public ConferenceReader() { + } - public ConferenceReader(final String pathAccountSid) { - this.pathAccountSid = pathAccountSid; + public ConferenceReader(final String pathaccountSid) { + this.pathaccountSid = pathaccountSid; } + public ConferenceReader setDateCreated(final LocalDate dateCreated) { this.dateCreated = dateCreated; return this; } - public ConferenceReader setDateCreatedBefore( - final LocalDate dateCreatedBefore - ) { + + public ConferenceReader setDateCreatedBefore(final LocalDate dateCreatedBefore) { this.dateCreatedBefore = dateCreatedBefore; return this; } - public ConferenceReader setDateCreatedAfter( - final LocalDate dateCreatedAfter - ) { + + public ConferenceReader setDateCreatedAfter(final LocalDate dateCreatedAfter) { this.dateCreatedAfter = dateCreatedAfter; return this; } + public ConferenceReader setDateUpdated(final LocalDate dateUpdated) { this.dateUpdated = dateUpdated; return this; } - public ConferenceReader setDateUpdatedBefore( - final LocalDate dateUpdatedBefore - ) { + + public ConferenceReader setDateUpdatedBefore(final LocalDate dateUpdatedBefore) { this.dateUpdatedBefore = dateUpdatedBefore; return this; } - public ConferenceReader setDateUpdatedAfter( - final LocalDate dateUpdatedAfter - ) { + + public ConferenceReader setDateUpdatedAfter(final LocalDate dateUpdatedAfter) { this.dateUpdatedAfter = dateUpdatedAfter; return this; } + public ConferenceReader setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + public ConferenceReader setStatus(final Conference.Status status) { this.status = status; return this; } + public ConferenceReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/2010-04-01/Accounts/{AccountSid}/Conferences.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.API.toString(), - path + HttpMethod.GET, + Domains.API.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Conference read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Conference read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "conferences", - response.getContent(), - Conference.class, - client.getObjectMapper() - ); + "conferences", + response.getContent(), + Conference.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.API.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.API.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (dateCreated != null) { - request.addQueryParam( - "DateCreated", - dateCreated.format( - DateTimeFormatter.ofPattern( - Request.QUERY_STRING_DATE_FORMAT - ) - ) - ); - } else if (dateCreatedAfter != null || dateCreatedBefore != null) { - request.addQueryDateRange( - "DateCreated", - dateCreatedAfter, - dateCreatedBefore - ); + Serializer.toString(request, "DateCreated", dateCreated, ParameterType.QUERY); + } + + + if (dateCreatedBefore != null) { + Serializer.toString(request, "DateCreated<", dateCreatedBefore, ParameterType.QUERY); + } + + + if (dateCreatedAfter != null) { + Serializer.toString(request, "DateCreated>", dateCreatedAfter, ParameterType.QUERY); } + + if (dateUpdated != null) { - request.addQueryParam( - "DateUpdated", - dateUpdated.format( - DateTimeFormatter.ofPattern( - Request.QUERY_STRING_DATE_FORMAT - ) - ) - ); - } else if (dateUpdatedAfter != null || dateUpdatedBefore != null) { - request.addQueryDateRange( - "DateUpdated", - dateUpdatedAfter, - dateUpdatedBefore - ); + Serializer.toString(request, "DateUpdated", dateUpdated, ParameterType.QUERY); + } + + + if (dateUpdatedBefore != null) { + Serializer.toString(request, "DateUpdated<", dateUpdatedBefore, ParameterType.QUERY); + } + + + if (dateUpdatedAfter != null) { + Serializer.toString(request, "DateUpdated>", dateUpdatedAfter, ParameterType.QUERY); } + + if (friendlyName != null) { - request.addQueryParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.QUERY); } + + if (status != null) { - request.addQueryParam("Status", status.toString()); + Serializer.toString(request, "Status", status, ParameterType.QUERY); } + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/ConferenceUpdater.java b/src/main/java/com/twilio/rest/api/v2010/account/ConferenceUpdater.java index 8299735342..6e23ba2637 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/ConferenceUpdater.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/ConferenceUpdater.java @@ -16,7 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; -import com.twilio.converter.Promoter; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,106 +26,96 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.net.URI; public class ConferenceUpdater extends Updater { - - private String pathSid; - private String pathAccountSid; + private String pathaccountSid; + private String pathsid; private Conference.UpdateStatus status; private URI announceUrl; private HttpMethod announceMethod; - public ConferenceUpdater(final String pathSid) { - this.pathSid = pathSid; + public ConferenceUpdater(final String pathsid) { + this.pathsid = pathsid; } - public ConferenceUpdater( - final String pathAccountSid, - final String pathSid - ) { - this.pathAccountSid = pathAccountSid; - this.pathSid = pathSid; + public ConferenceUpdater(final String pathaccountSid, final String pathsid) { + this.pathaccountSid = pathaccountSid; + this.pathsid = pathsid; } + public ConferenceUpdater setStatus(final Conference.UpdateStatus status) { this.status = status; return this; } + public ConferenceUpdater setAnnounceUrl(final URI announceUrl) { this.announceUrl = announceUrl; return this; } - public ConferenceUpdater setAnnounceUrl(final String announceUrl) { - return setAnnounceUrl(Promoter.uriFromString(announceUrl)); - } - public ConferenceUpdater setAnnounceMethod( - final HttpMethod announceMethod - ) { + public ConferenceUpdater setAnnounceMethod(final HttpMethod announceMethod) { this.announceMethod = announceMethod; return this; } + @Override public Conference update(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/Conferences/{Sid}.json"; - - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + + String path = "/2010-04-01/Accounts/{AccountSid}/Conferences/{Sid}.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.API.toString(), - path + HttpMethod.POST, + Domains.API.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Conference update failed: Unable to connect to server" - ); + throw new ApiConnectionException("Conference update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Conference.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Conference.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (status != null) { - request.addPostParam("Status", status.toString()); + Serializer.toString(request, "Status", status, ParameterType.URLENCODED); } + + if (announceUrl != null) { - request.addPostParam("AnnounceUrl", announceUrl.toString()); + Serializer.toString(request, "AnnounceUrl", announceUrl, ParameterType.URLENCODED); } + + if (announceMethod != null) { - request.addPostParam("AnnounceMethod", announceMethod.toString()); + Serializer.toString(request, "AnnounceMethod", announceMethod, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/ConnectApp.java b/src/main/java/com/twilio/rest/api/v2010/account/ConnectApp.java index 64e5e6198c..2c7974f8b9 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/ConnectApp.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/ConnectApp.java @@ -18,6 +18,7 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; @@ -25,72 +26,205 @@ import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.http.HttpMethod; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.util.List; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class ConnectApp extends Resource { - private static final long serialVersionUID = 203118827948403L; - public static ConnectAppDeleter deleter(final String pathSid) { - return new ConnectAppDeleter(pathSid); + public static ConnectAppDeleter deleter(final String pathsid) { + return new ConnectAppDeleter( + pathsid + ); } - public static ConnectAppDeleter deleter( - final String pathAccountSid, - final String pathSid - ) { - return new ConnectAppDeleter(pathAccountSid, pathSid); + + public static ConnectAppDeleter deleter(final String pathaccountSid, final String pathsid) { + return new ConnectAppDeleter( + pathaccountSid, pathsid + ); } - public static ConnectAppFetcher fetcher(final String pathSid) { - return new ConnectAppFetcher(pathSid); + + public static ConnectAppFetcher fetcher(final String pathsid) { + return new ConnectAppFetcher( + pathsid + ); } - public static ConnectAppFetcher fetcher( - final String pathAccountSid, - final String pathSid - ) { - return new ConnectAppFetcher(pathAccountSid, pathSid); + + public static ConnectAppFetcher fetcher(final String pathaccountSid, final String pathsid) { + return new ConnectAppFetcher( + pathaccountSid, pathsid + ); } + public static ConnectAppReader reader() { - return new ConnectAppReader(); + return new ConnectAppReader( + + ); } - public static ConnectAppReader reader(final String pathAccountSid) { - return new ConnectAppReader(pathAccountSid); + + public static ConnectAppReader reader(final String pathaccountSid) { + return new ConnectAppReader( + pathaccountSid + ); } - public static ConnectAppUpdater updater(final String pathSid) { - return new ConnectAppUpdater(pathSid); + + public static ConnectAppUpdater updater(final String pathsid) { + return new ConnectAppUpdater( + pathsid + ); } - public static ConnectAppUpdater updater( - final String pathAccountSid, - final String pathSid - ) { - return new ConnectAppUpdater(pathAccountSid, pathSid); + + public static ConnectAppUpdater updater(final String pathaccountSid, final String pathsid) { + return new ConnectAppUpdater( + pathaccountSid, pathsid + ); + } + + + public enum ConnectAppConnectAppConnectAppConnectAppConnectAppPermission { + GET_ALL("get-all"), + POST_ALL("post-all"); + + private final String value; + + private ConnectAppConnectAppConnectAppConnectAppConnectAppPermission(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static ConnectAppConnectAppConnectAppConnectAppConnectAppPermission forValue(final String value) { + return Promoter.enumFromString(value, ConnectAppConnectAppConnectAppConnectAppConnectAppPermission.values()); + } + } + + public enum ConnectAppConnectAppConnectAppPermission { + GET_ALL("get-all"), + POST_ALL("post-all"); + + private final String value; + + private ConnectAppConnectAppConnectAppPermission(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static ConnectAppConnectAppConnectAppPermission forValue(final String value) { + return Promoter.enumFromString(value, ConnectAppConnectAppConnectAppPermission.values()); + } + } + + public enum ConnectAppPermission { + GET_ALL("get-all"), + POST_ALL("post-all"); + + private final String value; + + private ConnectAppPermission(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static ConnectAppPermission forValue(final String value) { + return Promoter.enumFromString(value, ConnectAppPermission.values()); + } + } + + public enum ConnectAppConnectAppConnectAppConnectAppPermission { + GET_ALL("get-all"), + POST_ALL("post-all"); + + private final String value; + + private ConnectAppConnectAppConnectAppConnectAppPermission(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static ConnectAppConnectAppConnectAppConnectAppPermission forValue(final String value) { + return Promoter.enumFromString(value, ConnectAppConnectAppConnectAppConnectAppPermission.values()); + } + } + + public enum Permission { + GET_ALL("get-all"), + POST_ALL("post-all"); + + private final String value; + + private Permission(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static Permission forValue(final String value) { + return Promoter.enumFromString(value, Permission.values()); + } + } + + public enum ConnectAppConnectAppPermission { + GET_ALL("get-all"), + POST_ALL("post-all"); + + private final String value; + + private ConnectAppConnectAppPermission(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static ConnectAppConnectAppPermission forValue(final String value) { + return Promoter.enumFromString(value, ConnectAppConnectAppPermission.values()); + } } + /** * Converts a JSON String into a ConnectApp object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return ConnectApp object represented by the provided JSON */ - public static ConnectApp fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static ConnectApp fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, ConnectApp.class); @@ -105,14 +239,11 @@ public static ConnectApp fromJson( * Converts a JSON InputStream into a ConnectApp object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return ConnectApp object represented by the provided JSON */ - public static ConnectApp fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static ConnectApp fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, ConnectApp.class); @@ -123,37 +254,55 @@ public static ConnectApp fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; + @Getter private final URI authorizeRedirectUrl; + @Getter private final String companyName; + @Getter private final HttpMethod deauthorizeCallbackMethod; + @Getter private final URI deauthorizeCallbackUrl; + @Getter private final String description; + @Getter private final String friendlyName; + @Getter private final URI homepageUrl; - private final List permissions; + @Getter + private final List permissions; + @Getter private final String sid; + @Getter private final String uri; @JsonCreator private ConnectApp( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("authorize_redirect_url") final URI authorizeRedirectUrl, - @JsonProperty("company_name") final String companyName, - @JsonProperty( - "deauthorize_callback_method" - ) final HttpMethod deauthorizeCallbackMethod, - @JsonProperty( - "deauthorize_callback_url" - ) final URI deauthorizeCallbackUrl, - @JsonProperty("description") final String description, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("homepage_url") final URI homepageUrl, - @JsonProperty("permissions") final List< - ConnectApp.Permission - > permissions, - @JsonProperty("sid") final String sid, - @JsonProperty("uri") final String uri + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("authorize_redirect_url") final URI authorizeRedirectUrl, + @JsonProperty("company_name") final String companyName, + @JsonProperty("deauthorize_callback_method") final HttpMethod deauthorizeCallbackMethod, + @JsonProperty("deauthorize_callback_url") final URI deauthorizeCallbackUrl, + @JsonProperty("description") final String description, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("homepage_url") final URI homepageUrl, + @JsonProperty("permissions") final List permissions, + @JsonProperty("sid") final String sid, + @JsonProperty("uri") final String uri ) { this.accountSid = accountSid; this.authorizeRedirectUrl = authorizeRedirectUrl; @@ -168,50 +317,6 @@ private ConnectApp( this.uri = uri; } - public final String getAccountSid() { - return this.accountSid; - } - - public final URI getAuthorizeRedirectUrl() { - return this.authorizeRedirectUrl; - } - - public final String getCompanyName() { - return this.companyName; - } - - public final HttpMethod getDeauthorizeCallbackMethod() { - return this.deauthorizeCallbackMethod; - } - - public final URI getDeauthorizeCallbackUrl() { - return this.deauthorizeCallbackUrl; - } - - public final String getDescription() { - return this.description; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final URI getHomepageUrl() { - return this.homepageUrl; - } - - public final List getPermissions() { - return this.permissions; - } - - public final String getSid() { - return this.sid; - } - - public final String getUri() { - return this.uri; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -223,62 +328,38 @@ public boolean equals(final Object o) { } ConnectApp other = (ConnectApp) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(authorizeRedirectUrl, other.authorizeRedirectUrl) && - Objects.equals(companyName, other.companyName) && - Objects.equals( - deauthorizeCallbackMethod, - other.deauthorizeCallbackMethod - ) && - Objects.equals( - deauthorizeCallbackUrl, - other.deauthorizeCallbackUrl - ) && - Objects.equals(description, other.description) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(homepageUrl, other.homepageUrl) && - Objects.equals(permissions, other.permissions) && - Objects.equals(sid, other.sid) && - Objects.equals(uri, other.uri) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(authorizeRedirectUrl, other.authorizeRedirectUrl) && + Objects.equals(companyName, other.companyName) && + Objects.equals(deauthorizeCallbackMethod, other.deauthorizeCallbackMethod) && + Objects.equals(deauthorizeCallbackUrl, other.deauthorizeCallbackUrl) && + Objects.equals(description, other.description) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(homepageUrl, other.homepageUrl) && + Objects.equals(permissions, other.permissions) && + Objects.equals(sid, other.sid) && + Objects.equals(uri, other.uri) ); } @Override public int hashCode() { return Objects.hash( - accountSid, - authorizeRedirectUrl, - companyName, - deauthorizeCallbackMethod, - deauthorizeCallbackUrl, - description, - friendlyName, - homepageUrl, - permissions, - sid, - uri + accountSid, + authorizeRedirectUrl, + companyName, + deauthorizeCallbackMethod, + deauthorizeCallbackUrl, + description, + friendlyName, + homepageUrl, + permissions, + sid, + uri ); } - public enum Permission { - GET_ALL("get-all"), - POST_ALL("post-all"); - - private final String value; - - private Permission(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - @JsonCreator - public static Permission forValue(final String value) { - return Promoter.enumFromString(value, Permission.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/api/v2010/account/ConnectAppDeleter.java b/src/main/java/com/twilio/rest/api/v2010/account/ConnectAppDeleter.java index cddb8c5374..227d6aab02 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/ConnectAppDeleter.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/ConnectAppDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.api.v2010.account; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,59 +26,46 @@ public class ConnectAppDeleter extends Deleter { - private String pathSid; - private String pathAccountSid; + private String pathaccountSid; + private String pathsid; - public ConnectAppDeleter(final String pathSid) { - this.pathSid = pathSid; + public ConnectAppDeleter(final String pathsid) { + this.pathsid = pathsid; } - public ConnectAppDeleter( - final String pathAccountSid, - final String pathSid - ) { - this.pathAccountSid = pathAccountSid; - this.pathSid = pathSid; + public ConnectAppDeleter(final String pathaccountSid, final String pathsid) { + this.pathaccountSid = pathaccountSid; + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/ConnectApps/{Sid}.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/2010-04-01/Accounts/{AccountSid}/ConnectApps/{Sid}.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.API.toString(), - path + HttpMethod.DELETE, + Domains.API.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "ConnectApp delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("ConnectApp delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/ConnectAppFetcher.java b/src/main/java/com/twilio/rest/api/v2010/account/ConnectAppFetcher.java index c504e4f7ff..a18332fd0a 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/ConnectAppFetcher.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/ConnectAppFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.api.v2010.account; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,66 +26,49 @@ public class ConnectAppFetcher extends Fetcher { - private String pathSid; - private String pathAccountSid; + private String pathaccountSid; + private String pathsid; - public ConnectAppFetcher(final String pathSid) { - this.pathSid = pathSid; + public ConnectAppFetcher(final String pathsid) { + this.pathsid = pathsid; } - public ConnectAppFetcher( - final String pathAccountSid, - final String pathSid - ) { - this.pathAccountSid = pathAccountSid; - this.pathSid = pathSid; + public ConnectAppFetcher(final String pathaccountSid, final String pathsid) { + this.pathaccountSid = pathaccountSid; + this.pathsid = pathsid; } + @Override public ConnectApp fetch(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/ConnectApps/{Sid}.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/2010-04-01/Accounts/{AccountSid}/ConnectApps/{Sid}.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.API.toString(), - path + HttpMethod.GET, + Domains.API.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "ConnectApp fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("ConnectApp fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return ConnectApp.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return ConnectApp.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/ConnectAppReader.java b/src/main/java/com/twilio/rest/api/v2010/account/ConnectAppReader.java index 5853760eed..177eb91c92 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/ConnectAppReader.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/ConnectAppReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,121 +30,92 @@ public class ConnectAppReader extends Reader { - private String pathAccountSid; + private String pathaccountSid; private Long pageSize; - public ConnectAppReader() {} + public ConnectAppReader() { + } - public ConnectAppReader(final String pathAccountSid) { - this.pathAccountSid = pathAccountSid; + public ConnectAppReader(final String pathaccountSid) { + this.pathaccountSid = pathaccountSid; } + public ConnectAppReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/2010-04-01/Accounts/{AccountSid}/ConnectApps.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.API.toString(), - path + HttpMethod.GET, + Domains.API.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "ConnectApp read failed: Unable to connect to server" - ); + throw new ApiConnectionException("ConnectApp read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "connect_apps", - response.getContent(), - ConnectApp.class, - client.getObjectMapper() - ); + "connect_apps", + response.getContent(), + ConnectApp.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.API.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.API.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/ConnectAppUpdater.java b/src/main/java/com/twilio/rest/api/v2010/account/ConnectAppUpdater.java index fde80e935d..c9fc4a2367 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/ConnectAppUpdater.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/ConnectAppUpdater.java @@ -16,7 +16,9 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; import com.twilio.converter.Promoter; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,13 +27,13 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.net.URI; import java.util.List; public class ConnectAppUpdater extends Updater { - - private String pathSid; - private String pathAccountSid; + private String pathaccountSid; + private String pathsid; private URI authorizeRedirectUrl; private String companyName; private HttpMethod deauthorizeCallbackMethod; @@ -41,175 +43,145 @@ public class ConnectAppUpdater extends Updater { private URI homepageUrl; private List permissions; - public ConnectAppUpdater(final String pathSid) { - this.pathSid = pathSid; + public ConnectAppUpdater(final String pathsid) { + this.pathsid = pathsid; } - public ConnectAppUpdater( - final String pathAccountSid, - final String pathSid - ) { - this.pathAccountSid = pathAccountSid; - this.pathSid = pathSid; + public ConnectAppUpdater(final String pathaccountSid, final String pathsid) { + this.pathaccountSid = pathaccountSid; + this.pathsid = pathsid; } - public ConnectAppUpdater setAuthorizeRedirectUrl( - final URI authorizeRedirectUrl - ) { + + public ConnectAppUpdater setAuthorizeRedirectUrl(final URI authorizeRedirectUrl) { this.authorizeRedirectUrl = authorizeRedirectUrl; return this; } - public ConnectAppUpdater setAuthorizeRedirectUrl( - final String authorizeRedirectUrl - ) { - return setAuthorizeRedirectUrl( - Promoter.uriFromString(authorizeRedirectUrl) - ); - } public ConnectAppUpdater setCompanyName(final String companyName) { this.companyName = companyName; return this; } - public ConnectAppUpdater setDeauthorizeCallbackMethod( - final HttpMethod deauthorizeCallbackMethod - ) { + + public ConnectAppUpdater setDeauthorizeCallbackMethod(final HttpMethod deauthorizeCallbackMethod) { this.deauthorizeCallbackMethod = deauthorizeCallbackMethod; return this; } - public ConnectAppUpdater setDeauthorizeCallbackUrl( - final URI deauthorizeCallbackUrl - ) { + + public ConnectAppUpdater setDeauthorizeCallbackUrl(final URI deauthorizeCallbackUrl) { this.deauthorizeCallbackUrl = deauthorizeCallbackUrl; return this; } - public ConnectAppUpdater setDeauthorizeCallbackUrl( - final String deauthorizeCallbackUrl - ) { - return setDeauthorizeCallbackUrl( - Promoter.uriFromString(deauthorizeCallbackUrl) - ); - } public ConnectAppUpdater setDescription(final String description) { this.description = description; return this; } + public ConnectAppUpdater setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + public ConnectAppUpdater setHomepageUrl(final URI homepageUrl) { this.homepageUrl = homepageUrl; return this; } - public ConnectAppUpdater setHomepageUrl(final String homepageUrl) { - return setHomepageUrl(Promoter.uriFromString(homepageUrl)); - } - public ConnectAppUpdater setPermissions( - final List permissions - ) { + public ConnectAppUpdater setPermissions(final List permissions) { this.permissions = permissions; return this; } - public ConnectAppUpdater setPermissions( - final ConnectApp.Permission permissions - ) { + public ConnectAppUpdater setPermissions(final ConnectApp.Permission permissions) { return setPermissions(Promoter.listOfOne(permissions)); } @Override public ConnectApp update(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/ConnectApps/{Sid}.json"; - - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + + String path = "/2010-04-01/Accounts/{AccountSid}/ConnectApps/{Sid}.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.API.toString(), - path + HttpMethod.POST, + Domains.API.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "ConnectApp update failed: Unable to connect to server" - ); + throw new ApiConnectionException("ConnectApp update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return ConnectApp.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return ConnectApp.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (authorizeRedirectUrl != null) { - request.addPostParam( - "AuthorizeRedirectUrl", - authorizeRedirectUrl.toString() - ); + Serializer.toString(request, "AuthorizeRedirectUrl", authorizeRedirectUrl, ParameterType.URLENCODED); } + + if (companyName != null) { - request.addPostParam("CompanyName", companyName); + Serializer.toString(request, "CompanyName", companyName, ParameterType.URLENCODED); } + + if (deauthorizeCallbackMethod != null) { - request.addPostParam( - "DeauthorizeCallbackMethod", - deauthorizeCallbackMethod.toString() - ); + Serializer.toString(request, "DeauthorizeCallbackMethod", deauthorizeCallbackMethod, ParameterType.URLENCODED); } + + if (deauthorizeCallbackUrl != null) { - request.addPostParam( - "DeauthorizeCallbackUrl", - deauthorizeCallbackUrl.toString() - ); + Serializer.toString(request, "DeauthorizeCallbackUrl", deauthorizeCallbackUrl, ParameterType.URLENCODED); } + + if (description != null) { - request.addPostParam("Description", description); + Serializer.toString(request, "Description", description, ParameterType.URLENCODED); } + + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + if (homepageUrl != null) { - request.addPostParam("HomepageUrl", homepageUrl.toString()); + Serializer.toString(request, "HomepageUrl", homepageUrl, ParameterType.URLENCODED); } + + if (permissions != null) { - for (ConnectApp.Permission prop : permissions) { - request.addPostParam("Permissions", prop.toString()); + for (ConnectApp.Permission param : permissions) { + Serializer.toString(request, "Permissions", param, ParameterType.URLENCODED); } } + } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/IncomingPhoneNumber.java b/src/main/java/com/twilio/rest/api/v2010/account/IncomingPhoneNumber.java index 6c202374e5..98afdc6122 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/IncomingPhoneNumber.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/IncomingPhoneNumber.java @@ -18,107 +18,209 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.http.HttpMethod; import com.twilio.type.PhoneNumberCapabilities; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class IncomingPhoneNumber extends Resource { - private static final long serialVersionUID = 82830627507260L; - public static IncomingPhoneNumberCreator creator( - final com.twilio.type.PhoneNumber phoneNumber - ) { - return new IncomingPhoneNumberCreator(phoneNumber); + public static IncomingPhoneNumberCreator creator(final com.twilio.type.PhoneNumber phoneNumber) { + return new IncomingPhoneNumberCreator( + phoneNumber + ); } - public static IncomingPhoneNumberCreator creator( - final String pathAccountSid, - final com.twilio.type.PhoneNumber phoneNumber - ) { - return new IncomingPhoneNumberCreator(pathAccountSid, phoneNumber); + + public static IncomingPhoneNumberCreator creator(final String pathaccountSid, final com.twilio.type.PhoneNumber phoneNumber) { + return new IncomingPhoneNumberCreator( + pathaccountSid, phoneNumber + ); } + public static IncomingPhoneNumberCreator creator(final String areaCode) { - return new IncomingPhoneNumberCreator(areaCode); + return new IncomingPhoneNumberCreator( + areaCode + ); } - public static IncomingPhoneNumberCreator creator( - final String pathAccountSid, - final String areaCode - ) { - return new IncomingPhoneNumberCreator(pathAccountSid, areaCode); + + public static IncomingPhoneNumberCreator creator(final String pathaccountSid, final String areaCode) { + return new IncomingPhoneNumberCreator( + pathaccountSid, areaCode + ); } - public static IncomingPhoneNumberDeleter deleter(final String pathSid) { - return new IncomingPhoneNumberDeleter(pathSid); + + public static IncomingPhoneNumberDeleter deleter(final String pathsid) { + return new IncomingPhoneNumberDeleter( + pathsid + ); } - public static IncomingPhoneNumberDeleter deleter( - final String pathAccountSid, - final String pathSid - ) { - return new IncomingPhoneNumberDeleter(pathAccountSid, pathSid); + + public static IncomingPhoneNumberDeleter deleter(final String pathaccountSid, final String pathsid) { + return new IncomingPhoneNumberDeleter( + pathaccountSid, pathsid + ); } - public static IncomingPhoneNumberFetcher fetcher(final String pathSid) { - return new IncomingPhoneNumberFetcher(pathSid); + + public static IncomingPhoneNumberFetcher fetcher(final String pathsid) { + return new IncomingPhoneNumberFetcher( + pathsid + ); } - public static IncomingPhoneNumberFetcher fetcher( - final String pathAccountSid, - final String pathSid - ) { - return new IncomingPhoneNumberFetcher(pathAccountSid, pathSid); + + public static IncomingPhoneNumberFetcher fetcher(final String pathaccountSid, final String pathsid) { + return new IncomingPhoneNumberFetcher( + pathaccountSid, pathsid + ); } + public static IncomingPhoneNumberReader reader() { - return new IncomingPhoneNumberReader(); + return new IncomingPhoneNumberReader( + + ); } - public static IncomingPhoneNumberReader reader( - final String pathAccountSid - ) { - return new IncomingPhoneNumberReader(pathAccountSid); + + public static IncomingPhoneNumberReader reader(final String pathaccountSid) { + return new IncomingPhoneNumberReader( + pathaccountSid + ); } - public static IncomingPhoneNumberUpdater updater(final String pathSid) { - return new IncomingPhoneNumberUpdater(pathSid); + + public static IncomingPhoneNumberUpdater updater(final String pathsid) { + return new IncomingPhoneNumberUpdater( + pathsid + ); } - public static IncomingPhoneNumberUpdater updater( - final String pathAccountSid, - final String pathSid - ) { - return new IncomingPhoneNumberUpdater(pathAccountSid, pathSid); + + public static IncomingPhoneNumberUpdater updater(final String pathaccountSid, final String pathsid) { + return new IncomingPhoneNumberUpdater( + pathaccountSid, pathsid + ); + } + + + public enum EmergencyAddressStatus { + REGISTERED("registered"), + UNREGISTERED("unregistered"), + PENDING_REGISTRATION("pending-registration"), + REGISTRATION_FAILURE("registration-failure"), + PENDING_UNREGISTRATION("pending-unregistration"), + UNREGISTRATION_FAILURE("unregistration-failure"); + + private final String value; + + private EmergencyAddressStatus(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static EmergencyAddressStatus forValue(final String value) { + return Promoter.enumFromString(value, EmergencyAddressStatus.values()); + } + } + + public enum VoiceReceiveMode { + VOICE("voice"), + FAX("fax"); + + private final String value; + + private VoiceReceiveMode(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static VoiceReceiveMode forValue(final String value) { + return Promoter.enumFromString(value, VoiceReceiveMode.values()); + } + } + + public enum EmergencyStatus { + ACTIVE("Active"), + INACTIVE("Inactive"); + + private final String value; + + private EmergencyStatus(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static EmergencyStatus forValue(final String value) { + return Promoter.enumFromString(value, EmergencyStatus.values()); + } + } + + public enum AddressRequirement { + NONE("none"), + ANY("any"), + LOCAL("local"), + FOREIGN("foreign"); + + private final String value; + + private AddressRequirement(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static AddressRequirement forValue(final String value) { + return Promoter.enumFromString(value, AddressRequirement.values()); + } } + /** * Converts a JSON String into a IncomingPhoneNumber object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return IncomingPhoneNumber object represented by the provided JSON */ - public static IncomingPhoneNumber fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static IncomingPhoneNumber fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, IncomingPhoneNumber.class); @@ -133,14 +235,11 @@ public static IncomingPhoneNumber fromJson( * Converts a JSON InputStream into a IncomingPhoneNumber object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return IncomingPhoneNumber object represented by the provided JSON */ - public static IncomingPhoneNumber fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static IncomingPhoneNumber fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, IncomingPhoneNumber.class); @@ -151,266 +250,161 @@ public static IncomingPhoneNumber fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String addressSid; + @Getter private final IncomingPhoneNumber.AddressRequirement addressRequirements; + @Getter + private final String addressSid; + @Getter private final String apiVersion; + @Getter private final Boolean beta; + @Getter + private final String bundleSid; + @Getter private final PhoneNumberCapabilities capabilities; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; + @Getter + private final String emergencyAddressSid; + @Getter + private final IncomingPhoneNumber.EmergencyAddressStatus emergencyAddressStatus; + @Getter + private final IncomingPhoneNumber.EmergencyStatus emergencyStatus; + @Getter private final String friendlyName; + @Getter private final String identitySid; - private final com.twilio.type.PhoneNumber phoneNumber; + @Getter private final String origin; + @Getter + private final com.twilio.type.PhoneNumber phoneNumber; + @Getter private final String sid; + @Getter private final String smsApplicationSid; + @Getter private final HttpMethod smsFallbackMethod; + @Getter private final URI smsFallbackUrl; + @Getter private final HttpMethod smsMethod; + @Getter private final URI smsUrl; + @Getter + private final String status; + @Getter private final URI statusCallback; + @Getter private final HttpMethod statusCallbackMethod; + @Getter private final String trunkSid; + @Getter private final String uri; - private final IncomingPhoneNumber.VoiceReceiveMode voiceReceiveMode; + @Getter private final String voiceApplicationSid; + @Getter private final Boolean voiceCallerIdLookup; + @Getter private final HttpMethod voiceFallbackMethod; + @Getter private final URI voiceFallbackUrl; + @Getter private final HttpMethod voiceMethod; + @Getter + private final IncomingPhoneNumber.VoiceReceiveMode voiceReceiveMode; + @Getter private final URI voiceUrl; - private final IncomingPhoneNumber.EmergencyStatus emergencyStatus; - private final String emergencyAddressSid; - private final IncomingPhoneNumber.EmergencyAddressStatus emergencyAddressStatus; - private final String bundleSid; - private final String status; @JsonCreator private IncomingPhoneNumber( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("address_sid") final String addressSid, - @JsonProperty( - "address_requirements" - ) final IncomingPhoneNumber.AddressRequirement addressRequirements, - @JsonProperty("api_version") final String apiVersion, - @JsonProperty("beta") final Boolean beta, - @JsonProperty( - "capabilities" - ) final PhoneNumberCapabilities capabilities, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("identity_sid") final String identitySid, - @JsonProperty( - "phone_number" - ) final com.twilio.type.PhoneNumber phoneNumber, - @JsonProperty("origin") final String origin, - @JsonProperty("sid") final String sid, - @JsonProperty("sms_application_sid") final String smsApplicationSid, - @JsonProperty("sms_fallback_method") final HttpMethod smsFallbackMethod, - @JsonProperty("sms_fallback_url") final URI smsFallbackUrl, - @JsonProperty("sms_method") final HttpMethod smsMethod, - @JsonProperty("sms_url") final URI smsUrl, - @JsonProperty("status_callback") final URI statusCallback, - @JsonProperty( - "status_callback_method" - ) final HttpMethod statusCallbackMethod, - @JsonProperty("trunk_sid") final String trunkSid, - @JsonProperty("uri") final String uri, - @JsonProperty( - "voice_receive_mode" - ) final IncomingPhoneNumber.VoiceReceiveMode voiceReceiveMode, - @JsonProperty("voice_application_sid") final String voiceApplicationSid, - @JsonProperty( - "voice_caller_id_lookup" - ) final Boolean voiceCallerIdLookup, - @JsonProperty( - "voice_fallback_method" - ) final HttpMethod voiceFallbackMethod, - @JsonProperty("voice_fallback_url") final URI voiceFallbackUrl, - @JsonProperty("voice_method") final HttpMethod voiceMethod, - @JsonProperty("voice_url") final URI voiceUrl, - @JsonProperty( - "emergency_status" - ) final IncomingPhoneNumber.EmergencyStatus emergencyStatus, - @JsonProperty("emergency_address_sid") final String emergencyAddressSid, - @JsonProperty( - "emergency_address_status" - ) final IncomingPhoneNumber.EmergencyAddressStatus emergencyAddressStatus, - @JsonProperty("bundle_sid") final String bundleSid, - @JsonProperty("status") final String status + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("address_requirements") final IncomingPhoneNumber.AddressRequirement addressRequirements, + @JsonProperty("address_sid") final String addressSid, + @JsonProperty("api_version") final String apiVersion, + @JsonProperty("beta") final Boolean beta, + @JsonProperty("bundle_sid") final String bundleSid, + @JsonProperty("capabilities") final PhoneNumberCapabilities capabilities, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.RFC2822Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.RFC2822Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("emergency_address_sid") final String emergencyAddressSid, + @JsonProperty("emergency_address_status") final IncomingPhoneNumber.EmergencyAddressStatus emergencyAddressStatus, + @JsonProperty("emergency_status") final IncomingPhoneNumber.EmergencyStatus emergencyStatus, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("identity_sid") final String identitySid, + @JsonProperty("origin") final String origin, + @JsonProperty("phone_number") final com.twilio.type.PhoneNumber phoneNumber, + @JsonProperty("sid") final String sid, + @JsonProperty("sms_application_sid") final String smsApplicationSid, + @JsonProperty("sms_fallback_method") final HttpMethod smsFallbackMethod, + @JsonProperty("sms_fallback_url") final URI smsFallbackUrl, + @JsonProperty("sms_method") final HttpMethod smsMethod, + @JsonProperty("sms_url") final URI smsUrl, + @JsonProperty("status") final String status, + @JsonProperty("status_callback") final URI statusCallback, + @JsonProperty("status_callback_method") final HttpMethod statusCallbackMethod, + @JsonProperty("trunk_sid") final String trunkSid, + @JsonProperty("uri") final String uri, + @JsonProperty("voice_application_sid") final String voiceApplicationSid, + @JsonProperty("voice_caller_id_lookup") final Boolean voiceCallerIdLookup, + @JsonProperty("voice_fallback_method") final HttpMethod voiceFallbackMethod, + @JsonProperty("voice_fallback_url") final URI voiceFallbackUrl, + @JsonProperty("voice_method") final HttpMethod voiceMethod, + @JsonProperty("voice_receive_mode") final IncomingPhoneNumber.VoiceReceiveMode voiceReceiveMode, + @JsonProperty("voice_url") final URI voiceUrl ) { this.accountSid = accountSid; - this.addressSid = addressSid; this.addressRequirements = addressRequirements; + this.addressSid = addressSid; this.apiVersion = apiVersion; this.beta = beta; + this.bundleSid = bundleSid; this.capabilities = capabilities; - this.dateCreated = DateConverter.rfc2822DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.rfc2822DateTimeFromString(dateUpdated); + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; + this.emergencyAddressSid = emergencyAddressSid; + this.emergencyAddressStatus = emergencyAddressStatus; + this.emergencyStatus = emergencyStatus; this.friendlyName = friendlyName; this.identitySid = identitySid; - this.phoneNumber = phoneNumber; this.origin = origin; + this.phoneNumber = phoneNumber; this.sid = sid; this.smsApplicationSid = smsApplicationSid; this.smsFallbackMethod = smsFallbackMethod; this.smsFallbackUrl = smsFallbackUrl; this.smsMethod = smsMethod; this.smsUrl = smsUrl; + this.status = status; this.statusCallback = statusCallback; this.statusCallbackMethod = statusCallbackMethod; this.trunkSid = trunkSid; this.uri = uri; - this.voiceReceiveMode = voiceReceiveMode; this.voiceApplicationSid = voiceApplicationSid; this.voiceCallerIdLookup = voiceCallerIdLookup; this.voiceFallbackMethod = voiceFallbackMethod; this.voiceFallbackUrl = voiceFallbackUrl; this.voiceMethod = voiceMethod; + this.voiceReceiveMode = voiceReceiveMode; this.voiceUrl = voiceUrl; - this.emergencyStatus = emergencyStatus; - this.emergencyAddressSid = emergencyAddressSid; - this.emergencyAddressStatus = emergencyAddressStatus; - this.bundleSid = bundleSid; - this.status = status; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getAddressSid() { - return this.addressSid; - } - - public final IncomingPhoneNumber.AddressRequirement getAddressRequirements() { - return this.addressRequirements; - } - - public final String getApiVersion() { - return this.apiVersion; - } - - public final Boolean getBeta() { - return this.beta; - } - - public final PhoneNumberCapabilities getCapabilities() { - return this.capabilities; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final String getIdentitySid() { - return this.identitySid; - } - - public final com.twilio.type.PhoneNumber getPhoneNumber() { - return this.phoneNumber; - } - - public final String getOrigin() { - return this.origin; - } - - public final String getSid() { - return this.sid; - } - - public final String getSmsApplicationSid() { - return this.smsApplicationSid; - } - - public final HttpMethod getSmsFallbackMethod() { - return this.smsFallbackMethod; - } - - public final URI getSmsFallbackUrl() { - return this.smsFallbackUrl; - } - - public final HttpMethod getSmsMethod() { - return this.smsMethod; - } - - public final URI getSmsUrl() { - return this.smsUrl; - } - - public final URI getStatusCallback() { - return this.statusCallback; - } - - public final HttpMethod getStatusCallbackMethod() { - return this.statusCallbackMethod; - } - - public final String getTrunkSid() { - return this.trunkSid; - } - - public final String getUri() { - return this.uri; - } - - public final IncomingPhoneNumber.VoiceReceiveMode getVoiceReceiveMode() { - return this.voiceReceiveMode; - } - - public final String getVoiceApplicationSid() { - return this.voiceApplicationSid; - } - - public final Boolean getVoiceCallerIdLookup() { - return this.voiceCallerIdLookup; - } - - public final HttpMethod getVoiceFallbackMethod() { - return this.voiceFallbackMethod; - } - - public final URI getVoiceFallbackUrl() { - return this.voiceFallbackUrl; - } - - public final HttpMethod getVoiceMethod() { - return this.voiceMethod; - } - - public final URI getVoiceUrl() { - return this.voiceUrl; - } - - public final IncomingPhoneNumber.EmergencyStatus getEmergencyStatus() { - return this.emergencyStatus; - } - - public final String getEmergencyAddressSid() { - return this.emergencyAddressSid; - } - - public final IncomingPhoneNumber.EmergencyAddressStatus getEmergencyAddressStatus() { - return this.emergencyAddressStatus; - } - - public final String getBundleSid() { - return this.bundleSid; - } - - public final String getStatus() { - return this.status; } @Override @@ -424,174 +418,84 @@ public boolean equals(final Object o) { } IncomingPhoneNumber other = (IncomingPhoneNumber) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(addressSid, other.addressSid) && - Objects.equals(addressRequirements, other.addressRequirements) && - Objects.equals(apiVersion, other.apiVersion) && - Objects.equals(beta, other.beta) && - Objects.equals(capabilities, other.capabilities) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(identitySid, other.identitySid) && - Objects.equals(phoneNumber, other.phoneNumber) && - Objects.equals(origin, other.origin) && - Objects.equals(sid, other.sid) && - Objects.equals(smsApplicationSid, other.smsApplicationSid) && - Objects.equals(smsFallbackMethod, other.smsFallbackMethod) && - Objects.equals(smsFallbackUrl, other.smsFallbackUrl) && - Objects.equals(smsMethod, other.smsMethod) && - Objects.equals(smsUrl, other.smsUrl) && - Objects.equals(statusCallback, other.statusCallback) && - Objects.equals(statusCallbackMethod, other.statusCallbackMethod) && - Objects.equals(trunkSid, other.trunkSid) && - Objects.equals(uri, other.uri) && - Objects.equals(voiceReceiveMode, other.voiceReceiveMode) && - Objects.equals(voiceApplicationSid, other.voiceApplicationSid) && - Objects.equals(voiceCallerIdLookup, other.voiceCallerIdLookup) && - Objects.equals(voiceFallbackMethod, other.voiceFallbackMethod) && - Objects.equals(voiceFallbackUrl, other.voiceFallbackUrl) && - Objects.equals(voiceMethod, other.voiceMethod) && - Objects.equals(voiceUrl, other.voiceUrl) && - Objects.equals(emergencyStatus, other.emergencyStatus) && - Objects.equals(emergencyAddressSid, other.emergencyAddressSid) && - Objects.equals( - emergencyAddressStatus, - other.emergencyAddressStatus - ) && - Objects.equals(bundleSid, other.bundleSid) && - Objects.equals(status, other.status) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(addressRequirements, other.addressRequirements) && + Objects.equals(addressSid, other.addressSid) && + Objects.equals(apiVersion, other.apiVersion) && + Objects.equals(beta, other.beta) && + Objects.equals(bundleSid, other.bundleSid) && + Objects.equals(capabilities, other.capabilities) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(emergencyAddressSid, other.emergencyAddressSid) && + Objects.equals(emergencyAddressStatus, other.emergencyAddressStatus) && + Objects.equals(emergencyStatus, other.emergencyStatus) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(identitySid, other.identitySid) && + Objects.equals(origin, other.origin) && + Objects.equals(phoneNumber, other.phoneNumber) && + Objects.equals(sid, other.sid) && + Objects.equals(smsApplicationSid, other.smsApplicationSid) && + Objects.equals(smsFallbackMethod, other.smsFallbackMethod) && + Objects.equals(smsFallbackUrl, other.smsFallbackUrl) && + Objects.equals(smsMethod, other.smsMethod) && + Objects.equals(smsUrl, other.smsUrl) && + Objects.equals(status, other.status) && + Objects.equals(statusCallback, other.statusCallback) && + Objects.equals(statusCallbackMethod, other.statusCallbackMethod) && + Objects.equals(trunkSid, other.trunkSid) && + Objects.equals(uri, other.uri) && + Objects.equals(voiceApplicationSid, other.voiceApplicationSid) && + Objects.equals(voiceCallerIdLookup, other.voiceCallerIdLookup) && + Objects.equals(voiceFallbackMethod, other.voiceFallbackMethod) && + Objects.equals(voiceFallbackUrl, other.voiceFallbackUrl) && + Objects.equals(voiceMethod, other.voiceMethod) && + Objects.equals(voiceReceiveMode, other.voiceReceiveMode) && + Objects.equals(voiceUrl, other.voiceUrl) ); } @Override public int hashCode() { return Objects.hash( - accountSid, - addressSid, - addressRequirements, - apiVersion, - beta, - capabilities, - dateCreated, - dateUpdated, - friendlyName, - identitySid, - phoneNumber, - origin, - sid, - smsApplicationSid, - smsFallbackMethod, - smsFallbackUrl, - smsMethod, - smsUrl, - statusCallback, - statusCallbackMethod, - trunkSid, - uri, - voiceReceiveMode, - voiceApplicationSid, - voiceCallerIdLookup, - voiceFallbackMethod, - voiceFallbackUrl, - voiceMethod, - voiceUrl, - emergencyStatus, - emergencyAddressSid, - emergencyAddressStatus, - bundleSid, - status + accountSid, + addressRequirements, + addressSid, + apiVersion, + beta, + bundleSid, + capabilities, + dateCreated, + dateUpdated, + emergencyAddressSid, + emergencyAddressStatus, + emergencyStatus, + friendlyName, + identitySid, + origin, + phoneNumber, + sid, + smsApplicationSid, + smsFallbackMethod, + smsFallbackUrl, + smsMethod, + smsUrl, + status, + statusCallback, + statusCallbackMethod, + trunkSid, + uri, + voiceApplicationSid, + voiceCallerIdLookup, + voiceFallbackMethod, + voiceFallbackUrl, + voiceMethod, + voiceReceiveMode, + voiceUrl ); } - public enum EmergencyAddressStatus { - REGISTERED("registered"), - UNREGISTERED("unregistered"), - PENDING_REGISTRATION("pending-registration"), - REGISTRATION_FAILURE("registration-failure"), - PENDING_UNREGISTRATION("pending-unregistration"), - UNREGISTRATION_FAILURE("unregistration-failure"); - - private final String value; - - private EmergencyAddressStatus(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static EmergencyAddressStatus forValue(final String value) { - return Promoter.enumFromString( - value, - EmergencyAddressStatus.values() - ); - } - } - - public enum VoiceReceiveMode { - VOICE("voice"), - FAX("fax"); - - private final String value; - - private VoiceReceiveMode(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static VoiceReceiveMode forValue(final String value) { - return Promoter.enumFromString(value, VoiceReceiveMode.values()); - } - } - - public enum AddressRequirement { - NONE("none"), - ANY("any"), - LOCAL("local"), - FOREIGN("foreign"); - - private final String value; - - private AddressRequirement(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static AddressRequirement forValue(final String value) { - return Promoter.enumFromString(value, AddressRequirement.values()); - } - } - - public enum EmergencyStatus { - ACTIVE("Active"), - INACTIVE("Inactive"); - - private final String value; - - private EmergencyStatus(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - @JsonCreator - public static EmergencyStatus forValue(final String value) { - return Promoter.enumFromString(value, EmergencyStatus.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/api/v2010/account/IncomingPhoneNumberCreator.java b/src/main/java/com/twilio/rest/api/v2010/account/IncomingPhoneNumberCreator.java index 960d483bbe..21e101f524 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/IncomingPhoneNumberCreator.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/IncomingPhoneNumberCreator.java @@ -14,9 +14,12 @@ package com.twilio.rest.api.v2010.account; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; import com.twilio.converter.Promoter; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,12 +28,12 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -import java.net.URI; + import java.net.URI; public class IncomingPhoneNumberCreator extends Creator { - private String pathAccountSid; + private String pathaccountSid; private String apiVersion; private String friendlyName; private String smsApplicationSid; @@ -56,17 +59,12 @@ public class IncomingPhoneNumberCreator extends Creator { private com.twilio.type.PhoneNumber phoneNumber; private String areaCode; - public IncomingPhoneNumberCreator( - final com.twilio.type.PhoneNumber phoneNumber - ) { + public IncomingPhoneNumberCreator(final com.twilio.type.PhoneNumber phoneNumber) { this.phoneNumber = phoneNumber; } - public IncomingPhoneNumberCreator( - final String pathAccountSid, - final com.twilio.type.PhoneNumber phoneNumber - ) { - this.pathAccountSid = pathAccountSid; + public IncomingPhoneNumberCreator(final String pathaccountSid, final com.twilio.type.PhoneNumber phoneNumber) { + this.pathaccountSid = pathaccountSid; this.phoneNumber = phoneNumber; } @@ -74,181 +72,145 @@ public IncomingPhoneNumberCreator(final String areaCode) { this.areaCode = areaCode; } - public IncomingPhoneNumberCreator( - final String pathAccountSid, - final String areaCode - ) { - this.pathAccountSid = pathAccountSid; + public IncomingPhoneNumberCreator(final String pathaccountSid, final String areaCode) { + this.pathaccountSid = pathaccountSid; this.areaCode = areaCode; } + public IncomingPhoneNumberCreator setApiVersion(final String apiVersion) { this.apiVersion = apiVersion; return this; } - public IncomingPhoneNumberCreator setFriendlyName( - final String friendlyName - ) { + + public IncomingPhoneNumberCreator setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } - public IncomingPhoneNumberCreator setSmsApplicationSid( - final String smsApplicationSid - ) { + + public IncomingPhoneNumberCreator setSmsApplicationSid(final String smsApplicationSid) { this.smsApplicationSid = smsApplicationSid; return this; } - public IncomingPhoneNumberCreator setSmsFallbackMethod( - final HttpMethod smsFallbackMethod - ) { + + public IncomingPhoneNumberCreator setSmsFallbackMethod(final HttpMethod smsFallbackMethod) { this.smsFallbackMethod = smsFallbackMethod; return this; } - public IncomingPhoneNumberCreator setSmsFallbackUrl( - final URI smsFallbackUrl - ) { + + public IncomingPhoneNumberCreator setSmsFallbackUrl(final URI smsFallbackUrl) { this.smsFallbackUrl = smsFallbackUrl; return this; } - public IncomingPhoneNumberCreator setSmsFallbackUrl( - final String smsFallbackUrl - ) { - return setSmsFallbackUrl(Promoter.uriFromString(smsFallbackUrl)); - } public IncomingPhoneNumberCreator setSmsMethod(final HttpMethod smsMethod) { this.smsMethod = smsMethod; return this; } + public IncomingPhoneNumberCreator setSmsUrl(final URI smsUrl) { this.smsUrl = smsUrl; return this; } - public IncomingPhoneNumberCreator setSmsUrl(final String smsUrl) { - return setSmsUrl(Promoter.uriFromString(smsUrl)); - } - public IncomingPhoneNumberCreator setStatusCallback( - final URI statusCallback - ) { + public IncomingPhoneNumberCreator setStatusCallback(final URI statusCallback) { this.statusCallback = statusCallback; return this; } - public IncomingPhoneNumberCreator setStatusCallback( - final String statusCallback - ) { - return setStatusCallback(Promoter.uriFromString(statusCallback)); - } - public IncomingPhoneNumberCreator setStatusCallbackMethod( - final HttpMethod statusCallbackMethod - ) { + public IncomingPhoneNumberCreator setStatusCallbackMethod(final HttpMethod statusCallbackMethod) { this.statusCallbackMethod = statusCallbackMethod; return this; } - public IncomingPhoneNumberCreator setVoiceApplicationSid( - final String voiceApplicationSid - ) { + + public IncomingPhoneNumberCreator setVoiceApplicationSid(final String voiceApplicationSid) { this.voiceApplicationSid = voiceApplicationSid; return this; } - public IncomingPhoneNumberCreator setVoiceCallerIdLookup( - final Boolean voiceCallerIdLookup - ) { + + public IncomingPhoneNumberCreator setVoiceCallerIdLookup(final Boolean voiceCallerIdLookup) { this.voiceCallerIdLookup = voiceCallerIdLookup; return this; } - public IncomingPhoneNumberCreator setVoiceFallbackMethod( - final HttpMethod voiceFallbackMethod - ) { + + public IncomingPhoneNumberCreator setVoiceFallbackMethod(final HttpMethod voiceFallbackMethod) { this.voiceFallbackMethod = voiceFallbackMethod; return this; } - public IncomingPhoneNumberCreator setVoiceFallbackUrl( - final URI voiceFallbackUrl - ) { + + public IncomingPhoneNumberCreator setVoiceFallbackUrl(final URI voiceFallbackUrl) { this.voiceFallbackUrl = voiceFallbackUrl; return this; } - public IncomingPhoneNumberCreator setVoiceFallbackUrl( - final String voiceFallbackUrl - ) { - return setVoiceFallbackUrl(Promoter.uriFromString(voiceFallbackUrl)); - } - public IncomingPhoneNumberCreator setVoiceMethod( - final HttpMethod voiceMethod - ) { + public IncomingPhoneNumberCreator setVoiceMethod(final HttpMethod voiceMethod) { this.voiceMethod = voiceMethod; return this; } + public IncomingPhoneNumberCreator setVoiceUrl(final URI voiceUrl) { this.voiceUrl = voiceUrl; return this; } - public IncomingPhoneNumberCreator setVoiceUrl(final String voiceUrl) { - return setVoiceUrl(Promoter.uriFromString(voiceUrl)); - } - public IncomingPhoneNumberCreator setEmergencyStatus( - final IncomingPhoneNumber.EmergencyStatus emergencyStatus - ) { + public IncomingPhoneNumberCreator setEmergencyStatus(final IncomingPhoneNumber.EmergencyStatus emergencyStatus) { this.emergencyStatus = emergencyStatus; return this; } - public IncomingPhoneNumberCreator setEmergencyAddressSid( - final String emergencyAddressSid - ) { + + public IncomingPhoneNumberCreator setEmergencyAddressSid(final String emergencyAddressSid) { this.emergencyAddressSid = emergencyAddressSid; return this; } + public IncomingPhoneNumberCreator setTrunkSid(final String trunkSid) { this.trunkSid = trunkSid; return this; } + public IncomingPhoneNumberCreator setIdentitySid(final String identitySid) { this.identitySid = identitySid; return this; } + public IncomingPhoneNumberCreator setAddressSid(final String addressSid) { this.addressSid = addressSid; return this; } - public IncomingPhoneNumberCreator setVoiceReceiveMode( - final IncomingPhoneNumber.VoiceReceiveMode voiceReceiveMode - ) { + + public IncomingPhoneNumberCreator setVoiceReceiveMode(final IncomingPhoneNumber.VoiceReceiveMode voiceReceiveMode) { this.voiceReceiveMode = voiceReceiveMode; return this; } + public IncomingPhoneNumberCreator setBundleSid(final String bundleSid) { this.bundleSid = bundleSid; return this; } - public IncomingPhoneNumberCreator setPhoneNumber( - final com.twilio.type.PhoneNumber phoneNumber - ) { + + public IncomingPhoneNumberCreator setPhoneNumber(final com.twilio.type.PhoneNumber phoneNumber) { this.phoneNumber = phoneNumber; return this; } @@ -262,143 +224,163 @@ public IncomingPhoneNumberCreator setAreaCode(final String areaCode) { return this; } + @Override public IncomingPhoneNumber create(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/IncomingPhoneNumbers.json"; - - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); + + String path = "/2010-04-01/Accounts/{AccountSid}/IncomingPhoneNumbers.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.API.toString(), - path + HttpMethod.POST, + Domains.API.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "IncomingPhoneNumber creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("IncomingPhoneNumber creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return IncomingPhoneNumber.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return IncomingPhoneNumber.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (apiVersion != null) { - request.addPostParam("ApiVersion", apiVersion); + Serializer.toString(request, "ApiVersion", apiVersion, ParameterType.URLENCODED); } + + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + if (smsApplicationSid != null) { - request.addPostParam("SmsApplicationSid", smsApplicationSid); + Serializer.toString(request, "SmsApplicationSid", smsApplicationSid, ParameterType.URLENCODED); } + + if (smsFallbackMethod != null) { - request.addPostParam( - "SmsFallbackMethod", - smsFallbackMethod.toString() - ); + Serializer.toString(request, "SmsFallbackMethod", smsFallbackMethod, ParameterType.URLENCODED); } + + if (smsFallbackUrl != null) { - request.addPostParam("SmsFallbackUrl", smsFallbackUrl.toString()); + Serializer.toString(request, "SmsFallbackUrl", smsFallbackUrl, ParameterType.URLENCODED); } + + if (smsMethod != null) { - request.addPostParam("SmsMethod", smsMethod.toString()); + Serializer.toString(request, "SmsMethod", smsMethod, ParameterType.URLENCODED); } + + if (smsUrl != null) { - request.addPostParam("SmsUrl", smsUrl.toString()); + Serializer.toString(request, "SmsUrl", smsUrl, ParameterType.URLENCODED); } + + if (statusCallback != null) { - request.addPostParam("StatusCallback", statusCallback.toString()); + Serializer.toString(request, "StatusCallback", statusCallback, ParameterType.URLENCODED); } + + if (statusCallbackMethod != null) { - request.addPostParam( - "StatusCallbackMethod", - statusCallbackMethod.toString() - ); + Serializer.toString(request, "StatusCallbackMethod", statusCallbackMethod, ParameterType.URLENCODED); } + + if (voiceApplicationSid != null) { - request.addPostParam("VoiceApplicationSid", voiceApplicationSid); + Serializer.toString(request, "VoiceApplicationSid", voiceApplicationSid, ParameterType.URLENCODED); } + + if (voiceCallerIdLookup != null) { - request.addPostParam( - "VoiceCallerIdLookup", - voiceCallerIdLookup.toString() - ); + Serializer.toString(request, "VoiceCallerIdLookup", voiceCallerIdLookup, ParameterType.URLENCODED); } + + if (voiceFallbackMethod != null) { - request.addPostParam( - "VoiceFallbackMethod", - voiceFallbackMethod.toString() - ); + Serializer.toString(request, "VoiceFallbackMethod", voiceFallbackMethod, ParameterType.URLENCODED); } + + if (voiceFallbackUrl != null) { - request.addPostParam( - "VoiceFallbackUrl", - voiceFallbackUrl.toString() - ); + Serializer.toString(request, "VoiceFallbackUrl", voiceFallbackUrl, ParameterType.URLENCODED); } + + if (voiceMethod != null) { - request.addPostParam("VoiceMethod", voiceMethod.toString()); + Serializer.toString(request, "VoiceMethod", voiceMethod, ParameterType.URLENCODED); } + + if (voiceUrl != null) { - request.addPostParam("VoiceUrl", voiceUrl.toString()); + Serializer.toString(request, "VoiceUrl", voiceUrl, ParameterType.URLENCODED); } + + if (emergencyStatus != null) { - request.addPostParam("EmergencyStatus", emergencyStatus.toString()); + Serializer.toString(request, "EmergencyStatus", emergencyStatus, ParameterType.URLENCODED); } + + if (emergencyAddressSid != null) { - request.addPostParam("EmergencyAddressSid", emergencyAddressSid); + Serializer.toString(request, "EmergencyAddressSid", emergencyAddressSid, ParameterType.URLENCODED); } + + if (trunkSid != null) { - request.addPostParam("TrunkSid", trunkSid); + Serializer.toString(request, "TrunkSid", trunkSid, ParameterType.URLENCODED); } + + if (identitySid != null) { - request.addPostParam("IdentitySid", identitySid); + Serializer.toString(request, "IdentitySid", identitySid, ParameterType.URLENCODED); } + + if (addressSid != null) { - request.addPostParam("AddressSid", addressSid); + Serializer.toString(request, "AddressSid", addressSid, ParameterType.URLENCODED); } + + if (voiceReceiveMode != null) { - request.addPostParam( - "VoiceReceiveMode", - voiceReceiveMode.toString() - ); + Serializer.toString(request, "VoiceReceiveMode", voiceReceiveMode, ParameterType.URLENCODED); } + + if (bundleSid != null) { - request.addPostParam("BundleSid", bundleSid); + Serializer.toString(request, "BundleSid", bundleSid, ParameterType.URLENCODED); } + + if (phoneNumber != null) { - request.addPostParam("PhoneNumber", phoneNumber.toString()); + Serializer.toString(request, "PhoneNumber", phoneNumber, ParameterType.URLENCODED); } + + if (areaCode != null) { - request.addPostParam("AreaCode", areaCode); + Serializer.toString(request, "AreaCode", areaCode, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/IncomingPhoneNumberDeleter.java b/src/main/java/com/twilio/rest/api/v2010/account/IncomingPhoneNumberDeleter.java index 0f7ff8db7c..2f0192038d 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/IncomingPhoneNumberDeleter.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/IncomingPhoneNumberDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.api.v2010.account; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,59 +26,46 @@ public class IncomingPhoneNumberDeleter extends Deleter { - private String pathSid; - private String pathAccountSid; + private String pathaccountSid; + private String pathsid; - public IncomingPhoneNumberDeleter(final String pathSid) { - this.pathSid = pathSid; + public IncomingPhoneNumberDeleter(final String pathsid) { + this.pathsid = pathsid; } - public IncomingPhoneNumberDeleter( - final String pathAccountSid, - final String pathSid - ) { - this.pathAccountSid = pathAccountSid; - this.pathSid = pathSid; + public IncomingPhoneNumberDeleter(final String pathaccountSid, final String pathsid) { + this.pathaccountSid = pathaccountSid; + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/IncomingPhoneNumbers/{Sid}.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/2010-04-01/Accounts/{AccountSid}/IncomingPhoneNumbers/{Sid}.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.API.toString(), - path + HttpMethod.DELETE, + Domains.API.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "IncomingPhoneNumber delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("IncomingPhoneNumber delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/IncomingPhoneNumberFetcher.java b/src/main/java/com/twilio/rest/api/v2010/account/IncomingPhoneNumberFetcher.java index 3b7b56ae4e..b235fa3314 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/IncomingPhoneNumberFetcher.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/IncomingPhoneNumberFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.api.v2010.account; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,66 +26,49 @@ public class IncomingPhoneNumberFetcher extends Fetcher { - private String pathSid; - private String pathAccountSid; + private String pathaccountSid; + private String pathsid; - public IncomingPhoneNumberFetcher(final String pathSid) { - this.pathSid = pathSid; + public IncomingPhoneNumberFetcher(final String pathsid) { + this.pathsid = pathsid; } - public IncomingPhoneNumberFetcher( - final String pathAccountSid, - final String pathSid - ) { - this.pathAccountSid = pathAccountSid; - this.pathSid = pathSid; + public IncomingPhoneNumberFetcher(final String pathaccountSid, final String pathsid) { + this.pathaccountSid = pathaccountSid; + this.pathsid = pathsid; } + @Override public IncomingPhoneNumber fetch(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/IncomingPhoneNumbers/{Sid}.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/2010-04-01/Accounts/{AccountSid}/IncomingPhoneNumbers/{Sid}.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.API.toString(), - path + HttpMethod.GET, + Domains.API.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "IncomingPhoneNumber fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("IncomingPhoneNumber fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return IncomingPhoneNumber.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return IncomingPhoneNumber.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/IncomingPhoneNumberReader.java b/src/main/java/com/twilio/rest/api/v2010/account/IncomingPhoneNumberReader.java index 69c9eb10aa..3235785fca 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/IncomingPhoneNumberReader.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/IncomingPhoneNumberReader.java @@ -17,8 +17,9 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; import com.twilio.converter.Promoter; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -30,34 +31,34 @@ public class IncomingPhoneNumberReader extends Reader { - private String pathAccountSid; + private String pathaccountSid; private Boolean beta; private String friendlyName; private com.twilio.type.PhoneNumber phoneNumber; private String origin; private Long pageSize; - public IncomingPhoneNumberReader() {} + public IncomingPhoneNumberReader() { + } - public IncomingPhoneNumberReader(final String pathAccountSid) { - this.pathAccountSid = pathAccountSid; + public IncomingPhoneNumberReader(final String pathaccountSid) { + this.pathaccountSid = pathaccountSid; } + public IncomingPhoneNumberReader setBeta(final Boolean beta) { this.beta = beta; return this; } - public IncomingPhoneNumberReader setFriendlyName( - final String friendlyName - ) { + + public IncomingPhoneNumberReader setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } - public IncomingPhoneNumberReader setPhoneNumber( - final com.twilio.type.PhoneNumber phoneNumber - ) { + + public IncomingPhoneNumberReader setPhoneNumber(final com.twilio.type.PhoneNumber phoneNumber) { this.phoneNumber = phoneNumber; return this; } @@ -71,127 +72,102 @@ public IncomingPhoneNumberReader setOrigin(final String origin) { return this; } + public IncomingPhoneNumberReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override - public ResourceSet read( - final TwilioRestClient client - ) { + public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/IncomingPhoneNumbers.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); + + String path = "/2010-04-01/Accounts/{AccountSid}/IncomingPhoneNumbers.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.API.toString(), - path + HttpMethod.GET, + Domains.API.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "IncomingPhoneNumber read failed: Unable to connect to server" - ); + throw new ApiConnectionException("IncomingPhoneNumber read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "incoming_phone_numbers", - response.getContent(), - IncomingPhoneNumber.class, - client.getObjectMapper() - ); + "incoming_phone_numbers", + response.getContent(), + IncomingPhoneNumber.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.API.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.API.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (beta != null) { - request.addQueryParam("Beta", beta.toString()); + Serializer.toString(request, "Beta", beta, ParameterType.QUERY); } + + if (friendlyName != null) { - request.addQueryParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.QUERY); } + + if (phoneNumber != null) { - request.addQueryParam("PhoneNumber", phoneNumber.toString()); + Serializer.toString(request, "PhoneNumber", phoneNumber, ParameterType.QUERY); } + + if (origin != null) { - request.addQueryParam("Origin", origin); + Serializer.toString(request, "Origin", origin, ParameterType.QUERY); } + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/IncomingPhoneNumberUpdater.java b/src/main/java/com/twilio/rest/api/v2010/account/IncomingPhoneNumberUpdater.java index d28ef02997..67e1cbb1af 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/IncomingPhoneNumberUpdater.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/IncomingPhoneNumberUpdater.java @@ -16,7 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; -import com.twilio.converter.Promoter; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,12 +26,12 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.net.URI; public class IncomingPhoneNumberUpdater extends Updater { - - private String pathSid; - private String pathAccountSid; + private String pathaccountSid; + private String pathsid; private String accountSid; private String apiVersion; private String friendlyName; @@ -55,322 +56,306 @@ public class IncomingPhoneNumberUpdater extends Updater { private String addressSid; private String bundleSid; - public IncomingPhoneNumberUpdater(final String pathSid) { - this.pathSid = pathSid; + public IncomingPhoneNumberUpdater(final String pathsid) { + this.pathsid = pathsid; } - public IncomingPhoneNumberUpdater( - final String pathAccountSid, - final String pathSid - ) { - this.pathAccountSid = pathAccountSid; - this.pathSid = pathSid; + public IncomingPhoneNumberUpdater(final String pathaccountSid, final String pathsid) { + this.pathaccountSid = pathaccountSid; + this.pathsid = pathsid; } + public IncomingPhoneNumberUpdater setAccountSid(final String accountSid) { this.accountSid = accountSid; return this; } + public IncomingPhoneNumberUpdater setApiVersion(final String apiVersion) { this.apiVersion = apiVersion; return this; } - public IncomingPhoneNumberUpdater setFriendlyName( - final String friendlyName - ) { + + public IncomingPhoneNumberUpdater setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } - public IncomingPhoneNumberUpdater setSmsApplicationSid( - final String smsApplicationSid - ) { + + public IncomingPhoneNumberUpdater setSmsApplicationSid(final String smsApplicationSid) { this.smsApplicationSid = smsApplicationSid; return this; } - public IncomingPhoneNumberUpdater setSmsFallbackMethod( - final HttpMethod smsFallbackMethod - ) { + + public IncomingPhoneNumberUpdater setSmsFallbackMethod(final HttpMethod smsFallbackMethod) { this.smsFallbackMethod = smsFallbackMethod; return this; } - public IncomingPhoneNumberUpdater setSmsFallbackUrl( - final URI smsFallbackUrl - ) { + + public IncomingPhoneNumberUpdater setSmsFallbackUrl(final URI smsFallbackUrl) { this.smsFallbackUrl = smsFallbackUrl; return this; } - public IncomingPhoneNumberUpdater setSmsFallbackUrl( - final String smsFallbackUrl - ) { - return setSmsFallbackUrl(Promoter.uriFromString(smsFallbackUrl)); - } public IncomingPhoneNumberUpdater setSmsMethod(final HttpMethod smsMethod) { this.smsMethod = smsMethod; return this; } + public IncomingPhoneNumberUpdater setSmsUrl(final URI smsUrl) { this.smsUrl = smsUrl; return this; } - public IncomingPhoneNumberUpdater setSmsUrl(final String smsUrl) { - return setSmsUrl(Promoter.uriFromString(smsUrl)); - } - public IncomingPhoneNumberUpdater setStatusCallback( - final URI statusCallback - ) { + public IncomingPhoneNumberUpdater setStatusCallback(final URI statusCallback) { this.statusCallback = statusCallback; return this; } - public IncomingPhoneNumberUpdater setStatusCallback( - final String statusCallback - ) { - return setStatusCallback(Promoter.uriFromString(statusCallback)); - } - public IncomingPhoneNumberUpdater setStatusCallbackMethod( - final HttpMethod statusCallbackMethod - ) { + public IncomingPhoneNumberUpdater setStatusCallbackMethod(final HttpMethod statusCallbackMethod) { this.statusCallbackMethod = statusCallbackMethod; return this; } - public IncomingPhoneNumberUpdater setVoiceApplicationSid( - final String voiceApplicationSid - ) { + + public IncomingPhoneNumberUpdater setVoiceApplicationSid(final String voiceApplicationSid) { this.voiceApplicationSid = voiceApplicationSid; return this; } - public IncomingPhoneNumberUpdater setVoiceCallerIdLookup( - final Boolean voiceCallerIdLookup - ) { + + public IncomingPhoneNumberUpdater setVoiceCallerIdLookup(final Boolean voiceCallerIdLookup) { this.voiceCallerIdLookup = voiceCallerIdLookup; return this; } - public IncomingPhoneNumberUpdater setVoiceFallbackMethod( - final HttpMethod voiceFallbackMethod - ) { + + public IncomingPhoneNumberUpdater setVoiceFallbackMethod(final HttpMethod voiceFallbackMethod) { this.voiceFallbackMethod = voiceFallbackMethod; return this; } - public IncomingPhoneNumberUpdater setVoiceFallbackUrl( - final URI voiceFallbackUrl - ) { + + public IncomingPhoneNumberUpdater setVoiceFallbackUrl(final URI voiceFallbackUrl) { this.voiceFallbackUrl = voiceFallbackUrl; return this; } - public IncomingPhoneNumberUpdater setVoiceFallbackUrl( - final String voiceFallbackUrl - ) { - return setVoiceFallbackUrl(Promoter.uriFromString(voiceFallbackUrl)); - } - public IncomingPhoneNumberUpdater setVoiceMethod( - final HttpMethod voiceMethod - ) { + public IncomingPhoneNumberUpdater setVoiceMethod(final HttpMethod voiceMethod) { this.voiceMethod = voiceMethod; return this; } + public IncomingPhoneNumberUpdater setVoiceUrl(final URI voiceUrl) { this.voiceUrl = voiceUrl; return this; } - public IncomingPhoneNumberUpdater setVoiceUrl(final String voiceUrl) { - return setVoiceUrl(Promoter.uriFromString(voiceUrl)); - } - public IncomingPhoneNumberUpdater setEmergencyStatus( - final IncomingPhoneNumber.EmergencyStatus emergencyStatus - ) { + public IncomingPhoneNumberUpdater setEmergencyStatus(final IncomingPhoneNumber.EmergencyStatus emergencyStatus) { this.emergencyStatus = emergencyStatus; return this; } - public IncomingPhoneNumberUpdater setEmergencyAddressSid( - final String emergencyAddressSid - ) { + + public IncomingPhoneNumberUpdater setEmergencyAddressSid(final String emergencyAddressSid) { this.emergencyAddressSid = emergencyAddressSid; return this; } + public IncomingPhoneNumberUpdater setTrunkSid(final String trunkSid) { this.trunkSid = trunkSid; return this; } - public IncomingPhoneNumberUpdater setVoiceReceiveMode( - final IncomingPhoneNumber.VoiceReceiveMode voiceReceiveMode - ) { + + public IncomingPhoneNumberUpdater setVoiceReceiveMode(final IncomingPhoneNumber.VoiceReceiveMode voiceReceiveMode) { this.voiceReceiveMode = voiceReceiveMode; return this; } + public IncomingPhoneNumberUpdater setIdentitySid(final String identitySid) { this.identitySid = identitySid; return this; } + public IncomingPhoneNumberUpdater setAddressSid(final String addressSid) { this.addressSid = addressSid; return this; } + public IncomingPhoneNumberUpdater setBundleSid(final String bundleSid) { this.bundleSid = bundleSid; return this; } + @Override public IncomingPhoneNumber update(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/IncomingPhoneNumbers/{Sid}.json"; - - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + + String path = "/2010-04-01/Accounts/{AccountSid}/IncomingPhoneNumbers/{Sid}.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.API.toString(), - path + HttpMethod.POST, + Domains.API.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "IncomingPhoneNumber update failed: Unable to connect to server" - ); + throw new ApiConnectionException("IncomingPhoneNumber update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return IncomingPhoneNumber.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return IncomingPhoneNumber.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (accountSid != null) { - request.addPostParam("AccountSid", accountSid); + Serializer.toString(request, "AccountSid", accountSid, ParameterType.URLENCODED); } + + if (apiVersion != null) { - request.addPostParam("ApiVersion", apiVersion); + Serializer.toString(request, "ApiVersion", apiVersion, ParameterType.URLENCODED); } + + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + if (smsApplicationSid != null) { - request.addPostParam("SmsApplicationSid", smsApplicationSid); + Serializer.toString(request, "SmsApplicationSid", smsApplicationSid, ParameterType.URLENCODED); } + + if (smsFallbackMethod != null) { - request.addPostParam( - "SmsFallbackMethod", - smsFallbackMethod.toString() - ); + Serializer.toString(request, "SmsFallbackMethod", smsFallbackMethod, ParameterType.URLENCODED); } + + if (smsFallbackUrl != null) { - request.addPostParam("SmsFallbackUrl", smsFallbackUrl.toString()); + Serializer.toString(request, "SmsFallbackUrl", smsFallbackUrl, ParameterType.URLENCODED); } + + if (smsMethod != null) { - request.addPostParam("SmsMethod", smsMethod.toString()); + Serializer.toString(request, "SmsMethod", smsMethod, ParameterType.URLENCODED); } + + if (smsUrl != null) { - request.addPostParam("SmsUrl", smsUrl.toString()); + Serializer.toString(request, "SmsUrl", smsUrl, ParameterType.URLENCODED); } + + if (statusCallback != null) { - request.addPostParam("StatusCallback", statusCallback.toString()); + Serializer.toString(request, "StatusCallback", statusCallback, ParameterType.URLENCODED); } + + if (statusCallbackMethod != null) { - request.addPostParam( - "StatusCallbackMethod", - statusCallbackMethod.toString() - ); + Serializer.toString(request, "StatusCallbackMethod", statusCallbackMethod, ParameterType.URLENCODED); } + + if (voiceApplicationSid != null) { - request.addPostParam("VoiceApplicationSid", voiceApplicationSid); + Serializer.toString(request, "VoiceApplicationSid", voiceApplicationSid, ParameterType.URLENCODED); } + + if (voiceCallerIdLookup != null) { - request.addPostParam( - "VoiceCallerIdLookup", - voiceCallerIdLookup.toString() - ); + Serializer.toString(request, "VoiceCallerIdLookup", voiceCallerIdLookup, ParameterType.URLENCODED); } + + if (voiceFallbackMethod != null) { - request.addPostParam( - "VoiceFallbackMethod", - voiceFallbackMethod.toString() - ); + Serializer.toString(request, "VoiceFallbackMethod", voiceFallbackMethod, ParameterType.URLENCODED); } + + if (voiceFallbackUrl != null) { - request.addPostParam( - "VoiceFallbackUrl", - voiceFallbackUrl.toString() - ); + Serializer.toString(request, "VoiceFallbackUrl", voiceFallbackUrl, ParameterType.URLENCODED); } + + if (voiceMethod != null) { - request.addPostParam("VoiceMethod", voiceMethod.toString()); + Serializer.toString(request, "VoiceMethod", voiceMethod, ParameterType.URLENCODED); } + + if (voiceUrl != null) { - request.addPostParam("VoiceUrl", voiceUrl.toString()); + Serializer.toString(request, "VoiceUrl", voiceUrl, ParameterType.URLENCODED); } + + if (emergencyStatus != null) { - request.addPostParam("EmergencyStatus", emergencyStatus.toString()); + Serializer.toString(request, "EmergencyStatus", emergencyStatus, ParameterType.URLENCODED); } + + if (emergencyAddressSid != null) { - request.addPostParam("EmergencyAddressSid", emergencyAddressSid); + Serializer.toString(request, "EmergencyAddressSid", emergencyAddressSid, ParameterType.URLENCODED); } + + if (trunkSid != null) { - request.addPostParam("TrunkSid", trunkSid); + Serializer.toString(request, "TrunkSid", trunkSid, ParameterType.URLENCODED); } + + if (voiceReceiveMode != null) { - request.addPostParam( - "VoiceReceiveMode", - voiceReceiveMode.toString() - ); + Serializer.toString(request, "VoiceReceiveMode", voiceReceiveMode, ParameterType.URLENCODED); } + + if (identitySid != null) { - request.addPostParam("IdentitySid", identitySid); + Serializer.toString(request, "IdentitySid", identitySid, ParameterType.URLENCODED); } + + if (addressSid != null) { - request.addPostParam("AddressSid", addressSid); + Serializer.toString(request, "AddressSid", addressSid, ParameterType.URLENCODED); } + + if (bundleSid != null) { - request.addPostParam("BundleSid", bundleSid); + Serializer.toString(request, "BundleSid", bundleSid, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/Key.java b/src/main/java/com/twilio/rest/api/v2010/account/Key.java index d4accbbe79..4f57e5a965 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/Key.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/Key.java @@ -18,77 +18,90 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.time.ZonedDateTime; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Key extends Resource { - private static final long serialVersionUID = 35259719636912L; - public static KeyDeleter deleter(final String pathSid) { - return new KeyDeleter(pathSid); + public static KeyDeleter deleter(final String pathsid) { + return new KeyDeleter( + pathsid + ); } - public static KeyDeleter deleter( - final String pathAccountSid, - final String pathSid - ) { - return new KeyDeleter(pathAccountSid, pathSid); + + public static KeyDeleter deleter(final String pathaccountSid, final String pathsid) { + return new KeyDeleter( + pathaccountSid, pathsid + ); } - public static KeyFetcher fetcher(final String pathSid) { - return new KeyFetcher(pathSid); + + public static KeyFetcher fetcher(final String pathsid) { + return new KeyFetcher( + pathsid + ); } - public static KeyFetcher fetcher( - final String pathAccountSid, - final String pathSid - ) { - return new KeyFetcher(pathAccountSid, pathSid); + + public static KeyFetcher fetcher(final String pathaccountSid, final String pathsid) { + return new KeyFetcher( + pathaccountSid, pathsid + ); } + public static KeyReader reader() { - return new KeyReader(); + return new KeyReader( + + ); } - public static KeyReader reader(final String pathAccountSid) { - return new KeyReader(pathAccountSid); + + public static KeyReader reader(final String pathaccountSid) { + return new KeyReader( + pathaccountSid + ); } - public static KeyUpdater updater(final String pathSid) { - return new KeyUpdater(pathSid); + + public static KeyUpdater updater(final String pathsid) { + return new KeyUpdater( + pathsid + ); } - public static KeyUpdater updater( - final String pathAccountSid, - final String pathSid - ) { - return new KeyUpdater(pathAccountSid, pathSid); + + public static KeyUpdater updater(final String pathaccountSid, final String pathsid) { + return new KeyUpdater( + pathaccountSid, pathsid + ); } + /** * Converts a JSON String into a Key object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Key object represented by the provided JSON */ - public static Key fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Key fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Key.class); @@ -103,14 +116,11 @@ public static Key fromJson( * Converts a JSON InputStream into a Key object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Key object represented by the provided JSON */ - public static Key fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Key fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Key.class); @@ -121,38 +131,41 @@ public static Key fromJson( } } - private final String sid; - private final String friendlyName; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; + @Getter + private final String friendlyName; + @Getter + private final String sid; @JsonCreator private Key( - @JsonProperty("sid") final String sid, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.RFC2822Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.RFC2822Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("sid") final String sid ) { - this.sid = sid; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.friendlyName = friendlyName; - this.dateCreated = DateConverter.rfc2822DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.rfc2822DateTimeFromString(dateUpdated); - } - - public final String getSid() { - return this.sid; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; + this.sid = sid; } @Override @@ -166,17 +179,24 @@ public boolean equals(final Object o) { } Key other = (Key) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(sid, other.sid) ); } @Override public int hashCode() { - return Objects.hash(sid, friendlyName, dateCreated, dateUpdated); + return Objects.hash( + dateCreated, + dateUpdated, + friendlyName, + sid + ); } + + } + diff --git a/src/main/java/com/twilio/rest/api/v2010/account/KeyDeleter.java b/src/main/java/com/twilio/rest/api/v2010/account/KeyDeleter.java index 2896c41a06..5584ca1cf8 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/KeyDeleter.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/KeyDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.api.v2010.account; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,55 +26,46 @@ public class KeyDeleter extends Deleter { - private String pathSid; - private String pathAccountSid; + private String pathaccountSid; + private String pathsid; - public KeyDeleter(final String pathSid) { - this.pathSid = pathSid; + public KeyDeleter(final String pathsid) { + this.pathsid = pathsid; } - public KeyDeleter(final String pathAccountSid, final String pathSid) { - this.pathAccountSid = pathAccountSid; - this.pathSid = pathSid; + public KeyDeleter(final String pathaccountSid, final String pathsid) { + this.pathaccountSid = pathaccountSid; + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/2010-04-01/Accounts/{AccountSid}/Keys/{Sid}.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.API.toString(), - path + HttpMethod.DELETE, + Domains.API.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Key delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("Key delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/KeyFetcher.java b/src/main/java/com/twilio/rest/api/v2010/account/KeyFetcher.java index 756f3e96f3..adcb7a5ea5 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/KeyFetcher.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/KeyFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.api.v2010.account; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,59 +26,49 @@ public class KeyFetcher extends Fetcher { - private String pathSid; - private String pathAccountSid; + private String pathaccountSid; + private String pathsid; - public KeyFetcher(final String pathSid) { - this.pathSid = pathSid; + public KeyFetcher(final String pathsid) { + this.pathsid = pathsid; } - public KeyFetcher(final String pathAccountSid, final String pathSid) { - this.pathAccountSid = pathAccountSid; - this.pathSid = pathSid; + public KeyFetcher(final String pathaccountSid, final String pathsid) { + this.pathaccountSid = pathaccountSid; + this.pathsid = pathsid; } + @Override public Key fetch(final TwilioRestClient client) { + String path = "/2010-04-01/Accounts/{AccountSid}/Keys/{Sid}.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.API.toString(), - path + HttpMethod.GET, + Domains.API.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Key fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Key fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Key.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/KeyReader.java b/src/main/java/com/twilio/rest/api/v2010/account/KeyReader.java index cafc5135ab..f42e6b630d 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/KeyReader.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/KeyReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,121 +30,92 @@ public class KeyReader extends Reader { - private String pathAccountSid; + private String pathaccountSid; private Long pageSize; - public KeyReader() {} + public KeyReader() { + } - public KeyReader(final String pathAccountSid) { - this.pathAccountSid = pathAccountSid; + public KeyReader(final String pathaccountSid) { + this.pathaccountSid = pathaccountSid; } + public KeyReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/2010-04-01/Accounts/{AccountSid}/Keys.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.API.toString(), - path + HttpMethod.GET, + Domains.API.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Key read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Key read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "keys", - response.getContent(), - Key.class, - client.getObjectMapper() - ); + "keys", + response.getContent(), + Key.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.API.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.API.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/KeyUpdater.java b/src/main/java/com/twilio/rest/api/v2010/account/KeyUpdater.java index cfa629b0d1..a18e5134af 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/KeyUpdater.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/KeyUpdater.java @@ -16,6 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -26,62 +28,55 @@ import com.twilio.rest.Domains; public class KeyUpdater extends Updater { - - private String pathSid; - private String pathAccountSid; + private String pathaccountSid; + private String pathsid; private String friendlyName; - public KeyUpdater(final String pathSid) { - this.pathSid = pathSid; + public KeyUpdater(final String pathsid) { + this.pathsid = pathsid; } - public KeyUpdater(final String pathAccountSid, final String pathSid) { - this.pathAccountSid = pathAccountSid; - this.pathSid = pathSid; + public KeyUpdater(final String pathaccountSid, final String pathsid) { + this.pathaccountSid = pathaccountSid; + this.pathsid = pathsid; } + public KeyUpdater setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + @Override public Key update(final TwilioRestClient client) { + String path = "/2010-04-01/Accounts/{AccountSid}/Keys/{Sid}.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.API.toString(), - path + HttpMethod.POST, + Domains.API.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Key update failed: Unable to connect to server" - ); + throw new ApiConnectionException("Key update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -90,8 +85,11 @@ public Key update(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/Message.java b/src/main/java/com/twilio/rest/api/v2010/account/Message.java index 548b52b068..3d659bc4a9 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/Message.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/Message.java @@ -18,15 +18,17 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.CurrencyDeserializer; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; @@ -34,399 +36,162 @@ import java.util.Currency; import java.util.List; import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Message extends Resource { - private static final long serialVersionUID = 20600562506098L; - - public static MessageCreator creator( - final com.twilio.type.PhoneNumber to, - final com.twilio.type.PhoneNumber from, - final String body - ) { - return new MessageCreator(to, from, body); - } - - public static MessageCreator creator( - final String pathAccountSid, - final com.twilio.type.PhoneNumber to, - final com.twilio.type.PhoneNumber from, - final String body - ) { - return new MessageCreator(pathAccountSid, to, from, body); - } - public static MessageCreator creator( - final com.twilio.type.PhoneNumber to, - final com.twilio.type.PhoneNumber from, - final List mediaUrl - ) { - return new MessageCreator(to, from, mediaUrl); - } - - public static MessageCreator creator( - final String pathAccountSid, - final com.twilio.type.PhoneNumber to, - final com.twilio.type.PhoneNumber from, - final List mediaUrl - ) { - return new MessageCreator(pathAccountSid, to, from, mediaUrl); - } - - public static MessageCreator creator( - final com.twilio.type.PhoneNumber to, - final String messagingServiceSid, - final String body - ) { - return new MessageCreator(to, messagingServiceSid, body); - } - - public static MessageCreator creator( - final String pathAccountSid, - final com.twilio.type.PhoneNumber to, - final String messagingServiceSid, - final String body - ) { + public static MessageCreator creator(final com.twilio.type.PhoneNumber to, final com.twilio.type.PhoneNumber from, final String body) { return new MessageCreator( - pathAccountSid, - to, - messagingServiceSid, - body + to, from, body ); } - public static MessageCreator creator( - final com.twilio.type.PhoneNumber to, - final String messagingServiceSid, - final List mediaUrl - ) { - return new MessageCreator(to, messagingServiceSid, mediaUrl); - } - public static MessageCreator creator( - final String pathAccountSid, - final com.twilio.type.PhoneNumber to, - final String messagingServiceSid, - final List mediaUrl - ) { + public static MessageCreator creator(final String pathaccountSid, final com.twilio.type.PhoneNumber to, final com.twilio.type.PhoneNumber from, final String body) { return new MessageCreator( - pathAccountSid, - to, - messagingServiceSid, - mediaUrl + pathaccountSid, to, from, body ); } - public static MessageDeleter deleter(final String pathSid) { - return new MessageDeleter(pathSid); - } - public static MessageDeleter deleter( - final String pathAccountSid, - final String pathSid - ) { - return new MessageDeleter(pathAccountSid, pathSid); + public static MessageCreator creator(final com.twilio.type.PhoneNumber to, final com.twilio.type.PhoneNumber from, final List mediaUrl) { + return new MessageCreator( + to, from, mediaUrl + ); } - public static MessageFetcher fetcher(final String pathSid) { - return new MessageFetcher(pathSid); - } - public static MessageFetcher fetcher( - final String pathAccountSid, - final String pathSid - ) { - return new MessageFetcher(pathAccountSid, pathSid); + public static MessageCreator creator(final String pathaccountSid, final com.twilio.type.PhoneNumber to, final com.twilio.type.PhoneNumber from, final List mediaUrl) { + return new MessageCreator( + pathaccountSid, to, from, mediaUrl + ); } - public static MessageReader reader() { - return new MessageReader(); - } - public static MessageReader reader(final String pathAccountSid) { - return new MessageReader(pathAccountSid); + public static MessageCreator creator(final com.twilio.type.PhoneNumber to, final String messagingServiceSid, final String body) { + return new MessageCreator( + to, messagingServiceSid, body + ); } - public static MessageUpdater updater(final String pathSid) { - return new MessageUpdater(pathSid); - } - public static MessageUpdater updater( - final String pathAccountSid, - final String pathSid - ) { - return new MessageUpdater(pathAccountSid, pathSid); + public static MessageCreator creator(final String pathaccountSid, final com.twilio.type.PhoneNumber to, final String messagingServiceSid, final String body) { + return new MessageCreator( + pathaccountSid, to, messagingServiceSid, body + ); } - /** - * Converts a JSON String into a Message object using the provided ObjectMapper. - * - * @param json Raw JSON String - * @param objectMapper Jackson ObjectMapper - * @return Message object represented by the provided JSON - */ - public static Message fromJson( - final String json, - final ObjectMapper objectMapper - ) { - // Convert all checked exceptions to Runtime - try { - return objectMapper.readValue(json, Message.class); - } catch (final JsonMappingException | JsonParseException e) { - throw new ApiException(e.getMessage(), e); - } catch (final IOException e) { - throw new ApiConnectionException(e.getMessage(), e); - } - } - /** - * Converts a JSON InputStream into a Message object using the provided - * ObjectMapper. - * - * @param json Raw JSON InputStream - * @param objectMapper Jackson ObjectMapper - * @return Message object represented by the provided JSON - */ - public static Message fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { - // Convert all checked exceptions to Runtime - try { - return objectMapper.readValue(json, Message.class); - } catch (final JsonMappingException | JsonParseException e) { - throw new ApiException(e.getMessage(), e); - } catch (final IOException e) { - throw new ApiConnectionException(e.getMessage(), e); - } + public static MessageCreator creator(final com.twilio.type.PhoneNumber to, final String messagingServiceSid, final List mediaUrl) { + return new MessageCreator( + to, messagingServiceSid, mediaUrl + ); } - private final String body; - private final String numSegments; - private final Message.Direction direction; - private final com.twilio.type.PhoneNumber from; - private final String to; - private final ZonedDateTime dateUpdated; - private final String price; - private final String errorMessage; - private final String uri; - private final String accountSid; - private final String numMedia; - private final Message.Status status; - private final String messagingServiceSid; - private final String sid; - private final ZonedDateTime dateSent; - private final ZonedDateTime dateCreated; - private final Integer errorCode; - private final Currency priceUnit; - private final String apiVersion; - private final Map subresourceUris; - @JsonCreator - private Message( - @JsonProperty("body") final String body, - @JsonProperty("num_segments") final String numSegments, - @JsonProperty("direction") final Message.Direction direction, - @JsonProperty("from") final com.twilio.type.PhoneNumber from, - @JsonProperty("to") final String to, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("price") final String price, - @JsonProperty("error_message") final String errorMessage, - @JsonProperty("uri") final String uri, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("num_media") final String numMedia, - @JsonProperty("status") final Message.Status status, - @JsonProperty("messaging_service_sid") final String messagingServiceSid, - @JsonProperty("sid") final String sid, - @JsonProperty("date_sent") final String dateSent, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("error_code") final Integer errorCode, - @JsonProperty("price_unit") @JsonDeserialize( - using = com.twilio.converter.CurrencyDeserializer.class - ) final Currency priceUnit, - @JsonProperty("api_version") final String apiVersion, - @JsonProperty("subresource_uris") final Map< - String, - String - > subresourceUris - ) { - this.body = body; - this.numSegments = numSegments; - this.direction = direction; - this.from = from; - this.to = to; - this.dateUpdated = DateConverter.rfc2822DateTimeFromString(dateUpdated); - this.price = price; - this.errorMessage = errorMessage; - this.uri = uri; - this.accountSid = accountSid; - this.numMedia = numMedia; - this.status = status; - this.messagingServiceSid = messagingServiceSid; - this.sid = sid; - this.dateSent = DateConverter.rfc2822DateTimeFromString(dateSent); - this.dateCreated = DateConverter.rfc2822DateTimeFromString(dateCreated); - this.errorCode = errorCode; - this.priceUnit = priceUnit; - this.apiVersion = apiVersion; - this.subresourceUris = subresourceUris; + public static MessageCreator creator(final String pathaccountSid, final com.twilio.type.PhoneNumber to, final String messagingServiceSid, final List mediaUrl) { + return new MessageCreator( + pathaccountSid, to, messagingServiceSid, mediaUrl + ); } - public final String getBody() { - return this.body; - } - public final String getNumSegments() { - return this.numSegments; + public static MessageDeleter deleter(final String pathsid) { + return new MessageDeleter( + pathsid + ); } - public final Message.Direction getDirection() { - return this.direction; - } - public final com.twilio.type.PhoneNumber getFrom() { - return this.from; + public static MessageDeleter deleter(final String pathaccountSid, final String pathsid) { + return new MessageDeleter( + pathaccountSid, pathsid + ); } - public final String getTo() { - return this.to; - } - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; + public static MessageFetcher fetcher(final String pathsid) { + return new MessageFetcher( + pathsid + ); } - public final String getPrice() { - return this.price; - } - public final String getErrorMessage() { - return this.errorMessage; + public static MessageFetcher fetcher(final String pathaccountSid, final String pathsid) { + return new MessageFetcher( + pathaccountSid, pathsid + ); } - public final String getUri() { - return this.uri; - } - public final String getAccountSid() { - return this.accountSid; - } + public static MessageReader reader() { + return new MessageReader( - public final String getNumMedia() { - return this.numMedia; + ); } - public final Message.Status getStatus() { - return this.status; - } - public final String getMessagingServiceSid() { - return this.messagingServiceSid; + public static MessageReader reader(final String pathaccountSid) { + return new MessageReader( + pathaccountSid + ); } - public final String getSid() { - return this.sid; - } - public final ZonedDateTime getDateSent() { - return this.dateSent; + public static MessageUpdater updater(final String pathsid) { + return new MessageUpdater( + pathsid + ); } - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - public final Integer getErrorCode() { - return this.errorCode; + public static MessageUpdater updater(final String pathaccountSid, final String pathsid) { + return new MessageUpdater( + pathaccountSid, pathsid + ); } - public final Currency getPriceUnit() { - return this.priceUnit; - } - public final String getApiVersion() { - return this.apiVersion; - } + public enum Status { + QUEUED("queued"), + SENDING("sending"), + SENT("sent"), + FAILED("failed"), + DELIVERED("delivered"), + UNDELIVERED("undelivered"), + RECEIVING("receiving"), + RECEIVED("received"), + ACCEPTED("accepted"), + SCHEDULED("scheduled"), + READ("read"), + PARTIALLY_DELIVERED("partially_delivered"), + CANCELED("canceled"); - public final Map getSubresourceUris() { - return this.subresourceUris; - } + private final String value; - @Override - public boolean equals(final Object o) { - if (this == o) { - return true; + private Status(final String value) { + this.value = value; } - if (o == null || getClass() != o.getClass()) { - return false; + public String toString() { + return value; } - Message other = (Message) o; - - return ( - Objects.equals(body, other.body) && - Objects.equals(numSegments, other.numSegments) && - Objects.equals(direction, other.direction) && - Objects.equals(from, other.from) && - Objects.equals(to, other.to) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(price, other.price) && - Objects.equals(errorMessage, other.errorMessage) && - Objects.equals(uri, other.uri) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(numMedia, other.numMedia) && - Objects.equals(status, other.status) && - Objects.equals(messagingServiceSid, other.messagingServiceSid) && - Objects.equals(sid, other.sid) && - Objects.equals(dateSent, other.dateSent) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(errorCode, other.errorCode) && - Objects.equals(priceUnit, other.priceUnit) && - Objects.equals(apiVersion, other.apiVersion) && - Objects.equals(subresourceUris, other.subresourceUris) - ); - } - - @Override - public int hashCode() { - return Objects.hash( - body, - numSegments, - direction, - from, - to, - dateUpdated, - price, - errorMessage, - uri, - accountSid, - numMedia, - status, - messagingServiceSid, - sid, - dateSent, - dateCreated, - errorCode, - priceUnit, - apiVersion, - subresourceUris - ); + @JsonCreator + public static Status forValue(final String value) { + return Promoter.enumFromString(value, Status.values()); + } } - public enum AddressRetention { - RETAIN("retain"), - OBFUSCATE("obfuscate"); + public enum ScheduleType { + FIXED("fixed"); private final String value; - private AddressRetention(final String value) { + private ScheduleType(final String value) { this.value = value; } @@ -435,8 +200,8 @@ public String toString() { } @JsonCreator - public static AddressRetention forValue(final String value) { - return Promoter.enumFromString(value, AddressRetention.values()); + public static ScheduleType forValue(final String value) { + return Promoter.enumFromString(value, ScheduleType.values()); } } @@ -460,12 +225,12 @@ public static RiskCheck forValue(final String value) { } } - public enum TrafficType { - FREE("free"); + public enum UpdateStatus { + CANCELED("canceled"); private final String value; - private TrafficType(final String value) { + private UpdateStatus(final String value) { this.value = value; } @@ -474,17 +239,18 @@ public String toString() { } @JsonCreator - public static TrafficType forValue(final String value) { - return Promoter.enumFromString(value, TrafficType.values()); + public static UpdateStatus forValue(final String value) { + return Promoter.enumFromString(value, UpdateStatus.values()); } } - public enum UpdateStatus { - CANCELED("canceled"); + public enum ContentRetention { + RETAIN("retain"), + DISCARD("discard"); private final String value; - private UpdateStatus(final String value) { + private ContentRetention(final String value) { this.value = value; } @@ -493,8 +259,28 @@ public String toString() { } @JsonCreator - public static UpdateStatus forValue(final String value) { - return Promoter.enumFromString(value, UpdateStatus.values()); + public static ContentRetention forValue(final String value) { + return Promoter.enumFromString(value, ContentRetention.values()); + } + } + + public enum AddressRetention { + RETAIN("retain"), + OBFUSCATE("obfuscate"); + + private final String value; + + private AddressRetention(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static AddressRetention forValue(final String value) { + return Promoter.enumFromString(value, AddressRetention.values()); } } @@ -520,12 +306,12 @@ public static Direction forValue(final String value) { } } - public enum ScheduleType { - FIXED("fixed"); + public enum TrafficType { + FREE("free"); private final String value; - private ScheduleType(final String value) { + private TrafficType(final String value) { this.value = value; } @@ -534,59 +320,213 @@ public String toString() { } @JsonCreator - public static ScheduleType forValue(final String value) { - return Promoter.enumFromString(value, ScheduleType.values()); + public static TrafficType forValue(final String value) { + return Promoter.enumFromString(value, TrafficType.values()); } } - public enum ContentRetention { - RETAIN("retain"), - DISCARD("discard"); - private final String value; - - private ContentRetention(final String value) { - this.value = value; + /** + * Converts a JSON String into a Message object using the provided ObjectMapper. + * + * @param json Raw JSON String + * @param objectMapper Jackson ObjectMapper + * @return Message object represented by the provided JSON + */ + public static Message fromJson(final String json, final ObjectMapper objectMapper) { + // Convert all checked exceptions to Runtime + try { + return objectMapper.readValue(json, Message.class); + } catch (final JsonMappingException | JsonParseException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); } + } - public String toString() { - return value; + /** + * Converts a JSON InputStream into a Message object using the provided + * ObjectMapper. + * + * @param json Raw JSON InputStream + * @param objectMapper Jackson ObjectMapper + * @return Message object represented by the provided JSON + */ + public static Message fromJson(final InputStream json, final ObjectMapper objectMapper) { + // Convert all checked exceptions to Runtime + try { + return objectMapper.readValue(json, Message.class); + } catch (final JsonMappingException | JsonParseException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); } + } - @JsonCreator - public static ContentRetention forValue(final String value) { - return Promoter.enumFromString(value, ContentRetention.values()); + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); } } - public enum Status { - QUEUED("queued"), - SENDING("sending"), - SENT("sent"), - FAILED("failed"), - DELIVERED("delivered"), - UNDELIVERED("undelivered"), - RECEIVING("receiving"), - RECEIVED("received"), - ACCEPTED("accepted"), - SCHEDULED("scheduled"), - READ("read"), - PARTIALLY_DELIVERED("partially_delivered"), - CANCELED("canceled"); - private final String value; + @Getter + private final String accountSid; + @Getter + private final String apiVersion; + @Getter + private final String body; + @Getter + private final ZonedDateTime dateCreated; + @Getter + private final ZonedDateTime dateSent; + @Getter + private final ZonedDateTime dateUpdated; + @Getter + private final Message.Direction direction; + @Getter + private final Integer errorCode; + @Getter + private final String errorMessage; + @Getter + private final com.twilio.type.PhoneNumber from; + @Getter + private final String messagingServiceSid; + @Getter + private final String numMedia; + @Getter + private final String numSegments; + @Getter + private final String price; + @Getter + private final Currency priceUnit; + @Getter + private final String sid; + @Getter + private final Message.Status status; + @Getter + private final Map subresourceUris; + @Getter + private final String to; + @Getter + private final String uri; - private Status(final String value) { - this.value = value; - } + @JsonCreator + private Message( + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("api_version") final String apiVersion, + @JsonProperty("body") final String body, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.RFC2822Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_sent") + @JsonDeserialize(using = com.twilio.converter.RFC2822Deserializer.class) final ZonedDateTime dateSent, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.RFC2822Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("direction") final Message.Direction direction, + @JsonProperty("error_code") final Integer errorCode, + @JsonProperty("error_message") final String errorMessage, + @JsonProperty("from") final com.twilio.type.PhoneNumber from, + @JsonProperty("messaging_service_sid") final String messagingServiceSid, + @JsonProperty("num_media") final String numMedia, + @JsonProperty("num_segments") final String numSegments, + @JsonProperty("price") final String price, + @JsonProperty("price_unit") + @JsonDeserialize(using = com.twilio.converter.CurrencyDeserializer.class) final Currency priceUnit, + @JsonProperty("sid") final String sid, + @JsonProperty("status") final Message.Status status, + @JsonProperty("subresource_uris") final Map subresourceUris, + @JsonProperty("to") final String to, + @JsonProperty("uri") final String uri + ) { + this.accountSid = accountSid; + this.apiVersion = apiVersion; + this.body = body; + this.dateCreated = dateCreated; + this.dateSent = dateSent; + this.dateUpdated = dateUpdated; + this.direction = direction; + this.errorCode = errorCode; + this.errorMessage = errorMessage; + this.from = from; + this.messagingServiceSid = messagingServiceSid; + this.numMedia = numMedia; + this.numSegments = numSegments; + this.price = price; + this.priceUnit = priceUnit; + this.sid = sid; + this.status = status; + this.subresourceUris = subresourceUris; + this.to = to; + this.uri = uri; + } - public String toString() { - return value; + @Override + public boolean equals(final Object o) { + if (this == o) { + return true; } - @JsonCreator - public static Status forValue(final String value) { - return Promoter.enumFromString(value, Status.values()); + if (o == null || getClass() != o.getClass()) { + return false; } + + Message other = (Message) o; + return ( + Objects.equals(accountSid, other.accountSid) && + Objects.equals(apiVersion, other.apiVersion) && + Objects.equals(body, other.body) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateSent, other.dateSent) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(direction, other.direction) && + Objects.equals(errorCode, other.errorCode) && + Objects.equals(errorMessage, other.errorMessage) && + Objects.equals(from, other.from) && + Objects.equals(messagingServiceSid, other.messagingServiceSid) && + Objects.equals(numMedia, other.numMedia) && + Objects.equals(numSegments, other.numSegments) && + Objects.equals(price, other.price) && + Objects.equals(priceUnit, other.priceUnit) && + Objects.equals(sid, other.sid) && + Objects.equals(status, other.status) && + Objects.equals(subresourceUris, other.subresourceUris) && + Objects.equals(to, other.to) && + Objects.equals(uri, other.uri) + ); } + + @Override + public int hashCode() { + return Objects.hash( + accountSid, + apiVersion, + body, + dateCreated, + dateSent, + dateUpdated, + direction, + errorCode, + errorMessage, + from, + messagingServiceSid, + numMedia, + numSegments, + price, + priceUnit, + sid, + status, + subresourceUris, + to, + uri + ); + } + + } + diff --git a/src/main/java/com/twilio/rest/api/v2010/account/MessageCreator.java b/src/main/java/com/twilio/rest/api/v2010/account/MessageCreator.java index c938512a64..130dc3a3ae 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/MessageCreator.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/MessageCreator.java @@ -14,9 +14,12 @@ package com.twilio.rest.api.v2010.account; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; import com.twilio.converter.Promoter; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,18 +28,16 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -import java.math.BigDecimal; + import java.math.BigDecimal; import java.net.URI; -import java.net.URI; import java.time.ZonedDateTime; import java.util.List; -import java.util.List; public class MessageCreator extends Creator { + private String pathaccountSid; private com.twilio.type.PhoneNumber to; - private String pathAccountSid; private URI statusCallback; private String applicationSid; private BigDecimal maxPrice; @@ -61,94 +62,59 @@ public class MessageCreator extends Creator { private List mediaUrl; private String contentSid; - public MessageCreator( - final com.twilio.type.PhoneNumber to, - final com.twilio.type.PhoneNumber from, - final String body - ) { + public MessageCreator(final com.twilio.type.PhoneNumber to, final com.twilio.type.PhoneNumber from, final String body) { this.to = to; this.from = from; this.body = body; } - public MessageCreator( - final String pathAccountSid, - final com.twilio.type.PhoneNumber to, - final com.twilio.type.PhoneNumber from, - final String body - ) { - this.pathAccountSid = pathAccountSid; + public MessageCreator(final String pathaccountSid, final com.twilio.type.PhoneNumber to, final com.twilio.type.PhoneNumber from, final String body) { + this.pathaccountSid = pathaccountSid; this.to = to; this.from = from; this.body = body; } - public MessageCreator( - final com.twilio.type.PhoneNumber to, - final com.twilio.type.PhoneNumber from, - final List mediaUrl - ) { + public MessageCreator(final com.twilio.type.PhoneNumber to, final com.twilio.type.PhoneNumber from, final List mediaUrl) { this.to = to; this.from = from; this.mediaUrl = mediaUrl; } - public MessageCreator( - final String pathAccountSid, - final com.twilio.type.PhoneNumber to, - final com.twilio.type.PhoneNumber from, - final List mediaUrl - ) { - this.pathAccountSid = pathAccountSid; + public MessageCreator(final String pathaccountSid, final com.twilio.type.PhoneNumber to, final com.twilio.type.PhoneNumber from, final List mediaUrl) { + this.pathaccountSid = pathaccountSid; this.to = to; this.from = from; this.mediaUrl = mediaUrl; } - public MessageCreator( - final com.twilio.type.PhoneNumber to, - final String messagingServiceSid, - final String body - ) { + public MessageCreator(final com.twilio.type.PhoneNumber to, final String messagingServiceSid, final String body) { this.to = to; this.messagingServiceSid = messagingServiceSid; this.body = body; } - public MessageCreator( - final String pathAccountSid, - final com.twilio.type.PhoneNumber to, - final String messagingServiceSid, - final String body - ) { - this.pathAccountSid = pathAccountSid; + public MessageCreator(final String pathaccountSid, final com.twilio.type.PhoneNumber to, final String messagingServiceSid, final String body) { + this.pathaccountSid = pathaccountSid; this.to = to; this.messagingServiceSid = messagingServiceSid; this.body = body; } - public MessageCreator( - final com.twilio.type.PhoneNumber to, - final String messagingServiceSid, - final List mediaUrl - ) { + public MessageCreator(final com.twilio.type.PhoneNumber to, final String messagingServiceSid, final List mediaUrl) { this.to = to; this.messagingServiceSid = messagingServiceSid; this.mediaUrl = mediaUrl; } - public MessageCreator( - final String pathAccountSid, - final com.twilio.type.PhoneNumber to, - final String messagingServiceSid, - final List mediaUrl - ) { - this.pathAccountSid = pathAccountSid; + public MessageCreator(final String pathaccountSid, final com.twilio.type.PhoneNumber to, final String messagingServiceSid, final List mediaUrl) { + this.pathaccountSid = pathaccountSid; this.to = to; this.messagingServiceSid = messagingServiceSid; this.mediaUrl = mediaUrl; } + public MessageCreator setTo(final com.twilio.type.PhoneNumber to) { this.to = to; return this; @@ -163,62 +129,62 @@ public MessageCreator setStatusCallback(final URI statusCallback) { return this; } - public MessageCreator setStatusCallback(final String statusCallback) { - return setStatusCallback(Promoter.uriFromString(statusCallback)); - } public MessageCreator setApplicationSid(final String applicationSid) { this.applicationSid = applicationSid; return this; } + public MessageCreator setMaxPrice(final BigDecimal maxPrice) { this.maxPrice = maxPrice; return this; } + public MessageCreator setProvideFeedback(final Boolean provideFeedback) { this.provideFeedback = provideFeedback; return this; } + public MessageCreator setAttempt(final Integer attempt) { this.attempt = attempt; return this; } + public MessageCreator setValidityPeriod(final Integer validityPeriod) { this.validityPeriod = validityPeriod; return this; } + public MessageCreator setForceDelivery(final Boolean forceDelivery) { this.forceDelivery = forceDelivery; return this; } - public MessageCreator setContentRetention( - final Message.ContentRetention contentRetention - ) { + + public MessageCreator setContentRetention(final Message.ContentRetention contentRetention) { this.contentRetention = contentRetention; return this; } - public MessageCreator setAddressRetention( - final Message.AddressRetention addressRetention - ) { + + public MessageCreator setAddressRetention(final Message.AddressRetention addressRetention) { this.addressRetention = addressRetention; return this; } + public MessageCreator setSmartEncoded(final Boolean smartEncoded) { this.smartEncoded = smartEncoded; return this; } - public MessageCreator setPersistentAction( - final List persistentAction - ) { + + public MessageCreator setPersistentAction(final List persistentAction) { this.persistentAction = persistentAction; return this; } @@ -227,45 +193,48 @@ public MessageCreator setPersistentAction(final String persistentAction) { return setPersistentAction(Promoter.listOfOne(persistentAction)); } - public MessageCreator setTrafficType( - final Message.TrafficType trafficType - ) { + public MessageCreator setTrafficType(final Message.TrafficType trafficType) { this.trafficType = trafficType; return this; } + public MessageCreator setShortenUrls(final Boolean shortenUrls) { this.shortenUrls = shortenUrls; return this; } - public MessageCreator setScheduleType( - final Message.ScheduleType scheduleType - ) { + + public MessageCreator setScheduleType(final Message.ScheduleType scheduleType) { this.scheduleType = scheduleType; return this; } + public MessageCreator setSendAt(final ZonedDateTime sendAt) { this.sendAt = sendAt; return this; } + public MessageCreator setSendAsMms(final Boolean sendAsMms) { this.sendAsMms = sendAsMms; return this; } + public MessageCreator setContentVariables(final String contentVariables) { this.contentVariables = contentVariables; return this; } + public MessageCreator setRiskCheck(final Message.RiskCheck riskCheck) { this.riskCheck = riskCheck; return this; } + public MessageCreator setFrom(final com.twilio.type.PhoneNumber from) { this.from = from; return this; @@ -275,18 +244,18 @@ public MessageCreator setFrom(final String from) { return setFrom(Promoter.phoneNumberFromString(from)); } - public MessageCreator setMessagingServiceSid( - final String messagingServiceSid - ) { + public MessageCreator setMessagingServiceSid(final String messagingServiceSid) { this.messagingServiceSid = messagingServiceSid; return this; } + public MessageCreator setBody(final String body) { this.body = body; return this; } + public MessageCreator setMediaUrl(final List mediaUrl) { this.mediaUrl = mediaUrl; return this; @@ -296,52 +265,40 @@ public MessageCreator setMediaUrl(final URI mediaUrl) { return setMediaUrl(Promoter.listOfOne(mediaUrl)); } - public MessageCreator setMediaUrl(final String mediaUrl) { - return setMediaUrl(Promoter.uriFromString(mediaUrl)); - } - public MessageCreator setContentSid(final String contentSid) { this.contentSid = contentSid; return this; } + @Override public Message create(final TwilioRestClient client) { + String path = "/2010-04-01/Accounts/{AccountSid}/Messages.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = path.replace("{" + "To" + "}", this.to.toString()); + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.API.toString(), - path + HttpMethod.POST, + Domains.API.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Message creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("Message creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -350,87 +307,130 @@ public Message create(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (to != null) { - request.addPostParam("To", to.toString()); + Serializer.toString(request, "To", to, ParameterType.URLENCODED); } + + if (statusCallback != null) { - request.addPostParam("StatusCallback", statusCallback.toString()); + Serializer.toString(request, "StatusCallback", statusCallback, ParameterType.URLENCODED); } + + if (applicationSid != null) { - request.addPostParam("ApplicationSid", applicationSid); + Serializer.toString(request, "ApplicationSid", applicationSid, ParameterType.URLENCODED); } + + if (maxPrice != null) { - request.addPostParam("MaxPrice", maxPrice.toString()); + Serializer.toString(request, "MaxPrice", maxPrice, ParameterType.URLENCODED); } + + if (provideFeedback != null) { - request.addPostParam("ProvideFeedback", provideFeedback.toString()); + Serializer.toString(request, "ProvideFeedback", provideFeedback, ParameterType.URLENCODED); } + + if (attempt != null) { - request.addPostParam("Attempt", attempt.toString()); + Serializer.toString(request, "Attempt", attempt, ParameterType.URLENCODED); } + + if (validityPeriod != null) { - request.addPostParam("ValidityPeriod", validityPeriod.toString()); + Serializer.toString(request, "ValidityPeriod", validityPeriod, ParameterType.URLENCODED); } + + if (forceDelivery != null) { - request.addPostParam("ForceDelivery", forceDelivery.toString()); + Serializer.toString(request, "ForceDelivery", forceDelivery, ParameterType.URLENCODED); } + + if (contentRetention != null) { - request.addPostParam( - "ContentRetention", - contentRetention.toString() - ); + Serializer.toString(request, "ContentRetention", contentRetention, ParameterType.URLENCODED); } + + if (addressRetention != null) { - request.addPostParam( - "AddressRetention", - addressRetention.toString() - ); + Serializer.toString(request, "AddressRetention", addressRetention, ParameterType.URLENCODED); } + + if (smartEncoded != null) { - request.addPostParam("SmartEncoded", smartEncoded.toString()); + Serializer.toString(request, "SmartEncoded", smartEncoded, ParameterType.URLENCODED); } + + if (persistentAction != null) { - for (String prop : persistentAction) { - request.addPostParam("PersistentAction", prop); + for (String param : persistentAction) { + Serializer.toString(request, "PersistentAction", param, ParameterType.URLENCODED); } } + + if (trafficType != null) { - request.addPostParam("TrafficType", trafficType.toString()); + Serializer.toString(request, "TrafficType", trafficType, ParameterType.URLENCODED); } + + if (shortenUrls != null) { - request.addPostParam("ShortenUrls", shortenUrls.toString()); + Serializer.toString(request, "ShortenUrls", shortenUrls, ParameterType.URLENCODED); } + + if (scheduleType != null) { - request.addPostParam("ScheduleType", scheduleType.toString()); + Serializer.toString(request, "ScheduleType", scheduleType, ParameterType.URLENCODED); } + + if (sendAt != null) { - request.addPostParam("SendAt", sendAt.toInstant().toString()); + Serializer.toString(request, "SendAt", sendAt, ParameterType.URLENCODED); } + + if (sendAsMms != null) { - request.addPostParam("SendAsMms", sendAsMms.toString()); + Serializer.toString(request, "SendAsMms", sendAsMms, ParameterType.URLENCODED); } + + if (contentVariables != null) { - request.addPostParam("ContentVariables", contentVariables); + Serializer.toString(request, "ContentVariables", contentVariables, ParameterType.URLENCODED); } + + if (riskCheck != null) { - request.addPostParam("RiskCheck", riskCheck.toString()); + Serializer.toString(request, "RiskCheck", riskCheck, ParameterType.URLENCODED); } + + if (from != null) { - request.addPostParam("From", from.toString()); + Serializer.toString(request, "From", from, ParameterType.URLENCODED); } + + if (messagingServiceSid != null) { - request.addPostParam("MessagingServiceSid", messagingServiceSid); + Serializer.toString(request, "MessagingServiceSid", messagingServiceSid, ParameterType.URLENCODED); } + + if (body != null) { - request.addPostParam("Body", body); + Serializer.toString(request, "Body", body, ParameterType.URLENCODED); } + + if (mediaUrl != null) { - for (URI prop : mediaUrl) { - request.addPostParam("MediaUrl", prop.toString()); + for (URI param : mediaUrl) { + Serializer.toString(request, "MediaUrl", param, ParameterType.URLENCODED); } } + + if (contentSid != null) { - request.addPostParam("ContentSid", contentSid); + Serializer.toString(request, "ContentSid", contentSid, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/MessageDeleter.java b/src/main/java/com/twilio/rest/api/v2010/account/MessageDeleter.java index f2b7526a63..d7bf3ca144 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/MessageDeleter.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/MessageDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.api.v2010.account; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,55 +26,46 @@ public class MessageDeleter extends Deleter { - private String pathSid; - private String pathAccountSid; + private String pathaccountSid; + private String pathsid; - public MessageDeleter(final String pathSid) { - this.pathSid = pathSid; + public MessageDeleter(final String pathsid) { + this.pathsid = pathsid; } - public MessageDeleter(final String pathAccountSid, final String pathSid) { - this.pathAccountSid = pathAccountSid; - this.pathSid = pathSid; + public MessageDeleter(final String pathaccountSid, final String pathsid) { + this.pathaccountSid = pathaccountSid; + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/2010-04-01/Accounts/{AccountSid}/Messages/{Sid}.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.API.toString(), - path + HttpMethod.DELETE, + Domains.API.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Message delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("Message delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/MessageFetcher.java b/src/main/java/com/twilio/rest/api/v2010/account/MessageFetcher.java index d812229003..2a42850447 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/MessageFetcher.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/MessageFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.api.v2010.account; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,59 +26,49 @@ public class MessageFetcher extends Fetcher { - private String pathSid; - private String pathAccountSid; + private String pathaccountSid; + private String pathsid; - public MessageFetcher(final String pathSid) { - this.pathSid = pathSid; + public MessageFetcher(final String pathsid) { + this.pathsid = pathsid; } - public MessageFetcher(final String pathAccountSid, final String pathSid) { - this.pathAccountSid = pathAccountSid; - this.pathSid = pathSid; + public MessageFetcher(final String pathaccountSid, final String pathsid) { + this.pathaccountSid = pathaccountSid; + this.pathsid = pathsid; } + @Override public Message fetch(final TwilioRestClient client) { + String path = "/2010-04-01/Accounts/{AccountSid}/Messages/{Sid}.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.API.toString(), - path + HttpMethod.GET, + Domains.API.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Message fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Message fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Message.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/MessageReader.java b/src/main/java/com/twilio/rest/api/v2010/account/MessageReader.java index b3f6b38e68..7ae7e79855 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/MessageReader.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/MessageReader.java @@ -17,8 +17,9 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; import com.twilio.converter.Promoter; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,12 +28,12 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.time.ZonedDateTime; -import java.time.format.DateTimeFormatter; public class MessageReader extends Reader { - private String pathAccountSid; + private String pathaccountSid; private com.twilio.type.PhoneNumber to; private com.twilio.type.PhoneNumber from; private ZonedDateTime dateSent; @@ -40,12 +41,14 @@ public class MessageReader extends Reader { private ZonedDateTime dateSentAfter; private Long pageSize; - public MessageReader() {} + public MessageReader() { + } - public MessageReader(final String pathAccountSid) { - this.pathAccountSid = pathAccountSid; + public MessageReader(final String pathaccountSid) { + this.pathaccountSid = pathaccountSid; } + public MessageReader setTo(final com.twilio.type.PhoneNumber to) { this.to = to; return this; @@ -69,144 +72,119 @@ public MessageReader setDateSent(final ZonedDateTime dateSent) { return this; } + public MessageReader setDateSentBefore(final ZonedDateTime dateSentBefore) { this.dateSentBefore = dateSentBefore; return this; } + public MessageReader setDateSentAfter(final ZonedDateTime dateSentAfter) { this.dateSentAfter = dateSentAfter; return this; } + public MessageReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/2010-04-01/Accounts/{AccountSid}/Messages.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.API.toString(), - path + HttpMethod.GET, + Domains.API.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Message read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Message read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "messages", - response.getContent(), - Message.class, - client.getObjectMapper() - ); + "messages", + response.getContent(), + Message.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.API.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.API.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (to != null) { - request.addQueryParam("To", to.toString()); + Serializer.toString(request, "To", to, ParameterType.QUERY); } + + if (from != null) { - request.addQueryParam("From", from.toString()); + Serializer.toString(request, "From", from, ParameterType.QUERY); } + + if (dateSent != null) { - request.addQueryParam( - "DateSent", - dateSent.format( - DateTimeFormatter.ofPattern( - Request.QUERY_STRING_DATE_TIME_FORMAT - ) - ) - ); - } else if (dateSentAfter != null || dateSentBefore != null) { - request.addQueryDateTimeRange( - "DateSent", - dateSentAfter, - dateSentBefore - ); + Serializer.toString(request, "DateSent", dateSent, ParameterType.QUERY); } - if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + + + if (dateSentBefore != null) { + Serializer.toString(request, "DateSent<", dateSentBefore, ParameterType.QUERY); + } + + + if (dateSentAfter != null) { + Serializer.toString(request, "DateSent>", dateSentAfter, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); + + if (pageSize != null) { + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } + + } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/MessageUpdater.java b/src/main/java/com/twilio/rest/api/v2010/account/MessageUpdater.java index 1d5a48fd61..809e90a018 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/MessageUpdater.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/MessageUpdater.java @@ -16,6 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -26,68 +28,62 @@ import com.twilio.rest.Domains; public class MessageUpdater extends Updater { - - private String pathSid; - private String pathAccountSid; + private String pathaccountSid; + private String pathsid; private String body; private Message.UpdateStatus status; - public MessageUpdater(final String pathSid) { - this.pathSid = pathSid; + public MessageUpdater(final String pathsid) { + this.pathsid = pathsid; } - public MessageUpdater(final String pathAccountSid, final String pathSid) { - this.pathAccountSid = pathAccountSid; - this.pathSid = pathSid; + public MessageUpdater(final String pathaccountSid, final String pathsid) { + this.pathaccountSid = pathaccountSid; + this.pathsid = pathsid; } + public MessageUpdater setBody(final String body) { this.body = body; return this; } + public MessageUpdater setStatus(final Message.UpdateStatus status) { this.status = status; return this; } + @Override public Message update(final TwilioRestClient client) { + String path = "/2010-04-01/Accounts/{AccountSid}/Messages/{Sid}.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.API.toString(), - path + HttpMethod.POST, + Domains.API.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Message update failed: Unable to connect to server" - ); + throw new ApiConnectionException("Message update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -96,11 +92,16 @@ public Message update(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (body != null) { - request.addPostParam("Body", body); + Serializer.toString(request, "Body", body, ParameterType.URLENCODED); } + + if (status != null) { - request.addPostParam("Status", status.toString()); + Serializer.toString(request, "Status", status, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/NewKey.java b/src/main/java/com/twilio/rest/api/v2010/account/NewKey.java index 234fe5e285..c5e12525b1 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/NewKey.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/NewKey.java @@ -18,44 +18,48 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.time.ZonedDateTime; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class NewKey extends Resource { - private static final long serialVersionUID = 142441509867514L; public static NewKeyCreator creator() { - return new NewKeyCreator(); + return new NewKeyCreator( + + ); } - public static NewKeyCreator creator(final String pathAccountSid) { - return new NewKeyCreator(pathAccountSid); + + public static NewKeyCreator creator(final String pathaccountSid) { + return new NewKeyCreator( + pathaccountSid + ); } + /** * Converts a JSON String into a NewKey object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return NewKey object represented by the provided JSON */ - public static NewKey fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static NewKey fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, NewKey.class); @@ -70,14 +74,11 @@ public static NewKey fromJson( * Converts a JSON InputStream into a NewKey object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return NewKey object represented by the provided JSON */ - public static NewKey fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static NewKey fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, NewKey.class); @@ -88,45 +89,45 @@ public static NewKey fromJson( } } - private final String sid; - private final String friendlyName; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; + @Getter + private final String friendlyName; + @Getter private final String secret; + @Getter + private final String sid; @JsonCreator private NewKey( - @JsonProperty("sid") final String sid, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("secret") final String secret + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.RFC2822Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.RFC2822Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("secret") final String secret, + @JsonProperty("sid") final String sid ) { - this.sid = sid; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.friendlyName = friendlyName; - this.dateCreated = DateConverter.rfc2822DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.rfc2822DateTimeFromString(dateUpdated); this.secret = secret; - } - - public final String getSid() { - return this.sid; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final String getSecret() { - return this.secret; + this.sid = sid; } @Override @@ -140,24 +141,26 @@ public boolean equals(final Object o) { } NewKey other = (NewKey) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(secret, other.secret) + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(secret, other.secret) && + Objects.equals(sid, other.sid) ); } @Override public int hashCode() { return Objects.hash( - sid, - friendlyName, - dateCreated, - dateUpdated, - secret + dateCreated, + dateUpdated, + friendlyName, + secret, + sid ); } + + } + diff --git a/src/main/java/com/twilio/rest/api/v2010/account/NewKeyCreator.java b/src/main/java/com/twilio/rest/api/v2010/account/NewKeyCreator.java index 0a2c1226fc..c91e291687 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/NewKeyCreator.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/NewKeyCreator.java @@ -14,8 +14,11 @@ package com.twilio.rest.api.v2010.account; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,56 +30,51 @@ public class NewKeyCreator extends Creator { - private String pathAccountSid; + private String pathaccountSid; private String friendlyName; - public NewKeyCreator() {} + public NewKeyCreator() { + } - public NewKeyCreator(final String pathAccountSid) { - this.pathAccountSid = pathAccountSid; + public NewKeyCreator(final String pathaccountSid) { + this.pathaccountSid = pathaccountSid; } + public NewKeyCreator setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + @Override public NewKey create(final TwilioRestClient client) { + String path = "/2010-04-01/Accounts/{AccountSid}/Keys.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.API.toString(), - path + HttpMethod.POST, + Domains.API.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "NewKey creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("NewKey creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -85,8 +83,11 @@ public NewKey create(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/NewSigningKey.java b/src/main/java/com/twilio/rest/api/v2010/account/NewSigningKey.java index a8a1925ec4..9c7c984e3e 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/NewSigningKey.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/NewSigningKey.java @@ -18,44 +18,48 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.time.ZonedDateTime; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class NewSigningKey extends Resource { - private static final long serialVersionUID = 142441509867514L; public static NewSigningKeyCreator creator() { - return new NewSigningKeyCreator(); + return new NewSigningKeyCreator( + + ); } - public static NewSigningKeyCreator creator(final String pathAccountSid) { - return new NewSigningKeyCreator(pathAccountSid); + + public static NewSigningKeyCreator creator(final String pathaccountSid) { + return new NewSigningKeyCreator( + pathaccountSid + ); } + /** * Converts a JSON String into a NewSigningKey object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return NewSigningKey object represented by the provided JSON */ - public static NewSigningKey fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static NewSigningKey fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, NewSigningKey.class); @@ -70,14 +74,11 @@ public static NewSigningKey fromJson( * Converts a JSON InputStream into a NewSigningKey object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return NewSigningKey object represented by the provided JSON */ - public static NewSigningKey fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static NewSigningKey fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, NewSigningKey.class); @@ -88,45 +89,45 @@ public static NewSigningKey fromJson( } } - private final String sid; - private final String friendlyName; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; + @Getter + private final String friendlyName; + @Getter private final String secret; + @Getter + private final String sid; @JsonCreator private NewSigningKey( - @JsonProperty("sid") final String sid, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("secret") final String secret + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.RFC2822Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.RFC2822Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("secret") final String secret, + @JsonProperty("sid") final String sid ) { - this.sid = sid; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.friendlyName = friendlyName; - this.dateCreated = DateConverter.rfc2822DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.rfc2822DateTimeFromString(dateUpdated); this.secret = secret; - } - - public final String getSid() { - return this.sid; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final String getSecret() { - return this.secret; + this.sid = sid; } @Override @@ -140,24 +141,26 @@ public boolean equals(final Object o) { } NewSigningKey other = (NewSigningKey) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(secret, other.secret) + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(secret, other.secret) && + Objects.equals(sid, other.sid) ); } @Override public int hashCode() { return Objects.hash( - sid, - friendlyName, - dateCreated, - dateUpdated, - secret + dateCreated, + dateUpdated, + friendlyName, + secret, + sid ); } + + } + diff --git a/src/main/java/com/twilio/rest/api/v2010/account/NewSigningKeyCreator.java b/src/main/java/com/twilio/rest/api/v2010/account/NewSigningKeyCreator.java index 41bceac97a..b26475ca67 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/NewSigningKeyCreator.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/NewSigningKeyCreator.java @@ -14,8 +14,11 @@ package com.twilio.rest.api.v2010.account; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,69 +30,64 @@ public class NewSigningKeyCreator extends Creator { - private String pathAccountSid; + private String pathaccountSid; private String friendlyName; - public NewSigningKeyCreator() {} + public NewSigningKeyCreator() { + } - public NewSigningKeyCreator(final String pathAccountSid) { - this.pathAccountSid = pathAccountSid; + public NewSigningKeyCreator(final String pathaccountSid) { + this.pathaccountSid = pathaccountSid; } + public NewSigningKeyCreator setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + @Override public NewSigningKey create(final TwilioRestClient client) { + String path = "/2010-04-01/Accounts/{AccountSid}/SigningKeys.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.API.toString(), - path + HttpMethod.POST, + Domains.API.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "NewSigningKey creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("NewSigningKey creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return NewSigningKey.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return NewSigningKey.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/Notification.java b/src/main/java/com/twilio/rest/api/v2010/account/Notification.java index 455d8c991a..643e54214b 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/Notification.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/Notification.java @@ -18,57 +18,64 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.http.HttpMethod; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Notification extends Resource { - private static final long serialVersionUID = 162458167875227L; - public static NotificationFetcher fetcher(final String pathSid) { - return new NotificationFetcher(pathSid); + public static NotificationFetcher fetcher(final String pathsid) { + return new NotificationFetcher( + pathsid + ); } - public static NotificationFetcher fetcher( - final String pathAccountSid, - final String pathSid - ) { - return new NotificationFetcher(pathAccountSid, pathSid); + + public static NotificationFetcher fetcher(final String pathaccountSid, final String pathsid) { + return new NotificationFetcher( + pathaccountSid, pathsid + ); } + public static NotificationReader reader() { - return new NotificationReader(); + return new NotificationReader( + + ); } - public static NotificationReader reader(final String pathAccountSid) { - return new NotificationReader(pathAccountSid); + + public static NotificationReader reader(final String pathaccountSid) { + return new NotificationReader( + pathaccountSid + ); } + /** * Converts a JSON String into a Notification object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Notification object represented by the provided JSON */ - public static Notification fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Notification fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Notification.class); @@ -83,14 +90,11 @@ public static Notification fromJson( * Converts a JSON InputStream into a Notification object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Notification object represented by the provided JSON */ - public static Notification fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Notification fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Notification.class); @@ -101,52 +105,85 @@ public static Notification fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; + @Getter private final String apiVersion; + @Getter private final String callSid; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; + @Getter private final String errorCode; + @Getter private final String log; + @Getter private final ZonedDateTime messageDate; + @Getter private final String messageText; + @Getter private final URI moreInfo; + @Getter private final HttpMethod requestMethod; + @Getter private final URI requestUrl; + @Getter private final String requestVariables; + @Getter private final String responseBody; + @Getter private final String responseHeaders; + @Getter private final String sid; + @Getter private final String uri; @JsonCreator private Notification( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("api_version") final String apiVersion, - @JsonProperty("call_sid") final String callSid, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("error_code") final String errorCode, - @JsonProperty("log") final String log, - @JsonProperty("message_date") final String messageDate, - @JsonProperty("message_text") final String messageText, - @JsonProperty("more_info") final URI moreInfo, - @JsonProperty("request_method") final HttpMethod requestMethod, - @JsonProperty("request_url") final URI requestUrl, - @JsonProperty("request_variables") final String requestVariables, - @JsonProperty("response_body") final String responseBody, - @JsonProperty("response_headers") final String responseHeaders, - @JsonProperty("sid") final String sid, - @JsonProperty("uri") final String uri + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("api_version") final String apiVersion, + @JsonProperty("call_sid") final String callSid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.RFC2822Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.RFC2822Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("error_code") final String errorCode, + @JsonProperty("log") final String log, + @JsonProperty("message_date") + @JsonDeserialize(using = com.twilio.converter.RFC2822Deserializer.class) final ZonedDateTime messageDate, + @JsonProperty("message_text") final String messageText, + @JsonProperty("more_info") final URI moreInfo, + @JsonProperty("request_method") final HttpMethod requestMethod, + @JsonProperty("request_url") final URI requestUrl, + @JsonProperty("request_variables") final String requestVariables, + @JsonProperty("response_body") final String responseBody, + @JsonProperty("response_headers") final String responseHeaders, + @JsonProperty("sid") final String sid, + @JsonProperty("uri") final String uri ) { this.accountSid = accountSid; this.apiVersion = apiVersion; this.callSid = callSid; - this.dateCreated = DateConverter.rfc2822DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.rfc2822DateTimeFromString(dateUpdated); + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.errorCode = errorCode; this.log = log; - this.messageDate = DateConverter.rfc2822DateTimeFromString(messageDate); + this.messageDate = messageDate; this.messageText = messageText; this.moreInfo = moreInfo; this.requestMethod = requestMethod; @@ -158,74 +195,6 @@ private Notification( this.uri = uri; } - public final String getAccountSid() { - return this.accountSid; - } - - public final String getApiVersion() { - return this.apiVersion; - } - - public final String getCallSid() { - return this.callSid; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final String getErrorCode() { - return this.errorCode; - } - - public final String getLog() { - return this.log; - } - - public final ZonedDateTime getMessageDate() { - return this.messageDate; - } - - public final String getMessageText() { - return this.messageText; - } - - public final URI getMoreInfo() { - return this.moreInfo; - } - - public final HttpMethod getRequestMethod() { - return this.requestMethod; - } - - public final URI getRequestUrl() { - return this.requestUrl; - } - - public final String getRequestVariables() { - return this.requestVariables; - } - - public final String getResponseBody() { - return this.responseBody; - } - - public final String getResponseHeaders() { - return this.responseHeaders; - } - - public final String getSid() { - return this.sid; - } - - public final String getUri() { - return this.uri; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -237,48 +206,50 @@ public boolean equals(final Object o) { } Notification other = (Notification) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(apiVersion, other.apiVersion) && - Objects.equals(callSid, other.callSid) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(errorCode, other.errorCode) && - Objects.equals(log, other.log) && - Objects.equals(messageDate, other.messageDate) && - Objects.equals(messageText, other.messageText) && - Objects.equals(moreInfo, other.moreInfo) && - Objects.equals(requestMethod, other.requestMethod) && - Objects.equals(requestUrl, other.requestUrl) && - Objects.equals(requestVariables, other.requestVariables) && - Objects.equals(responseBody, other.responseBody) && - Objects.equals(responseHeaders, other.responseHeaders) && - Objects.equals(sid, other.sid) && - Objects.equals(uri, other.uri) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(apiVersion, other.apiVersion) && + Objects.equals(callSid, other.callSid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(errorCode, other.errorCode) && + Objects.equals(log, other.log) && + Objects.equals(messageDate, other.messageDate) && + Objects.equals(messageText, other.messageText) && + Objects.equals(moreInfo, other.moreInfo) && + Objects.equals(requestMethod, other.requestMethod) && + Objects.equals(requestUrl, other.requestUrl) && + Objects.equals(requestVariables, other.requestVariables) && + Objects.equals(responseBody, other.responseBody) && + Objects.equals(responseHeaders, other.responseHeaders) && + Objects.equals(sid, other.sid) && + Objects.equals(uri, other.uri) ); } @Override public int hashCode() { return Objects.hash( - accountSid, - apiVersion, - callSid, - dateCreated, - dateUpdated, - errorCode, - log, - messageDate, - messageText, - moreInfo, - requestMethod, - requestUrl, - requestVariables, - responseBody, - responseHeaders, - sid, - uri + accountSid, + apiVersion, + callSid, + dateCreated, + dateUpdated, + errorCode, + log, + messageDate, + messageText, + moreInfo, + requestMethod, + requestUrl, + requestVariables, + responseBody, + responseHeaders, + sid, + uri ); } + + } + diff --git a/src/main/java/com/twilio/rest/api/v2010/account/NotificationFetcher.java b/src/main/java/com/twilio/rest/api/v2010/account/NotificationFetcher.java index 51b5d5a11d..81ac6dd7df 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/NotificationFetcher.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/NotificationFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.api.v2010.account; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,66 +26,49 @@ public class NotificationFetcher extends Fetcher { - private String pathSid; - private String pathAccountSid; + private String pathaccountSid; + private String pathsid; - public NotificationFetcher(final String pathSid) { - this.pathSid = pathSid; + public NotificationFetcher(final String pathsid) { + this.pathsid = pathsid; } - public NotificationFetcher( - final String pathAccountSid, - final String pathSid - ) { - this.pathAccountSid = pathAccountSid; - this.pathSid = pathSid; + public NotificationFetcher(final String pathaccountSid, final String pathsid) { + this.pathaccountSid = pathaccountSid; + this.pathsid = pathsid; } + @Override public Notification fetch(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/Notifications/{Sid}.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/2010-04-01/Accounts/{AccountSid}/Notifications/{Sid}.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.API.toString(), - path + HttpMethod.GET, + Domains.API.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Notification fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Notification fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return Notification.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Notification.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/NotificationReader.java b/src/main/java/com/twilio/rest/api/v2010/account/NotificationReader.java index 525003a8a1..b076497cb9 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/NotificationReader.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/NotificationReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -26,173 +27,145 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.time.LocalDate; -import java.time.format.DateTimeFormatter; public class NotificationReader extends Reader { - private String pathAccountSid; + private String pathaccountSid; private Integer log; private LocalDate messageDate; private LocalDate messageDateBefore; private LocalDate messageDateAfter; private Long pageSize; - public NotificationReader() {} + public NotificationReader() { + } - public NotificationReader(final String pathAccountSid) { - this.pathAccountSid = pathAccountSid; + public NotificationReader(final String pathaccountSid) { + this.pathaccountSid = pathaccountSid; } + public NotificationReader setLog(final Integer log) { this.log = log; return this; } + public NotificationReader setMessageDate(final LocalDate messageDate) { this.messageDate = messageDate; return this; } - public NotificationReader setMessageDateBefore( - final LocalDate messageDateBefore - ) { + + public NotificationReader setMessageDateBefore(final LocalDate messageDateBefore) { this.messageDateBefore = messageDateBefore; return this; } - public NotificationReader setMessageDateAfter( - final LocalDate messageDateAfter - ) { + + public NotificationReader setMessageDateAfter(final LocalDate messageDateAfter) { this.messageDateAfter = messageDateAfter; return this; } + public NotificationReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/2010-04-01/Accounts/{AccountSid}/Notifications.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.API.toString(), - path + HttpMethod.GET, + Domains.API.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Notification read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Notification read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "notifications", - response.getContent(), - Notification.class, - client.getObjectMapper() - ); + "notifications", + response.getContent(), + Notification.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.API.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.API.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (log != null) { - request.addQueryParam("Log", log.toString()); + Serializer.toString(request, "Log", log, ParameterType.QUERY); } + + if (messageDate != null) { - request.addQueryParam( - "MessageDate", - messageDate.format( - DateTimeFormatter.ofPattern( - Request.QUERY_STRING_DATE_FORMAT - ) - ) - ); - } else if (messageDateAfter != null || messageDateBefore != null) { - request.addQueryDateRange( - "MessageDate", - messageDateAfter, - messageDateBefore - ); + Serializer.toString(request, "MessageDate", messageDate, ParameterType.QUERY); } - if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + + + if (messageDateBefore != null) { + Serializer.toString(request, "MessageDate<", messageDateBefore, ParameterType.QUERY); + } + + + if (messageDateAfter != null) { + Serializer.toString(request, "MessageDate>", messageDateAfter, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); + + if (pageSize != null) { + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } + + } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/OutgoingCallerId.java b/src/main/java/com/twilio/rest/api/v2010/account/OutgoingCallerId.java index 40f1bd6469..f23b2149a7 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/OutgoingCallerId.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/OutgoingCallerId.java @@ -18,77 +18,90 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.time.ZonedDateTime; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class OutgoingCallerId extends Resource { - private static final long serialVersionUID = 75956517535233L; - public static OutgoingCallerIdDeleter deleter(final String pathSid) { - return new OutgoingCallerIdDeleter(pathSid); + public static OutgoingCallerIdDeleter deleter(final String pathsid) { + return new OutgoingCallerIdDeleter( + pathsid + ); } - public static OutgoingCallerIdDeleter deleter( - final String pathAccountSid, - final String pathSid - ) { - return new OutgoingCallerIdDeleter(pathAccountSid, pathSid); + + public static OutgoingCallerIdDeleter deleter(final String pathaccountSid, final String pathsid) { + return new OutgoingCallerIdDeleter( + pathaccountSid, pathsid + ); } - public static OutgoingCallerIdFetcher fetcher(final String pathSid) { - return new OutgoingCallerIdFetcher(pathSid); + + public static OutgoingCallerIdFetcher fetcher(final String pathsid) { + return new OutgoingCallerIdFetcher( + pathsid + ); } - public static OutgoingCallerIdFetcher fetcher( - final String pathAccountSid, - final String pathSid - ) { - return new OutgoingCallerIdFetcher(pathAccountSid, pathSid); + + public static OutgoingCallerIdFetcher fetcher(final String pathaccountSid, final String pathsid) { + return new OutgoingCallerIdFetcher( + pathaccountSid, pathsid + ); } + public static OutgoingCallerIdReader reader() { - return new OutgoingCallerIdReader(); + return new OutgoingCallerIdReader( + + ); } - public static OutgoingCallerIdReader reader(final String pathAccountSid) { - return new OutgoingCallerIdReader(pathAccountSid); + + public static OutgoingCallerIdReader reader(final String pathaccountSid) { + return new OutgoingCallerIdReader( + pathaccountSid + ); } - public static OutgoingCallerIdUpdater updater(final String pathSid) { - return new OutgoingCallerIdUpdater(pathSid); + + public static OutgoingCallerIdUpdater updater(final String pathsid) { + return new OutgoingCallerIdUpdater( + pathsid + ); } - public static OutgoingCallerIdUpdater updater( - final String pathAccountSid, - final String pathSid - ) { - return new OutgoingCallerIdUpdater(pathAccountSid, pathSid); + + public static OutgoingCallerIdUpdater updater(final String pathaccountSid, final String pathsid) { + return new OutgoingCallerIdUpdater( + pathaccountSid, pathsid + ); } + /** * Converts a JSON String into a OutgoingCallerId object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return OutgoingCallerId object represented by the provided JSON */ - public static OutgoingCallerId fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static OutgoingCallerId fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, OutgoingCallerId.class); @@ -103,14 +116,11 @@ public static OutgoingCallerId fromJson( * Converts a JSON InputStream into a OutgoingCallerId object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return OutgoingCallerId object represented by the provided JSON */ - public static OutgoingCallerId fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static OutgoingCallerId fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, OutgoingCallerId.class); @@ -121,63 +131,55 @@ public static OutgoingCallerId fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter + private final String accountSid; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; + @Getter private final String friendlyName; - private final String accountSid; + @Getter private final com.twilio.type.PhoneNumber phoneNumber; + @Getter + private final String sid; + @Getter private final String uri; @JsonCreator private OutgoingCallerId( - @JsonProperty("sid") final String sid, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty( - "phone_number" - ) final com.twilio.type.PhoneNumber phoneNumber, - @JsonProperty("uri") final String uri + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.RFC2822Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.RFC2822Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("phone_number") final com.twilio.type.PhoneNumber phoneNumber, + @JsonProperty("sid") final String sid, + @JsonProperty("uri") final String uri ) { - this.sid = sid; - this.dateCreated = DateConverter.rfc2822DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.rfc2822DateTimeFromString(dateUpdated); - this.friendlyName = friendlyName; this.accountSid = accountSid; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; + this.friendlyName = friendlyName; this.phoneNumber = phoneNumber; + this.sid = sid; this.uri = uri; } - public final String getSid() { - return this.sid; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final com.twilio.type.PhoneNumber getPhoneNumber() { - return this.phoneNumber; - } - - public final String getUri() { - return this.uri; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -189,28 +191,30 @@ public boolean equals(final Object o) { } OutgoingCallerId other = (OutgoingCallerId) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(phoneNumber, other.phoneNumber) && - Objects.equals(uri, other.uri) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(phoneNumber, other.phoneNumber) && + Objects.equals(sid, other.sid) && + Objects.equals(uri, other.uri) ); } @Override public int hashCode() { return Objects.hash( - sid, - dateCreated, - dateUpdated, - friendlyName, - accountSid, - phoneNumber, - uri + accountSid, + dateCreated, + dateUpdated, + friendlyName, + phoneNumber, + sid, + uri ); } + + } + diff --git a/src/main/java/com/twilio/rest/api/v2010/account/OutgoingCallerIdDeleter.java b/src/main/java/com/twilio/rest/api/v2010/account/OutgoingCallerIdDeleter.java index b2c9fff3f3..cc0eed260e 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/OutgoingCallerIdDeleter.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/OutgoingCallerIdDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.api.v2010.account; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,59 +26,46 @@ public class OutgoingCallerIdDeleter extends Deleter { - private String pathSid; - private String pathAccountSid; + private String pathaccountSid; + private String pathsid; - public OutgoingCallerIdDeleter(final String pathSid) { - this.pathSid = pathSid; + public OutgoingCallerIdDeleter(final String pathsid) { + this.pathsid = pathsid; } - public OutgoingCallerIdDeleter( - final String pathAccountSid, - final String pathSid - ) { - this.pathAccountSid = pathAccountSid; - this.pathSid = pathSid; + public OutgoingCallerIdDeleter(final String pathaccountSid, final String pathsid) { + this.pathaccountSid = pathaccountSid; + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/OutgoingCallerIds/{Sid}.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/2010-04-01/Accounts/{AccountSid}/OutgoingCallerIds/{Sid}.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.API.toString(), - path + HttpMethod.DELETE, + Domains.API.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "OutgoingCallerId delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("OutgoingCallerId delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/OutgoingCallerIdFetcher.java b/src/main/java/com/twilio/rest/api/v2010/account/OutgoingCallerIdFetcher.java index 6360c25a3c..50345d9cb8 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/OutgoingCallerIdFetcher.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/OutgoingCallerIdFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.api.v2010.account; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,66 +26,49 @@ public class OutgoingCallerIdFetcher extends Fetcher { - private String pathSid; - private String pathAccountSid; + private String pathaccountSid; + private String pathsid; - public OutgoingCallerIdFetcher(final String pathSid) { - this.pathSid = pathSid; + public OutgoingCallerIdFetcher(final String pathsid) { + this.pathsid = pathsid; } - public OutgoingCallerIdFetcher( - final String pathAccountSid, - final String pathSid - ) { - this.pathAccountSid = pathAccountSid; - this.pathSid = pathSid; + public OutgoingCallerIdFetcher(final String pathaccountSid, final String pathsid) { + this.pathaccountSid = pathaccountSid; + this.pathsid = pathsid; } + @Override public OutgoingCallerId fetch(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/OutgoingCallerIds/{Sid}.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/2010-04-01/Accounts/{AccountSid}/OutgoingCallerIds/{Sid}.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.API.toString(), - path + HttpMethod.GET, + Domains.API.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "OutgoingCallerId fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("OutgoingCallerId fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return OutgoingCallerId.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return OutgoingCallerId.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/OutgoingCallerIdReader.java b/src/main/java/com/twilio/rest/api/v2010/account/OutgoingCallerIdReader.java index 090c1887f3..5bdae7a169 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/OutgoingCallerIdReader.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/OutgoingCallerIdReader.java @@ -17,8 +17,9 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; import com.twilio.converter.Promoter; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -30,20 +31,20 @@ public class OutgoingCallerIdReader extends Reader { - private String pathAccountSid; + private String pathaccountSid; private com.twilio.type.PhoneNumber phoneNumber; private String friendlyName; private Long pageSize; - public OutgoingCallerIdReader() {} + public OutgoingCallerIdReader() { + } - public OutgoingCallerIdReader(final String pathAccountSid) { - this.pathAccountSid = pathAccountSid; + public OutgoingCallerIdReader(final String pathaccountSid) { + this.pathaccountSid = pathaccountSid; } - public OutgoingCallerIdReader setPhoneNumber( - final com.twilio.type.PhoneNumber phoneNumber - ) { + + public OutgoingCallerIdReader setPhoneNumber(final com.twilio.type.PhoneNumber phoneNumber) { this.phoneNumber = phoneNumber; return this; } @@ -57,119 +58,92 @@ public OutgoingCallerIdReader setFriendlyName(final String friendlyName) { return this; } + public OutgoingCallerIdReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/OutgoingCallerIds.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); + + String path = "/2010-04-01/Accounts/{AccountSid}/OutgoingCallerIds.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.API.toString(), - path + HttpMethod.GET, + Domains.API.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "OutgoingCallerId read failed: Unable to connect to server" - ); + throw new ApiConnectionException("OutgoingCallerId read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "outgoing_caller_ids", - response.getContent(), - OutgoingCallerId.class, - client.getObjectMapper() - ); + "outgoing_caller_ids", + response.getContent(), + OutgoingCallerId.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.API.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.API.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (phoneNumber != null) { - request.addQueryParam("PhoneNumber", phoneNumber.toString()); + Serializer.toString(request, "PhoneNumber", phoneNumber, ParameterType.QUERY); } + + if (friendlyName != null) { - request.addQueryParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.QUERY); } + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/OutgoingCallerIdUpdater.java b/src/main/java/com/twilio/rest/api/v2010/account/OutgoingCallerIdUpdater.java index 1ddd2018d2..efb1ce16e3 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/OutgoingCallerIdUpdater.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/OutgoingCallerIdUpdater.java @@ -16,6 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -26,79 +28,68 @@ import com.twilio.rest.Domains; public class OutgoingCallerIdUpdater extends Updater { - - private String pathSid; - private String pathAccountSid; + private String pathaccountSid; + private String pathsid; private String friendlyName; - public OutgoingCallerIdUpdater(final String pathSid) { - this.pathSid = pathSid; + public OutgoingCallerIdUpdater(final String pathsid) { + this.pathsid = pathsid; } - public OutgoingCallerIdUpdater( - final String pathAccountSid, - final String pathSid - ) { - this.pathAccountSid = pathAccountSid; - this.pathSid = pathSid; + public OutgoingCallerIdUpdater(final String pathaccountSid, final String pathsid) { + this.pathaccountSid = pathaccountSid; + this.pathsid = pathsid; } + public OutgoingCallerIdUpdater setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + @Override public OutgoingCallerId update(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/OutgoingCallerIds/{Sid}.json"; - - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + + String path = "/2010-04-01/Accounts/{AccountSid}/OutgoingCallerIds/{Sid}.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.API.toString(), - path + HttpMethod.POST, + Domains.API.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "OutgoingCallerId update failed: Unable to connect to server" - ); + throw new ApiConnectionException("OutgoingCallerId update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return OutgoingCallerId.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return OutgoingCallerId.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/Queue.java b/src/main/java/com/twilio/rest/api/v2010/account/Queue.java index 673d5f862b..a4e7a24d7a 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/Queue.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/Queue.java @@ -18,88 +18,104 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.time.ZonedDateTime; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Queue extends Resource { - private static final long serialVersionUID = 17909156629067L; public static QueueCreator creator(final String friendlyName) { - return new QueueCreator(friendlyName); + return new QueueCreator( + friendlyName + ); } - public static QueueCreator creator( - final String pathAccountSid, - final String friendlyName - ) { - return new QueueCreator(pathAccountSid, friendlyName); + + public static QueueCreator creator(final String pathaccountSid, final String friendlyName) { + return new QueueCreator( + pathaccountSid, friendlyName + ); } - public static QueueDeleter deleter(final String pathSid) { - return new QueueDeleter(pathSid); + + public static QueueDeleter deleter(final String pathsid) { + return new QueueDeleter( + pathsid + ); } - public static QueueDeleter deleter( - final String pathAccountSid, - final String pathSid - ) { - return new QueueDeleter(pathAccountSid, pathSid); + + public static QueueDeleter deleter(final String pathaccountSid, final String pathsid) { + return new QueueDeleter( + pathaccountSid, pathsid + ); } - public static QueueFetcher fetcher(final String pathSid) { - return new QueueFetcher(pathSid); + + public static QueueFetcher fetcher(final String pathsid) { + return new QueueFetcher( + pathsid + ); } - public static QueueFetcher fetcher( - final String pathAccountSid, - final String pathSid - ) { - return new QueueFetcher(pathAccountSid, pathSid); + + public static QueueFetcher fetcher(final String pathaccountSid, final String pathsid) { + return new QueueFetcher( + pathaccountSid, pathsid + ); } + public static QueueReader reader() { - return new QueueReader(); + return new QueueReader( + + ); } - public static QueueReader reader(final String pathAccountSid) { - return new QueueReader(pathAccountSid); + + public static QueueReader reader(final String pathaccountSid) { + return new QueueReader( + pathaccountSid + ); } - public static QueueUpdater updater(final String pathSid) { - return new QueueUpdater(pathSid); + + public static QueueUpdater updater(final String pathsid) { + return new QueueUpdater( + pathsid + ); } - public static QueueUpdater updater( - final String pathAccountSid, - final String pathSid - ) { - return new QueueUpdater(pathAccountSid, pathSid); + + public static QueueUpdater updater(final String pathaccountSid, final String pathsid) { + return new QueueUpdater( + pathaccountSid, pathsid + ); } + /** * Converts a JSON String into a Queue object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Queue object represented by the provided JSON */ - public static Queue fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Queue fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Queue.class); @@ -114,14 +130,11 @@ public static Queue fromJson( * Converts a JSON InputStream into a Queue object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Queue object represented by the provided JSON */ - public static Queue fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Queue fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Queue.class); @@ -132,73 +145,61 @@ public static Queue fromJson( } } - private final ZonedDateTime dateUpdated; - private final Integer currentSize; - private final String friendlyName; - private final String uri; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; + @Getter private final Integer averageWaitTime; - private final String sid; + @Getter + private final Integer currentSize; + @Getter private final ZonedDateTime dateCreated; + @Getter + private final ZonedDateTime dateUpdated; + @Getter + private final String friendlyName; + @Getter private final Integer maxSize; + @Getter + private final String sid; + @Getter + private final String uri; @JsonCreator private Queue( - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("current_size") final Integer currentSize, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("uri") final String uri, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("average_wait_time") final Integer averageWaitTime, - @JsonProperty("sid") final String sid, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("max_size") final Integer maxSize + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("average_wait_time") final Integer averageWaitTime, + @JsonProperty("current_size") final Integer currentSize, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.RFC2822Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.RFC2822Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("max_size") final Integer maxSize, + @JsonProperty("sid") final String sid, + @JsonProperty("uri") final String uri ) { - this.dateUpdated = DateConverter.rfc2822DateTimeFromString(dateUpdated); - this.currentSize = currentSize; - this.friendlyName = friendlyName; - this.uri = uri; this.accountSid = accountSid; this.averageWaitTime = averageWaitTime; - this.sid = sid; - this.dateCreated = DateConverter.rfc2822DateTimeFromString(dateCreated); + this.currentSize = currentSize; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; + this.friendlyName = friendlyName; this.maxSize = maxSize; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final Integer getCurrentSize() { - return this.currentSize; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final String getUri() { - return this.uri; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final Integer getAverageWaitTime() { - return this.averageWaitTime; - } - - public final String getSid() { - return this.sid; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final Integer getMaxSize() { - return this.maxSize; + this.sid = sid; + this.uri = uri; } @Override @@ -212,32 +213,34 @@ public boolean equals(final Object o) { } Queue other = (Queue) o; - return ( - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(currentSize, other.currentSize) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(uri, other.uri) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(averageWaitTime, other.averageWaitTime) && - Objects.equals(sid, other.sid) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(maxSize, other.maxSize) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(averageWaitTime, other.averageWaitTime) && + Objects.equals(currentSize, other.currentSize) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(maxSize, other.maxSize) && + Objects.equals(sid, other.sid) && + Objects.equals(uri, other.uri) ); } @Override public int hashCode() { return Objects.hash( - dateUpdated, - currentSize, - friendlyName, - uri, - accountSid, - averageWaitTime, - sid, - dateCreated, - maxSize + accountSid, + averageWaitTime, + currentSize, + dateCreated, + dateUpdated, + friendlyName, + maxSize, + sid, + uri ); } + + } + diff --git a/src/main/java/com/twilio/rest/api/v2010/account/QueueCreator.java b/src/main/java/com/twilio/rest/api/v2010/account/QueueCreator.java index 852a64f977..1edeb4ae82 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/QueueCreator.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/QueueCreator.java @@ -14,8 +14,11 @@ package com.twilio.rest.api.v2010.account; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,73 +30,60 @@ public class QueueCreator extends Creator { + private String pathaccountSid; private String friendlyName; - private String pathAccountSid; private Integer maxSize; public QueueCreator(final String friendlyName) { this.friendlyName = friendlyName; } - public QueueCreator( - final String pathAccountSid, - final String friendlyName - ) { - this.pathAccountSid = pathAccountSid; + public QueueCreator(final String pathaccountSid, final String friendlyName) { + this.pathaccountSid = pathaccountSid; this.friendlyName = friendlyName; } + public QueueCreator setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + public QueueCreator setMaxSize(final Integer maxSize) { this.maxSize = maxSize; return this; } + @Override public Queue create(final TwilioRestClient client) { + String path = "/2010-04-01/Accounts/{AccountSid}/Queues.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = - path.replace( - "{" + "FriendlyName" + "}", - this.friendlyName.toString() - ); + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.API.toString(), - path + HttpMethod.POST, + Domains.API.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Queue creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("Queue creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -102,11 +92,16 @@ public Queue create(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + if (maxSize != null) { - request.addPostParam("MaxSize", maxSize.toString()); + Serializer.toString(request, "MaxSize", maxSize, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/QueueDeleter.java b/src/main/java/com/twilio/rest/api/v2010/account/QueueDeleter.java index 0bbb6b99ed..e2ebb0f69c 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/QueueDeleter.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/QueueDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.api.v2010.account; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,55 +26,46 @@ public class QueueDeleter extends Deleter { - private String pathSid; - private String pathAccountSid; + private String pathaccountSid; + private String pathsid; - public QueueDeleter(final String pathSid) { - this.pathSid = pathSid; + public QueueDeleter(final String pathsid) { + this.pathsid = pathsid; } - public QueueDeleter(final String pathAccountSid, final String pathSid) { - this.pathAccountSid = pathAccountSid; - this.pathSid = pathSid; + public QueueDeleter(final String pathaccountSid, final String pathsid) { + this.pathaccountSid = pathaccountSid; + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/2010-04-01/Accounts/{AccountSid}/Queues/{Sid}.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.API.toString(), - path + HttpMethod.DELETE, + Domains.API.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Queue delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("Queue delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/QueueFetcher.java b/src/main/java/com/twilio/rest/api/v2010/account/QueueFetcher.java index ddcd56a56c..3f1062c85a 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/QueueFetcher.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/QueueFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.api.v2010.account; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,59 +26,49 @@ public class QueueFetcher extends Fetcher { - private String pathSid; - private String pathAccountSid; + private String pathaccountSid; + private String pathsid; - public QueueFetcher(final String pathSid) { - this.pathSid = pathSid; + public QueueFetcher(final String pathsid) { + this.pathsid = pathsid; } - public QueueFetcher(final String pathAccountSid, final String pathSid) { - this.pathAccountSid = pathAccountSid; - this.pathSid = pathSid; + public QueueFetcher(final String pathaccountSid, final String pathsid) { + this.pathaccountSid = pathaccountSid; + this.pathsid = pathsid; } + @Override public Queue fetch(final TwilioRestClient client) { + String path = "/2010-04-01/Accounts/{AccountSid}/Queues/{Sid}.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.API.toString(), - path + HttpMethod.GET, + Domains.API.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Queue fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Queue fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Queue.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/QueueReader.java b/src/main/java/com/twilio/rest/api/v2010/account/QueueReader.java index c13d27fed9..f159db95d0 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/QueueReader.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/QueueReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,121 +30,92 @@ public class QueueReader extends Reader { - private String pathAccountSid; + private String pathaccountSid; private Long pageSize; - public QueueReader() {} + public QueueReader() { + } - public QueueReader(final String pathAccountSid) { - this.pathAccountSid = pathAccountSid; + public QueueReader(final String pathaccountSid) { + this.pathaccountSid = pathaccountSid; } + public QueueReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/2010-04-01/Accounts/{AccountSid}/Queues.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.API.toString(), - path + HttpMethod.GET, + Domains.API.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Queue read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Queue read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "queues", - response.getContent(), - Queue.class, - client.getObjectMapper() - ); + "queues", + response.getContent(), + Queue.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.API.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.API.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/QueueUpdater.java b/src/main/java/com/twilio/rest/api/v2010/account/QueueUpdater.java index aee51bf132..3eb913ed79 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/QueueUpdater.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/QueueUpdater.java @@ -16,6 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -26,68 +28,62 @@ import com.twilio.rest.Domains; public class QueueUpdater extends Updater { - - private String pathSid; - private String pathAccountSid; + private String pathaccountSid; + private String pathsid; private String friendlyName; private Integer maxSize; - public QueueUpdater(final String pathSid) { - this.pathSid = pathSid; + public QueueUpdater(final String pathsid) { + this.pathsid = pathsid; } - public QueueUpdater(final String pathAccountSid, final String pathSid) { - this.pathAccountSid = pathAccountSid; - this.pathSid = pathSid; + public QueueUpdater(final String pathaccountSid, final String pathsid) { + this.pathaccountSid = pathaccountSid; + this.pathsid = pathsid; } + public QueueUpdater setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + public QueueUpdater setMaxSize(final Integer maxSize) { this.maxSize = maxSize; return this; } + @Override public Queue update(final TwilioRestClient client) { + String path = "/2010-04-01/Accounts/{AccountSid}/Queues/{Sid}.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.API.toString(), - path + HttpMethod.POST, + Domains.API.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Queue update failed: Unable to connect to server" - ); + throw new ApiConnectionException("Queue update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -96,11 +92,16 @@ public Queue update(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + if (maxSize != null) { - request.addPostParam("MaxSize", maxSize.toString()); + Serializer.toString(request, "MaxSize", maxSize, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/Recording.java b/src/main/java/com/twilio/rest/api/v2010/account/Recording.java index 88e79667f7..f9ae8ab598 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/Recording.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/Recording.java @@ -18,70 +18,130 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Recording extends Resource { - private static final long serialVersionUID = 8927692317007L; - public static RecordingDeleter deleter(final String pathSid) { - return new RecordingDeleter(pathSid); + public static RecordingDeleter deleter(final String pathsid) { + return new RecordingDeleter( + pathsid + ); } - public static RecordingDeleter deleter( - final String pathAccountSid, - final String pathSid - ) { - return new RecordingDeleter(pathAccountSid, pathSid); + + public static RecordingDeleter deleter(final String pathaccountSid, final String pathsid) { + return new RecordingDeleter( + pathaccountSid, pathsid + ); } - public static RecordingFetcher fetcher(final String pathSid) { - return new RecordingFetcher(pathSid); + + public static RecordingFetcher fetcher(final String pathsid) { + return new RecordingFetcher( + pathsid + ); } - public static RecordingFetcher fetcher( - final String pathAccountSid, - final String pathSid - ) { - return new RecordingFetcher(pathAccountSid, pathSid); + + public static RecordingFetcher fetcher(final String pathaccountSid, final String pathsid) { + return new RecordingFetcher( + pathaccountSid, pathsid + ); } + public static RecordingReader reader() { - return new RecordingReader(); + return new RecordingReader( + + ); + } + + + public static RecordingReader reader(final String pathaccountSid) { + return new RecordingReader( + pathaccountSid + ); + } + + + public enum Status { + IN_PROGRESS("in-progress"), + PAUSED("paused"), + STOPPED("stopped"), + PROCESSING("processing"), + COMPLETED("completed"), + ABSENT("absent"), + DELETED("deleted"); + + private final String value; + + private Status(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static Status forValue(final String value) { + return Promoter.enumFromString(value, Status.values()); + } } - public static RecordingReader reader(final String pathAccountSid) { - return new RecordingReader(pathAccountSid); + public enum Source { + DIAL_VERB("DialVerb"), + CONFERENCE("Conference"), + OUTBOUND_API("OutboundAPI"), + TRUNKING("Trunking"), + RECORD_VERB("RecordVerb"), + START_CALL_RECORDING_API("StartCallRecordingAPI"), + START_CONFERENCE_RECORDING_API("StartConferenceRecordingAPI"); + + private final String value; + + private Source(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static Source forValue(final String value) { + return Promoter.enumFromString(value, Source.values()); + } } + /** * Converts a JSON String into a Recording object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Recording object represented by the provided JSON */ - public static Recording fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Recording fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Recording.class); @@ -96,14 +156,11 @@ public static Recording fromJson( * Converts a JSON InputStream into a Recording object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Recording object represented by the provided JSON */ - public static Recording fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Recording fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Recording.class); @@ -114,149 +171,102 @@ public static Recording fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; + @Getter private final String apiVersion; + @Getter private final String callSid; + @Getter + private final Integer channels; + @Getter private final String conferenceSid; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; - private final ZonedDateTime startTime; + @Getter private final String duration; - private final String sid; + @Getter + private final Object encryptionDetails; + @Getter + private final Integer errorCode; + @Getter + private final URI mediaUrl; + @Getter private final String price; + @Getter private final String priceUnit; - private final Recording.Status status; - private final Integer channels; + @Getter + private final String sid; + @Getter private final Recording.Source source; - private final Integer errorCode; - private final String uri; - private final Map encryptionDetails; + @Getter + private final ZonedDateTime startTime; + @Getter + private final Recording.Status status; + @Getter private final Map subresourceUris; - private final URI mediaUrl; + @Getter + private final String uri; @JsonCreator private Recording( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("api_version") final String apiVersion, - @JsonProperty("call_sid") final String callSid, - @JsonProperty("conference_sid") final String conferenceSid, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("start_time") final String startTime, - @JsonProperty("duration") final String duration, - @JsonProperty("sid") final String sid, - @JsonProperty("price") final String price, - @JsonProperty("price_unit") final String priceUnit, - @JsonProperty("status") final Recording.Status status, - @JsonProperty("channels") final Integer channels, - @JsonProperty("source") final Recording.Source source, - @JsonProperty("error_code") final Integer errorCode, - @JsonProperty("uri") final String uri, - @JsonProperty("encryption_details") final Map< - String, - Object - > encryptionDetails, - @JsonProperty("subresource_uris") final Map< - String, - String - > subresourceUris, - @JsonProperty("media_url") final URI mediaUrl + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("api_version") final String apiVersion, + @JsonProperty("call_sid") final String callSid, + @JsonProperty("channels") final Integer channels, + @JsonProperty("conference_sid") final String conferenceSid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.RFC2822Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.RFC2822Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("duration") final String duration, + @JsonProperty("encryption_details") final Object encryptionDetails, + @JsonProperty("error_code") final Integer errorCode, + @JsonProperty("media_url") final URI mediaUrl, + @JsonProperty("price") final String price, + @JsonProperty("price_unit") final String priceUnit, + @JsonProperty("sid") final String sid, + @JsonProperty("source") final Recording.Source source, + @JsonProperty("start_time") + @JsonDeserialize(using = com.twilio.converter.RFC2822Deserializer.class) final ZonedDateTime startTime, + @JsonProperty("status") final Recording.Status status, + @JsonProperty("subresource_uris") final Map subresourceUris, + @JsonProperty("uri") final String uri ) { this.accountSid = accountSid; this.apiVersion = apiVersion; this.callSid = callSid; + this.channels = channels; this.conferenceSid = conferenceSid; - this.dateCreated = DateConverter.rfc2822DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.rfc2822DateTimeFromString(dateUpdated); - this.startTime = DateConverter.rfc2822DateTimeFromString(startTime); + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.duration = duration; - this.sid = sid; + this.encryptionDetails = encryptionDetails; + this.errorCode = errorCode; + this.mediaUrl = mediaUrl; this.price = price; this.priceUnit = priceUnit; - this.status = status; - this.channels = channels; + this.sid = sid; this.source = source; - this.errorCode = errorCode; - this.uri = uri; - this.encryptionDetails = encryptionDetails; + this.startTime = startTime; + this.status = status; this.subresourceUris = subresourceUris; - this.mediaUrl = mediaUrl; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getApiVersion() { - return this.apiVersion; - } - - public final String getCallSid() { - return this.callSid; - } - - public final String getConferenceSid() { - return this.conferenceSid; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final ZonedDateTime getStartTime() { - return this.startTime; - } - - public final String getDuration() { - return this.duration; - } - - public final String getSid() { - return this.sid; - } - - public final String getPrice() { - return this.price; - } - - public final String getPriceUnit() { - return this.priceUnit; - } - - public final Recording.Status getStatus() { - return this.status; - } - - public final Integer getChannels() { - return this.channels; - } - - public final Recording.Source getSource() { - return this.source; - } - - public final Integer getErrorCode() { - return this.errorCode; - } - - public final String getUri() { - return this.uri; - } - - public final Map getEncryptionDetails() { - return this.encryptionDetails; - } - - public final Map getSubresourceUris() { - return this.subresourceUris; - } - - public final URI getMediaUrl() { - return this.mediaUrl; + this.uri = uri; } @Override @@ -270,102 +280,54 @@ public boolean equals(final Object o) { } Recording other = (Recording) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(apiVersion, other.apiVersion) && - Objects.equals(callSid, other.callSid) && - Objects.equals(conferenceSid, other.conferenceSid) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(startTime, other.startTime) && - Objects.equals(duration, other.duration) && - Objects.equals(sid, other.sid) && - Objects.equals(price, other.price) && - Objects.equals(priceUnit, other.priceUnit) && - Objects.equals(status, other.status) && - Objects.equals(channels, other.channels) && - Objects.equals(source, other.source) && - Objects.equals(errorCode, other.errorCode) && - Objects.equals(uri, other.uri) && - Objects.equals(encryptionDetails, other.encryptionDetails) && - Objects.equals(subresourceUris, other.subresourceUris) && - Objects.equals(mediaUrl, other.mediaUrl) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(apiVersion, other.apiVersion) && + Objects.equals(callSid, other.callSid) && + Objects.equals(channels, other.channels) && + Objects.equals(conferenceSid, other.conferenceSid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(duration, other.duration) && + Objects.equals(encryptionDetails, other.encryptionDetails) && + Objects.equals(errorCode, other.errorCode) && + Objects.equals(mediaUrl, other.mediaUrl) && + Objects.equals(price, other.price) && + Objects.equals(priceUnit, other.priceUnit) && + Objects.equals(sid, other.sid) && + Objects.equals(source, other.source) && + Objects.equals(startTime, other.startTime) && + Objects.equals(status, other.status) && + Objects.equals(subresourceUris, other.subresourceUris) && + Objects.equals(uri, other.uri) ); } @Override public int hashCode() { return Objects.hash( - accountSid, - apiVersion, - callSid, - conferenceSid, - dateCreated, - dateUpdated, - startTime, - duration, - sid, - price, - priceUnit, - status, - channels, - source, - errorCode, - uri, - encryptionDetails, - subresourceUris, - mediaUrl + accountSid, + apiVersion, + callSid, + channels, + conferenceSid, + dateCreated, + dateUpdated, + duration, + encryptionDetails, + errorCode, + mediaUrl, + price, + priceUnit, + sid, + source, + startTime, + status, + subresourceUris, + uri ); } - public enum Source { - DIALVERB("DialVerb"), - CONFERENCE("Conference"), - OUTBOUNDAPI("OutboundAPI"), - TRUNKING("Trunking"), - RECORDVERB("RecordVerb"), - STARTCALLRECORDINGAPI("StartCallRecordingAPI"), - STARTCONFERENCERECORDINGAPI("StartConferenceRecordingAPI"); - - private final String value; - - private Source(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static Source forValue(final String value) { - return Promoter.enumFromString(value, Source.values()); - } - } - public enum Status { - IN_PROGRESS("in-progress"), - PAUSED("paused"), - STOPPED("stopped"), - PROCESSING("processing"), - COMPLETED("completed"), - ABSENT("absent"), - DELETED("deleted"); - - private final String value; - - private Status(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static Status forValue(final String value) { - return Promoter.enumFromString(value, Status.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/api/v2010/account/RecordingDeleter.java b/src/main/java/com/twilio/rest/api/v2010/account/RecordingDeleter.java index cec64a74e5..9a3da74b1a 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/RecordingDeleter.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/RecordingDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.api.v2010.account; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,55 +26,46 @@ public class RecordingDeleter extends Deleter { - private String pathSid; - private String pathAccountSid; + private String pathaccountSid; + private String pathsid; - public RecordingDeleter(final String pathSid) { - this.pathSid = pathSid; + public RecordingDeleter(final String pathsid) { + this.pathsid = pathsid; } - public RecordingDeleter(final String pathAccountSid, final String pathSid) { - this.pathAccountSid = pathAccountSid; - this.pathSid = pathSid; + public RecordingDeleter(final String pathaccountSid, final String pathsid) { + this.pathaccountSid = pathaccountSid; + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/2010-04-01/Accounts/{AccountSid}/Recordings/{Sid}.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.API.toString(), - path + HttpMethod.DELETE, + Domains.API.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Recording delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("Recording delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/RecordingFetcher.java b/src/main/java/com/twilio/rest/api/v2010/account/RecordingFetcher.java index 3245e8e80d..326947eacc 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/RecordingFetcher.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/RecordingFetcher.java @@ -15,7 +15,8 @@ package com.twilio.rest.api.v2010.account; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,80 +28,67 @@ public class RecordingFetcher extends Fetcher { - private String pathSid; - private String pathAccountSid; + private String pathaccountSid; + private String pathsid; private Boolean includeSoftDeleted; - public RecordingFetcher(final String pathSid) { - this.pathSid = pathSid; + public RecordingFetcher(final String pathsid) { + this.pathsid = pathsid; } - public RecordingFetcher(final String pathAccountSid, final String pathSid) { - this.pathAccountSid = pathAccountSid; - this.pathSid = pathSid; + public RecordingFetcher(final String pathaccountSid, final String pathsid) { + this.pathaccountSid = pathaccountSid; + this.pathsid = pathsid; } - public RecordingFetcher setIncludeSoftDeleted( - final Boolean includeSoftDeleted - ) { + + public RecordingFetcher setIncludeSoftDeleted(final Boolean includeSoftDeleted) { this.includeSoftDeleted = includeSoftDeleted; return this; } + @Override public Recording fetch(final TwilioRestClient client) { + String path = "/2010-04-01/Accounts/{AccountSid}/Recordings/{Sid}.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.API.toString(), - path + HttpMethod.GET, + Domains.API.toString(), + path ); addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Recording fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Recording fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return Recording.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Recording.fromJson(response.getStream(), client.getObjectMapper()); } private void addQueryParams(final Request request) { + + if (includeSoftDeleted != null) { - request.addQueryParam( - "IncludeSoftDeleted", - includeSoftDeleted.toString() - ); + Serializer.toString(request, "IncludeSoftDeleted", includeSoftDeleted, ParameterType.QUERY); } + + } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/RecordingReader.java b/src/main/java/com/twilio/rest/api/v2010/account/RecordingReader.java index d896119875..bef19dd510 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/RecordingReader.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/RecordingReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -26,12 +27,12 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.time.ZonedDateTime; -import java.time.format.DateTimeFormatter; public class RecordingReader extends Reader { - private String pathAccountSid; + private String pathaccountSid; private ZonedDateTime dateCreated; private ZonedDateTime dateCreatedBefore; private ZonedDateTime dateCreatedAfter; @@ -40,182 +41,155 @@ public class RecordingReader extends Reader { private Boolean includeSoftDeleted; private Long pageSize; - public RecordingReader() {} + public RecordingReader() { + } - public RecordingReader(final String pathAccountSid) { - this.pathAccountSid = pathAccountSid; + public RecordingReader(final String pathaccountSid) { + this.pathaccountSid = pathaccountSid; } + public RecordingReader setDateCreated(final ZonedDateTime dateCreated) { this.dateCreated = dateCreated; return this; } - public RecordingReader setDateCreatedBefore( - final ZonedDateTime dateCreatedBefore - ) { + + public RecordingReader setDateCreatedBefore(final ZonedDateTime dateCreatedBefore) { this.dateCreatedBefore = dateCreatedBefore; return this; } - public RecordingReader setDateCreatedAfter( - final ZonedDateTime dateCreatedAfter - ) { + + public RecordingReader setDateCreatedAfter(final ZonedDateTime dateCreatedAfter) { this.dateCreatedAfter = dateCreatedAfter; return this; } + public RecordingReader setCallSid(final String callSid) { this.callSid = callSid; return this; } + public RecordingReader setConferenceSid(final String conferenceSid) { this.conferenceSid = conferenceSid; return this; } - public RecordingReader setIncludeSoftDeleted( - final Boolean includeSoftDeleted - ) { + + public RecordingReader setIncludeSoftDeleted(final Boolean includeSoftDeleted) { this.includeSoftDeleted = includeSoftDeleted; return this; } + public RecordingReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/2010-04-01/Accounts/{AccountSid}/Recordings.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.API.toString(), - path + HttpMethod.GET, + Domains.API.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Recording read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Recording read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "recordings", - response.getContent(), - Recording.class, - client.getObjectMapper() - ); + "recordings", + response.getContent(), + Recording.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.API.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.API.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (dateCreated != null) { - request.addQueryParam( - "DateCreated", - dateCreated.format( - DateTimeFormatter.ofPattern( - Request.QUERY_STRING_DATE_TIME_FORMAT - ) - ) - ); - } else if (dateCreatedAfter != null || dateCreatedBefore != null) { - request.addQueryDateTimeRange( - "DateCreated", - dateCreatedAfter, - dateCreatedBefore - ); + Serializer.toString(request, "DateCreated", dateCreated, ParameterType.QUERY); + } + + + if (dateCreatedBefore != null) { + Serializer.toString(request, "DateCreated<", dateCreatedBefore, ParameterType.QUERY); + } + + + if (dateCreatedAfter != null) { + Serializer.toString(request, "DateCreated>", dateCreatedAfter, ParameterType.QUERY); } + + if (callSid != null) { - request.addQueryParam("CallSid", callSid); + Serializer.toString(request, "CallSid", callSid, ParameterType.QUERY); } + + if (conferenceSid != null) { - request.addQueryParam("ConferenceSid", conferenceSid); + Serializer.toString(request, "ConferenceSid", conferenceSid, ParameterType.QUERY); } + + if (includeSoftDeleted != null) { - request.addQueryParam( - "IncludeSoftDeleted", - includeSoftDeleted.toString() - ); + Serializer.toString(request, "IncludeSoftDeleted", includeSoftDeleted, ParameterType.QUERY); } + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/ShortCode.java b/src/main/java/com/twilio/rest/api/v2010/account/ShortCode.java index 810e86246f..3b67445cc2 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/ShortCode.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/ShortCode.java @@ -18,68 +18,78 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.http.HttpMethod; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class ShortCode extends Resource { - private static final long serialVersionUID = 169753160210519L; - public static ShortCodeFetcher fetcher(final String pathSid) { - return new ShortCodeFetcher(pathSid); + public static ShortCodeFetcher fetcher(final String pathsid) { + return new ShortCodeFetcher( + pathsid + ); } - public static ShortCodeFetcher fetcher( - final String pathAccountSid, - final String pathSid - ) { - return new ShortCodeFetcher(pathAccountSid, pathSid); + + public static ShortCodeFetcher fetcher(final String pathaccountSid, final String pathsid) { + return new ShortCodeFetcher( + pathaccountSid, pathsid + ); } + public static ShortCodeReader reader() { - return new ShortCodeReader(); + return new ShortCodeReader( + + ); } - public static ShortCodeReader reader(final String pathAccountSid) { - return new ShortCodeReader(pathAccountSid); + + public static ShortCodeReader reader(final String pathaccountSid) { + return new ShortCodeReader( + pathaccountSid + ); } - public static ShortCodeUpdater updater(final String pathSid) { - return new ShortCodeUpdater(pathSid); + + public static ShortCodeUpdater updater(final String pathsid) { + return new ShortCodeUpdater( + pathsid + ); } - public static ShortCodeUpdater updater( - final String pathAccountSid, - final String pathSid - ) { - return new ShortCodeUpdater(pathAccountSid, pathSid); + + public static ShortCodeUpdater updater(final String pathaccountSid, final String pathsid) { + return new ShortCodeUpdater( + pathaccountSid, pathsid + ); } + /** * Converts a JSON String into a ShortCode object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return ShortCode object represented by the provided JSON */ - public static ShortCode fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static ShortCode fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, ShortCode.class); @@ -94,14 +104,11 @@ public static ShortCode fromJson( * Converts a JSON InputStream into a ShortCode object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return ShortCode object represented by the provided JSON */ - public static ShortCode fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static ShortCode fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, ShortCode.class); @@ -112,38 +119,65 @@ public static ShortCode fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; + @Getter private final String apiVersion; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; + @Getter private final String friendlyName; + @Getter private final String shortCode; + @Getter private final String sid; + @Getter private final HttpMethod smsFallbackMethod; + @Getter private final URI smsFallbackUrl; + @Getter private final HttpMethod smsMethod; + @Getter private final URI smsUrl; + @Getter private final String uri; @JsonCreator private ShortCode( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("api_version") final String apiVersion, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("short_code") final String shortCode, - @JsonProperty("sid") final String sid, - @JsonProperty("sms_fallback_method") final HttpMethod smsFallbackMethod, - @JsonProperty("sms_fallback_url") final URI smsFallbackUrl, - @JsonProperty("sms_method") final HttpMethod smsMethod, - @JsonProperty("sms_url") final URI smsUrl, - @JsonProperty("uri") final String uri + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("api_version") final String apiVersion, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.RFC2822Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.RFC2822Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("short_code") final String shortCode, + @JsonProperty("sid") final String sid, + @JsonProperty("sms_fallback_method") final HttpMethod smsFallbackMethod, + @JsonProperty("sms_fallback_url") final URI smsFallbackUrl, + @JsonProperty("sms_method") final HttpMethod smsMethod, + @JsonProperty("sms_url") final URI smsUrl, + @JsonProperty("uri") final String uri ) { this.accountSid = accountSid; this.apiVersion = apiVersion; - this.dateCreated = DateConverter.rfc2822DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.rfc2822DateTimeFromString(dateUpdated); + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.friendlyName = friendlyName; this.shortCode = shortCode; this.sid = sid; @@ -154,54 +188,6 @@ private ShortCode( this.uri = uri; } - public final String getAccountSid() { - return this.accountSid; - } - - public final String getApiVersion() { - return this.apiVersion; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final String getShortCode() { - return this.shortCode; - } - - public final String getSid() { - return this.sid; - } - - public final HttpMethod getSmsFallbackMethod() { - return this.smsFallbackMethod; - } - - public final URI getSmsFallbackUrl() { - return this.smsFallbackUrl; - } - - public final HttpMethod getSmsMethod() { - return this.smsMethod; - } - - public final URI getSmsUrl() { - return this.smsUrl; - } - - public final String getUri() { - return this.uri; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -213,38 +199,40 @@ public boolean equals(final Object o) { } ShortCode other = (ShortCode) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(apiVersion, other.apiVersion) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(shortCode, other.shortCode) && - Objects.equals(sid, other.sid) && - Objects.equals(smsFallbackMethod, other.smsFallbackMethod) && - Objects.equals(smsFallbackUrl, other.smsFallbackUrl) && - Objects.equals(smsMethod, other.smsMethod) && - Objects.equals(smsUrl, other.smsUrl) && - Objects.equals(uri, other.uri) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(apiVersion, other.apiVersion) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(shortCode, other.shortCode) && + Objects.equals(sid, other.sid) && + Objects.equals(smsFallbackMethod, other.smsFallbackMethod) && + Objects.equals(smsFallbackUrl, other.smsFallbackUrl) && + Objects.equals(smsMethod, other.smsMethod) && + Objects.equals(smsUrl, other.smsUrl) && + Objects.equals(uri, other.uri) ); } @Override public int hashCode() { return Objects.hash( - accountSid, - apiVersion, - dateCreated, - dateUpdated, - friendlyName, - shortCode, - sid, - smsFallbackMethod, - smsFallbackUrl, - smsMethod, - smsUrl, - uri + accountSid, + apiVersion, + dateCreated, + dateUpdated, + friendlyName, + shortCode, + sid, + smsFallbackMethod, + smsFallbackUrl, + smsMethod, + smsUrl, + uri ); } + + } + diff --git a/src/main/java/com/twilio/rest/api/v2010/account/ShortCodeFetcher.java b/src/main/java/com/twilio/rest/api/v2010/account/ShortCodeFetcher.java index 834d6ca2a2..b554625775 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/ShortCodeFetcher.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/ShortCodeFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.api.v2010.account; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,63 +26,49 @@ public class ShortCodeFetcher extends Fetcher { - private String pathSid; - private String pathAccountSid; + private String pathaccountSid; + private String pathsid; - public ShortCodeFetcher(final String pathSid) { - this.pathSid = pathSid; + public ShortCodeFetcher(final String pathsid) { + this.pathsid = pathsid; } - public ShortCodeFetcher(final String pathAccountSid, final String pathSid) { - this.pathAccountSid = pathAccountSid; - this.pathSid = pathSid; + public ShortCodeFetcher(final String pathaccountSid, final String pathsid) { + this.pathaccountSid = pathaccountSid; + this.pathsid = pathsid; } + @Override public ShortCode fetch(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/SMS/ShortCodes/{Sid}.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/2010-04-01/Accounts/{AccountSid}/SMS/ShortCodes/{Sid}.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.API.toString(), - path + HttpMethod.GET, + Domains.API.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "ShortCode fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("ShortCode fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return ShortCode.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return ShortCode.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/ShortCodeReader.java b/src/main/java/com/twilio/rest/api/v2010/account/ShortCodeReader.java index 2549ce0c8c..d07c7f0ddc 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/ShortCodeReader.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/ShortCodeReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,139 +30,116 @@ public class ShortCodeReader extends Reader { - private String pathAccountSid; + private String pathaccountSid; private String friendlyName; private String shortCode; private Long pageSize; - public ShortCodeReader() {} + public ShortCodeReader() { + } - public ShortCodeReader(final String pathAccountSid) { - this.pathAccountSid = pathAccountSid; + public ShortCodeReader(final String pathaccountSid) { + this.pathaccountSid = pathaccountSid; } + public ShortCodeReader setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + public ShortCodeReader setShortCode(final String shortCode) { this.shortCode = shortCode; return this; } + public ShortCodeReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/2010-04-01/Accounts/{AccountSid}/SMS/ShortCodes.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.API.toString(), - path + HttpMethod.GET, + Domains.API.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "ShortCode read failed: Unable to connect to server" - ); + throw new ApiConnectionException("ShortCode read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "short_codes", - response.getContent(), - ShortCode.class, - client.getObjectMapper() - ); + "short_codes", + response.getContent(), + ShortCode.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.API.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.API.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (friendlyName != null) { - request.addQueryParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.QUERY); } + + if (shortCode != null) { - request.addQueryParam("ShortCode", shortCode); + Serializer.toString(request, "ShortCode", shortCode, ParameterType.QUERY); } + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/ShortCodeUpdater.java b/src/main/java/com/twilio/rest/api/v2010/account/ShortCodeUpdater.java index 70fae46c94..52176a07e4 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/ShortCodeUpdater.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/ShortCodeUpdater.java @@ -16,7 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; -import com.twilio.converter.Promoter; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,12 +26,12 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.net.URI; public class ShortCodeUpdater extends Updater { - - private String pathSid; - private String pathAccountSid; + private String pathaccountSid; + private String pathsid; private String friendlyName; private String apiVersion; private URI smsUrl; @@ -38,124 +39,119 @@ public class ShortCodeUpdater extends Updater { private URI smsFallbackUrl; private HttpMethod smsFallbackMethod; - public ShortCodeUpdater(final String pathSid) { - this.pathSid = pathSid; + public ShortCodeUpdater(final String pathsid) { + this.pathsid = pathsid; } - public ShortCodeUpdater(final String pathAccountSid, final String pathSid) { - this.pathAccountSid = pathAccountSid; - this.pathSid = pathSid; + public ShortCodeUpdater(final String pathaccountSid, final String pathsid) { + this.pathaccountSid = pathaccountSid; + this.pathsid = pathsid; } + public ShortCodeUpdater setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + public ShortCodeUpdater setApiVersion(final String apiVersion) { this.apiVersion = apiVersion; return this; } + public ShortCodeUpdater setSmsUrl(final URI smsUrl) { this.smsUrl = smsUrl; return this; } - public ShortCodeUpdater setSmsUrl(final String smsUrl) { - return setSmsUrl(Promoter.uriFromString(smsUrl)); - } public ShortCodeUpdater setSmsMethod(final HttpMethod smsMethod) { this.smsMethod = smsMethod; return this; } + public ShortCodeUpdater setSmsFallbackUrl(final URI smsFallbackUrl) { this.smsFallbackUrl = smsFallbackUrl; return this; } - public ShortCodeUpdater setSmsFallbackUrl(final String smsFallbackUrl) { - return setSmsFallbackUrl(Promoter.uriFromString(smsFallbackUrl)); - } - public ShortCodeUpdater setSmsFallbackMethod( - final HttpMethod smsFallbackMethod - ) { + public ShortCodeUpdater setSmsFallbackMethod(final HttpMethod smsFallbackMethod) { this.smsFallbackMethod = smsFallbackMethod; return this; } + @Override public ShortCode update(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/SMS/ShortCodes/{Sid}.json"; - - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + + String path = "/2010-04-01/Accounts/{AccountSid}/SMS/ShortCodes/{Sid}.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.API.toString(), - path + HttpMethod.POST, + Domains.API.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "ShortCode update failed: Unable to connect to server" - ); + throw new ApiConnectionException("ShortCode update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return ShortCode.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return ShortCode.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + if (apiVersion != null) { - request.addPostParam("ApiVersion", apiVersion); + Serializer.toString(request, "ApiVersion", apiVersion, ParameterType.URLENCODED); } + + if (smsUrl != null) { - request.addPostParam("SmsUrl", smsUrl.toString()); + Serializer.toString(request, "SmsUrl", smsUrl, ParameterType.URLENCODED); } + + if (smsMethod != null) { - request.addPostParam("SmsMethod", smsMethod.toString()); + Serializer.toString(request, "SmsMethod", smsMethod, ParameterType.URLENCODED); } + + if (smsFallbackUrl != null) { - request.addPostParam("SmsFallbackUrl", smsFallbackUrl.toString()); + Serializer.toString(request, "SmsFallbackUrl", smsFallbackUrl, ParameterType.URLENCODED); } + + if (smsFallbackMethod != null) { - request.addPostParam( - "SmsFallbackMethod", - smsFallbackMethod.toString() - ); + Serializer.toString(request, "SmsFallbackMethod", smsFallbackMethod, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/SigningKey.java b/src/main/java/com/twilio/rest/api/v2010/account/SigningKey.java index e8ee7a453d..12f8911b64 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/SigningKey.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/SigningKey.java @@ -18,77 +18,90 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.time.ZonedDateTime; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class SigningKey extends Resource { - private static final long serialVersionUID = 35259719636912L; - public static SigningKeyDeleter deleter(final String pathSid) { - return new SigningKeyDeleter(pathSid); + public static SigningKeyDeleter deleter(final String pathsid) { + return new SigningKeyDeleter( + pathsid + ); } - public static SigningKeyDeleter deleter( - final String pathAccountSid, - final String pathSid - ) { - return new SigningKeyDeleter(pathAccountSid, pathSid); + + public static SigningKeyDeleter deleter(final String pathaccountSid, final String pathsid) { + return new SigningKeyDeleter( + pathaccountSid, pathsid + ); } - public static SigningKeyFetcher fetcher(final String pathSid) { - return new SigningKeyFetcher(pathSid); + + public static SigningKeyFetcher fetcher(final String pathsid) { + return new SigningKeyFetcher( + pathsid + ); } - public static SigningKeyFetcher fetcher( - final String pathAccountSid, - final String pathSid - ) { - return new SigningKeyFetcher(pathAccountSid, pathSid); + + public static SigningKeyFetcher fetcher(final String pathaccountSid, final String pathsid) { + return new SigningKeyFetcher( + pathaccountSid, pathsid + ); } + public static SigningKeyReader reader() { - return new SigningKeyReader(); + return new SigningKeyReader( + + ); } - public static SigningKeyReader reader(final String pathAccountSid) { - return new SigningKeyReader(pathAccountSid); + + public static SigningKeyReader reader(final String pathaccountSid) { + return new SigningKeyReader( + pathaccountSid + ); } - public static SigningKeyUpdater updater(final String pathSid) { - return new SigningKeyUpdater(pathSid); + + public static SigningKeyUpdater updater(final String pathsid) { + return new SigningKeyUpdater( + pathsid + ); } - public static SigningKeyUpdater updater( - final String pathAccountSid, - final String pathSid - ) { - return new SigningKeyUpdater(pathAccountSid, pathSid); + + public static SigningKeyUpdater updater(final String pathaccountSid, final String pathsid) { + return new SigningKeyUpdater( + pathaccountSid, pathsid + ); } + /** * Converts a JSON String into a SigningKey object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return SigningKey object represented by the provided JSON */ - public static SigningKey fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static SigningKey fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, SigningKey.class); @@ -103,14 +116,11 @@ public static SigningKey fromJson( * Converts a JSON InputStream into a SigningKey object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return SigningKey object represented by the provided JSON */ - public static SigningKey fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static SigningKey fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, SigningKey.class); @@ -121,38 +131,41 @@ public static SigningKey fromJson( } } - private final String sid; - private final String friendlyName; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; + @Getter + private final String friendlyName; + @Getter + private final String sid; @JsonCreator private SigningKey( - @JsonProperty("sid") final String sid, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.RFC2822Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.RFC2822Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("sid") final String sid ) { - this.sid = sid; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.friendlyName = friendlyName; - this.dateCreated = DateConverter.rfc2822DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.rfc2822DateTimeFromString(dateUpdated); - } - - public final String getSid() { - return this.sid; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; + this.sid = sid; } @Override @@ -166,17 +179,24 @@ public boolean equals(final Object o) { } SigningKey other = (SigningKey) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(sid, other.sid) ); } @Override public int hashCode() { - return Objects.hash(sid, friendlyName, dateCreated, dateUpdated); + return Objects.hash( + dateCreated, + dateUpdated, + friendlyName, + sid + ); } + + } + diff --git a/src/main/java/com/twilio/rest/api/v2010/account/SigningKeyDeleter.java b/src/main/java/com/twilio/rest/api/v2010/account/SigningKeyDeleter.java index 511088924d..af59f1f000 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/SigningKeyDeleter.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/SigningKeyDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.api.v2010.account; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,59 +26,46 @@ public class SigningKeyDeleter extends Deleter { - private String pathSid; - private String pathAccountSid; + private String pathaccountSid; + private String pathsid; - public SigningKeyDeleter(final String pathSid) { - this.pathSid = pathSid; + public SigningKeyDeleter(final String pathsid) { + this.pathsid = pathsid; } - public SigningKeyDeleter( - final String pathAccountSid, - final String pathSid - ) { - this.pathAccountSid = pathAccountSid; - this.pathSid = pathSid; + public SigningKeyDeleter(final String pathaccountSid, final String pathsid) { + this.pathaccountSid = pathaccountSid; + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/SigningKeys/{Sid}.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/2010-04-01/Accounts/{AccountSid}/SigningKeys/{Sid}.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.API.toString(), - path + HttpMethod.DELETE, + Domains.API.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "SigningKey delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("SigningKey delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/SigningKeyFetcher.java b/src/main/java/com/twilio/rest/api/v2010/account/SigningKeyFetcher.java index 4ee0c47174..8ac4ca32d0 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/SigningKeyFetcher.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/SigningKeyFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.api.v2010.account; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,66 +26,49 @@ public class SigningKeyFetcher extends Fetcher { - private String pathSid; - private String pathAccountSid; + private String pathaccountSid; + private String pathsid; - public SigningKeyFetcher(final String pathSid) { - this.pathSid = pathSid; + public SigningKeyFetcher(final String pathsid) { + this.pathsid = pathsid; } - public SigningKeyFetcher( - final String pathAccountSid, - final String pathSid - ) { - this.pathAccountSid = pathAccountSid; - this.pathSid = pathSid; + public SigningKeyFetcher(final String pathaccountSid, final String pathsid) { + this.pathaccountSid = pathaccountSid; + this.pathsid = pathsid; } + @Override public SigningKey fetch(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/SigningKeys/{Sid}.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/2010-04-01/Accounts/{AccountSid}/SigningKeys/{Sid}.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.API.toString(), - path + HttpMethod.GET, + Domains.API.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "SigningKey fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("SigningKey fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return SigningKey.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return SigningKey.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/SigningKeyReader.java b/src/main/java/com/twilio/rest/api/v2010/account/SigningKeyReader.java index 803052972f..16f5099dfa 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/SigningKeyReader.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/SigningKeyReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,121 +30,92 @@ public class SigningKeyReader extends Reader { - private String pathAccountSid; + private String pathaccountSid; private Long pageSize; - public SigningKeyReader() {} + public SigningKeyReader() { + } - public SigningKeyReader(final String pathAccountSid) { - this.pathAccountSid = pathAccountSid; + public SigningKeyReader(final String pathaccountSid) { + this.pathaccountSid = pathaccountSid; } + public SigningKeyReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/2010-04-01/Accounts/{AccountSid}/SigningKeys.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.API.toString(), - path + HttpMethod.GET, + Domains.API.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "SigningKey read failed: Unable to connect to server" - ); + throw new ApiConnectionException("SigningKey read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "signing_keys", - response.getContent(), - SigningKey.class, - client.getObjectMapper() - ); + "signing_keys", + response.getContent(), + SigningKey.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.API.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.API.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/SigningKeyUpdater.java b/src/main/java/com/twilio/rest/api/v2010/account/SigningKeyUpdater.java index da7acf7d09..b6c0818a28 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/SigningKeyUpdater.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/SigningKeyUpdater.java @@ -16,6 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -26,79 +28,68 @@ import com.twilio.rest.Domains; public class SigningKeyUpdater extends Updater { - - private String pathSid; - private String pathAccountSid; + private String pathaccountSid; + private String pathsid; private String friendlyName; - public SigningKeyUpdater(final String pathSid) { - this.pathSid = pathSid; + public SigningKeyUpdater(final String pathsid) { + this.pathsid = pathsid; } - public SigningKeyUpdater( - final String pathAccountSid, - final String pathSid - ) { - this.pathAccountSid = pathAccountSid; - this.pathSid = pathSid; + public SigningKeyUpdater(final String pathaccountSid, final String pathsid) { + this.pathaccountSid = pathaccountSid; + this.pathsid = pathsid; } + public SigningKeyUpdater setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + @Override public SigningKey update(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/SigningKeys/{Sid}.json"; - - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + + String path = "/2010-04-01/Accounts/{AccountSid}/SigningKeys/{Sid}.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.API.toString(), - path + HttpMethod.POST, + Domains.API.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "SigningKey update failed: Unable to connect to server" - ); + throw new ApiConnectionException("SigningKey update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return SigningKey.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return SigningKey.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/Token.java b/src/main/java/com/twilio/rest/api/v2010/account/Token.java index 6ab0eff4fc..d2c6a826cd 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/Token.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/Token.java @@ -18,46 +18,50 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.type.IceServer; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.time.ZonedDateTime; import java.util.List; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Token extends Resource { - private static final long serialVersionUID = 218446728059095L; public static TokenCreator creator() { - return new TokenCreator(); + return new TokenCreator( + + ); } - public static TokenCreator creator(final String pathAccountSid) { - return new TokenCreator(pathAccountSid); + + public static TokenCreator creator(final String pathaccountSid) { + return new TokenCreator( + pathaccountSid + ); } + /** * Converts a JSON String into a Token object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Token object represented by the provided JSON */ - public static Token fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Token fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Token.class); @@ -72,14 +76,11 @@ public static Token fromJson( * Converts a JSON InputStream into a Token object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Token object represented by the provided JSON */ - public static Token fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Token fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Token.class); @@ -90,61 +91,55 @@ public static Token fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; + @Getter private final List iceServers; + @Getter private final String password; + @Getter private final String ttl; + @Getter private final String username; @JsonCreator private Token( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("ice_servers") final List iceServers, - @JsonProperty("password") final String password, - @JsonProperty("ttl") final String ttl, - @JsonProperty("username") final String username + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.RFC2822Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.RFC2822Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("ice_servers") final List iceServers, + @JsonProperty("password") final String password, + @JsonProperty("ttl") final String ttl, + @JsonProperty("username") final String username ) { this.accountSid = accountSid; - this.dateCreated = DateConverter.rfc2822DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.rfc2822DateTimeFromString(dateUpdated); + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.iceServers = iceServers; this.password = password; this.ttl = ttl; this.username = username; } - public final String getAccountSid() { - return this.accountSid; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final List getIceServers() { - return this.iceServers; - } - - public final String getPassword() { - return this.password; - } - - public final String getTtl() { - return this.ttl; - } - - public final String getUsername() { - return this.username; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -156,28 +151,30 @@ public boolean equals(final Object o) { } Token other = (Token) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(iceServers, other.iceServers) && - Objects.equals(password, other.password) && - Objects.equals(ttl, other.ttl) && - Objects.equals(username, other.username) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(iceServers, other.iceServers) && + Objects.equals(password, other.password) && + Objects.equals(ttl, other.ttl) && + Objects.equals(username, other.username) ); } @Override public int hashCode() { return Objects.hash( - accountSid, - dateCreated, - dateUpdated, - iceServers, - password, - ttl, - username + accountSid, + dateCreated, + dateUpdated, + iceServers, + password, + ttl, + username ); } + + } + diff --git a/src/main/java/com/twilio/rest/api/v2010/account/TokenCreator.java b/src/main/java/com/twilio/rest/api/v2010/account/TokenCreator.java index 4896759b74..97bae5b4f7 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/TokenCreator.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/TokenCreator.java @@ -14,8 +14,11 @@ package com.twilio.rest.api.v2010.account; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,56 +30,51 @@ public class TokenCreator extends Creator { - private String pathAccountSid; + private String pathaccountSid; private Integer ttl; - public TokenCreator() {} + public TokenCreator() { + } - public TokenCreator(final String pathAccountSid) { - this.pathAccountSid = pathAccountSid; + public TokenCreator(final String pathaccountSid) { + this.pathaccountSid = pathaccountSid; } + public TokenCreator setTtl(final Integer ttl) { this.ttl = ttl; return this; } + @Override public Token create(final TwilioRestClient client) { + String path = "/2010-04-01/Accounts/{AccountSid}/Tokens.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.API.toString(), - path + HttpMethod.POST, + Domains.API.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Token creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("Token creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -85,8 +83,11 @@ public Token create(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (ttl != null) { - request.addPostParam("Ttl", ttl.toString()); + Serializer.toString(request, "Ttl", ttl, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/Transcription.java b/src/main/java/com/twilio/rest/api/v2010/account/Transcription.java index a9525ed472..64c518211c 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/Transcription.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/Transcription.java @@ -18,71 +18,101 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.CurrencyDeserializer; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.math.BigDecimal; import java.time.ZonedDateTime; import java.util.Currency; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Transcription extends Resource { - private static final long serialVersionUID = 169453036448500L; - public static TranscriptionDeleter deleter(final String pathSid) { - return new TranscriptionDeleter(pathSid); + public static TranscriptionDeleter deleter(final String pathsid) { + return new TranscriptionDeleter( + pathsid + ); } - public static TranscriptionDeleter deleter( - final String pathAccountSid, - final String pathSid - ) { - return new TranscriptionDeleter(pathAccountSid, pathSid); + + public static TranscriptionDeleter deleter(final String pathaccountSid, final String pathsid) { + return new TranscriptionDeleter( + pathaccountSid, pathsid + ); } - public static TranscriptionFetcher fetcher(final String pathSid) { - return new TranscriptionFetcher(pathSid); + + public static TranscriptionFetcher fetcher(final String pathsid) { + return new TranscriptionFetcher( + pathsid + ); } - public static TranscriptionFetcher fetcher( - final String pathAccountSid, - final String pathSid - ) { - return new TranscriptionFetcher(pathAccountSid, pathSid); + + public static TranscriptionFetcher fetcher(final String pathaccountSid, final String pathsid) { + return new TranscriptionFetcher( + pathaccountSid, pathsid + ); } + public static TranscriptionReader reader() { - return new TranscriptionReader(); + return new TranscriptionReader( + + ); + } + + + public static TranscriptionReader reader(final String pathaccountSid) { + return new TranscriptionReader( + pathaccountSid + ); } - public static TranscriptionReader reader(final String pathAccountSid) { - return new TranscriptionReader(pathAccountSid); + + public enum Status { + IN_PROGRESS("in-progress"), + COMPLETED("completed"), + FAILED("failed"); + + private final String value; + + private Status(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static Status forValue(final String value) { + return Promoter.enumFromString(value, Status.values()); + } } + /** * Converts a JSON String into a Transcription object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Transcription object represented by the provided JSON */ - public static Transcription fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Transcription fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Transcription.class); @@ -97,14 +127,11 @@ public static Transcription fromJson( * Converts a JSON InputStream into a Transcription object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Transcription object represented by the provided JSON */ - public static Transcription fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Transcription fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Transcription.class); @@ -115,42 +142,69 @@ public static Transcription fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; + @Getter private final String apiVersion; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; + @Getter private final String duration; + @Getter private final BigDecimal price; + @Getter private final Currency priceUnit; + @Getter private final String recordingSid; + @Getter private final String sid; + @Getter private final Transcription.Status status; + @Getter private final String transcriptionText; + @Getter private final String type; + @Getter private final String uri; @JsonCreator private Transcription( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("api_version") final String apiVersion, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("duration") final String duration, - @JsonProperty("price") final BigDecimal price, - @JsonProperty("price_unit") @JsonDeserialize( - using = com.twilio.converter.CurrencyDeserializer.class - ) final Currency priceUnit, - @JsonProperty("recording_sid") final String recordingSid, - @JsonProperty("sid") final String sid, - @JsonProperty("status") final Transcription.Status status, - @JsonProperty("transcription_text") final String transcriptionText, - @JsonProperty("type") final String type, - @JsonProperty("uri") final String uri + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("api_version") final String apiVersion, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.RFC2822Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.RFC2822Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("duration") final String duration, + @JsonProperty("price") final BigDecimal price, + @JsonProperty("price_unit") + @JsonDeserialize(using = com.twilio.converter.CurrencyDeserializer.class) final Currency priceUnit, + @JsonProperty("recording_sid") final String recordingSid, + @JsonProperty("sid") final String sid, + @JsonProperty("status") final Transcription.Status status, + @JsonProperty("transcription_text") final String transcriptionText, + @JsonProperty("type") final String type, + @JsonProperty("uri") final String uri ) { this.accountSid = accountSid; this.apiVersion = apiVersion; - this.dateCreated = DateConverter.rfc2822DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.rfc2822DateTimeFromString(dateUpdated); + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.duration = duration; this.price = price; this.priceUnit = priceUnit; @@ -162,58 +216,6 @@ private Transcription( this.uri = uri; } - public final String getAccountSid() { - return this.accountSid; - } - - public final String getApiVersion() { - return this.apiVersion; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final String getDuration() { - return this.duration; - } - - public final BigDecimal getPrice() { - return this.price; - } - - public final Currency getPriceUnit() { - return this.priceUnit; - } - - public final String getRecordingSid() { - return this.recordingSid; - } - - public final String getSid() { - return this.sid; - } - - public final Transcription.Status getStatus() { - return this.status; - } - - public final String getTranscriptionText() { - return this.transcriptionText; - } - - public final String getType() { - return this.type; - } - - public final String getUri() { - return this.uri; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -225,61 +227,42 @@ public boolean equals(final Object o) { } Transcription other = (Transcription) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(apiVersion, other.apiVersion) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(duration, other.duration) && - Objects.equals(price, other.price) && - Objects.equals(priceUnit, other.priceUnit) && - Objects.equals(recordingSid, other.recordingSid) && - Objects.equals(sid, other.sid) && - Objects.equals(status, other.status) && - Objects.equals(transcriptionText, other.transcriptionText) && - Objects.equals(type, other.type) && - Objects.equals(uri, other.uri) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(apiVersion, other.apiVersion) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(duration, other.duration) && + Objects.equals(price, other.price) && + Objects.equals(priceUnit, other.priceUnit) && + Objects.equals(recordingSid, other.recordingSid) && + Objects.equals(sid, other.sid) && + Objects.equals(status, other.status) && + Objects.equals(transcriptionText, other.transcriptionText) && + Objects.equals(type, other.type) && + Objects.equals(uri, other.uri) ); } @Override public int hashCode() { return Objects.hash( - accountSid, - apiVersion, - dateCreated, - dateUpdated, - duration, - price, - priceUnit, - recordingSid, - sid, - status, - transcriptionText, - type, - uri + accountSid, + apiVersion, + dateCreated, + dateUpdated, + duration, + price, + priceUnit, + recordingSid, + sid, + status, + transcriptionText, + type, + uri ); } - public enum Status { - IN_PROGRESS("in-progress"), - COMPLETED("completed"), - FAILED("failed"); - - private final String value; - - private Status(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - @JsonCreator - public static Status forValue(final String value) { - return Promoter.enumFromString(value, Status.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/api/v2010/account/TranscriptionDeleter.java b/src/main/java/com/twilio/rest/api/v2010/account/TranscriptionDeleter.java index a5d69b511c..776f5aef72 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/TranscriptionDeleter.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/TranscriptionDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.api.v2010.account; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,59 +26,46 @@ public class TranscriptionDeleter extends Deleter { - private String pathSid; - private String pathAccountSid; + private String pathaccountSid; + private String pathsid; - public TranscriptionDeleter(final String pathSid) { - this.pathSid = pathSid; + public TranscriptionDeleter(final String pathsid) { + this.pathsid = pathsid; } - public TranscriptionDeleter( - final String pathAccountSid, - final String pathSid - ) { - this.pathAccountSid = pathAccountSid; - this.pathSid = pathSid; + public TranscriptionDeleter(final String pathaccountSid, final String pathsid) { + this.pathaccountSid = pathaccountSid; + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/Transcriptions/{Sid}.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/2010-04-01/Accounts/{AccountSid}/Transcriptions/{Sid}.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.API.toString(), - path + HttpMethod.DELETE, + Domains.API.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Transcription delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("Transcription delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/TranscriptionFetcher.java b/src/main/java/com/twilio/rest/api/v2010/account/TranscriptionFetcher.java index c53cc92e69..41f3ab22fa 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/TranscriptionFetcher.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/TranscriptionFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.api.v2010.account; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,66 +26,49 @@ public class TranscriptionFetcher extends Fetcher { - private String pathSid; - private String pathAccountSid; + private String pathaccountSid; + private String pathsid; - public TranscriptionFetcher(final String pathSid) { - this.pathSid = pathSid; + public TranscriptionFetcher(final String pathsid) { + this.pathsid = pathsid; } - public TranscriptionFetcher( - final String pathAccountSid, - final String pathSid - ) { - this.pathAccountSid = pathAccountSid; - this.pathSid = pathSid; + public TranscriptionFetcher(final String pathaccountSid, final String pathsid) { + this.pathaccountSid = pathaccountSid; + this.pathsid = pathsid; } + @Override public Transcription fetch(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/Transcriptions/{Sid}.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/2010-04-01/Accounts/{AccountSid}/Transcriptions/{Sid}.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.API.toString(), - path + HttpMethod.GET, + Domains.API.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Transcription fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Transcription fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return Transcription.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Transcription.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/TranscriptionReader.java b/src/main/java/com/twilio/rest/api/v2010/account/TranscriptionReader.java index 111b969712..e576eff77e 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/TranscriptionReader.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/TranscriptionReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,121 +30,92 @@ public class TranscriptionReader extends Reader { - private String pathAccountSid; + private String pathaccountSid; private Long pageSize; - public TranscriptionReader() {} + public TranscriptionReader() { + } - public TranscriptionReader(final String pathAccountSid) { - this.pathAccountSid = pathAccountSid; + public TranscriptionReader(final String pathaccountSid) { + this.pathaccountSid = pathaccountSid; } + public TranscriptionReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/2010-04-01/Accounts/{AccountSid}/Transcriptions.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.API.toString(), - path + HttpMethod.GET, + Domains.API.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Transcription read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Transcription read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "transcriptions", - response.getContent(), - Transcription.class, - client.getObjectMapper() - ); + "transcriptions", + response.getContent(), + Transcription.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.API.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.API.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/ValidationRequest.java b/src/main/java/com/twilio/rest/api/v2010/account/ValidationRequest.java index e4135dd589..22bd8e58fb 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/ValidationRequest.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/ValidationRequest.java @@ -18,47 +18,46 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class ValidationRequest extends Resource { - private static final long serialVersionUID = 159203610764140L; - public static ValidationRequestCreator creator( - final com.twilio.type.PhoneNumber phoneNumber - ) { - return new ValidationRequestCreator(phoneNumber); + public static ValidationRequestCreator creator(final com.twilio.type.PhoneNumber phoneNumber) { + return new ValidationRequestCreator( + phoneNumber + ); } - public static ValidationRequestCreator creator( - final String pathAccountSid, - final com.twilio.type.PhoneNumber phoneNumber - ) { - return new ValidationRequestCreator(pathAccountSid, phoneNumber); + + public static ValidationRequestCreator creator(final String pathaccountSid, final com.twilio.type.PhoneNumber phoneNumber) { + return new ValidationRequestCreator( + pathaccountSid, phoneNumber + ); } + /** * Converts a JSON String into a ValidationRequest object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return ValidationRequest object represented by the provided JSON */ - public static ValidationRequest fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static ValidationRequest fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, ValidationRequest.class); @@ -73,14 +72,11 @@ public static ValidationRequest fromJson( * Converts a JSON InputStream into a ValidationRequest object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return ValidationRequest object represented by the provided JSON */ - public static ValidationRequest fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static ValidationRequest fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, ValidationRequest.class); @@ -91,21 +87,37 @@ public static ValidationRequest fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; + @Getter private final String callSid; + @Getter private final String friendlyName; + @Getter private final com.twilio.type.PhoneNumber phoneNumber; + @Getter private final String validationCode; @JsonCreator private ValidationRequest( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("call_sid") final String callSid, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty( - "phone_number" - ) final com.twilio.type.PhoneNumber phoneNumber, - @JsonProperty("validation_code") final String validationCode + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("call_sid") final String callSid, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("phone_number") final com.twilio.type.PhoneNumber phoneNumber, + @JsonProperty("validation_code") final String validationCode ) { this.accountSid = accountSid; this.callSid = callSid; @@ -114,26 +126,6 @@ private ValidationRequest( this.validationCode = validationCode; } - public final String getAccountSid() { - return this.accountSid; - } - - public final String getCallSid() { - return this.callSid; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final com.twilio.type.PhoneNumber getPhoneNumber() { - return this.phoneNumber; - } - - public final String getValidationCode() { - return this.validationCode; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -145,24 +137,26 @@ public boolean equals(final Object o) { } ValidationRequest other = (ValidationRequest) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(callSid, other.callSid) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(phoneNumber, other.phoneNumber) && - Objects.equals(validationCode, other.validationCode) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(callSid, other.callSid) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(phoneNumber, other.phoneNumber) && + Objects.equals(validationCode, other.validationCode) ); } @Override public int hashCode() { return Objects.hash( - accountSid, - callSid, - friendlyName, - phoneNumber, - validationCode + accountSid, + callSid, + friendlyName, + phoneNumber, + validationCode ); } + + } + diff --git a/src/main/java/com/twilio/rest/api/v2010/account/ValidationRequestCreator.java b/src/main/java/com/twilio/rest/api/v2010/account/ValidationRequestCreator.java index 15486f1597..87f49945a9 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/ValidationRequestCreator.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/ValidationRequestCreator.java @@ -14,9 +14,12 @@ package com.twilio.rest.api.v2010.account; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; import com.twilio.converter.Promoter; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,36 +28,30 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -import java.net.URI; + import java.net.URI; public class ValidationRequestCreator extends Creator { + private String pathaccountSid; private com.twilio.type.PhoneNumber phoneNumber; - private String pathAccountSid; private String friendlyName; private Integer callDelay; private String extension; private URI statusCallback; private HttpMethod statusCallbackMethod; - public ValidationRequestCreator( - final com.twilio.type.PhoneNumber phoneNumber - ) { + public ValidationRequestCreator(final com.twilio.type.PhoneNumber phoneNumber) { this.phoneNumber = phoneNumber; } - public ValidationRequestCreator( - final String pathAccountSid, - final com.twilio.type.PhoneNumber phoneNumber - ) { - this.pathAccountSid = pathAccountSid; + public ValidationRequestCreator(final String pathaccountSid, final com.twilio.type.PhoneNumber phoneNumber) { + this.pathaccountSid = pathaccountSid; this.phoneNumber = phoneNumber; } - public ValidationRequestCreator setPhoneNumber( - final com.twilio.type.PhoneNumber phoneNumber - ) { + + public ValidationRequestCreator setPhoneNumber(final com.twilio.type.PhoneNumber phoneNumber) { this.phoneNumber = phoneNumber; return this; } @@ -68,109 +65,97 @@ public ValidationRequestCreator setFriendlyName(final String friendlyName) { return this; } + public ValidationRequestCreator setCallDelay(final Integer callDelay) { this.callDelay = callDelay; return this; } + public ValidationRequestCreator setExtension(final String extension) { this.extension = extension; return this; } - public ValidationRequestCreator setStatusCallback( - final URI statusCallback - ) { + + public ValidationRequestCreator setStatusCallback(final URI statusCallback) { this.statusCallback = statusCallback; return this; } - public ValidationRequestCreator setStatusCallback( - final String statusCallback - ) { - return setStatusCallback(Promoter.uriFromString(statusCallback)); - } - public ValidationRequestCreator setStatusCallbackMethod( - final HttpMethod statusCallbackMethod - ) { + public ValidationRequestCreator setStatusCallbackMethod(final HttpMethod statusCallbackMethod) { this.statusCallbackMethod = statusCallbackMethod; return this; } + @Override public ValidationRequest create(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/OutgoingCallerIds.json"; - - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = - path.replace( - "{" + "PhoneNumber" + "}", - this.phoneNumber.toString() - ); + + String path = "/2010-04-01/Accounts/{AccountSid}/OutgoingCallerIds.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.API.toString(), - path + HttpMethod.POST, + Domains.API.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "ValidationRequest creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("ValidationRequest creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return ValidationRequest.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return ValidationRequest.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (phoneNumber != null) { - request.addPostParam("PhoneNumber", phoneNumber.toString()); + Serializer.toString(request, "PhoneNumber", phoneNumber, ParameterType.URLENCODED); } + + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + if (callDelay != null) { - request.addPostParam("CallDelay", callDelay.toString()); + Serializer.toString(request, "CallDelay", callDelay, ParameterType.URLENCODED); } + + if (extension != null) { - request.addPostParam("Extension", extension); + Serializer.toString(request, "Extension", extension, ParameterType.URLENCODED); } + + if (statusCallback != null) { - request.addPostParam("StatusCallback", statusCallback.toString()); + Serializer.toString(request, "StatusCallback", statusCallback, ParameterType.URLENCODED); } + + if (statusCallbackMethod != null) { - request.addPostParam( - "StatusCallbackMethod", - statusCallbackMethod.toString() - ); + Serializer.toString(request, "StatusCallbackMethod", statusCallbackMethod, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/address/DependentPhoneNumber.java b/src/main/java/com/twilio/rest/api/v2010/account/address/DependentPhoneNumber.java index 3c65422d55..8699f0fc36 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/address/DependentPhoneNumber.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/address/DependentPhoneNumber.java @@ -18,54 +18,94 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.http.HttpMethod; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; -import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class DependentPhoneNumber extends Resource { - private static final long serialVersionUID = 279811089031324L; - public static DependentPhoneNumberReader reader( - final String pathAddressSid - ) { - return new DependentPhoneNumberReader(pathAddressSid); + public static DependentPhoneNumberReader reader(final String pathaddressSid) { + return new DependentPhoneNumberReader( + pathaddressSid + ); } - public static DependentPhoneNumberReader reader( - final String pathAccountSid, - final String pathAddressSid - ) { - return new DependentPhoneNumberReader(pathAccountSid, pathAddressSid); + + public static DependentPhoneNumberReader reader(final String pathaccountSid, final String pathaddressSid) { + return new DependentPhoneNumberReader( + pathaccountSid, pathaddressSid + ); } + + public enum EmergencyStatus { + ACTIVE("Active"), + INACTIVE("Inactive"); + + private final String value; + + private EmergencyStatus(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static EmergencyStatus forValue(final String value) { + return Promoter.enumFromString(value, EmergencyStatus.values()); + } + } + + public enum AddressRequirement { + NONE("none"), + ANY("any"), + LOCAL("local"), + FOREIGN("foreign"); + + private final String value; + + private AddressRequirement(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static AddressRequirement forValue(final String value) { + return Promoter.enumFromString(value, AddressRequirement.values()); + } + } + + /** * Converts a JSON String into a DependentPhoneNumber object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return DependentPhoneNumber object represented by the provided JSON */ - public static DependentPhoneNumber fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static DependentPhoneNumber fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, DependentPhoneNumber.class); @@ -80,14 +120,11 @@ public static DependentPhoneNumber fromJson( * Converts a JSON InputStream into a DependentPhoneNumber object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return DependentPhoneNumber object represented by the provided JSON */ - public static DependentPhoneNumber fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static DependentPhoneNumber fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, DependentPhoneNumber.class); @@ -98,204 +135,129 @@ public static DependentPhoneNumber fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String friendlyName; - private final com.twilio.type.PhoneNumber phoneNumber; - private final URI voiceUrl; - private final HttpMethod voiceMethod; - private final HttpMethod voiceFallbackMethod; - private final URI voiceFallbackUrl; - private final Boolean voiceCallerIdLookup; + @Getter + private final DependentPhoneNumber.AddressRequirement addressRequirements; + @Getter + private final String apiVersion; + @Getter + private final Object capabilities; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; + @Getter + private final String emergencyAddressSid; + @Getter + private final DependentPhoneNumber.EmergencyStatus emergencyStatus; + @Getter + private final String friendlyName; + @Getter + private final com.twilio.type.PhoneNumber phoneNumber; + @Getter + private final String sid; + @Getter + private final String smsApplicationSid; + @Getter private final HttpMethod smsFallbackMethod; + @Getter private final URI smsFallbackUrl; + @Getter private final HttpMethod smsMethod; + @Getter private final URI smsUrl; - private final DependentPhoneNumber.AddressRequirement addressRequirements; - private final Map capabilities; + @Getter private final URI statusCallback; + @Getter private final HttpMethod statusCallbackMethod; - private final String apiVersion; - private final String smsApplicationSid; - private final String voiceApplicationSid; + @Getter private final String trunkSid; - private final DependentPhoneNumber.EmergencyStatus emergencyStatus; - private final String emergencyAddressSid; + @Getter private final String uri; + @Getter + private final String voiceApplicationSid; + @Getter + private final Boolean voiceCallerIdLookup; + @Getter + private final HttpMethod voiceFallbackMethod; + @Getter + private final URI voiceFallbackUrl; + @Getter + private final HttpMethod voiceMethod; + @Getter + private final URI voiceUrl; @JsonCreator private DependentPhoneNumber( - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty( - "phone_number" - ) final com.twilio.type.PhoneNumber phoneNumber, - @JsonProperty("voice_url") final URI voiceUrl, - @JsonProperty("voice_method") final HttpMethod voiceMethod, - @JsonProperty( - "voice_fallback_method" - ) final HttpMethod voiceFallbackMethod, - @JsonProperty("voice_fallback_url") final URI voiceFallbackUrl, - @JsonProperty( - "voice_caller_id_lookup" - ) final Boolean voiceCallerIdLookup, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("sms_fallback_method") final HttpMethod smsFallbackMethod, - @JsonProperty("sms_fallback_url") final URI smsFallbackUrl, - @JsonProperty("sms_method") final HttpMethod smsMethod, - @JsonProperty("sms_url") final URI smsUrl, - @JsonProperty( - "address_requirements" - ) final DependentPhoneNumber.AddressRequirement addressRequirements, - @JsonProperty("capabilities") final Map capabilities, - @JsonProperty("status_callback") final URI statusCallback, - @JsonProperty( - "status_callback_method" - ) final HttpMethod statusCallbackMethod, - @JsonProperty("api_version") final String apiVersion, - @JsonProperty("sms_application_sid") final String smsApplicationSid, - @JsonProperty("voice_application_sid") final String voiceApplicationSid, - @JsonProperty("trunk_sid") final String trunkSid, - @JsonProperty( - "emergency_status" - ) final DependentPhoneNumber.EmergencyStatus emergencyStatus, - @JsonProperty("emergency_address_sid") final String emergencyAddressSid, - @JsonProperty("uri") final String uri + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("address_requirements") final DependentPhoneNumber.AddressRequirement addressRequirements, + @JsonProperty("api_version") final String apiVersion, + @JsonProperty("capabilities") final Object capabilities, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.RFC2822Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.RFC2822Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("emergency_address_sid") final String emergencyAddressSid, + @JsonProperty("emergency_status") final DependentPhoneNumber.EmergencyStatus emergencyStatus, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("phone_number") final com.twilio.type.PhoneNumber phoneNumber, + @JsonProperty("sid") final String sid, + @JsonProperty("sms_application_sid") final String smsApplicationSid, + @JsonProperty("sms_fallback_method") final HttpMethod smsFallbackMethod, + @JsonProperty("sms_fallback_url") final URI smsFallbackUrl, + @JsonProperty("sms_method") final HttpMethod smsMethod, + @JsonProperty("sms_url") final URI smsUrl, + @JsonProperty("status_callback") final URI statusCallback, + @JsonProperty("status_callback_method") final HttpMethod statusCallbackMethod, + @JsonProperty("trunk_sid") final String trunkSid, + @JsonProperty("uri") final String uri, + @JsonProperty("voice_application_sid") final String voiceApplicationSid, + @JsonProperty("voice_caller_id_lookup") final Boolean voiceCallerIdLookup, + @JsonProperty("voice_fallback_method") final HttpMethod voiceFallbackMethod, + @JsonProperty("voice_fallback_url") final URI voiceFallbackUrl, + @JsonProperty("voice_method") final HttpMethod voiceMethod, + @JsonProperty("voice_url") final URI voiceUrl ) { - this.sid = sid; this.accountSid = accountSid; + this.addressRequirements = addressRequirements; + this.apiVersion = apiVersion; + this.capabilities = capabilities; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; + this.emergencyAddressSid = emergencyAddressSid; + this.emergencyStatus = emergencyStatus; this.friendlyName = friendlyName; this.phoneNumber = phoneNumber; - this.voiceUrl = voiceUrl; - this.voiceMethod = voiceMethod; - this.voiceFallbackMethod = voiceFallbackMethod; - this.voiceFallbackUrl = voiceFallbackUrl; - this.voiceCallerIdLookup = voiceCallerIdLookup; - this.dateCreated = DateConverter.rfc2822DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.rfc2822DateTimeFromString(dateUpdated); + this.sid = sid; + this.smsApplicationSid = smsApplicationSid; this.smsFallbackMethod = smsFallbackMethod; this.smsFallbackUrl = smsFallbackUrl; this.smsMethod = smsMethod; this.smsUrl = smsUrl; - this.addressRequirements = addressRequirements; - this.capabilities = capabilities; this.statusCallback = statusCallback; this.statusCallbackMethod = statusCallbackMethod; - this.apiVersion = apiVersion; - this.smsApplicationSid = smsApplicationSid; - this.voiceApplicationSid = voiceApplicationSid; this.trunkSid = trunkSid; - this.emergencyStatus = emergencyStatus; - this.emergencyAddressSid = emergencyAddressSid; this.uri = uri; - } - - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final com.twilio.type.PhoneNumber getPhoneNumber() { - return this.phoneNumber; - } - - public final URI getVoiceUrl() { - return this.voiceUrl; - } - - public final HttpMethod getVoiceMethod() { - return this.voiceMethod; - } - - public final HttpMethod getVoiceFallbackMethod() { - return this.voiceFallbackMethod; - } - - public final URI getVoiceFallbackUrl() { - return this.voiceFallbackUrl; - } - - public final Boolean getVoiceCallerIdLookup() { - return this.voiceCallerIdLookup; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final HttpMethod getSmsFallbackMethod() { - return this.smsFallbackMethod; - } - - public final URI getSmsFallbackUrl() { - return this.smsFallbackUrl; - } - - public final HttpMethod getSmsMethod() { - return this.smsMethod; - } - - public final URI getSmsUrl() { - return this.smsUrl; - } - - public final DependentPhoneNumber.AddressRequirement getAddressRequirements() { - return this.addressRequirements; - } - - public final Map getCapabilities() { - return this.capabilities; - } - - public final URI getStatusCallback() { - return this.statusCallback; - } - - public final HttpMethod getStatusCallbackMethod() { - return this.statusCallbackMethod; - } - - public final String getApiVersion() { - return this.apiVersion; - } - - public final String getSmsApplicationSid() { - return this.smsApplicationSid; - } - - public final String getVoiceApplicationSid() { - return this.voiceApplicationSid; - } - - public final String getTrunkSid() { - return this.trunkSid; - } - - public final DependentPhoneNumber.EmergencyStatus getEmergencyStatus() { - return this.emergencyStatus; - } - - public final String getEmergencyAddressSid() { - return this.emergencyAddressSid; - } - - public final String getUri() { - return this.uri; + this.voiceApplicationSid = voiceApplicationSid; + this.voiceCallerIdLookup = voiceCallerIdLookup; + this.voiceFallbackMethod = voiceFallbackMethod; + this.voiceFallbackUrl = voiceFallbackUrl; + this.voiceMethod = voiceMethod; + this.voiceUrl = voiceUrl; } @Override @@ -309,108 +271,68 @@ public boolean equals(final Object o) { } DependentPhoneNumber other = (DependentPhoneNumber) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(phoneNumber, other.phoneNumber) && - Objects.equals(voiceUrl, other.voiceUrl) && - Objects.equals(voiceMethod, other.voiceMethod) && - Objects.equals(voiceFallbackMethod, other.voiceFallbackMethod) && - Objects.equals(voiceFallbackUrl, other.voiceFallbackUrl) && - Objects.equals(voiceCallerIdLookup, other.voiceCallerIdLookup) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(smsFallbackMethod, other.smsFallbackMethod) && - Objects.equals(smsFallbackUrl, other.smsFallbackUrl) && - Objects.equals(smsMethod, other.smsMethod) && - Objects.equals(smsUrl, other.smsUrl) && - Objects.equals(addressRequirements, other.addressRequirements) && - Objects.equals(capabilities, other.capabilities) && - Objects.equals(statusCallback, other.statusCallback) && - Objects.equals(statusCallbackMethod, other.statusCallbackMethod) && - Objects.equals(apiVersion, other.apiVersion) && - Objects.equals(smsApplicationSid, other.smsApplicationSid) && - Objects.equals(voiceApplicationSid, other.voiceApplicationSid) && - Objects.equals(trunkSid, other.trunkSid) && - Objects.equals(emergencyStatus, other.emergencyStatus) && - Objects.equals(emergencyAddressSid, other.emergencyAddressSid) && - Objects.equals(uri, other.uri) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(addressRequirements, other.addressRequirements) && + Objects.equals(apiVersion, other.apiVersion) && + Objects.equals(capabilities, other.capabilities) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(emergencyAddressSid, other.emergencyAddressSid) && + Objects.equals(emergencyStatus, other.emergencyStatus) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(phoneNumber, other.phoneNumber) && + Objects.equals(sid, other.sid) && + Objects.equals(smsApplicationSid, other.smsApplicationSid) && + Objects.equals(smsFallbackMethod, other.smsFallbackMethod) && + Objects.equals(smsFallbackUrl, other.smsFallbackUrl) && + Objects.equals(smsMethod, other.smsMethod) && + Objects.equals(smsUrl, other.smsUrl) && + Objects.equals(statusCallback, other.statusCallback) && + Objects.equals(statusCallbackMethod, other.statusCallbackMethod) && + Objects.equals(trunkSid, other.trunkSid) && + Objects.equals(uri, other.uri) && + Objects.equals(voiceApplicationSid, other.voiceApplicationSid) && + Objects.equals(voiceCallerIdLookup, other.voiceCallerIdLookup) && + Objects.equals(voiceFallbackMethod, other.voiceFallbackMethod) && + Objects.equals(voiceFallbackUrl, other.voiceFallbackUrl) && + Objects.equals(voiceMethod, other.voiceMethod) && + Objects.equals(voiceUrl, other.voiceUrl) ); } @Override public int hashCode() { return Objects.hash( - sid, - accountSid, - friendlyName, - phoneNumber, - voiceUrl, - voiceMethod, - voiceFallbackMethod, - voiceFallbackUrl, - voiceCallerIdLookup, - dateCreated, - dateUpdated, - smsFallbackMethod, - smsFallbackUrl, - smsMethod, - smsUrl, - addressRequirements, - capabilities, - statusCallback, - statusCallbackMethod, - apiVersion, - smsApplicationSid, - voiceApplicationSid, - trunkSid, - emergencyStatus, - emergencyAddressSid, - uri + accountSid, + addressRequirements, + apiVersion, + capabilities, + dateCreated, + dateUpdated, + emergencyAddressSid, + emergencyStatus, + friendlyName, + phoneNumber, + sid, + smsApplicationSid, + smsFallbackMethod, + smsFallbackUrl, + smsMethod, + smsUrl, + statusCallback, + statusCallbackMethod, + trunkSid, + uri, + voiceApplicationSid, + voiceCallerIdLookup, + voiceFallbackMethod, + voiceFallbackUrl, + voiceMethod, + voiceUrl ); } - public enum AddressRequirement { - NONE("none"), - ANY("any"), - LOCAL("local"), - FOREIGN("foreign"); - - private final String value; - - private AddressRequirement(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - @JsonCreator - public static AddressRequirement forValue(final String value) { - return Promoter.enumFromString(value, AddressRequirement.values()); - } - } - - public enum EmergencyStatus { - ACTIVE("Active"), - INACTIVE("Inactive"); - - private final String value; - - private EmergencyStatus(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static EmergencyStatus forValue(final String value) { - return Promoter.enumFromString(value, EmergencyStatus.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/api/v2010/account/address/DependentPhoneNumberReader.java b/src/main/java/com/twilio/rest/api/v2010/account/address/DependentPhoneNumberReader.java index 0f855c425b..28a610202a 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/address/DependentPhoneNumberReader.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/address/DependentPhoneNumberReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,136 +30,96 @@ public class DependentPhoneNumberReader extends Reader { - private String pathAddressSid; - private String pathAccountSid; + private String pathaccountSid; + private String pathaddressSid; private Long pageSize; - public DependentPhoneNumberReader(final String pathAddressSid) { - this.pathAddressSid = pathAddressSid; + public DependentPhoneNumberReader(final String pathaddressSid) { + this.pathaddressSid = pathaddressSid; } - public DependentPhoneNumberReader( - final String pathAccountSid, - final String pathAddressSid - ) { - this.pathAccountSid = pathAccountSid; - this.pathAddressSid = pathAddressSid; + public DependentPhoneNumberReader(final String pathaccountSid, final String pathaddressSid) { + this.pathaccountSid = pathaccountSid; + this.pathaddressSid = pathaddressSid; } + public DependentPhoneNumberReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override - public ResourceSet read( - final TwilioRestClient client - ) { + public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/Addresses/{AddressSid}/DependentPhoneNumbers.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = - path.replace( - "{" + "AddressSid" + "}", - this.pathAddressSid.toString() - ); + + String path = "/2010-04-01/Accounts/{AccountSid}/Addresses/{AddressSid}/DependentPhoneNumbers.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "AddressSid" + "}", this.pathaddressSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.API.toString(), - path + HttpMethod.GET, + Domains.API.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "DependentPhoneNumber read failed: Unable to connect to server" - ); + throw new ApiConnectionException("DependentPhoneNumber read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "dependent_phone_numbers", - response.getContent(), - DependentPhoneNumber.class, - client.getObjectMapper() - ); + "dependent_phone_numbers", + response.getContent(), + DependentPhoneNumber.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.API.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.API.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/availablephonenumbercountry/Local.java b/src/main/java/com/twilio/rest/api/v2010/account/availablephonenumbercountry/Local.java index d9eb281278..75612d14eb 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/availablephonenumbercountry/Local.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/availablephonenumbercountry/Local.java @@ -18,47 +18,48 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.type.PhoneNumberCapabilities; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.math.BigDecimal; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Local extends Resource { - private static final long serialVersionUID = 211749226408502L; - public static LocalReader reader(final String pathCountryCode) { - return new LocalReader(pathCountryCode); + public static LocalReader reader(final String pathcountryCode) { + return new LocalReader( + pathcountryCode + ); } - public static LocalReader reader( - final String pathAccountSid, - final String pathCountryCode - ) { - return new LocalReader(pathAccountSid, pathCountryCode); + + public static LocalReader reader(final String pathaccountSid, final String pathcountryCode) { + return new LocalReader( + pathaccountSid, pathcountryCode + ); } + /** * Converts a JSON String into a Local object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Local object represented by the provided JSON */ - public static Local fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Local fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Local.class); @@ -73,14 +74,11 @@ public static Local fromJson( * Converts a JSON InputStream into a Local object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Local object represented by the provided JSON */ - public static Local fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Local fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Local.class); @@ -91,105 +89,75 @@ public static Local fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter + private final String addressRequirements; + @Getter + private final Boolean beta; + @Getter + private final PhoneNumberCapabilities capabilities; + @Getter private final com.twilio.type.PhoneNumber friendlyName; - private final com.twilio.type.PhoneNumber phoneNumber; + @Getter + private final String isoCountry; + @Getter private final String lata; - private final String locality; - private final String rateCenter; + @Getter private final BigDecimal latitude; + @Getter + private final String locality; + @Getter private final BigDecimal longitude; - private final String region; + @Getter + private final com.twilio.type.PhoneNumber phoneNumber; + @Getter private final String postalCode; - private final String isoCountry; - private final String addressRequirements; - private final Boolean beta; - private final PhoneNumberCapabilities capabilities; + @Getter + private final String rateCenter; + @Getter + private final String region; @JsonCreator private Local( - @JsonProperty( - "friendly_name" - ) final com.twilio.type.PhoneNumber friendlyName, - @JsonProperty( - "phone_number" - ) final com.twilio.type.PhoneNumber phoneNumber, - @JsonProperty("lata") final String lata, - @JsonProperty("locality") final String locality, - @JsonProperty("rate_center") final String rateCenter, - @JsonProperty("latitude") final BigDecimal latitude, - @JsonProperty("longitude") final BigDecimal longitude, - @JsonProperty("region") final String region, - @JsonProperty("postal_code") final String postalCode, - @JsonProperty("iso_country") final String isoCountry, - @JsonProperty("address_requirements") final String addressRequirements, - @JsonProperty("beta") final Boolean beta, - @JsonProperty("capabilities") final PhoneNumberCapabilities capabilities + @JsonProperty("address_requirements") final String addressRequirements, + @JsonProperty("beta") final Boolean beta, + @JsonProperty("capabilities") final PhoneNumberCapabilities capabilities, + @JsonProperty("friendly_name") final com.twilio.type.PhoneNumber friendlyName, + @JsonProperty("iso_country") final String isoCountry, + @JsonProperty("lata") final String lata, + @JsonProperty("latitude") final BigDecimal latitude, + @JsonProperty("locality") final String locality, + @JsonProperty("longitude") final BigDecimal longitude, + @JsonProperty("phone_number") final com.twilio.type.PhoneNumber phoneNumber, + @JsonProperty("postal_code") final String postalCode, + @JsonProperty("rate_center") final String rateCenter, + @JsonProperty("region") final String region ) { + this.addressRequirements = addressRequirements; + this.beta = beta; + this.capabilities = capabilities; this.friendlyName = friendlyName; - this.phoneNumber = phoneNumber; + this.isoCountry = isoCountry; this.lata = lata; - this.locality = locality; - this.rateCenter = rateCenter; this.latitude = latitude; + this.locality = locality; this.longitude = longitude; - this.region = region; + this.phoneNumber = phoneNumber; this.postalCode = postalCode; - this.isoCountry = isoCountry; - this.addressRequirements = addressRequirements; - this.beta = beta; - this.capabilities = capabilities; - } - - public final com.twilio.type.PhoneNumber getFriendlyName() { - return this.friendlyName; - } - - public final com.twilio.type.PhoneNumber getPhoneNumber() { - return this.phoneNumber; - } - - public final String getLata() { - return this.lata; - } - - public final String getLocality() { - return this.locality; - } - - public final String getRateCenter() { - return this.rateCenter; - } - - public final BigDecimal getLatitude() { - return this.latitude; - } - - public final BigDecimal getLongitude() { - return this.longitude; - } - - public final String getRegion() { - return this.region; - } - - public final String getPostalCode() { - return this.postalCode; - } - - public final String getIsoCountry() { - return this.isoCountry; - } - - public final String getAddressRequirements() { - return this.addressRequirements; - } - - public final Boolean getBeta() { - return this.beta; - } - - public final PhoneNumberCapabilities getCapabilities() { - return this.capabilities; + this.rateCenter = rateCenter; + this.region = region; } @Override @@ -203,40 +171,42 @@ public boolean equals(final Object o) { } Local other = (Local) o; - return ( - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(phoneNumber, other.phoneNumber) && - Objects.equals(lata, other.lata) && - Objects.equals(locality, other.locality) && - Objects.equals(rateCenter, other.rateCenter) && - Objects.equals(latitude, other.latitude) && - Objects.equals(longitude, other.longitude) && - Objects.equals(region, other.region) && - Objects.equals(postalCode, other.postalCode) && - Objects.equals(isoCountry, other.isoCountry) && - Objects.equals(addressRequirements, other.addressRequirements) && - Objects.equals(beta, other.beta) && - Objects.equals(capabilities, other.capabilities) + Objects.equals(addressRequirements, other.addressRequirements) && + Objects.equals(beta, other.beta) && + Objects.equals(capabilities, other.capabilities) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(isoCountry, other.isoCountry) && + Objects.equals(lata, other.lata) && + Objects.equals(latitude, other.latitude) && + Objects.equals(locality, other.locality) && + Objects.equals(longitude, other.longitude) && + Objects.equals(phoneNumber, other.phoneNumber) && + Objects.equals(postalCode, other.postalCode) && + Objects.equals(rateCenter, other.rateCenter) && + Objects.equals(region, other.region) ); } @Override public int hashCode() { return Objects.hash( - friendlyName, - phoneNumber, - lata, - locality, - rateCenter, - latitude, - longitude, - region, - postalCode, - isoCountry, - addressRequirements, - beta, - capabilities + addressRequirements, + beta, + capabilities, + friendlyName, + isoCountry, + lata, + latitude, + locality, + longitude, + phoneNumber, + postalCode, + rateCenter, + region ); } + + } + diff --git a/src/main/java/com/twilio/rest/api/v2010/account/availablephonenumbercountry/LocalReader.java b/src/main/java/com/twilio/rest/api/v2010/account/availablephonenumbercountry/LocalReader.java index 8417c3105b..0243e95cc4 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/availablephonenumbercountry/LocalReader.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/availablephonenumbercountry/LocalReader.java @@ -17,8 +17,9 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; import com.twilio.converter.Promoter; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -30,8 +31,8 @@ public class LocalReader extends Reader { - private String pathCountryCode; - private String pathAccountSid; + private String pathaccountSid; + private String pathcountryCode; private Integer areaCode; private String contains; private Boolean smsEnabled; @@ -52,72 +53,71 @@ public class LocalReader extends Reader { private Boolean faxEnabled; private Long pageSize; - public LocalReader(final String pathCountryCode) { - this.pathCountryCode = pathCountryCode; + public LocalReader(final String pathcountryCode) { + this.pathcountryCode = pathcountryCode; } - public LocalReader( - final String pathAccountSid, - final String pathCountryCode - ) { - this.pathAccountSid = pathAccountSid; - this.pathCountryCode = pathCountryCode; + public LocalReader(final String pathaccountSid, final String pathcountryCode) { + this.pathaccountSid = pathaccountSid; + this.pathcountryCode = pathcountryCode; } + public LocalReader setAreaCode(final Integer areaCode) { this.areaCode = areaCode; return this; } + public LocalReader setContains(final String contains) { this.contains = contains; return this; } + public LocalReader setSmsEnabled(final Boolean smsEnabled) { this.smsEnabled = smsEnabled; return this; } + public LocalReader setMmsEnabled(final Boolean mmsEnabled) { this.mmsEnabled = mmsEnabled; return this; } + public LocalReader setVoiceEnabled(final Boolean voiceEnabled) { this.voiceEnabled = voiceEnabled; return this; } - public LocalReader setExcludeAllAddressRequired( - final Boolean excludeAllAddressRequired - ) { + + public LocalReader setExcludeAllAddressRequired(final Boolean excludeAllAddressRequired) { this.excludeAllAddressRequired = excludeAllAddressRequired; return this; } - public LocalReader setExcludeLocalAddressRequired( - final Boolean excludeLocalAddressRequired - ) { + + public LocalReader setExcludeLocalAddressRequired(final Boolean excludeLocalAddressRequired) { this.excludeLocalAddressRequired = excludeLocalAddressRequired; return this; } - public LocalReader setExcludeForeignAddressRequired( - final Boolean excludeForeignAddressRequired - ) { + + public LocalReader setExcludeForeignAddressRequired(final Boolean excludeForeignAddressRequired) { this.excludeForeignAddressRequired = excludeForeignAddressRequired; return this; } + public LocalReader setBeta(final Boolean beta) { this.beta = beta; return this; } - public LocalReader setNearNumber( - final com.twilio.type.PhoneNumber nearNumber - ) { + + public LocalReader setNearNumber(final com.twilio.type.PhoneNumber nearNumber) { this.nearNumber = nearNumber; return this; } @@ -131,216 +131,215 @@ public LocalReader setNearLatLong(final String nearLatLong) { return this; } + public LocalReader setDistance(final Integer distance) { this.distance = distance; return this; } + public LocalReader setInPostalCode(final String inPostalCode) { this.inPostalCode = inPostalCode; return this; } + public LocalReader setInRegion(final String inRegion) { this.inRegion = inRegion; return this; } + public LocalReader setInRateCenter(final String inRateCenter) { this.inRateCenter = inRateCenter; return this; } + public LocalReader setInLata(final String inLata) { this.inLata = inLata; return this; } + public LocalReader setInLocality(final String inLocality) { this.inLocality = inLocality; return this; } + public LocalReader setFaxEnabled(final Boolean faxEnabled) { this.faxEnabled = faxEnabled; return this; } + public LocalReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/AvailablePhoneNumbers/{CountryCode}/Local.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = - path.replace( - "{" + "CountryCode" + "}", - this.pathCountryCode.toString() - ); + + String path = "/2010-04-01/Accounts/{AccountSid}/AvailablePhoneNumbers/{CountryCode}/Local.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "CountryCode" + "}", this.pathcountryCode.toString()); Request request = new Request( - HttpMethod.GET, - Domains.API.toString(), - path + HttpMethod.GET, + Domains.API.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Local read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Local read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "available_phone_numbers", - response.getContent(), - Local.class, - client.getObjectMapper() - ); + "available_phone_numbers", + response.getContent(), + Local.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.API.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.API.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (areaCode != null) { - request.addQueryParam("AreaCode", areaCode.toString()); + Serializer.toString(request, "AreaCode", areaCode, ParameterType.QUERY); } + + if (contains != null) { - request.addQueryParam("Contains", contains); + Serializer.toString(request, "Contains", contains, ParameterType.QUERY); } + + if (smsEnabled != null) { - request.addQueryParam("SmsEnabled", smsEnabled.toString()); + Serializer.toString(request, "SmsEnabled", smsEnabled, ParameterType.QUERY); } + + if (mmsEnabled != null) { - request.addQueryParam("MmsEnabled", mmsEnabled.toString()); + Serializer.toString(request, "MmsEnabled", mmsEnabled, ParameterType.QUERY); } + + if (voiceEnabled != null) { - request.addQueryParam("VoiceEnabled", voiceEnabled.toString()); + Serializer.toString(request, "VoiceEnabled", voiceEnabled, ParameterType.QUERY); } + + if (excludeAllAddressRequired != null) { - request.addQueryParam( - "ExcludeAllAddressRequired", - excludeAllAddressRequired.toString() - ); + Serializer.toString(request, "ExcludeAllAddressRequired", excludeAllAddressRequired, ParameterType.QUERY); } + + if (excludeLocalAddressRequired != null) { - request.addQueryParam( - "ExcludeLocalAddressRequired", - excludeLocalAddressRequired.toString() - ); + Serializer.toString(request, "ExcludeLocalAddressRequired", excludeLocalAddressRequired, ParameterType.QUERY); } + + if (excludeForeignAddressRequired != null) { - request.addQueryParam( - "ExcludeForeignAddressRequired", - excludeForeignAddressRequired.toString() - ); + Serializer.toString(request, "ExcludeForeignAddressRequired", excludeForeignAddressRequired, ParameterType.QUERY); } + + if (beta != null) { - request.addQueryParam("Beta", beta.toString()); + Serializer.toString(request, "Beta", beta, ParameterType.QUERY); } + + if (nearNumber != null) { - request.addQueryParam("NearNumber", nearNumber.toString()); + Serializer.toString(request, "NearNumber", nearNumber, ParameterType.QUERY); } + + if (nearLatLong != null) { - request.addQueryParam("NearLatLong", nearLatLong); + Serializer.toString(request, "NearLatLong", nearLatLong, ParameterType.QUERY); } + + if (distance != null) { - request.addQueryParam("Distance", distance.toString()); + Serializer.toString(request, "Distance", distance, ParameterType.QUERY); } + + if (inPostalCode != null) { - request.addQueryParam("InPostalCode", inPostalCode); + Serializer.toString(request, "InPostalCode", inPostalCode, ParameterType.QUERY); } + + if (inRegion != null) { - request.addQueryParam("InRegion", inRegion); + Serializer.toString(request, "InRegion", inRegion, ParameterType.QUERY); } + + if (inRateCenter != null) { - request.addQueryParam("InRateCenter", inRateCenter); + Serializer.toString(request, "InRateCenter", inRateCenter, ParameterType.QUERY); } + + if (inLata != null) { - request.addQueryParam("InLata", inLata); + Serializer.toString(request, "InLata", inLata, ParameterType.QUERY); } + + if (inLocality != null) { - request.addQueryParam("InLocality", inLocality); + Serializer.toString(request, "InLocality", inLocality, ParameterType.QUERY); } + + if (faxEnabled != null) { - request.addQueryParam("FaxEnabled", faxEnabled.toString()); + Serializer.toString(request, "FaxEnabled", faxEnabled, ParameterType.QUERY); } + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/availablephonenumbercountry/MachineToMachine.java b/src/main/java/com/twilio/rest/api/v2010/account/availablephonenumbercountry/MachineToMachine.java index 013df4f252..81ece5a688 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/availablephonenumbercountry/MachineToMachine.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/availablephonenumbercountry/MachineToMachine.java @@ -18,47 +18,48 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.type.PhoneNumberCapabilities; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.math.BigDecimal; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class MachineToMachine extends Resource { - private static final long serialVersionUID = 211749226408502L; - public static MachineToMachineReader reader(final String pathCountryCode) { - return new MachineToMachineReader(pathCountryCode); + public static MachineToMachineReader reader(final String pathcountryCode) { + return new MachineToMachineReader( + pathcountryCode + ); } - public static MachineToMachineReader reader( - final String pathAccountSid, - final String pathCountryCode - ) { - return new MachineToMachineReader(pathAccountSid, pathCountryCode); + + public static MachineToMachineReader reader(final String pathaccountSid, final String pathcountryCode) { + return new MachineToMachineReader( + pathaccountSid, pathcountryCode + ); } + /** * Converts a JSON String into a MachineToMachine object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return MachineToMachine object represented by the provided JSON */ - public static MachineToMachine fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static MachineToMachine fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, MachineToMachine.class); @@ -73,14 +74,11 @@ public static MachineToMachine fromJson( * Converts a JSON InputStream into a MachineToMachine object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return MachineToMachine object represented by the provided JSON */ - public static MachineToMachine fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static MachineToMachine fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, MachineToMachine.class); @@ -91,105 +89,75 @@ public static MachineToMachine fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter + private final String addressRequirements; + @Getter + private final Boolean beta; + @Getter + private final PhoneNumberCapabilities capabilities; + @Getter private final com.twilio.type.PhoneNumber friendlyName; - private final com.twilio.type.PhoneNumber phoneNumber; + @Getter + private final String isoCountry; + @Getter private final String lata; - private final String locality; - private final String rateCenter; + @Getter private final BigDecimal latitude; + @Getter + private final String locality; + @Getter private final BigDecimal longitude; - private final String region; + @Getter + private final com.twilio.type.PhoneNumber phoneNumber; + @Getter private final String postalCode; - private final String isoCountry; - private final String addressRequirements; - private final Boolean beta; - private final PhoneNumberCapabilities capabilities; + @Getter + private final String rateCenter; + @Getter + private final String region; @JsonCreator private MachineToMachine( - @JsonProperty( - "friendly_name" - ) final com.twilio.type.PhoneNumber friendlyName, - @JsonProperty( - "phone_number" - ) final com.twilio.type.PhoneNumber phoneNumber, - @JsonProperty("lata") final String lata, - @JsonProperty("locality") final String locality, - @JsonProperty("rate_center") final String rateCenter, - @JsonProperty("latitude") final BigDecimal latitude, - @JsonProperty("longitude") final BigDecimal longitude, - @JsonProperty("region") final String region, - @JsonProperty("postal_code") final String postalCode, - @JsonProperty("iso_country") final String isoCountry, - @JsonProperty("address_requirements") final String addressRequirements, - @JsonProperty("beta") final Boolean beta, - @JsonProperty("capabilities") final PhoneNumberCapabilities capabilities + @JsonProperty("address_requirements") final String addressRequirements, + @JsonProperty("beta") final Boolean beta, + @JsonProperty("capabilities") final PhoneNumberCapabilities capabilities, + @JsonProperty("friendly_name") final com.twilio.type.PhoneNumber friendlyName, + @JsonProperty("iso_country") final String isoCountry, + @JsonProperty("lata") final String lata, + @JsonProperty("latitude") final BigDecimal latitude, + @JsonProperty("locality") final String locality, + @JsonProperty("longitude") final BigDecimal longitude, + @JsonProperty("phone_number") final com.twilio.type.PhoneNumber phoneNumber, + @JsonProperty("postal_code") final String postalCode, + @JsonProperty("rate_center") final String rateCenter, + @JsonProperty("region") final String region ) { + this.addressRequirements = addressRequirements; + this.beta = beta; + this.capabilities = capabilities; this.friendlyName = friendlyName; - this.phoneNumber = phoneNumber; + this.isoCountry = isoCountry; this.lata = lata; - this.locality = locality; - this.rateCenter = rateCenter; this.latitude = latitude; + this.locality = locality; this.longitude = longitude; - this.region = region; + this.phoneNumber = phoneNumber; this.postalCode = postalCode; - this.isoCountry = isoCountry; - this.addressRequirements = addressRequirements; - this.beta = beta; - this.capabilities = capabilities; - } - - public final com.twilio.type.PhoneNumber getFriendlyName() { - return this.friendlyName; - } - - public final com.twilio.type.PhoneNumber getPhoneNumber() { - return this.phoneNumber; - } - - public final String getLata() { - return this.lata; - } - - public final String getLocality() { - return this.locality; - } - - public final String getRateCenter() { - return this.rateCenter; - } - - public final BigDecimal getLatitude() { - return this.latitude; - } - - public final BigDecimal getLongitude() { - return this.longitude; - } - - public final String getRegion() { - return this.region; - } - - public final String getPostalCode() { - return this.postalCode; - } - - public final String getIsoCountry() { - return this.isoCountry; - } - - public final String getAddressRequirements() { - return this.addressRequirements; - } - - public final Boolean getBeta() { - return this.beta; - } - - public final PhoneNumberCapabilities getCapabilities() { - return this.capabilities; + this.rateCenter = rateCenter; + this.region = region; } @Override @@ -203,40 +171,42 @@ public boolean equals(final Object o) { } MachineToMachine other = (MachineToMachine) o; - return ( - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(phoneNumber, other.phoneNumber) && - Objects.equals(lata, other.lata) && - Objects.equals(locality, other.locality) && - Objects.equals(rateCenter, other.rateCenter) && - Objects.equals(latitude, other.latitude) && - Objects.equals(longitude, other.longitude) && - Objects.equals(region, other.region) && - Objects.equals(postalCode, other.postalCode) && - Objects.equals(isoCountry, other.isoCountry) && - Objects.equals(addressRequirements, other.addressRequirements) && - Objects.equals(beta, other.beta) && - Objects.equals(capabilities, other.capabilities) + Objects.equals(addressRequirements, other.addressRequirements) && + Objects.equals(beta, other.beta) && + Objects.equals(capabilities, other.capabilities) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(isoCountry, other.isoCountry) && + Objects.equals(lata, other.lata) && + Objects.equals(latitude, other.latitude) && + Objects.equals(locality, other.locality) && + Objects.equals(longitude, other.longitude) && + Objects.equals(phoneNumber, other.phoneNumber) && + Objects.equals(postalCode, other.postalCode) && + Objects.equals(rateCenter, other.rateCenter) && + Objects.equals(region, other.region) ); } @Override public int hashCode() { return Objects.hash( - friendlyName, - phoneNumber, - lata, - locality, - rateCenter, - latitude, - longitude, - region, - postalCode, - isoCountry, - addressRequirements, - beta, - capabilities + addressRequirements, + beta, + capabilities, + friendlyName, + isoCountry, + lata, + latitude, + locality, + longitude, + phoneNumber, + postalCode, + rateCenter, + region ); } + + } + diff --git a/src/main/java/com/twilio/rest/api/v2010/account/availablephonenumbercountry/MachineToMachineReader.java b/src/main/java/com/twilio/rest/api/v2010/account/availablephonenumbercountry/MachineToMachineReader.java index 64b12734e6..7cdb67a630 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/availablephonenumbercountry/MachineToMachineReader.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/availablephonenumbercountry/MachineToMachineReader.java @@ -17,8 +17,9 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; import com.twilio.converter.Promoter; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -30,8 +31,8 @@ public class MachineToMachineReader extends Reader { - private String pathCountryCode; - private String pathAccountSid; + private String pathaccountSid; + private String pathcountryCode; private Integer areaCode; private String contains; private Boolean smsEnabled; @@ -52,72 +53,71 @@ public class MachineToMachineReader extends Reader { private Boolean faxEnabled; private Long pageSize; - public MachineToMachineReader(final String pathCountryCode) { - this.pathCountryCode = pathCountryCode; + public MachineToMachineReader(final String pathcountryCode) { + this.pathcountryCode = pathcountryCode; } - public MachineToMachineReader( - final String pathAccountSid, - final String pathCountryCode - ) { - this.pathAccountSid = pathAccountSid; - this.pathCountryCode = pathCountryCode; + public MachineToMachineReader(final String pathaccountSid, final String pathcountryCode) { + this.pathaccountSid = pathaccountSid; + this.pathcountryCode = pathcountryCode; } + public MachineToMachineReader setAreaCode(final Integer areaCode) { this.areaCode = areaCode; return this; } + public MachineToMachineReader setContains(final String contains) { this.contains = contains; return this; } + public MachineToMachineReader setSmsEnabled(final Boolean smsEnabled) { this.smsEnabled = smsEnabled; return this; } + public MachineToMachineReader setMmsEnabled(final Boolean mmsEnabled) { this.mmsEnabled = mmsEnabled; return this; } + public MachineToMachineReader setVoiceEnabled(final Boolean voiceEnabled) { this.voiceEnabled = voiceEnabled; return this; } - public MachineToMachineReader setExcludeAllAddressRequired( - final Boolean excludeAllAddressRequired - ) { + + public MachineToMachineReader setExcludeAllAddressRequired(final Boolean excludeAllAddressRequired) { this.excludeAllAddressRequired = excludeAllAddressRequired; return this; } - public MachineToMachineReader setExcludeLocalAddressRequired( - final Boolean excludeLocalAddressRequired - ) { + + public MachineToMachineReader setExcludeLocalAddressRequired(final Boolean excludeLocalAddressRequired) { this.excludeLocalAddressRequired = excludeLocalAddressRequired; return this; } - public MachineToMachineReader setExcludeForeignAddressRequired( - final Boolean excludeForeignAddressRequired - ) { + + public MachineToMachineReader setExcludeForeignAddressRequired(final Boolean excludeForeignAddressRequired) { this.excludeForeignAddressRequired = excludeForeignAddressRequired; return this; } + public MachineToMachineReader setBeta(final Boolean beta) { this.beta = beta; return this; } - public MachineToMachineReader setNearNumber( - final com.twilio.type.PhoneNumber nearNumber - ) { + + public MachineToMachineReader setNearNumber(final com.twilio.type.PhoneNumber nearNumber) { this.nearNumber = nearNumber; return this; } @@ -131,216 +131,215 @@ public MachineToMachineReader setNearLatLong(final String nearLatLong) { return this; } + public MachineToMachineReader setDistance(final Integer distance) { this.distance = distance; return this; } + public MachineToMachineReader setInPostalCode(final String inPostalCode) { this.inPostalCode = inPostalCode; return this; } + public MachineToMachineReader setInRegion(final String inRegion) { this.inRegion = inRegion; return this; } + public MachineToMachineReader setInRateCenter(final String inRateCenter) { this.inRateCenter = inRateCenter; return this; } + public MachineToMachineReader setInLata(final String inLata) { this.inLata = inLata; return this; } + public MachineToMachineReader setInLocality(final String inLocality) { this.inLocality = inLocality; return this; } + public MachineToMachineReader setFaxEnabled(final Boolean faxEnabled) { this.faxEnabled = faxEnabled; return this; } + public MachineToMachineReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/AvailablePhoneNumbers/{CountryCode}/MachineToMachine.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = - path.replace( - "{" + "CountryCode" + "}", - this.pathCountryCode.toString() - ); + + String path = "/2010-04-01/Accounts/{AccountSid}/AvailablePhoneNumbers/{CountryCode}/MachineToMachine.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "CountryCode" + "}", this.pathcountryCode.toString()); Request request = new Request( - HttpMethod.GET, - Domains.API.toString(), - path + HttpMethod.GET, + Domains.API.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "MachineToMachine read failed: Unable to connect to server" - ); + throw new ApiConnectionException("MachineToMachine read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "available_phone_numbers", - response.getContent(), - MachineToMachine.class, - client.getObjectMapper() - ); + "available_phone_numbers", + response.getContent(), + MachineToMachine.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.API.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.API.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (areaCode != null) { - request.addQueryParam("AreaCode", areaCode.toString()); + Serializer.toString(request, "AreaCode", areaCode, ParameterType.QUERY); } + + if (contains != null) { - request.addQueryParam("Contains", contains); + Serializer.toString(request, "Contains", contains, ParameterType.QUERY); } + + if (smsEnabled != null) { - request.addQueryParam("SmsEnabled", smsEnabled.toString()); + Serializer.toString(request, "SmsEnabled", smsEnabled, ParameterType.QUERY); } + + if (mmsEnabled != null) { - request.addQueryParam("MmsEnabled", mmsEnabled.toString()); + Serializer.toString(request, "MmsEnabled", mmsEnabled, ParameterType.QUERY); } + + if (voiceEnabled != null) { - request.addQueryParam("VoiceEnabled", voiceEnabled.toString()); + Serializer.toString(request, "VoiceEnabled", voiceEnabled, ParameterType.QUERY); } + + if (excludeAllAddressRequired != null) { - request.addQueryParam( - "ExcludeAllAddressRequired", - excludeAllAddressRequired.toString() - ); + Serializer.toString(request, "ExcludeAllAddressRequired", excludeAllAddressRequired, ParameterType.QUERY); } + + if (excludeLocalAddressRequired != null) { - request.addQueryParam( - "ExcludeLocalAddressRequired", - excludeLocalAddressRequired.toString() - ); + Serializer.toString(request, "ExcludeLocalAddressRequired", excludeLocalAddressRequired, ParameterType.QUERY); } + + if (excludeForeignAddressRequired != null) { - request.addQueryParam( - "ExcludeForeignAddressRequired", - excludeForeignAddressRequired.toString() - ); + Serializer.toString(request, "ExcludeForeignAddressRequired", excludeForeignAddressRequired, ParameterType.QUERY); } + + if (beta != null) { - request.addQueryParam("Beta", beta.toString()); + Serializer.toString(request, "Beta", beta, ParameterType.QUERY); } + + if (nearNumber != null) { - request.addQueryParam("NearNumber", nearNumber.toString()); + Serializer.toString(request, "NearNumber", nearNumber, ParameterType.QUERY); } + + if (nearLatLong != null) { - request.addQueryParam("NearLatLong", nearLatLong); + Serializer.toString(request, "NearLatLong", nearLatLong, ParameterType.QUERY); } + + if (distance != null) { - request.addQueryParam("Distance", distance.toString()); + Serializer.toString(request, "Distance", distance, ParameterType.QUERY); } + + if (inPostalCode != null) { - request.addQueryParam("InPostalCode", inPostalCode); + Serializer.toString(request, "InPostalCode", inPostalCode, ParameterType.QUERY); } + + if (inRegion != null) { - request.addQueryParam("InRegion", inRegion); + Serializer.toString(request, "InRegion", inRegion, ParameterType.QUERY); } + + if (inRateCenter != null) { - request.addQueryParam("InRateCenter", inRateCenter); + Serializer.toString(request, "InRateCenter", inRateCenter, ParameterType.QUERY); } + + if (inLata != null) { - request.addQueryParam("InLata", inLata); + Serializer.toString(request, "InLata", inLata, ParameterType.QUERY); } + + if (inLocality != null) { - request.addQueryParam("InLocality", inLocality); + Serializer.toString(request, "InLocality", inLocality, ParameterType.QUERY); } + + if (faxEnabled != null) { - request.addQueryParam("FaxEnabled", faxEnabled.toString()); + Serializer.toString(request, "FaxEnabled", faxEnabled, ParameterType.QUERY); } + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/availablephonenumbercountry/Mobile.java b/src/main/java/com/twilio/rest/api/v2010/account/availablephonenumbercountry/Mobile.java index 98d2acd516..dfd2114e79 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/availablephonenumbercountry/Mobile.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/availablephonenumbercountry/Mobile.java @@ -18,47 +18,48 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.type.PhoneNumberCapabilities; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.math.BigDecimal; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Mobile extends Resource { - private static final long serialVersionUID = 211749226408502L; - public static MobileReader reader(final String pathCountryCode) { - return new MobileReader(pathCountryCode); + public static MobileReader reader(final String pathcountryCode) { + return new MobileReader( + pathcountryCode + ); } - public static MobileReader reader( - final String pathAccountSid, - final String pathCountryCode - ) { - return new MobileReader(pathAccountSid, pathCountryCode); + + public static MobileReader reader(final String pathaccountSid, final String pathcountryCode) { + return new MobileReader( + pathaccountSid, pathcountryCode + ); } + /** * Converts a JSON String into a Mobile object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Mobile object represented by the provided JSON */ - public static Mobile fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Mobile fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Mobile.class); @@ -73,14 +74,11 @@ public static Mobile fromJson( * Converts a JSON InputStream into a Mobile object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Mobile object represented by the provided JSON */ - public static Mobile fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Mobile fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Mobile.class); @@ -91,105 +89,75 @@ public static Mobile fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter + private final String addressRequirements; + @Getter + private final Boolean beta; + @Getter + private final PhoneNumberCapabilities capabilities; + @Getter private final com.twilio.type.PhoneNumber friendlyName; - private final com.twilio.type.PhoneNumber phoneNumber; + @Getter + private final String isoCountry; + @Getter private final String lata; - private final String locality; - private final String rateCenter; + @Getter private final BigDecimal latitude; + @Getter + private final String locality; + @Getter private final BigDecimal longitude; - private final String region; + @Getter + private final com.twilio.type.PhoneNumber phoneNumber; + @Getter private final String postalCode; - private final String isoCountry; - private final String addressRequirements; - private final Boolean beta; - private final PhoneNumberCapabilities capabilities; + @Getter + private final String rateCenter; + @Getter + private final String region; @JsonCreator private Mobile( - @JsonProperty( - "friendly_name" - ) final com.twilio.type.PhoneNumber friendlyName, - @JsonProperty( - "phone_number" - ) final com.twilio.type.PhoneNumber phoneNumber, - @JsonProperty("lata") final String lata, - @JsonProperty("locality") final String locality, - @JsonProperty("rate_center") final String rateCenter, - @JsonProperty("latitude") final BigDecimal latitude, - @JsonProperty("longitude") final BigDecimal longitude, - @JsonProperty("region") final String region, - @JsonProperty("postal_code") final String postalCode, - @JsonProperty("iso_country") final String isoCountry, - @JsonProperty("address_requirements") final String addressRequirements, - @JsonProperty("beta") final Boolean beta, - @JsonProperty("capabilities") final PhoneNumberCapabilities capabilities + @JsonProperty("address_requirements") final String addressRequirements, + @JsonProperty("beta") final Boolean beta, + @JsonProperty("capabilities") final PhoneNumberCapabilities capabilities, + @JsonProperty("friendly_name") final com.twilio.type.PhoneNumber friendlyName, + @JsonProperty("iso_country") final String isoCountry, + @JsonProperty("lata") final String lata, + @JsonProperty("latitude") final BigDecimal latitude, + @JsonProperty("locality") final String locality, + @JsonProperty("longitude") final BigDecimal longitude, + @JsonProperty("phone_number") final com.twilio.type.PhoneNumber phoneNumber, + @JsonProperty("postal_code") final String postalCode, + @JsonProperty("rate_center") final String rateCenter, + @JsonProperty("region") final String region ) { + this.addressRequirements = addressRequirements; + this.beta = beta; + this.capabilities = capabilities; this.friendlyName = friendlyName; - this.phoneNumber = phoneNumber; + this.isoCountry = isoCountry; this.lata = lata; - this.locality = locality; - this.rateCenter = rateCenter; this.latitude = latitude; + this.locality = locality; this.longitude = longitude; - this.region = region; + this.phoneNumber = phoneNumber; this.postalCode = postalCode; - this.isoCountry = isoCountry; - this.addressRequirements = addressRequirements; - this.beta = beta; - this.capabilities = capabilities; - } - - public final com.twilio.type.PhoneNumber getFriendlyName() { - return this.friendlyName; - } - - public final com.twilio.type.PhoneNumber getPhoneNumber() { - return this.phoneNumber; - } - - public final String getLata() { - return this.lata; - } - - public final String getLocality() { - return this.locality; - } - - public final String getRateCenter() { - return this.rateCenter; - } - - public final BigDecimal getLatitude() { - return this.latitude; - } - - public final BigDecimal getLongitude() { - return this.longitude; - } - - public final String getRegion() { - return this.region; - } - - public final String getPostalCode() { - return this.postalCode; - } - - public final String getIsoCountry() { - return this.isoCountry; - } - - public final String getAddressRequirements() { - return this.addressRequirements; - } - - public final Boolean getBeta() { - return this.beta; - } - - public final PhoneNumberCapabilities getCapabilities() { - return this.capabilities; + this.rateCenter = rateCenter; + this.region = region; } @Override @@ -203,40 +171,42 @@ public boolean equals(final Object o) { } Mobile other = (Mobile) o; - return ( - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(phoneNumber, other.phoneNumber) && - Objects.equals(lata, other.lata) && - Objects.equals(locality, other.locality) && - Objects.equals(rateCenter, other.rateCenter) && - Objects.equals(latitude, other.latitude) && - Objects.equals(longitude, other.longitude) && - Objects.equals(region, other.region) && - Objects.equals(postalCode, other.postalCode) && - Objects.equals(isoCountry, other.isoCountry) && - Objects.equals(addressRequirements, other.addressRequirements) && - Objects.equals(beta, other.beta) && - Objects.equals(capabilities, other.capabilities) + Objects.equals(addressRequirements, other.addressRequirements) && + Objects.equals(beta, other.beta) && + Objects.equals(capabilities, other.capabilities) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(isoCountry, other.isoCountry) && + Objects.equals(lata, other.lata) && + Objects.equals(latitude, other.latitude) && + Objects.equals(locality, other.locality) && + Objects.equals(longitude, other.longitude) && + Objects.equals(phoneNumber, other.phoneNumber) && + Objects.equals(postalCode, other.postalCode) && + Objects.equals(rateCenter, other.rateCenter) && + Objects.equals(region, other.region) ); } @Override public int hashCode() { return Objects.hash( - friendlyName, - phoneNumber, - lata, - locality, - rateCenter, - latitude, - longitude, - region, - postalCode, - isoCountry, - addressRequirements, - beta, - capabilities + addressRequirements, + beta, + capabilities, + friendlyName, + isoCountry, + lata, + latitude, + locality, + longitude, + phoneNumber, + postalCode, + rateCenter, + region ); } + + } + diff --git a/src/main/java/com/twilio/rest/api/v2010/account/availablephonenumbercountry/MobileReader.java b/src/main/java/com/twilio/rest/api/v2010/account/availablephonenumbercountry/MobileReader.java index 01cc85ea1d..f443768ce9 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/availablephonenumbercountry/MobileReader.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/availablephonenumbercountry/MobileReader.java @@ -17,8 +17,9 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; import com.twilio.converter.Promoter; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -30,8 +31,8 @@ public class MobileReader extends Reader { - private String pathCountryCode; - private String pathAccountSid; + private String pathaccountSid; + private String pathcountryCode; private Integer areaCode; private String contains; private Boolean smsEnabled; @@ -52,72 +53,71 @@ public class MobileReader extends Reader { private Boolean faxEnabled; private Long pageSize; - public MobileReader(final String pathCountryCode) { - this.pathCountryCode = pathCountryCode; + public MobileReader(final String pathcountryCode) { + this.pathcountryCode = pathcountryCode; } - public MobileReader( - final String pathAccountSid, - final String pathCountryCode - ) { - this.pathAccountSid = pathAccountSid; - this.pathCountryCode = pathCountryCode; + public MobileReader(final String pathaccountSid, final String pathcountryCode) { + this.pathaccountSid = pathaccountSid; + this.pathcountryCode = pathcountryCode; } + public MobileReader setAreaCode(final Integer areaCode) { this.areaCode = areaCode; return this; } + public MobileReader setContains(final String contains) { this.contains = contains; return this; } + public MobileReader setSmsEnabled(final Boolean smsEnabled) { this.smsEnabled = smsEnabled; return this; } + public MobileReader setMmsEnabled(final Boolean mmsEnabled) { this.mmsEnabled = mmsEnabled; return this; } + public MobileReader setVoiceEnabled(final Boolean voiceEnabled) { this.voiceEnabled = voiceEnabled; return this; } - public MobileReader setExcludeAllAddressRequired( - final Boolean excludeAllAddressRequired - ) { + + public MobileReader setExcludeAllAddressRequired(final Boolean excludeAllAddressRequired) { this.excludeAllAddressRequired = excludeAllAddressRequired; return this; } - public MobileReader setExcludeLocalAddressRequired( - final Boolean excludeLocalAddressRequired - ) { + + public MobileReader setExcludeLocalAddressRequired(final Boolean excludeLocalAddressRequired) { this.excludeLocalAddressRequired = excludeLocalAddressRequired; return this; } - public MobileReader setExcludeForeignAddressRequired( - final Boolean excludeForeignAddressRequired - ) { + + public MobileReader setExcludeForeignAddressRequired(final Boolean excludeForeignAddressRequired) { this.excludeForeignAddressRequired = excludeForeignAddressRequired; return this; } + public MobileReader setBeta(final Boolean beta) { this.beta = beta; return this; } - public MobileReader setNearNumber( - final com.twilio.type.PhoneNumber nearNumber - ) { + + public MobileReader setNearNumber(final com.twilio.type.PhoneNumber nearNumber) { this.nearNumber = nearNumber; return this; } @@ -131,216 +131,215 @@ public MobileReader setNearLatLong(final String nearLatLong) { return this; } + public MobileReader setDistance(final Integer distance) { this.distance = distance; return this; } + public MobileReader setInPostalCode(final String inPostalCode) { this.inPostalCode = inPostalCode; return this; } + public MobileReader setInRegion(final String inRegion) { this.inRegion = inRegion; return this; } + public MobileReader setInRateCenter(final String inRateCenter) { this.inRateCenter = inRateCenter; return this; } + public MobileReader setInLata(final String inLata) { this.inLata = inLata; return this; } + public MobileReader setInLocality(final String inLocality) { this.inLocality = inLocality; return this; } + public MobileReader setFaxEnabled(final Boolean faxEnabled) { this.faxEnabled = faxEnabled; return this; } + public MobileReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/AvailablePhoneNumbers/{CountryCode}/Mobile.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = - path.replace( - "{" + "CountryCode" + "}", - this.pathCountryCode.toString() - ); + + String path = "/2010-04-01/Accounts/{AccountSid}/AvailablePhoneNumbers/{CountryCode}/Mobile.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "CountryCode" + "}", this.pathcountryCode.toString()); Request request = new Request( - HttpMethod.GET, - Domains.API.toString(), - path + HttpMethod.GET, + Domains.API.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Mobile read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Mobile read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "available_phone_numbers", - response.getContent(), - Mobile.class, - client.getObjectMapper() - ); + "available_phone_numbers", + response.getContent(), + Mobile.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.API.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.API.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (areaCode != null) { - request.addQueryParam("AreaCode", areaCode.toString()); + Serializer.toString(request, "AreaCode", areaCode, ParameterType.QUERY); } + + if (contains != null) { - request.addQueryParam("Contains", contains); + Serializer.toString(request, "Contains", contains, ParameterType.QUERY); } + + if (smsEnabled != null) { - request.addQueryParam("SmsEnabled", smsEnabled.toString()); + Serializer.toString(request, "SmsEnabled", smsEnabled, ParameterType.QUERY); } + + if (mmsEnabled != null) { - request.addQueryParam("MmsEnabled", mmsEnabled.toString()); + Serializer.toString(request, "MmsEnabled", mmsEnabled, ParameterType.QUERY); } + + if (voiceEnabled != null) { - request.addQueryParam("VoiceEnabled", voiceEnabled.toString()); + Serializer.toString(request, "VoiceEnabled", voiceEnabled, ParameterType.QUERY); } + + if (excludeAllAddressRequired != null) { - request.addQueryParam( - "ExcludeAllAddressRequired", - excludeAllAddressRequired.toString() - ); + Serializer.toString(request, "ExcludeAllAddressRequired", excludeAllAddressRequired, ParameterType.QUERY); } + + if (excludeLocalAddressRequired != null) { - request.addQueryParam( - "ExcludeLocalAddressRequired", - excludeLocalAddressRequired.toString() - ); + Serializer.toString(request, "ExcludeLocalAddressRequired", excludeLocalAddressRequired, ParameterType.QUERY); } + + if (excludeForeignAddressRequired != null) { - request.addQueryParam( - "ExcludeForeignAddressRequired", - excludeForeignAddressRequired.toString() - ); + Serializer.toString(request, "ExcludeForeignAddressRequired", excludeForeignAddressRequired, ParameterType.QUERY); } + + if (beta != null) { - request.addQueryParam("Beta", beta.toString()); + Serializer.toString(request, "Beta", beta, ParameterType.QUERY); } + + if (nearNumber != null) { - request.addQueryParam("NearNumber", nearNumber.toString()); + Serializer.toString(request, "NearNumber", nearNumber, ParameterType.QUERY); } + + if (nearLatLong != null) { - request.addQueryParam("NearLatLong", nearLatLong); + Serializer.toString(request, "NearLatLong", nearLatLong, ParameterType.QUERY); } + + if (distance != null) { - request.addQueryParam("Distance", distance.toString()); + Serializer.toString(request, "Distance", distance, ParameterType.QUERY); } + + if (inPostalCode != null) { - request.addQueryParam("InPostalCode", inPostalCode); + Serializer.toString(request, "InPostalCode", inPostalCode, ParameterType.QUERY); } + + if (inRegion != null) { - request.addQueryParam("InRegion", inRegion); + Serializer.toString(request, "InRegion", inRegion, ParameterType.QUERY); } + + if (inRateCenter != null) { - request.addQueryParam("InRateCenter", inRateCenter); + Serializer.toString(request, "InRateCenter", inRateCenter, ParameterType.QUERY); } + + if (inLata != null) { - request.addQueryParam("InLata", inLata); + Serializer.toString(request, "InLata", inLata, ParameterType.QUERY); } + + if (inLocality != null) { - request.addQueryParam("InLocality", inLocality); + Serializer.toString(request, "InLocality", inLocality, ParameterType.QUERY); } + + if (faxEnabled != null) { - request.addQueryParam("FaxEnabled", faxEnabled.toString()); + Serializer.toString(request, "FaxEnabled", faxEnabled, ParameterType.QUERY); } + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/availablephonenumbercountry/National.java b/src/main/java/com/twilio/rest/api/v2010/account/availablephonenumbercountry/National.java index d9489d1055..63bb0a8d86 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/availablephonenumbercountry/National.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/availablephonenumbercountry/National.java @@ -18,47 +18,48 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.type.PhoneNumberCapabilities; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.math.BigDecimal; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class National extends Resource { - private static final long serialVersionUID = 211749226408502L; - public static NationalReader reader(final String pathCountryCode) { - return new NationalReader(pathCountryCode); + public static NationalReader reader(final String pathcountryCode) { + return new NationalReader( + pathcountryCode + ); } - public static NationalReader reader( - final String pathAccountSid, - final String pathCountryCode - ) { - return new NationalReader(pathAccountSid, pathCountryCode); + + public static NationalReader reader(final String pathaccountSid, final String pathcountryCode) { + return new NationalReader( + pathaccountSid, pathcountryCode + ); } + /** * Converts a JSON String into a National object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return National object represented by the provided JSON */ - public static National fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static National fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, National.class); @@ -73,14 +74,11 @@ public static National fromJson( * Converts a JSON InputStream into a National object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return National object represented by the provided JSON */ - public static National fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static National fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, National.class); @@ -91,105 +89,75 @@ public static National fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter + private final String addressRequirements; + @Getter + private final Boolean beta; + @Getter + private final PhoneNumberCapabilities capabilities; + @Getter private final com.twilio.type.PhoneNumber friendlyName; - private final com.twilio.type.PhoneNumber phoneNumber; + @Getter + private final String isoCountry; + @Getter private final String lata; - private final String locality; - private final String rateCenter; + @Getter private final BigDecimal latitude; + @Getter + private final String locality; + @Getter private final BigDecimal longitude; - private final String region; + @Getter + private final com.twilio.type.PhoneNumber phoneNumber; + @Getter private final String postalCode; - private final String isoCountry; - private final String addressRequirements; - private final Boolean beta; - private final PhoneNumberCapabilities capabilities; + @Getter + private final String rateCenter; + @Getter + private final String region; @JsonCreator private National( - @JsonProperty( - "friendly_name" - ) final com.twilio.type.PhoneNumber friendlyName, - @JsonProperty( - "phone_number" - ) final com.twilio.type.PhoneNumber phoneNumber, - @JsonProperty("lata") final String lata, - @JsonProperty("locality") final String locality, - @JsonProperty("rate_center") final String rateCenter, - @JsonProperty("latitude") final BigDecimal latitude, - @JsonProperty("longitude") final BigDecimal longitude, - @JsonProperty("region") final String region, - @JsonProperty("postal_code") final String postalCode, - @JsonProperty("iso_country") final String isoCountry, - @JsonProperty("address_requirements") final String addressRequirements, - @JsonProperty("beta") final Boolean beta, - @JsonProperty("capabilities") final PhoneNumberCapabilities capabilities + @JsonProperty("address_requirements") final String addressRequirements, + @JsonProperty("beta") final Boolean beta, + @JsonProperty("capabilities") final PhoneNumberCapabilities capabilities, + @JsonProperty("friendly_name") final com.twilio.type.PhoneNumber friendlyName, + @JsonProperty("iso_country") final String isoCountry, + @JsonProperty("lata") final String lata, + @JsonProperty("latitude") final BigDecimal latitude, + @JsonProperty("locality") final String locality, + @JsonProperty("longitude") final BigDecimal longitude, + @JsonProperty("phone_number") final com.twilio.type.PhoneNumber phoneNumber, + @JsonProperty("postal_code") final String postalCode, + @JsonProperty("rate_center") final String rateCenter, + @JsonProperty("region") final String region ) { + this.addressRequirements = addressRequirements; + this.beta = beta; + this.capabilities = capabilities; this.friendlyName = friendlyName; - this.phoneNumber = phoneNumber; + this.isoCountry = isoCountry; this.lata = lata; - this.locality = locality; - this.rateCenter = rateCenter; this.latitude = latitude; + this.locality = locality; this.longitude = longitude; - this.region = region; + this.phoneNumber = phoneNumber; this.postalCode = postalCode; - this.isoCountry = isoCountry; - this.addressRequirements = addressRequirements; - this.beta = beta; - this.capabilities = capabilities; - } - - public final com.twilio.type.PhoneNumber getFriendlyName() { - return this.friendlyName; - } - - public final com.twilio.type.PhoneNumber getPhoneNumber() { - return this.phoneNumber; - } - - public final String getLata() { - return this.lata; - } - - public final String getLocality() { - return this.locality; - } - - public final String getRateCenter() { - return this.rateCenter; - } - - public final BigDecimal getLatitude() { - return this.latitude; - } - - public final BigDecimal getLongitude() { - return this.longitude; - } - - public final String getRegion() { - return this.region; - } - - public final String getPostalCode() { - return this.postalCode; - } - - public final String getIsoCountry() { - return this.isoCountry; - } - - public final String getAddressRequirements() { - return this.addressRequirements; - } - - public final Boolean getBeta() { - return this.beta; - } - - public final PhoneNumberCapabilities getCapabilities() { - return this.capabilities; + this.rateCenter = rateCenter; + this.region = region; } @Override @@ -203,40 +171,42 @@ public boolean equals(final Object o) { } National other = (National) o; - return ( - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(phoneNumber, other.phoneNumber) && - Objects.equals(lata, other.lata) && - Objects.equals(locality, other.locality) && - Objects.equals(rateCenter, other.rateCenter) && - Objects.equals(latitude, other.latitude) && - Objects.equals(longitude, other.longitude) && - Objects.equals(region, other.region) && - Objects.equals(postalCode, other.postalCode) && - Objects.equals(isoCountry, other.isoCountry) && - Objects.equals(addressRequirements, other.addressRequirements) && - Objects.equals(beta, other.beta) && - Objects.equals(capabilities, other.capabilities) + Objects.equals(addressRequirements, other.addressRequirements) && + Objects.equals(beta, other.beta) && + Objects.equals(capabilities, other.capabilities) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(isoCountry, other.isoCountry) && + Objects.equals(lata, other.lata) && + Objects.equals(latitude, other.latitude) && + Objects.equals(locality, other.locality) && + Objects.equals(longitude, other.longitude) && + Objects.equals(phoneNumber, other.phoneNumber) && + Objects.equals(postalCode, other.postalCode) && + Objects.equals(rateCenter, other.rateCenter) && + Objects.equals(region, other.region) ); } @Override public int hashCode() { return Objects.hash( - friendlyName, - phoneNumber, - lata, - locality, - rateCenter, - latitude, - longitude, - region, - postalCode, - isoCountry, - addressRequirements, - beta, - capabilities + addressRequirements, + beta, + capabilities, + friendlyName, + isoCountry, + lata, + latitude, + locality, + longitude, + phoneNumber, + postalCode, + rateCenter, + region ); } + + } + diff --git a/src/main/java/com/twilio/rest/api/v2010/account/availablephonenumbercountry/NationalReader.java b/src/main/java/com/twilio/rest/api/v2010/account/availablephonenumbercountry/NationalReader.java index bda9c10f2b..38aab5f2be 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/availablephonenumbercountry/NationalReader.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/availablephonenumbercountry/NationalReader.java @@ -17,8 +17,9 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; import com.twilio.converter.Promoter; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -30,8 +31,8 @@ public class NationalReader extends Reader { - private String pathCountryCode; - private String pathAccountSid; + private String pathaccountSid; + private String pathcountryCode; private Integer areaCode; private String contains; private Boolean smsEnabled; @@ -52,72 +53,71 @@ public class NationalReader extends Reader { private Boolean faxEnabled; private Long pageSize; - public NationalReader(final String pathCountryCode) { - this.pathCountryCode = pathCountryCode; + public NationalReader(final String pathcountryCode) { + this.pathcountryCode = pathcountryCode; } - public NationalReader( - final String pathAccountSid, - final String pathCountryCode - ) { - this.pathAccountSid = pathAccountSid; - this.pathCountryCode = pathCountryCode; + public NationalReader(final String pathaccountSid, final String pathcountryCode) { + this.pathaccountSid = pathaccountSid; + this.pathcountryCode = pathcountryCode; } + public NationalReader setAreaCode(final Integer areaCode) { this.areaCode = areaCode; return this; } + public NationalReader setContains(final String contains) { this.contains = contains; return this; } + public NationalReader setSmsEnabled(final Boolean smsEnabled) { this.smsEnabled = smsEnabled; return this; } + public NationalReader setMmsEnabled(final Boolean mmsEnabled) { this.mmsEnabled = mmsEnabled; return this; } + public NationalReader setVoiceEnabled(final Boolean voiceEnabled) { this.voiceEnabled = voiceEnabled; return this; } - public NationalReader setExcludeAllAddressRequired( - final Boolean excludeAllAddressRequired - ) { + + public NationalReader setExcludeAllAddressRequired(final Boolean excludeAllAddressRequired) { this.excludeAllAddressRequired = excludeAllAddressRequired; return this; } - public NationalReader setExcludeLocalAddressRequired( - final Boolean excludeLocalAddressRequired - ) { + + public NationalReader setExcludeLocalAddressRequired(final Boolean excludeLocalAddressRequired) { this.excludeLocalAddressRequired = excludeLocalAddressRequired; return this; } - public NationalReader setExcludeForeignAddressRequired( - final Boolean excludeForeignAddressRequired - ) { + + public NationalReader setExcludeForeignAddressRequired(final Boolean excludeForeignAddressRequired) { this.excludeForeignAddressRequired = excludeForeignAddressRequired; return this; } + public NationalReader setBeta(final Boolean beta) { this.beta = beta; return this; } - public NationalReader setNearNumber( - final com.twilio.type.PhoneNumber nearNumber - ) { + + public NationalReader setNearNumber(final com.twilio.type.PhoneNumber nearNumber) { this.nearNumber = nearNumber; return this; } @@ -131,216 +131,215 @@ public NationalReader setNearLatLong(final String nearLatLong) { return this; } + public NationalReader setDistance(final Integer distance) { this.distance = distance; return this; } + public NationalReader setInPostalCode(final String inPostalCode) { this.inPostalCode = inPostalCode; return this; } + public NationalReader setInRegion(final String inRegion) { this.inRegion = inRegion; return this; } + public NationalReader setInRateCenter(final String inRateCenter) { this.inRateCenter = inRateCenter; return this; } + public NationalReader setInLata(final String inLata) { this.inLata = inLata; return this; } + public NationalReader setInLocality(final String inLocality) { this.inLocality = inLocality; return this; } + public NationalReader setFaxEnabled(final Boolean faxEnabled) { this.faxEnabled = faxEnabled; return this; } + public NationalReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/AvailablePhoneNumbers/{CountryCode}/National.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = - path.replace( - "{" + "CountryCode" + "}", - this.pathCountryCode.toString() - ); + + String path = "/2010-04-01/Accounts/{AccountSid}/AvailablePhoneNumbers/{CountryCode}/National.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "CountryCode" + "}", this.pathcountryCode.toString()); Request request = new Request( - HttpMethod.GET, - Domains.API.toString(), - path + HttpMethod.GET, + Domains.API.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "National read failed: Unable to connect to server" - ); + throw new ApiConnectionException("National read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "available_phone_numbers", - response.getContent(), - National.class, - client.getObjectMapper() - ); + "available_phone_numbers", + response.getContent(), + National.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.API.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.API.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (areaCode != null) { - request.addQueryParam("AreaCode", areaCode.toString()); + Serializer.toString(request, "AreaCode", areaCode, ParameterType.QUERY); } + + if (contains != null) { - request.addQueryParam("Contains", contains); + Serializer.toString(request, "Contains", contains, ParameterType.QUERY); } + + if (smsEnabled != null) { - request.addQueryParam("SmsEnabled", smsEnabled.toString()); + Serializer.toString(request, "SmsEnabled", smsEnabled, ParameterType.QUERY); } + + if (mmsEnabled != null) { - request.addQueryParam("MmsEnabled", mmsEnabled.toString()); + Serializer.toString(request, "MmsEnabled", mmsEnabled, ParameterType.QUERY); } + + if (voiceEnabled != null) { - request.addQueryParam("VoiceEnabled", voiceEnabled.toString()); + Serializer.toString(request, "VoiceEnabled", voiceEnabled, ParameterType.QUERY); } + + if (excludeAllAddressRequired != null) { - request.addQueryParam( - "ExcludeAllAddressRequired", - excludeAllAddressRequired.toString() - ); + Serializer.toString(request, "ExcludeAllAddressRequired", excludeAllAddressRequired, ParameterType.QUERY); } + + if (excludeLocalAddressRequired != null) { - request.addQueryParam( - "ExcludeLocalAddressRequired", - excludeLocalAddressRequired.toString() - ); + Serializer.toString(request, "ExcludeLocalAddressRequired", excludeLocalAddressRequired, ParameterType.QUERY); } + + if (excludeForeignAddressRequired != null) { - request.addQueryParam( - "ExcludeForeignAddressRequired", - excludeForeignAddressRequired.toString() - ); + Serializer.toString(request, "ExcludeForeignAddressRequired", excludeForeignAddressRequired, ParameterType.QUERY); } + + if (beta != null) { - request.addQueryParam("Beta", beta.toString()); + Serializer.toString(request, "Beta", beta, ParameterType.QUERY); } + + if (nearNumber != null) { - request.addQueryParam("NearNumber", nearNumber.toString()); + Serializer.toString(request, "NearNumber", nearNumber, ParameterType.QUERY); } + + if (nearLatLong != null) { - request.addQueryParam("NearLatLong", nearLatLong); + Serializer.toString(request, "NearLatLong", nearLatLong, ParameterType.QUERY); } + + if (distance != null) { - request.addQueryParam("Distance", distance.toString()); + Serializer.toString(request, "Distance", distance, ParameterType.QUERY); } + + if (inPostalCode != null) { - request.addQueryParam("InPostalCode", inPostalCode); + Serializer.toString(request, "InPostalCode", inPostalCode, ParameterType.QUERY); } + + if (inRegion != null) { - request.addQueryParam("InRegion", inRegion); + Serializer.toString(request, "InRegion", inRegion, ParameterType.QUERY); } + + if (inRateCenter != null) { - request.addQueryParam("InRateCenter", inRateCenter); + Serializer.toString(request, "InRateCenter", inRateCenter, ParameterType.QUERY); } + + if (inLata != null) { - request.addQueryParam("InLata", inLata); + Serializer.toString(request, "InLata", inLata, ParameterType.QUERY); } + + if (inLocality != null) { - request.addQueryParam("InLocality", inLocality); + Serializer.toString(request, "InLocality", inLocality, ParameterType.QUERY); } + + if (faxEnabled != null) { - request.addQueryParam("FaxEnabled", faxEnabled.toString()); + Serializer.toString(request, "FaxEnabled", faxEnabled, ParameterType.QUERY); } + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/availablephonenumbercountry/SharedCost.java b/src/main/java/com/twilio/rest/api/v2010/account/availablephonenumbercountry/SharedCost.java index cf263c0a75..74daf5c582 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/availablephonenumbercountry/SharedCost.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/availablephonenumbercountry/SharedCost.java @@ -18,47 +18,48 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.type.PhoneNumberCapabilities; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.math.BigDecimal; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class SharedCost extends Resource { - private static final long serialVersionUID = 211749226408502L; - public static SharedCostReader reader(final String pathCountryCode) { - return new SharedCostReader(pathCountryCode); + public static SharedCostReader reader(final String pathcountryCode) { + return new SharedCostReader( + pathcountryCode + ); } - public static SharedCostReader reader( - final String pathAccountSid, - final String pathCountryCode - ) { - return new SharedCostReader(pathAccountSid, pathCountryCode); + + public static SharedCostReader reader(final String pathaccountSid, final String pathcountryCode) { + return new SharedCostReader( + pathaccountSid, pathcountryCode + ); } + /** * Converts a JSON String into a SharedCost object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return SharedCost object represented by the provided JSON */ - public static SharedCost fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static SharedCost fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, SharedCost.class); @@ -73,14 +74,11 @@ public static SharedCost fromJson( * Converts a JSON InputStream into a SharedCost object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return SharedCost object represented by the provided JSON */ - public static SharedCost fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static SharedCost fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, SharedCost.class); @@ -91,105 +89,75 @@ public static SharedCost fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter + private final String addressRequirements; + @Getter + private final Boolean beta; + @Getter + private final PhoneNumberCapabilities capabilities; + @Getter private final com.twilio.type.PhoneNumber friendlyName; - private final com.twilio.type.PhoneNumber phoneNumber; + @Getter + private final String isoCountry; + @Getter private final String lata; - private final String locality; - private final String rateCenter; + @Getter private final BigDecimal latitude; + @Getter + private final String locality; + @Getter private final BigDecimal longitude; - private final String region; + @Getter + private final com.twilio.type.PhoneNumber phoneNumber; + @Getter private final String postalCode; - private final String isoCountry; - private final String addressRequirements; - private final Boolean beta; - private final PhoneNumberCapabilities capabilities; + @Getter + private final String rateCenter; + @Getter + private final String region; @JsonCreator private SharedCost( - @JsonProperty( - "friendly_name" - ) final com.twilio.type.PhoneNumber friendlyName, - @JsonProperty( - "phone_number" - ) final com.twilio.type.PhoneNumber phoneNumber, - @JsonProperty("lata") final String lata, - @JsonProperty("locality") final String locality, - @JsonProperty("rate_center") final String rateCenter, - @JsonProperty("latitude") final BigDecimal latitude, - @JsonProperty("longitude") final BigDecimal longitude, - @JsonProperty("region") final String region, - @JsonProperty("postal_code") final String postalCode, - @JsonProperty("iso_country") final String isoCountry, - @JsonProperty("address_requirements") final String addressRequirements, - @JsonProperty("beta") final Boolean beta, - @JsonProperty("capabilities") final PhoneNumberCapabilities capabilities + @JsonProperty("address_requirements") final String addressRequirements, + @JsonProperty("beta") final Boolean beta, + @JsonProperty("capabilities") final PhoneNumberCapabilities capabilities, + @JsonProperty("friendly_name") final com.twilio.type.PhoneNumber friendlyName, + @JsonProperty("iso_country") final String isoCountry, + @JsonProperty("lata") final String lata, + @JsonProperty("latitude") final BigDecimal latitude, + @JsonProperty("locality") final String locality, + @JsonProperty("longitude") final BigDecimal longitude, + @JsonProperty("phone_number") final com.twilio.type.PhoneNumber phoneNumber, + @JsonProperty("postal_code") final String postalCode, + @JsonProperty("rate_center") final String rateCenter, + @JsonProperty("region") final String region ) { + this.addressRequirements = addressRequirements; + this.beta = beta; + this.capabilities = capabilities; this.friendlyName = friendlyName; - this.phoneNumber = phoneNumber; + this.isoCountry = isoCountry; this.lata = lata; - this.locality = locality; - this.rateCenter = rateCenter; this.latitude = latitude; + this.locality = locality; this.longitude = longitude; - this.region = region; + this.phoneNumber = phoneNumber; this.postalCode = postalCode; - this.isoCountry = isoCountry; - this.addressRequirements = addressRequirements; - this.beta = beta; - this.capabilities = capabilities; - } - - public final com.twilio.type.PhoneNumber getFriendlyName() { - return this.friendlyName; - } - - public final com.twilio.type.PhoneNumber getPhoneNumber() { - return this.phoneNumber; - } - - public final String getLata() { - return this.lata; - } - - public final String getLocality() { - return this.locality; - } - - public final String getRateCenter() { - return this.rateCenter; - } - - public final BigDecimal getLatitude() { - return this.latitude; - } - - public final BigDecimal getLongitude() { - return this.longitude; - } - - public final String getRegion() { - return this.region; - } - - public final String getPostalCode() { - return this.postalCode; - } - - public final String getIsoCountry() { - return this.isoCountry; - } - - public final String getAddressRequirements() { - return this.addressRequirements; - } - - public final Boolean getBeta() { - return this.beta; - } - - public final PhoneNumberCapabilities getCapabilities() { - return this.capabilities; + this.rateCenter = rateCenter; + this.region = region; } @Override @@ -203,40 +171,42 @@ public boolean equals(final Object o) { } SharedCost other = (SharedCost) o; - return ( - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(phoneNumber, other.phoneNumber) && - Objects.equals(lata, other.lata) && - Objects.equals(locality, other.locality) && - Objects.equals(rateCenter, other.rateCenter) && - Objects.equals(latitude, other.latitude) && - Objects.equals(longitude, other.longitude) && - Objects.equals(region, other.region) && - Objects.equals(postalCode, other.postalCode) && - Objects.equals(isoCountry, other.isoCountry) && - Objects.equals(addressRequirements, other.addressRequirements) && - Objects.equals(beta, other.beta) && - Objects.equals(capabilities, other.capabilities) + Objects.equals(addressRequirements, other.addressRequirements) && + Objects.equals(beta, other.beta) && + Objects.equals(capabilities, other.capabilities) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(isoCountry, other.isoCountry) && + Objects.equals(lata, other.lata) && + Objects.equals(latitude, other.latitude) && + Objects.equals(locality, other.locality) && + Objects.equals(longitude, other.longitude) && + Objects.equals(phoneNumber, other.phoneNumber) && + Objects.equals(postalCode, other.postalCode) && + Objects.equals(rateCenter, other.rateCenter) && + Objects.equals(region, other.region) ); } @Override public int hashCode() { return Objects.hash( - friendlyName, - phoneNumber, - lata, - locality, - rateCenter, - latitude, - longitude, - region, - postalCode, - isoCountry, - addressRequirements, - beta, - capabilities + addressRequirements, + beta, + capabilities, + friendlyName, + isoCountry, + lata, + latitude, + locality, + longitude, + phoneNumber, + postalCode, + rateCenter, + region ); } + + } + diff --git a/src/main/java/com/twilio/rest/api/v2010/account/availablephonenumbercountry/SharedCostReader.java b/src/main/java/com/twilio/rest/api/v2010/account/availablephonenumbercountry/SharedCostReader.java index 10d5b8762c..14be7ec03d 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/availablephonenumbercountry/SharedCostReader.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/availablephonenumbercountry/SharedCostReader.java @@ -17,8 +17,9 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; import com.twilio.converter.Promoter; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -30,8 +31,8 @@ public class SharedCostReader extends Reader { - private String pathCountryCode; - private String pathAccountSid; + private String pathaccountSid; + private String pathcountryCode; private Integer areaCode; private String contains; private Boolean smsEnabled; @@ -52,72 +53,71 @@ public class SharedCostReader extends Reader { private Boolean faxEnabled; private Long pageSize; - public SharedCostReader(final String pathCountryCode) { - this.pathCountryCode = pathCountryCode; + public SharedCostReader(final String pathcountryCode) { + this.pathcountryCode = pathcountryCode; } - public SharedCostReader( - final String pathAccountSid, - final String pathCountryCode - ) { - this.pathAccountSid = pathAccountSid; - this.pathCountryCode = pathCountryCode; + public SharedCostReader(final String pathaccountSid, final String pathcountryCode) { + this.pathaccountSid = pathaccountSid; + this.pathcountryCode = pathcountryCode; } + public SharedCostReader setAreaCode(final Integer areaCode) { this.areaCode = areaCode; return this; } + public SharedCostReader setContains(final String contains) { this.contains = contains; return this; } + public SharedCostReader setSmsEnabled(final Boolean smsEnabled) { this.smsEnabled = smsEnabled; return this; } + public SharedCostReader setMmsEnabled(final Boolean mmsEnabled) { this.mmsEnabled = mmsEnabled; return this; } + public SharedCostReader setVoiceEnabled(final Boolean voiceEnabled) { this.voiceEnabled = voiceEnabled; return this; } - public SharedCostReader setExcludeAllAddressRequired( - final Boolean excludeAllAddressRequired - ) { + + public SharedCostReader setExcludeAllAddressRequired(final Boolean excludeAllAddressRequired) { this.excludeAllAddressRequired = excludeAllAddressRequired; return this; } - public SharedCostReader setExcludeLocalAddressRequired( - final Boolean excludeLocalAddressRequired - ) { + + public SharedCostReader setExcludeLocalAddressRequired(final Boolean excludeLocalAddressRequired) { this.excludeLocalAddressRequired = excludeLocalAddressRequired; return this; } - public SharedCostReader setExcludeForeignAddressRequired( - final Boolean excludeForeignAddressRequired - ) { + + public SharedCostReader setExcludeForeignAddressRequired(final Boolean excludeForeignAddressRequired) { this.excludeForeignAddressRequired = excludeForeignAddressRequired; return this; } + public SharedCostReader setBeta(final Boolean beta) { this.beta = beta; return this; } - public SharedCostReader setNearNumber( - final com.twilio.type.PhoneNumber nearNumber - ) { + + public SharedCostReader setNearNumber(final com.twilio.type.PhoneNumber nearNumber) { this.nearNumber = nearNumber; return this; } @@ -131,216 +131,215 @@ public SharedCostReader setNearLatLong(final String nearLatLong) { return this; } + public SharedCostReader setDistance(final Integer distance) { this.distance = distance; return this; } + public SharedCostReader setInPostalCode(final String inPostalCode) { this.inPostalCode = inPostalCode; return this; } + public SharedCostReader setInRegion(final String inRegion) { this.inRegion = inRegion; return this; } + public SharedCostReader setInRateCenter(final String inRateCenter) { this.inRateCenter = inRateCenter; return this; } + public SharedCostReader setInLata(final String inLata) { this.inLata = inLata; return this; } + public SharedCostReader setInLocality(final String inLocality) { this.inLocality = inLocality; return this; } + public SharedCostReader setFaxEnabled(final Boolean faxEnabled) { this.faxEnabled = faxEnabled; return this; } + public SharedCostReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/AvailablePhoneNumbers/{CountryCode}/SharedCost.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = - path.replace( - "{" + "CountryCode" + "}", - this.pathCountryCode.toString() - ); + + String path = "/2010-04-01/Accounts/{AccountSid}/AvailablePhoneNumbers/{CountryCode}/SharedCost.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "CountryCode" + "}", this.pathcountryCode.toString()); Request request = new Request( - HttpMethod.GET, - Domains.API.toString(), - path + HttpMethod.GET, + Domains.API.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "SharedCost read failed: Unable to connect to server" - ); + throw new ApiConnectionException("SharedCost read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "available_phone_numbers", - response.getContent(), - SharedCost.class, - client.getObjectMapper() - ); + "available_phone_numbers", + response.getContent(), + SharedCost.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.API.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.API.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (areaCode != null) { - request.addQueryParam("AreaCode", areaCode.toString()); + Serializer.toString(request, "AreaCode", areaCode, ParameterType.QUERY); } + + if (contains != null) { - request.addQueryParam("Contains", contains); + Serializer.toString(request, "Contains", contains, ParameterType.QUERY); } + + if (smsEnabled != null) { - request.addQueryParam("SmsEnabled", smsEnabled.toString()); + Serializer.toString(request, "SmsEnabled", smsEnabled, ParameterType.QUERY); } + + if (mmsEnabled != null) { - request.addQueryParam("MmsEnabled", mmsEnabled.toString()); + Serializer.toString(request, "MmsEnabled", mmsEnabled, ParameterType.QUERY); } + + if (voiceEnabled != null) { - request.addQueryParam("VoiceEnabled", voiceEnabled.toString()); + Serializer.toString(request, "VoiceEnabled", voiceEnabled, ParameterType.QUERY); } + + if (excludeAllAddressRequired != null) { - request.addQueryParam( - "ExcludeAllAddressRequired", - excludeAllAddressRequired.toString() - ); + Serializer.toString(request, "ExcludeAllAddressRequired", excludeAllAddressRequired, ParameterType.QUERY); } + + if (excludeLocalAddressRequired != null) { - request.addQueryParam( - "ExcludeLocalAddressRequired", - excludeLocalAddressRequired.toString() - ); + Serializer.toString(request, "ExcludeLocalAddressRequired", excludeLocalAddressRequired, ParameterType.QUERY); } + + if (excludeForeignAddressRequired != null) { - request.addQueryParam( - "ExcludeForeignAddressRequired", - excludeForeignAddressRequired.toString() - ); + Serializer.toString(request, "ExcludeForeignAddressRequired", excludeForeignAddressRequired, ParameterType.QUERY); } + + if (beta != null) { - request.addQueryParam("Beta", beta.toString()); + Serializer.toString(request, "Beta", beta, ParameterType.QUERY); } + + if (nearNumber != null) { - request.addQueryParam("NearNumber", nearNumber.toString()); + Serializer.toString(request, "NearNumber", nearNumber, ParameterType.QUERY); } + + if (nearLatLong != null) { - request.addQueryParam("NearLatLong", nearLatLong); + Serializer.toString(request, "NearLatLong", nearLatLong, ParameterType.QUERY); } + + if (distance != null) { - request.addQueryParam("Distance", distance.toString()); + Serializer.toString(request, "Distance", distance, ParameterType.QUERY); } + + if (inPostalCode != null) { - request.addQueryParam("InPostalCode", inPostalCode); + Serializer.toString(request, "InPostalCode", inPostalCode, ParameterType.QUERY); } + + if (inRegion != null) { - request.addQueryParam("InRegion", inRegion); + Serializer.toString(request, "InRegion", inRegion, ParameterType.QUERY); } + + if (inRateCenter != null) { - request.addQueryParam("InRateCenter", inRateCenter); + Serializer.toString(request, "InRateCenter", inRateCenter, ParameterType.QUERY); } + + if (inLata != null) { - request.addQueryParam("InLata", inLata); + Serializer.toString(request, "InLata", inLata, ParameterType.QUERY); } + + if (inLocality != null) { - request.addQueryParam("InLocality", inLocality); + Serializer.toString(request, "InLocality", inLocality, ParameterType.QUERY); } + + if (faxEnabled != null) { - request.addQueryParam("FaxEnabled", faxEnabled.toString()); + Serializer.toString(request, "FaxEnabled", faxEnabled, ParameterType.QUERY); } + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/availablephonenumbercountry/TollFree.java b/src/main/java/com/twilio/rest/api/v2010/account/availablephonenumbercountry/TollFree.java index c9d8ac7b2e..44a3227545 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/availablephonenumbercountry/TollFree.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/availablephonenumbercountry/TollFree.java @@ -18,47 +18,48 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.type.PhoneNumberCapabilities; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.math.BigDecimal; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class TollFree extends Resource { - private static final long serialVersionUID = 211749226408502L; - public static TollFreeReader reader(final String pathCountryCode) { - return new TollFreeReader(pathCountryCode); + public static TollFreeReader reader(final String pathcountryCode) { + return new TollFreeReader( + pathcountryCode + ); } - public static TollFreeReader reader( - final String pathAccountSid, - final String pathCountryCode - ) { - return new TollFreeReader(pathAccountSid, pathCountryCode); + + public static TollFreeReader reader(final String pathaccountSid, final String pathcountryCode) { + return new TollFreeReader( + pathaccountSid, pathcountryCode + ); } + /** * Converts a JSON String into a TollFree object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return TollFree object represented by the provided JSON */ - public static TollFree fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static TollFree fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, TollFree.class); @@ -73,14 +74,11 @@ public static TollFree fromJson( * Converts a JSON InputStream into a TollFree object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return TollFree object represented by the provided JSON */ - public static TollFree fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static TollFree fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, TollFree.class); @@ -91,105 +89,75 @@ public static TollFree fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter + private final String addressRequirements; + @Getter + private final Boolean beta; + @Getter + private final PhoneNumberCapabilities capabilities; + @Getter private final com.twilio.type.PhoneNumber friendlyName; - private final com.twilio.type.PhoneNumber phoneNumber; + @Getter + private final String isoCountry; + @Getter private final String lata; - private final String locality; - private final String rateCenter; + @Getter private final BigDecimal latitude; + @Getter + private final String locality; + @Getter private final BigDecimal longitude; - private final String region; + @Getter + private final com.twilio.type.PhoneNumber phoneNumber; + @Getter private final String postalCode; - private final String isoCountry; - private final String addressRequirements; - private final Boolean beta; - private final PhoneNumberCapabilities capabilities; + @Getter + private final String rateCenter; + @Getter + private final String region; @JsonCreator private TollFree( - @JsonProperty( - "friendly_name" - ) final com.twilio.type.PhoneNumber friendlyName, - @JsonProperty( - "phone_number" - ) final com.twilio.type.PhoneNumber phoneNumber, - @JsonProperty("lata") final String lata, - @JsonProperty("locality") final String locality, - @JsonProperty("rate_center") final String rateCenter, - @JsonProperty("latitude") final BigDecimal latitude, - @JsonProperty("longitude") final BigDecimal longitude, - @JsonProperty("region") final String region, - @JsonProperty("postal_code") final String postalCode, - @JsonProperty("iso_country") final String isoCountry, - @JsonProperty("address_requirements") final String addressRequirements, - @JsonProperty("beta") final Boolean beta, - @JsonProperty("capabilities") final PhoneNumberCapabilities capabilities + @JsonProperty("address_requirements") final String addressRequirements, + @JsonProperty("beta") final Boolean beta, + @JsonProperty("capabilities") final PhoneNumberCapabilities capabilities, + @JsonProperty("friendly_name") final com.twilio.type.PhoneNumber friendlyName, + @JsonProperty("iso_country") final String isoCountry, + @JsonProperty("lata") final String lata, + @JsonProperty("latitude") final BigDecimal latitude, + @JsonProperty("locality") final String locality, + @JsonProperty("longitude") final BigDecimal longitude, + @JsonProperty("phone_number") final com.twilio.type.PhoneNumber phoneNumber, + @JsonProperty("postal_code") final String postalCode, + @JsonProperty("rate_center") final String rateCenter, + @JsonProperty("region") final String region ) { + this.addressRequirements = addressRequirements; + this.beta = beta; + this.capabilities = capabilities; this.friendlyName = friendlyName; - this.phoneNumber = phoneNumber; + this.isoCountry = isoCountry; this.lata = lata; - this.locality = locality; - this.rateCenter = rateCenter; this.latitude = latitude; + this.locality = locality; this.longitude = longitude; - this.region = region; + this.phoneNumber = phoneNumber; this.postalCode = postalCode; - this.isoCountry = isoCountry; - this.addressRequirements = addressRequirements; - this.beta = beta; - this.capabilities = capabilities; - } - - public final com.twilio.type.PhoneNumber getFriendlyName() { - return this.friendlyName; - } - - public final com.twilio.type.PhoneNumber getPhoneNumber() { - return this.phoneNumber; - } - - public final String getLata() { - return this.lata; - } - - public final String getLocality() { - return this.locality; - } - - public final String getRateCenter() { - return this.rateCenter; - } - - public final BigDecimal getLatitude() { - return this.latitude; - } - - public final BigDecimal getLongitude() { - return this.longitude; - } - - public final String getRegion() { - return this.region; - } - - public final String getPostalCode() { - return this.postalCode; - } - - public final String getIsoCountry() { - return this.isoCountry; - } - - public final String getAddressRequirements() { - return this.addressRequirements; - } - - public final Boolean getBeta() { - return this.beta; - } - - public final PhoneNumberCapabilities getCapabilities() { - return this.capabilities; + this.rateCenter = rateCenter; + this.region = region; } @Override @@ -203,40 +171,42 @@ public boolean equals(final Object o) { } TollFree other = (TollFree) o; - return ( - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(phoneNumber, other.phoneNumber) && - Objects.equals(lata, other.lata) && - Objects.equals(locality, other.locality) && - Objects.equals(rateCenter, other.rateCenter) && - Objects.equals(latitude, other.latitude) && - Objects.equals(longitude, other.longitude) && - Objects.equals(region, other.region) && - Objects.equals(postalCode, other.postalCode) && - Objects.equals(isoCountry, other.isoCountry) && - Objects.equals(addressRequirements, other.addressRequirements) && - Objects.equals(beta, other.beta) && - Objects.equals(capabilities, other.capabilities) + Objects.equals(addressRequirements, other.addressRequirements) && + Objects.equals(beta, other.beta) && + Objects.equals(capabilities, other.capabilities) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(isoCountry, other.isoCountry) && + Objects.equals(lata, other.lata) && + Objects.equals(latitude, other.latitude) && + Objects.equals(locality, other.locality) && + Objects.equals(longitude, other.longitude) && + Objects.equals(phoneNumber, other.phoneNumber) && + Objects.equals(postalCode, other.postalCode) && + Objects.equals(rateCenter, other.rateCenter) && + Objects.equals(region, other.region) ); } @Override public int hashCode() { return Objects.hash( - friendlyName, - phoneNumber, - lata, - locality, - rateCenter, - latitude, - longitude, - region, - postalCode, - isoCountry, - addressRequirements, - beta, - capabilities + addressRequirements, + beta, + capabilities, + friendlyName, + isoCountry, + lata, + latitude, + locality, + longitude, + phoneNumber, + postalCode, + rateCenter, + region ); } + + } + diff --git a/src/main/java/com/twilio/rest/api/v2010/account/availablephonenumbercountry/TollFreeReader.java b/src/main/java/com/twilio/rest/api/v2010/account/availablephonenumbercountry/TollFreeReader.java index b2970b6a85..b743f33fa8 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/availablephonenumbercountry/TollFreeReader.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/availablephonenumbercountry/TollFreeReader.java @@ -17,8 +17,9 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; import com.twilio.converter.Promoter; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -30,8 +31,8 @@ public class TollFreeReader extends Reader { - private String pathCountryCode; - private String pathAccountSid; + private String pathaccountSid; + private String pathcountryCode; private Integer areaCode; private String contains; private Boolean smsEnabled; @@ -52,72 +53,71 @@ public class TollFreeReader extends Reader { private Boolean faxEnabled; private Long pageSize; - public TollFreeReader(final String pathCountryCode) { - this.pathCountryCode = pathCountryCode; + public TollFreeReader(final String pathcountryCode) { + this.pathcountryCode = pathcountryCode; } - public TollFreeReader( - final String pathAccountSid, - final String pathCountryCode - ) { - this.pathAccountSid = pathAccountSid; - this.pathCountryCode = pathCountryCode; + public TollFreeReader(final String pathaccountSid, final String pathcountryCode) { + this.pathaccountSid = pathaccountSid; + this.pathcountryCode = pathcountryCode; } + public TollFreeReader setAreaCode(final Integer areaCode) { this.areaCode = areaCode; return this; } + public TollFreeReader setContains(final String contains) { this.contains = contains; return this; } + public TollFreeReader setSmsEnabled(final Boolean smsEnabled) { this.smsEnabled = smsEnabled; return this; } + public TollFreeReader setMmsEnabled(final Boolean mmsEnabled) { this.mmsEnabled = mmsEnabled; return this; } + public TollFreeReader setVoiceEnabled(final Boolean voiceEnabled) { this.voiceEnabled = voiceEnabled; return this; } - public TollFreeReader setExcludeAllAddressRequired( - final Boolean excludeAllAddressRequired - ) { + + public TollFreeReader setExcludeAllAddressRequired(final Boolean excludeAllAddressRequired) { this.excludeAllAddressRequired = excludeAllAddressRequired; return this; } - public TollFreeReader setExcludeLocalAddressRequired( - final Boolean excludeLocalAddressRequired - ) { + + public TollFreeReader setExcludeLocalAddressRequired(final Boolean excludeLocalAddressRequired) { this.excludeLocalAddressRequired = excludeLocalAddressRequired; return this; } - public TollFreeReader setExcludeForeignAddressRequired( - final Boolean excludeForeignAddressRequired - ) { + + public TollFreeReader setExcludeForeignAddressRequired(final Boolean excludeForeignAddressRequired) { this.excludeForeignAddressRequired = excludeForeignAddressRequired; return this; } + public TollFreeReader setBeta(final Boolean beta) { this.beta = beta; return this; } - public TollFreeReader setNearNumber( - final com.twilio.type.PhoneNumber nearNumber - ) { + + public TollFreeReader setNearNumber(final com.twilio.type.PhoneNumber nearNumber) { this.nearNumber = nearNumber; return this; } @@ -131,216 +131,215 @@ public TollFreeReader setNearLatLong(final String nearLatLong) { return this; } + public TollFreeReader setDistance(final Integer distance) { this.distance = distance; return this; } + public TollFreeReader setInPostalCode(final String inPostalCode) { this.inPostalCode = inPostalCode; return this; } + public TollFreeReader setInRegion(final String inRegion) { this.inRegion = inRegion; return this; } + public TollFreeReader setInRateCenter(final String inRateCenter) { this.inRateCenter = inRateCenter; return this; } + public TollFreeReader setInLata(final String inLata) { this.inLata = inLata; return this; } + public TollFreeReader setInLocality(final String inLocality) { this.inLocality = inLocality; return this; } + public TollFreeReader setFaxEnabled(final Boolean faxEnabled) { this.faxEnabled = faxEnabled; return this; } + public TollFreeReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/AvailablePhoneNumbers/{CountryCode}/TollFree.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = - path.replace( - "{" + "CountryCode" + "}", - this.pathCountryCode.toString() - ); + + String path = "/2010-04-01/Accounts/{AccountSid}/AvailablePhoneNumbers/{CountryCode}/TollFree.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "CountryCode" + "}", this.pathcountryCode.toString()); Request request = new Request( - HttpMethod.GET, - Domains.API.toString(), - path + HttpMethod.GET, + Domains.API.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "TollFree read failed: Unable to connect to server" - ); + throw new ApiConnectionException("TollFree read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "available_phone_numbers", - response.getContent(), - TollFree.class, - client.getObjectMapper() - ); + "available_phone_numbers", + response.getContent(), + TollFree.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.API.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.API.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (areaCode != null) { - request.addQueryParam("AreaCode", areaCode.toString()); + Serializer.toString(request, "AreaCode", areaCode, ParameterType.QUERY); } + + if (contains != null) { - request.addQueryParam("Contains", contains); + Serializer.toString(request, "Contains", contains, ParameterType.QUERY); } + + if (smsEnabled != null) { - request.addQueryParam("SmsEnabled", smsEnabled.toString()); + Serializer.toString(request, "SmsEnabled", smsEnabled, ParameterType.QUERY); } + + if (mmsEnabled != null) { - request.addQueryParam("MmsEnabled", mmsEnabled.toString()); + Serializer.toString(request, "MmsEnabled", mmsEnabled, ParameterType.QUERY); } + + if (voiceEnabled != null) { - request.addQueryParam("VoiceEnabled", voiceEnabled.toString()); + Serializer.toString(request, "VoiceEnabled", voiceEnabled, ParameterType.QUERY); } + + if (excludeAllAddressRequired != null) { - request.addQueryParam( - "ExcludeAllAddressRequired", - excludeAllAddressRequired.toString() - ); + Serializer.toString(request, "ExcludeAllAddressRequired", excludeAllAddressRequired, ParameterType.QUERY); } + + if (excludeLocalAddressRequired != null) { - request.addQueryParam( - "ExcludeLocalAddressRequired", - excludeLocalAddressRequired.toString() - ); + Serializer.toString(request, "ExcludeLocalAddressRequired", excludeLocalAddressRequired, ParameterType.QUERY); } + + if (excludeForeignAddressRequired != null) { - request.addQueryParam( - "ExcludeForeignAddressRequired", - excludeForeignAddressRequired.toString() - ); + Serializer.toString(request, "ExcludeForeignAddressRequired", excludeForeignAddressRequired, ParameterType.QUERY); } + + if (beta != null) { - request.addQueryParam("Beta", beta.toString()); + Serializer.toString(request, "Beta", beta, ParameterType.QUERY); } + + if (nearNumber != null) { - request.addQueryParam("NearNumber", nearNumber.toString()); + Serializer.toString(request, "NearNumber", nearNumber, ParameterType.QUERY); } + + if (nearLatLong != null) { - request.addQueryParam("NearLatLong", nearLatLong); + Serializer.toString(request, "NearLatLong", nearLatLong, ParameterType.QUERY); } + + if (distance != null) { - request.addQueryParam("Distance", distance.toString()); + Serializer.toString(request, "Distance", distance, ParameterType.QUERY); } + + if (inPostalCode != null) { - request.addQueryParam("InPostalCode", inPostalCode); + Serializer.toString(request, "InPostalCode", inPostalCode, ParameterType.QUERY); } + + if (inRegion != null) { - request.addQueryParam("InRegion", inRegion); + Serializer.toString(request, "InRegion", inRegion, ParameterType.QUERY); } + + if (inRateCenter != null) { - request.addQueryParam("InRateCenter", inRateCenter); + Serializer.toString(request, "InRateCenter", inRateCenter, ParameterType.QUERY); } + + if (inLata != null) { - request.addQueryParam("InLata", inLata); + Serializer.toString(request, "InLata", inLata, ParameterType.QUERY); } + + if (inLocality != null) { - request.addQueryParam("InLocality", inLocality); + Serializer.toString(request, "InLocality", inLocality, ParameterType.QUERY); } + + if (faxEnabled != null) { - request.addQueryParam("FaxEnabled", faxEnabled.toString()); + Serializer.toString(request, "FaxEnabled", faxEnabled, ParameterType.QUERY); } + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/availablephonenumbercountry/Voip.java b/src/main/java/com/twilio/rest/api/v2010/account/availablephonenumbercountry/Voip.java index b7afdb186e..ba71ff7e87 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/availablephonenumbercountry/Voip.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/availablephonenumbercountry/Voip.java @@ -18,47 +18,48 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.type.PhoneNumberCapabilities; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.math.BigDecimal; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Voip extends Resource { - private static final long serialVersionUID = 211749226408502L; - public static VoipReader reader(final String pathCountryCode) { - return new VoipReader(pathCountryCode); + public static VoipReader reader(final String pathcountryCode) { + return new VoipReader( + pathcountryCode + ); } - public static VoipReader reader( - final String pathAccountSid, - final String pathCountryCode - ) { - return new VoipReader(pathAccountSid, pathCountryCode); + + public static VoipReader reader(final String pathaccountSid, final String pathcountryCode) { + return new VoipReader( + pathaccountSid, pathcountryCode + ); } + /** * Converts a JSON String into a Voip object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Voip object represented by the provided JSON */ - public static Voip fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Voip fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Voip.class); @@ -73,14 +74,11 @@ public static Voip fromJson( * Converts a JSON InputStream into a Voip object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Voip object represented by the provided JSON */ - public static Voip fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Voip fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Voip.class); @@ -91,105 +89,75 @@ public static Voip fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter + private final String addressRequirements; + @Getter + private final Boolean beta; + @Getter + private final PhoneNumberCapabilities capabilities; + @Getter private final com.twilio.type.PhoneNumber friendlyName; - private final com.twilio.type.PhoneNumber phoneNumber; + @Getter + private final String isoCountry; + @Getter private final String lata; - private final String locality; - private final String rateCenter; + @Getter private final BigDecimal latitude; + @Getter + private final String locality; + @Getter private final BigDecimal longitude; - private final String region; + @Getter + private final com.twilio.type.PhoneNumber phoneNumber; + @Getter private final String postalCode; - private final String isoCountry; - private final String addressRequirements; - private final Boolean beta; - private final PhoneNumberCapabilities capabilities; + @Getter + private final String rateCenter; + @Getter + private final String region; @JsonCreator private Voip( - @JsonProperty( - "friendly_name" - ) final com.twilio.type.PhoneNumber friendlyName, - @JsonProperty( - "phone_number" - ) final com.twilio.type.PhoneNumber phoneNumber, - @JsonProperty("lata") final String lata, - @JsonProperty("locality") final String locality, - @JsonProperty("rate_center") final String rateCenter, - @JsonProperty("latitude") final BigDecimal latitude, - @JsonProperty("longitude") final BigDecimal longitude, - @JsonProperty("region") final String region, - @JsonProperty("postal_code") final String postalCode, - @JsonProperty("iso_country") final String isoCountry, - @JsonProperty("address_requirements") final String addressRequirements, - @JsonProperty("beta") final Boolean beta, - @JsonProperty("capabilities") final PhoneNumberCapabilities capabilities + @JsonProperty("address_requirements") final String addressRequirements, + @JsonProperty("beta") final Boolean beta, + @JsonProperty("capabilities") final PhoneNumberCapabilities capabilities, + @JsonProperty("friendly_name") final com.twilio.type.PhoneNumber friendlyName, + @JsonProperty("iso_country") final String isoCountry, + @JsonProperty("lata") final String lata, + @JsonProperty("latitude") final BigDecimal latitude, + @JsonProperty("locality") final String locality, + @JsonProperty("longitude") final BigDecimal longitude, + @JsonProperty("phone_number") final com.twilio.type.PhoneNumber phoneNumber, + @JsonProperty("postal_code") final String postalCode, + @JsonProperty("rate_center") final String rateCenter, + @JsonProperty("region") final String region ) { + this.addressRequirements = addressRequirements; + this.beta = beta; + this.capabilities = capabilities; this.friendlyName = friendlyName; - this.phoneNumber = phoneNumber; + this.isoCountry = isoCountry; this.lata = lata; - this.locality = locality; - this.rateCenter = rateCenter; this.latitude = latitude; + this.locality = locality; this.longitude = longitude; - this.region = region; + this.phoneNumber = phoneNumber; this.postalCode = postalCode; - this.isoCountry = isoCountry; - this.addressRequirements = addressRequirements; - this.beta = beta; - this.capabilities = capabilities; - } - - public final com.twilio.type.PhoneNumber getFriendlyName() { - return this.friendlyName; - } - - public final com.twilio.type.PhoneNumber getPhoneNumber() { - return this.phoneNumber; - } - - public final String getLata() { - return this.lata; - } - - public final String getLocality() { - return this.locality; - } - - public final String getRateCenter() { - return this.rateCenter; - } - - public final BigDecimal getLatitude() { - return this.latitude; - } - - public final BigDecimal getLongitude() { - return this.longitude; - } - - public final String getRegion() { - return this.region; - } - - public final String getPostalCode() { - return this.postalCode; - } - - public final String getIsoCountry() { - return this.isoCountry; - } - - public final String getAddressRequirements() { - return this.addressRequirements; - } - - public final Boolean getBeta() { - return this.beta; - } - - public final PhoneNumberCapabilities getCapabilities() { - return this.capabilities; + this.rateCenter = rateCenter; + this.region = region; } @Override @@ -203,40 +171,42 @@ public boolean equals(final Object o) { } Voip other = (Voip) o; - return ( - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(phoneNumber, other.phoneNumber) && - Objects.equals(lata, other.lata) && - Objects.equals(locality, other.locality) && - Objects.equals(rateCenter, other.rateCenter) && - Objects.equals(latitude, other.latitude) && - Objects.equals(longitude, other.longitude) && - Objects.equals(region, other.region) && - Objects.equals(postalCode, other.postalCode) && - Objects.equals(isoCountry, other.isoCountry) && - Objects.equals(addressRequirements, other.addressRequirements) && - Objects.equals(beta, other.beta) && - Objects.equals(capabilities, other.capabilities) + Objects.equals(addressRequirements, other.addressRequirements) && + Objects.equals(beta, other.beta) && + Objects.equals(capabilities, other.capabilities) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(isoCountry, other.isoCountry) && + Objects.equals(lata, other.lata) && + Objects.equals(latitude, other.latitude) && + Objects.equals(locality, other.locality) && + Objects.equals(longitude, other.longitude) && + Objects.equals(phoneNumber, other.phoneNumber) && + Objects.equals(postalCode, other.postalCode) && + Objects.equals(rateCenter, other.rateCenter) && + Objects.equals(region, other.region) ); } @Override public int hashCode() { return Objects.hash( - friendlyName, - phoneNumber, - lata, - locality, - rateCenter, - latitude, - longitude, - region, - postalCode, - isoCountry, - addressRequirements, - beta, - capabilities + addressRequirements, + beta, + capabilities, + friendlyName, + isoCountry, + lata, + latitude, + locality, + longitude, + phoneNumber, + postalCode, + rateCenter, + region ); } + + } + diff --git a/src/main/java/com/twilio/rest/api/v2010/account/availablephonenumbercountry/VoipReader.java b/src/main/java/com/twilio/rest/api/v2010/account/availablephonenumbercountry/VoipReader.java index e434af66ad..688d1f91dc 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/availablephonenumbercountry/VoipReader.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/availablephonenumbercountry/VoipReader.java @@ -17,8 +17,9 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; import com.twilio.converter.Promoter; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -30,8 +31,8 @@ public class VoipReader extends Reader { - private String pathCountryCode; - private String pathAccountSid; + private String pathaccountSid; + private String pathcountryCode; private Integer areaCode; private String contains; private Boolean smsEnabled; @@ -52,72 +53,71 @@ public class VoipReader extends Reader { private Boolean faxEnabled; private Long pageSize; - public VoipReader(final String pathCountryCode) { - this.pathCountryCode = pathCountryCode; + public VoipReader(final String pathcountryCode) { + this.pathcountryCode = pathcountryCode; } - public VoipReader( - final String pathAccountSid, - final String pathCountryCode - ) { - this.pathAccountSid = pathAccountSid; - this.pathCountryCode = pathCountryCode; + public VoipReader(final String pathaccountSid, final String pathcountryCode) { + this.pathaccountSid = pathaccountSid; + this.pathcountryCode = pathcountryCode; } + public VoipReader setAreaCode(final Integer areaCode) { this.areaCode = areaCode; return this; } + public VoipReader setContains(final String contains) { this.contains = contains; return this; } + public VoipReader setSmsEnabled(final Boolean smsEnabled) { this.smsEnabled = smsEnabled; return this; } + public VoipReader setMmsEnabled(final Boolean mmsEnabled) { this.mmsEnabled = mmsEnabled; return this; } + public VoipReader setVoiceEnabled(final Boolean voiceEnabled) { this.voiceEnabled = voiceEnabled; return this; } - public VoipReader setExcludeAllAddressRequired( - final Boolean excludeAllAddressRequired - ) { + + public VoipReader setExcludeAllAddressRequired(final Boolean excludeAllAddressRequired) { this.excludeAllAddressRequired = excludeAllAddressRequired; return this; } - public VoipReader setExcludeLocalAddressRequired( - final Boolean excludeLocalAddressRequired - ) { + + public VoipReader setExcludeLocalAddressRequired(final Boolean excludeLocalAddressRequired) { this.excludeLocalAddressRequired = excludeLocalAddressRequired; return this; } - public VoipReader setExcludeForeignAddressRequired( - final Boolean excludeForeignAddressRequired - ) { + + public VoipReader setExcludeForeignAddressRequired(final Boolean excludeForeignAddressRequired) { this.excludeForeignAddressRequired = excludeForeignAddressRequired; return this; } + public VoipReader setBeta(final Boolean beta) { this.beta = beta; return this; } - public VoipReader setNearNumber( - final com.twilio.type.PhoneNumber nearNumber - ) { + + public VoipReader setNearNumber(final com.twilio.type.PhoneNumber nearNumber) { this.nearNumber = nearNumber; return this; } @@ -131,216 +131,215 @@ public VoipReader setNearLatLong(final String nearLatLong) { return this; } + public VoipReader setDistance(final Integer distance) { this.distance = distance; return this; } + public VoipReader setInPostalCode(final String inPostalCode) { this.inPostalCode = inPostalCode; return this; } + public VoipReader setInRegion(final String inRegion) { this.inRegion = inRegion; return this; } + public VoipReader setInRateCenter(final String inRateCenter) { this.inRateCenter = inRateCenter; return this; } + public VoipReader setInLata(final String inLata) { this.inLata = inLata; return this; } + public VoipReader setInLocality(final String inLocality) { this.inLocality = inLocality; return this; } + public VoipReader setFaxEnabled(final Boolean faxEnabled) { this.faxEnabled = faxEnabled; return this; } + public VoipReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/AvailablePhoneNumbers/{CountryCode}/Voip.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = - path.replace( - "{" + "CountryCode" + "}", - this.pathCountryCode.toString() - ); + + String path = "/2010-04-01/Accounts/{AccountSid}/AvailablePhoneNumbers/{CountryCode}/Voip.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "CountryCode" + "}", this.pathcountryCode.toString()); Request request = new Request( - HttpMethod.GET, - Domains.API.toString(), - path + HttpMethod.GET, + Domains.API.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Voip read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Voip read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "available_phone_numbers", - response.getContent(), - Voip.class, - client.getObjectMapper() - ); + "available_phone_numbers", + response.getContent(), + Voip.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.API.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.API.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (areaCode != null) { - request.addQueryParam("AreaCode", areaCode.toString()); + Serializer.toString(request, "AreaCode", areaCode, ParameterType.QUERY); } + + if (contains != null) { - request.addQueryParam("Contains", contains); + Serializer.toString(request, "Contains", contains, ParameterType.QUERY); } + + if (smsEnabled != null) { - request.addQueryParam("SmsEnabled", smsEnabled.toString()); + Serializer.toString(request, "SmsEnabled", smsEnabled, ParameterType.QUERY); } + + if (mmsEnabled != null) { - request.addQueryParam("MmsEnabled", mmsEnabled.toString()); + Serializer.toString(request, "MmsEnabled", mmsEnabled, ParameterType.QUERY); } + + if (voiceEnabled != null) { - request.addQueryParam("VoiceEnabled", voiceEnabled.toString()); + Serializer.toString(request, "VoiceEnabled", voiceEnabled, ParameterType.QUERY); } + + if (excludeAllAddressRequired != null) { - request.addQueryParam( - "ExcludeAllAddressRequired", - excludeAllAddressRequired.toString() - ); + Serializer.toString(request, "ExcludeAllAddressRequired", excludeAllAddressRequired, ParameterType.QUERY); } + + if (excludeLocalAddressRequired != null) { - request.addQueryParam( - "ExcludeLocalAddressRequired", - excludeLocalAddressRequired.toString() - ); + Serializer.toString(request, "ExcludeLocalAddressRequired", excludeLocalAddressRequired, ParameterType.QUERY); } + + if (excludeForeignAddressRequired != null) { - request.addQueryParam( - "ExcludeForeignAddressRequired", - excludeForeignAddressRequired.toString() - ); + Serializer.toString(request, "ExcludeForeignAddressRequired", excludeForeignAddressRequired, ParameterType.QUERY); } + + if (beta != null) { - request.addQueryParam("Beta", beta.toString()); + Serializer.toString(request, "Beta", beta, ParameterType.QUERY); } + + if (nearNumber != null) { - request.addQueryParam("NearNumber", nearNumber.toString()); + Serializer.toString(request, "NearNumber", nearNumber, ParameterType.QUERY); } + + if (nearLatLong != null) { - request.addQueryParam("NearLatLong", nearLatLong); + Serializer.toString(request, "NearLatLong", nearLatLong, ParameterType.QUERY); } + + if (distance != null) { - request.addQueryParam("Distance", distance.toString()); + Serializer.toString(request, "Distance", distance, ParameterType.QUERY); } + + if (inPostalCode != null) { - request.addQueryParam("InPostalCode", inPostalCode); + Serializer.toString(request, "InPostalCode", inPostalCode, ParameterType.QUERY); } + + if (inRegion != null) { - request.addQueryParam("InRegion", inRegion); + Serializer.toString(request, "InRegion", inRegion, ParameterType.QUERY); } + + if (inRateCenter != null) { - request.addQueryParam("InRateCenter", inRateCenter); + Serializer.toString(request, "InRateCenter", inRateCenter, ParameterType.QUERY); } + + if (inLata != null) { - request.addQueryParam("InLata", inLata); + Serializer.toString(request, "InLata", inLata, ParameterType.QUERY); } + + if (inLocality != null) { - request.addQueryParam("InLocality", inLocality); + Serializer.toString(request, "InLocality", inLocality, ParameterType.QUERY); } + + if (faxEnabled != null) { - request.addQueryParam("FaxEnabled", faxEnabled.toString()); + Serializer.toString(request, "FaxEnabled", faxEnabled, ParameterType.QUERY); } + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/call/Event.java b/src/main/java/com/twilio/rest/api/v2010/account/call/Event.java index cffe7272a7..a80e8f0f02 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/call/Event.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/call/Event.java @@ -18,47 +18,46 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; -import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Event extends Resource { - private static final long serialVersionUID = 87960678380335L; - public static EventReader reader(final String pathCallSid) { - return new EventReader(pathCallSid); + public static EventReader reader(final String pathcallSid) { + return new EventReader( + pathcallSid + ); } - public static EventReader reader( - final String pathAccountSid, - final String pathCallSid - ) { - return new EventReader(pathAccountSid, pathCallSid); + + public static EventReader reader(final String pathaccountSid, final String pathcallSid) { + return new EventReader( + pathaccountSid, pathcallSid + ); } + /** * Converts a JSON String into a Event object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Event object represented by the provided JSON */ - public static Event fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Event fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Event.class); @@ -73,14 +72,11 @@ public static Event fromJson( * Converts a JSON InputStream into a Event object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Event object represented by the provided JSON */ - public static Event fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Event fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Event.class); @@ -91,26 +87,33 @@ public static Event fromJson( } } - private final Map request; - private final Map response; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter + private final Object request; + @Getter + private final Object response; @JsonCreator private Event( - @JsonProperty("request") final Map request, - @JsonProperty("response") final Map response + @JsonProperty("request") final Object request, + @JsonProperty("response") final Object response ) { this.request = request; this.response = response; } - public final Map getRequest() { - return this.request; - } - - public final Map getResponse() { - return this.response; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -122,15 +125,20 @@ public boolean equals(final Object o) { } Event other = (Event) o; - return ( - Objects.equals(request, other.request) && - Objects.equals(response, other.response) + Objects.equals(request, other.request) && + Objects.equals(response, other.response) ); } @Override public int hashCode() { - return Objects.hash(request, response); + return Objects.hash( + request, + response + ); } + + } + diff --git a/src/main/java/com/twilio/rest/api/v2010/account/call/EventReader.java b/src/main/java/com/twilio/rest/api/v2010/account/call/EventReader.java index f53d13a8c9..dcb1a870b8 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/call/EventReader.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/call/EventReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,127 +30,96 @@ public class EventReader extends Reader { - private String pathCallSid; - private String pathAccountSid; + private String pathaccountSid; + private String pathcallSid; private Long pageSize; - public EventReader(final String pathCallSid) { - this.pathCallSid = pathCallSid; + public EventReader(final String pathcallSid) { + this.pathcallSid = pathcallSid; } - public EventReader(final String pathAccountSid, final String pathCallSid) { - this.pathAccountSid = pathAccountSid; - this.pathCallSid = pathCallSid; + public EventReader(final String pathaccountSid, final String pathcallSid) { + this.pathaccountSid = pathaccountSid; + this.pathcallSid = pathcallSid; } + public EventReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/Calls/{CallSid}/Events.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = path.replace("{" + "CallSid" + "}", this.pathCallSid.toString()); + + String path = "/2010-04-01/Accounts/{AccountSid}/Calls/{CallSid}/Events.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "CallSid" + "}", this.pathcallSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.API.toString(), - path + HttpMethod.GET, + Domains.API.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Event read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Event read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "events", - response.getContent(), - Event.class, - client.getObjectMapper() - ); + "events", + response.getContent(), + Event.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.API.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.API.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/call/Notification.java b/src/main/java/com/twilio/rest/api/v2010/account/call/Notification.java index f597752c87..f49d870f0d 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/call/Notification.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/call/Notification.java @@ -18,64 +18,64 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.http.HttpMethod; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Notification extends Resource { - private static final long serialVersionUID = 162458167875227L; - public static NotificationFetcher fetcher( - final String pathCallSid, - final String pathSid - ) { - return new NotificationFetcher(pathCallSid, pathSid); + public static NotificationFetcher fetcher(final String pathcallSid, final String pathsid) { + return new NotificationFetcher( + pathcallSid, pathsid + ); } - public static NotificationFetcher fetcher( - final String pathAccountSid, - final String pathCallSid, - final String pathSid - ) { - return new NotificationFetcher(pathAccountSid, pathCallSid, pathSid); + + public static NotificationFetcher fetcher(final String pathaccountSid, final String pathcallSid, final String pathsid) { + return new NotificationFetcher( + pathaccountSid, pathcallSid, pathsid + ); } - public static NotificationReader reader(final String pathCallSid) { - return new NotificationReader(pathCallSid); + + public static NotificationReader reader(final String pathcallSid) { + return new NotificationReader( + pathcallSid + ); } - public static NotificationReader reader( - final String pathAccountSid, - final String pathCallSid - ) { - return new NotificationReader(pathAccountSid, pathCallSid); + + public static NotificationReader reader(final String pathaccountSid, final String pathcallSid) { + return new NotificationReader( + pathaccountSid, pathcallSid + ); } + /** * Converts a JSON String into a Notification object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Notification object represented by the provided JSON */ - public static Notification fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Notification fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Notification.class); @@ -90,14 +90,11 @@ public static Notification fromJson( * Converts a JSON InputStream into a Notification object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Notification object represented by the provided JSON */ - public static Notification fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Notification fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Notification.class); @@ -108,52 +105,85 @@ public static Notification fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; + @Getter private final String apiVersion; + @Getter private final String callSid; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; + @Getter private final String errorCode; + @Getter private final String log; + @Getter private final ZonedDateTime messageDate; + @Getter private final String messageText; + @Getter private final URI moreInfo; + @Getter private final HttpMethod requestMethod; + @Getter private final URI requestUrl; + @Getter private final String requestVariables; + @Getter private final String responseBody; + @Getter private final String responseHeaders; + @Getter private final String sid; + @Getter private final String uri; @JsonCreator private Notification( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("api_version") final String apiVersion, - @JsonProperty("call_sid") final String callSid, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("error_code") final String errorCode, - @JsonProperty("log") final String log, - @JsonProperty("message_date") final String messageDate, - @JsonProperty("message_text") final String messageText, - @JsonProperty("more_info") final URI moreInfo, - @JsonProperty("request_method") final HttpMethod requestMethod, - @JsonProperty("request_url") final URI requestUrl, - @JsonProperty("request_variables") final String requestVariables, - @JsonProperty("response_body") final String responseBody, - @JsonProperty("response_headers") final String responseHeaders, - @JsonProperty("sid") final String sid, - @JsonProperty("uri") final String uri + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("api_version") final String apiVersion, + @JsonProperty("call_sid") final String callSid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.RFC2822Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.RFC2822Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("error_code") final String errorCode, + @JsonProperty("log") final String log, + @JsonProperty("message_date") + @JsonDeserialize(using = com.twilio.converter.RFC2822Deserializer.class) final ZonedDateTime messageDate, + @JsonProperty("message_text") final String messageText, + @JsonProperty("more_info") final URI moreInfo, + @JsonProperty("request_method") final HttpMethod requestMethod, + @JsonProperty("request_url") final URI requestUrl, + @JsonProperty("request_variables") final String requestVariables, + @JsonProperty("response_body") final String responseBody, + @JsonProperty("response_headers") final String responseHeaders, + @JsonProperty("sid") final String sid, + @JsonProperty("uri") final String uri ) { this.accountSid = accountSid; this.apiVersion = apiVersion; this.callSid = callSid; - this.dateCreated = DateConverter.rfc2822DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.rfc2822DateTimeFromString(dateUpdated); + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.errorCode = errorCode; this.log = log; - this.messageDate = DateConverter.rfc2822DateTimeFromString(messageDate); + this.messageDate = messageDate; this.messageText = messageText; this.moreInfo = moreInfo; this.requestMethod = requestMethod; @@ -165,74 +195,6 @@ private Notification( this.uri = uri; } - public final String getAccountSid() { - return this.accountSid; - } - - public final String getApiVersion() { - return this.apiVersion; - } - - public final String getCallSid() { - return this.callSid; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final String getErrorCode() { - return this.errorCode; - } - - public final String getLog() { - return this.log; - } - - public final ZonedDateTime getMessageDate() { - return this.messageDate; - } - - public final String getMessageText() { - return this.messageText; - } - - public final URI getMoreInfo() { - return this.moreInfo; - } - - public final HttpMethod getRequestMethod() { - return this.requestMethod; - } - - public final URI getRequestUrl() { - return this.requestUrl; - } - - public final String getRequestVariables() { - return this.requestVariables; - } - - public final String getResponseBody() { - return this.responseBody; - } - - public final String getResponseHeaders() { - return this.responseHeaders; - } - - public final String getSid() { - return this.sid; - } - - public final String getUri() { - return this.uri; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -244,48 +206,50 @@ public boolean equals(final Object o) { } Notification other = (Notification) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(apiVersion, other.apiVersion) && - Objects.equals(callSid, other.callSid) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(errorCode, other.errorCode) && - Objects.equals(log, other.log) && - Objects.equals(messageDate, other.messageDate) && - Objects.equals(messageText, other.messageText) && - Objects.equals(moreInfo, other.moreInfo) && - Objects.equals(requestMethod, other.requestMethod) && - Objects.equals(requestUrl, other.requestUrl) && - Objects.equals(requestVariables, other.requestVariables) && - Objects.equals(responseBody, other.responseBody) && - Objects.equals(responseHeaders, other.responseHeaders) && - Objects.equals(sid, other.sid) && - Objects.equals(uri, other.uri) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(apiVersion, other.apiVersion) && + Objects.equals(callSid, other.callSid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(errorCode, other.errorCode) && + Objects.equals(log, other.log) && + Objects.equals(messageDate, other.messageDate) && + Objects.equals(messageText, other.messageText) && + Objects.equals(moreInfo, other.moreInfo) && + Objects.equals(requestMethod, other.requestMethod) && + Objects.equals(requestUrl, other.requestUrl) && + Objects.equals(requestVariables, other.requestVariables) && + Objects.equals(responseBody, other.responseBody) && + Objects.equals(responseHeaders, other.responseHeaders) && + Objects.equals(sid, other.sid) && + Objects.equals(uri, other.uri) ); } @Override public int hashCode() { return Objects.hash( - accountSid, - apiVersion, - callSid, - dateCreated, - dateUpdated, - errorCode, - log, - messageDate, - messageText, - moreInfo, - requestMethod, - requestUrl, - requestVariables, - responseBody, - responseHeaders, - sid, - uri + accountSid, + apiVersion, + callSid, + dateCreated, + dateUpdated, + errorCode, + log, + messageDate, + messageText, + moreInfo, + requestMethod, + requestUrl, + requestVariables, + responseBody, + responseHeaders, + sid, + uri ); } + + } + diff --git a/src/main/java/com/twilio/rest/api/v2010/account/call/NotificationFetcher.java b/src/main/java/com/twilio/rest/api/v2010/account/call/NotificationFetcher.java index 3a1e6e9bd2..34d1039c69 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/call/NotificationFetcher.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/call/NotificationFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.api.v2010.account.call; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,71 +26,53 @@ public class NotificationFetcher extends Fetcher { - private String pathCallSid; - private String pathSid; - private String pathAccountSid; + private String pathaccountSid; + private String pathcallSid; + private String pathsid; - public NotificationFetcher(final String pathCallSid, final String pathSid) { - this.pathCallSid = pathCallSid; - this.pathSid = pathSid; + public NotificationFetcher(final String pathcallSid, final String pathsid) { + this.pathcallSid = pathcallSid; + this.pathsid = pathsid; } - public NotificationFetcher( - final String pathAccountSid, - final String pathCallSid, - final String pathSid - ) { - this.pathAccountSid = pathAccountSid; - this.pathCallSid = pathCallSid; - this.pathSid = pathSid; + public NotificationFetcher(final String pathaccountSid, final String pathcallSid, final String pathsid) { + this.pathaccountSid = pathaccountSid; + this.pathcallSid = pathcallSid; + this.pathsid = pathsid; } + @Override public Notification fetch(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/Calls/{CallSid}/Notifications/{Sid}.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = path.replace("{" + "CallSid" + "}", this.pathCallSid.toString()); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/2010-04-01/Accounts/{AccountSid}/Calls/{CallSid}/Notifications/{Sid}.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "CallSid" + "}", this.pathcallSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.API.toString(), - path + HttpMethod.GET, + Domains.API.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Notification fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Notification fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return Notification.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Notification.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/call/NotificationReader.java b/src/main/java/com/twilio/rest/api/v2010/account/call/NotificationReader.java index f4f51aedb4..3350123c1c 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/call/NotificationReader.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/call/NotificationReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -26,182 +27,149 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.time.LocalDate; -import java.time.format.DateTimeFormatter; public class NotificationReader extends Reader { - private String pathCallSid; - private String pathAccountSid; + private String pathaccountSid; + private String pathcallSid; private Integer log; private LocalDate messageDate; private LocalDate messageDateBefore; private LocalDate messageDateAfter; private Long pageSize; - public NotificationReader(final String pathCallSid) { - this.pathCallSid = pathCallSid; + public NotificationReader(final String pathcallSid) { + this.pathcallSid = pathcallSid; } - public NotificationReader( - final String pathAccountSid, - final String pathCallSid - ) { - this.pathAccountSid = pathAccountSid; - this.pathCallSid = pathCallSid; + public NotificationReader(final String pathaccountSid, final String pathcallSid) { + this.pathaccountSid = pathaccountSid; + this.pathcallSid = pathcallSid; } + public NotificationReader setLog(final Integer log) { this.log = log; return this; } + public NotificationReader setMessageDate(final LocalDate messageDate) { this.messageDate = messageDate; return this; } - public NotificationReader setMessageDateBefore( - final LocalDate messageDateBefore - ) { + + public NotificationReader setMessageDateBefore(final LocalDate messageDateBefore) { this.messageDateBefore = messageDateBefore; return this; } - public NotificationReader setMessageDateAfter( - final LocalDate messageDateAfter - ) { + + public NotificationReader setMessageDateAfter(final LocalDate messageDateAfter) { this.messageDateAfter = messageDateAfter; return this; } + public NotificationReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/Calls/{CallSid}/Notifications.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = path.replace("{" + "CallSid" + "}", this.pathCallSid.toString()); + + String path = "/2010-04-01/Accounts/{AccountSid}/Calls/{CallSid}/Notifications.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "CallSid" + "}", this.pathcallSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.API.toString(), - path + HttpMethod.GET, + Domains.API.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Notification read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Notification read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "notifications", - response.getContent(), - Notification.class, - client.getObjectMapper() - ); + "notifications", + response.getContent(), + Notification.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.API.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.API.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (log != null) { - request.addQueryParam("Log", log.toString()); + Serializer.toString(request, "Log", log, ParameterType.QUERY); } + + if (messageDate != null) { - request.addQueryParam( - "MessageDate", - messageDate.format( - DateTimeFormatter.ofPattern( - Request.QUERY_STRING_DATE_FORMAT - ) - ) - ); - } else if (messageDateAfter != null || messageDateBefore != null) { - request.addQueryDateRange( - "MessageDate", - messageDateAfter, - messageDateBefore - ); + Serializer.toString(request, "MessageDate", messageDate, ParameterType.QUERY); } - if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + + + if (messageDateBefore != null) { + Serializer.toString(request, "MessageDate<", messageDateBefore, ParameterType.QUERY); + } + + + if (messageDateAfter != null) { + Serializer.toString(request, "MessageDate>", messageDateAfter, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); + + if (pageSize != null) { + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } + + } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/call/Payment.java b/src/main/java/com/twilio/rest/api/v2010/account/call/Payment.java index 648ce5f217..3f32fdccb6 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/call/Payment.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/call/Payment.java @@ -18,211 +18,63 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Payment extends Resource { - private static final long serialVersionUID = 75287507384907L; - - public static PaymentCreator creator( - final String pathCallSid, - final String idempotencyKey, - final URI statusCallback - ) { - return new PaymentCreator(pathCallSid, idempotencyKey, statusCallback); - } - public static PaymentCreator creator( - final String pathAccountSid, - final String pathCallSid, - final String idempotencyKey, - final URI statusCallback - ) { + public static PaymentCreator creator(final String pathcallSid, final String idempotencyKey, final URI statusCallback) { return new PaymentCreator( - pathAccountSid, - pathCallSid, - idempotencyKey, - statusCallback + pathcallSid, idempotencyKey, statusCallback ); } - public static PaymentUpdater updater( - final String pathCallSid, - final String pathSid, - final String idempotencyKey, - final URI statusCallback - ) { - return new PaymentUpdater( - pathCallSid, - pathSid, - idempotencyKey, - statusCallback - ); - } - public static PaymentUpdater updater( - final String pathAccountSid, - final String pathCallSid, - final String pathSid, - final String idempotencyKey, - final URI statusCallback - ) { - return new PaymentUpdater( - pathAccountSid, - pathCallSid, - pathSid, - idempotencyKey, - statusCallback + public static PaymentCreator creator(final String pathaccountSid, final String pathcallSid, final String idempotencyKey, final URI statusCallback) { + return new PaymentCreator( + pathaccountSid, pathcallSid, idempotencyKey, statusCallback ); } - /** - * Converts a JSON String into a Payment object using the provided ObjectMapper. - * - * @param json Raw JSON String - * @param objectMapper Jackson ObjectMapper - * @return Payment object represented by the provided JSON - */ - public static Payment fromJson( - final String json, - final ObjectMapper objectMapper - ) { - // Convert all checked exceptions to Runtime - try { - return objectMapper.readValue(json, Payment.class); - } catch (final JsonMappingException | JsonParseException e) { - throw new ApiException(e.getMessage(), e); - } catch (final IOException e) { - throw new ApiConnectionException(e.getMessage(), e); - } - } - - /** - * Converts a JSON InputStream into a Payment object using the provided - * ObjectMapper. - * - * @param json Raw JSON InputStream - * @param objectMapper Jackson ObjectMapper - * @return Payment object represented by the provided JSON - */ - public static Payment fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { - // Convert all checked exceptions to Runtime - try { - return objectMapper.readValue(json, Payment.class); - } catch (final JsonMappingException | JsonParseException e) { - throw new ApiException(e.getMessage(), e); - } catch (final IOException e) { - throw new ApiConnectionException(e.getMessage(), e); - } - } - - private final String accountSid; - private final String callSid; - private final String sid; - private final ZonedDateTime dateCreated; - private final ZonedDateTime dateUpdated; - private final String uri; - - @JsonCreator - private Payment( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("call_sid") final String callSid, - @JsonProperty("sid") final String sid, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("uri") final String uri - ) { - this.accountSid = accountSid; - this.callSid = callSid; - this.sid = sid; - this.dateCreated = DateConverter.rfc2822DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.rfc2822DateTimeFromString(dateUpdated); - this.uri = uri; - } - - public final String getAccountSid() { - return this.accountSid; - } - public final String getCallSid() { - return this.callSid; - } - - public final String getSid() { - return this.sid; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; + public static PaymentUpdater updater(final String pathcallSid, final String pathsid, final String idempotencyKey, final URI statusCallback) { + return new PaymentUpdater( + pathcallSid, pathsid, idempotencyKey, statusCallback + ); } - public final String getUri() { - return this.uri; - } - @Override - public boolean equals(final Object o) { - if (this == o) { - return true; - } - - if (o == null || getClass() != o.getClass()) { - return false; - } - - Payment other = (Payment) o; - - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(callSid, other.callSid) && - Objects.equals(sid, other.sid) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(uri, other.uri) + public static PaymentUpdater updater(final String pathaccountSid, final String pathcallSid, final String pathsid, final String idempotencyKey, final URI statusCallback) { + return new PaymentUpdater( + pathaccountSid, pathcallSid, pathsid, idempotencyKey, statusCallback ); } - @Override - public int hashCode() { - return Objects.hash( - accountSid, - callSid, - sid, - dateCreated, - dateUpdated, - uri - ); - } - public enum PaymentMethod { - CREDIT_CARD("credit-card"), - ACH_DEBIT("ach-debit"); + public enum Status { + COMPLETE("complete"), + CANCEL("cancel"); private final String value; - private PaymentMethod(final String value) { + private Status(final String value) { this.value = value; } @@ -231,8 +83,8 @@ public String toString() { } @JsonCreator - public static PaymentMethod forValue(final String value) { - return Promoter.enumFromString(value, PaymentMethod.values()); + public static Status forValue(final String value) { + return Promoter.enumFromString(value, Status.values()); } } @@ -278,6 +130,26 @@ public static BankAccountType forValue(final String value) { } } + public enum PaymentMethod { + CREDIT_CARD("credit-card"), + ACH_DEBIT("ach-debit"); + + private final String value; + + private PaymentMethod(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static PaymentMethod forValue(final String value) { + return Promoter.enumFromString(value, PaymentMethod.values()); + } + } + public enum Capture { PAYMENT_CARD_NUMBER("payment-card-number"), EXPIRATION_DATE("expiration-date"), @@ -302,23 +174,122 @@ public static Capture forValue(final String value) { } } - public enum Status { - COMPLETE("complete"), - CANCEL("cancel"); - private final String value; + /** + * Converts a JSON String into a Payment object using the provided ObjectMapper. + * + * @param json Raw JSON String + * @param objectMapper Jackson ObjectMapper + * @return Payment object represented by the provided JSON + */ + public static Payment fromJson(final String json, final ObjectMapper objectMapper) { + // Convert all checked exceptions to Runtime + try { + return objectMapper.readValue(json, Payment.class); + } catch (final JsonMappingException | JsonParseException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } - private Status(final String value) { - this.value = value; + /** + * Converts a JSON InputStream into a Payment object using the provided + * ObjectMapper. + * + * @param json Raw JSON InputStream + * @param objectMapper Jackson ObjectMapper + * @return Payment object represented by the provided JSON + */ + public static Payment fromJson(final InputStream json, final ObjectMapper objectMapper) { + // Convert all checked exceptions to Runtime + try { + return objectMapper.readValue(json, Payment.class); + } catch (final JsonMappingException | JsonParseException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); } + } - public String toString() { - return value; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); } + } - @JsonCreator - public static Status forValue(final String value) { - return Promoter.enumFromString(value, Status.values()); + + @Getter + private final String accountSid; + @Getter + private final String callSid; + @Getter + private final ZonedDateTime dateCreated; + @Getter + private final ZonedDateTime dateUpdated; + @Getter + private final String sid; + @Getter + private final String uri; + + @JsonCreator + private Payment( + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("call_sid") final String callSid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.RFC2822Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.RFC2822Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("sid") final String sid, + @JsonProperty("uri") final String uri + ) { + this.accountSid = accountSid; + this.callSid = callSid; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; + this.sid = sid; + this.uri = uri; + } + + @Override + public boolean equals(final Object o) { + if (this == o) { + return true; + } + + if (o == null || getClass() != o.getClass()) { + return false; } + + Payment other = (Payment) o; + return ( + Objects.equals(accountSid, other.accountSid) && + Objects.equals(callSid, other.callSid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(sid, other.sid) && + Objects.equals(uri, other.uri) + ); } + + @Override + public int hashCode() { + return Objects.hash( + accountSid, + callSid, + dateCreated, + dateUpdated, + sid, + uri + ); + } + + } + diff --git a/src/main/java/com/twilio/rest/api/v2010/account/call/PaymentCreator.java b/src/main/java/com/twilio/rest/api/v2010/account/call/PaymentCreator.java index c34dfa3202..709ef28de1 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/call/PaymentCreator.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/call/PaymentCreator.java @@ -14,11 +14,11 @@ package com.twilio.rest.api.v2010.account.call; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; -import com.twilio.converter.Converter; -import com.twilio.converter.Converter; -import com.twilio.converter.Promoter; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,17 +27,16 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -import java.math.BigDecimal; + import java.math.BigDecimal; import java.net.URI; -import java.net.URI; public class PaymentCreator extends Creator { - private String pathCallSid; + private String pathaccountSid; + private String pathcallSid; private String idempotencyKey; private URI statusCallback; - private String pathAccountSid; private Payment.BankAccountType bankAccountType; private BigDecimal chargeAmount; private String currency; @@ -53,166 +52,145 @@ public class PaymentCreator extends Creator { private Payment.TokenType tokenType; private String validCardTypes; - public PaymentCreator( - final String pathCallSid, - final String idempotencyKey, - final URI statusCallback - ) { - this.pathCallSid = pathCallSid; + public PaymentCreator(final String pathcallSid, final String idempotencyKey, final URI statusCallback) { + this.pathcallSid = pathcallSid; this.idempotencyKey = idempotencyKey; this.statusCallback = statusCallback; } - public PaymentCreator( - final String pathAccountSid, - final String pathCallSid, - final String idempotencyKey, - final URI statusCallback - ) { - this.pathAccountSid = pathAccountSid; - this.pathCallSid = pathCallSid; + public PaymentCreator(final String pathaccountSid, final String pathcallSid, final String idempotencyKey, final URI statusCallback) { + this.pathaccountSid = pathaccountSid; + this.pathcallSid = pathcallSid; this.idempotencyKey = idempotencyKey; this.statusCallback = statusCallback; } + public PaymentCreator setIdempotencyKey(final String idempotencyKey) { this.idempotencyKey = idempotencyKey; return this; } + public PaymentCreator setStatusCallback(final URI statusCallback) { this.statusCallback = statusCallback; return this; } - public PaymentCreator setStatusCallback(final String statusCallback) { - return setStatusCallback(Promoter.uriFromString(statusCallback)); - } - public PaymentCreator setBankAccountType( - final Payment.BankAccountType bankAccountType - ) { + public PaymentCreator setBankAccountType(final Payment.BankAccountType bankAccountType) { this.bankAccountType = bankAccountType; return this; } + public PaymentCreator setChargeAmount(final BigDecimal chargeAmount) { this.chargeAmount = chargeAmount; return this; } + public PaymentCreator setCurrency(final String currency) { this.currency = currency; return this; } + public PaymentCreator setDescription(final String description) { this.description = description; return this; } + public PaymentCreator setInput(final String input) { this.input = input; return this; } - public PaymentCreator setMinPostalCodeLength( - final Integer minPostalCodeLength - ) { + + public PaymentCreator setMinPostalCodeLength(final Integer minPostalCodeLength) { this.minPostalCodeLength = minPostalCodeLength; return this; } + public PaymentCreator setParameter(final Object parameter) { this.parameter = parameter; return this; } + public PaymentCreator setPaymentConnector(final String paymentConnector) { this.paymentConnector = paymentConnector; return this; } - public PaymentCreator setPaymentMethod( - final Payment.PaymentMethod paymentMethod - ) { + + public PaymentCreator setPaymentMethod(final Payment.PaymentMethod paymentMethod) { this.paymentMethod = paymentMethod; return this; } + public PaymentCreator setPostalCode(final Boolean postalCode) { this.postalCode = postalCode; return this; } + public PaymentCreator setSecurityCode(final Boolean securityCode) { this.securityCode = securityCode; return this; } + public PaymentCreator setTimeout(final Integer timeout) { this.timeout = timeout; return this; } + public PaymentCreator setTokenType(final Payment.TokenType tokenType) { this.tokenType = tokenType; return this; } + public PaymentCreator setValidCardTypes(final String validCardTypes) { this.validCardTypes = validCardTypes; return this; } + @Override public Payment create(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/Calls/{CallSid}/Payments.json"; - - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = path.replace("{" + "CallSid" + "}", this.pathCallSid.toString()); - path = - path.replace( - "{" + "IdempotencyKey" + "}", - this.idempotencyKey.toString() - ); - path = - path.replace( - "{" + "StatusCallback" + "}", - this.statusCallback.toString() - ); + + String path = "/2010-04-01/Accounts/{AccountSid}/Calls/{CallSid}/Payments.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "CallSid" + "}", this.pathcallSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.API.toString(), - path + HttpMethod.POST, + Domains.API.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Payment creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("Payment creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -221,59 +199,86 @@ public Payment create(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (idempotencyKey != null) { - request.addPostParam("IdempotencyKey", idempotencyKey); + Serializer.toString(request, "IdempotencyKey", idempotencyKey, ParameterType.URLENCODED); } + + if (statusCallback != null) { - request.addPostParam("StatusCallback", statusCallback.toString()); + Serializer.toString(request, "StatusCallback", statusCallback, ParameterType.URLENCODED); } + + if (bankAccountType != null) { - request.addPostParam("BankAccountType", bankAccountType.toString()); + Serializer.toString(request, "BankAccountType", bankAccountType, ParameterType.URLENCODED); } + + if (chargeAmount != null) { - request.addPostParam("ChargeAmount", chargeAmount.toString()); + Serializer.toString(request, "ChargeAmount", chargeAmount, ParameterType.URLENCODED); } + + if (currency != null) { - request.addPostParam("Currency", currency); + Serializer.toString(request, "Currency", currency, ParameterType.URLENCODED); } + + if (description != null) { - request.addPostParam("Description", description); + Serializer.toString(request, "Description", description, ParameterType.URLENCODED); } + + if (input != null) { - request.addPostParam("Input", input); + Serializer.toString(request, "Input", input, ParameterType.URLENCODED); } + + if (minPostalCodeLength != null) { - request.addPostParam( - "MinPostalCodeLength", - minPostalCodeLength.toString() - ); + Serializer.toString(request, "MinPostalCodeLength", minPostalCodeLength, ParameterType.URLENCODED); } + + if (parameter != null) { - request.addPostParam( - "Parameter", - Converter.objectToJson(parameter) - ); + Serializer.toString(request, "Parameter", parameter, ParameterType.URLENCODED); } + + if (paymentConnector != null) { - request.addPostParam("PaymentConnector", paymentConnector); + Serializer.toString(request, "PaymentConnector", paymentConnector, ParameterType.URLENCODED); } + + if (paymentMethod != null) { - request.addPostParam("PaymentMethod", paymentMethod.toString()); + Serializer.toString(request, "PaymentMethod", paymentMethod, ParameterType.URLENCODED); } + + if (postalCode != null) { - request.addPostParam("PostalCode", postalCode.toString()); + Serializer.toString(request, "PostalCode", postalCode, ParameterType.URLENCODED); } + + if (securityCode != null) { - request.addPostParam("SecurityCode", securityCode.toString()); + Serializer.toString(request, "SecurityCode", securityCode, ParameterType.URLENCODED); } + + if (timeout != null) { - request.addPostParam("Timeout", timeout.toString()); + Serializer.toString(request, "Timeout", timeout, ParameterType.URLENCODED); } + + if (tokenType != null) { - request.addPostParam("TokenType", tokenType.toString()); + Serializer.toString(request, "TokenType", tokenType, ParameterType.URLENCODED); } + + if (validCardTypes != null) { - request.addPostParam("ValidCardTypes", validCardTypes); + Serializer.toString(request, "ValidCardTypes", validCardTypes, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/call/PaymentUpdater.java b/src/main/java/com/twilio/rest/api/v2010/account/call/PaymentUpdater.java index 49a32d033f..ee45c950f1 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/call/PaymentUpdater.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/call/PaymentUpdater.java @@ -16,7 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; -import com.twilio.converter.Promoter; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,117 +26,88 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.net.URI; public class PaymentUpdater extends Updater { - - private String pathCallSid; - private String pathSid; + private String pathaccountSid; + private String pathcallSid; + private String pathsid; private String idempotencyKey; private URI statusCallback; - private String pathAccountSid; private Payment.Capture capture; private Payment.Status status; - public PaymentUpdater( - final String pathCallSid, - final String pathSid, - final String idempotencyKey, - final URI statusCallback - ) { - this.pathCallSid = pathCallSid; - this.pathSid = pathSid; + public PaymentUpdater(final String pathcallSid, final String pathsid, final String idempotencyKey, final URI statusCallback) { + this.pathcallSid = pathcallSid; + this.pathsid = pathsid; this.idempotencyKey = idempotencyKey; this.statusCallback = statusCallback; } - public PaymentUpdater( - final String pathAccountSid, - final String pathCallSid, - final String pathSid, - final String idempotencyKey, - final URI statusCallback - ) { - this.pathAccountSid = pathAccountSid; - this.pathCallSid = pathCallSid; - this.pathSid = pathSid; + public PaymentUpdater(final String pathaccountSid, final String pathcallSid, final String pathsid, final String idempotencyKey, final URI statusCallback) { + this.pathaccountSid = pathaccountSid; + this.pathcallSid = pathcallSid; + this.pathsid = pathsid; this.idempotencyKey = idempotencyKey; this.statusCallback = statusCallback; } + public PaymentUpdater setIdempotencyKey(final String idempotencyKey) { this.idempotencyKey = idempotencyKey; return this; } + public PaymentUpdater setStatusCallback(final URI statusCallback) { this.statusCallback = statusCallback; return this; } - public PaymentUpdater setStatusCallback(final String statusCallback) { - return setStatusCallback(Promoter.uriFromString(statusCallback)); - } public PaymentUpdater setCapture(final Payment.Capture capture) { this.capture = capture; return this; } + public PaymentUpdater setStatus(final Payment.Status status) { this.status = status; return this; } + @Override public Payment update(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/Calls/{CallSid}/Payments/{Sid}.json"; - - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = path.replace("{" + "CallSid" + "}", this.pathCallSid.toString()); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); - path = - path.replace( - "{" + "IdempotencyKey" + "}", - this.idempotencyKey.toString() - ); - path = - path.replace( - "{" + "StatusCallback" + "}", - this.statusCallback.toString() - ); + + String path = "/2010-04-01/Accounts/{AccountSid}/Calls/{CallSid}/Payments/{Sid}.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "CallSid" + "}", this.pathcallSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.API.toString(), - path + HttpMethod.POST, + Domains.API.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Payment update failed: Unable to connect to server" - ); + throw new ApiConnectionException("Payment update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -144,17 +116,26 @@ public Payment update(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (idempotencyKey != null) { - request.addPostParam("IdempotencyKey", idempotencyKey); + Serializer.toString(request, "IdempotencyKey", idempotencyKey, ParameterType.URLENCODED); } + + if (statusCallback != null) { - request.addPostParam("StatusCallback", statusCallback.toString()); + Serializer.toString(request, "StatusCallback", statusCallback, ParameterType.URLENCODED); } + + if (capture != null) { - request.addPostParam("Capture", capture.toString()); + Serializer.toString(request, "Capture", capture, ParameterType.URLENCODED); } + + if (status != null) { - request.addPostParam("Status", status.toString()); + Serializer.toString(request, "Status", status, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/call/Recording.java b/src/main/java/com/twilio/rest/api/v2010/account/call/Recording.java index 12054b2b44..cc40c31de9 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/call/Recording.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/call/Recording.java @@ -18,117 +18,157 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.CurrencyDeserializer; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.math.BigDecimal; import java.time.ZonedDateTime; import java.util.Currency; -import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Recording extends Resource { - private static final long serialVersionUID = 269042081197241L; - public static RecordingCreator creator(final String pathCallSid) { - return new RecordingCreator(pathCallSid); + public static RecordingCreator creator(final String pathcallSid) { + return new RecordingCreator( + pathcallSid + ); } - public static RecordingCreator creator( - final String pathAccountSid, - final String pathCallSid - ) { - return new RecordingCreator(pathAccountSid, pathCallSid); + + public static RecordingCreator creator(final String pathaccountSid, final String pathcallSid) { + return new RecordingCreator( + pathaccountSid, pathcallSid + ); } - public static RecordingDeleter deleter( - final String pathCallSid, - final String pathSid - ) { - return new RecordingDeleter(pathCallSid, pathSid); + + public static RecordingDeleter deleter(final String pathcallSid, final String pathsid) { + return new RecordingDeleter( + pathcallSid, pathsid + ); } - public static RecordingDeleter deleter( - final String pathAccountSid, - final String pathCallSid, - final String pathSid - ) { - return new RecordingDeleter(pathAccountSid, pathCallSid, pathSid); + + public static RecordingDeleter deleter(final String pathaccountSid, final String pathcallSid, final String pathsid) { + return new RecordingDeleter( + pathaccountSid, pathcallSid, pathsid + ); } - public static RecordingFetcher fetcher( - final String pathCallSid, - final String pathSid - ) { - return new RecordingFetcher(pathCallSid, pathSid); + + public static RecordingFetcher fetcher(final String pathcallSid, final String pathsid) { + return new RecordingFetcher( + pathcallSid, pathsid + ); } - public static RecordingFetcher fetcher( - final String pathAccountSid, - final String pathCallSid, - final String pathSid - ) { - return new RecordingFetcher(pathAccountSid, pathCallSid, pathSid); + + public static RecordingFetcher fetcher(final String pathaccountSid, final String pathcallSid, final String pathsid) { + return new RecordingFetcher( + pathaccountSid, pathcallSid, pathsid + ); } - public static RecordingReader reader(final String pathCallSid) { - return new RecordingReader(pathCallSid); + + public static RecordingReader reader(final String pathcallSid) { + return new RecordingReader( + pathcallSid + ); } - public static RecordingReader reader( - final String pathAccountSid, - final String pathCallSid - ) { - return new RecordingReader(pathAccountSid, pathCallSid); + + public static RecordingReader reader(final String pathaccountSid, final String pathcallSid) { + return new RecordingReader( + pathaccountSid, pathcallSid + ); } - public static RecordingUpdater updater( - final String pathCallSid, - final String pathSid, - final Recording.Status status - ) { - return new RecordingUpdater(pathCallSid, pathSid, status); + + public static RecordingUpdater updater(final String pathcallSid, final String pathsid, final Recording.Status status) { + return new RecordingUpdater( + pathcallSid, pathsid, status + ); } - public static RecordingUpdater updater( - final String pathAccountSid, - final String pathCallSid, - final String pathSid, - final Recording.Status status - ) { + + public static RecordingUpdater updater(final String pathaccountSid, final String pathcallSid, final String pathsid, final Recording.Status status) { return new RecordingUpdater( - pathAccountSid, - pathCallSid, - pathSid, - status + pathaccountSid, pathcallSid, pathsid, status ); } + + public enum Status { + IN_PROGRESS("in-progress"), + PAUSED("paused"), + STOPPED("stopped"), + PROCESSING("processing"), + COMPLETED("completed"), + ABSENT("absent"); + + private final String value; + + private Status(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static Status forValue(final String value) { + return Promoter.enumFromString(value, Status.values()); + } + } + + public enum Source { + DIAL_VERB("DialVerb"), + CONFERENCE("Conference"), + OUTBOUND_API("OutboundAPI"), + TRUNKING("Trunking"), + RECORD_VERB("RecordVerb"), + START_CALL_RECORDING_API("StartCallRecordingAPI"), + START_CONFERENCE_RECORDING_API("StartConferenceRecordingAPI"); + + private final String value; + + private Source(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static Source forValue(final String value) { + return Promoter.enumFromString(value, Source.values()); + } + } + + /** * Converts a JSON String into a Recording object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Recording object represented by the provided JSON */ - public static Recording fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Recording fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Recording.class); @@ -143,14 +183,11 @@ public static Recording fromJson( * Converts a JSON InputStream into a Recording object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Recording object represented by the provided JSON */ - public static Recording fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Recording fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Recording.class); @@ -161,141 +198,99 @@ public static Recording fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; + @Getter private final String apiVersion; + @Getter private final String callSid; + @Getter + private final Integer channels; + @Getter private final String conferenceSid; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; - private final ZonedDateTime startTime; + @Getter private final String duration; - private final String sid; + @Getter + private final Object encryptionDetails; + @Getter + private final Integer errorCode; + @Getter private final BigDecimal price; - private final String uri; - private final Map encryptionDetails; + @Getter private final Currency priceUnit; - private final Recording.Status status; - private final Integer channels; + @Getter + private final String sid; + @Getter private final Recording.Source source; - private final Integer errorCode; + @Getter + private final ZonedDateTime startTime; + @Getter + private final Recording.Status status; + @Getter private final String track; + @Getter + private final String uri; @JsonCreator private Recording( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("api_version") final String apiVersion, - @JsonProperty("call_sid") final String callSid, - @JsonProperty("conference_sid") final String conferenceSid, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("start_time") final String startTime, - @JsonProperty("duration") final String duration, - @JsonProperty("sid") final String sid, - @JsonProperty("price") final BigDecimal price, - @JsonProperty("uri") final String uri, - @JsonProperty("encryption_details") final Map< - String, - Object - > encryptionDetails, - @JsonProperty("price_unit") @JsonDeserialize( - using = com.twilio.converter.CurrencyDeserializer.class - ) final Currency priceUnit, - @JsonProperty("status") final Recording.Status status, - @JsonProperty("channels") final Integer channels, - @JsonProperty("source") final Recording.Source source, - @JsonProperty("error_code") final Integer errorCode, - @JsonProperty("track") final String track + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("api_version") final String apiVersion, + @JsonProperty("call_sid") final String callSid, + @JsonProperty("channels") final Integer channels, + @JsonProperty("conference_sid") final String conferenceSid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.RFC2822Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.RFC2822Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("duration") final String duration, + @JsonProperty("encryption_details") final Object encryptionDetails, + @JsonProperty("error_code") final Integer errorCode, + @JsonProperty("price") final BigDecimal price, + @JsonProperty("price_unit") + @JsonDeserialize(using = com.twilio.converter.CurrencyDeserializer.class) final Currency priceUnit, + @JsonProperty("sid") final String sid, + @JsonProperty("source") final Recording.Source source, + @JsonProperty("start_time") + @JsonDeserialize(using = com.twilio.converter.RFC2822Deserializer.class) final ZonedDateTime startTime, + @JsonProperty("status") final Recording.Status status, + @JsonProperty("track") final String track, + @JsonProperty("uri") final String uri ) { this.accountSid = accountSid; this.apiVersion = apiVersion; this.callSid = callSid; + this.channels = channels; this.conferenceSid = conferenceSid; - this.dateCreated = DateConverter.rfc2822DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.rfc2822DateTimeFromString(dateUpdated); - this.startTime = DateConverter.rfc2822DateTimeFromString(startTime); + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.duration = duration; - this.sid = sid; - this.price = price; - this.uri = uri; this.encryptionDetails = encryptionDetails; + this.errorCode = errorCode; + this.price = price; this.priceUnit = priceUnit; - this.status = status; - this.channels = channels; + this.sid = sid; this.source = source; - this.errorCode = errorCode; + this.startTime = startTime; + this.status = status; this.track = track; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getApiVersion() { - return this.apiVersion; - } - - public final String getCallSid() { - return this.callSid; - } - - public final String getConferenceSid() { - return this.conferenceSid; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final ZonedDateTime getStartTime() { - return this.startTime; - } - - public final String getDuration() { - return this.duration; - } - - public final String getSid() { - return this.sid; - } - - public final BigDecimal getPrice() { - return this.price; - } - - public final String getUri() { - return this.uri; - } - - public final Map getEncryptionDetails() { - return this.encryptionDetails; - } - - public final Currency getPriceUnit() { - return this.priceUnit; - } - - public final Recording.Status getStatus() { - return this.status; - } - - public final Integer getChannels() { - return this.channels; - } - - public final Recording.Source getSource() { - return this.source; - } - - public final Integer getErrorCode() { - return this.errorCode; - } - - public final String getTrack() { - return this.track; + this.uri = uri; } @Override @@ -309,99 +304,52 @@ public boolean equals(final Object o) { } Recording other = (Recording) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(apiVersion, other.apiVersion) && - Objects.equals(callSid, other.callSid) && - Objects.equals(conferenceSid, other.conferenceSid) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(startTime, other.startTime) && - Objects.equals(duration, other.duration) && - Objects.equals(sid, other.sid) && - Objects.equals(price, other.price) && - Objects.equals(uri, other.uri) && - Objects.equals(encryptionDetails, other.encryptionDetails) && - Objects.equals(priceUnit, other.priceUnit) && - Objects.equals(status, other.status) && - Objects.equals(channels, other.channels) && - Objects.equals(source, other.source) && - Objects.equals(errorCode, other.errorCode) && - Objects.equals(track, other.track) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(apiVersion, other.apiVersion) && + Objects.equals(callSid, other.callSid) && + Objects.equals(channels, other.channels) && + Objects.equals(conferenceSid, other.conferenceSid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(duration, other.duration) && + Objects.equals(encryptionDetails, other.encryptionDetails) && + Objects.equals(errorCode, other.errorCode) && + Objects.equals(price, other.price) && + Objects.equals(priceUnit, other.priceUnit) && + Objects.equals(sid, other.sid) && + Objects.equals(source, other.source) && + Objects.equals(startTime, other.startTime) && + Objects.equals(status, other.status) && + Objects.equals(track, other.track) && + Objects.equals(uri, other.uri) ); } @Override public int hashCode() { return Objects.hash( - accountSid, - apiVersion, - callSid, - conferenceSid, - dateCreated, - dateUpdated, - startTime, - duration, - sid, - price, - uri, - encryptionDetails, - priceUnit, - status, - channels, - source, - errorCode, - track + accountSid, + apiVersion, + callSid, + channels, + conferenceSid, + dateCreated, + dateUpdated, + duration, + encryptionDetails, + errorCode, + price, + priceUnit, + sid, + source, + startTime, + status, + track, + uri ); } - public enum Source { - DIALVERB("DialVerb"), - CONFERENCE("Conference"), - OUTBOUNDAPI("OutboundAPI"), - TRUNKING("Trunking"), - RECORDVERB("RecordVerb"), - STARTCALLRECORDINGAPI("StartCallRecordingAPI"), - STARTCONFERENCERECORDINGAPI("StartConferenceRecordingAPI"); - - private final String value; - - private Source(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static Source forValue(final String value) { - return Promoter.enumFromString(value, Source.values()); - } - } - - public enum Status { - IN_PROGRESS("in-progress"), - PAUSED("paused"), - STOPPED("stopped"), - PROCESSING("processing"), - COMPLETED("completed"), - ABSENT("absent"); - - private final String value; - - private Status(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - @JsonCreator - public static Status forValue(final String value) { - return Promoter.enumFromString(value, Status.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/api/v2010/account/call/RecordingCreator.java b/src/main/java/com/twilio/rest/api/v2010/account/call/RecordingCreator.java index 6a082de577..93c2c41698 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/call/RecordingCreator.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/call/RecordingCreator.java @@ -14,9 +14,12 @@ package com.twilio.rest.api.v2010.account.call; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; import com.twilio.converter.Promoter; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,15 +28,14 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -import java.net.URI; + import java.net.URI; import java.util.List; -import java.util.List; public class RecordingCreator extends Creator { - private String pathCallSid; - private String pathAccountSid; + private String pathaccountSid; + private String pathcallSid; private List recordingStatusCallbackEvent; private URI recordingStatusCallback; private HttpMethod recordingStatusCallbackMethod; @@ -41,146 +43,125 @@ public class RecordingCreator extends Creator { private String recordingChannels; private String recordingTrack; - public RecordingCreator(final String pathCallSid) { - this.pathCallSid = pathCallSid; + public RecordingCreator(final String pathcallSid) { + this.pathcallSid = pathcallSid; } - public RecordingCreator( - final String pathAccountSid, - final String pathCallSid - ) { - this.pathAccountSid = pathAccountSid; - this.pathCallSid = pathCallSid; + public RecordingCreator(final String pathaccountSid, final String pathcallSid) { + this.pathaccountSid = pathaccountSid; + this.pathcallSid = pathcallSid; } - public RecordingCreator setRecordingStatusCallbackEvent( - final List recordingStatusCallbackEvent - ) { + + public RecordingCreator setRecordingStatusCallbackEvent(final List recordingStatusCallbackEvent) { this.recordingStatusCallbackEvent = recordingStatusCallbackEvent; return this; } - public RecordingCreator setRecordingStatusCallbackEvent( - final String recordingStatusCallbackEvent - ) { - return setRecordingStatusCallbackEvent( - Promoter.listOfOne(recordingStatusCallbackEvent) - ); + public RecordingCreator setRecordingStatusCallbackEvent(final String recordingStatusCallbackEvent) { + return setRecordingStatusCallbackEvent(Promoter.listOfOne(recordingStatusCallbackEvent)); } - public RecordingCreator setRecordingStatusCallback( - final URI recordingStatusCallback - ) { + public RecordingCreator setRecordingStatusCallback(final URI recordingStatusCallback) { this.recordingStatusCallback = recordingStatusCallback; return this; } - public RecordingCreator setRecordingStatusCallback( - final String recordingStatusCallback - ) { - return setRecordingStatusCallback( - Promoter.uriFromString(recordingStatusCallback) - ); - } - public RecordingCreator setRecordingStatusCallbackMethod( - final HttpMethod recordingStatusCallbackMethod - ) { + public RecordingCreator setRecordingStatusCallbackMethod(final HttpMethod recordingStatusCallbackMethod) { this.recordingStatusCallbackMethod = recordingStatusCallbackMethod; return this; } + public RecordingCreator setTrim(final String trim) { this.trim = trim; return this; } - public RecordingCreator setRecordingChannels( - final String recordingChannels - ) { + + public RecordingCreator setRecordingChannels(final String recordingChannels) { this.recordingChannels = recordingChannels; return this; } + public RecordingCreator setRecordingTrack(final String recordingTrack) { this.recordingTrack = recordingTrack; return this; } + @Override public Recording create(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/Calls/{CallSid}/Recordings.json"; - - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = path.replace("{" + "CallSid" + "}", this.pathCallSid.toString()); + + String path = "/2010-04-01/Accounts/{AccountSid}/Calls/{CallSid}/Recordings.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "CallSid" + "}", this.pathcallSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.API.toString(), - path + HttpMethod.POST, + Domains.API.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Recording creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("Recording creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Recording.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Recording.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + + if (recordingStatusCallbackEvent != null) { - for (String prop : recordingStatusCallbackEvent) { - request.addPostParam("RecordingStatusCallbackEvent", prop); + for (String param : recordingStatusCallbackEvent) { + Serializer.toString(request, "RecordingStatusCallbackEvent", param, ParameterType.URLENCODED); } } + + if (recordingStatusCallback != null) { - request.addPostParam( - "RecordingStatusCallback", - recordingStatusCallback.toString() - ); + Serializer.toString(request, "RecordingStatusCallback", recordingStatusCallback, ParameterType.URLENCODED); } + + if (recordingStatusCallbackMethod != null) { - request.addPostParam( - "RecordingStatusCallbackMethod", - recordingStatusCallbackMethod.toString() - ); + Serializer.toString(request, "RecordingStatusCallbackMethod", recordingStatusCallbackMethod, ParameterType.URLENCODED); } + + if (trim != null) { - request.addPostParam("Trim", trim); + Serializer.toString(request, "Trim", trim, ParameterType.URLENCODED); } + + if (recordingChannels != null) { - request.addPostParam("RecordingChannels", recordingChannels); + Serializer.toString(request, "RecordingChannels", recordingChannels, ParameterType.URLENCODED); } + + if (recordingTrack != null) { - request.addPostParam("RecordingTrack", recordingTrack); + Serializer.toString(request, "RecordingTrack", recordingTrack, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/call/RecordingDeleter.java b/src/main/java/com/twilio/rest/api/v2010/account/call/RecordingDeleter.java index cac109a3e7..76ba69ba44 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/call/RecordingDeleter.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/call/RecordingDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.api.v2010.account.call; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,64 +26,50 @@ public class RecordingDeleter extends Deleter { - private String pathCallSid; - private String pathSid; - private String pathAccountSid; + private String pathaccountSid; + private String pathcallSid; + private String pathsid; - public RecordingDeleter(final String pathCallSid, final String pathSid) { - this.pathCallSid = pathCallSid; - this.pathSid = pathSid; + public RecordingDeleter(final String pathcallSid, final String pathsid) { + this.pathcallSid = pathcallSid; + this.pathsid = pathsid; } - public RecordingDeleter( - final String pathAccountSid, - final String pathCallSid, - final String pathSid - ) { - this.pathAccountSid = pathAccountSid; - this.pathCallSid = pathCallSid; - this.pathSid = pathSid; + public RecordingDeleter(final String pathaccountSid, final String pathcallSid, final String pathsid) { + this.pathaccountSid = pathaccountSid; + this.pathcallSid = pathcallSid; + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/Calls/{CallSid}/Recordings/{Sid}.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = path.replace("{" + "CallSid" + "}", this.pathCallSid.toString()); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/2010-04-01/Accounts/{AccountSid}/Calls/{CallSid}/Recordings/{Sid}.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "CallSid" + "}", this.pathcallSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.API.toString(), - path + HttpMethod.DELETE, + Domains.API.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Recording delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("Recording delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/call/RecordingFetcher.java b/src/main/java/com/twilio/rest/api/v2010/account/call/RecordingFetcher.java index 12c69c071f..d0c2394d97 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/call/RecordingFetcher.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/call/RecordingFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.api.v2010.account.call; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,71 +26,53 @@ public class RecordingFetcher extends Fetcher { - private String pathCallSid; - private String pathSid; - private String pathAccountSid; + private String pathaccountSid; + private String pathcallSid; + private String pathsid; - public RecordingFetcher(final String pathCallSid, final String pathSid) { - this.pathCallSid = pathCallSid; - this.pathSid = pathSid; + public RecordingFetcher(final String pathcallSid, final String pathsid) { + this.pathcallSid = pathcallSid; + this.pathsid = pathsid; } - public RecordingFetcher( - final String pathAccountSid, - final String pathCallSid, - final String pathSid - ) { - this.pathAccountSid = pathAccountSid; - this.pathCallSid = pathCallSid; - this.pathSid = pathSid; + public RecordingFetcher(final String pathaccountSid, final String pathcallSid, final String pathsid) { + this.pathaccountSid = pathaccountSid; + this.pathcallSid = pathcallSid; + this.pathsid = pathsid; } + @Override public Recording fetch(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/Calls/{CallSid}/Recordings/{Sid}.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = path.replace("{" + "CallSid" + "}", this.pathCallSid.toString()); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/2010-04-01/Accounts/{AccountSid}/Calls/{CallSid}/Recordings/{Sid}.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "CallSid" + "}", this.pathcallSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.API.toString(), - path + HttpMethod.GET, + Domains.API.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Recording fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Recording fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return Recording.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Recording.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/call/RecordingReader.java b/src/main/java/com/twilio/rest/api/v2010/account/call/RecordingReader.java index d76faab957..e35abb896e 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/call/RecordingReader.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/call/RecordingReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -26,173 +27,137 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.time.LocalDate; -import java.time.format.DateTimeFormatter; public class RecordingReader extends Reader { - private String pathCallSid; - private String pathAccountSid; + private String pathaccountSid; + private String pathcallSid; private LocalDate dateCreated; private LocalDate dateCreatedBefore; private LocalDate dateCreatedAfter; private Long pageSize; - public RecordingReader(final String pathCallSid) { - this.pathCallSid = pathCallSid; + public RecordingReader(final String pathcallSid) { + this.pathcallSid = pathcallSid; } - public RecordingReader( - final String pathAccountSid, - final String pathCallSid - ) { - this.pathAccountSid = pathAccountSid; - this.pathCallSid = pathCallSid; + public RecordingReader(final String pathaccountSid, final String pathcallSid) { + this.pathaccountSid = pathaccountSid; + this.pathcallSid = pathcallSid; } + public RecordingReader setDateCreated(final LocalDate dateCreated) { this.dateCreated = dateCreated; return this; } - public RecordingReader setDateCreatedBefore( - final LocalDate dateCreatedBefore - ) { + + public RecordingReader setDateCreatedBefore(final LocalDate dateCreatedBefore) { this.dateCreatedBefore = dateCreatedBefore; return this; } - public RecordingReader setDateCreatedAfter( - final LocalDate dateCreatedAfter - ) { + + public RecordingReader setDateCreatedAfter(final LocalDate dateCreatedAfter) { this.dateCreatedAfter = dateCreatedAfter; return this; } + public RecordingReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/Calls/{CallSid}/Recordings.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = path.replace("{" + "CallSid" + "}", this.pathCallSid.toString()); + + String path = "/2010-04-01/Accounts/{AccountSid}/Calls/{CallSid}/Recordings.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "CallSid" + "}", this.pathcallSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.API.toString(), - path + HttpMethod.GET, + Domains.API.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Recording read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Recording read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "recordings", - response.getContent(), - Recording.class, - client.getObjectMapper() - ); + "recordings", + response.getContent(), + Recording.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.API.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.API.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (dateCreated != null) { - request.addQueryParam( - "DateCreated", - dateCreated.format( - DateTimeFormatter.ofPattern( - Request.QUERY_STRING_DATE_FORMAT - ) - ) - ); - } else if (dateCreatedAfter != null || dateCreatedBefore != null) { - request.addQueryDateRange( - "DateCreated", - dateCreatedAfter, - dateCreatedBefore - ); + Serializer.toString(request, "DateCreated", dateCreated, ParameterType.QUERY); } - if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + + + if (dateCreatedBefore != null) { + Serializer.toString(request, "DateCreated<", dateCreatedBefore, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); + + if (dateCreatedAfter != null) { + Serializer.toString(request, "DateCreated>", dateCreatedAfter, ParameterType.QUERY); } + + + if (pageSize != null) { + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); + } + + } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/call/RecordingUpdater.java b/src/main/java/com/twilio/rest/api/v2010/account/call/RecordingUpdater.java index e9823834d5..23ca8b2a42 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/call/RecordingUpdater.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/call/RecordingUpdater.java @@ -16,6 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -26,101 +28,86 @@ import com.twilio.rest.Domains; public class RecordingUpdater extends Updater { - - private String pathCallSid; - private String pathSid; + private String pathaccountSid; + private String pathcallSid; + private String pathsid; private Recording.Status status; - private String pathAccountSid; private String pauseBehavior; - public RecordingUpdater( - final String pathCallSid, - final String pathSid, - final Recording.Status status - ) { - this.pathCallSid = pathCallSid; - this.pathSid = pathSid; + public RecordingUpdater(final String pathcallSid, final String pathsid, final Recording.Status status) { + this.pathcallSid = pathcallSid; + this.pathsid = pathsid; this.status = status; } - public RecordingUpdater( - final String pathAccountSid, - final String pathCallSid, - final String pathSid, - final Recording.Status status - ) { - this.pathAccountSid = pathAccountSid; - this.pathCallSid = pathCallSid; - this.pathSid = pathSid; + public RecordingUpdater(final String pathaccountSid, final String pathcallSid, final String pathsid, final Recording.Status status) { + this.pathaccountSid = pathaccountSid; + this.pathcallSid = pathcallSid; + this.pathsid = pathsid; this.status = status; } + public RecordingUpdater setStatus(final Recording.Status status) { this.status = status; return this; } + public RecordingUpdater setPauseBehavior(final String pauseBehavior) { this.pauseBehavior = pauseBehavior; return this; } + @Override public Recording update(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/Calls/{CallSid}/Recordings/{Sid}.json"; - - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = path.replace("{" + "CallSid" + "}", this.pathCallSid.toString()); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); - path = path.replace("{" + "Status" + "}", this.status.toString()); + + String path = "/2010-04-01/Accounts/{AccountSid}/Calls/{CallSid}/Recordings/{Sid}.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "CallSid" + "}", this.pathcallSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.API.toString(), - path + HttpMethod.POST, + Domains.API.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Recording update failed: Unable to connect to server" - ); + throw new ApiConnectionException("Recording update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Recording.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Recording.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (status != null) { - request.addPostParam("Status", status.toString()); + Serializer.toString(request, "Status", status, ParameterType.URLENCODED); } + + if (pauseBehavior != null) { - request.addPostParam("PauseBehavior", pauseBehavior); + Serializer.toString(request, "PauseBehavior", pauseBehavior, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/call/Siprec.java b/src/main/java/com/twilio/rest/api/v2010/account/call/Siprec.java index 376b870d65..ba22e338e3 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/call/Siprec.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/call/Siprec.java @@ -18,65 +18,124 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.time.ZonedDateTime; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Siprec extends Resource { - private static final long serialVersionUID = 230113301753485L; - public static SiprecCreator creator(final String pathCallSid) { - return new SiprecCreator(pathCallSid); + public static SiprecCreator creator(final String pathcallSid) { + return new SiprecCreator( + pathcallSid + ); } - public static SiprecCreator creator( - final String pathAccountSid, - final String pathCallSid - ) { - return new SiprecCreator(pathAccountSid, pathCallSid); + + public static SiprecCreator creator(final String pathaccountSid, final String pathcallSid) { + return new SiprecCreator( + pathaccountSid, pathcallSid + ); } - public static SiprecUpdater updater( - final String pathCallSid, - final String pathSid, - final Siprec.UpdateStatus status - ) { - return new SiprecUpdater(pathCallSid, pathSid, status); + + public static SiprecUpdater updater(final String pathcallSid, final String pathsid, final Siprec.UpdateStatus status) { + return new SiprecUpdater( + pathcallSid, pathsid, status + ); } - public static SiprecUpdater updater( - final String pathAccountSid, - final String pathCallSid, - final String pathSid, - final Siprec.UpdateStatus status - ) { - return new SiprecUpdater(pathAccountSid, pathCallSid, pathSid, status); + + public static SiprecUpdater updater(final String pathaccountSid, final String pathcallSid, final String pathsid, final Siprec.UpdateStatus status) { + return new SiprecUpdater( + pathaccountSid, pathcallSid, pathsid, status + ); + } + + + public enum Status { + IN_PROGRESS("in-progress"), + STOPPED("stopped"); + + private final String value; + + private Status(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static Status forValue(final String value) { + return Promoter.enumFromString(value, Status.values()); + } + } + + public enum UpdateStatus { + STOPPED("stopped"); + + private final String value; + + private UpdateStatus(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static UpdateStatus forValue(final String value) { + return Promoter.enumFromString(value, UpdateStatus.values()); + } + } + + public enum Track { + INBOUND_TRACK("inbound_track"), + OUTBOUND_TRACK("outbound_track"), + BOTH_TRACKS("both_tracks"); + + private final String value; + + private Track(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static Track forValue(final String value) { + return Promoter.enumFromString(value, Track.values()); + } } + /** * Converts a JSON String into a Siprec object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Siprec object represented by the provided JSON */ - public static Siprec fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Siprec fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Siprec.class); @@ -91,14 +150,11 @@ public static Siprec fromJson( * Converts a JSON InputStream into a Siprec object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Siprec object represented by the provided JSON */ - public static Siprec fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Siprec fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Siprec.class); @@ -109,61 +165,54 @@ public static Siprec fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; + @Getter private final String callSid; + @Getter + private final ZonedDateTime dateUpdated; + @Getter private final String name; + @Getter + private final String sid; + @Getter private final Siprec.Status status; - private final ZonedDateTime dateUpdated; + @Getter private final String uri; @JsonCreator private Siprec( - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("call_sid") final String callSid, - @JsonProperty("name") final String name, - @JsonProperty("status") final Siprec.Status status, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("uri") final String uri + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("call_sid") final String callSid, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.RFC2822Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("name") final String name, + @JsonProperty("sid") final String sid, + @JsonProperty("status") final Siprec.Status status, + @JsonProperty("uri") final String uri ) { - this.sid = sid; this.accountSid = accountSid; this.callSid = callSid; + this.dateUpdated = dateUpdated; this.name = name; + this.sid = sid; this.status = status; - this.dateUpdated = DateConverter.rfc2822DateTimeFromString(dateUpdated); this.uri = uri; } - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getCallSid() { - return this.callSid; - } - - public final String getName() { - return this.name; - } - - public final Siprec.Status getStatus() { - return this.status; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final String getUri() { - return this.uri; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -175,88 +224,30 @@ public boolean equals(final Object o) { } Siprec other = (Siprec) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(callSid, other.callSid) && - Objects.equals(name, other.name) && - Objects.equals(status, other.status) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(uri, other.uri) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(callSid, other.callSid) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(name, other.name) && + Objects.equals(sid, other.sid) && + Objects.equals(status, other.status) && + Objects.equals(uri, other.uri) ); } @Override public int hashCode() { return Objects.hash( - sid, - accountSid, - callSid, - name, - status, - dateUpdated, - uri + accountSid, + callSid, + dateUpdated, + name, + sid, + status, + uri ); } - public enum UpdateStatus { - STOPPED("stopped"); - - private final String value; - - private UpdateStatus(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static UpdateStatus forValue(final String value) { - return Promoter.enumFromString(value, UpdateStatus.values()); - } - } - public enum Track { - INBOUND_TRACK("inbound_track"), - OUTBOUND_TRACK("outbound_track"), - BOTH_TRACKS("both_tracks"); - - private final String value; - - private Track(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static Track forValue(final String value) { - return Promoter.enumFromString(value, Track.values()); - } - } - - public enum Status { - IN_PROGRESS("in-progress"), - STOPPED("stopped"); - - private final String value; - - private Status(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static Status forValue(final String value) { - return Promoter.enumFromString(value, Status.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/api/v2010/account/call/SiprecCreator.java b/src/main/java/com/twilio/rest/api/v2010/account/call/SiprecCreator.java index 6f12632a84..8f26293159 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/call/SiprecCreator.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/call/SiprecCreator.java @@ -14,9 +14,11 @@ package com.twilio.rest.api.v2010.account.call; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; -import com.twilio.converter.Promoter; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,13 +27,13 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -import java.net.URI; + import java.net.URI; public class SiprecCreator extends Creator { - private String pathCallSid; - private String pathAccountSid; + private String pathaccountSid; + private String pathcallSid; private String name; private String connectorName; private Siprec.Track track; @@ -236,1077 +238,1263 @@ public class SiprecCreator extends Creator { private String parameter99Name; private String parameter99Value; - public SiprecCreator(final String pathCallSid) { - this.pathCallSid = pathCallSid; + public SiprecCreator(final String pathcallSid) { + this.pathcallSid = pathcallSid; } - public SiprecCreator( - final String pathAccountSid, - final String pathCallSid - ) { - this.pathAccountSid = pathAccountSid; - this.pathCallSid = pathCallSid; + public SiprecCreator(final String pathaccountSid, final String pathcallSid) { + this.pathaccountSid = pathaccountSid; + this.pathcallSid = pathcallSid; } + public SiprecCreator setName(final String name) { this.name = name; return this; } + public SiprecCreator setConnectorName(final String connectorName) { this.connectorName = connectorName; return this; } + public SiprecCreator setTrack(final Siprec.Track track) { this.track = track; return this; } + public SiprecCreator setStatusCallback(final URI statusCallback) { this.statusCallback = statusCallback; return this; } - public SiprecCreator setStatusCallback(final String statusCallback) { - return setStatusCallback(Promoter.uriFromString(statusCallback)); - } - public SiprecCreator setStatusCallbackMethod( - final HttpMethod statusCallbackMethod - ) { + public SiprecCreator setStatusCallbackMethod(final HttpMethod statusCallbackMethod) { this.statusCallbackMethod = statusCallbackMethod; return this; } + public SiprecCreator setParameter1Name(final String parameter1Name) { this.parameter1Name = parameter1Name; return this; } + public SiprecCreator setParameter1Value(final String parameter1Value) { this.parameter1Value = parameter1Value; return this; } + public SiprecCreator setParameter2Name(final String parameter2Name) { this.parameter2Name = parameter2Name; return this; } + public SiprecCreator setParameter2Value(final String parameter2Value) { this.parameter2Value = parameter2Value; return this; } + public SiprecCreator setParameter3Name(final String parameter3Name) { this.parameter3Name = parameter3Name; return this; } + public SiprecCreator setParameter3Value(final String parameter3Value) { this.parameter3Value = parameter3Value; return this; } + public SiprecCreator setParameter4Name(final String parameter4Name) { this.parameter4Name = parameter4Name; return this; } + public SiprecCreator setParameter4Value(final String parameter4Value) { this.parameter4Value = parameter4Value; return this; } + public SiprecCreator setParameter5Name(final String parameter5Name) { this.parameter5Name = parameter5Name; return this; } + public SiprecCreator setParameter5Value(final String parameter5Value) { this.parameter5Value = parameter5Value; return this; } + public SiprecCreator setParameter6Name(final String parameter6Name) { this.parameter6Name = parameter6Name; return this; } + public SiprecCreator setParameter6Value(final String parameter6Value) { this.parameter6Value = parameter6Value; return this; } + public SiprecCreator setParameter7Name(final String parameter7Name) { this.parameter7Name = parameter7Name; return this; } + public SiprecCreator setParameter7Value(final String parameter7Value) { this.parameter7Value = parameter7Value; return this; } + public SiprecCreator setParameter8Name(final String parameter8Name) { this.parameter8Name = parameter8Name; return this; } + public SiprecCreator setParameter8Value(final String parameter8Value) { this.parameter8Value = parameter8Value; return this; } + public SiprecCreator setParameter9Name(final String parameter9Name) { this.parameter9Name = parameter9Name; return this; } + public SiprecCreator setParameter9Value(final String parameter9Value) { this.parameter9Value = parameter9Value; return this; } + public SiprecCreator setParameter10Name(final String parameter10Name) { this.parameter10Name = parameter10Name; return this; } + public SiprecCreator setParameter10Value(final String parameter10Value) { this.parameter10Value = parameter10Value; return this; } + public SiprecCreator setParameter11Name(final String parameter11Name) { this.parameter11Name = parameter11Name; return this; } + public SiprecCreator setParameter11Value(final String parameter11Value) { this.parameter11Value = parameter11Value; return this; } + public SiprecCreator setParameter12Name(final String parameter12Name) { this.parameter12Name = parameter12Name; return this; } + public SiprecCreator setParameter12Value(final String parameter12Value) { this.parameter12Value = parameter12Value; return this; } + public SiprecCreator setParameter13Name(final String parameter13Name) { this.parameter13Name = parameter13Name; return this; } + public SiprecCreator setParameter13Value(final String parameter13Value) { this.parameter13Value = parameter13Value; return this; } + public SiprecCreator setParameter14Name(final String parameter14Name) { this.parameter14Name = parameter14Name; return this; } + public SiprecCreator setParameter14Value(final String parameter14Value) { this.parameter14Value = parameter14Value; return this; } + public SiprecCreator setParameter15Name(final String parameter15Name) { this.parameter15Name = parameter15Name; return this; } + public SiprecCreator setParameter15Value(final String parameter15Value) { this.parameter15Value = parameter15Value; return this; } + public SiprecCreator setParameter16Name(final String parameter16Name) { this.parameter16Name = parameter16Name; return this; } + public SiprecCreator setParameter16Value(final String parameter16Value) { this.parameter16Value = parameter16Value; return this; } + public SiprecCreator setParameter17Name(final String parameter17Name) { this.parameter17Name = parameter17Name; return this; } + public SiprecCreator setParameter17Value(final String parameter17Value) { this.parameter17Value = parameter17Value; return this; } + public SiprecCreator setParameter18Name(final String parameter18Name) { this.parameter18Name = parameter18Name; return this; } + public SiprecCreator setParameter18Value(final String parameter18Value) { this.parameter18Value = parameter18Value; return this; } + public SiprecCreator setParameter19Name(final String parameter19Name) { this.parameter19Name = parameter19Name; return this; } + public SiprecCreator setParameter19Value(final String parameter19Value) { this.parameter19Value = parameter19Value; return this; } + public SiprecCreator setParameter20Name(final String parameter20Name) { this.parameter20Name = parameter20Name; return this; } + public SiprecCreator setParameter20Value(final String parameter20Value) { this.parameter20Value = parameter20Value; return this; } + public SiprecCreator setParameter21Name(final String parameter21Name) { this.parameter21Name = parameter21Name; return this; } + public SiprecCreator setParameter21Value(final String parameter21Value) { this.parameter21Value = parameter21Value; return this; } + public SiprecCreator setParameter22Name(final String parameter22Name) { this.parameter22Name = parameter22Name; return this; } + public SiprecCreator setParameter22Value(final String parameter22Value) { this.parameter22Value = parameter22Value; return this; } + public SiprecCreator setParameter23Name(final String parameter23Name) { this.parameter23Name = parameter23Name; return this; } + public SiprecCreator setParameter23Value(final String parameter23Value) { this.parameter23Value = parameter23Value; return this; } + public SiprecCreator setParameter24Name(final String parameter24Name) { this.parameter24Name = parameter24Name; return this; } + public SiprecCreator setParameter24Value(final String parameter24Value) { this.parameter24Value = parameter24Value; return this; } + public SiprecCreator setParameter25Name(final String parameter25Name) { this.parameter25Name = parameter25Name; return this; } + public SiprecCreator setParameter25Value(final String parameter25Value) { this.parameter25Value = parameter25Value; return this; } + public SiprecCreator setParameter26Name(final String parameter26Name) { this.parameter26Name = parameter26Name; return this; } + public SiprecCreator setParameter26Value(final String parameter26Value) { this.parameter26Value = parameter26Value; return this; } + public SiprecCreator setParameter27Name(final String parameter27Name) { this.parameter27Name = parameter27Name; return this; } + public SiprecCreator setParameter27Value(final String parameter27Value) { this.parameter27Value = parameter27Value; return this; } + public SiprecCreator setParameter28Name(final String parameter28Name) { this.parameter28Name = parameter28Name; return this; } + public SiprecCreator setParameter28Value(final String parameter28Value) { this.parameter28Value = parameter28Value; return this; } + public SiprecCreator setParameter29Name(final String parameter29Name) { this.parameter29Name = parameter29Name; return this; } + public SiprecCreator setParameter29Value(final String parameter29Value) { this.parameter29Value = parameter29Value; return this; } + public SiprecCreator setParameter30Name(final String parameter30Name) { this.parameter30Name = parameter30Name; return this; } + public SiprecCreator setParameter30Value(final String parameter30Value) { this.parameter30Value = parameter30Value; return this; } + public SiprecCreator setParameter31Name(final String parameter31Name) { this.parameter31Name = parameter31Name; return this; } + public SiprecCreator setParameter31Value(final String parameter31Value) { this.parameter31Value = parameter31Value; return this; } + public SiprecCreator setParameter32Name(final String parameter32Name) { this.parameter32Name = parameter32Name; return this; } + public SiprecCreator setParameter32Value(final String parameter32Value) { this.parameter32Value = parameter32Value; return this; } + public SiprecCreator setParameter33Name(final String parameter33Name) { this.parameter33Name = parameter33Name; return this; } + public SiprecCreator setParameter33Value(final String parameter33Value) { this.parameter33Value = parameter33Value; return this; } + public SiprecCreator setParameter34Name(final String parameter34Name) { this.parameter34Name = parameter34Name; return this; } + public SiprecCreator setParameter34Value(final String parameter34Value) { this.parameter34Value = parameter34Value; return this; } + public SiprecCreator setParameter35Name(final String parameter35Name) { this.parameter35Name = parameter35Name; return this; } + public SiprecCreator setParameter35Value(final String parameter35Value) { this.parameter35Value = parameter35Value; return this; } + public SiprecCreator setParameter36Name(final String parameter36Name) { this.parameter36Name = parameter36Name; return this; } + public SiprecCreator setParameter36Value(final String parameter36Value) { this.parameter36Value = parameter36Value; return this; } + public SiprecCreator setParameter37Name(final String parameter37Name) { this.parameter37Name = parameter37Name; return this; } + public SiprecCreator setParameter37Value(final String parameter37Value) { this.parameter37Value = parameter37Value; return this; } + public SiprecCreator setParameter38Name(final String parameter38Name) { this.parameter38Name = parameter38Name; return this; } + public SiprecCreator setParameter38Value(final String parameter38Value) { this.parameter38Value = parameter38Value; return this; } + public SiprecCreator setParameter39Name(final String parameter39Name) { this.parameter39Name = parameter39Name; return this; } + public SiprecCreator setParameter39Value(final String parameter39Value) { this.parameter39Value = parameter39Value; return this; } + public SiprecCreator setParameter40Name(final String parameter40Name) { this.parameter40Name = parameter40Name; return this; } + public SiprecCreator setParameter40Value(final String parameter40Value) { this.parameter40Value = parameter40Value; return this; } + public SiprecCreator setParameter41Name(final String parameter41Name) { this.parameter41Name = parameter41Name; return this; } + public SiprecCreator setParameter41Value(final String parameter41Value) { this.parameter41Value = parameter41Value; return this; } + public SiprecCreator setParameter42Name(final String parameter42Name) { this.parameter42Name = parameter42Name; return this; } + public SiprecCreator setParameter42Value(final String parameter42Value) { this.parameter42Value = parameter42Value; return this; } + public SiprecCreator setParameter43Name(final String parameter43Name) { this.parameter43Name = parameter43Name; return this; } + public SiprecCreator setParameter43Value(final String parameter43Value) { this.parameter43Value = parameter43Value; return this; } + public SiprecCreator setParameter44Name(final String parameter44Name) { this.parameter44Name = parameter44Name; return this; } + public SiprecCreator setParameter44Value(final String parameter44Value) { this.parameter44Value = parameter44Value; return this; } + public SiprecCreator setParameter45Name(final String parameter45Name) { this.parameter45Name = parameter45Name; return this; } + public SiprecCreator setParameter45Value(final String parameter45Value) { this.parameter45Value = parameter45Value; return this; } + public SiprecCreator setParameter46Name(final String parameter46Name) { this.parameter46Name = parameter46Name; return this; } + public SiprecCreator setParameter46Value(final String parameter46Value) { this.parameter46Value = parameter46Value; return this; } + public SiprecCreator setParameter47Name(final String parameter47Name) { this.parameter47Name = parameter47Name; return this; } + public SiprecCreator setParameter47Value(final String parameter47Value) { this.parameter47Value = parameter47Value; return this; } + public SiprecCreator setParameter48Name(final String parameter48Name) { this.parameter48Name = parameter48Name; return this; } + public SiprecCreator setParameter48Value(final String parameter48Value) { this.parameter48Value = parameter48Value; return this; } + public SiprecCreator setParameter49Name(final String parameter49Name) { this.parameter49Name = parameter49Name; return this; } + public SiprecCreator setParameter49Value(final String parameter49Value) { this.parameter49Value = parameter49Value; return this; } + public SiprecCreator setParameter50Name(final String parameter50Name) { this.parameter50Name = parameter50Name; return this; } + public SiprecCreator setParameter50Value(final String parameter50Value) { this.parameter50Value = parameter50Value; return this; } + public SiprecCreator setParameter51Name(final String parameter51Name) { this.parameter51Name = parameter51Name; return this; } + public SiprecCreator setParameter51Value(final String parameter51Value) { this.parameter51Value = parameter51Value; return this; } + public SiprecCreator setParameter52Name(final String parameter52Name) { this.parameter52Name = parameter52Name; return this; } + public SiprecCreator setParameter52Value(final String parameter52Value) { this.parameter52Value = parameter52Value; return this; } + public SiprecCreator setParameter53Name(final String parameter53Name) { this.parameter53Name = parameter53Name; return this; } + public SiprecCreator setParameter53Value(final String parameter53Value) { this.parameter53Value = parameter53Value; return this; } + public SiprecCreator setParameter54Name(final String parameter54Name) { this.parameter54Name = parameter54Name; return this; } + public SiprecCreator setParameter54Value(final String parameter54Value) { this.parameter54Value = parameter54Value; return this; } + public SiprecCreator setParameter55Name(final String parameter55Name) { this.parameter55Name = parameter55Name; return this; } + public SiprecCreator setParameter55Value(final String parameter55Value) { this.parameter55Value = parameter55Value; return this; } + public SiprecCreator setParameter56Name(final String parameter56Name) { this.parameter56Name = parameter56Name; return this; } + public SiprecCreator setParameter56Value(final String parameter56Value) { this.parameter56Value = parameter56Value; return this; } + public SiprecCreator setParameter57Name(final String parameter57Name) { this.parameter57Name = parameter57Name; return this; } + public SiprecCreator setParameter57Value(final String parameter57Value) { this.parameter57Value = parameter57Value; return this; } + public SiprecCreator setParameter58Name(final String parameter58Name) { this.parameter58Name = parameter58Name; return this; } + public SiprecCreator setParameter58Value(final String parameter58Value) { this.parameter58Value = parameter58Value; return this; } + public SiprecCreator setParameter59Name(final String parameter59Name) { this.parameter59Name = parameter59Name; return this; } + public SiprecCreator setParameter59Value(final String parameter59Value) { this.parameter59Value = parameter59Value; return this; } + public SiprecCreator setParameter60Name(final String parameter60Name) { this.parameter60Name = parameter60Name; return this; } + public SiprecCreator setParameter60Value(final String parameter60Value) { this.parameter60Value = parameter60Value; return this; } + public SiprecCreator setParameter61Name(final String parameter61Name) { this.parameter61Name = parameter61Name; return this; } + public SiprecCreator setParameter61Value(final String parameter61Value) { this.parameter61Value = parameter61Value; return this; } + public SiprecCreator setParameter62Name(final String parameter62Name) { this.parameter62Name = parameter62Name; return this; } + public SiprecCreator setParameter62Value(final String parameter62Value) { this.parameter62Value = parameter62Value; return this; } + public SiprecCreator setParameter63Name(final String parameter63Name) { this.parameter63Name = parameter63Name; return this; } + public SiprecCreator setParameter63Value(final String parameter63Value) { this.parameter63Value = parameter63Value; return this; } + public SiprecCreator setParameter64Name(final String parameter64Name) { this.parameter64Name = parameter64Name; return this; } + public SiprecCreator setParameter64Value(final String parameter64Value) { this.parameter64Value = parameter64Value; return this; } + public SiprecCreator setParameter65Name(final String parameter65Name) { this.parameter65Name = parameter65Name; return this; } + public SiprecCreator setParameter65Value(final String parameter65Value) { this.parameter65Value = parameter65Value; return this; } + public SiprecCreator setParameter66Name(final String parameter66Name) { this.parameter66Name = parameter66Name; return this; } + public SiprecCreator setParameter66Value(final String parameter66Value) { this.parameter66Value = parameter66Value; return this; } + public SiprecCreator setParameter67Name(final String parameter67Name) { this.parameter67Name = parameter67Name; return this; } + public SiprecCreator setParameter67Value(final String parameter67Value) { this.parameter67Value = parameter67Value; return this; } + public SiprecCreator setParameter68Name(final String parameter68Name) { this.parameter68Name = parameter68Name; return this; } + public SiprecCreator setParameter68Value(final String parameter68Value) { this.parameter68Value = parameter68Value; return this; } + public SiprecCreator setParameter69Name(final String parameter69Name) { this.parameter69Name = parameter69Name; return this; } + public SiprecCreator setParameter69Value(final String parameter69Value) { this.parameter69Value = parameter69Value; return this; } + public SiprecCreator setParameter70Name(final String parameter70Name) { this.parameter70Name = parameter70Name; return this; } + public SiprecCreator setParameter70Value(final String parameter70Value) { this.parameter70Value = parameter70Value; return this; } + public SiprecCreator setParameter71Name(final String parameter71Name) { this.parameter71Name = parameter71Name; return this; } + public SiprecCreator setParameter71Value(final String parameter71Value) { this.parameter71Value = parameter71Value; return this; } + public SiprecCreator setParameter72Name(final String parameter72Name) { this.parameter72Name = parameter72Name; return this; } + public SiprecCreator setParameter72Value(final String parameter72Value) { this.parameter72Value = parameter72Value; return this; } + public SiprecCreator setParameter73Name(final String parameter73Name) { this.parameter73Name = parameter73Name; return this; } + public SiprecCreator setParameter73Value(final String parameter73Value) { this.parameter73Value = parameter73Value; return this; } + public SiprecCreator setParameter74Name(final String parameter74Name) { this.parameter74Name = parameter74Name; return this; } + public SiprecCreator setParameter74Value(final String parameter74Value) { this.parameter74Value = parameter74Value; return this; } + public SiprecCreator setParameter75Name(final String parameter75Name) { this.parameter75Name = parameter75Name; return this; } + public SiprecCreator setParameter75Value(final String parameter75Value) { this.parameter75Value = parameter75Value; return this; } + public SiprecCreator setParameter76Name(final String parameter76Name) { this.parameter76Name = parameter76Name; return this; } + public SiprecCreator setParameter76Value(final String parameter76Value) { this.parameter76Value = parameter76Value; return this; } + public SiprecCreator setParameter77Name(final String parameter77Name) { this.parameter77Name = parameter77Name; return this; } + public SiprecCreator setParameter77Value(final String parameter77Value) { this.parameter77Value = parameter77Value; return this; } + public SiprecCreator setParameter78Name(final String parameter78Name) { this.parameter78Name = parameter78Name; return this; } + public SiprecCreator setParameter78Value(final String parameter78Value) { this.parameter78Value = parameter78Value; return this; } + public SiprecCreator setParameter79Name(final String parameter79Name) { this.parameter79Name = parameter79Name; return this; } + public SiprecCreator setParameter79Value(final String parameter79Value) { this.parameter79Value = parameter79Value; return this; } + public SiprecCreator setParameter80Name(final String parameter80Name) { this.parameter80Name = parameter80Name; return this; } + public SiprecCreator setParameter80Value(final String parameter80Value) { this.parameter80Value = parameter80Value; return this; } + public SiprecCreator setParameter81Name(final String parameter81Name) { this.parameter81Name = parameter81Name; return this; } + public SiprecCreator setParameter81Value(final String parameter81Value) { this.parameter81Value = parameter81Value; return this; } + public SiprecCreator setParameter82Name(final String parameter82Name) { this.parameter82Name = parameter82Name; return this; } + public SiprecCreator setParameter82Value(final String parameter82Value) { this.parameter82Value = parameter82Value; return this; } + public SiprecCreator setParameter83Name(final String parameter83Name) { this.parameter83Name = parameter83Name; return this; } + public SiprecCreator setParameter83Value(final String parameter83Value) { this.parameter83Value = parameter83Value; return this; } + public SiprecCreator setParameter84Name(final String parameter84Name) { this.parameter84Name = parameter84Name; return this; } + public SiprecCreator setParameter84Value(final String parameter84Value) { this.parameter84Value = parameter84Value; return this; } + public SiprecCreator setParameter85Name(final String parameter85Name) { this.parameter85Name = parameter85Name; return this; } + public SiprecCreator setParameter85Value(final String parameter85Value) { this.parameter85Value = parameter85Value; return this; } + public SiprecCreator setParameter86Name(final String parameter86Name) { this.parameter86Name = parameter86Name; return this; } + public SiprecCreator setParameter86Value(final String parameter86Value) { this.parameter86Value = parameter86Value; return this; } + public SiprecCreator setParameter87Name(final String parameter87Name) { this.parameter87Name = parameter87Name; return this; } + public SiprecCreator setParameter87Value(final String parameter87Value) { this.parameter87Value = parameter87Value; return this; } + public SiprecCreator setParameter88Name(final String parameter88Name) { this.parameter88Name = parameter88Name; return this; } + public SiprecCreator setParameter88Value(final String parameter88Value) { this.parameter88Value = parameter88Value; return this; } + public SiprecCreator setParameter89Name(final String parameter89Name) { this.parameter89Name = parameter89Name; return this; } + public SiprecCreator setParameter89Value(final String parameter89Value) { this.parameter89Value = parameter89Value; return this; } + public SiprecCreator setParameter90Name(final String parameter90Name) { this.parameter90Name = parameter90Name; return this; } + public SiprecCreator setParameter90Value(final String parameter90Value) { this.parameter90Value = parameter90Value; return this; } + public SiprecCreator setParameter91Name(final String parameter91Name) { this.parameter91Name = parameter91Name; return this; } + public SiprecCreator setParameter91Value(final String parameter91Value) { this.parameter91Value = parameter91Value; return this; } + public SiprecCreator setParameter92Name(final String parameter92Name) { this.parameter92Name = parameter92Name; return this; } + public SiprecCreator setParameter92Value(final String parameter92Value) { this.parameter92Value = parameter92Value; return this; } + public SiprecCreator setParameter93Name(final String parameter93Name) { this.parameter93Name = parameter93Name; return this; } + public SiprecCreator setParameter93Value(final String parameter93Value) { this.parameter93Value = parameter93Value; return this; } + public SiprecCreator setParameter94Name(final String parameter94Name) { this.parameter94Name = parameter94Name; return this; } + public SiprecCreator setParameter94Value(final String parameter94Value) { this.parameter94Value = parameter94Value; return this; } + public SiprecCreator setParameter95Name(final String parameter95Name) { this.parameter95Name = parameter95Name; return this; } + public SiprecCreator setParameter95Value(final String parameter95Value) { this.parameter95Value = parameter95Value; return this; } + public SiprecCreator setParameter96Name(final String parameter96Name) { this.parameter96Name = parameter96Name; return this; } + public SiprecCreator setParameter96Value(final String parameter96Value) { this.parameter96Value = parameter96Value; return this; } + public SiprecCreator setParameter97Name(final String parameter97Name) { this.parameter97Name = parameter97Name; return this; } + public SiprecCreator setParameter97Value(final String parameter97Value) { this.parameter97Value = parameter97Value; return this; } + public SiprecCreator setParameter98Name(final String parameter98Name) { this.parameter98Name = parameter98Name; return this; } + public SiprecCreator setParameter98Value(final String parameter98Value) { this.parameter98Value = parameter98Value; return this; } + public SiprecCreator setParameter99Name(final String parameter99Name) { this.parameter99Name = parameter99Name; return this; } + public SiprecCreator setParameter99Value(final String parameter99Value) { this.parameter99Value = parameter99Value; return this; } + @Override public Siprec create(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/Calls/{CallSid}/Siprec.json"; - - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = path.replace("{" + "CallSid" + "}", this.pathCallSid.toString()); + + String path = "/2010-04-01/Accounts/{AccountSid}/Calls/{CallSid}/Siprec.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "CallSid" + "}", this.pathcallSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.API.toString(), - path + HttpMethod.POST, + Domains.API.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Siprec creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("Siprec creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -1315,617 +1503,1021 @@ public Siprec create(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (name != null) { - request.addPostParam("Name", name); + Serializer.toString(request, "Name", name, ParameterType.URLENCODED); } + + if (connectorName != null) { - request.addPostParam("ConnectorName", connectorName); + Serializer.toString(request, "ConnectorName", connectorName, ParameterType.URLENCODED); } + + if (track != null) { - request.addPostParam("Track", track.toString()); + Serializer.toString(request, "Track", track, ParameterType.URLENCODED); } + + if (statusCallback != null) { - request.addPostParam("StatusCallback", statusCallback.toString()); + Serializer.toString(request, "StatusCallback", statusCallback, ParameterType.URLENCODED); } + + if (statusCallbackMethod != null) { - request.addPostParam( - "StatusCallbackMethod", - statusCallbackMethod.toString() - ); + Serializer.toString(request, "StatusCallbackMethod", statusCallbackMethod, ParameterType.URLENCODED); } + + if (parameter1Name != null) { - request.addPostParam("Parameter1.Name", parameter1Name); + Serializer.toString(request, "Parameter1.Name", parameter1Name, ParameterType.URLENCODED); } + + if (parameter1Value != null) { - request.addPostParam("Parameter1.Value", parameter1Value); + Serializer.toString(request, "Parameter1.Value", parameter1Value, ParameterType.URLENCODED); } + + if (parameter2Name != null) { - request.addPostParam("Parameter2.Name", parameter2Name); + Serializer.toString(request, "Parameter2.Name", parameter2Name, ParameterType.URLENCODED); } + + if (parameter2Value != null) { - request.addPostParam("Parameter2.Value", parameter2Value); + Serializer.toString(request, "Parameter2.Value", parameter2Value, ParameterType.URLENCODED); } + + if (parameter3Name != null) { - request.addPostParam("Parameter3.Name", parameter3Name); + Serializer.toString(request, "Parameter3.Name", parameter3Name, ParameterType.URLENCODED); } + + if (parameter3Value != null) { - request.addPostParam("Parameter3.Value", parameter3Value); + Serializer.toString(request, "Parameter3.Value", parameter3Value, ParameterType.URLENCODED); } + + if (parameter4Name != null) { - request.addPostParam("Parameter4.Name", parameter4Name); + Serializer.toString(request, "Parameter4.Name", parameter4Name, ParameterType.URLENCODED); } + + if (parameter4Value != null) { - request.addPostParam("Parameter4.Value", parameter4Value); + Serializer.toString(request, "Parameter4.Value", parameter4Value, ParameterType.URLENCODED); } + + if (parameter5Name != null) { - request.addPostParam("Parameter5.Name", parameter5Name); + Serializer.toString(request, "Parameter5.Name", parameter5Name, ParameterType.URLENCODED); } + + if (parameter5Value != null) { - request.addPostParam("Parameter5.Value", parameter5Value); + Serializer.toString(request, "Parameter5.Value", parameter5Value, ParameterType.URLENCODED); } + + if (parameter6Name != null) { - request.addPostParam("Parameter6.Name", parameter6Name); + Serializer.toString(request, "Parameter6.Name", parameter6Name, ParameterType.URLENCODED); } + + if (parameter6Value != null) { - request.addPostParam("Parameter6.Value", parameter6Value); + Serializer.toString(request, "Parameter6.Value", parameter6Value, ParameterType.URLENCODED); } + + if (parameter7Name != null) { - request.addPostParam("Parameter7.Name", parameter7Name); + Serializer.toString(request, "Parameter7.Name", parameter7Name, ParameterType.URLENCODED); } + + if (parameter7Value != null) { - request.addPostParam("Parameter7.Value", parameter7Value); + Serializer.toString(request, "Parameter7.Value", parameter7Value, ParameterType.URLENCODED); } + + if (parameter8Name != null) { - request.addPostParam("Parameter8.Name", parameter8Name); + Serializer.toString(request, "Parameter8.Name", parameter8Name, ParameterType.URLENCODED); } + + if (parameter8Value != null) { - request.addPostParam("Parameter8.Value", parameter8Value); + Serializer.toString(request, "Parameter8.Value", parameter8Value, ParameterType.URLENCODED); } + + if (parameter9Name != null) { - request.addPostParam("Parameter9.Name", parameter9Name); + Serializer.toString(request, "Parameter9.Name", parameter9Name, ParameterType.URLENCODED); } + + if (parameter9Value != null) { - request.addPostParam("Parameter9.Value", parameter9Value); + Serializer.toString(request, "Parameter9.Value", parameter9Value, ParameterType.URLENCODED); } + + if (parameter10Name != null) { - request.addPostParam("Parameter10.Name", parameter10Name); + Serializer.toString(request, "Parameter10.Name", parameter10Name, ParameterType.URLENCODED); } + + if (parameter10Value != null) { - request.addPostParam("Parameter10.Value", parameter10Value); + Serializer.toString(request, "Parameter10.Value", parameter10Value, ParameterType.URLENCODED); } + + if (parameter11Name != null) { - request.addPostParam("Parameter11.Name", parameter11Name); + Serializer.toString(request, "Parameter11.Name", parameter11Name, ParameterType.URLENCODED); } + + if (parameter11Value != null) { - request.addPostParam("Parameter11.Value", parameter11Value); + Serializer.toString(request, "Parameter11.Value", parameter11Value, ParameterType.URLENCODED); } + + if (parameter12Name != null) { - request.addPostParam("Parameter12.Name", parameter12Name); + Serializer.toString(request, "Parameter12.Name", parameter12Name, ParameterType.URLENCODED); } + + if (parameter12Value != null) { - request.addPostParam("Parameter12.Value", parameter12Value); + Serializer.toString(request, "Parameter12.Value", parameter12Value, ParameterType.URLENCODED); } + + if (parameter13Name != null) { - request.addPostParam("Parameter13.Name", parameter13Name); + Serializer.toString(request, "Parameter13.Name", parameter13Name, ParameterType.URLENCODED); } + + if (parameter13Value != null) { - request.addPostParam("Parameter13.Value", parameter13Value); + Serializer.toString(request, "Parameter13.Value", parameter13Value, ParameterType.URLENCODED); } + + if (parameter14Name != null) { - request.addPostParam("Parameter14.Name", parameter14Name); + Serializer.toString(request, "Parameter14.Name", parameter14Name, ParameterType.URLENCODED); } + + if (parameter14Value != null) { - request.addPostParam("Parameter14.Value", parameter14Value); + Serializer.toString(request, "Parameter14.Value", parameter14Value, ParameterType.URLENCODED); } + + if (parameter15Name != null) { - request.addPostParam("Parameter15.Name", parameter15Name); + Serializer.toString(request, "Parameter15.Name", parameter15Name, ParameterType.URLENCODED); } + + if (parameter15Value != null) { - request.addPostParam("Parameter15.Value", parameter15Value); + Serializer.toString(request, "Parameter15.Value", parameter15Value, ParameterType.URLENCODED); } + + if (parameter16Name != null) { - request.addPostParam("Parameter16.Name", parameter16Name); + Serializer.toString(request, "Parameter16.Name", parameter16Name, ParameterType.URLENCODED); } + + if (parameter16Value != null) { - request.addPostParam("Parameter16.Value", parameter16Value); + Serializer.toString(request, "Parameter16.Value", parameter16Value, ParameterType.URLENCODED); } + + if (parameter17Name != null) { - request.addPostParam("Parameter17.Name", parameter17Name); + Serializer.toString(request, "Parameter17.Name", parameter17Name, ParameterType.URLENCODED); } + + if (parameter17Value != null) { - request.addPostParam("Parameter17.Value", parameter17Value); + Serializer.toString(request, "Parameter17.Value", parameter17Value, ParameterType.URLENCODED); } + + if (parameter18Name != null) { - request.addPostParam("Parameter18.Name", parameter18Name); + Serializer.toString(request, "Parameter18.Name", parameter18Name, ParameterType.URLENCODED); } + + if (parameter18Value != null) { - request.addPostParam("Parameter18.Value", parameter18Value); + Serializer.toString(request, "Parameter18.Value", parameter18Value, ParameterType.URLENCODED); } + + if (parameter19Name != null) { - request.addPostParam("Parameter19.Name", parameter19Name); + Serializer.toString(request, "Parameter19.Name", parameter19Name, ParameterType.URLENCODED); } + + if (parameter19Value != null) { - request.addPostParam("Parameter19.Value", parameter19Value); + Serializer.toString(request, "Parameter19.Value", parameter19Value, ParameterType.URLENCODED); } + + if (parameter20Name != null) { - request.addPostParam("Parameter20.Name", parameter20Name); + Serializer.toString(request, "Parameter20.Name", parameter20Name, ParameterType.URLENCODED); } + + if (parameter20Value != null) { - request.addPostParam("Parameter20.Value", parameter20Value); + Serializer.toString(request, "Parameter20.Value", parameter20Value, ParameterType.URLENCODED); } + + if (parameter21Name != null) { - request.addPostParam("Parameter21.Name", parameter21Name); + Serializer.toString(request, "Parameter21.Name", parameter21Name, ParameterType.URLENCODED); } + + if (parameter21Value != null) { - request.addPostParam("Parameter21.Value", parameter21Value); + Serializer.toString(request, "Parameter21.Value", parameter21Value, ParameterType.URLENCODED); } + + if (parameter22Name != null) { - request.addPostParam("Parameter22.Name", parameter22Name); + Serializer.toString(request, "Parameter22.Name", parameter22Name, ParameterType.URLENCODED); } + + if (parameter22Value != null) { - request.addPostParam("Parameter22.Value", parameter22Value); + Serializer.toString(request, "Parameter22.Value", parameter22Value, ParameterType.URLENCODED); } + + if (parameter23Name != null) { - request.addPostParam("Parameter23.Name", parameter23Name); + Serializer.toString(request, "Parameter23.Name", parameter23Name, ParameterType.URLENCODED); } + + if (parameter23Value != null) { - request.addPostParam("Parameter23.Value", parameter23Value); + Serializer.toString(request, "Parameter23.Value", parameter23Value, ParameterType.URLENCODED); } + + if (parameter24Name != null) { - request.addPostParam("Parameter24.Name", parameter24Name); + Serializer.toString(request, "Parameter24.Name", parameter24Name, ParameterType.URLENCODED); } + + if (parameter24Value != null) { - request.addPostParam("Parameter24.Value", parameter24Value); + Serializer.toString(request, "Parameter24.Value", parameter24Value, ParameterType.URLENCODED); } + + if (parameter25Name != null) { - request.addPostParam("Parameter25.Name", parameter25Name); + Serializer.toString(request, "Parameter25.Name", parameter25Name, ParameterType.URLENCODED); } + + if (parameter25Value != null) { - request.addPostParam("Parameter25.Value", parameter25Value); + Serializer.toString(request, "Parameter25.Value", parameter25Value, ParameterType.URLENCODED); } + + if (parameter26Name != null) { - request.addPostParam("Parameter26.Name", parameter26Name); + Serializer.toString(request, "Parameter26.Name", parameter26Name, ParameterType.URLENCODED); } + + if (parameter26Value != null) { - request.addPostParam("Parameter26.Value", parameter26Value); + Serializer.toString(request, "Parameter26.Value", parameter26Value, ParameterType.URLENCODED); } + + if (parameter27Name != null) { - request.addPostParam("Parameter27.Name", parameter27Name); + Serializer.toString(request, "Parameter27.Name", parameter27Name, ParameterType.URLENCODED); } + + if (parameter27Value != null) { - request.addPostParam("Parameter27.Value", parameter27Value); + Serializer.toString(request, "Parameter27.Value", parameter27Value, ParameterType.URLENCODED); } + + if (parameter28Name != null) { - request.addPostParam("Parameter28.Name", parameter28Name); + Serializer.toString(request, "Parameter28.Name", parameter28Name, ParameterType.URLENCODED); } + + if (parameter28Value != null) { - request.addPostParam("Parameter28.Value", parameter28Value); + Serializer.toString(request, "Parameter28.Value", parameter28Value, ParameterType.URLENCODED); } + + if (parameter29Name != null) { - request.addPostParam("Parameter29.Name", parameter29Name); + Serializer.toString(request, "Parameter29.Name", parameter29Name, ParameterType.URLENCODED); } + + if (parameter29Value != null) { - request.addPostParam("Parameter29.Value", parameter29Value); + Serializer.toString(request, "Parameter29.Value", parameter29Value, ParameterType.URLENCODED); } + + if (parameter30Name != null) { - request.addPostParam("Parameter30.Name", parameter30Name); + Serializer.toString(request, "Parameter30.Name", parameter30Name, ParameterType.URLENCODED); } + + if (parameter30Value != null) { - request.addPostParam("Parameter30.Value", parameter30Value); + Serializer.toString(request, "Parameter30.Value", parameter30Value, ParameterType.URLENCODED); } + + if (parameter31Name != null) { - request.addPostParam("Parameter31.Name", parameter31Name); + Serializer.toString(request, "Parameter31.Name", parameter31Name, ParameterType.URLENCODED); } + + if (parameter31Value != null) { - request.addPostParam("Parameter31.Value", parameter31Value); + Serializer.toString(request, "Parameter31.Value", parameter31Value, ParameterType.URLENCODED); } + + if (parameter32Name != null) { - request.addPostParam("Parameter32.Name", parameter32Name); + Serializer.toString(request, "Parameter32.Name", parameter32Name, ParameterType.URLENCODED); } + + if (parameter32Value != null) { - request.addPostParam("Parameter32.Value", parameter32Value); + Serializer.toString(request, "Parameter32.Value", parameter32Value, ParameterType.URLENCODED); } + + if (parameter33Name != null) { - request.addPostParam("Parameter33.Name", parameter33Name); + Serializer.toString(request, "Parameter33.Name", parameter33Name, ParameterType.URLENCODED); } + + if (parameter33Value != null) { - request.addPostParam("Parameter33.Value", parameter33Value); + Serializer.toString(request, "Parameter33.Value", parameter33Value, ParameterType.URLENCODED); } + + if (parameter34Name != null) { - request.addPostParam("Parameter34.Name", parameter34Name); + Serializer.toString(request, "Parameter34.Name", parameter34Name, ParameterType.URLENCODED); } + + if (parameter34Value != null) { - request.addPostParam("Parameter34.Value", parameter34Value); + Serializer.toString(request, "Parameter34.Value", parameter34Value, ParameterType.URLENCODED); } + + if (parameter35Name != null) { - request.addPostParam("Parameter35.Name", parameter35Name); + Serializer.toString(request, "Parameter35.Name", parameter35Name, ParameterType.URLENCODED); } + + if (parameter35Value != null) { - request.addPostParam("Parameter35.Value", parameter35Value); + Serializer.toString(request, "Parameter35.Value", parameter35Value, ParameterType.URLENCODED); } + + if (parameter36Name != null) { - request.addPostParam("Parameter36.Name", parameter36Name); + Serializer.toString(request, "Parameter36.Name", parameter36Name, ParameterType.URLENCODED); } + + if (parameter36Value != null) { - request.addPostParam("Parameter36.Value", parameter36Value); + Serializer.toString(request, "Parameter36.Value", parameter36Value, ParameterType.URLENCODED); } + + if (parameter37Name != null) { - request.addPostParam("Parameter37.Name", parameter37Name); + Serializer.toString(request, "Parameter37.Name", parameter37Name, ParameterType.URLENCODED); } + + if (parameter37Value != null) { - request.addPostParam("Parameter37.Value", parameter37Value); + Serializer.toString(request, "Parameter37.Value", parameter37Value, ParameterType.URLENCODED); } + + if (parameter38Name != null) { - request.addPostParam("Parameter38.Name", parameter38Name); + Serializer.toString(request, "Parameter38.Name", parameter38Name, ParameterType.URLENCODED); } + + if (parameter38Value != null) { - request.addPostParam("Parameter38.Value", parameter38Value); + Serializer.toString(request, "Parameter38.Value", parameter38Value, ParameterType.URLENCODED); } + + if (parameter39Name != null) { - request.addPostParam("Parameter39.Name", parameter39Name); + Serializer.toString(request, "Parameter39.Name", parameter39Name, ParameterType.URLENCODED); } + + if (parameter39Value != null) { - request.addPostParam("Parameter39.Value", parameter39Value); + Serializer.toString(request, "Parameter39.Value", parameter39Value, ParameterType.URLENCODED); } + + if (parameter40Name != null) { - request.addPostParam("Parameter40.Name", parameter40Name); + Serializer.toString(request, "Parameter40.Name", parameter40Name, ParameterType.URLENCODED); } + + if (parameter40Value != null) { - request.addPostParam("Parameter40.Value", parameter40Value); + Serializer.toString(request, "Parameter40.Value", parameter40Value, ParameterType.URLENCODED); } + + if (parameter41Name != null) { - request.addPostParam("Parameter41.Name", parameter41Name); + Serializer.toString(request, "Parameter41.Name", parameter41Name, ParameterType.URLENCODED); } + + if (parameter41Value != null) { - request.addPostParam("Parameter41.Value", parameter41Value); + Serializer.toString(request, "Parameter41.Value", parameter41Value, ParameterType.URLENCODED); } + + if (parameter42Name != null) { - request.addPostParam("Parameter42.Name", parameter42Name); + Serializer.toString(request, "Parameter42.Name", parameter42Name, ParameterType.URLENCODED); } + + if (parameter42Value != null) { - request.addPostParam("Parameter42.Value", parameter42Value); + Serializer.toString(request, "Parameter42.Value", parameter42Value, ParameterType.URLENCODED); } + + if (parameter43Name != null) { - request.addPostParam("Parameter43.Name", parameter43Name); + Serializer.toString(request, "Parameter43.Name", parameter43Name, ParameterType.URLENCODED); } + + if (parameter43Value != null) { - request.addPostParam("Parameter43.Value", parameter43Value); + Serializer.toString(request, "Parameter43.Value", parameter43Value, ParameterType.URLENCODED); } + + if (parameter44Name != null) { - request.addPostParam("Parameter44.Name", parameter44Name); + Serializer.toString(request, "Parameter44.Name", parameter44Name, ParameterType.URLENCODED); } + + if (parameter44Value != null) { - request.addPostParam("Parameter44.Value", parameter44Value); + Serializer.toString(request, "Parameter44.Value", parameter44Value, ParameterType.URLENCODED); } + + if (parameter45Name != null) { - request.addPostParam("Parameter45.Name", parameter45Name); + Serializer.toString(request, "Parameter45.Name", parameter45Name, ParameterType.URLENCODED); } + + if (parameter45Value != null) { - request.addPostParam("Parameter45.Value", parameter45Value); + Serializer.toString(request, "Parameter45.Value", parameter45Value, ParameterType.URLENCODED); } + + if (parameter46Name != null) { - request.addPostParam("Parameter46.Name", parameter46Name); + Serializer.toString(request, "Parameter46.Name", parameter46Name, ParameterType.URLENCODED); } + + if (parameter46Value != null) { - request.addPostParam("Parameter46.Value", parameter46Value); + Serializer.toString(request, "Parameter46.Value", parameter46Value, ParameterType.URLENCODED); } + + if (parameter47Name != null) { - request.addPostParam("Parameter47.Name", parameter47Name); + Serializer.toString(request, "Parameter47.Name", parameter47Name, ParameterType.URLENCODED); } + + if (parameter47Value != null) { - request.addPostParam("Parameter47.Value", parameter47Value); + Serializer.toString(request, "Parameter47.Value", parameter47Value, ParameterType.URLENCODED); } + + if (parameter48Name != null) { - request.addPostParam("Parameter48.Name", parameter48Name); + Serializer.toString(request, "Parameter48.Name", parameter48Name, ParameterType.URLENCODED); } + + if (parameter48Value != null) { - request.addPostParam("Parameter48.Value", parameter48Value); + Serializer.toString(request, "Parameter48.Value", parameter48Value, ParameterType.URLENCODED); } + + if (parameter49Name != null) { - request.addPostParam("Parameter49.Name", parameter49Name); + Serializer.toString(request, "Parameter49.Name", parameter49Name, ParameterType.URLENCODED); } + + if (parameter49Value != null) { - request.addPostParam("Parameter49.Value", parameter49Value); + Serializer.toString(request, "Parameter49.Value", parameter49Value, ParameterType.URLENCODED); } + + if (parameter50Name != null) { - request.addPostParam("Parameter50.Name", parameter50Name); + Serializer.toString(request, "Parameter50.Name", parameter50Name, ParameterType.URLENCODED); } + + if (parameter50Value != null) { - request.addPostParam("Parameter50.Value", parameter50Value); + Serializer.toString(request, "Parameter50.Value", parameter50Value, ParameterType.URLENCODED); } + + if (parameter51Name != null) { - request.addPostParam("Parameter51.Name", parameter51Name); + Serializer.toString(request, "Parameter51.Name", parameter51Name, ParameterType.URLENCODED); } + + if (parameter51Value != null) { - request.addPostParam("Parameter51.Value", parameter51Value); + Serializer.toString(request, "Parameter51.Value", parameter51Value, ParameterType.URLENCODED); } + + if (parameter52Name != null) { - request.addPostParam("Parameter52.Name", parameter52Name); + Serializer.toString(request, "Parameter52.Name", parameter52Name, ParameterType.URLENCODED); } + + if (parameter52Value != null) { - request.addPostParam("Parameter52.Value", parameter52Value); + Serializer.toString(request, "Parameter52.Value", parameter52Value, ParameterType.URLENCODED); } + + if (parameter53Name != null) { - request.addPostParam("Parameter53.Name", parameter53Name); + Serializer.toString(request, "Parameter53.Name", parameter53Name, ParameterType.URLENCODED); } + + if (parameter53Value != null) { - request.addPostParam("Parameter53.Value", parameter53Value); + Serializer.toString(request, "Parameter53.Value", parameter53Value, ParameterType.URLENCODED); } + + if (parameter54Name != null) { - request.addPostParam("Parameter54.Name", parameter54Name); + Serializer.toString(request, "Parameter54.Name", parameter54Name, ParameterType.URLENCODED); } + + if (parameter54Value != null) { - request.addPostParam("Parameter54.Value", parameter54Value); + Serializer.toString(request, "Parameter54.Value", parameter54Value, ParameterType.URLENCODED); } + + if (parameter55Name != null) { - request.addPostParam("Parameter55.Name", parameter55Name); + Serializer.toString(request, "Parameter55.Name", parameter55Name, ParameterType.URLENCODED); } + + if (parameter55Value != null) { - request.addPostParam("Parameter55.Value", parameter55Value); + Serializer.toString(request, "Parameter55.Value", parameter55Value, ParameterType.URLENCODED); } + + if (parameter56Name != null) { - request.addPostParam("Parameter56.Name", parameter56Name); + Serializer.toString(request, "Parameter56.Name", parameter56Name, ParameterType.URLENCODED); } + + if (parameter56Value != null) { - request.addPostParam("Parameter56.Value", parameter56Value); + Serializer.toString(request, "Parameter56.Value", parameter56Value, ParameterType.URLENCODED); } + + if (parameter57Name != null) { - request.addPostParam("Parameter57.Name", parameter57Name); + Serializer.toString(request, "Parameter57.Name", parameter57Name, ParameterType.URLENCODED); } + + if (parameter57Value != null) { - request.addPostParam("Parameter57.Value", parameter57Value); + Serializer.toString(request, "Parameter57.Value", parameter57Value, ParameterType.URLENCODED); } + + if (parameter58Name != null) { - request.addPostParam("Parameter58.Name", parameter58Name); + Serializer.toString(request, "Parameter58.Name", parameter58Name, ParameterType.URLENCODED); } + + if (parameter58Value != null) { - request.addPostParam("Parameter58.Value", parameter58Value); + Serializer.toString(request, "Parameter58.Value", parameter58Value, ParameterType.URLENCODED); } + + if (parameter59Name != null) { - request.addPostParam("Parameter59.Name", parameter59Name); + Serializer.toString(request, "Parameter59.Name", parameter59Name, ParameterType.URLENCODED); } + + if (parameter59Value != null) { - request.addPostParam("Parameter59.Value", parameter59Value); + Serializer.toString(request, "Parameter59.Value", parameter59Value, ParameterType.URLENCODED); } + + if (parameter60Name != null) { - request.addPostParam("Parameter60.Name", parameter60Name); + Serializer.toString(request, "Parameter60.Name", parameter60Name, ParameterType.URLENCODED); } + + if (parameter60Value != null) { - request.addPostParam("Parameter60.Value", parameter60Value); + Serializer.toString(request, "Parameter60.Value", parameter60Value, ParameterType.URLENCODED); } + + if (parameter61Name != null) { - request.addPostParam("Parameter61.Name", parameter61Name); + Serializer.toString(request, "Parameter61.Name", parameter61Name, ParameterType.URLENCODED); } + + if (parameter61Value != null) { - request.addPostParam("Parameter61.Value", parameter61Value); + Serializer.toString(request, "Parameter61.Value", parameter61Value, ParameterType.URLENCODED); } + + if (parameter62Name != null) { - request.addPostParam("Parameter62.Name", parameter62Name); + Serializer.toString(request, "Parameter62.Name", parameter62Name, ParameterType.URLENCODED); } + + if (parameter62Value != null) { - request.addPostParam("Parameter62.Value", parameter62Value); + Serializer.toString(request, "Parameter62.Value", parameter62Value, ParameterType.URLENCODED); } + + if (parameter63Name != null) { - request.addPostParam("Parameter63.Name", parameter63Name); + Serializer.toString(request, "Parameter63.Name", parameter63Name, ParameterType.URLENCODED); } + + if (parameter63Value != null) { - request.addPostParam("Parameter63.Value", parameter63Value); + Serializer.toString(request, "Parameter63.Value", parameter63Value, ParameterType.URLENCODED); } + + if (parameter64Name != null) { - request.addPostParam("Parameter64.Name", parameter64Name); + Serializer.toString(request, "Parameter64.Name", parameter64Name, ParameterType.URLENCODED); } + + if (parameter64Value != null) { - request.addPostParam("Parameter64.Value", parameter64Value); + Serializer.toString(request, "Parameter64.Value", parameter64Value, ParameterType.URLENCODED); } + + if (parameter65Name != null) { - request.addPostParam("Parameter65.Name", parameter65Name); + Serializer.toString(request, "Parameter65.Name", parameter65Name, ParameterType.URLENCODED); } + + if (parameter65Value != null) { - request.addPostParam("Parameter65.Value", parameter65Value); + Serializer.toString(request, "Parameter65.Value", parameter65Value, ParameterType.URLENCODED); } + + if (parameter66Name != null) { - request.addPostParam("Parameter66.Name", parameter66Name); + Serializer.toString(request, "Parameter66.Name", parameter66Name, ParameterType.URLENCODED); } + + if (parameter66Value != null) { - request.addPostParam("Parameter66.Value", parameter66Value); + Serializer.toString(request, "Parameter66.Value", parameter66Value, ParameterType.URLENCODED); } + + if (parameter67Name != null) { - request.addPostParam("Parameter67.Name", parameter67Name); + Serializer.toString(request, "Parameter67.Name", parameter67Name, ParameterType.URLENCODED); } + + if (parameter67Value != null) { - request.addPostParam("Parameter67.Value", parameter67Value); + Serializer.toString(request, "Parameter67.Value", parameter67Value, ParameterType.URLENCODED); } + + if (parameter68Name != null) { - request.addPostParam("Parameter68.Name", parameter68Name); + Serializer.toString(request, "Parameter68.Name", parameter68Name, ParameterType.URLENCODED); } + + if (parameter68Value != null) { - request.addPostParam("Parameter68.Value", parameter68Value); + Serializer.toString(request, "Parameter68.Value", parameter68Value, ParameterType.URLENCODED); } + + if (parameter69Name != null) { - request.addPostParam("Parameter69.Name", parameter69Name); + Serializer.toString(request, "Parameter69.Name", parameter69Name, ParameterType.URLENCODED); } + + if (parameter69Value != null) { - request.addPostParam("Parameter69.Value", parameter69Value); + Serializer.toString(request, "Parameter69.Value", parameter69Value, ParameterType.URLENCODED); } + + if (parameter70Name != null) { - request.addPostParam("Parameter70.Name", parameter70Name); + Serializer.toString(request, "Parameter70.Name", parameter70Name, ParameterType.URLENCODED); } + + if (parameter70Value != null) { - request.addPostParam("Parameter70.Value", parameter70Value); + Serializer.toString(request, "Parameter70.Value", parameter70Value, ParameterType.URLENCODED); } + + if (parameter71Name != null) { - request.addPostParam("Parameter71.Name", parameter71Name); + Serializer.toString(request, "Parameter71.Name", parameter71Name, ParameterType.URLENCODED); } + + if (parameter71Value != null) { - request.addPostParam("Parameter71.Value", parameter71Value); + Serializer.toString(request, "Parameter71.Value", parameter71Value, ParameterType.URLENCODED); } + + if (parameter72Name != null) { - request.addPostParam("Parameter72.Name", parameter72Name); + Serializer.toString(request, "Parameter72.Name", parameter72Name, ParameterType.URLENCODED); } + + if (parameter72Value != null) { - request.addPostParam("Parameter72.Value", parameter72Value); + Serializer.toString(request, "Parameter72.Value", parameter72Value, ParameterType.URLENCODED); } + + if (parameter73Name != null) { - request.addPostParam("Parameter73.Name", parameter73Name); + Serializer.toString(request, "Parameter73.Name", parameter73Name, ParameterType.URLENCODED); } + + if (parameter73Value != null) { - request.addPostParam("Parameter73.Value", parameter73Value); + Serializer.toString(request, "Parameter73.Value", parameter73Value, ParameterType.URLENCODED); } + + if (parameter74Name != null) { - request.addPostParam("Parameter74.Name", parameter74Name); + Serializer.toString(request, "Parameter74.Name", parameter74Name, ParameterType.URLENCODED); } + + if (parameter74Value != null) { - request.addPostParam("Parameter74.Value", parameter74Value); + Serializer.toString(request, "Parameter74.Value", parameter74Value, ParameterType.URLENCODED); } + + if (parameter75Name != null) { - request.addPostParam("Parameter75.Name", parameter75Name); + Serializer.toString(request, "Parameter75.Name", parameter75Name, ParameterType.URLENCODED); } + + if (parameter75Value != null) { - request.addPostParam("Parameter75.Value", parameter75Value); + Serializer.toString(request, "Parameter75.Value", parameter75Value, ParameterType.URLENCODED); } + + if (parameter76Name != null) { - request.addPostParam("Parameter76.Name", parameter76Name); + Serializer.toString(request, "Parameter76.Name", parameter76Name, ParameterType.URLENCODED); } + + if (parameter76Value != null) { - request.addPostParam("Parameter76.Value", parameter76Value); + Serializer.toString(request, "Parameter76.Value", parameter76Value, ParameterType.URLENCODED); } + + if (parameter77Name != null) { - request.addPostParam("Parameter77.Name", parameter77Name); + Serializer.toString(request, "Parameter77.Name", parameter77Name, ParameterType.URLENCODED); } + + if (parameter77Value != null) { - request.addPostParam("Parameter77.Value", parameter77Value); + Serializer.toString(request, "Parameter77.Value", parameter77Value, ParameterType.URLENCODED); } + + if (parameter78Name != null) { - request.addPostParam("Parameter78.Name", parameter78Name); + Serializer.toString(request, "Parameter78.Name", parameter78Name, ParameterType.URLENCODED); } + + if (parameter78Value != null) { - request.addPostParam("Parameter78.Value", parameter78Value); + Serializer.toString(request, "Parameter78.Value", parameter78Value, ParameterType.URLENCODED); } + + if (parameter79Name != null) { - request.addPostParam("Parameter79.Name", parameter79Name); + Serializer.toString(request, "Parameter79.Name", parameter79Name, ParameterType.URLENCODED); } + + if (parameter79Value != null) { - request.addPostParam("Parameter79.Value", parameter79Value); + Serializer.toString(request, "Parameter79.Value", parameter79Value, ParameterType.URLENCODED); } + + if (parameter80Name != null) { - request.addPostParam("Parameter80.Name", parameter80Name); + Serializer.toString(request, "Parameter80.Name", parameter80Name, ParameterType.URLENCODED); } + + if (parameter80Value != null) { - request.addPostParam("Parameter80.Value", parameter80Value); + Serializer.toString(request, "Parameter80.Value", parameter80Value, ParameterType.URLENCODED); } + + if (parameter81Name != null) { - request.addPostParam("Parameter81.Name", parameter81Name); + Serializer.toString(request, "Parameter81.Name", parameter81Name, ParameterType.URLENCODED); } + + if (parameter81Value != null) { - request.addPostParam("Parameter81.Value", parameter81Value); + Serializer.toString(request, "Parameter81.Value", parameter81Value, ParameterType.URLENCODED); } + + if (parameter82Name != null) { - request.addPostParam("Parameter82.Name", parameter82Name); + Serializer.toString(request, "Parameter82.Name", parameter82Name, ParameterType.URLENCODED); } + + if (parameter82Value != null) { - request.addPostParam("Parameter82.Value", parameter82Value); + Serializer.toString(request, "Parameter82.Value", parameter82Value, ParameterType.URLENCODED); } + + if (parameter83Name != null) { - request.addPostParam("Parameter83.Name", parameter83Name); + Serializer.toString(request, "Parameter83.Name", parameter83Name, ParameterType.URLENCODED); } + + if (parameter83Value != null) { - request.addPostParam("Parameter83.Value", parameter83Value); + Serializer.toString(request, "Parameter83.Value", parameter83Value, ParameterType.URLENCODED); } + + if (parameter84Name != null) { - request.addPostParam("Parameter84.Name", parameter84Name); + Serializer.toString(request, "Parameter84.Name", parameter84Name, ParameterType.URLENCODED); } + + if (parameter84Value != null) { - request.addPostParam("Parameter84.Value", parameter84Value); + Serializer.toString(request, "Parameter84.Value", parameter84Value, ParameterType.URLENCODED); } + + if (parameter85Name != null) { - request.addPostParam("Parameter85.Name", parameter85Name); + Serializer.toString(request, "Parameter85.Name", parameter85Name, ParameterType.URLENCODED); } + + if (parameter85Value != null) { - request.addPostParam("Parameter85.Value", parameter85Value); + Serializer.toString(request, "Parameter85.Value", parameter85Value, ParameterType.URLENCODED); } + + if (parameter86Name != null) { - request.addPostParam("Parameter86.Name", parameter86Name); + Serializer.toString(request, "Parameter86.Name", parameter86Name, ParameterType.URLENCODED); } + + if (parameter86Value != null) { - request.addPostParam("Parameter86.Value", parameter86Value); + Serializer.toString(request, "Parameter86.Value", parameter86Value, ParameterType.URLENCODED); } + + if (parameter87Name != null) { - request.addPostParam("Parameter87.Name", parameter87Name); + Serializer.toString(request, "Parameter87.Name", parameter87Name, ParameterType.URLENCODED); } + + if (parameter87Value != null) { - request.addPostParam("Parameter87.Value", parameter87Value); + Serializer.toString(request, "Parameter87.Value", parameter87Value, ParameterType.URLENCODED); } + + if (parameter88Name != null) { - request.addPostParam("Parameter88.Name", parameter88Name); + Serializer.toString(request, "Parameter88.Name", parameter88Name, ParameterType.URLENCODED); } + + if (parameter88Value != null) { - request.addPostParam("Parameter88.Value", parameter88Value); + Serializer.toString(request, "Parameter88.Value", parameter88Value, ParameterType.URLENCODED); } + + if (parameter89Name != null) { - request.addPostParam("Parameter89.Name", parameter89Name); + Serializer.toString(request, "Parameter89.Name", parameter89Name, ParameterType.URLENCODED); } + + if (parameter89Value != null) { - request.addPostParam("Parameter89.Value", parameter89Value); + Serializer.toString(request, "Parameter89.Value", parameter89Value, ParameterType.URLENCODED); } + + if (parameter90Name != null) { - request.addPostParam("Parameter90.Name", parameter90Name); + Serializer.toString(request, "Parameter90.Name", parameter90Name, ParameterType.URLENCODED); } + + if (parameter90Value != null) { - request.addPostParam("Parameter90.Value", parameter90Value); + Serializer.toString(request, "Parameter90.Value", parameter90Value, ParameterType.URLENCODED); } + + if (parameter91Name != null) { - request.addPostParam("Parameter91.Name", parameter91Name); + Serializer.toString(request, "Parameter91.Name", parameter91Name, ParameterType.URLENCODED); } + + if (parameter91Value != null) { - request.addPostParam("Parameter91.Value", parameter91Value); + Serializer.toString(request, "Parameter91.Value", parameter91Value, ParameterType.URLENCODED); } + + if (parameter92Name != null) { - request.addPostParam("Parameter92.Name", parameter92Name); + Serializer.toString(request, "Parameter92.Name", parameter92Name, ParameterType.URLENCODED); } + + if (parameter92Value != null) { - request.addPostParam("Parameter92.Value", parameter92Value); + Serializer.toString(request, "Parameter92.Value", parameter92Value, ParameterType.URLENCODED); } + + if (parameter93Name != null) { - request.addPostParam("Parameter93.Name", parameter93Name); + Serializer.toString(request, "Parameter93.Name", parameter93Name, ParameterType.URLENCODED); } + + if (parameter93Value != null) { - request.addPostParam("Parameter93.Value", parameter93Value); + Serializer.toString(request, "Parameter93.Value", parameter93Value, ParameterType.URLENCODED); } + + if (parameter94Name != null) { - request.addPostParam("Parameter94.Name", parameter94Name); + Serializer.toString(request, "Parameter94.Name", parameter94Name, ParameterType.URLENCODED); } + + if (parameter94Value != null) { - request.addPostParam("Parameter94.Value", parameter94Value); + Serializer.toString(request, "Parameter94.Value", parameter94Value, ParameterType.URLENCODED); } + + if (parameter95Name != null) { - request.addPostParam("Parameter95.Name", parameter95Name); + Serializer.toString(request, "Parameter95.Name", parameter95Name, ParameterType.URLENCODED); } + + if (parameter95Value != null) { - request.addPostParam("Parameter95.Value", parameter95Value); + Serializer.toString(request, "Parameter95.Value", parameter95Value, ParameterType.URLENCODED); } + + if (parameter96Name != null) { - request.addPostParam("Parameter96.Name", parameter96Name); + Serializer.toString(request, "Parameter96.Name", parameter96Name, ParameterType.URLENCODED); } + + if (parameter96Value != null) { - request.addPostParam("Parameter96.Value", parameter96Value); + Serializer.toString(request, "Parameter96.Value", parameter96Value, ParameterType.URLENCODED); } + + if (parameter97Name != null) { - request.addPostParam("Parameter97.Name", parameter97Name); + Serializer.toString(request, "Parameter97.Name", parameter97Name, ParameterType.URLENCODED); } + + if (parameter97Value != null) { - request.addPostParam("Parameter97.Value", parameter97Value); + Serializer.toString(request, "Parameter97.Value", parameter97Value, ParameterType.URLENCODED); } + + if (parameter98Name != null) { - request.addPostParam("Parameter98.Name", parameter98Name); + Serializer.toString(request, "Parameter98.Name", parameter98Name, ParameterType.URLENCODED); } + + if (parameter98Value != null) { - request.addPostParam("Parameter98.Value", parameter98Value); + Serializer.toString(request, "Parameter98.Value", parameter98Value, ParameterType.URLENCODED); } + + if (parameter99Name != null) { - request.addPostParam("Parameter99.Name", parameter99Name); + Serializer.toString(request, "Parameter99.Name", parameter99Name, ParameterType.URLENCODED); } + + if (parameter99Value != null) { - request.addPostParam("Parameter99.Value", parameter99Value); + Serializer.toString(request, "Parameter99.Value", parameter99Value, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/call/SiprecUpdater.java b/src/main/java/com/twilio/rest/api/v2010/account/call/SiprecUpdater.java index 955e8d0b4a..e1aec8d849 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/call/SiprecUpdater.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/call/SiprecUpdater.java @@ -16,6 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -26,79 +28,61 @@ import com.twilio.rest.Domains; public class SiprecUpdater extends Updater { - - private String pathCallSid; - private String pathSid; + private String pathaccountSid; + private String pathcallSid; + private String pathsid; private Siprec.UpdateStatus status; - private String pathAccountSid; - - public SiprecUpdater( - final String pathCallSid, - final String pathSid, - final Siprec.UpdateStatus status - ) { - this.pathCallSid = pathCallSid; - this.pathSid = pathSid; + + public SiprecUpdater(final String pathcallSid, final String pathsid, final Siprec.UpdateStatus status) { + this.pathcallSid = pathcallSid; + this.pathsid = pathsid; this.status = status; } - public SiprecUpdater( - final String pathAccountSid, - final String pathCallSid, - final String pathSid, - final Siprec.UpdateStatus status - ) { - this.pathAccountSid = pathAccountSid; - this.pathCallSid = pathCallSid; - this.pathSid = pathSid; + public SiprecUpdater(final String pathaccountSid, final String pathcallSid, final String pathsid, final Siprec.UpdateStatus status) { + this.pathaccountSid = pathaccountSid; + this.pathcallSid = pathcallSid; + this.pathsid = pathsid; this.status = status; } + public SiprecUpdater setStatus(final Siprec.UpdateStatus status) { this.status = status; return this; } + @Override public Siprec update(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/Calls/{CallSid}/Siprec/{Sid}.json"; - - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = path.replace("{" + "CallSid" + "}", this.pathCallSid.toString()); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); - path = path.replace("{" + "Status" + "}", this.status.toString()); + + String path = "/2010-04-01/Accounts/{AccountSid}/Calls/{CallSid}/Siprec/{Sid}.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "CallSid" + "}", this.pathcallSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.API.toString(), - path + HttpMethod.POST, + Domains.API.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Siprec update failed: Unable to connect to server" - ); + throw new ApiConnectionException("Siprec update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -107,8 +91,11 @@ public Siprec update(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (status != null) { - request.addPostParam("Status", status.toString()); + Serializer.toString(request, "Status", status, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/call/Stream.java b/src/main/java/com/twilio/rest/api/v2010/account/call/Stream.java index c646360c75..2fe726bee0 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/call/Stream.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/call/Stream.java @@ -18,70 +18,125 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Stream extends Resource { - private static final long serialVersionUID = 189203494840345L; - public static StreamCreator creator( - final String pathCallSid, - final URI url - ) { - return new StreamCreator(pathCallSid, url); + public static StreamCreator creator(final String pathcallSid, final URI url) { + return new StreamCreator( + pathcallSid, url + ); } - public static StreamCreator creator( - final String pathAccountSid, - final String pathCallSid, - final URI url - ) { - return new StreamCreator(pathAccountSid, pathCallSid, url); + + public static StreamCreator creator(final String pathaccountSid, final String pathcallSid, final URI url) { + return new StreamCreator( + pathaccountSid, pathcallSid, url + ); } - public static StreamUpdater updater( - final String pathCallSid, - final String pathSid, - final Stream.UpdateStatus status - ) { - return new StreamUpdater(pathCallSid, pathSid, status); + + public static StreamUpdater updater(final String pathcallSid, final String pathsid, final Stream.UpdateStatus status) { + return new StreamUpdater( + pathcallSid, pathsid, status + ); } - public static StreamUpdater updater( - final String pathAccountSid, - final String pathCallSid, - final String pathSid, - final Stream.UpdateStatus status - ) { - return new StreamUpdater(pathAccountSid, pathCallSid, pathSid, status); + + public static StreamUpdater updater(final String pathaccountSid, final String pathcallSid, final String pathsid, final Stream.UpdateStatus status) { + return new StreamUpdater( + pathaccountSid, pathcallSid, pathsid, status + ); + } + + + public enum Status { + IN_PROGRESS("in-progress"), + STOPPED("stopped"); + + private final String value; + + private Status(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static Status forValue(final String value) { + return Promoter.enumFromString(value, Status.values()); + } + } + + public enum UpdateStatus { + STOPPED("stopped"); + + private final String value; + + private UpdateStatus(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static UpdateStatus forValue(final String value) { + return Promoter.enumFromString(value, UpdateStatus.values()); + } + } + + public enum Track { + INBOUND_TRACK("inbound_track"), + OUTBOUND_TRACK("outbound_track"), + BOTH_TRACKS("both_tracks"); + + private final String value; + + private Track(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static Track forValue(final String value) { + return Promoter.enumFromString(value, Track.values()); + } } + /** * Converts a JSON String into a Stream object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Stream object represented by the provided JSON */ - public static Stream fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Stream fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Stream.class); @@ -96,14 +151,11 @@ public static Stream fromJson( * Converts a JSON InputStream into a Stream object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Stream object represented by the provided JSON */ - public static Stream fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Stream fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Stream.class); @@ -114,61 +166,54 @@ public static Stream fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; + @Getter private final String callSid; + @Getter + private final ZonedDateTime dateUpdated; + @Getter private final String name; + @Getter + private final String sid; + @Getter private final Stream.Status status; - private final ZonedDateTime dateUpdated; + @Getter private final String uri; @JsonCreator private Stream( - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("call_sid") final String callSid, - @JsonProperty("name") final String name, - @JsonProperty("status") final Stream.Status status, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("uri") final String uri + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("call_sid") final String callSid, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.RFC2822Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("name") final String name, + @JsonProperty("sid") final String sid, + @JsonProperty("status") final Stream.Status status, + @JsonProperty("uri") final String uri ) { - this.sid = sid; this.accountSid = accountSid; this.callSid = callSid; + this.dateUpdated = dateUpdated; this.name = name; + this.sid = sid; this.status = status; - this.dateUpdated = DateConverter.rfc2822DateTimeFromString(dateUpdated); this.uri = uri; } - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getCallSid() { - return this.callSid; - } - - public final String getName() { - return this.name; - } - - public final Stream.Status getStatus() { - return this.status; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final String getUri() { - return this.uri; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -180,88 +225,30 @@ public boolean equals(final Object o) { } Stream other = (Stream) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(callSid, other.callSid) && - Objects.equals(name, other.name) && - Objects.equals(status, other.status) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(uri, other.uri) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(callSid, other.callSid) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(name, other.name) && + Objects.equals(sid, other.sid) && + Objects.equals(status, other.status) && + Objects.equals(uri, other.uri) ); } @Override public int hashCode() { return Objects.hash( - sid, - accountSid, - callSid, - name, - status, - dateUpdated, - uri + accountSid, + callSid, + dateUpdated, + name, + sid, + status, + uri ); } - public enum UpdateStatus { - STOPPED("stopped"); - - private final String value; - - private UpdateStatus(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static UpdateStatus forValue(final String value) { - return Promoter.enumFromString(value, UpdateStatus.values()); - } - } - - public enum Status { - IN_PROGRESS("in-progress"), - STOPPED("stopped"); - - private final String value; - - private Status(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static Status forValue(final String value) { - return Promoter.enumFromString(value, Status.values()); - } - } - - public enum Track { - INBOUND_TRACK("inbound_track"), - OUTBOUND_TRACK("outbound_track"), - BOTH_TRACKS("both_tracks"); - - private final String value; - - private Track(final String value) { - this.value = value; - } - public String toString() { - return value; - } - - @JsonCreator - public static Track forValue(final String value) { - return Promoter.enumFromString(value, Track.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/api/v2010/account/call/StreamCreator.java b/src/main/java/com/twilio/rest/api/v2010/account/call/StreamCreator.java index 654c9f7797..83d1c21157 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/call/StreamCreator.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/call/StreamCreator.java @@ -14,9 +14,11 @@ package com.twilio.rest.api.v2010.account.call; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; -import com.twilio.converter.Promoter; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,14 +27,14 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -import java.net.URI; + import java.net.URI; public class StreamCreator extends Creator { - private String pathCallSid; + private String pathaccountSid; + private String pathcallSid; private URI url; - private String pathAccountSid; private String name; private Stream.Track track; private URI statusCallback; @@ -236,1085 +238,1265 @@ public class StreamCreator extends Creator { private String parameter99Name; private String parameter99Value; - public StreamCreator(final String pathCallSid, final URI url) { - this.pathCallSid = pathCallSid; + public StreamCreator(final String pathcallSid, final URI url) { + this.pathcallSid = pathcallSid; this.url = url; } - public StreamCreator( - final String pathAccountSid, - final String pathCallSid, - final URI url - ) { - this.pathAccountSid = pathAccountSid; - this.pathCallSid = pathCallSid; + public StreamCreator(final String pathaccountSid, final String pathcallSid, final URI url) { + this.pathaccountSid = pathaccountSid; + this.pathcallSid = pathcallSid; this.url = url; } + public StreamCreator setUrl(final URI url) { this.url = url; return this; } - public StreamCreator setUrl(final String url) { - return setUrl(Promoter.uriFromString(url)); - } public StreamCreator setName(final String name) { this.name = name; return this; } + public StreamCreator setTrack(final Stream.Track track) { this.track = track; return this; } + public StreamCreator setStatusCallback(final URI statusCallback) { this.statusCallback = statusCallback; return this; } - public StreamCreator setStatusCallback(final String statusCallback) { - return setStatusCallback(Promoter.uriFromString(statusCallback)); - } - public StreamCreator setStatusCallbackMethod( - final HttpMethod statusCallbackMethod - ) { + public StreamCreator setStatusCallbackMethod(final HttpMethod statusCallbackMethod) { this.statusCallbackMethod = statusCallbackMethod; return this; } + public StreamCreator setParameter1Name(final String parameter1Name) { this.parameter1Name = parameter1Name; return this; } + public StreamCreator setParameter1Value(final String parameter1Value) { this.parameter1Value = parameter1Value; return this; } + public StreamCreator setParameter2Name(final String parameter2Name) { this.parameter2Name = parameter2Name; return this; } + public StreamCreator setParameter2Value(final String parameter2Value) { this.parameter2Value = parameter2Value; return this; } + public StreamCreator setParameter3Name(final String parameter3Name) { this.parameter3Name = parameter3Name; return this; } + public StreamCreator setParameter3Value(final String parameter3Value) { this.parameter3Value = parameter3Value; return this; } + public StreamCreator setParameter4Name(final String parameter4Name) { this.parameter4Name = parameter4Name; return this; } + public StreamCreator setParameter4Value(final String parameter4Value) { this.parameter4Value = parameter4Value; return this; } + public StreamCreator setParameter5Name(final String parameter5Name) { this.parameter5Name = parameter5Name; return this; } + public StreamCreator setParameter5Value(final String parameter5Value) { this.parameter5Value = parameter5Value; return this; } + public StreamCreator setParameter6Name(final String parameter6Name) { this.parameter6Name = parameter6Name; return this; } + public StreamCreator setParameter6Value(final String parameter6Value) { this.parameter6Value = parameter6Value; return this; } + public StreamCreator setParameter7Name(final String parameter7Name) { this.parameter7Name = parameter7Name; return this; } + public StreamCreator setParameter7Value(final String parameter7Value) { this.parameter7Value = parameter7Value; return this; } + public StreamCreator setParameter8Name(final String parameter8Name) { this.parameter8Name = parameter8Name; return this; } + public StreamCreator setParameter8Value(final String parameter8Value) { this.parameter8Value = parameter8Value; return this; } + public StreamCreator setParameter9Name(final String parameter9Name) { this.parameter9Name = parameter9Name; return this; } + public StreamCreator setParameter9Value(final String parameter9Value) { this.parameter9Value = parameter9Value; return this; } + public StreamCreator setParameter10Name(final String parameter10Name) { this.parameter10Name = parameter10Name; return this; } + public StreamCreator setParameter10Value(final String parameter10Value) { this.parameter10Value = parameter10Value; return this; } + public StreamCreator setParameter11Name(final String parameter11Name) { this.parameter11Name = parameter11Name; return this; } + public StreamCreator setParameter11Value(final String parameter11Value) { this.parameter11Value = parameter11Value; return this; } + public StreamCreator setParameter12Name(final String parameter12Name) { this.parameter12Name = parameter12Name; return this; } + public StreamCreator setParameter12Value(final String parameter12Value) { this.parameter12Value = parameter12Value; return this; } + public StreamCreator setParameter13Name(final String parameter13Name) { this.parameter13Name = parameter13Name; return this; } + public StreamCreator setParameter13Value(final String parameter13Value) { this.parameter13Value = parameter13Value; return this; } + public StreamCreator setParameter14Name(final String parameter14Name) { this.parameter14Name = parameter14Name; return this; } + public StreamCreator setParameter14Value(final String parameter14Value) { this.parameter14Value = parameter14Value; return this; } + public StreamCreator setParameter15Name(final String parameter15Name) { this.parameter15Name = parameter15Name; return this; } + public StreamCreator setParameter15Value(final String parameter15Value) { this.parameter15Value = parameter15Value; return this; } + public StreamCreator setParameter16Name(final String parameter16Name) { this.parameter16Name = parameter16Name; return this; } + public StreamCreator setParameter16Value(final String parameter16Value) { this.parameter16Value = parameter16Value; return this; } + public StreamCreator setParameter17Name(final String parameter17Name) { this.parameter17Name = parameter17Name; return this; } + public StreamCreator setParameter17Value(final String parameter17Value) { this.parameter17Value = parameter17Value; return this; } + public StreamCreator setParameter18Name(final String parameter18Name) { this.parameter18Name = parameter18Name; return this; } + public StreamCreator setParameter18Value(final String parameter18Value) { this.parameter18Value = parameter18Value; return this; } + public StreamCreator setParameter19Name(final String parameter19Name) { this.parameter19Name = parameter19Name; return this; } + public StreamCreator setParameter19Value(final String parameter19Value) { this.parameter19Value = parameter19Value; return this; } + public StreamCreator setParameter20Name(final String parameter20Name) { this.parameter20Name = parameter20Name; return this; } + public StreamCreator setParameter20Value(final String parameter20Value) { this.parameter20Value = parameter20Value; return this; } + public StreamCreator setParameter21Name(final String parameter21Name) { this.parameter21Name = parameter21Name; return this; } + public StreamCreator setParameter21Value(final String parameter21Value) { this.parameter21Value = parameter21Value; return this; } + public StreamCreator setParameter22Name(final String parameter22Name) { this.parameter22Name = parameter22Name; return this; } + public StreamCreator setParameter22Value(final String parameter22Value) { this.parameter22Value = parameter22Value; return this; } + public StreamCreator setParameter23Name(final String parameter23Name) { this.parameter23Name = parameter23Name; return this; } + public StreamCreator setParameter23Value(final String parameter23Value) { this.parameter23Value = parameter23Value; return this; } + public StreamCreator setParameter24Name(final String parameter24Name) { this.parameter24Name = parameter24Name; return this; } + public StreamCreator setParameter24Value(final String parameter24Value) { this.parameter24Value = parameter24Value; return this; } + public StreamCreator setParameter25Name(final String parameter25Name) { this.parameter25Name = parameter25Name; return this; } + public StreamCreator setParameter25Value(final String parameter25Value) { this.parameter25Value = parameter25Value; return this; } + public StreamCreator setParameter26Name(final String parameter26Name) { this.parameter26Name = parameter26Name; return this; } + public StreamCreator setParameter26Value(final String parameter26Value) { this.parameter26Value = parameter26Value; return this; } + public StreamCreator setParameter27Name(final String parameter27Name) { this.parameter27Name = parameter27Name; return this; } + public StreamCreator setParameter27Value(final String parameter27Value) { this.parameter27Value = parameter27Value; return this; } + public StreamCreator setParameter28Name(final String parameter28Name) { this.parameter28Name = parameter28Name; return this; } + public StreamCreator setParameter28Value(final String parameter28Value) { this.parameter28Value = parameter28Value; return this; } + public StreamCreator setParameter29Name(final String parameter29Name) { this.parameter29Name = parameter29Name; return this; } + public StreamCreator setParameter29Value(final String parameter29Value) { this.parameter29Value = parameter29Value; return this; } + public StreamCreator setParameter30Name(final String parameter30Name) { this.parameter30Name = parameter30Name; return this; } + public StreamCreator setParameter30Value(final String parameter30Value) { this.parameter30Value = parameter30Value; return this; } + public StreamCreator setParameter31Name(final String parameter31Name) { this.parameter31Name = parameter31Name; return this; } + public StreamCreator setParameter31Value(final String parameter31Value) { this.parameter31Value = parameter31Value; return this; } + public StreamCreator setParameter32Name(final String parameter32Name) { this.parameter32Name = parameter32Name; return this; } + public StreamCreator setParameter32Value(final String parameter32Value) { this.parameter32Value = parameter32Value; return this; } + public StreamCreator setParameter33Name(final String parameter33Name) { this.parameter33Name = parameter33Name; return this; } + public StreamCreator setParameter33Value(final String parameter33Value) { this.parameter33Value = parameter33Value; return this; } + public StreamCreator setParameter34Name(final String parameter34Name) { this.parameter34Name = parameter34Name; return this; } + public StreamCreator setParameter34Value(final String parameter34Value) { this.parameter34Value = parameter34Value; return this; } + public StreamCreator setParameter35Name(final String parameter35Name) { this.parameter35Name = parameter35Name; return this; } + public StreamCreator setParameter35Value(final String parameter35Value) { this.parameter35Value = parameter35Value; return this; } + public StreamCreator setParameter36Name(final String parameter36Name) { this.parameter36Name = parameter36Name; return this; } + public StreamCreator setParameter36Value(final String parameter36Value) { this.parameter36Value = parameter36Value; return this; } + public StreamCreator setParameter37Name(final String parameter37Name) { this.parameter37Name = parameter37Name; return this; } + public StreamCreator setParameter37Value(final String parameter37Value) { this.parameter37Value = parameter37Value; return this; } + public StreamCreator setParameter38Name(final String parameter38Name) { this.parameter38Name = parameter38Name; return this; } + public StreamCreator setParameter38Value(final String parameter38Value) { this.parameter38Value = parameter38Value; return this; } + public StreamCreator setParameter39Name(final String parameter39Name) { this.parameter39Name = parameter39Name; return this; } + public StreamCreator setParameter39Value(final String parameter39Value) { this.parameter39Value = parameter39Value; return this; } + public StreamCreator setParameter40Name(final String parameter40Name) { this.parameter40Name = parameter40Name; return this; } + public StreamCreator setParameter40Value(final String parameter40Value) { this.parameter40Value = parameter40Value; return this; } + public StreamCreator setParameter41Name(final String parameter41Name) { this.parameter41Name = parameter41Name; return this; } + public StreamCreator setParameter41Value(final String parameter41Value) { this.parameter41Value = parameter41Value; return this; } + public StreamCreator setParameter42Name(final String parameter42Name) { this.parameter42Name = parameter42Name; return this; } + public StreamCreator setParameter42Value(final String parameter42Value) { this.parameter42Value = parameter42Value; return this; } + public StreamCreator setParameter43Name(final String parameter43Name) { this.parameter43Name = parameter43Name; return this; } + public StreamCreator setParameter43Value(final String parameter43Value) { this.parameter43Value = parameter43Value; return this; } + public StreamCreator setParameter44Name(final String parameter44Name) { this.parameter44Name = parameter44Name; return this; } + public StreamCreator setParameter44Value(final String parameter44Value) { this.parameter44Value = parameter44Value; return this; } + public StreamCreator setParameter45Name(final String parameter45Name) { this.parameter45Name = parameter45Name; return this; } + public StreamCreator setParameter45Value(final String parameter45Value) { this.parameter45Value = parameter45Value; return this; } + public StreamCreator setParameter46Name(final String parameter46Name) { this.parameter46Name = parameter46Name; return this; } + public StreamCreator setParameter46Value(final String parameter46Value) { this.parameter46Value = parameter46Value; return this; } + public StreamCreator setParameter47Name(final String parameter47Name) { this.parameter47Name = parameter47Name; return this; } + public StreamCreator setParameter47Value(final String parameter47Value) { this.parameter47Value = parameter47Value; return this; } + public StreamCreator setParameter48Name(final String parameter48Name) { this.parameter48Name = parameter48Name; return this; } + public StreamCreator setParameter48Value(final String parameter48Value) { this.parameter48Value = parameter48Value; return this; } + public StreamCreator setParameter49Name(final String parameter49Name) { this.parameter49Name = parameter49Name; return this; } + public StreamCreator setParameter49Value(final String parameter49Value) { this.parameter49Value = parameter49Value; return this; } + public StreamCreator setParameter50Name(final String parameter50Name) { this.parameter50Name = parameter50Name; return this; } + public StreamCreator setParameter50Value(final String parameter50Value) { this.parameter50Value = parameter50Value; return this; } + public StreamCreator setParameter51Name(final String parameter51Name) { this.parameter51Name = parameter51Name; return this; } + public StreamCreator setParameter51Value(final String parameter51Value) { this.parameter51Value = parameter51Value; return this; } + public StreamCreator setParameter52Name(final String parameter52Name) { this.parameter52Name = parameter52Name; return this; } + public StreamCreator setParameter52Value(final String parameter52Value) { this.parameter52Value = parameter52Value; return this; } + public StreamCreator setParameter53Name(final String parameter53Name) { this.parameter53Name = parameter53Name; return this; } + public StreamCreator setParameter53Value(final String parameter53Value) { this.parameter53Value = parameter53Value; return this; } + public StreamCreator setParameter54Name(final String parameter54Name) { this.parameter54Name = parameter54Name; return this; } + public StreamCreator setParameter54Value(final String parameter54Value) { this.parameter54Value = parameter54Value; return this; } + public StreamCreator setParameter55Name(final String parameter55Name) { this.parameter55Name = parameter55Name; return this; } + public StreamCreator setParameter55Value(final String parameter55Value) { this.parameter55Value = parameter55Value; return this; } + public StreamCreator setParameter56Name(final String parameter56Name) { this.parameter56Name = parameter56Name; return this; } + public StreamCreator setParameter56Value(final String parameter56Value) { this.parameter56Value = parameter56Value; return this; } + public StreamCreator setParameter57Name(final String parameter57Name) { this.parameter57Name = parameter57Name; return this; } + public StreamCreator setParameter57Value(final String parameter57Value) { this.parameter57Value = parameter57Value; return this; } + public StreamCreator setParameter58Name(final String parameter58Name) { this.parameter58Name = parameter58Name; return this; } + public StreamCreator setParameter58Value(final String parameter58Value) { this.parameter58Value = parameter58Value; return this; } + public StreamCreator setParameter59Name(final String parameter59Name) { this.parameter59Name = parameter59Name; return this; } + public StreamCreator setParameter59Value(final String parameter59Value) { this.parameter59Value = parameter59Value; return this; } + public StreamCreator setParameter60Name(final String parameter60Name) { this.parameter60Name = parameter60Name; return this; } + public StreamCreator setParameter60Value(final String parameter60Value) { this.parameter60Value = parameter60Value; return this; } + public StreamCreator setParameter61Name(final String parameter61Name) { this.parameter61Name = parameter61Name; return this; } + public StreamCreator setParameter61Value(final String parameter61Value) { this.parameter61Value = parameter61Value; return this; } + public StreamCreator setParameter62Name(final String parameter62Name) { this.parameter62Name = parameter62Name; return this; } + public StreamCreator setParameter62Value(final String parameter62Value) { this.parameter62Value = parameter62Value; return this; } + public StreamCreator setParameter63Name(final String parameter63Name) { this.parameter63Name = parameter63Name; return this; } + public StreamCreator setParameter63Value(final String parameter63Value) { this.parameter63Value = parameter63Value; return this; } + public StreamCreator setParameter64Name(final String parameter64Name) { this.parameter64Name = parameter64Name; return this; } + public StreamCreator setParameter64Value(final String parameter64Value) { this.parameter64Value = parameter64Value; return this; } + public StreamCreator setParameter65Name(final String parameter65Name) { this.parameter65Name = parameter65Name; return this; } + public StreamCreator setParameter65Value(final String parameter65Value) { this.parameter65Value = parameter65Value; return this; } + public StreamCreator setParameter66Name(final String parameter66Name) { this.parameter66Name = parameter66Name; return this; } + public StreamCreator setParameter66Value(final String parameter66Value) { this.parameter66Value = parameter66Value; return this; } + public StreamCreator setParameter67Name(final String parameter67Name) { this.parameter67Name = parameter67Name; return this; } + public StreamCreator setParameter67Value(final String parameter67Value) { this.parameter67Value = parameter67Value; return this; } + public StreamCreator setParameter68Name(final String parameter68Name) { this.parameter68Name = parameter68Name; return this; } + public StreamCreator setParameter68Value(final String parameter68Value) { this.parameter68Value = parameter68Value; return this; } + public StreamCreator setParameter69Name(final String parameter69Name) { this.parameter69Name = parameter69Name; return this; } + public StreamCreator setParameter69Value(final String parameter69Value) { this.parameter69Value = parameter69Value; return this; } + public StreamCreator setParameter70Name(final String parameter70Name) { this.parameter70Name = parameter70Name; return this; } + public StreamCreator setParameter70Value(final String parameter70Value) { this.parameter70Value = parameter70Value; return this; } + public StreamCreator setParameter71Name(final String parameter71Name) { this.parameter71Name = parameter71Name; return this; } + public StreamCreator setParameter71Value(final String parameter71Value) { this.parameter71Value = parameter71Value; return this; } + public StreamCreator setParameter72Name(final String parameter72Name) { this.parameter72Name = parameter72Name; return this; } + public StreamCreator setParameter72Value(final String parameter72Value) { this.parameter72Value = parameter72Value; return this; } + public StreamCreator setParameter73Name(final String parameter73Name) { this.parameter73Name = parameter73Name; return this; } + public StreamCreator setParameter73Value(final String parameter73Value) { this.parameter73Value = parameter73Value; return this; } + public StreamCreator setParameter74Name(final String parameter74Name) { this.parameter74Name = parameter74Name; return this; } + public StreamCreator setParameter74Value(final String parameter74Value) { this.parameter74Value = parameter74Value; return this; } + public StreamCreator setParameter75Name(final String parameter75Name) { this.parameter75Name = parameter75Name; return this; } + public StreamCreator setParameter75Value(final String parameter75Value) { this.parameter75Value = parameter75Value; return this; } + public StreamCreator setParameter76Name(final String parameter76Name) { this.parameter76Name = parameter76Name; return this; } + public StreamCreator setParameter76Value(final String parameter76Value) { this.parameter76Value = parameter76Value; return this; } + public StreamCreator setParameter77Name(final String parameter77Name) { this.parameter77Name = parameter77Name; return this; } + public StreamCreator setParameter77Value(final String parameter77Value) { this.parameter77Value = parameter77Value; return this; } + public StreamCreator setParameter78Name(final String parameter78Name) { this.parameter78Name = parameter78Name; return this; } + public StreamCreator setParameter78Value(final String parameter78Value) { this.parameter78Value = parameter78Value; return this; } + public StreamCreator setParameter79Name(final String parameter79Name) { this.parameter79Name = parameter79Name; return this; } + public StreamCreator setParameter79Value(final String parameter79Value) { this.parameter79Value = parameter79Value; return this; } + public StreamCreator setParameter80Name(final String parameter80Name) { this.parameter80Name = parameter80Name; return this; } + public StreamCreator setParameter80Value(final String parameter80Value) { this.parameter80Value = parameter80Value; return this; } + public StreamCreator setParameter81Name(final String parameter81Name) { this.parameter81Name = parameter81Name; return this; } + public StreamCreator setParameter81Value(final String parameter81Value) { this.parameter81Value = parameter81Value; return this; } + public StreamCreator setParameter82Name(final String parameter82Name) { this.parameter82Name = parameter82Name; return this; } + public StreamCreator setParameter82Value(final String parameter82Value) { this.parameter82Value = parameter82Value; return this; } + public StreamCreator setParameter83Name(final String parameter83Name) { this.parameter83Name = parameter83Name; return this; } + public StreamCreator setParameter83Value(final String parameter83Value) { this.parameter83Value = parameter83Value; return this; } + public StreamCreator setParameter84Name(final String parameter84Name) { this.parameter84Name = parameter84Name; return this; } + public StreamCreator setParameter84Value(final String parameter84Value) { this.parameter84Value = parameter84Value; return this; } + public StreamCreator setParameter85Name(final String parameter85Name) { this.parameter85Name = parameter85Name; return this; } + public StreamCreator setParameter85Value(final String parameter85Value) { this.parameter85Value = parameter85Value; return this; } + public StreamCreator setParameter86Name(final String parameter86Name) { this.parameter86Name = parameter86Name; return this; } + public StreamCreator setParameter86Value(final String parameter86Value) { this.parameter86Value = parameter86Value; return this; } + public StreamCreator setParameter87Name(final String parameter87Name) { this.parameter87Name = parameter87Name; return this; } + public StreamCreator setParameter87Value(final String parameter87Value) { this.parameter87Value = parameter87Value; return this; } + public StreamCreator setParameter88Name(final String parameter88Name) { this.parameter88Name = parameter88Name; return this; } + public StreamCreator setParameter88Value(final String parameter88Value) { this.parameter88Value = parameter88Value; return this; } + public StreamCreator setParameter89Name(final String parameter89Name) { this.parameter89Name = parameter89Name; return this; } + public StreamCreator setParameter89Value(final String parameter89Value) { this.parameter89Value = parameter89Value; return this; } + public StreamCreator setParameter90Name(final String parameter90Name) { this.parameter90Name = parameter90Name; return this; } + public StreamCreator setParameter90Value(final String parameter90Value) { this.parameter90Value = parameter90Value; return this; } + public StreamCreator setParameter91Name(final String parameter91Name) { this.parameter91Name = parameter91Name; return this; } + public StreamCreator setParameter91Value(final String parameter91Value) { this.parameter91Value = parameter91Value; return this; } + public StreamCreator setParameter92Name(final String parameter92Name) { this.parameter92Name = parameter92Name; return this; } + public StreamCreator setParameter92Value(final String parameter92Value) { this.parameter92Value = parameter92Value; return this; } + public StreamCreator setParameter93Name(final String parameter93Name) { this.parameter93Name = parameter93Name; return this; } + public StreamCreator setParameter93Value(final String parameter93Value) { this.parameter93Value = parameter93Value; return this; } + public StreamCreator setParameter94Name(final String parameter94Name) { this.parameter94Name = parameter94Name; return this; } + public StreamCreator setParameter94Value(final String parameter94Value) { this.parameter94Value = parameter94Value; return this; } + public StreamCreator setParameter95Name(final String parameter95Name) { this.parameter95Name = parameter95Name; return this; } + public StreamCreator setParameter95Value(final String parameter95Value) { this.parameter95Value = parameter95Value; return this; } + public StreamCreator setParameter96Name(final String parameter96Name) { this.parameter96Name = parameter96Name; return this; } + public StreamCreator setParameter96Value(final String parameter96Value) { this.parameter96Value = parameter96Value; return this; } + public StreamCreator setParameter97Name(final String parameter97Name) { this.parameter97Name = parameter97Name; return this; } + public StreamCreator setParameter97Value(final String parameter97Value) { this.parameter97Value = parameter97Value; return this; } + public StreamCreator setParameter98Name(final String parameter98Name) { this.parameter98Name = parameter98Name; return this; } + public StreamCreator setParameter98Value(final String parameter98Value) { this.parameter98Value = parameter98Value; return this; } + public StreamCreator setParameter99Name(final String parameter99Name) { this.parameter99Name = parameter99Name; return this; } + public StreamCreator setParameter99Value(final String parameter99Value) { this.parameter99Value = parameter99Value; return this; } + @Override public Stream create(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/Calls/{CallSid}/Streams.json"; - - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = path.replace("{" + "CallSid" + "}", this.pathCallSid.toString()); - path = path.replace("{" + "Url" + "}", this.url.toString()); + + String path = "/2010-04-01/Accounts/{AccountSid}/Calls/{CallSid}/Streams.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "CallSid" + "}", this.pathcallSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.API.toString(), - path + HttpMethod.POST, + Domains.API.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Stream creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("Stream creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -1323,617 +1505,1021 @@ public Stream create(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (url != null) { - request.addPostParam("Url", url.toString()); + Serializer.toString(request, "Url", url, ParameterType.URLENCODED); } + + if (name != null) { - request.addPostParam("Name", name); + Serializer.toString(request, "Name", name, ParameterType.URLENCODED); } + + if (track != null) { - request.addPostParam("Track", track.toString()); + Serializer.toString(request, "Track", track, ParameterType.URLENCODED); } + + if (statusCallback != null) { - request.addPostParam("StatusCallback", statusCallback.toString()); + Serializer.toString(request, "StatusCallback", statusCallback, ParameterType.URLENCODED); } + + if (statusCallbackMethod != null) { - request.addPostParam( - "StatusCallbackMethod", - statusCallbackMethod.toString() - ); + Serializer.toString(request, "StatusCallbackMethod", statusCallbackMethod, ParameterType.URLENCODED); } + + if (parameter1Name != null) { - request.addPostParam("Parameter1.Name", parameter1Name); + Serializer.toString(request, "Parameter1.Name", parameter1Name, ParameterType.URLENCODED); } + + if (parameter1Value != null) { - request.addPostParam("Parameter1.Value", parameter1Value); + Serializer.toString(request, "Parameter1.Value", parameter1Value, ParameterType.URLENCODED); } + + if (parameter2Name != null) { - request.addPostParam("Parameter2.Name", parameter2Name); + Serializer.toString(request, "Parameter2.Name", parameter2Name, ParameterType.URLENCODED); } + + if (parameter2Value != null) { - request.addPostParam("Parameter2.Value", parameter2Value); + Serializer.toString(request, "Parameter2.Value", parameter2Value, ParameterType.URLENCODED); } + + if (parameter3Name != null) { - request.addPostParam("Parameter3.Name", parameter3Name); + Serializer.toString(request, "Parameter3.Name", parameter3Name, ParameterType.URLENCODED); } + + if (parameter3Value != null) { - request.addPostParam("Parameter3.Value", parameter3Value); + Serializer.toString(request, "Parameter3.Value", parameter3Value, ParameterType.URLENCODED); } + + if (parameter4Name != null) { - request.addPostParam("Parameter4.Name", parameter4Name); + Serializer.toString(request, "Parameter4.Name", parameter4Name, ParameterType.URLENCODED); } + + if (parameter4Value != null) { - request.addPostParam("Parameter4.Value", parameter4Value); + Serializer.toString(request, "Parameter4.Value", parameter4Value, ParameterType.URLENCODED); } + + if (parameter5Name != null) { - request.addPostParam("Parameter5.Name", parameter5Name); + Serializer.toString(request, "Parameter5.Name", parameter5Name, ParameterType.URLENCODED); } + + if (parameter5Value != null) { - request.addPostParam("Parameter5.Value", parameter5Value); + Serializer.toString(request, "Parameter5.Value", parameter5Value, ParameterType.URLENCODED); } + + if (parameter6Name != null) { - request.addPostParam("Parameter6.Name", parameter6Name); + Serializer.toString(request, "Parameter6.Name", parameter6Name, ParameterType.URLENCODED); } + + if (parameter6Value != null) { - request.addPostParam("Parameter6.Value", parameter6Value); + Serializer.toString(request, "Parameter6.Value", parameter6Value, ParameterType.URLENCODED); } + + if (parameter7Name != null) { - request.addPostParam("Parameter7.Name", parameter7Name); + Serializer.toString(request, "Parameter7.Name", parameter7Name, ParameterType.URLENCODED); } + + if (parameter7Value != null) { - request.addPostParam("Parameter7.Value", parameter7Value); + Serializer.toString(request, "Parameter7.Value", parameter7Value, ParameterType.URLENCODED); } + + if (parameter8Name != null) { - request.addPostParam("Parameter8.Name", parameter8Name); + Serializer.toString(request, "Parameter8.Name", parameter8Name, ParameterType.URLENCODED); } + + if (parameter8Value != null) { - request.addPostParam("Parameter8.Value", parameter8Value); + Serializer.toString(request, "Parameter8.Value", parameter8Value, ParameterType.URLENCODED); } + + if (parameter9Name != null) { - request.addPostParam("Parameter9.Name", parameter9Name); + Serializer.toString(request, "Parameter9.Name", parameter9Name, ParameterType.URLENCODED); } + + if (parameter9Value != null) { - request.addPostParam("Parameter9.Value", parameter9Value); + Serializer.toString(request, "Parameter9.Value", parameter9Value, ParameterType.URLENCODED); } + + if (parameter10Name != null) { - request.addPostParam("Parameter10.Name", parameter10Name); + Serializer.toString(request, "Parameter10.Name", parameter10Name, ParameterType.URLENCODED); } + + if (parameter10Value != null) { - request.addPostParam("Parameter10.Value", parameter10Value); + Serializer.toString(request, "Parameter10.Value", parameter10Value, ParameterType.URLENCODED); } + + if (parameter11Name != null) { - request.addPostParam("Parameter11.Name", parameter11Name); + Serializer.toString(request, "Parameter11.Name", parameter11Name, ParameterType.URLENCODED); } + + if (parameter11Value != null) { - request.addPostParam("Parameter11.Value", parameter11Value); + Serializer.toString(request, "Parameter11.Value", parameter11Value, ParameterType.URLENCODED); } + + if (parameter12Name != null) { - request.addPostParam("Parameter12.Name", parameter12Name); + Serializer.toString(request, "Parameter12.Name", parameter12Name, ParameterType.URLENCODED); } + + if (parameter12Value != null) { - request.addPostParam("Parameter12.Value", parameter12Value); + Serializer.toString(request, "Parameter12.Value", parameter12Value, ParameterType.URLENCODED); } + + if (parameter13Name != null) { - request.addPostParam("Parameter13.Name", parameter13Name); + Serializer.toString(request, "Parameter13.Name", parameter13Name, ParameterType.URLENCODED); } + + if (parameter13Value != null) { - request.addPostParam("Parameter13.Value", parameter13Value); + Serializer.toString(request, "Parameter13.Value", parameter13Value, ParameterType.URLENCODED); } + + if (parameter14Name != null) { - request.addPostParam("Parameter14.Name", parameter14Name); + Serializer.toString(request, "Parameter14.Name", parameter14Name, ParameterType.URLENCODED); } + + if (parameter14Value != null) { - request.addPostParam("Parameter14.Value", parameter14Value); + Serializer.toString(request, "Parameter14.Value", parameter14Value, ParameterType.URLENCODED); } + + if (parameter15Name != null) { - request.addPostParam("Parameter15.Name", parameter15Name); + Serializer.toString(request, "Parameter15.Name", parameter15Name, ParameterType.URLENCODED); } + + if (parameter15Value != null) { - request.addPostParam("Parameter15.Value", parameter15Value); + Serializer.toString(request, "Parameter15.Value", parameter15Value, ParameterType.URLENCODED); } + + if (parameter16Name != null) { - request.addPostParam("Parameter16.Name", parameter16Name); + Serializer.toString(request, "Parameter16.Name", parameter16Name, ParameterType.URLENCODED); } + + if (parameter16Value != null) { - request.addPostParam("Parameter16.Value", parameter16Value); + Serializer.toString(request, "Parameter16.Value", parameter16Value, ParameterType.URLENCODED); } + + if (parameter17Name != null) { - request.addPostParam("Parameter17.Name", parameter17Name); + Serializer.toString(request, "Parameter17.Name", parameter17Name, ParameterType.URLENCODED); } + + if (parameter17Value != null) { - request.addPostParam("Parameter17.Value", parameter17Value); + Serializer.toString(request, "Parameter17.Value", parameter17Value, ParameterType.URLENCODED); } + + if (parameter18Name != null) { - request.addPostParam("Parameter18.Name", parameter18Name); + Serializer.toString(request, "Parameter18.Name", parameter18Name, ParameterType.URLENCODED); } + + if (parameter18Value != null) { - request.addPostParam("Parameter18.Value", parameter18Value); + Serializer.toString(request, "Parameter18.Value", parameter18Value, ParameterType.URLENCODED); } + + if (parameter19Name != null) { - request.addPostParam("Parameter19.Name", parameter19Name); + Serializer.toString(request, "Parameter19.Name", parameter19Name, ParameterType.URLENCODED); } + + if (parameter19Value != null) { - request.addPostParam("Parameter19.Value", parameter19Value); + Serializer.toString(request, "Parameter19.Value", parameter19Value, ParameterType.URLENCODED); } + + if (parameter20Name != null) { - request.addPostParam("Parameter20.Name", parameter20Name); + Serializer.toString(request, "Parameter20.Name", parameter20Name, ParameterType.URLENCODED); } + + if (parameter20Value != null) { - request.addPostParam("Parameter20.Value", parameter20Value); + Serializer.toString(request, "Parameter20.Value", parameter20Value, ParameterType.URLENCODED); } + + if (parameter21Name != null) { - request.addPostParam("Parameter21.Name", parameter21Name); + Serializer.toString(request, "Parameter21.Name", parameter21Name, ParameterType.URLENCODED); } + + if (parameter21Value != null) { - request.addPostParam("Parameter21.Value", parameter21Value); + Serializer.toString(request, "Parameter21.Value", parameter21Value, ParameterType.URLENCODED); } + + if (parameter22Name != null) { - request.addPostParam("Parameter22.Name", parameter22Name); + Serializer.toString(request, "Parameter22.Name", parameter22Name, ParameterType.URLENCODED); } + + if (parameter22Value != null) { - request.addPostParam("Parameter22.Value", parameter22Value); + Serializer.toString(request, "Parameter22.Value", parameter22Value, ParameterType.URLENCODED); } + + if (parameter23Name != null) { - request.addPostParam("Parameter23.Name", parameter23Name); + Serializer.toString(request, "Parameter23.Name", parameter23Name, ParameterType.URLENCODED); } + + if (parameter23Value != null) { - request.addPostParam("Parameter23.Value", parameter23Value); + Serializer.toString(request, "Parameter23.Value", parameter23Value, ParameterType.URLENCODED); } + + if (parameter24Name != null) { - request.addPostParam("Parameter24.Name", parameter24Name); + Serializer.toString(request, "Parameter24.Name", parameter24Name, ParameterType.URLENCODED); } + + if (parameter24Value != null) { - request.addPostParam("Parameter24.Value", parameter24Value); + Serializer.toString(request, "Parameter24.Value", parameter24Value, ParameterType.URLENCODED); } + + if (parameter25Name != null) { - request.addPostParam("Parameter25.Name", parameter25Name); + Serializer.toString(request, "Parameter25.Name", parameter25Name, ParameterType.URLENCODED); } + + if (parameter25Value != null) { - request.addPostParam("Parameter25.Value", parameter25Value); + Serializer.toString(request, "Parameter25.Value", parameter25Value, ParameterType.URLENCODED); } + + if (parameter26Name != null) { - request.addPostParam("Parameter26.Name", parameter26Name); + Serializer.toString(request, "Parameter26.Name", parameter26Name, ParameterType.URLENCODED); } + + if (parameter26Value != null) { - request.addPostParam("Parameter26.Value", parameter26Value); + Serializer.toString(request, "Parameter26.Value", parameter26Value, ParameterType.URLENCODED); } + + if (parameter27Name != null) { - request.addPostParam("Parameter27.Name", parameter27Name); + Serializer.toString(request, "Parameter27.Name", parameter27Name, ParameterType.URLENCODED); } + + if (parameter27Value != null) { - request.addPostParam("Parameter27.Value", parameter27Value); + Serializer.toString(request, "Parameter27.Value", parameter27Value, ParameterType.URLENCODED); } + + if (parameter28Name != null) { - request.addPostParam("Parameter28.Name", parameter28Name); + Serializer.toString(request, "Parameter28.Name", parameter28Name, ParameterType.URLENCODED); } + + if (parameter28Value != null) { - request.addPostParam("Parameter28.Value", parameter28Value); + Serializer.toString(request, "Parameter28.Value", parameter28Value, ParameterType.URLENCODED); } + + if (parameter29Name != null) { - request.addPostParam("Parameter29.Name", parameter29Name); + Serializer.toString(request, "Parameter29.Name", parameter29Name, ParameterType.URLENCODED); } + + if (parameter29Value != null) { - request.addPostParam("Parameter29.Value", parameter29Value); + Serializer.toString(request, "Parameter29.Value", parameter29Value, ParameterType.URLENCODED); } + + if (parameter30Name != null) { - request.addPostParam("Parameter30.Name", parameter30Name); + Serializer.toString(request, "Parameter30.Name", parameter30Name, ParameterType.URLENCODED); } + + if (parameter30Value != null) { - request.addPostParam("Parameter30.Value", parameter30Value); + Serializer.toString(request, "Parameter30.Value", parameter30Value, ParameterType.URLENCODED); } + + if (parameter31Name != null) { - request.addPostParam("Parameter31.Name", parameter31Name); + Serializer.toString(request, "Parameter31.Name", parameter31Name, ParameterType.URLENCODED); } + + if (parameter31Value != null) { - request.addPostParam("Parameter31.Value", parameter31Value); + Serializer.toString(request, "Parameter31.Value", parameter31Value, ParameterType.URLENCODED); } + + if (parameter32Name != null) { - request.addPostParam("Parameter32.Name", parameter32Name); + Serializer.toString(request, "Parameter32.Name", parameter32Name, ParameterType.URLENCODED); } + + if (parameter32Value != null) { - request.addPostParam("Parameter32.Value", parameter32Value); + Serializer.toString(request, "Parameter32.Value", parameter32Value, ParameterType.URLENCODED); } + + if (parameter33Name != null) { - request.addPostParam("Parameter33.Name", parameter33Name); + Serializer.toString(request, "Parameter33.Name", parameter33Name, ParameterType.URLENCODED); } + + if (parameter33Value != null) { - request.addPostParam("Parameter33.Value", parameter33Value); + Serializer.toString(request, "Parameter33.Value", parameter33Value, ParameterType.URLENCODED); } + + if (parameter34Name != null) { - request.addPostParam("Parameter34.Name", parameter34Name); + Serializer.toString(request, "Parameter34.Name", parameter34Name, ParameterType.URLENCODED); } + + if (parameter34Value != null) { - request.addPostParam("Parameter34.Value", parameter34Value); + Serializer.toString(request, "Parameter34.Value", parameter34Value, ParameterType.URLENCODED); } + + if (parameter35Name != null) { - request.addPostParam("Parameter35.Name", parameter35Name); + Serializer.toString(request, "Parameter35.Name", parameter35Name, ParameterType.URLENCODED); } + + if (parameter35Value != null) { - request.addPostParam("Parameter35.Value", parameter35Value); + Serializer.toString(request, "Parameter35.Value", parameter35Value, ParameterType.URLENCODED); } + + if (parameter36Name != null) { - request.addPostParam("Parameter36.Name", parameter36Name); + Serializer.toString(request, "Parameter36.Name", parameter36Name, ParameterType.URLENCODED); } + + if (parameter36Value != null) { - request.addPostParam("Parameter36.Value", parameter36Value); + Serializer.toString(request, "Parameter36.Value", parameter36Value, ParameterType.URLENCODED); } + + if (parameter37Name != null) { - request.addPostParam("Parameter37.Name", parameter37Name); + Serializer.toString(request, "Parameter37.Name", parameter37Name, ParameterType.URLENCODED); } + + if (parameter37Value != null) { - request.addPostParam("Parameter37.Value", parameter37Value); + Serializer.toString(request, "Parameter37.Value", parameter37Value, ParameterType.URLENCODED); } + + if (parameter38Name != null) { - request.addPostParam("Parameter38.Name", parameter38Name); + Serializer.toString(request, "Parameter38.Name", parameter38Name, ParameterType.URLENCODED); } + + if (parameter38Value != null) { - request.addPostParam("Parameter38.Value", parameter38Value); + Serializer.toString(request, "Parameter38.Value", parameter38Value, ParameterType.URLENCODED); } + + if (parameter39Name != null) { - request.addPostParam("Parameter39.Name", parameter39Name); + Serializer.toString(request, "Parameter39.Name", parameter39Name, ParameterType.URLENCODED); } + + if (parameter39Value != null) { - request.addPostParam("Parameter39.Value", parameter39Value); + Serializer.toString(request, "Parameter39.Value", parameter39Value, ParameterType.URLENCODED); } + + if (parameter40Name != null) { - request.addPostParam("Parameter40.Name", parameter40Name); + Serializer.toString(request, "Parameter40.Name", parameter40Name, ParameterType.URLENCODED); } + + if (parameter40Value != null) { - request.addPostParam("Parameter40.Value", parameter40Value); + Serializer.toString(request, "Parameter40.Value", parameter40Value, ParameterType.URLENCODED); } + + if (parameter41Name != null) { - request.addPostParam("Parameter41.Name", parameter41Name); + Serializer.toString(request, "Parameter41.Name", parameter41Name, ParameterType.URLENCODED); } + + if (parameter41Value != null) { - request.addPostParam("Parameter41.Value", parameter41Value); + Serializer.toString(request, "Parameter41.Value", parameter41Value, ParameterType.URLENCODED); } + + if (parameter42Name != null) { - request.addPostParam("Parameter42.Name", parameter42Name); + Serializer.toString(request, "Parameter42.Name", parameter42Name, ParameterType.URLENCODED); } + + if (parameter42Value != null) { - request.addPostParam("Parameter42.Value", parameter42Value); + Serializer.toString(request, "Parameter42.Value", parameter42Value, ParameterType.URLENCODED); } + + if (parameter43Name != null) { - request.addPostParam("Parameter43.Name", parameter43Name); + Serializer.toString(request, "Parameter43.Name", parameter43Name, ParameterType.URLENCODED); } + + if (parameter43Value != null) { - request.addPostParam("Parameter43.Value", parameter43Value); + Serializer.toString(request, "Parameter43.Value", parameter43Value, ParameterType.URLENCODED); } + + if (parameter44Name != null) { - request.addPostParam("Parameter44.Name", parameter44Name); + Serializer.toString(request, "Parameter44.Name", parameter44Name, ParameterType.URLENCODED); } + + if (parameter44Value != null) { - request.addPostParam("Parameter44.Value", parameter44Value); + Serializer.toString(request, "Parameter44.Value", parameter44Value, ParameterType.URLENCODED); } + + if (parameter45Name != null) { - request.addPostParam("Parameter45.Name", parameter45Name); + Serializer.toString(request, "Parameter45.Name", parameter45Name, ParameterType.URLENCODED); } + + if (parameter45Value != null) { - request.addPostParam("Parameter45.Value", parameter45Value); + Serializer.toString(request, "Parameter45.Value", parameter45Value, ParameterType.URLENCODED); } + + if (parameter46Name != null) { - request.addPostParam("Parameter46.Name", parameter46Name); + Serializer.toString(request, "Parameter46.Name", parameter46Name, ParameterType.URLENCODED); } + + if (parameter46Value != null) { - request.addPostParam("Parameter46.Value", parameter46Value); + Serializer.toString(request, "Parameter46.Value", parameter46Value, ParameterType.URLENCODED); } + + if (parameter47Name != null) { - request.addPostParam("Parameter47.Name", parameter47Name); + Serializer.toString(request, "Parameter47.Name", parameter47Name, ParameterType.URLENCODED); } + + if (parameter47Value != null) { - request.addPostParam("Parameter47.Value", parameter47Value); + Serializer.toString(request, "Parameter47.Value", parameter47Value, ParameterType.URLENCODED); } + + if (parameter48Name != null) { - request.addPostParam("Parameter48.Name", parameter48Name); + Serializer.toString(request, "Parameter48.Name", parameter48Name, ParameterType.URLENCODED); } + + if (parameter48Value != null) { - request.addPostParam("Parameter48.Value", parameter48Value); + Serializer.toString(request, "Parameter48.Value", parameter48Value, ParameterType.URLENCODED); } + + if (parameter49Name != null) { - request.addPostParam("Parameter49.Name", parameter49Name); + Serializer.toString(request, "Parameter49.Name", parameter49Name, ParameterType.URLENCODED); } + + if (parameter49Value != null) { - request.addPostParam("Parameter49.Value", parameter49Value); + Serializer.toString(request, "Parameter49.Value", parameter49Value, ParameterType.URLENCODED); } + + if (parameter50Name != null) { - request.addPostParam("Parameter50.Name", parameter50Name); + Serializer.toString(request, "Parameter50.Name", parameter50Name, ParameterType.URLENCODED); } + + if (parameter50Value != null) { - request.addPostParam("Parameter50.Value", parameter50Value); + Serializer.toString(request, "Parameter50.Value", parameter50Value, ParameterType.URLENCODED); } + + if (parameter51Name != null) { - request.addPostParam("Parameter51.Name", parameter51Name); + Serializer.toString(request, "Parameter51.Name", parameter51Name, ParameterType.URLENCODED); } + + if (parameter51Value != null) { - request.addPostParam("Parameter51.Value", parameter51Value); + Serializer.toString(request, "Parameter51.Value", parameter51Value, ParameterType.URLENCODED); } + + if (parameter52Name != null) { - request.addPostParam("Parameter52.Name", parameter52Name); + Serializer.toString(request, "Parameter52.Name", parameter52Name, ParameterType.URLENCODED); } + + if (parameter52Value != null) { - request.addPostParam("Parameter52.Value", parameter52Value); + Serializer.toString(request, "Parameter52.Value", parameter52Value, ParameterType.URLENCODED); } + + if (parameter53Name != null) { - request.addPostParam("Parameter53.Name", parameter53Name); + Serializer.toString(request, "Parameter53.Name", parameter53Name, ParameterType.URLENCODED); } + + if (parameter53Value != null) { - request.addPostParam("Parameter53.Value", parameter53Value); + Serializer.toString(request, "Parameter53.Value", parameter53Value, ParameterType.URLENCODED); } + + if (parameter54Name != null) { - request.addPostParam("Parameter54.Name", parameter54Name); + Serializer.toString(request, "Parameter54.Name", parameter54Name, ParameterType.URLENCODED); } + + if (parameter54Value != null) { - request.addPostParam("Parameter54.Value", parameter54Value); + Serializer.toString(request, "Parameter54.Value", parameter54Value, ParameterType.URLENCODED); } + + if (parameter55Name != null) { - request.addPostParam("Parameter55.Name", parameter55Name); + Serializer.toString(request, "Parameter55.Name", parameter55Name, ParameterType.URLENCODED); } + + if (parameter55Value != null) { - request.addPostParam("Parameter55.Value", parameter55Value); + Serializer.toString(request, "Parameter55.Value", parameter55Value, ParameterType.URLENCODED); } + + if (parameter56Name != null) { - request.addPostParam("Parameter56.Name", parameter56Name); + Serializer.toString(request, "Parameter56.Name", parameter56Name, ParameterType.URLENCODED); } + + if (parameter56Value != null) { - request.addPostParam("Parameter56.Value", parameter56Value); + Serializer.toString(request, "Parameter56.Value", parameter56Value, ParameterType.URLENCODED); } + + if (parameter57Name != null) { - request.addPostParam("Parameter57.Name", parameter57Name); + Serializer.toString(request, "Parameter57.Name", parameter57Name, ParameterType.URLENCODED); } + + if (parameter57Value != null) { - request.addPostParam("Parameter57.Value", parameter57Value); + Serializer.toString(request, "Parameter57.Value", parameter57Value, ParameterType.URLENCODED); } + + if (parameter58Name != null) { - request.addPostParam("Parameter58.Name", parameter58Name); + Serializer.toString(request, "Parameter58.Name", parameter58Name, ParameterType.URLENCODED); } + + if (parameter58Value != null) { - request.addPostParam("Parameter58.Value", parameter58Value); + Serializer.toString(request, "Parameter58.Value", parameter58Value, ParameterType.URLENCODED); } + + if (parameter59Name != null) { - request.addPostParam("Parameter59.Name", parameter59Name); + Serializer.toString(request, "Parameter59.Name", parameter59Name, ParameterType.URLENCODED); } + + if (parameter59Value != null) { - request.addPostParam("Parameter59.Value", parameter59Value); + Serializer.toString(request, "Parameter59.Value", parameter59Value, ParameterType.URLENCODED); } + + if (parameter60Name != null) { - request.addPostParam("Parameter60.Name", parameter60Name); + Serializer.toString(request, "Parameter60.Name", parameter60Name, ParameterType.URLENCODED); } + + if (parameter60Value != null) { - request.addPostParam("Parameter60.Value", parameter60Value); + Serializer.toString(request, "Parameter60.Value", parameter60Value, ParameterType.URLENCODED); } + + if (parameter61Name != null) { - request.addPostParam("Parameter61.Name", parameter61Name); + Serializer.toString(request, "Parameter61.Name", parameter61Name, ParameterType.URLENCODED); } + + if (parameter61Value != null) { - request.addPostParam("Parameter61.Value", parameter61Value); + Serializer.toString(request, "Parameter61.Value", parameter61Value, ParameterType.URLENCODED); } + + if (parameter62Name != null) { - request.addPostParam("Parameter62.Name", parameter62Name); + Serializer.toString(request, "Parameter62.Name", parameter62Name, ParameterType.URLENCODED); } + + if (parameter62Value != null) { - request.addPostParam("Parameter62.Value", parameter62Value); + Serializer.toString(request, "Parameter62.Value", parameter62Value, ParameterType.URLENCODED); } + + if (parameter63Name != null) { - request.addPostParam("Parameter63.Name", parameter63Name); + Serializer.toString(request, "Parameter63.Name", parameter63Name, ParameterType.URLENCODED); } + + if (parameter63Value != null) { - request.addPostParam("Parameter63.Value", parameter63Value); + Serializer.toString(request, "Parameter63.Value", parameter63Value, ParameterType.URLENCODED); } + + if (parameter64Name != null) { - request.addPostParam("Parameter64.Name", parameter64Name); + Serializer.toString(request, "Parameter64.Name", parameter64Name, ParameterType.URLENCODED); } + + if (parameter64Value != null) { - request.addPostParam("Parameter64.Value", parameter64Value); + Serializer.toString(request, "Parameter64.Value", parameter64Value, ParameterType.URLENCODED); } + + if (parameter65Name != null) { - request.addPostParam("Parameter65.Name", parameter65Name); + Serializer.toString(request, "Parameter65.Name", parameter65Name, ParameterType.URLENCODED); } + + if (parameter65Value != null) { - request.addPostParam("Parameter65.Value", parameter65Value); + Serializer.toString(request, "Parameter65.Value", parameter65Value, ParameterType.URLENCODED); } + + if (parameter66Name != null) { - request.addPostParam("Parameter66.Name", parameter66Name); + Serializer.toString(request, "Parameter66.Name", parameter66Name, ParameterType.URLENCODED); } + + if (parameter66Value != null) { - request.addPostParam("Parameter66.Value", parameter66Value); + Serializer.toString(request, "Parameter66.Value", parameter66Value, ParameterType.URLENCODED); } + + if (parameter67Name != null) { - request.addPostParam("Parameter67.Name", parameter67Name); + Serializer.toString(request, "Parameter67.Name", parameter67Name, ParameterType.URLENCODED); } + + if (parameter67Value != null) { - request.addPostParam("Parameter67.Value", parameter67Value); + Serializer.toString(request, "Parameter67.Value", parameter67Value, ParameterType.URLENCODED); } + + if (parameter68Name != null) { - request.addPostParam("Parameter68.Name", parameter68Name); + Serializer.toString(request, "Parameter68.Name", parameter68Name, ParameterType.URLENCODED); } + + if (parameter68Value != null) { - request.addPostParam("Parameter68.Value", parameter68Value); + Serializer.toString(request, "Parameter68.Value", parameter68Value, ParameterType.URLENCODED); } + + if (parameter69Name != null) { - request.addPostParam("Parameter69.Name", parameter69Name); + Serializer.toString(request, "Parameter69.Name", parameter69Name, ParameterType.URLENCODED); } + + if (parameter69Value != null) { - request.addPostParam("Parameter69.Value", parameter69Value); + Serializer.toString(request, "Parameter69.Value", parameter69Value, ParameterType.URLENCODED); } + + if (parameter70Name != null) { - request.addPostParam("Parameter70.Name", parameter70Name); + Serializer.toString(request, "Parameter70.Name", parameter70Name, ParameterType.URLENCODED); } + + if (parameter70Value != null) { - request.addPostParam("Parameter70.Value", parameter70Value); + Serializer.toString(request, "Parameter70.Value", parameter70Value, ParameterType.URLENCODED); } + + if (parameter71Name != null) { - request.addPostParam("Parameter71.Name", parameter71Name); + Serializer.toString(request, "Parameter71.Name", parameter71Name, ParameterType.URLENCODED); } + + if (parameter71Value != null) { - request.addPostParam("Parameter71.Value", parameter71Value); + Serializer.toString(request, "Parameter71.Value", parameter71Value, ParameterType.URLENCODED); } + + if (parameter72Name != null) { - request.addPostParam("Parameter72.Name", parameter72Name); + Serializer.toString(request, "Parameter72.Name", parameter72Name, ParameterType.URLENCODED); } + + if (parameter72Value != null) { - request.addPostParam("Parameter72.Value", parameter72Value); + Serializer.toString(request, "Parameter72.Value", parameter72Value, ParameterType.URLENCODED); } + + if (parameter73Name != null) { - request.addPostParam("Parameter73.Name", parameter73Name); + Serializer.toString(request, "Parameter73.Name", parameter73Name, ParameterType.URLENCODED); } + + if (parameter73Value != null) { - request.addPostParam("Parameter73.Value", parameter73Value); + Serializer.toString(request, "Parameter73.Value", parameter73Value, ParameterType.URLENCODED); } + + if (parameter74Name != null) { - request.addPostParam("Parameter74.Name", parameter74Name); + Serializer.toString(request, "Parameter74.Name", parameter74Name, ParameterType.URLENCODED); } + + if (parameter74Value != null) { - request.addPostParam("Parameter74.Value", parameter74Value); + Serializer.toString(request, "Parameter74.Value", parameter74Value, ParameterType.URLENCODED); } + + if (parameter75Name != null) { - request.addPostParam("Parameter75.Name", parameter75Name); + Serializer.toString(request, "Parameter75.Name", parameter75Name, ParameterType.URLENCODED); } + + if (parameter75Value != null) { - request.addPostParam("Parameter75.Value", parameter75Value); + Serializer.toString(request, "Parameter75.Value", parameter75Value, ParameterType.URLENCODED); } + + if (parameter76Name != null) { - request.addPostParam("Parameter76.Name", parameter76Name); + Serializer.toString(request, "Parameter76.Name", parameter76Name, ParameterType.URLENCODED); } + + if (parameter76Value != null) { - request.addPostParam("Parameter76.Value", parameter76Value); + Serializer.toString(request, "Parameter76.Value", parameter76Value, ParameterType.URLENCODED); } + + if (parameter77Name != null) { - request.addPostParam("Parameter77.Name", parameter77Name); + Serializer.toString(request, "Parameter77.Name", parameter77Name, ParameterType.URLENCODED); } + + if (parameter77Value != null) { - request.addPostParam("Parameter77.Value", parameter77Value); + Serializer.toString(request, "Parameter77.Value", parameter77Value, ParameterType.URLENCODED); } + + if (parameter78Name != null) { - request.addPostParam("Parameter78.Name", parameter78Name); + Serializer.toString(request, "Parameter78.Name", parameter78Name, ParameterType.URLENCODED); } + + if (parameter78Value != null) { - request.addPostParam("Parameter78.Value", parameter78Value); + Serializer.toString(request, "Parameter78.Value", parameter78Value, ParameterType.URLENCODED); } + + if (parameter79Name != null) { - request.addPostParam("Parameter79.Name", parameter79Name); + Serializer.toString(request, "Parameter79.Name", parameter79Name, ParameterType.URLENCODED); } + + if (parameter79Value != null) { - request.addPostParam("Parameter79.Value", parameter79Value); + Serializer.toString(request, "Parameter79.Value", parameter79Value, ParameterType.URLENCODED); } + + if (parameter80Name != null) { - request.addPostParam("Parameter80.Name", parameter80Name); + Serializer.toString(request, "Parameter80.Name", parameter80Name, ParameterType.URLENCODED); } + + if (parameter80Value != null) { - request.addPostParam("Parameter80.Value", parameter80Value); + Serializer.toString(request, "Parameter80.Value", parameter80Value, ParameterType.URLENCODED); } + + if (parameter81Name != null) { - request.addPostParam("Parameter81.Name", parameter81Name); + Serializer.toString(request, "Parameter81.Name", parameter81Name, ParameterType.URLENCODED); } + + if (parameter81Value != null) { - request.addPostParam("Parameter81.Value", parameter81Value); + Serializer.toString(request, "Parameter81.Value", parameter81Value, ParameterType.URLENCODED); } + + if (parameter82Name != null) { - request.addPostParam("Parameter82.Name", parameter82Name); + Serializer.toString(request, "Parameter82.Name", parameter82Name, ParameterType.URLENCODED); } + + if (parameter82Value != null) { - request.addPostParam("Parameter82.Value", parameter82Value); + Serializer.toString(request, "Parameter82.Value", parameter82Value, ParameterType.URLENCODED); } + + if (parameter83Name != null) { - request.addPostParam("Parameter83.Name", parameter83Name); + Serializer.toString(request, "Parameter83.Name", parameter83Name, ParameterType.URLENCODED); } + + if (parameter83Value != null) { - request.addPostParam("Parameter83.Value", parameter83Value); + Serializer.toString(request, "Parameter83.Value", parameter83Value, ParameterType.URLENCODED); } + + if (parameter84Name != null) { - request.addPostParam("Parameter84.Name", parameter84Name); + Serializer.toString(request, "Parameter84.Name", parameter84Name, ParameterType.URLENCODED); } + + if (parameter84Value != null) { - request.addPostParam("Parameter84.Value", parameter84Value); + Serializer.toString(request, "Parameter84.Value", parameter84Value, ParameterType.URLENCODED); } + + if (parameter85Name != null) { - request.addPostParam("Parameter85.Name", parameter85Name); + Serializer.toString(request, "Parameter85.Name", parameter85Name, ParameterType.URLENCODED); } + + if (parameter85Value != null) { - request.addPostParam("Parameter85.Value", parameter85Value); + Serializer.toString(request, "Parameter85.Value", parameter85Value, ParameterType.URLENCODED); } + + if (parameter86Name != null) { - request.addPostParam("Parameter86.Name", parameter86Name); + Serializer.toString(request, "Parameter86.Name", parameter86Name, ParameterType.URLENCODED); } + + if (parameter86Value != null) { - request.addPostParam("Parameter86.Value", parameter86Value); + Serializer.toString(request, "Parameter86.Value", parameter86Value, ParameterType.URLENCODED); } + + if (parameter87Name != null) { - request.addPostParam("Parameter87.Name", parameter87Name); + Serializer.toString(request, "Parameter87.Name", parameter87Name, ParameterType.URLENCODED); } + + if (parameter87Value != null) { - request.addPostParam("Parameter87.Value", parameter87Value); + Serializer.toString(request, "Parameter87.Value", parameter87Value, ParameterType.URLENCODED); } + + if (parameter88Name != null) { - request.addPostParam("Parameter88.Name", parameter88Name); + Serializer.toString(request, "Parameter88.Name", parameter88Name, ParameterType.URLENCODED); } + + if (parameter88Value != null) { - request.addPostParam("Parameter88.Value", parameter88Value); + Serializer.toString(request, "Parameter88.Value", parameter88Value, ParameterType.URLENCODED); } + + if (parameter89Name != null) { - request.addPostParam("Parameter89.Name", parameter89Name); + Serializer.toString(request, "Parameter89.Name", parameter89Name, ParameterType.URLENCODED); } + + if (parameter89Value != null) { - request.addPostParam("Parameter89.Value", parameter89Value); + Serializer.toString(request, "Parameter89.Value", parameter89Value, ParameterType.URLENCODED); } + + if (parameter90Name != null) { - request.addPostParam("Parameter90.Name", parameter90Name); + Serializer.toString(request, "Parameter90.Name", parameter90Name, ParameterType.URLENCODED); } + + if (parameter90Value != null) { - request.addPostParam("Parameter90.Value", parameter90Value); + Serializer.toString(request, "Parameter90.Value", parameter90Value, ParameterType.URLENCODED); } + + if (parameter91Name != null) { - request.addPostParam("Parameter91.Name", parameter91Name); + Serializer.toString(request, "Parameter91.Name", parameter91Name, ParameterType.URLENCODED); } + + if (parameter91Value != null) { - request.addPostParam("Parameter91.Value", parameter91Value); + Serializer.toString(request, "Parameter91.Value", parameter91Value, ParameterType.URLENCODED); } + + if (parameter92Name != null) { - request.addPostParam("Parameter92.Name", parameter92Name); + Serializer.toString(request, "Parameter92.Name", parameter92Name, ParameterType.URLENCODED); } + + if (parameter92Value != null) { - request.addPostParam("Parameter92.Value", parameter92Value); + Serializer.toString(request, "Parameter92.Value", parameter92Value, ParameterType.URLENCODED); } + + if (parameter93Name != null) { - request.addPostParam("Parameter93.Name", parameter93Name); + Serializer.toString(request, "Parameter93.Name", parameter93Name, ParameterType.URLENCODED); } + + if (parameter93Value != null) { - request.addPostParam("Parameter93.Value", parameter93Value); + Serializer.toString(request, "Parameter93.Value", parameter93Value, ParameterType.URLENCODED); } + + if (parameter94Name != null) { - request.addPostParam("Parameter94.Name", parameter94Name); + Serializer.toString(request, "Parameter94.Name", parameter94Name, ParameterType.URLENCODED); } + + if (parameter94Value != null) { - request.addPostParam("Parameter94.Value", parameter94Value); + Serializer.toString(request, "Parameter94.Value", parameter94Value, ParameterType.URLENCODED); } + + if (parameter95Name != null) { - request.addPostParam("Parameter95.Name", parameter95Name); + Serializer.toString(request, "Parameter95.Name", parameter95Name, ParameterType.URLENCODED); } + + if (parameter95Value != null) { - request.addPostParam("Parameter95.Value", parameter95Value); + Serializer.toString(request, "Parameter95.Value", parameter95Value, ParameterType.URLENCODED); } + + if (parameter96Name != null) { - request.addPostParam("Parameter96.Name", parameter96Name); + Serializer.toString(request, "Parameter96.Name", parameter96Name, ParameterType.URLENCODED); } + + if (parameter96Value != null) { - request.addPostParam("Parameter96.Value", parameter96Value); + Serializer.toString(request, "Parameter96.Value", parameter96Value, ParameterType.URLENCODED); } + + if (parameter97Name != null) { - request.addPostParam("Parameter97.Name", parameter97Name); + Serializer.toString(request, "Parameter97.Name", parameter97Name, ParameterType.URLENCODED); } + + if (parameter97Value != null) { - request.addPostParam("Parameter97.Value", parameter97Value); + Serializer.toString(request, "Parameter97.Value", parameter97Value, ParameterType.URLENCODED); } + + if (parameter98Name != null) { - request.addPostParam("Parameter98.Name", parameter98Name); + Serializer.toString(request, "Parameter98.Name", parameter98Name, ParameterType.URLENCODED); } + + if (parameter98Value != null) { - request.addPostParam("Parameter98.Value", parameter98Value); + Serializer.toString(request, "Parameter98.Value", parameter98Value, ParameterType.URLENCODED); } + + if (parameter99Name != null) { - request.addPostParam("Parameter99.Name", parameter99Name); + Serializer.toString(request, "Parameter99.Name", parameter99Name, ParameterType.URLENCODED); } + + if (parameter99Value != null) { - request.addPostParam("Parameter99.Value", parameter99Value); + Serializer.toString(request, "Parameter99.Value", parameter99Value, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/call/StreamUpdater.java b/src/main/java/com/twilio/rest/api/v2010/account/call/StreamUpdater.java index 421350c2d0..069dd04736 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/call/StreamUpdater.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/call/StreamUpdater.java @@ -16,6 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -26,79 +28,61 @@ import com.twilio.rest.Domains; public class StreamUpdater extends Updater { - - private String pathCallSid; - private String pathSid; + private String pathaccountSid; + private String pathcallSid; + private String pathsid; private Stream.UpdateStatus status; - private String pathAccountSid; - - public StreamUpdater( - final String pathCallSid, - final String pathSid, - final Stream.UpdateStatus status - ) { - this.pathCallSid = pathCallSid; - this.pathSid = pathSid; + + public StreamUpdater(final String pathcallSid, final String pathsid, final Stream.UpdateStatus status) { + this.pathcallSid = pathcallSid; + this.pathsid = pathsid; this.status = status; } - public StreamUpdater( - final String pathAccountSid, - final String pathCallSid, - final String pathSid, - final Stream.UpdateStatus status - ) { - this.pathAccountSid = pathAccountSid; - this.pathCallSid = pathCallSid; - this.pathSid = pathSid; + public StreamUpdater(final String pathaccountSid, final String pathcallSid, final String pathsid, final Stream.UpdateStatus status) { + this.pathaccountSid = pathaccountSid; + this.pathcallSid = pathcallSid; + this.pathsid = pathsid; this.status = status; } + public StreamUpdater setStatus(final Stream.UpdateStatus status) { this.status = status; return this; } + @Override public Stream update(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/Calls/{CallSid}/Streams/{Sid}.json"; - - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = path.replace("{" + "CallSid" + "}", this.pathCallSid.toString()); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); - path = path.replace("{" + "Status" + "}", this.status.toString()); + + String path = "/2010-04-01/Accounts/{AccountSid}/Calls/{CallSid}/Streams/{Sid}.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "CallSid" + "}", this.pathcallSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.API.toString(), - path + HttpMethod.POST, + Domains.API.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Stream update failed: Unable to connect to server" - ); + throw new ApiConnectionException("Stream update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -107,8 +91,11 @@ public Stream update(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (status != null) { - request.addPostParam("Status", status.toString()); + Serializer.toString(request, "Status", status, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/call/Transcription.java b/src/main/java/com/twilio/rest/api/v2010/account/call/Transcription.java index 1f1083335a..8cbdec2abb 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/call/Transcription.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/call/Transcription.java @@ -18,70 +18,124 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.time.ZonedDateTime; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Transcription extends Resource { - private static final long serialVersionUID = 149103878272565L; - public static TranscriptionCreator creator(final String pathCallSid) { - return new TranscriptionCreator(pathCallSid); + public static TranscriptionCreator creator(final String pathcallSid) { + return new TranscriptionCreator( + pathcallSid + ); } - public static TranscriptionCreator creator( - final String pathAccountSid, - final String pathCallSid - ) { - return new TranscriptionCreator(pathAccountSid, pathCallSid); + + public static TranscriptionCreator creator(final String pathaccountSid, final String pathcallSid) { + return new TranscriptionCreator( + pathaccountSid, pathcallSid + ); } - public static TranscriptionUpdater updater( - final String pathCallSid, - final String pathSid, - final Transcription.UpdateStatus status - ) { - return new TranscriptionUpdater(pathCallSid, pathSid, status); + + public static TranscriptionUpdater updater(final String pathcallSid, final String pathsid, final Transcription.UpdateStatus status) { + return new TranscriptionUpdater( + pathcallSid, pathsid, status + ); } - public static TranscriptionUpdater updater( - final String pathAccountSid, - final String pathCallSid, - final String pathSid, - final Transcription.UpdateStatus status - ) { + + public static TranscriptionUpdater updater(final String pathaccountSid, final String pathcallSid, final String pathsid, final Transcription.UpdateStatus status) { return new TranscriptionUpdater( - pathAccountSid, - pathCallSid, - pathSid, - status + pathaccountSid, pathcallSid, pathsid, status ); } + + public enum Status { + IN_PROGRESS("in-progress"), + STOPPED("stopped"); + + private final String value; + + private Status(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static Status forValue(final String value) { + return Promoter.enumFromString(value, Status.values()); + } + } + + public enum UpdateStatus { + STOPPED("stopped"); + + private final String value; + + private UpdateStatus(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static UpdateStatus forValue(final String value) { + return Promoter.enumFromString(value, UpdateStatus.values()); + } + } + + public enum Track { + INBOUND_TRACK("inbound_track"), + OUTBOUND_TRACK("outbound_track"), + BOTH_TRACKS("both_tracks"); + + private final String value; + + private Track(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static Track forValue(final String value) { + return Promoter.enumFromString(value, Track.values()); + } + } + + /** * Converts a JSON String into a Transcription object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Transcription object represented by the provided JSON */ - public static Transcription fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Transcription fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Transcription.class); @@ -96,14 +150,11 @@ public static Transcription fromJson( * Converts a JSON InputStream into a Transcription object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Transcription object represented by the provided JSON */ - public static Transcription fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Transcription fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Transcription.class); @@ -114,61 +165,54 @@ public static Transcription fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; + @Getter private final String callSid; + @Getter + private final ZonedDateTime dateUpdated; + @Getter private final String name; + @Getter + private final String sid; + @Getter private final Transcription.Status status; - private final ZonedDateTime dateUpdated; + @Getter private final String uri; @JsonCreator private Transcription( - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("call_sid") final String callSid, - @JsonProperty("name") final String name, - @JsonProperty("status") final Transcription.Status status, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("uri") final String uri + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("call_sid") final String callSid, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.RFC2822Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("name") final String name, + @JsonProperty("sid") final String sid, + @JsonProperty("status") final Transcription.Status status, + @JsonProperty("uri") final String uri ) { - this.sid = sid; this.accountSid = accountSid; this.callSid = callSid; + this.dateUpdated = dateUpdated; this.name = name; + this.sid = sid; this.status = status; - this.dateUpdated = DateConverter.rfc2822DateTimeFromString(dateUpdated); this.uri = uri; } - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getCallSid() { - return this.callSid; - } - - public final String getName() { - return this.name; - } - - public final Transcription.Status getStatus() { - return this.status; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final String getUri() { - return this.uri; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -180,88 +224,30 @@ public boolean equals(final Object o) { } Transcription other = (Transcription) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(callSid, other.callSid) && - Objects.equals(name, other.name) && - Objects.equals(status, other.status) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(uri, other.uri) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(callSid, other.callSid) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(name, other.name) && + Objects.equals(sid, other.sid) && + Objects.equals(status, other.status) && + Objects.equals(uri, other.uri) ); } @Override public int hashCode() { return Objects.hash( - sid, - accountSid, - callSid, - name, - status, - dateUpdated, - uri + accountSid, + callSid, + dateUpdated, + name, + sid, + status, + uri ); } - public enum Track { - INBOUND_TRACK("inbound_track"), - OUTBOUND_TRACK("outbound_track"), - BOTH_TRACKS("both_tracks"); - - private final String value; - private Track(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static Track forValue(final String value) { - return Promoter.enumFromString(value, Track.values()); - } - } - - public enum UpdateStatus { - STOPPED("stopped"); - - private final String value; - - private UpdateStatus(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static UpdateStatus forValue(final String value) { - return Promoter.enumFromString(value, UpdateStatus.values()); - } - } - - public enum Status { - IN_PROGRESS("in-progress"), - STOPPED("stopped"); - - private final String value; - - private Status(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static Status forValue(final String value) { - return Promoter.enumFromString(value, Status.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/api/v2010/account/call/TranscriptionCreator.java b/src/main/java/com/twilio/rest/api/v2010/account/call/TranscriptionCreator.java index 5d472d9fdc..1965f5d50e 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/call/TranscriptionCreator.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/call/TranscriptionCreator.java @@ -14,9 +14,11 @@ package com.twilio.rest.api.v2010.account.call; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; -import com.twilio.converter.Promoter; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,13 +27,13 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -import java.net.URI; + import java.net.URI; public class TranscriptionCreator extends Creator { - private String pathCallSid; - private String pathAccountSid; + private String pathaccountSid; + private String pathcallSid; private String name; private Transcription.Track track; private URI statusCallbackUrl; @@ -47,211 +49,207 @@ public class TranscriptionCreator extends Creator { private Boolean enableAutomaticPunctuation; private String intelligenceService; - public TranscriptionCreator(final String pathCallSid) { - this.pathCallSid = pathCallSid; + public TranscriptionCreator(final String pathcallSid) { + this.pathcallSid = pathcallSid; } - public TranscriptionCreator( - final String pathAccountSid, - final String pathCallSid - ) { - this.pathAccountSid = pathAccountSid; - this.pathCallSid = pathCallSid; + public TranscriptionCreator(final String pathaccountSid, final String pathcallSid) { + this.pathaccountSid = pathaccountSid; + this.pathcallSid = pathcallSid; } + public TranscriptionCreator setName(final String name) { this.name = name; return this; } + public TranscriptionCreator setTrack(final Transcription.Track track) { this.track = track; return this; } - public TranscriptionCreator setStatusCallbackUrl( - final URI statusCallbackUrl - ) { + + public TranscriptionCreator setStatusCallbackUrl(final URI statusCallbackUrl) { this.statusCallbackUrl = statusCallbackUrl; return this; } - public TranscriptionCreator setStatusCallbackUrl( - final String statusCallbackUrl - ) { - return setStatusCallbackUrl(Promoter.uriFromString(statusCallbackUrl)); - } - public TranscriptionCreator setStatusCallbackMethod( - final HttpMethod statusCallbackMethod - ) { + public TranscriptionCreator setStatusCallbackMethod(final HttpMethod statusCallbackMethod) { this.statusCallbackMethod = statusCallbackMethod; return this; } - public TranscriptionCreator setInboundTrackLabel( - final String inboundTrackLabel - ) { + + public TranscriptionCreator setInboundTrackLabel(final String inboundTrackLabel) { this.inboundTrackLabel = inboundTrackLabel; return this; } - public TranscriptionCreator setOutboundTrackLabel( - final String outboundTrackLabel - ) { + + public TranscriptionCreator setOutboundTrackLabel(final String outboundTrackLabel) { this.outboundTrackLabel = outboundTrackLabel; return this; } - public TranscriptionCreator setPartialResults( - final Boolean partialResults - ) { + + public TranscriptionCreator setPartialResults(final Boolean partialResults) { this.partialResults = partialResults; return this; } + public TranscriptionCreator setLanguageCode(final String languageCode) { this.languageCode = languageCode; return this; } - public TranscriptionCreator setTranscriptionEngine( - final String transcriptionEngine - ) { + + public TranscriptionCreator setTranscriptionEngine(final String transcriptionEngine) { this.transcriptionEngine = transcriptionEngine; return this; } - public TranscriptionCreator setProfanityFilter( - final Boolean profanityFilter - ) { + + public TranscriptionCreator setProfanityFilter(final Boolean profanityFilter) { this.profanityFilter = profanityFilter; return this; } + public TranscriptionCreator setSpeechModel(final String speechModel) { this.speechModel = speechModel; return this; } + public TranscriptionCreator setHints(final String hints) { this.hints = hints; return this; } - public TranscriptionCreator setEnableAutomaticPunctuation( - final Boolean enableAutomaticPunctuation - ) { + + public TranscriptionCreator setEnableAutomaticPunctuation(final Boolean enableAutomaticPunctuation) { this.enableAutomaticPunctuation = enableAutomaticPunctuation; return this; } - public TranscriptionCreator setIntelligenceService( - final String intelligenceService - ) { + + public TranscriptionCreator setIntelligenceService(final String intelligenceService) { this.intelligenceService = intelligenceService; return this; } + @Override public Transcription create(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/Calls/{CallSid}/Transcriptions.json"; - - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = path.replace("{" + "CallSid" + "}", this.pathCallSid.toString()); + + String path = "/2010-04-01/Accounts/{AccountSid}/Calls/{CallSid}/Transcriptions.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "CallSid" + "}", this.pathcallSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.API.toString(), - path + HttpMethod.POST, + Domains.API.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Transcription creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("Transcription creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Transcription.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Transcription.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (name != null) { - request.addPostParam("Name", name); + Serializer.toString(request, "Name", name, ParameterType.URLENCODED); } + + if (track != null) { - request.addPostParam("Track", track.toString()); + Serializer.toString(request, "Track", track, ParameterType.URLENCODED); } + + if (statusCallbackUrl != null) { - request.addPostParam( - "StatusCallbackUrl", - statusCallbackUrl.toString() - ); + Serializer.toString(request, "StatusCallbackUrl", statusCallbackUrl, ParameterType.URLENCODED); } + + if (statusCallbackMethod != null) { - request.addPostParam( - "StatusCallbackMethod", - statusCallbackMethod.toString() - ); + Serializer.toString(request, "StatusCallbackMethod", statusCallbackMethod, ParameterType.URLENCODED); } + + if (inboundTrackLabel != null) { - request.addPostParam("InboundTrackLabel", inboundTrackLabel); + Serializer.toString(request, "InboundTrackLabel", inboundTrackLabel, ParameterType.URLENCODED); } + + if (outboundTrackLabel != null) { - request.addPostParam("OutboundTrackLabel", outboundTrackLabel); + Serializer.toString(request, "OutboundTrackLabel", outboundTrackLabel, ParameterType.URLENCODED); } + + if (partialResults != null) { - request.addPostParam("PartialResults", partialResults.toString()); + Serializer.toString(request, "PartialResults", partialResults, ParameterType.URLENCODED); } + + if (languageCode != null) { - request.addPostParam("LanguageCode", languageCode); + Serializer.toString(request, "LanguageCode", languageCode, ParameterType.URLENCODED); } + + if (transcriptionEngine != null) { - request.addPostParam("TranscriptionEngine", transcriptionEngine); + Serializer.toString(request, "TranscriptionEngine", transcriptionEngine, ParameterType.URLENCODED); } + + if (profanityFilter != null) { - request.addPostParam("ProfanityFilter", profanityFilter.toString()); + Serializer.toString(request, "ProfanityFilter", profanityFilter, ParameterType.URLENCODED); } + + if (speechModel != null) { - request.addPostParam("SpeechModel", speechModel); + Serializer.toString(request, "SpeechModel", speechModel, ParameterType.URLENCODED); } + + if (hints != null) { - request.addPostParam("Hints", hints); + Serializer.toString(request, "Hints", hints, ParameterType.URLENCODED); } + + if (enableAutomaticPunctuation != null) { - request.addPostParam( - "EnableAutomaticPunctuation", - enableAutomaticPunctuation.toString() - ); + Serializer.toString(request, "EnableAutomaticPunctuation", enableAutomaticPunctuation, ParameterType.URLENCODED); } + + if (intelligenceService != null) { - request.addPostParam("IntelligenceService", intelligenceService); + Serializer.toString(request, "IntelligenceService", intelligenceService, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/call/TranscriptionUpdater.java b/src/main/java/com/twilio/rest/api/v2010/account/call/TranscriptionUpdater.java index a16b443757..e00603ac7c 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/call/TranscriptionUpdater.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/call/TranscriptionUpdater.java @@ -16,6 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -26,94 +28,74 @@ import com.twilio.rest.Domains; public class TranscriptionUpdater extends Updater { - - private String pathCallSid; - private String pathSid; + private String pathaccountSid; + private String pathcallSid; + private String pathsid; private Transcription.UpdateStatus status; - private String pathAccountSid; - - public TranscriptionUpdater( - final String pathCallSid, - final String pathSid, - final Transcription.UpdateStatus status - ) { - this.pathCallSid = pathCallSid; - this.pathSid = pathSid; + + public TranscriptionUpdater(final String pathcallSid, final String pathsid, final Transcription.UpdateStatus status) { + this.pathcallSid = pathcallSid; + this.pathsid = pathsid; this.status = status; } - public TranscriptionUpdater( - final String pathAccountSid, - final String pathCallSid, - final String pathSid, - final Transcription.UpdateStatus status - ) { - this.pathAccountSid = pathAccountSid; - this.pathCallSid = pathCallSid; - this.pathSid = pathSid; + public TranscriptionUpdater(final String pathaccountSid, final String pathcallSid, final String pathsid, final Transcription.UpdateStatus status) { + this.pathaccountSid = pathaccountSid; + this.pathcallSid = pathcallSid; + this.pathsid = pathsid; this.status = status; } - public TranscriptionUpdater setStatus( - final Transcription.UpdateStatus status - ) { + + public TranscriptionUpdater setStatus(final Transcription.UpdateStatus status) { this.status = status; return this; } + @Override public Transcription update(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/Calls/{CallSid}/Transcriptions/{Sid}.json"; - - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = path.replace("{" + "CallSid" + "}", this.pathCallSid.toString()); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); - path = path.replace("{" + "Status" + "}", this.status.toString()); + + String path = "/2010-04-01/Accounts/{AccountSid}/Calls/{CallSid}/Transcriptions/{Sid}.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "CallSid" + "}", this.pathcallSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.API.toString(), - path + HttpMethod.POST, + Domains.API.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Transcription update failed: Unable to connect to server" - ); + throw new ApiConnectionException("Transcription update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Transcription.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Transcription.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (status != null) { - request.addPostParam("Status", status.toString()); + Serializer.toString(request, "Status", status, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/call/UserDefinedMessage.java b/src/main/java/com/twilio/rest/api/v2010/account/call/UserDefinedMessage.java index 94140fe427..690bcfe7bc 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/call/UserDefinedMessage.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/call/UserDefinedMessage.java @@ -18,55 +18,48 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.time.ZonedDateTime; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class UserDefinedMessage extends Resource { - private static final long serialVersionUID = 278501461523415L; - public static UserDefinedMessageCreator creator( - final String pathCallSid, - final String content - ) { - return new UserDefinedMessageCreator(pathCallSid, content); + public static UserDefinedMessageCreator creator(final String pathcallSid, final String content) { + return new UserDefinedMessageCreator( + pathcallSid, content + ); } - public static UserDefinedMessageCreator creator( - final String pathAccountSid, - final String pathCallSid, - final String content - ) { + + public static UserDefinedMessageCreator creator(final String pathaccountSid, final String pathcallSid, final String content) { return new UserDefinedMessageCreator( - pathAccountSid, - pathCallSid, - content + pathaccountSid, pathcallSid, content ); } + /** * Converts a JSON String into a UserDefinedMessage object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return UserDefinedMessage object represented by the provided JSON */ - public static UserDefinedMessage fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static UserDefinedMessage fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, UserDefinedMessage.class); @@ -81,14 +74,11 @@ public static UserDefinedMessage fromJson( * Converts a JSON InputStream into a UserDefinedMessage object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return UserDefinedMessage object represented by the provided JSON */ - public static UserDefinedMessage fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static UserDefinedMessage fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, UserDefinedMessage.class); @@ -99,38 +89,40 @@ public static UserDefinedMessage fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; + @Getter private final String callSid; - private final String sid; + @Getter private final ZonedDateTime dateCreated; + @Getter + private final String sid; @JsonCreator private UserDefinedMessage( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("call_sid") final String callSid, - @JsonProperty("sid") final String sid, - @JsonProperty("date_created") final String dateCreated + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("call_sid") final String callSid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.RFC2822Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("sid") final String sid ) { this.accountSid = accountSid; this.callSid = callSid; + this.dateCreated = dateCreated; this.sid = sid; - this.dateCreated = DateConverter.rfc2822DateTimeFromString(dateCreated); - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getCallSid() { - return this.callSid; - } - - public final String getSid() { - return this.sid; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; } @Override @@ -144,17 +136,24 @@ public boolean equals(final Object o) { } UserDefinedMessage other = (UserDefinedMessage) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(callSid, other.callSid) && - Objects.equals(sid, other.sid) && - Objects.equals(dateCreated, other.dateCreated) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(callSid, other.callSid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(sid, other.sid) ); } @Override public int hashCode() { - return Objects.hash(accountSid, callSid, sid, dateCreated); + return Objects.hash( + accountSid, + callSid, + dateCreated, + sid + ); } + + } + diff --git a/src/main/java/com/twilio/rest/api/v2010/account/call/UserDefinedMessageCreator.java b/src/main/java/com/twilio/rest/api/v2010/account/call/UserDefinedMessageCreator.java index 5ad497e2d7..0ae9a07fe9 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/call/UserDefinedMessageCreator.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/call/UserDefinedMessageCreator.java @@ -14,8 +14,11 @@ package com.twilio.rest.api.v2010.account.call; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,96 +30,82 @@ public class UserDefinedMessageCreator extends Creator { - private String pathCallSid; + private String pathaccountSid; + private String pathcallSid; private String content; - private String pathAccountSid; private String idempotencyKey; - public UserDefinedMessageCreator( - final String pathCallSid, - final String content - ) { - this.pathCallSid = pathCallSid; + public UserDefinedMessageCreator(final String pathcallSid, final String content) { + this.pathcallSid = pathcallSid; this.content = content; } - public UserDefinedMessageCreator( - final String pathAccountSid, - final String pathCallSid, - final String content - ) { - this.pathAccountSid = pathAccountSid; - this.pathCallSid = pathCallSid; + public UserDefinedMessageCreator(final String pathaccountSid, final String pathcallSid, final String content) { + this.pathaccountSid = pathaccountSid; + this.pathcallSid = pathcallSid; this.content = content; } + public UserDefinedMessageCreator setContent(final String content) { this.content = content; return this; } - public UserDefinedMessageCreator setIdempotencyKey( - final String idempotencyKey - ) { + + public UserDefinedMessageCreator setIdempotencyKey(final String idempotencyKey) { this.idempotencyKey = idempotencyKey; return this; } + @Override public UserDefinedMessage create(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/Calls/{CallSid}/UserDefinedMessages.json"; - - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = path.replace("{" + "CallSid" + "}", this.pathCallSid.toString()); - path = path.replace("{" + "Content" + "}", this.content.toString()); + + String path = "/2010-04-01/Accounts/{AccountSid}/Calls/{CallSid}/UserDefinedMessages.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "CallSid" + "}", this.pathcallSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.API.toString(), - path + HttpMethod.POST, + Domains.API.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "UserDefinedMessage creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("UserDefinedMessage creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return UserDefinedMessage.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return UserDefinedMessage.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (content != null) { - request.addPostParam("Content", content); + Serializer.toString(request, "Content", content, ParameterType.URLENCODED); } + + if (idempotencyKey != null) { - request.addPostParam("IdempotencyKey", idempotencyKey); + Serializer.toString(request, "IdempotencyKey", idempotencyKey, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/call/UserDefinedMessageSubscription.java b/src/main/java/com/twilio/rest/api/v2010/account/call/UserDefinedMessageSubscription.java index ae702709e4..031028afa9 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/call/UserDefinedMessageSubscription.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/call/UserDefinedMessageSubscription.java @@ -18,81 +18,66 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class UserDefinedMessageSubscription extends Resource { - private static final long serialVersionUID = 182880491726748L; - public static UserDefinedMessageSubscriptionCreator creator( - final String pathCallSid, - final URI callback - ) { - return new UserDefinedMessageSubscriptionCreator(pathCallSid, callback); + public static UserDefinedMessageSubscriptionCreator creator(final String pathcallSid, final URI callback) { + return new UserDefinedMessageSubscriptionCreator( + pathcallSid, callback + ); } - public static UserDefinedMessageSubscriptionCreator creator( - final String pathAccountSid, - final String pathCallSid, - final URI callback - ) { + + public static UserDefinedMessageSubscriptionCreator creator(final String pathaccountSid, final String pathcallSid, final URI callback) { return new UserDefinedMessageSubscriptionCreator( - pathAccountSid, - pathCallSid, - callback + pathaccountSid, pathcallSid, callback ); } - public static UserDefinedMessageSubscriptionDeleter deleter( - final String pathCallSid, - final String pathSid - ) { - return new UserDefinedMessageSubscriptionDeleter(pathCallSid, pathSid); + + public static UserDefinedMessageSubscriptionDeleter deleter(final String pathcallSid, final String pathsid) { + return new UserDefinedMessageSubscriptionDeleter( + pathcallSid, pathsid + ); } - public static UserDefinedMessageSubscriptionDeleter deleter( - final String pathAccountSid, - final String pathCallSid, - final String pathSid - ) { + + public static UserDefinedMessageSubscriptionDeleter deleter(final String pathaccountSid, final String pathcallSid, final String pathsid) { return new UserDefinedMessageSubscriptionDeleter( - pathAccountSid, - pathCallSid, - pathSid + pathaccountSid, pathcallSid, pathsid ); } + /** * Converts a JSON String into a UserDefinedMessageSubscription object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return UserDefinedMessageSubscription object represented by the provided JSON */ - public static UserDefinedMessageSubscription fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static UserDefinedMessageSubscription fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { - return objectMapper.readValue( - json, - UserDefinedMessageSubscription.class - ); + return objectMapper.readValue(json, UserDefinedMessageSubscription.class); } catch (final JsonMappingException | JsonParseException e) { throw new ApiException(e.getMessage(), e); } catch (final IOException e) { @@ -104,20 +89,14 @@ public static UserDefinedMessageSubscription fromJson( * Converts a JSON InputStream into a UserDefinedMessageSubscription object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return UserDefinedMessageSubscription object represented by the provided JSON */ - public static UserDefinedMessageSubscription fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static UserDefinedMessageSubscription fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { - return objectMapper.readValue( - json, - UserDefinedMessageSubscription.class - ); + return objectMapper.readValue(json, UserDefinedMessageSubscription.class); } catch (final JsonMappingException | JsonParseException e) { throw new ApiException(e.getMessage(), e); } catch (final IOException e) { @@ -125,47 +104,46 @@ public static UserDefinedMessageSubscription fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; + @Getter private final String callSid; - private final String sid; + @Getter private final ZonedDateTime dateCreated; + @Getter + private final String sid; + @Getter private final String uri; @JsonCreator private UserDefinedMessageSubscription( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("call_sid") final String callSid, - @JsonProperty("sid") final String sid, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("uri") final String uri + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("call_sid") final String callSid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.RFC2822Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("sid") final String sid, + @JsonProperty("uri") final String uri ) { this.accountSid = accountSid; this.callSid = callSid; + this.dateCreated = dateCreated; this.sid = sid; - this.dateCreated = DateConverter.rfc2822DateTimeFromString(dateCreated); this.uri = uri; } - public final String getAccountSid() { - return this.accountSid; - } - - public final String getCallSid() { - return this.callSid; - } - - public final String getSid() { - return this.sid; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final String getUri() { - return this.uri; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -176,20 +154,27 @@ public boolean equals(final Object o) { return false; } - UserDefinedMessageSubscription other = - (UserDefinedMessageSubscription) o; - + UserDefinedMessageSubscription other = (UserDefinedMessageSubscription) o; return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(callSid, other.callSid) && - Objects.equals(sid, other.sid) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(uri, other.uri) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(callSid, other.callSid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(sid, other.sid) && + Objects.equals(uri, other.uri) ); } @Override public int hashCode() { - return Objects.hash(accountSid, callSid, sid, dateCreated, uri); + return Objects.hash( + accountSid, + callSid, + dateCreated, + sid, + uri + ); } + + } + diff --git a/src/main/java/com/twilio/rest/api/v2010/account/call/UserDefinedMessageSubscriptionCreator.java b/src/main/java/com/twilio/rest/api/v2010/account/call/UserDefinedMessageSubscriptionCreator.java index 795516907f..929b9cfb0c 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/call/UserDefinedMessageSubscriptionCreator.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/call/UserDefinedMessageSubscriptionCreator.java @@ -14,9 +14,11 @@ package com.twilio.rest.api.v2010.account.call; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; -import com.twilio.converter.Promoter; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,123 +27,99 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -import java.net.URI; + import java.net.URI; -public class UserDefinedMessageSubscriptionCreator - extends Creator { +public class UserDefinedMessageSubscriptionCreator extends Creator { - private String pathCallSid; + private String pathaccountSid; + private String pathcallSid; private URI callback; - private String pathAccountSid; private String idempotencyKey; private HttpMethod method; - public UserDefinedMessageSubscriptionCreator( - final String pathCallSid, - final URI callback - ) { - this.pathCallSid = pathCallSid; + public UserDefinedMessageSubscriptionCreator(final String pathcallSid, final URI callback) { + this.pathcallSid = pathcallSid; this.callback = callback; } - public UserDefinedMessageSubscriptionCreator( - final String pathAccountSid, - final String pathCallSid, - final URI callback - ) { - this.pathAccountSid = pathAccountSid; - this.pathCallSid = pathCallSid; + public UserDefinedMessageSubscriptionCreator(final String pathaccountSid, final String pathcallSid, final URI callback) { + this.pathaccountSid = pathaccountSid; + this.pathcallSid = pathcallSid; this.callback = callback; } - public UserDefinedMessageSubscriptionCreator setCallback( - final URI callback - ) { + + public UserDefinedMessageSubscriptionCreator setCallback(final URI callback) { this.callback = callback; return this; } - public UserDefinedMessageSubscriptionCreator setCallback( - final String callback - ) { - return setCallback(Promoter.uriFromString(callback)); - } - public UserDefinedMessageSubscriptionCreator setIdempotencyKey( - final String idempotencyKey - ) { + public UserDefinedMessageSubscriptionCreator setIdempotencyKey(final String idempotencyKey) { this.idempotencyKey = idempotencyKey; return this; } - public UserDefinedMessageSubscriptionCreator setMethod( - final HttpMethod method - ) { + + public UserDefinedMessageSubscriptionCreator setMethod(final HttpMethod method) { this.method = method; return this; } + @Override - public UserDefinedMessageSubscription create( - final TwilioRestClient client - ) { - String path = - "/2010-04-01/Accounts/{AccountSid}/Calls/{CallSid}/UserDefinedMessageSubscriptions.json"; - - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = path.replace("{" + "CallSid" + "}", this.pathCallSid.toString()); - path = path.replace("{" + "Callback" + "}", this.callback.toString()); + public UserDefinedMessageSubscription create(final TwilioRestClient client) { + + String path = "/2010-04-01/Accounts/{AccountSid}/Calls/{CallSid}/UserDefinedMessageSubscriptions.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "CallSid" + "}", this.pathcallSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.API.toString(), - path + HttpMethod.POST, + Domains.API.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "UserDefinedMessageSubscription creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("UserDefinedMessageSubscription creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return UserDefinedMessageSubscription.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return UserDefinedMessageSubscription.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (callback != null) { - request.addPostParam("Callback", callback.toString()); + Serializer.toString(request, "Callback", callback, ParameterType.URLENCODED); } + + if (idempotencyKey != null) { - request.addPostParam("IdempotencyKey", idempotencyKey); + Serializer.toString(request, "IdempotencyKey", idempotencyKey, ParameterType.URLENCODED); } + + if (method != null) { - request.addPostParam("Method", method.toString()); + Serializer.toString(request, "Method", method, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/call/UserDefinedMessageSubscriptionDeleter.java b/src/main/java/com/twilio/rest/api/v2010/account/call/UserDefinedMessageSubscriptionDeleter.java index 85de115901..fbcde50bee 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/call/UserDefinedMessageSubscriptionDeleter.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/call/UserDefinedMessageSubscriptionDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.api.v2010.account.call; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,70 +24,52 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class UserDefinedMessageSubscriptionDeleter - extends Deleter { +public class UserDefinedMessageSubscriptionDeleter extends Deleter { - private String pathCallSid; - private String pathSid; - private String pathAccountSid; + private String pathaccountSid; + private String pathcallSid; + private String pathsid; - public UserDefinedMessageSubscriptionDeleter( - final String pathCallSid, - final String pathSid - ) { - this.pathCallSid = pathCallSid; - this.pathSid = pathSid; + public UserDefinedMessageSubscriptionDeleter(final String pathcallSid, final String pathsid) { + this.pathcallSid = pathcallSid; + this.pathsid = pathsid; } - public UserDefinedMessageSubscriptionDeleter( - final String pathAccountSid, - final String pathCallSid, - final String pathSid - ) { - this.pathAccountSid = pathAccountSid; - this.pathCallSid = pathCallSid; - this.pathSid = pathSid; + public UserDefinedMessageSubscriptionDeleter(final String pathaccountSid, final String pathcallSid, final String pathsid) { + this.pathaccountSid = pathaccountSid; + this.pathcallSid = pathcallSid; + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/Calls/{CallSid}/UserDefinedMessageSubscriptions/{Sid}.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = path.replace("{" + "CallSid" + "}", this.pathCallSid.toString()); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/2010-04-01/Accounts/{AccountSid}/Calls/{CallSid}/UserDefinedMessageSubscriptions/{Sid}.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "CallSid" + "}", this.pathcallSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.API.toString(), - path + HttpMethod.DELETE, + Domains.API.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "UserDefinedMessageSubscription delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("UserDefinedMessageSubscription delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/conference/Participant.java b/src/main/java/com/twilio/rest/api/v2010/account/conference/Participant.java index 1eb8a9218a..3f2ce68466 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/conference/Participant.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/conference/Participant.java @@ -18,127 +18,131 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import com.twilio.type.Endpoint; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.time.ZonedDateTime; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Participant extends Resource { - private static final long serialVersionUID = 178960491032323L; - public static ParticipantCreator creator( - final String pathConferenceSid, - final com.twilio.type.Endpoint from, - final com.twilio.type.Endpoint to - ) { - return new ParticipantCreator(pathConferenceSid, from, to); + public static ParticipantCreator creator(final String pathconferenceSid, final Endpoint from, final Endpoint to) { + return new ParticipantCreator( + pathconferenceSid, from, to + ); } - public static ParticipantCreator creator( - final String pathAccountSid, - final String pathConferenceSid, - final com.twilio.type.Endpoint from, - final com.twilio.type.Endpoint to - ) { + + public static ParticipantCreator creator(final String pathaccountSid, final String pathconferenceSid, final Endpoint from, final Endpoint to) { return new ParticipantCreator( - pathAccountSid, - pathConferenceSid, - from, - to + pathaccountSid, pathconferenceSid, from, to ); } - public static ParticipantDeleter deleter( - final String pathConferenceSid, - final String pathCallSid - ) { - return new ParticipantDeleter(pathConferenceSid, pathCallSid); + + public static ParticipantDeleter deleter(final String pathconferenceSid, final String pathcallSid) { + return new ParticipantDeleter( + pathconferenceSid, pathcallSid + ); } - public static ParticipantDeleter deleter( - final String pathAccountSid, - final String pathConferenceSid, - final String pathCallSid - ) { + + public static ParticipantDeleter deleter(final String pathaccountSid, final String pathconferenceSid, final String pathcallSid) { return new ParticipantDeleter( - pathAccountSid, - pathConferenceSid, - pathCallSid + pathaccountSid, pathconferenceSid, pathcallSid ); } - public static ParticipantFetcher fetcher( - final String pathConferenceSid, - final String pathCallSid - ) { - return new ParticipantFetcher(pathConferenceSid, pathCallSid); + + public static ParticipantFetcher fetcher(final String pathconferenceSid, final String pathcallSid) { + return new ParticipantFetcher( + pathconferenceSid, pathcallSid + ); } - public static ParticipantFetcher fetcher( - final String pathAccountSid, - final String pathConferenceSid, - final String pathCallSid - ) { + + public static ParticipantFetcher fetcher(final String pathaccountSid, final String pathconferenceSid, final String pathcallSid) { return new ParticipantFetcher( - pathAccountSid, - pathConferenceSid, - pathCallSid + pathaccountSid, pathconferenceSid, pathcallSid ); } - public static ParticipantReader reader(final String pathConferenceSid) { - return new ParticipantReader(pathConferenceSid); + + public static ParticipantReader reader(final String pathconferenceSid) { + return new ParticipantReader( + pathconferenceSid + ); } - public static ParticipantReader reader( - final String pathAccountSid, - final String pathConferenceSid - ) { - return new ParticipantReader(pathAccountSid, pathConferenceSid); + + public static ParticipantReader reader(final String pathaccountSid, final String pathconferenceSid) { + return new ParticipantReader( + pathaccountSid, pathconferenceSid + ); } - public static ParticipantUpdater updater( - final String pathConferenceSid, - final String pathCallSid - ) { - return new ParticipantUpdater(pathConferenceSid, pathCallSid); + + public static ParticipantUpdater updater(final String pathconferenceSid, final String pathcallSid) { + return new ParticipantUpdater( + pathconferenceSid, pathcallSid + ); } - public static ParticipantUpdater updater( - final String pathAccountSid, - final String pathConferenceSid, - final String pathCallSid - ) { + + public static ParticipantUpdater updater(final String pathaccountSid, final String pathconferenceSid, final String pathcallSid) { return new ParticipantUpdater( - pathAccountSid, - pathConferenceSid, - pathCallSid + pathaccountSid, pathconferenceSid, pathcallSid ); } + + public enum Status { + QUEUED("queued"), + CONNECTING("connecting"), + RINGING("ringing"), + CONNECTED("connected"), + COMPLETE("complete"), + FAILED("failed"); + + private final String value; + + private Status(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static Status forValue(final String value) { + return Promoter.enumFromString(value, Status.values()); + } + } + + /** * Converts a JSON String into a Participant object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Participant object represented by the provided JSON */ - public static Participant fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Participant fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Participant.class); @@ -153,14 +157,11 @@ public static Participant fromJson( * Converts a JSON InputStream into a Participant object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Participant object represented by the provided JSON */ - public static Participant fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Participant fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Participant.class); @@ -171,121 +172,87 @@ public static Participant fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; + @Getter private final String callSid; - private final String label; + @Getter private final String callSidToCoach; + @Getter private final Boolean coaching; + @Getter private final String conferenceSid; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; + @Getter private final Boolean endConferenceOnExit; - private final Boolean muted; + @Getter private final Boolean hold; + @Getter + private final String label; + @Getter + private final Boolean muted; + @Getter + private final String queueTime; + @Getter private final Boolean startConferenceOnEnter; + @Getter private final Participant.Status status; - private final String queueTime; + @Getter private final String uri; @JsonCreator private Participant( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("call_sid") final String callSid, - @JsonProperty("label") final String label, - @JsonProperty("call_sid_to_coach") final String callSidToCoach, - @JsonProperty("coaching") final Boolean coaching, - @JsonProperty("conference_sid") final String conferenceSid, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty( - "end_conference_on_exit" - ) final Boolean endConferenceOnExit, - @JsonProperty("muted") final Boolean muted, - @JsonProperty("hold") final Boolean hold, - @JsonProperty( - "start_conference_on_enter" - ) final Boolean startConferenceOnEnter, - @JsonProperty("status") final Participant.Status status, - @JsonProperty("queue_time") final String queueTime, - @JsonProperty("uri") final String uri + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("call_sid") final String callSid, + @JsonProperty("call_sid_to_coach") final String callSidToCoach, + @JsonProperty("coaching") final Boolean coaching, + @JsonProperty("conference_sid") final String conferenceSid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.RFC2822Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.RFC2822Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("end_conference_on_exit") final Boolean endConferenceOnExit, + @JsonProperty("hold") final Boolean hold, + @JsonProperty("label") final String label, + @JsonProperty("muted") final Boolean muted, + @JsonProperty("queue_time") final String queueTime, + @JsonProperty("start_conference_on_enter") final Boolean startConferenceOnEnter, + @JsonProperty("status") final Participant.Status status, + @JsonProperty("uri") final String uri ) { this.accountSid = accountSid; this.callSid = callSid; - this.label = label; this.callSidToCoach = callSidToCoach; this.coaching = coaching; this.conferenceSid = conferenceSid; - this.dateCreated = DateConverter.rfc2822DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.rfc2822DateTimeFromString(dateUpdated); + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.endConferenceOnExit = endConferenceOnExit; - this.muted = muted; this.hold = hold; + this.label = label; + this.muted = muted; + this.queueTime = queueTime; this.startConferenceOnEnter = startConferenceOnEnter; this.status = status; - this.queueTime = queueTime; this.uri = uri; } - public final String getAccountSid() { - return this.accountSid; - } - - public final String getCallSid() { - return this.callSid; - } - - public final String getLabel() { - return this.label; - } - - public final String getCallSidToCoach() { - return this.callSidToCoach; - } - - public final Boolean getCoaching() { - return this.coaching; - } - - public final String getConferenceSid() { - return this.conferenceSid; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final Boolean getEndConferenceOnExit() { - return this.endConferenceOnExit; - } - - public final Boolean getMuted() { - return this.muted; - } - - public final Boolean getHold() { - return this.hold; - } - - public final Boolean getStartConferenceOnEnter() { - return this.startConferenceOnEnter; - } - - public final Participant.Status getStatus() { - return this.status; - } - - public final String getQueueTime() { - return this.queueTime; - } - - public final String getUri() { - return this.uri; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -297,71 +264,46 @@ public boolean equals(final Object o) { } Participant other = (Participant) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(callSid, other.callSid) && - Objects.equals(label, other.label) && - Objects.equals(callSidToCoach, other.callSidToCoach) && - Objects.equals(coaching, other.coaching) && - Objects.equals(conferenceSid, other.conferenceSid) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(endConferenceOnExit, other.endConferenceOnExit) && - Objects.equals(muted, other.muted) && - Objects.equals(hold, other.hold) && - Objects.equals( - startConferenceOnEnter, - other.startConferenceOnEnter - ) && - Objects.equals(status, other.status) && - Objects.equals(queueTime, other.queueTime) && - Objects.equals(uri, other.uri) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(callSid, other.callSid) && + Objects.equals(callSidToCoach, other.callSidToCoach) && + Objects.equals(coaching, other.coaching) && + Objects.equals(conferenceSid, other.conferenceSid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(endConferenceOnExit, other.endConferenceOnExit) && + Objects.equals(hold, other.hold) && + Objects.equals(label, other.label) && + Objects.equals(muted, other.muted) && + Objects.equals(queueTime, other.queueTime) && + Objects.equals(startConferenceOnEnter, other.startConferenceOnEnter) && + Objects.equals(status, other.status) && + Objects.equals(uri, other.uri) ); } @Override public int hashCode() { return Objects.hash( - accountSid, - callSid, - label, - callSidToCoach, - coaching, - conferenceSid, - dateCreated, - dateUpdated, - endConferenceOnExit, - muted, - hold, - startConferenceOnEnter, - status, - queueTime, - uri + accountSid, + callSid, + callSidToCoach, + coaching, + conferenceSid, + dateCreated, + dateUpdated, + endConferenceOnExit, + hold, + label, + muted, + queueTime, + startConferenceOnEnter, + status, + uri ); } - public enum Status { - QUEUED("queued"), - CONNECTING("connecting"), - RINGING("ringing"), - CONNECTED("connected"), - COMPLETE("complete"), - FAILED("failed"); - - private final String value; - private Status(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static Status forValue(final String value) { - return Promoter.enumFromString(value, Status.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/api/v2010/account/conference/ParticipantCreator.java b/src/main/java/com/twilio/rest/api/v2010/account/conference/ParticipantCreator.java index 6d9b33c6ca..1568d08ac8 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/conference/ParticipantCreator.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/conference/ParticipantCreator.java @@ -14,9 +14,12 @@ package com.twilio.rest.api.v2010.account.conference; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; import com.twilio.converter.Promoter; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,17 +28,17 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -import java.net.URI; +import com.twilio.type.Endpoint; + import java.net.URI; import java.util.List; -import java.util.List; public class ParticipantCreator extends Creator { - private String pathConferenceSid; - private com.twilio.type.Endpoint from; - private com.twilio.type.Endpoint to; - private String pathAccountSid; + private String pathaccountSid; + private String pathconferenceSid; + private Endpoint from; + private Endpoint to; private URI statusCallback; private HttpMethod statusCallbackMethod; private List statusCallbackEvent; @@ -83,64 +86,50 @@ public class ParticipantCreator extends Creator { private String trim; private String callToken; - public ParticipantCreator( - final String pathConferenceSid, - final com.twilio.type.Endpoint from, - final com.twilio.type.Endpoint to - ) { - this.pathConferenceSid = pathConferenceSid; + public ParticipantCreator(final String pathconferenceSid, final Endpoint from, final Endpoint to) { + this.pathconferenceSid = pathconferenceSid; this.from = from; this.to = to; } - public ParticipantCreator( - final String pathAccountSid, - final String pathConferenceSid, - final com.twilio.type.Endpoint from, - final com.twilio.type.Endpoint to - ) { - this.pathAccountSid = pathAccountSid; - this.pathConferenceSid = pathConferenceSid; + public ParticipantCreator(final String pathaccountSid, final String pathconferenceSid, final Endpoint from, final Endpoint to) { + this.pathaccountSid = pathaccountSid; + this.pathconferenceSid = pathconferenceSid; this.from = from; this.to = to; } - public ParticipantCreator setFrom(final com.twilio.type.Endpoint from) { + + public ParticipantCreator setFrom(final Endpoint from) { this.from = from; return this; } - public ParticipantCreator setTo(final com.twilio.type.Endpoint to) { + + public ParticipantCreator setTo(final Endpoint to) { this.to = to; return this; } + public ParticipantCreator setStatusCallback(final URI statusCallback) { this.statusCallback = statusCallback; return this; } - public ParticipantCreator setStatusCallback(final String statusCallback) { - return setStatusCallback(Promoter.uriFromString(statusCallback)); - } - public ParticipantCreator setStatusCallbackMethod( - final HttpMethod statusCallbackMethod - ) { + public ParticipantCreator setStatusCallbackMethod(final HttpMethod statusCallbackMethod) { this.statusCallbackMethod = statusCallbackMethod; return this; } - public ParticipantCreator setStatusCallbackEvent( - final List statusCallbackEvent - ) { + + public ParticipantCreator setStatusCallbackEvent(final List statusCallbackEvent) { this.statusCallbackEvent = statusCallbackEvent; return this; } - public ParticipantCreator setStatusCallbackEvent( - final String statusCallbackEvent - ) { + public ParticipantCreator setStatusCallbackEvent(final String statusCallbackEvent) { return setStatusCallbackEvent(Promoter.listOfOne(statusCallbackEvent)); } @@ -149,212 +138,164 @@ public ParticipantCreator setLabel(final String label) { return this; } + public ParticipantCreator setTimeout(final Integer timeout) { this.timeout = timeout; return this; } + public ParticipantCreator setRecord(final Boolean record) { this.record = record; return this; } + public ParticipantCreator setMuted(final Boolean muted) { this.muted = muted; return this; } + public ParticipantCreator setBeep(final String beep) { this.beep = beep; return this; } - public ParticipantCreator setStartConferenceOnEnter( - final Boolean startConferenceOnEnter - ) { + + public ParticipantCreator setStartConferenceOnEnter(final Boolean startConferenceOnEnter) { this.startConferenceOnEnter = startConferenceOnEnter; return this; } - public ParticipantCreator setEndConferenceOnExit( - final Boolean endConferenceOnExit - ) { + + public ParticipantCreator setEndConferenceOnExit(final Boolean endConferenceOnExit) { this.endConferenceOnExit = endConferenceOnExit; return this; } + public ParticipantCreator setWaitUrl(final URI waitUrl) { this.waitUrl = waitUrl; return this; } - public ParticipantCreator setWaitUrl(final String waitUrl) { - return setWaitUrl(Promoter.uriFromString(waitUrl)); - } public ParticipantCreator setWaitMethod(final HttpMethod waitMethod) { this.waitMethod = waitMethod; return this; } + public ParticipantCreator setEarlyMedia(final Boolean earlyMedia) { this.earlyMedia = earlyMedia; return this; } - public ParticipantCreator setMaxParticipants( - final Integer maxParticipants - ) { + + public ParticipantCreator setMaxParticipants(final Integer maxParticipants) { this.maxParticipants = maxParticipants; return this; } - public ParticipantCreator setConferenceRecord( - final String conferenceRecord - ) { + + public ParticipantCreator setConferenceRecord(final String conferenceRecord) { this.conferenceRecord = conferenceRecord; return this; } + public ParticipantCreator setConferenceTrim(final String conferenceTrim) { this.conferenceTrim = conferenceTrim; return this; } - public ParticipantCreator setConferenceStatusCallback( - final URI conferenceStatusCallback - ) { + + public ParticipantCreator setConferenceStatusCallback(final URI conferenceStatusCallback) { this.conferenceStatusCallback = conferenceStatusCallback; return this; } - public ParticipantCreator setConferenceStatusCallback( - final String conferenceStatusCallback - ) { - return setConferenceStatusCallback( - Promoter.uriFromString(conferenceStatusCallback) - ); - } - public ParticipantCreator setConferenceStatusCallbackMethod( - final HttpMethod conferenceStatusCallbackMethod - ) { + public ParticipantCreator setConferenceStatusCallbackMethod(final HttpMethod conferenceStatusCallbackMethod) { this.conferenceStatusCallbackMethod = conferenceStatusCallbackMethod; return this; } - public ParticipantCreator setConferenceStatusCallbackEvent( - final List conferenceStatusCallbackEvent - ) { + + public ParticipantCreator setConferenceStatusCallbackEvent(final List conferenceStatusCallbackEvent) { this.conferenceStatusCallbackEvent = conferenceStatusCallbackEvent; return this; } - public ParticipantCreator setConferenceStatusCallbackEvent( - final String conferenceStatusCallbackEvent - ) { - return setConferenceStatusCallbackEvent( - Promoter.listOfOne(conferenceStatusCallbackEvent) - ); + public ParticipantCreator setConferenceStatusCallbackEvent(final String conferenceStatusCallbackEvent) { + return setConferenceStatusCallbackEvent(Promoter.listOfOne(conferenceStatusCallbackEvent)); } - public ParticipantCreator setRecordingChannels( - final String recordingChannels - ) { + public ParticipantCreator setRecordingChannels(final String recordingChannels) { this.recordingChannels = recordingChannels; return this; } - public ParticipantCreator setRecordingStatusCallback( - final URI recordingStatusCallback - ) { + + public ParticipantCreator setRecordingStatusCallback(final URI recordingStatusCallback) { this.recordingStatusCallback = recordingStatusCallback; return this; } - public ParticipantCreator setRecordingStatusCallback( - final String recordingStatusCallback - ) { - return setRecordingStatusCallback( - Promoter.uriFromString(recordingStatusCallback) - ); - } - public ParticipantCreator setRecordingStatusCallbackMethod( - final HttpMethod recordingStatusCallbackMethod - ) { + public ParticipantCreator setRecordingStatusCallbackMethod(final HttpMethod recordingStatusCallbackMethod) { this.recordingStatusCallbackMethod = recordingStatusCallbackMethod; return this; } + public ParticipantCreator setSipAuthUsername(final String sipAuthUsername) { this.sipAuthUsername = sipAuthUsername; return this; } + public ParticipantCreator setSipAuthPassword(final String sipAuthPassword) { this.sipAuthPassword = sipAuthPassword; return this; } + public ParticipantCreator setRegion(final String region) { this.region = region; return this; } - public ParticipantCreator setConferenceRecordingStatusCallback( - final URI conferenceRecordingStatusCallback - ) { - this.conferenceRecordingStatusCallback = - conferenceRecordingStatusCallback; + + public ParticipantCreator setConferenceRecordingStatusCallback(final URI conferenceRecordingStatusCallback) { + this.conferenceRecordingStatusCallback = conferenceRecordingStatusCallback; return this; } - public ParticipantCreator setConferenceRecordingStatusCallback( - final String conferenceRecordingStatusCallback - ) { - return setConferenceRecordingStatusCallback( - Promoter.uriFromString(conferenceRecordingStatusCallback) - ); - } - public ParticipantCreator setConferenceRecordingStatusCallbackMethod( - final HttpMethod conferenceRecordingStatusCallbackMethod - ) { - this.conferenceRecordingStatusCallbackMethod = - conferenceRecordingStatusCallbackMethod; + public ParticipantCreator setConferenceRecordingStatusCallbackMethod(final HttpMethod conferenceRecordingStatusCallbackMethod) { + this.conferenceRecordingStatusCallbackMethod = conferenceRecordingStatusCallbackMethod; return this; } - public ParticipantCreator setRecordingStatusCallbackEvent( - final List recordingStatusCallbackEvent - ) { + + public ParticipantCreator setRecordingStatusCallbackEvent(final List recordingStatusCallbackEvent) { this.recordingStatusCallbackEvent = recordingStatusCallbackEvent; return this; } - public ParticipantCreator setRecordingStatusCallbackEvent( - final String recordingStatusCallbackEvent - ) { - return setRecordingStatusCallbackEvent( - Promoter.listOfOne(recordingStatusCallbackEvent) - ); + public ParticipantCreator setRecordingStatusCallbackEvent(final String recordingStatusCallbackEvent) { + return setRecordingStatusCallbackEvent(Promoter.listOfOne(recordingStatusCallbackEvent)); } - public ParticipantCreator setConferenceRecordingStatusCallbackEvent( - final List conferenceRecordingStatusCallbackEvent - ) { - this.conferenceRecordingStatusCallbackEvent = - conferenceRecordingStatusCallbackEvent; + public ParticipantCreator setConferenceRecordingStatusCallbackEvent(final List conferenceRecordingStatusCallbackEvent) { + this.conferenceRecordingStatusCallbackEvent = conferenceRecordingStatusCallbackEvent; return this; } - public ParticipantCreator setConferenceRecordingStatusCallbackEvent( - final String conferenceRecordingStatusCallbackEvent - ) { - return setConferenceRecordingStatusCallbackEvent( - Promoter.listOfOne(conferenceRecordingStatusCallbackEvent) - ); + public ParticipantCreator setConferenceRecordingStatusCallbackEvent(final String conferenceRecordingStatusCallbackEvent) { + return setConferenceRecordingStatusCallbackEvent(Promoter.listOfOne(conferenceRecordingStatusCallbackEvent)); } public ParticipantCreator setCoaching(final Boolean coaching) { @@ -362,363 +303,388 @@ public ParticipantCreator setCoaching(final Boolean coaching) { return this; } + public ParticipantCreator setCallSidToCoach(final String callSidToCoach) { this.callSidToCoach = callSidToCoach; return this; } - public ParticipantCreator setJitterBufferSize( - final String jitterBufferSize - ) { + + public ParticipantCreator setJitterBufferSize(final String jitterBufferSize) { this.jitterBufferSize = jitterBufferSize; return this; } + public ParticipantCreator setByoc(final String byoc) { this.byoc = byoc; return this; } + public ParticipantCreator setCallerId(final String callerId) { this.callerId = callerId; return this; } + public ParticipantCreator setCallReason(final String callReason) { this.callReason = callReason; return this; } + public ParticipantCreator setRecordingTrack(final String recordingTrack) { this.recordingTrack = recordingTrack; return this; } + public ParticipantCreator setTimeLimit(final Integer timeLimit) { this.timeLimit = timeLimit; return this; } - public ParticipantCreator setMachineDetection( - final String machineDetection - ) { + + public ParticipantCreator setMachineDetection(final String machineDetection) { this.machineDetection = machineDetection; return this; } - public ParticipantCreator setMachineDetectionTimeout( - final Integer machineDetectionTimeout - ) { + + public ParticipantCreator setMachineDetectionTimeout(final Integer machineDetectionTimeout) { this.machineDetectionTimeout = machineDetectionTimeout; return this; } - public ParticipantCreator setMachineDetectionSpeechThreshold( - final Integer machineDetectionSpeechThreshold - ) { + + public ParticipantCreator setMachineDetectionSpeechThreshold(final Integer machineDetectionSpeechThreshold) { this.machineDetectionSpeechThreshold = machineDetectionSpeechThreshold; return this; } - public ParticipantCreator setMachineDetectionSpeechEndThreshold( - final Integer machineDetectionSpeechEndThreshold - ) { - this.machineDetectionSpeechEndThreshold = - machineDetectionSpeechEndThreshold; + + public ParticipantCreator setMachineDetectionSpeechEndThreshold(final Integer machineDetectionSpeechEndThreshold) { + this.machineDetectionSpeechEndThreshold = machineDetectionSpeechEndThreshold; return this; } - public ParticipantCreator setMachineDetectionSilenceTimeout( - final Integer machineDetectionSilenceTimeout - ) { + + public ParticipantCreator setMachineDetectionSilenceTimeout(final Integer machineDetectionSilenceTimeout) { this.machineDetectionSilenceTimeout = machineDetectionSilenceTimeout; return this; } - public ParticipantCreator setAmdStatusCallback( - final URI amdStatusCallback - ) { + + public ParticipantCreator setAmdStatusCallback(final URI amdStatusCallback) { this.amdStatusCallback = amdStatusCallback; return this; } - public ParticipantCreator setAmdStatusCallback( - final String amdStatusCallback - ) { - return setAmdStatusCallback(Promoter.uriFromString(amdStatusCallback)); - } - public ParticipantCreator setAmdStatusCallbackMethod( - final HttpMethod amdStatusCallbackMethod - ) { + public ParticipantCreator setAmdStatusCallbackMethod(final HttpMethod amdStatusCallbackMethod) { this.amdStatusCallbackMethod = amdStatusCallbackMethod; return this; } + public ParticipantCreator setTrim(final String trim) { this.trim = trim; return this; } + public ParticipantCreator setCallToken(final String callToken) { this.callToken = callToken; return this; } + @Override public Participant create(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/Conferences/{ConferenceSid}/Participants.json"; - - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = - path.replace( - "{" + "ConferenceSid" + "}", - this.pathConferenceSid.toString() - ); - path = path.replace("{" + "From" + "}", this.from.toString()); - path = path.replace("{" + "To" + "}", this.to.toString()); + + String path = "/2010-04-01/Accounts/{AccountSid}/Conferences/{ConferenceSid}/Participants.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "ConferenceSid" + "}", this.pathconferenceSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.API.toString(), - path + HttpMethod.POST, + Domains.API.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Participant creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("Participant creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Participant.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Participant.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (from != null) { - request.addPostParam("From", from.toString()); + Serializer.toString(request, "From", from, ParameterType.URLENCODED); } + + if (to != null) { - request.addPostParam("To", to.toString()); + Serializer.toString(request, "To", to, ParameterType.URLENCODED); } + + if (statusCallback != null) { - request.addPostParam("StatusCallback", statusCallback.toString()); + Serializer.toString(request, "StatusCallback", statusCallback, ParameterType.URLENCODED); } + + if (statusCallbackMethod != null) { - request.addPostParam( - "StatusCallbackMethod", - statusCallbackMethod.toString() - ); + Serializer.toString(request, "StatusCallbackMethod", statusCallbackMethod, ParameterType.URLENCODED); } + + if (statusCallbackEvent != null) { - for (String prop : statusCallbackEvent) { - request.addPostParam("StatusCallbackEvent", prop); + for (String param : statusCallbackEvent) { + Serializer.toString(request, "StatusCallbackEvent", param, ParameterType.URLENCODED); } } + + if (label != null) { - request.addPostParam("Label", label); + Serializer.toString(request, "Label", label, ParameterType.URLENCODED); } + + if (timeout != null) { - request.addPostParam("Timeout", timeout.toString()); + Serializer.toString(request, "Timeout", timeout, ParameterType.URLENCODED); } + + if (record != null) { - request.addPostParam("Record", record.toString()); + Serializer.toString(request, "Record", record, ParameterType.URLENCODED); } + + if (muted != null) { - request.addPostParam("Muted", muted.toString()); + Serializer.toString(request, "Muted", muted, ParameterType.URLENCODED); } + + if (beep != null) { - request.addPostParam("Beep", beep); + Serializer.toString(request, "Beep", beep, ParameterType.URLENCODED); } + + if (startConferenceOnEnter != null) { - request.addPostParam( - "StartConferenceOnEnter", - startConferenceOnEnter.toString() - ); + Serializer.toString(request, "StartConferenceOnEnter", startConferenceOnEnter, ParameterType.URLENCODED); } + + if (endConferenceOnExit != null) { - request.addPostParam( - "EndConferenceOnExit", - endConferenceOnExit.toString() - ); + Serializer.toString(request, "EndConferenceOnExit", endConferenceOnExit, ParameterType.URLENCODED); } + + if (waitUrl != null) { - request.addPostParam("WaitUrl", waitUrl.toString()); + Serializer.toString(request, "WaitUrl", waitUrl, ParameterType.URLENCODED); } + + if (waitMethod != null) { - request.addPostParam("WaitMethod", waitMethod.toString()); + Serializer.toString(request, "WaitMethod", waitMethod, ParameterType.URLENCODED); } + + if (earlyMedia != null) { - request.addPostParam("EarlyMedia", earlyMedia.toString()); + Serializer.toString(request, "EarlyMedia", earlyMedia, ParameterType.URLENCODED); } + + if (maxParticipants != null) { - request.addPostParam("MaxParticipants", maxParticipants.toString()); + Serializer.toString(request, "MaxParticipants", maxParticipants, ParameterType.URLENCODED); } + + if (conferenceRecord != null) { - request.addPostParam("ConferenceRecord", conferenceRecord); + Serializer.toString(request, "ConferenceRecord", conferenceRecord, ParameterType.URLENCODED); } + + if (conferenceTrim != null) { - request.addPostParam("ConferenceTrim", conferenceTrim); + Serializer.toString(request, "ConferenceTrim", conferenceTrim, ParameterType.URLENCODED); } + + if (conferenceStatusCallback != null) { - request.addPostParam( - "ConferenceStatusCallback", - conferenceStatusCallback.toString() - ); + Serializer.toString(request, "ConferenceStatusCallback", conferenceStatusCallback, ParameterType.URLENCODED); } + + if (conferenceStatusCallbackMethod != null) { - request.addPostParam( - "ConferenceStatusCallbackMethod", - conferenceStatusCallbackMethod.toString() - ); + Serializer.toString(request, "ConferenceStatusCallbackMethod", conferenceStatusCallbackMethod, ParameterType.URLENCODED); } + + if (conferenceStatusCallbackEvent != null) { - for (String prop : conferenceStatusCallbackEvent) { - request.addPostParam("ConferenceStatusCallbackEvent", prop); + for (String param : conferenceStatusCallbackEvent) { + Serializer.toString(request, "ConferenceStatusCallbackEvent", param, ParameterType.URLENCODED); } } + + if (recordingChannels != null) { - request.addPostParam("RecordingChannels", recordingChannels); + Serializer.toString(request, "RecordingChannels", recordingChannels, ParameterType.URLENCODED); } + + if (recordingStatusCallback != null) { - request.addPostParam( - "RecordingStatusCallback", - recordingStatusCallback.toString() - ); + Serializer.toString(request, "RecordingStatusCallback", recordingStatusCallback, ParameterType.URLENCODED); } + + if (recordingStatusCallbackMethod != null) { - request.addPostParam( - "RecordingStatusCallbackMethod", - recordingStatusCallbackMethod.toString() - ); + Serializer.toString(request, "RecordingStatusCallbackMethod", recordingStatusCallbackMethod, ParameterType.URLENCODED); } + + if (sipAuthUsername != null) { - request.addPostParam("SipAuthUsername", sipAuthUsername); + Serializer.toString(request, "SipAuthUsername", sipAuthUsername, ParameterType.URLENCODED); } + + if (sipAuthPassword != null) { - request.addPostParam("SipAuthPassword", sipAuthPassword); + Serializer.toString(request, "SipAuthPassword", sipAuthPassword, ParameterType.URLENCODED); } + + if (region != null) { - request.addPostParam("Region", region); + Serializer.toString(request, "Region", region, ParameterType.URLENCODED); } + + if (conferenceRecordingStatusCallback != null) { - request.addPostParam( - "ConferenceRecordingStatusCallback", - conferenceRecordingStatusCallback.toString() - ); + Serializer.toString(request, "ConferenceRecordingStatusCallback", conferenceRecordingStatusCallback, ParameterType.URLENCODED); } + + if (conferenceRecordingStatusCallbackMethod != null) { - request.addPostParam( - "ConferenceRecordingStatusCallbackMethod", - conferenceRecordingStatusCallbackMethod.toString() - ); + Serializer.toString(request, "ConferenceRecordingStatusCallbackMethod", conferenceRecordingStatusCallbackMethod, ParameterType.URLENCODED); } + + if (recordingStatusCallbackEvent != null) { - for (String prop : recordingStatusCallbackEvent) { - request.addPostParam("RecordingStatusCallbackEvent", prop); + for (String param : recordingStatusCallbackEvent) { + Serializer.toString(request, "RecordingStatusCallbackEvent", param, ParameterType.URLENCODED); } } + + if (conferenceRecordingStatusCallbackEvent != null) { - for (String prop : conferenceRecordingStatusCallbackEvent) { - request.addPostParam( - "ConferenceRecordingStatusCallbackEvent", - prop - ); + for (String param : conferenceRecordingStatusCallbackEvent) { + Serializer.toString(request, "ConferenceRecordingStatusCallbackEvent", param, ParameterType.URLENCODED); } } + + if (coaching != null) { - request.addPostParam("Coaching", coaching.toString()); + Serializer.toString(request, "Coaching", coaching, ParameterType.URLENCODED); } + + if (callSidToCoach != null) { - request.addPostParam("CallSidToCoach", callSidToCoach); + Serializer.toString(request, "CallSidToCoach", callSidToCoach, ParameterType.URLENCODED); } + + if (jitterBufferSize != null) { - request.addPostParam("JitterBufferSize", jitterBufferSize); + Serializer.toString(request, "JitterBufferSize", jitterBufferSize, ParameterType.URLENCODED); } + + if (byoc != null) { - request.addPostParam("Byoc", byoc); + Serializer.toString(request, "Byoc", byoc, ParameterType.URLENCODED); } + + if (callerId != null) { - request.addPostParam("CallerId", callerId); + Serializer.toString(request, "CallerId", callerId, ParameterType.URLENCODED); } + + if (callReason != null) { - request.addPostParam("CallReason", callReason); + Serializer.toString(request, "CallReason", callReason, ParameterType.URLENCODED); } + + if (recordingTrack != null) { - request.addPostParam("RecordingTrack", recordingTrack); + Serializer.toString(request, "RecordingTrack", recordingTrack, ParameterType.URLENCODED); } + + if (timeLimit != null) { - request.addPostParam("TimeLimit", timeLimit.toString()); + Serializer.toString(request, "TimeLimit", timeLimit, ParameterType.URLENCODED); } + + if (machineDetection != null) { - request.addPostParam("MachineDetection", machineDetection); + Serializer.toString(request, "MachineDetection", machineDetection, ParameterType.URLENCODED); } + + if (machineDetectionTimeout != null) { - request.addPostParam( - "MachineDetectionTimeout", - machineDetectionTimeout.toString() - ); + Serializer.toString(request, "MachineDetectionTimeout", machineDetectionTimeout, ParameterType.URLENCODED); } + + if (machineDetectionSpeechThreshold != null) { - request.addPostParam( - "MachineDetectionSpeechThreshold", - machineDetectionSpeechThreshold.toString() - ); + Serializer.toString(request, "MachineDetectionSpeechThreshold", machineDetectionSpeechThreshold, ParameterType.URLENCODED); } + + if (machineDetectionSpeechEndThreshold != null) { - request.addPostParam( - "MachineDetectionSpeechEndThreshold", - machineDetectionSpeechEndThreshold.toString() - ); + Serializer.toString(request, "MachineDetectionSpeechEndThreshold", machineDetectionSpeechEndThreshold, ParameterType.URLENCODED); } + + if (machineDetectionSilenceTimeout != null) { - request.addPostParam( - "MachineDetectionSilenceTimeout", - machineDetectionSilenceTimeout.toString() - ); + Serializer.toString(request, "MachineDetectionSilenceTimeout", machineDetectionSilenceTimeout, ParameterType.URLENCODED); } + + if (amdStatusCallback != null) { - request.addPostParam( - "AmdStatusCallback", - amdStatusCallback.toString() - ); + Serializer.toString(request, "AmdStatusCallback", amdStatusCallback, ParameterType.URLENCODED); } + + if (amdStatusCallbackMethod != null) { - request.addPostParam( - "AmdStatusCallbackMethod", - amdStatusCallbackMethod.toString() - ); + Serializer.toString(request, "AmdStatusCallbackMethod", amdStatusCallbackMethod, ParameterType.URLENCODED); } + + if (trim != null) { - request.addPostParam("Trim", trim); + Serializer.toString(request, "Trim", trim, ParameterType.URLENCODED); } + + if (callToken != null) { - request.addPostParam("CallToken", callToken); + Serializer.toString(request, "CallToken", callToken, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/conference/ParticipantDeleter.java b/src/main/java/com/twilio/rest/api/v2010/account/conference/ParticipantDeleter.java index 08dc374e73..bdc0b1602f 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/conference/ParticipantDeleter.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/conference/ParticipantDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.api.v2010.account.conference; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,71 +26,50 @@ public class ParticipantDeleter extends Deleter { - private String pathConferenceSid; - private String pathCallSid; - private String pathAccountSid; + private String pathaccountSid; + private String pathconferenceSid; + private String pathcallSid; - public ParticipantDeleter( - final String pathConferenceSid, - final String pathCallSid - ) { - this.pathConferenceSid = pathConferenceSid; - this.pathCallSid = pathCallSid; + public ParticipantDeleter(final String pathconferenceSid, final String pathcallSid) { + this.pathconferenceSid = pathconferenceSid; + this.pathcallSid = pathcallSid; } - public ParticipantDeleter( - final String pathAccountSid, - final String pathConferenceSid, - final String pathCallSid - ) { - this.pathAccountSid = pathAccountSid; - this.pathConferenceSid = pathConferenceSid; - this.pathCallSid = pathCallSid; + public ParticipantDeleter(final String pathaccountSid, final String pathconferenceSid, final String pathcallSid) { + this.pathaccountSid = pathaccountSid; + this.pathconferenceSid = pathconferenceSid; + this.pathcallSid = pathcallSid; } + @Override public boolean delete(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/Conferences/{ConferenceSid}/Participants/{CallSid}.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = - path.replace( - "{" + "ConferenceSid" + "}", - this.pathConferenceSid.toString() - ); - path = path.replace("{" + "CallSid" + "}", this.pathCallSid.toString()); + String path = "/2010-04-01/Accounts/{AccountSid}/Conferences/{ConferenceSid}/Participants/{CallSid}.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "ConferenceSid" + "}", this.pathconferenceSid.toString()); + path = path.replace("{" + "CallSid" + "}", this.pathcallSid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.API.toString(), - path + HttpMethod.DELETE, + Domains.API.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Participant delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("Participant delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/conference/ParticipantFetcher.java b/src/main/java/com/twilio/rest/api/v2010/account/conference/ParticipantFetcher.java index 7018a8030e..b295727512 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/conference/ParticipantFetcher.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/conference/ParticipantFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.api.v2010.account.conference; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,78 +26,53 @@ public class ParticipantFetcher extends Fetcher { - private String pathConferenceSid; - private String pathCallSid; - private String pathAccountSid; + private String pathaccountSid; + private String pathconferenceSid; + private String pathcallSid; - public ParticipantFetcher( - final String pathConferenceSid, - final String pathCallSid - ) { - this.pathConferenceSid = pathConferenceSid; - this.pathCallSid = pathCallSid; + public ParticipantFetcher(final String pathconferenceSid, final String pathcallSid) { + this.pathconferenceSid = pathconferenceSid; + this.pathcallSid = pathcallSid; } - public ParticipantFetcher( - final String pathAccountSid, - final String pathConferenceSid, - final String pathCallSid - ) { - this.pathAccountSid = pathAccountSid; - this.pathConferenceSid = pathConferenceSid; - this.pathCallSid = pathCallSid; + public ParticipantFetcher(final String pathaccountSid, final String pathconferenceSid, final String pathcallSid) { + this.pathaccountSid = pathaccountSid; + this.pathconferenceSid = pathconferenceSid; + this.pathcallSid = pathcallSid; } + @Override public Participant fetch(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/Conferences/{ConferenceSid}/Participants/{CallSid}.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = - path.replace( - "{" + "ConferenceSid" + "}", - this.pathConferenceSid.toString() - ); - path = path.replace("{" + "CallSid" + "}", this.pathCallSid.toString()); + String path = "/2010-04-01/Accounts/{AccountSid}/Conferences/{ConferenceSid}/Participants/{CallSid}.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "ConferenceSid" + "}", this.pathconferenceSid.toString()); + path = path.replace("{" + "CallSid" + "}", this.pathcallSid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.API.toString(), - path + HttpMethod.GET, + Domains.API.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Participant fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Participant fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return Participant.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Participant.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/conference/ParticipantReader.java b/src/main/java/com/twilio/rest/api/v2010/account/conference/ParticipantReader.java index bd90d764c4..ef2949a154 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/conference/ParticipantReader.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/conference/ParticipantReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,161 +30,132 @@ public class ParticipantReader extends Reader { - private String pathConferenceSid; - private String pathAccountSid; + private String pathaccountSid; + private String pathconferenceSid; private Boolean muted; private Boolean hold; private Boolean coaching; private Long pageSize; - public ParticipantReader(final String pathConferenceSid) { - this.pathConferenceSid = pathConferenceSid; + public ParticipantReader(final String pathconferenceSid) { + this.pathconferenceSid = pathconferenceSid; } - public ParticipantReader( - final String pathAccountSid, - final String pathConferenceSid - ) { - this.pathAccountSid = pathAccountSid; - this.pathConferenceSid = pathConferenceSid; + public ParticipantReader(final String pathaccountSid, final String pathconferenceSid) { + this.pathaccountSid = pathaccountSid; + this.pathconferenceSid = pathconferenceSid; } + public ParticipantReader setMuted(final Boolean muted) { this.muted = muted; return this; } + public ParticipantReader setHold(final Boolean hold) { this.hold = hold; return this; } + public ParticipantReader setCoaching(final Boolean coaching) { this.coaching = coaching; return this; } + public ParticipantReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/Conferences/{ConferenceSid}/Participants.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = - path.replace( - "{" + "ConferenceSid" + "}", - this.pathConferenceSid.toString() - ); + + String path = "/2010-04-01/Accounts/{AccountSid}/Conferences/{ConferenceSid}/Participants.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "ConferenceSid" + "}", this.pathconferenceSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.API.toString(), - path + HttpMethod.GET, + Domains.API.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Participant read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Participant read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "participants", - response.getContent(), - Participant.class, - client.getObjectMapper() - ); + "participants", + response.getContent(), + Participant.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.API.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.API.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (muted != null) { - request.addQueryParam("Muted", muted.toString()); + Serializer.toString(request, "Muted", muted, ParameterType.QUERY); } + + if (hold != null) { - request.addQueryParam("Hold", hold.toString()); + Serializer.toString(request, "Hold", hold, ParameterType.QUERY); } + + if (coaching != null) { - request.addQueryParam("Coaching", coaching.toString()); + Serializer.toString(request, "Coaching", coaching, ParameterType.QUERY); } + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/conference/ParticipantUpdater.java b/src/main/java/com/twilio/rest/api/v2010/account/conference/ParticipantUpdater.java index 4af451cb53..1cc3ec2355 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/conference/ParticipantUpdater.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/conference/ParticipantUpdater.java @@ -16,7 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; -import com.twilio.converter.Promoter; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,13 +26,13 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.net.URI; public class ParticipantUpdater extends Updater { - - private String pathConferenceSid; - private String pathCallSid; - private String pathAccountSid; + private String pathaccountSid; + private String pathconferenceSid; + private String pathcallSid; private Boolean muted; private Boolean hold; private URI holdUrl; @@ -45,192 +46,188 @@ public class ParticipantUpdater extends Updater { private Boolean coaching; private String callSidToCoach; - public ParticipantUpdater( - final String pathConferenceSid, - final String pathCallSid - ) { - this.pathConferenceSid = pathConferenceSid; - this.pathCallSid = pathCallSid; + public ParticipantUpdater(final String pathconferenceSid, final String pathcallSid) { + this.pathconferenceSid = pathconferenceSid; + this.pathcallSid = pathcallSid; } - public ParticipantUpdater( - final String pathAccountSid, - final String pathConferenceSid, - final String pathCallSid - ) { - this.pathAccountSid = pathAccountSid; - this.pathConferenceSid = pathConferenceSid; - this.pathCallSid = pathCallSid; + public ParticipantUpdater(final String pathaccountSid, final String pathconferenceSid, final String pathcallSid) { + this.pathaccountSid = pathaccountSid; + this.pathconferenceSid = pathconferenceSid; + this.pathcallSid = pathcallSid; } + public ParticipantUpdater setMuted(final Boolean muted) { this.muted = muted; return this; } + public ParticipantUpdater setHold(final Boolean hold) { this.hold = hold; return this; } + public ParticipantUpdater setHoldUrl(final URI holdUrl) { this.holdUrl = holdUrl; return this; } - public ParticipantUpdater setHoldUrl(final String holdUrl) { - return setHoldUrl(Promoter.uriFromString(holdUrl)); - } public ParticipantUpdater setHoldMethod(final HttpMethod holdMethod) { this.holdMethod = holdMethod; return this; } + public ParticipantUpdater setAnnounceUrl(final URI announceUrl) { this.announceUrl = announceUrl; return this; } - public ParticipantUpdater setAnnounceUrl(final String announceUrl) { - return setAnnounceUrl(Promoter.uriFromString(announceUrl)); - } - public ParticipantUpdater setAnnounceMethod( - final HttpMethod announceMethod - ) { + public ParticipantUpdater setAnnounceMethod(final HttpMethod announceMethod) { this.announceMethod = announceMethod; return this; } + public ParticipantUpdater setWaitUrl(final URI waitUrl) { this.waitUrl = waitUrl; return this; } - public ParticipantUpdater setWaitUrl(final String waitUrl) { - return setWaitUrl(Promoter.uriFromString(waitUrl)); - } public ParticipantUpdater setWaitMethod(final HttpMethod waitMethod) { this.waitMethod = waitMethod; return this; } + public ParticipantUpdater setBeepOnExit(final Boolean beepOnExit) { this.beepOnExit = beepOnExit; return this; } - public ParticipantUpdater setEndConferenceOnExit( - final Boolean endConferenceOnExit - ) { + + public ParticipantUpdater setEndConferenceOnExit(final Boolean endConferenceOnExit) { this.endConferenceOnExit = endConferenceOnExit; return this; } + public ParticipantUpdater setCoaching(final Boolean coaching) { this.coaching = coaching; return this; } + public ParticipantUpdater setCallSidToCoach(final String callSidToCoach) { this.callSidToCoach = callSidToCoach; return this; } + @Override public Participant update(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/Conferences/{ConferenceSid}/Participants/{CallSid}.json"; - - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = - path.replace( - "{" + "ConferenceSid" + "}", - this.pathConferenceSid.toString() - ); - path = path.replace("{" + "CallSid" + "}", this.pathCallSid.toString()); + + String path = "/2010-04-01/Accounts/{AccountSid}/Conferences/{ConferenceSid}/Participants/{CallSid}.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "ConferenceSid" + "}", this.pathconferenceSid.toString()); + path = path.replace("{" + "CallSid" + "}", this.pathcallSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.API.toString(), - path + HttpMethod.POST, + Domains.API.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Participant update failed: Unable to connect to server" - ); + throw new ApiConnectionException("Participant update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Participant.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Participant.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (muted != null) { - request.addPostParam("Muted", muted.toString()); + Serializer.toString(request, "Muted", muted, ParameterType.URLENCODED); } + + if (hold != null) { - request.addPostParam("Hold", hold.toString()); + Serializer.toString(request, "Hold", hold, ParameterType.URLENCODED); } + + if (holdUrl != null) { - request.addPostParam("HoldUrl", holdUrl.toString()); + Serializer.toString(request, "HoldUrl", holdUrl, ParameterType.URLENCODED); } + + if (holdMethod != null) { - request.addPostParam("HoldMethod", holdMethod.toString()); + Serializer.toString(request, "HoldMethod", holdMethod, ParameterType.URLENCODED); } + + if (announceUrl != null) { - request.addPostParam("AnnounceUrl", announceUrl.toString()); + Serializer.toString(request, "AnnounceUrl", announceUrl, ParameterType.URLENCODED); } + + if (announceMethod != null) { - request.addPostParam("AnnounceMethod", announceMethod.toString()); + Serializer.toString(request, "AnnounceMethod", announceMethod, ParameterType.URLENCODED); } + + if (waitUrl != null) { - request.addPostParam("WaitUrl", waitUrl.toString()); + Serializer.toString(request, "WaitUrl", waitUrl, ParameterType.URLENCODED); } + + if (waitMethod != null) { - request.addPostParam("WaitMethod", waitMethod.toString()); + Serializer.toString(request, "WaitMethod", waitMethod, ParameterType.URLENCODED); } + + if (beepOnExit != null) { - request.addPostParam("BeepOnExit", beepOnExit.toString()); + Serializer.toString(request, "BeepOnExit", beepOnExit, ParameterType.URLENCODED); } + + if (endConferenceOnExit != null) { - request.addPostParam( - "EndConferenceOnExit", - endConferenceOnExit.toString() - ); + Serializer.toString(request, "EndConferenceOnExit", endConferenceOnExit, ParameterType.URLENCODED); } + + if (coaching != null) { - request.addPostParam("Coaching", coaching.toString()); + Serializer.toString(request, "Coaching", coaching, ParameterType.URLENCODED); } + + if (callSidToCoach != null) { - request.addPostParam("CallSidToCoach", callSidToCoach); + Serializer.toString(request, "CallSidToCoach", callSidToCoach, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/conference/Recording.java b/src/main/java/com/twilio/rest/api/v2010/account/conference/Recording.java index 0a4e1b2876..157501f7e7 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/conference/Recording.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/conference/Recording.java @@ -18,105 +18,142 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.CurrencyDeserializer; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.time.ZonedDateTime; import java.util.Currency; -import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Recording extends Resource { - private static final long serialVersionUID = 71375271651535L; - public static RecordingDeleter deleter( - final String pathConferenceSid, - final String pathSid - ) { - return new RecordingDeleter(pathConferenceSid, pathSid); + public static RecordingDeleter deleter(final String pathconferenceSid, final String pathsid) { + return new RecordingDeleter( + pathconferenceSid, pathsid + ); } - public static RecordingDeleter deleter( - final String pathAccountSid, - final String pathConferenceSid, - final String pathSid - ) { - return new RecordingDeleter(pathAccountSid, pathConferenceSid, pathSid); + + public static RecordingDeleter deleter(final String pathaccountSid, final String pathconferenceSid, final String pathsid) { + return new RecordingDeleter( + pathaccountSid, pathconferenceSid, pathsid + ); } - public static RecordingFetcher fetcher( - final String pathConferenceSid, - final String pathSid - ) { - return new RecordingFetcher(pathConferenceSid, pathSid); + + public static RecordingFetcher fetcher(final String pathconferenceSid, final String pathsid) { + return new RecordingFetcher( + pathconferenceSid, pathsid + ); } - public static RecordingFetcher fetcher( - final String pathAccountSid, - final String pathConferenceSid, - final String pathSid - ) { - return new RecordingFetcher(pathAccountSid, pathConferenceSid, pathSid); + + public static RecordingFetcher fetcher(final String pathaccountSid, final String pathconferenceSid, final String pathsid) { + return new RecordingFetcher( + pathaccountSid, pathconferenceSid, pathsid + ); } - public static RecordingReader reader(final String pathConferenceSid) { - return new RecordingReader(pathConferenceSid); + + public static RecordingReader reader(final String pathconferenceSid) { + return new RecordingReader( + pathconferenceSid + ); } - public static RecordingReader reader( - final String pathAccountSid, - final String pathConferenceSid - ) { - return new RecordingReader(pathAccountSid, pathConferenceSid); + + public static RecordingReader reader(final String pathaccountSid, final String pathconferenceSid) { + return new RecordingReader( + pathaccountSid, pathconferenceSid + ); } - public static RecordingUpdater updater( - final String pathConferenceSid, - final String pathSid, - final Recording.Status status - ) { - return new RecordingUpdater(pathConferenceSid, pathSid, status); + + public static RecordingUpdater updater(final String pathconferenceSid, final String pathsid, final Recording.Status status) { + return new RecordingUpdater( + pathconferenceSid, pathsid, status + ); } - public static RecordingUpdater updater( - final String pathAccountSid, - final String pathConferenceSid, - final String pathSid, - final Recording.Status status - ) { + + public static RecordingUpdater updater(final String pathaccountSid, final String pathconferenceSid, final String pathsid, final Recording.Status status) { return new RecordingUpdater( - pathAccountSid, - pathConferenceSid, - pathSid, - status + pathaccountSid, pathconferenceSid, pathsid, status ); } + + public enum Status { + IN_PROGRESS("in-progress"), + PAUSED("paused"), + STOPPED("stopped"), + PROCESSING("processing"), + COMPLETED("completed"), + ABSENT("absent"); + + private final String value; + + private Status(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static Status forValue(final String value) { + return Promoter.enumFromString(value, Status.values()); + } + } + + public enum Source { + DIAL_VERB("DialVerb"), + CONFERENCE("Conference"), + OUTBOUND_API("OutboundAPI"), + TRUNKING("Trunking"), + RECORD_VERB("RecordVerb"), + START_CALL_RECORDING_API("StartCallRecordingAPI"), + START_CONFERENCE_RECORDING_API("StartConferenceRecordingAPI"); + + private final String value; + + private Source(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static Source forValue(final String value) { + return Promoter.enumFromString(value, Source.values()); + } + } + + /** * Converts a JSON String into a Recording object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Recording object represented by the provided JSON */ - public static Recording fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Recording fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Recording.class); @@ -131,14 +168,11 @@ public static Recording fromJson( * Converts a JSON InputStream into a Recording object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Recording object represented by the provided JSON */ - public static Recording fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Recording fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Recording.class); @@ -149,136 +183,97 @@ public static Recording fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; + @Getter private final String apiVersion; + @Getter private final String callSid; + @Getter + private final Integer channels; + @Getter private final String conferenceSid; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; - private final ZonedDateTime startTime; + @Getter private final String duration; - private final String sid; + @Getter + private final Object encryptionDetails; + @Getter + private final Integer errorCode; + @Getter private final String price; + @Getter private final Currency priceUnit; - private final Recording.Status status; - private final Integer channels; + @Getter + private final String sid; + @Getter private final Recording.Source source; - private final Integer errorCode; - private final Map encryptionDetails; + @Getter + private final ZonedDateTime startTime; + @Getter + private final Recording.Status status; + @Getter private final String uri; @JsonCreator private Recording( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("api_version") final String apiVersion, - @JsonProperty("call_sid") final String callSid, - @JsonProperty("conference_sid") final String conferenceSid, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("start_time") final String startTime, - @JsonProperty("duration") final String duration, - @JsonProperty("sid") final String sid, - @JsonProperty("price") final String price, - @JsonProperty("price_unit") @JsonDeserialize( - using = com.twilio.converter.CurrencyDeserializer.class - ) final Currency priceUnit, - @JsonProperty("status") final Recording.Status status, - @JsonProperty("channels") final Integer channels, - @JsonProperty("source") final Recording.Source source, - @JsonProperty("error_code") final Integer errorCode, - @JsonProperty("encryption_details") final Map< - String, - Object - > encryptionDetails, - @JsonProperty("uri") final String uri + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("api_version") final String apiVersion, + @JsonProperty("call_sid") final String callSid, + @JsonProperty("channels") final Integer channels, + @JsonProperty("conference_sid") final String conferenceSid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.RFC2822Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.RFC2822Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("duration") final String duration, + @JsonProperty("encryption_details") final Object encryptionDetails, + @JsonProperty("error_code") final Integer errorCode, + @JsonProperty("price") final String price, + @JsonProperty("price_unit") + @JsonDeserialize(using = com.twilio.converter.CurrencyDeserializer.class) final Currency priceUnit, + @JsonProperty("sid") final String sid, + @JsonProperty("source") final Recording.Source source, + @JsonProperty("start_time") + @JsonDeserialize(using = com.twilio.converter.RFC2822Deserializer.class) final ZonedDateTime startTime, + @JsonProperty("status") final Recording.Status status, + @JsonProperty("uri") final String uri ) { this.accountSid = accountSid; this.apiVersion = apiVersion; this.callSid = callSid; + this.channels = channels; this.conferenceSid = conferenceSid; - this.dateCreated = DateConverter.rfc2822DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.rfc2822DateTimeFromString(dateUpdated); - this.startTime = DateConverter.rfc2822DateTimeFromString(startTime); + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.duration = duration; - this.sid = sid; + this.encryptionDetails = encryptionDetails; + this.errorCode = errorCode; this.price = price; this.priceUnit = priceUnit; - this.status = status; - this.channels = channels; + this.sid = sid; this.source = source; - this.errorCode = errorCode; - this.encryptionDetails = encryptionDetails; + this.startTime = startTime; + this.status = status; this.uri = uri; } - public final String getAccountSid() { - return this.accountSid; - } - - public final String getApiVersion() { - return this.apiVersion; - } - - public final String getCallSid() { - return this.callSid; - } - - public final String getConferenceSid() { - return this.conferenceSid; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final ZonedDateTime getStartTime() { - return this.startTime; - } - - public final String getDuration() { - return this.duration; - } - - public final String getSid() { - return this.sid; - } - - public final String getPrice() { - return this.price; - } - - public final Currency getPriceUnit() { - return this.priceUnit; - } - - public final Recording.Status getStatus() { - return this.status; - } - - public final Integer getChannels() { - return this.channels; - } - - public final Recording.Source getSource() { - return this.source; - } - - public final Integer getErrorCode() { - return this.errorCode; - } - - public final Map getEncryptionDetails() { - return this.encryptionDetails; - } - - public final String getUri() { - return this.uri; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -290,97 +285,50 @@ public boolean equals(final Object o) { } Recording other = (Recording) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(apiVersion, other.apiVersion) && - Objects.equals(callSid, other.callSid) && - Objects.equals(conferenceSid, other.conferenceSid) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(startTime, other.startTime) && - Objects.equals(duration, other.duration) && - Objects.equals(sid, other.sid) && - Objects.equals(price, other.price) && - Objects.equals(priceUnit, other.priceUnit) && - Objects.equals(status, other.status) && - Objects.equals(channels, other.channels) && - Objects.equals(source, other.source) && - Objects.equals(errorCode, other.errorCode) && - Objects.equals(encryptionDetails, other.encryptionDetails) && - Objects.equals(uri, other.uri) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(apiVersion, other.apiVersion) && + Objects.equals(callSid, other.callSid) && + Objects.equals(channels, other.channels) && + Objects.equals(conferenceSid, other.conferenceSid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(duration, other.duration) && + Objects.equals(encryptionDetails, other.encryptionDetails) && + Objects.equals(errorCode, other.errorCode) && + Objects.equals(price, other.price) && + Objects.equals(priceUnit, other.priceUnit) && + Objects.equals(sid, other.sid) && + Objects.equals(source, other.source) && + Objects.equals(startTime, other.startTime) && + Objects.equals(status, other.status) && + Objects.equals(uri, other.uri) ); } @Override public int hashCode() { return Objects.hash( - accountSid, - apiVersion, - callSid, - conferenceSid, - dateCreated, - dateUpdated, - startTime, - duration, - sid, - price, - priceUnit, - status, - channels, - source, - errorCode, - encryptionDetails, - uri + accountSid, + apiVersion, + callSid, + channels, + conferenceSid, + dateCreated, + dateUpdated, + duration, + encryptionDetails, + errorCode, + price, + priceUnit, + sid, + source, + startTime, + status, + uri ); } - public enum Source { - DIALVERB("DialVerb"), - CONFERENCE("Conference"), - OUTBOUNDAPI("OutboundAPI"), - TRUNKING("Trunking"), - RECORDVERB("RecordVerb"), - STARTCALLRECORDINGAPI("StartCallRecordingAPI"), - STARTCONFERENCERECORDINGAPI("StartConferenceRecordingAPI"); - - private final String value; - - private Source(final String value) { - this.value = value; - } - public String toString() { - return value; - } - - @JsonCreator - public static Source forValue(final String value) { - return Promoter.enumFromString(value, Source.values()); - } - } - - public enum Status { - IN_PROGRESS("in-progress"), - PAUSED("paused"), - STOPPED("stopped"), - PROCESSING("processing"), - COMPLETED("completed"), - ABSENT("absent"); - - private final String value; - - private Status(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static Status forValue(final String value) { - return Promoter.enumFromString(value, Status.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/api/v2010/account/conference/RecordingDeleter.java b/src/main/java/com/twilio/rest/api/v2010/account/conference/RecordingDeleter.java index 880c59412d..a4c0f3bee5 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/conference/RecordingDeleter.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/conference/RecordingDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.api.v2010.account.conference; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,71 +26,50 @@ public class RecordingDeleter extends Deleter { - private String pathConferenceSid; - private String pathSid; - private String pathAccountSid; + private String pathaccountSid; + private String pathconferenceSid; + private String pathsid; - public RecordingDeleter( - final String pathConferenceSid, - final String pathSid - ) { - this.pathConferenceSid = pathConferenceSid; - this.pathSid = pathSid; + public RecordingDeleter(final String pathconferenceSid, final String pathsid) { + this.pathconferenceSid = pathconferenceSid; + this.pathsid = pathsid; } - public RecordingDeleter( - final String pathAccountSid, - final String pathConferenceSid, - final String pathSid - ) { - this.pathAccountSid = pathAccountSid; - this.pathConferenceSid = pathConferenceSid; - this.pathSid = pathSid; + public RecordingDeleter(final String pathaccountSid, final String pathconferenceSid, final String pathsid) { + this.pathaccountSid = pathaccountSid; + this.pathconferenceSid = pathconferenceSid; + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/Conferences/{ConferenceSid}/Recordings/{Sid}.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = - path.replace( - "{" + "ConferenceSid" + "}", - this.pathConferenceSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/2010-04-01/Accounts/{AccountSid}/Conferences/{ConferenceSid}/Recordings/{Sid}.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "ConferenceSid" + "}", this.pathconferenceSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.API.toString(), - path + HttpMethod.DELETE, + Domains.API.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Recording delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("Recording delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/conference/RecordingFetcher.java b/src/main/java/com/twilio/rest/api/v2010/account/conference/RecordingFetcher.java index dca193037a..cc085a2b57 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/conference/RecordingFetcher.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/conference/RecordingFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.api.v2010.account.conference; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,78 +26,53 @@ public class RecordingFetcher extends Fetcher { - private String pathConferenceSid; - private String pathSid; - private String pathAccountSid; + private String pathaccountSid; + private String pathconferenceSid; + private String pathsid; - public RecordingFetcher( - final String pathConferenceSid, - final String pathSid - ) { - this.pathConferenceSid = pathConferenceSid; - this.pathSid = pathSid; + public RecordingFetcher(final String pathconferenceSid, final String pathsid) { + this.pathconferenceSid = pathconferenceSid; + this.pathsid = pathsid; } - public RecordingFetcher( - final String pathAccountSid, - final String pathConferenceSid, - final String pathSid - ) { - this.pathAccountSid = pathAccountSid; - this.pathConferenceSid = pathConferenceSid; - this.pathSid = pathSid; + public RecordingFetcher(final String pathaccountSid, final String pathconferenceSid, final String pathsid) { + this.pathaccountSid = pathaccountSid; + this.pathconferenceSid = pathconferenceSid; + this.pathsid = pathsid; } + @Override public Recording fetch(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/Conferences/{ConferenceSid}/Recordings/{Sid}.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = - path.replace( - "{" + "ConferenceSid" + "}", - this.pathConferenceSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/2010-04-01/Accounts/{AccountSid}/Conferences/{ConferenceSid}/Recordings/{Sid}.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "ConferenceSid" + "}", this.pathconferenceSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.API.toString(), - path + HttpMethod.GET, + Domains.API.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Recording fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Recording fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return Recording.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Recording.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/conference/RecordingReader.java b/src/main/java/com/twilio/rest/api/v2010/account/conference/RecordingReader.java index ba707074cd..47d751a5b2 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/conference/RecordingReader.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/conference/RecordingReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -26,177 +27,137 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.time.LocalDate; -import java.time.format.DateTimeFormatter; public class RecordingReader extends Reader { - private String pathConferenceSid; - private String pathAccountSid; + private String pathaccountSid; + private String pathconferenceSid; private LocalDate dateCreated; private LocalDate dateCreatedBefore; private LocalDate dateCreatedAfter; private Long pageSize; - public RecordingReader(final String pathConferenceSid) { - this.pathConferenceSid = pathConferenceSid; + public RecordingReader(final String pathconferenceSid) { + this.pathconferenceSid = pathconferenceSid; } - public RecordingReader( - final String pathAccountSid, - final String pathConferenceSid - ) { - this.pathAccountSid = pathAccountSid; - this.pathConferenceSid = pathConferenceSid; + public RecordingReader(final String pathaccountSid, final String pathconferenceSid) { + this.pathaccountSid = pathaccountSid; + this.pathconferenceSid = pathconferenceSid; } + public RecordingReader setDateCreated(final LocalDate dateCreated) { this.dateCreated = dateCreated; return this; } - public RecordingReader setDateCreatedBefore( - final LocalDate dateCreatedBefore - ) { + + public RecordingReader setDateCreatedBefore(final LocalDate dateCreatedBefore) { this.dateCreatedBefore = dateCreatedBefore; return this; } - public RecordingReader setDateCreatedAfter( - final LocalDate dateCreatedAfter - ) { + + public RecordingReader setDateCreatedAfter(final LocalDate dateCreatedAfter) { this.dateCreatedAfter = dateCreatedAfter; return this; } + public RecordingReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/Conferences/{ConferenceSid}/Recordings.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = - path.replace( - "{" + "ConferenceSid" + "}", - this.pathConferenceSid.toString() - ); + + String path = "/2010-04-01/Accounts/{AccountSid}/Conferences/{ConferenceSid}/Recordings.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "ConferenceSid" + "}", this.pathconferenceSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.API.toString(), - path + HttpMethod.GET, + Domains.API.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Recording read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Recording read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "recordings", - response.getContent(), - Recording.class, - client.getObjectMapper() - ); + "recordings", + response.getContent(), + Recording.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.API.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.API.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (dateCreated != null) { - request.addQueryParam( - "DateCreated", - dateCreated.format( - DateTimeFormatter.ofPattern( - Request.QUERY_STRING_DATE_FORMAT - ) - ) - ); - } else if (dateCreatedAfter != null || dateCreatedBefore != null) { - request.addQueryDateRange( - "DateCreated", - dateCreatedAfter, - dateCreatedBefore - ); + Serializer.toString(request, "DateCreated", dateCreated, ParameterType.QUERY); } - if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + + + if (dateCreatedBefore != null) { + Serializer.toString(request, "DateCreated<", dateCreatedBefore, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); + + if (dateCreatedAfter != null) { + Serializer.toString(request, "DateCreated>", dateCreatedAfter, ParameterType.QUERY); } + + + if (pageSize != null) { + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); + } + + } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/conference/RecordingUpdater.java b/src/main/java/com/twilio/rest/api/v2010/account/conference/RecordingUpdater.java index 12589bcad7..492a6ea2c7 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/conference/RecordingUpdater.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/conference/RecordingUpdater.java @@ -16,6 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -26,105 +28,86 @@ import com.twilio.rest.Domains; public class RecordingUpdater extends Updater { - - private String pathConferenceSid; - private String pathSid; + private String pathaccountSid; + private String pathconferenceSid; + private String pathsid; private Recording.Status status; - private String pathAccountSid; private String pauseBehavior; - public RecordingUpdater( - final String pathConferenceSid, - final String pathSid, - final Recording.Status status - ) { - this.pathConferenceSid = pathConferenceSid; - this.pathSid = pathSid; + public RecordingUpdater(final String pathconferenceSid, final String pathsid, final Recording.Status status) { + this.pathconferenceSid = pathconferenceSid; + this.pathsid = pathsid; this.status = status; } - public RecordingUpdater( - final String pathAccountSid, - final String pathConferenceSid, - final String pathSid, - final Recording.Status status - ) { - this.pathAccountSid = pathAccountSid; - this.pathConferenceSid = pathConferenceSid; - this.pathSid = pathSid; + public RecordingUpdater(final String pathaccountSid, final String pathconferenceSid, final String pathsid, final Recording.Status status) { + this.pathaccountSid = pathaccountSid; + this.pathconferenceSid = pathconferenceSid; + this.pathsid = pathsid; this.status = status; } + public RecordingUpdater setStatus(final Recording.Status status) { this.status = status; return this; } + public RecordingUpdater setPauseBehavior(final String pauseBehavior) { this.pauseBehavior = pauseBehavior; return this; } + @Override public Recording update(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/Conferences/{ConferenceSid}/Recordings/{Sid}.json"; - - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = - path.replace( - "{" + "ConferenceSid" + "}", - this.pathConferenceSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); - path = path.replace("{" + "Status" + "}", this.status.toString()); + + String path = "/2010-04-01/Accounts/{AccountSid}/Conferences/{ConferenceSid}/Recordings/{Sid}.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "ConferenceSid" + "}", this.pathconferenceSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.API.toString(), - path + HttpMethod.POST, + Domains.API.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Recording update failed: Unable to connect to server" - ); + throw new ApiConnectionException("Recording update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Recording.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Recording.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (status != null) { - request.addPostParam("Status", status.toString()); + Serializer.toString(request, "Status", status, ParameterType.URLENCODED); } + + if (pauseBehavior != null) { - request.addPostParam("PauseBehavior", pauseBehavior); + Serializer.toString(request, "PauseBehavior", pauseBehavior, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/incomingphonenumber/AssignedAddOn.java b/src/main/java/com/twilio/rest/api/v2010/account/incomingphonenumber/AssignedAddOn.java index 1d00f4ea41..4e66c5731b 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/incomingphonenumber/AssignedAddOn.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/incomingphonenumber/AssignedAddOn.java @@ -18,106 +18,91 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.time.ZonedDateTime; import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class AssignedAddOn extends Resource { - private static final long serialVersionUID = 114193682949091L; - public static AssignedAddOnCreator creator( - final String pathResourceSid, - final String installedAddOnSid - ) { - return new AssignedAddOnCreator(pathResourceSid, installedAddOnSid); + public static AssignedAddOnCreator creator(final String pathresourceSid, final String installedAddOnSid) { + return new AssignedAddOnCreator( + pathresourceSid, installedAddOnSid + ); } - public static AssignedAddOnCreator creator( - final String pathAccountSid, - final String pathResourceSid, - final String installedAddOnSid - ) { + + public static AssignedAddOnCreator creator(final String pathaccountSid, final String pathresourceSid, final String installedAddOnSid) { return new AssignedAddOnCreator( - pathAccountSid, - pathResourceSid, - installedAddOnSid + pathaccountSid, pathresourceSid, installedAddOnSid ); } - public static AssignedAddOnDeleter deleter( - final String pathResourceSid, - final String pathSid - ) { - return new AssignedAddOnDeleter(pathResourceSid, pathSid); + + public static AssignedAddOnDeleter deleter(final String pathresourceSid, final String pathsid) { + return new AssignedAddOnDeleter( + pathresourceSid, pathsid + ); } - public static AssignedAddOnDeleter deleter( - final String pathAccountSid, - final String pathResourceSid, - final String pathSid - ) { + + public static AssignedAddOnDeleter deleter(final String pathaccountSid, final String pathresourceSid, final String pathsid) { return new AssignedAddOnDeleter( - pathAccountSid, - pathResourceSid, - pathSid + pathaccountSid, pathresourceSid, pathsid ); } - public static AssignedAddOnFetcher fetcher( - final String pathResourceSid, - final String pathSid - ) { - return new AssignedAddOnFetcher(pathResourceSid, pathSid); + + public static AssignedAddOnFetcher fetcher(final String pathresourceSid, final String pathsid) { + return new AssignedAddOnFetcher( + pathresourceSid, pathsid + ); } - public static AssignedAddOnFetcher fetcher( - final String pathAccountSid, - final String pathResourceSid, - final String pathSid - ) { + + public static AssignedAddOnFetcher fetcher(final String pathaccountSid, final String pathresourceSid, final String pathsid) { return new AssignedAddOnFetcher( - pathAccountSid, - pathResourceSid, - pathSid + pathaccountSid, pathresourceSid, pathsid ); } - public static AssignedAddOnReader reader(final String pathResourceSid) { - return new AssignedAddOnReader(pathResourceSid); + + public static AssignedAddOnReader reader(final String pathresourceSid) { + return new AssignedAddOnReader( + pathresourceSid + ); } - public static AssignedAddOnReader reader( - final String pathAccountSid, - final String pathResourceSid - ) { - return new AssignedAddOnReader(pathAccountSid, pathResourceSid); + + public static AssignedAddOnReader reader(final String pathaccountSid, final String pathresourceSid) { + return new AssignedAddOnReader( + pathaccountSid, pathresourceSid + ); } + /** * Converts a JSON String into a AssignedAddOn object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return AssignedAddOn object represented by the provided JSON */ - public static AssignedAddOn fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static AssignedAddOn fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, AssignedAddOn.class); @@ -132,14 +117,11 @@ public static AssignedAddOn fromJson( * Converts a JSON InputStream into a AssignedAddOn object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return AssignedAddOn object represented by the provided JSON */ - public static AssignedAddOn fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static AssignedAddOn fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, AssignedAddOn.class); @@ -150,90 +132,69 @@ public static AssignedAddOn fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String resourceSid; - private final String friendlyName; - private final String description; - private final Map configuration; - private final String uniqueName; + @Getter + private final Object configuration; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; - private final String uri; + @Getter + private final String description; + @Getter + private final String friendlyName; + @Getter + private final String resourceSid; + @Getter + private final String sid; + @Getter private final Map subresourceUris; + @Getter + private final String uniqueName; + @Getter + private final String uri; @JsonCreator private AssignedAddOn( - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("resource_sid") final String resourceSid, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("description") final String description, - @JsonProperty("configuration") final Map configuration, - @JsonProperty("unique_name") final String uniqueName, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("uri") final String uri, - @JsonProperty("subresource_uris") final Map< - String, - String - > subresourceUris + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("configuration") final Object configuration, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.RFC2822Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.RFC2822Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("description") final String description, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("resource_sid") final String resourceSid, + @JsonProperty("sid") final String sid, + @JsonProperty("subresource_uris") final Map subresourceUris, + @JsonProperty("unique_name") final String uniqueName, + @JsonProperty("uri") final String uri ) { - this.sid = sid; this.accountSid = accountSid; - this.resourceSid = resourceSid; - this.friendlyName = friendlyName; - this.description = description; this.configuration = configuration; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; + this.description = description; + this.friendlyName = friendlyName; + this.resourceSid = resourceSid; + this.sid = sid; + this.subresourceUris = subresourceUris; this.uniqueName = uniqueName; - this.dateCreated = DateConverter.rfc2822DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.rfc2822DateTimeFromString(dateUpdated); this.uri = uri; - this.subresourceUris = subresourceUris; - } - - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getResourceSid() { - return this.resourceSid; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final String getDescription() { - return this.description; - } - - public final Map getConfiguration() { - return this.configuration; - } - - public final String getUniqueName() { - return this.uniqueName; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final String getUri() { - return this.uri; - } - - public final Map getSubresourceUris() { - return this.subresourceUris; } @Override @@ -247,36 +208,38 @@ public boolean equals(final Object o) { } AssignedAddOn other = (AssignedAddOn) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(resourceSid, other.resourceSid) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(description, other.description) && - Objects.equals(configuration, other.configuration) && - Objects.equals(uniqueName, other.uniqueName) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(uri, other.uri) && - Objects.equals(subresourceUris, other.subresourceUris) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(configuration, other.configuration) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(description, other.description) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(resourceSid, other.resourceSid) && + Objects.equals(sid, other.sid) && + Objects.equals(subresourceUris, other.subresourceUris) && + Objects.equals(uniqueName, other.uniqueName) && + Objects.equals(uri, other.uri) ); } @Override public int hashCode() { return Objects.hash( - sid, - accountSid, - resourceSid, - friendlyName, - description, - configuration, - uniqueName, - dateCreated, - dateUpdated, - uri, - subresourceUris + accountSid, + configuration, + dateCreated, + dateUpdated, + description, + friendlyName, + resourceSid, + sid, + subresourceUris, + uniqueName, + uri ); } + + } + diff --git a/src/main/java/com/twilio/rest/api/v2010/account/incomingphonenumber/AssignedAddOnCreator.java b/src/main/java/com/twilio/rest/api/v2010/account/incomingphonenumber/AssignedAddOnCreator.java index e3ee05883c..d60663d4eb 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/incomingphonenumber/AssignedAddOnCreator.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/incomingphonenumber/AssignedAddOnCreator.java @@ -14,8 +14,11 @@ package com.twilio.rest.api.v2010.account.incomingphonenumber; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,95 +30,70 @@ public class AssignedAddOnCreator extends Creator { - private String pathResourceSid; + private String pathaccountSid; + private String pathresourceSid; private String installedAddOnSid; - private String pathAccountSid; - public AssignedAddOnCreator( - final String pathResourceSid, - final String installedAddOnSid - ) { - this.pathResourceSid = pathResourceSid; + public AssignedAddOnCreator(final String pathresourceSid, final String installedAddOnSid) { + this.pathresourceSid = pathresourceSid; this.installedAddOnSid = installedAddOnSid; } - public AssignedAddOnCreator( - final String pathAccountSid, - final String pathResourceSid, - final String installedAddOnSid - ) { - this.pathAccountSid = pathAccountSid; - this.pathResourceSid = pathResourceSid; + public AssignedAddOnCreator(final String pathaccountSid, final String pathresourceSid, final String installedAddOnSid) { + this.pathaccountSid = pathaccountSid; + this.pathresourceSid = pathresourceSid; this.installedAddOnSid = installedAddOnSid; } - public AssignedAddOnCreator setInstalledAddOnSid( - final String installedAddOnSid - ) { + + public AssignedAddOnCreator setInstalledAddOnSid(final String installedAddOnSid) { this.installedAddOnSid = installedAddOnSid; return this; } + @Override public AssignedAddOn create(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/IncomingPhoneNumbers/{ResourceSid}/AssignedAddOns.json"; - - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = - path.replace( - "{" + "ResourceSid" + "}", - this.pathResourceSid.toString() - ); - path = - path.replace( - "{" + "InstalledAddOnSid" + "}", - this.installedAddOnSid.toString() - ); + + String path = "/2010-04-01/Accounts/{AccountSid}/IncomingPhoneNumbers/{ResourceSid}/AssignedAddOns.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "ResourceSid" + "}", this.pathresourceSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.API.toString(), - path + HttpMethod.POST, + Domains.API.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "AssignedAddOn creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("AssignedAddOn creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return AssignedAddOn.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return AssignedAddOn.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (installedAddOnSid != null) { - request.addPostParam("InstalledAddOnSid", installedAddOnSid); + Serializer.toString(request, "InstalledAddOnSid", installedAddOnSid, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/incomingphonenumber/AssignedAddOnDeleter.java b/src/main/java/com/twilio/rest/api/v2010/account/incomingphonenumber/AssignedAddOnDeleter.java index 6721e8f15b..411a9a841f 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/incomingphonenumber/AssignedAddOnDeleter.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/incomingphonenumber/AssignedAddOnDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.api.v2010.account.incomingphonenumber; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,71 +26,50 @@ public class AssignedAddOnDeleter extends Deleter { - private String pathResourceSid; - private String pathSid; - private String pathAccountSid; + private String pathaccountSid; + private String pathresourceSid; + private String pathsid; - public AssignedAddOnDeleter( - final String pathResourceSid, - final String pathSid - ) { - this.pathResourceSid = pathResourceSid; - this.pathSid = pathSid; + public AssignedAddOnDeleter(final String pathresourceSid, final String pathsid) { + this.pathresourceSid = pathresourceSid; + this.pathsid = pathsid; } - public AssignedAddOnDeleter( - final String pathAccountSid, - final String pathResourceSid, - final String pathSid - ) { - this.pathAccountSid = pathAccountSid; - this.pathResourceSid = pathResourceSid; - this.pathSid = pathSid; + public AssignedAddOnDeleter(final String pathaccountSid, final String pathresourceSid, final String pathsid) { + this.pathaccountSid = pathaccountSid; + this.pathresourceSid = pathresourceSid; + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/IncomingPhoneNumbers/{ResourceSid}/AssignedAddOns/{Sid}.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = - path.replace( - "{" + "ResourceSid" + "}", - this.pathResourceSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/2010-04-01/Accounts/{AccountSid}/IncomingPhoneNumbers/{ResourceSid}/AssignedAddOns/{Sid}.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "ResourceSid" + "}", this.pathresourceSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.API.toString(), - path + HttpMethod.DELETE, + Domains.API.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "AssignedAddOn delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("AssignedAddOn delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/incomingphonenumber/AssignedAddOnFetcher.java b/src/main/java/com/twilio/rest/api/v2010/account/incomingphonenumber/AssignedAddOnFetcher.java index b50a92ee1f..02007463ea 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/incomingphonenumber/AssignedAddOnFetcher.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/incomingphonenumber/AssignedAddOnFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.api.v2010.account.incomingphonenumber; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,78 +26,53 @@ public class AssignedAddOnFetcher extends Fetcher { - private String pathResourceSid; - private String pathSid; - private String pathAccountSid; + private String pathaccountSid; + private String pathresourceSid; + private String pathsid; - public AssignedAddOnFetcher( - final String pathResourceSid, - final String pathSid - ) { - this.pathResourceSid = pathResourceSid; - this.pathSid = pathSid; + public AssignedAddOnFetcher(final String pathresourceSid, final String pathsid) { + this.pathresourceSid = pathresourceSid; + this.pathsid = pathsid; } - public AssignedAddOnFetcher( - final String pathAccountSid, - final String pathResourceSid, - final String pathSid - ) { - this.pathAccountSid = pathAccountSid; - this.pathResourceSid = pathResourceSid; - this.pathSid = pathSid; + public AssignedAddOnFetcher(final String pathaccountSid, final String pathresourceSid, final String pathsid) { + this.pathaccountSid = pathaccountSid; + this.pathresourceSid = pathresourceSid; + this.pathsid = pathsid; } + @Override public AssignedAddOn fetch(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/IncomingPhoneNumbers/{ResourceSid}/AssignedAddOns/{Sid}.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = - path.replace( - "{" + "ResourceSid" + "}", - this.pathResourceSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/2010-04-01/Accounts/{AccountSid}/IncomingPhoneNumbers/{ResourceSid}/AssignedAddOns/{Sid}.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "ResourceSid" + "}", this.pathresourceSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.API.toString(), - path + HttpMethod.GET, + Domains.API.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "AssignedAddOn fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("AssignedAddOn fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return AssignedAddOn.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return AssignedAddOn.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/incomingphonenumber/AssignedAddOnReader.java b/src/main/java/com/twilio/rest/api/v2010/account/incomingphonenumber/AssignedAddOnReader.java index a8200aa055..a15411af56 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/incomingphonenumber/AssignedAddOnReader.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/incomingphonenumber/AssignedAddOnReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,134 +30,96 @@ public class AssignedAddOnReader extends Reader { - private String pathResourceSid; - private String pathAccountSid; + private String pathaccountSid; + private String pathresourceSid; private Long pageSize; - public AssignedAddOnReader(final String pathResourceSid) { - this.pathResourceSid = pathResourceSid; + public AssignedAddOnReader(final String pathresourceSid) { + this.pathresourceSid = pathresourceSid; } - public AssignedAddOnReader( - final String pathAccountSid, - final String pathResourceSid - ) { - this.pathAccountSid = pathAccountSid; - this.pathResourceSid = pathResourceSid; + public AssignedAddOnReader(final String pathaccountSid, final String pathresourceSid) { + this.pathaccountSid = pathaccountSid; + this.pathresourceSid = pathresourceSid; } + public AssignedAddOnReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/IncomingPhoneNumbers/{ResourceSid}/AssignedAddOns.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = - path.replace( - "{" + "ResourceSid" + "}", - this.pathResourceSid.toString() - ); + + String path = "/2010-04-01/Accounts/{AccountSid}/IncomingPhoneNumbers/{ResourceSid}/AssignedAddOns.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "ResourceSid" + "}", this.pathresourceSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.API.toString(), - path + HttpMethod.GET, + Domains.API.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "AssignedAddOn read failed: Unable to connect to server" - ); + throw new ApiConnectionException("AssignedAddOn read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "assigned_add_ons", - response.getContent(), - AssignedAddOn.class, - client.getObjectMapper() - ); + "assigned_add_ons", + response.getContent(), + AssignedAddOn.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.API.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.API.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/incomingphonenumber/Local.java b/src/main/java/com/twilio/rest/api/v2010/account/incomingphonenumber/Local.java index 801ff7fc75..a33d3673f7 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/incomingphonenumber/Local.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/incomingphonenumber/Local.java @@ -18,61 +18,153 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.http.HttpMethod; import com.twilio.type.PhoneNumberCapabilities; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Local extends Resource { - private static final long serialVersionUID = 226189121371341L; - public static LocalCreator creator( - final com.twilio.type.PhoneNumber phoneNumber - ) { - return new LocalCreator(phoneNumber); + public static LocalCreator creator(final com.twilio.type.PhoneNumber phoneNumber) { + return new LocalCreator( + phoneNumber + ); } - public static LocalCreator creator( - final String pathAccountSid, - final com.twilio.type.PhoneNumber phoneNumber - ) { - return new LocalCreator(pathAccountSid, phoneNumber); + + public static LocalCreator creator(final String pathaccountSid, final com.twilio.type.PhoneNumber phoneNumber) { + return new LocalCreator( + pathaccountSid, phoneNumber + ); } + public static LocalReader reader() { - return new LocalReader(); + return new LocalReader( + + ); + } + + + public static LocalReader reader(final String pathaccountSid) { + return new LocalReader( + pathaccountSid + ); + } + + + public enum EmergencyAddressStatus { + REGISTERED("registered"), + UNREGISTERED("unregistered"), + PENDING_REGISTRATION("pending-registration"), + REGISTRATION_FAILURE("registration-failure"), + PENDING_UNREGISTRATION("pending-unregistration"), + UNREGISTRATION_FAILURE("unregistration-failure"); + + private final String value; + + private EmergencyAddressStatus(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static EmergencyAddressStatus forValue(final String value) { + return Promoter.enumFromString(value, EmergencyAddressStatus.values()); + } + } + + public enum VoiceReceiveMode { + VOICE("voice"), + FAX("fax"); + + private final String value; + + private VoiceReceiveMode(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static VoiceReceiveMode forValue(final String value) { + return Promoter.enumFromString(value, VoiceReceiveMode.values()); + } + } + + public enum EmergencyStatus { + ACTIVE("Active"), + INACTIVE("Inactive"); + + private final String value; + + private EmergencyStatus(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static EmergencyStatus forValue(final String value) { + return Promoter.enumFromString(value, EmergencyStatus.values()); + } } - public static LocalReader reader(final String pathAccountSid) { - return new LocalReader(pathAccountSid); + public enum AddressRequirement { + NONE("none"), + ANY("any"), + LOCAL("local"), + FOREIGN("foreign"); + + private final String value; + + private AddressRequirement(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static AddressRequirement forValue(final String value) { + return Promoter.enumFromString(value, AddressRequirement.values()); + } } + /** * Converts a JSON String into a Local object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Local object represented by the provided JSON */ - public static Local fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Local fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Local.class); @@ -87,14 +179,11 @@ public static Local fromJson( * Converts a JSON InputStream into a Local object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Local object represented by the provided JSON */ - public static Local fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Local fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Local.class); @@ -105,266 +194,161 @@ public static Local fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String addressSid; + @Getter private final Local.AddressRequirement addressRequirements; + @Getter + private final String addressSid; + @Getter private final String apiVersion; + @Getter private final Boolean beta; + @Getter + private final String bundleSid; + @Getter private final PhoneNumberCapabilities capabilities; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; + @Getter + private final String emergencyAddressSid; + @Getter + private final Local.EmergencyAddressStatus emergencyAddressStatus; + @Getter + private final Local.EmergencyStatus emergencyStatus; + @Getter private final String friendlyName; + @Getter private final String identitySid; - private final com.twilio.type.PhoneNumber phoneNumber; + @Getter private final String origin; + @Getter + private final com.twilio.type.PhoneNumber phoneNumber; + @Getter private final String sid; + @Getter private final String smsApplicationSid; + @Getter private final HttpMethod smsFallbackMethod; + @Getter private final URI smsFallbackUrl; + @Getter private final HttpMethod smsMethod; + @Getter private final URI smsUrl; + @Getter + private final String status; + @Getter private final URI statusCallback; + @Getter private final HttpMethod statusCallbackMethod; + @Getter private final String trunkSid; + @Getter private final String uri; - private final Local.VoiceReceiveMode voiceReceiveMode; + @Getter private final String voiceApplicationSid; + @Getter private final Boolean voiceCallerIdLookup; + @Getter private final HttpMethod voiceFallbackMethod; + @Getter private final URI voiceFallbackUrl; + @Getter private final HttpMethod voiceMethod; + @Getter + private final Local.VoiceReceiveMode voiceReceiveMode; + @Getter private final URI voiceUrl; - private final Local.EmergencyStatus emergencyStatus; - private final String emergencyAddressSid; - private final Local.EmergencyAddressStatus emergencyAddressStatus; - private final String bundleSid; - private final String status; @JsonCreator private Local( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("address_sid") final String addressSid, - @JsonProperty( - "address_requirements" - ) final Local.AddressRequirement addressRequirements, - @JsonProperty("api_version") final String apiVersion, - @JsonProperty("beta") final Boolean beta, - @JsonProperty( - "capabilities" - ) final PhoneNumberCapabilities capabilities, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("identity_sid") final String identitySid, - @JsonProperty( - "phone_number" - ) final com.twilio.type.PhoneNumber phoneNumber, - @JsonProperty("origin") final String origin, - @JsonProperty("sid") final String sid, - @JsonProperty("sms_application_sid") final String smsApplicationSid, - @JsonProperty("sms_fallback_method") final HttpMethod smsFallbackMethod, - @JsonProperty("sms_fallback_url") final URI smsFallbackUrl, - @JsonProperty("sms_method") final HttpMethod smsMethod, - @JsonProperty("sms_url") final URI smsUrl, - @JsonProperty("status_callback") final URI statusCallback, - @JsonProperty( - "status_callback_method" - ) final HttpMethod statusCallbackMethod, - @JsonProperty("trunk_sid") final String trunkSid, - @JsonProperty("uri") final String uri, - @JsonProperty( - "voice_receive_mode" - ) final Local.VoiceReceiveMode voiceReceiveMode, - @JsonProperty("voice_application_sid") final String voiceApplicationSid, - @JsonProperty( - "voice_caller_id_lookup" - ) final Boolean voiceCallerIdLookup, - @JsonProperty( - "voice_fallback_method" - ) final HttpMethod voiceFallbackMethod, - @JsonProperty("voice_fallback_url") final URI voiceFallbackUrl, - @JsonProperty("voice_method") final HttpMethod voiceMethod, - @JsonProperty("voice_url") final URI voiceUrl, - @JsonProperty( - "emergency_status" - ) final Local.EmergencyStatus emergencyStatus, - @JsonProperty("emergency_address_sid") final String emergencyAddressSid, - @JsonProperty( - "emergency_address_status" - ) final Local.EmergencyAddressStatus emergencyAddressStatus, - @JsonProperty("bundle_sid") final String bundleSid, - @JsonProperty("status") final String status + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("address_requirements") final Local.AddressRequirement addressRequirements, + @JsonProperty("address_sid") final String addressSid, + @JsonProperty("api_version") final String apiVersion, + @JsonProperty("beta") final Boolean beta, + @JsonProperty("bundle_sid") final String bundleSid, + @JsonProperty("capabilities") final PhoneNumberCapabilities capabilities, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.RFC2822Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.RFC2822Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("emergency_address_sid") final String emergencyAddressSid, + @JsonProperty("emergency_address_status") final Local.EmergencyAddressStatus emergencyAddressStatus, + @JsonProperty("emergency_status") final Local.EmergencyStatus emergencyStatus, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("identity_sid") final String identitySid, + @JsonProperty("origin") final String origin, + @JsonProperty("phone_number") final com.twilio.type.PhoneNumber phoneNumber, + @JsonProperty("sid") final String sid, + @JsonProperty("sms_application_sid") final String smsApplicationSid, + @JsonProperty("sms_fallback_method") final HttpMethod smsFallbackMethod, + @JsonProperty("sms_fallback_url") final URI smsFallbackUrl, + @JsonProperty("sms_method") final HttpMethod smsMethod, + @JsonProperty("sms_url") final URI smsUrl, + @JsonProperty("status") final String status, + @JsonProperty("status_callback") final URI statusCallback, + @JsonProperty("status_callback_method") final HttpMethod statusCallbackMethod, + @JsonProperty("trunk_sid") final String trunkSid, + @JsonProperty("uri") final String uri, + @JsonProperty("voice_application_sid") final String voiceApplicationSid, + @JsonProperty("voice_caller_id_lookup") final Boolean voiceCallerIdLookup, + @JsonProperty("voice_fallback_method") final HttpMethod voiceFallbackMethod, + @JsonProperty("voice_fallback_url") final URI voiceFallbackUrl, + @JsonProperty("voice_method") final HttpMethod voiceMethod, + @JsonProperty("voice_receive_mode") final Local.VoiceReceiveMode voiceReceiveMode, + @JsonProperty("voice_url") final URI voiceUrl ) { this.accountSid = accountSid; - this.addressSid = addressSid; this.addressRequirements = addressRequirements; + this.addressSid = addressSid; this.apiVersion = apiVersion; this.beta = beta; + this.bundleSid = bundleSid; this.capabilities = capabilities; - this.dateCreated = DateConverter.rfc2822DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.rfc2822DateTimeFromString(dateUpdated); + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; + this.emergencyAddressSid = emergencyAddressSid; + this.emergencyAddressStatus = emergencyAddressStatus; + this.emergencyStatus = emergencyStatus; this.friendlyName = friendlyName; this.identitySid = identitySid; - this.phoneNumber = phoneNumber; this.origin = origin; + this.phoneNumber = phoneNumber; this.sid = sid; this.smsApplicationSid = smsApplicationSid; this.smsFallbackMethod = smsFallbackMethod; this.smsFallbackUrl = smsFallbackUrl; this.smsMethod = smsMethod; this.smsUrl = smsUrl; + this.status = status; this.statusCallback = statusCallback; this.statusCallbackMethod = statusCallbackMethod; this.trunkSid = trunkSid; this.uri = uri; - this.voiceReceiveMode = voiceReceiveMode; this.voiceApplicationSid = voiceApplicationSid; this.voiceCallerIdLookup = voiceCallerIdLookup; this.voiceFallbackMethod = voiceFallbackMethod; this.voiceFallbackUrl = voiceFallbackUrl; this.voiceMethod = voiceMethod; + this.voiceReceiveMode = voiceReceiveMode; this.voiceUrl = voiceUrl; - this.emergencyStatus = emergencyStatus; - this.emergencyAddressSid = emergencyAddressSid; - this.emergencyAddressStatus = emergencyAddressStatus; - this.bundleSid = bundleSid; - this.status = status; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getAddressSid() { - return this.addressSid; - } - - public final Local.AddressRequirement getAddressRequirements() { - return this.addressRequirements; - } - - public final String getApiVersion() { - return this.apiVersion; - } - - public final Boolean getBeta() { - return this.beta; - } - - public final PhoneNumberCapabilities getCapabilities() { - return this.capabilities; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final String getIdentitySid() { - return this.identitySid; - } - - public final com.twilio.type.PhoneNumber getPhoneNumber() { - return this.phoneNumber; - } - - public final String getOrigin() { - return this.origin; - } - - public final String getSid() { - return this.sid; - } - - public final String getSmsApplicationSid() { - return this.smsApplicationSid; - } - - public final HttpMethod getSmsFallbackMethod() { - return this.smsFallbackMethod; - } - - public final URI getSmsFallbackUrl() { - return this.smsFallbackUrl; - } - - public final HttpMethod getSmsMethod() { - return this.smsMethod; - } - - public final URI getSmsUrl() { - return this.smsUrl; - } - - public final URI getStatusCallback() { - return this.statusCallback; - } - - public final HttpMethod getStatusCallbackMethod() { - return this.statusCallbackMethod; - } - - public final String getTrunkSid() { - return this.trunkSid; - } - - public final String getUri() { - return this.uri; - } - - public final Local.VoiceReceiveMode getVoiceReceiveMode() { - return this.voiceReceiveMode; - } - - public final String getVoiceApplicationSid() { - return this.voiceApplicationSid; - } - - public final Boolean getVoiceCallerIdLookup() { - return this.voiceCallerIdLookup; - } - - public final HttpMethod getVoiceFallbackMethod() { - return this.voiceFallbackMethod; - } - - public final URI getVoiceFallbackUrl() { - return this.voiceFallbackUrl; - } - - public final HttpMethod getVoiceMethod() { - return this.voiceMethod; - } - - public final URI getVoiceUrl() { - return this.voiceUrl; - } - - public final Local.EmergencyStatus getEmergencyStatus() { - return this.emergencyStatus; - } - - public final String getEmergencyAddressSid() { - return this.emergencyAddressSid; - } - - public final Local.EmergencyAddressStatus getEmergencyAddressStatus() { - return this.emergencyAddressStatus; - } - - public final String getBundleSid() { - return this.bundleSid; - } - - public final String getStatus() { - return this.status; } @Override @@ -378,174 +362,84 @@ public boolean equals(final Object o) { } Local other = (Local) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(addressSid, other.addressSid) && - Objects.equals(addressRequirements, other.addressRequirements) && - Objects.equals(apiVersion, other.apiVersion) && - Objects.equals(beta, other.beta) && - Objects.equals(capabilities, other.capabilities) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(identitySid, other.identitySid) && - Objects.equals(phoneNumber, other.phoneNumber) && - Objects.equals(origin, other.origin) && - Objects.equals(sid, other.sid) && - Objects.equals(smsApplicationSid, other.smsApplicationSid) && - Objects.equals(smsFallbackMethod, other.smsFallbackMethod) && - Objects.equals(smsFallbackUrl, other.smsFallbackUrl) && - Objects.equals(smsMethod, other.smsMethod) && - Objects.equals(smsUrl, other.smsUrl) && - Objects.equals(statusCallback, other.statusCallback) && - Objects.equals(statusCallbackMethod, other.statusCallbackMethod) && - Objects.equals(trunkSid, other.trunkSid) && - Objects.equals(uri, other.uri) && - Objects.equals(voiceReceiveMode, other.voiceReceiveMode) && - Objects.equals(voiceApplicationSid, other.voiceApplicationSid) && - Objects.equals(voiceCallerIdLookup, other.voiceCallerIdLookup) && - Objects.equals(voiceFallbackMethod, other.voiceFallbackMethod) && - Objects.equals(voiceFallbackUrl, other.voiceFallbackUrl) && - Objects.equals(voiceMethod, other.voiceMethod) && - Objects.equals(voiceUrl, other.voiceUrl) && - Objects.equals(emergencyStatus, other.emergencyStatus) && - Objects.equals(emergencyAddressSid, other.emergencyAddressSid) && - Objects.equals( - emergencyAddressStatus, - other.emergencyAddressStatus - ) && - Objects.equals(bundleSid, other.bundleSid) && - Objects.equals(status, other.status) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(addressRequirements, other.addressRequirements) && + Objects.equals(addressSid, other.addressSid) && + Objects.equals(apiVersion, other.apiVersion) && + Objects.equals(beta, other.beta) && + Objects.equals(bundleSid, other.bundleSid) && + Objects.equals(capabilities, other.capabilities) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(emergencyAddressSid, other.emergencyAddressSid) && + Objects.equals(emergencyAddressStatus, other.emergencyAddressStatus) && + Objects.equals(emergencyStatus, other.emergencyStatus) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(identitySid, other.identitySid) && + Objects.equals(origin, other.origin) && + Objects.equals(phoneNumber, other.phoneNumber) && + Objects.equals(sid, other.sid) && + Objects.equals(smsApplicationSid, other.smsApplicationSid) && + Objects.equals(smsFallbackMethod, other.smsFallbackMethod) && + Objects.equals(smsFallbackUrl, other.smsFallbackUrl) && + Objects.equals(smsMethod, other.smsMethod) && + Objects.equals(smsUrl, other.smsUrl) && + Objects.equals(status, other.status) && + Objects.equals(statusCallback, other.statusCallback) && + Objects.equals(statusCallbackMethod, other.statusCallbackMethod) && + Objects.equals(trunkSid, other.trunkSid) && + Objects.equals(uri, other.uri) && + Objects.equals(voiceApplicationSid, other.voiceApplicationSid) && + Objects.equals(voiceCallerIdLookup, other.voiceCallerIdLookup) && + Objects.equals(voiceFallbackMethod, other.voiceFallbackMethod) && + Objects.equals(voiceFallbackUrl, other.voiceFallbackUrl) && + Objects.equals(voiceMethod, other.voiceMethod) && + Objects.equals(voiceReceiveMode, other.voiceReceiveMode) && + Objects.equals(voiceUrl, other.voiceUrl) ); } @Override public int hashCode() { return Objects.hash( - accountSid, - addressSid, - addressRequirements, - apiVersion, - beta, - capabilities, - dateCreated, - dateUpdated, - friendlyName, - identitySid, - phoneNumber, - origin, - sid, - smsApplicationSid, - smsFallbackMethod, - smsFallbackUrl, - smsMethod, - smsUrl, - statusCallback, - statusCallbackMethod, - trunkSid, - uri, - voiceReceiveMode, - voiceApplicationSid, - voiceCallerIdLookup, - voiceFallbackMethod, - voiceFallbackUrl, - voiceMethod, - voiceUrl, - emergencyStatus, - emergencyAddressSid, - emergencyAddressStatus, - bundleSid, - status + accountSid, + addressRequirements, + addressSid, + apiVersion, + beta, + bundleSid, + capabilities, + dateCreated, + dateUpdated, + emergencyAddressSid, + emergencyAddressStatus, + emergencyStatus, + friendlyName, + identitySid, + origin, + phoneNumber, + sid, + smsApplicationSid, + smsFallbackMethod, + smsFallbackUrl, + smsMethod, + smsUrl, + status, + statusCallback, + statusCallbackMethod, + trunkSid, + uri, + voiceApplicationSid, + voiceCallerIdLookup, + voiceFallbackMethod, + voiceFallbackUrl, + voiceMethod, + voiceReceiveMode, + voiceUrl ); } - public enum EmergencyStatus { - ACTIVE("Active"), - INACTIVE("Inactive"); - - private final String value; - private EmergencyStatus(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static EmergencyStatus forValue(final String value) { - return Promoter.enumFromString(value, EmergencyStatus.values()); - } - } - - public enum AddressRequirement { - NONE("none"), - ANY("any"), - LOCAL("local"), - FOREIGN("foreign"); - - private final String value; - - private AddressRequirement(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static AddressRequirement forValue(final String value) { - return Promoter.enumFromString(value, AddressRequirement.values()); - } - } - - public enum EmergencyAddressStatus { - REGISTERED("registered"), - UNREGISTERED("unregistered"), - PENDING_REGISTRATION("pending-registration"), - REGISTRATION_FAILURE("registration-failure"), - PENDING_UNREGISTRATION("pending-unregistration"), - UNREGISTRATION_FAILURE("unregistration-failure"); - - private final String value; - - private EmergencyAddressStatus(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static EmergencyAddressStatus forValue(final String value) { - return Promoter.enumFromString( - value, - EmergencyAddressStatus.values() - ); - } - } - - public enum VoiceReceiveMode { - VOICE("voice"), - FAX("fax"); - - private final String value; - - private VoiceReceiveMode(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static VoiceReceiveMode forValue(final String value) { - return Promoter.enumFromString(value, VoiceReceiveMode.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/api/v2010/account/incomingphonenumber/LocalCreator.java b/src/main/java/com/twilio/rest/api/v2010/account/incomingphonenumber/LocalCreator.java index 25a74eb499..bd45cf7e73 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/incomingphonenumber/LocalCreator.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/incomingphonenumber/LocalCreator.java @@ -14,9 +14,12 @@ package com.twilio.rest.api.v2010.account.incomingphonenumber; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; import com.twilio.converter.Promoter; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,13 +28,13 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -import java.net.URI; + import java.net.URI; public class LocalCreator extends Creator { + private String pathaccountSid; private com.twilio.type.PhoneNumber phoneNumber; - private String pathAccountSid; private String apiVersion; private String friendlyName; private String smsApplicationSid; @@ -59,17 +62,13 @@ public LocalCreator(final com.twilio.type.PhoneNumber phoneNumber) { this.phoneNumber = phoneNumber; } - public LocalCreator( - final String pathAccountSid, - final com.twilio.type.PhoneNumber phoneNumber - ) { - this.pathAccountSid = pathAccountSid; + public LocalCreator(final String pathaccountSid, final com.twilio.type.PhoneNumber phoneNumber) { + this.pathaccountSid = pathaccountSid; this.phoneNumber = phoneNumber; } - public LocalCreator setPhoneNumber( - final com.twilio.type.PhoneNumber phoneNumber - ) { + + public LocalCreator setPhoneNumber(final com.twilio.type.PhoneNumber phoneNumber) { this.phoneNumber = phoneNumber; return this; } @@ -83,189 +82,161 @@ public LocalCreator setApiVersion(final String apiVersion) { return this; } + public LocalCreator setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + public LocalCreator setSmsApplicationSid(final String smsApplicationSid) { this.smsApplicationSid = smsApplicationSid; return this; } - public LocalCreator setSmsFallbackMethod( - final HttpMethod smsFallbackMethod - ) { + + public LocalCreator setSmsFallbackMethod(final HttpMethod smsFallbackMethod) { this.smsFallbackMethod = smsFallbackMethod; return this; } + public LocalCreator setSmsFallbackUrl(final URI smsFallbackUrl) { this.smsFallbackUrl = smsFallbackUrl; return this; } - public LocalCreator setSmsFallbackUrl(final String smsFallbackUrl) { - return setSmsFallbackUrl(Promoter.uriFromString(smsFallbackUrl)); - } public LocalCreator setSmsMethod(final HttpMethod smsMethod) { this.smsMethod = smsMethod; return this; } + public LocalCreator setSmsUrl(final URI smsUrl) { this.smsUrl = smsUrl; return this; } - public LocalCreator setSmsUrl(final String smsUrl) { - return setSmsUrl(Promoter.uriFromString(smsUrl)); - } public LocalCreator setStatusCallback(final URI statusCallback) { this.statusCallback = statusCallback; return this; } - public LocalCreator setStatusCallback(final String statusCallback) { - return setStatusCallback(Promoter.uriFromString(statusCallback)); - } - public LocalCreator setStatusCallbackMethod( - final HttpMethod statusCallbackMethod - ) { + public LocalCreator setStatusCallbackMethod(final HttpMethod statusCallbackMethod) { this.statusCallbackMethod = statusCallbackMethod; return this; } - public LocalCreator setVoiceApplicationSid( - final String voiceApplicationSid - ) { + + public LocalCreator setVoiceApplicationSid(final String voiceApplicationSid) { this.voiceApplicationSid = voiceApplicationSid; return this; } - public LocalCreator setVoiceCallerIdLookup( - final Boolean voiceCallerIdLookup - ) { + + public LocalCreator setVoiceCallerIdLookup(final Boolean voiceCallerIdLookup) { this.voiceCallerIdLookup = voiceCallerIdLookup; return this; } - public LocalCreator setVoiceFallbackMethod( - final HttpMethod voiceFallbackMethod - ) { + + public LocalCreator setVoiceFallbackMethod(final HttpMethod voiceFallbackMethod) { this.voiceFallbackMethod = voiceFallbackMethod; return this; } + public LocalCreator setVoiceFallbackUrl(final URI voiceFallbackUrl) { this.voiceFallbackUrl = voiceFallbackUrl; return this; } - public LocalCreator setVoiceFallbackUrl(final String voiceFallbackUrl) { - return setVoiceFallbackUrl(Promoter.uriFromString(voiceFallbackUrl)); - } public LocalCreator setVoiceMethod(final HttpMethod voiceMethod) { this.voiceMethod = voiceMethod; return this; } + public LocalCreator setVoiceUrl(final URI voiceUrl) { this.voiceUrl = voiceUrl; return this; } - public LocalCreator setVoiceUrl(final String voiceUrl) { - return setVoiceUrl(Promoter.uriFromString(voiceUrl)); - } public LocalCreator setIdentitySid(final String identitySid) { this.identitySid = identitySid; return this; } + public LocalCreator setAddressSid(final String addressSid) { this.addressSid = addressSid; return this; } - public LocalCreator setEmergencyStatus( - final Local.EmergencyStatus emergencyStatus - ) { + + public LocalCreator setEmergencyStatus(final Local.EmergencyStatus emergencyStatus) { this.emergencyStatus = emergencyStatus; return this; } - public LocalCreator setEmergencyAddressSid( - final String emergencyAddressSid - ) { + + public LocalCreator setEmergencyAddressSid(final String emergencyAddressSid) { this.emergencyAddressSid = emergencyAddressSid; return this; } + public LocalCreator setTrunkSid(final String trunkSid) { this.trunkSid = trunkSid; return this; } - public LocalCreator setVoiceReceiveMode( - final Local.VoiceReceiveMode voiceReceiveMode - ) { + + public LocalCreator setVoiceReceiveMode(final Local.VoiceReceiveMode voiceReceiveMode) { this.voiceReceiveMode = voiceReceiveMode; return this; } + public LocalCreator setBundleSid(final String bundleSid) { this.bundleSid = bundleSid; return this; } + @Override public Local create(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/IncomingPhoneNumbers/Local.json"; - - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = - path.replace( - "{" + "PhoneNumber" + "}", - this.phoneNumber.toString() - ); + + String path = "/2010-04-01/Accounts/{AccountSid}/IncomingPhoneNumbers/Local.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.API.toString(), - path + HttpMethod.POST, + Domains.API.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Local creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("Local creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -274,92 +245,121 @@ public Local create(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (phoneNumber != null) { - request.addPostParam("PhoneNumber", phoneNumber.toString()); + Serializer.toString(request, "PhoneNumber", phoneNumber, ParameterType.URLENCODED); } + + if (apiVersion != null) { - request.addPostParam("ApiVersion", apiVersion); + Serializer.toString(request, "ApiVersion", apiVersion, ParameterType.URLENCODED); } + + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + if (smsApplicationSid != null) { - request.addPostParam("SmsApplicationSid", smsApplicationSid); + Serializer.toString(request, "SmsApplicationSid", smsApplicationSid, ParameterType.URLENCODED); } + + if (smsFallbackMethod != null) { - request.addPostParam( - "SmsFallbackMethod", - smsFallbackMethod.toString() - ); + Serializer.toString(request, "SmsFallbackMethod", smsFallbackMethod, ParameterType.URLENCODED); } + + if (smsFallbackUrl != null) { - request.addPostParam("SmsFallbackUrl", smsFallbackUrl.toString()); + Serializer.toString(request, "SmsFallbackUrl", smsFallbackUrl, ParameterType.URLENCODED); } + + if (smsMethod != null) { - request.addPostParam("SmsMethod", smsMethod.toString()); + Serializer.toString(request, "SmsMethod", smsMethod, ParameterType.URLENCODED); } + + if (smsUrl != null) { - request.addPostParam("SmsUrl", smsUrl.toString()); + Serializer.toString(request, "SmsUrl", smsUrl, ParameterType.URLENCODED); } + + if (statusCallback != null) { - request.addPostParam("StatusCallback", statusCallback.toString()); + Serializer.toString(request, "StatusCallback", statusCallback, ParameterType.URLENCODED); } + + if (statusCallbackMethod != null) { - request.addPostParam( - "StatusCallbackMethod", - statusCallbackMethod.toString() - ); + Serializer.toString(request, "StatusCallbackMethod", statusCallbackMethod, ParameterType.URLENCODED); } + + if (voiceApplicationSid != null) { - request.addPostParam("VoiceApplicationSid", voiceApplicationSid); + Serializer.toString(request, "VoiceApplicationSid", voiceApplicationSid, ParameterType.URLENCODED); } + + if (voiceCallerIdLookup != null) { - request.addPostParam( - "VoiceCallerIdLookup", - voiceCallerIdLookup.toString() - ); + Serializer.toString(request, "VoiceCallerIdLookup", voiceCallerIdLookup, ParameterType.URLENCODED); } + + if (voiceFallbackMethod != null) { - request.addPostParam( - "VoiceFallbackMethod", - voiceFallbackMethod.toString() - ); + Serializer.toString(request, "VoiceFallbackMethod", voiceFallbackMethod, ParameterType.URLENCODED); } + + if (voiceFallbackUrl != null) { - request.addPostParam( - "VoiceFallbackUrl", - voiceFallbackUrl.toString() - ); + Serializer.toString(request, "VoiceFallbackUrl", voiceFallbackUrl, ParameterType.URLENCODED); } + + if (voiceMethod != null) { - request.addPostParam("VoiceMethod", voiceMethod.toString()); + Serializer.toString(request, "VoiceMethod", voiceMethod, ParameterType.URLENCODED); } + + if (voiceUrl != null) { - request.addPostParam("VoiceUrl", voiceUrl.toString()); + Serializer.toString(request, "VoiceUrl", voiceUrl, ParameterType.URLENCODED); } + + if (identitySid != null) { - request.addPostParam("IdentitySid", identitySid); + Serializer.toString(request, "IdentitySid", identitySid, ParameterType.URLENCODED); } + + if (addressSid != null) { - request.addPostParam("AddressSid", addressSid); + Serializer.toString(request, "AddressSid", addressSid, ParameterType.URLENCODED); } + + if (emergencyStatus != null) { - request.addPostParam("EmergencyStatus", emergencyStatus.toString()); + Serializer.toString(request, "EmergencyStatus", emergencyStatus, ParameterType.URLENCODED); } + + if (emergencyAddressSid != null) { - request.addPostParam("EmergencyAddressSid", emergencyAddressSid); + Serializer.toString(request, "EmergencyAddressSid", emergencyAddressSid, ParameterType.URLENCODED); } + + if (trunkSid != null) { - request.addPostParam("TrunkSid", trunkSid); + Serializer.toString(request, "TrunkSid", trunkSid, ParameterType.URLENCODED); } + + if (voiceReceiveMode != null) { - request.addPostParam( - "VoiceReceiveMode", - voiceReceiveMode.toString() - ); + Serializer.toString(request, "VoiceReceiveMode", voiceReceiveMode, ParameterType.URLENCODED); } + + if (bundleSid != null) { - request.addPostParam("BundleSid", bundleSid); + Serializer.toString(request, "BundleSid", bundleSid, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/incomingphonenumber/LocalReader.java b/src/main/java/com/twilio/rest/api/v2010/account/incomingphonenumber/LocalReader.java index 8d8152510d..afbc6c7d76 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/incomingphonenumber/LocalReader.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/incomingphonenumber/LocalReader.java @@ -17,8 +17,9 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; import com.twilio.converter.Promoter; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -30,32 +31,34 @@ public class LocalReader extends Reader { - private String pathAccountSid; + private String pathaccountSid; private Boolean beta; private String friendlyName; private com.twilio.type.PhoneNumber phoneNumber; private String origin; private Long pageSize; - public LocalReader() {} + public LocalReader() { + } - public LocalReader(final String pathAccountSid) { - this.pathAccountSid = pathAccountSid; + public LocalReader(final String pathaccountSid) { + this.pathaccountSid = pathaccountSid; } + public LocalReader setBeta(final Boolean beta) { this.beta = beta; return this; } + public LocalReader setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } - public LocalReader setPhoneNumber( - final com.twilio.type.PhoneNumber phoneNumber - ) { + + public LocalReader setPhoneNumber(final com.twilio.type.PhoneNumber phoneNumber) { this.phoneNumber = phoneNumber; return this; } @@ -69,125 +72,102 @@ public LocalReader setOrigin(final String origin) { return this; } + public LocalReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/IncomingPhoneNumbers/Local.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); + + String path = "/2010-04-01/Accounts/{AccountSid}/IncomingPhoneNumbers/Local.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.API.toString(), - path + HttpMethod.GET, + Domains.API.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Local read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Local read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "incoming_phone_numbers", - response.getContent(), - Local.class, - client.getObjectMapper() - ); + "incoming_phone_numbers", + response.getContent(), + Local.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.API.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.API.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (beta != null) { - request.addQueryParam("Beta", beta.toString()); + Serializer.toString(request, "Beta", beta, ParameterType.QUERY); } + + if (friendlyName != null) { - request.addQueryParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.QUERY); } + + if (phoneNumber != null) { - request.addQueryParam("PhoneNumber", phoneNumber.toString()); + Serializer.toString(request, "PhoneNumber", phoneNumber, ParameterType.QUERY); } + + if (origin != null) { - request.addQueryParam("Origin", origin); + Serializer.toString(request, "Origin", origin, ParameterType.QUERY); } + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/incomingphonenumber/Mobile.java b/src/main/java/com/twilio/rest/api/v2010/account/incomingphonenumber/Mobile.java index 62c6156f9e..55f5f8923a 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/incomingphonenumber/Mobile.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/incomingphonenumber/Mobile.java @@ -18,61 +18,153 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.http.HttpMethod; import com.twilio.type.PhoneNumberCapabilities; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Mobile extends Resource { - private static final long serialVersionUID = 79850849216916L; - public static MobileCreator creator( - final com.twilio.type.PhoneNumber phoneNumber - ) { - return new MobileCreator(phoneNumber); + public static MobileCreator creator(final com.twilio.type.PhoneNumber phoneNumber) { + return new MobileCreator( + phoneNumber + ); } - public static MobileCreator creator( - final String pathAccountSid, - final com.twilio.type.PhoneNumber phoneNumber - ) { - return new MobileCreator(pathAccountSid, phoneNumber); + + public static MobileCreator creator(final String pathaccountSid, final com.twilio.type.PhoneNumber phoneNumber) { + return new MobileCreator( + pathaccountSid, phoneNumber + ); } + public static MobileReader reader() { - return new MobileReader(); + return new MobileReader( + + ); + } + + + public static MobileReader reader(final String pathaccountSid) { + return new MobileReader( + pathaccountSid + ); + } + + + public enum EmergencyAddressStatus { + REGISTERED("registered"), + UNREGISTERED("unregistered"), + PENDING_REGISTRATION("pending-registration"), + REGISTRATION_FAILURE("registration-failure"), + PENDING_UNREGISTRATION("pending-unregistration"), + UNREGISTRATION_FAILURE("unregistration-failure"); + + private final String value; + + private EmergencyAddressStatus(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static EmergencyAddressStatus forValue(final String value) { + return Promoter.enumFromString(value, EmergencyAddressStatus.values()); + } + } + + public enum VoiceReceiveMode { + VOICE("voice"), + FAX("fax"); + + private final String value; + + private VoiceReceiveMode(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static VoiceReceiveMode forValue(final String value) { + return Promoter.enumFromString(value, VoiceReceiveMode.values()); + } + } + + public enum EmergencyStatus { + ACTIVE("Active"), + INACTIVE("Inactive"); + + private final String value; + + private EmergencyStatus(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static EmergencyStatus forValue(final String value) { + return Promoter.enumFromString(value, EmergencyStatus.values()); + } } - public static MobileReader reader(final String pathAccountSid) { - return new MobileReader(pathAccountSid); + public enum AddressRequirement { + NONE("none"), + ANY("any"), + LOCAL("local"), + FOREIGN("foreign"); + + private final String value; + + private AddressRequirement(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static AddressRequirement forValue(final String value) { + return Promoter.enumFromString(value, AddressRequirement.values()); + } } + /** * Converts a JSON String into a Mobile object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Mobile object represented by the provided JSON */ - public static Mobile fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Mobile fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Mobile.class); @@ -87,14 +179,11 @@ public static Mobile fromJson( * Converts a JSON InputStream into a Mobile object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Mobile object represented by the provided JSON */ - public static Mobile fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Mobile fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Mobile.class); @@ -105,266 +194,161 @@ public static Mobile fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String addressSid; + @Getter private final Mobile.AddressRequirement addressRequirements; + @Getter + private final String addressSid; + @Getter private final String apiVersion; + @Getter private final Boolean beta; + @Getter + private final String bundleSid; + @Getter private final PhoneNumberCapabilities capabilities; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; + @Getter + private final String emergencyAddressSid; + @Getter + private final Mobile.EmergencyAddressStatus emergencyAddressStatus; + @Getter + private final Mobile.EmergencyStatus emergencyStatus; + @Getter private final String friendlyName; + @Getter private final String identitySid; - private final com.twilio.type.PhoneNumber phoneNumber; + @Getter private final String origin; + @Getter + private final com.twilio.type.PhoneNumber phoneNumber; + @Getter private final String sid; + @Getter private final String smsApplicationSid; + @Getter private final HttpMethod smsFallbackMethod; + @Getter private final URI smsFallbackUrl; + @Getter private final HttpMethod smsMethod; + @Getter private final URI smsUrl; + @Getter + private final String status; + @Getter private final URI statusCallback; + @Getter private final HttpMethod statusCallbackMethod; + @Getter private final String trunkSid; + @Getter private final String uri; - private final Mobile.VoiceReceiveMode voiceReceiveMode; + @Getter private final String voiceApplicationSid; + @Getter private final Boolean voiceCallerIdLookup; + @Getter private final HttpMethod voiceFallbackMethod; + @Getter private final URI voiceFallbackUrl; + @Getter private final HttpMethod voiceMethod; + @Getter + private final Mobile.VoiceReceiveMode voiceReceiveMode; + @Getter private final URI voiceUrl; - private final Mobile.EmergencyStatus emergencyStatus; - private final String emergencyAddressSid; - private final Mobile.EmergencyAddressStatus emergencyAddressStatus; - private final String bundleSid; - private final String status; @JsonCreator private Mobile( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("address_sid") final String addressSid, - @JsonProperty( - "address_requirements" - ) final Mobile.AddressRequirement addressRequirements, - @JsonProperty("api_version") final String apiVersion, - @JsonProperty("beta") final Boolean beta, - @JsonProperty( - "capabilities" - ) final PhoneNumberCapabilities capabilities, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("identity_sid") final String identitySid, - @JsonProperty( - "phone_number" - ) final com.twilio.type.PhoneNumber phoneNumber, - @JsonProperty("origin") final String origin, - @JsonProperty("sid") final String sid, - @JsonProperty("sms_application_sid") final String smsApplicationSid, - @JsonProperty("sms_fallback_method") final HttpMethod smsFallbackMethod, - @JsonProperty("sms_fallback_url") final URI smsFallbackUrl, - @JsonProperty("sms_method") final HttpMethod smsMethod, - @JsonProperty("sms_url") final URI smsUrl, - @JsonProperty("status_callback") final URI statusCallback, - @JsonProperty( - "status_callback_method" - ) final HttpMethod statusCallbackMethod, - @JsonProperty("trunk_sid") final String trunkSid, - @JsonProperty("uri") final String uri, - @JsonProperty( - "voice_receive_mode" - ) final Mobile.VoiceReceiveMode voiceReceiveMode, - @JsonProperty("voice_application_sid") final String voiceApplicationSid, - @JsonProperty( - "voice_caller_id_lookup" - ) final Boolean voiceCallerIdLookup, - @JsonProperty( - "voice_fallback_method" - ) final HttpMethod voiceFallbackMethod, - @JsonProperty("voice_fallback_url") final URI voiceFallbackUrl, - @JsonProperty("voice_method") final HttpMethod voiceMethod, - @JsonProperty("voice_url") final URI voiceUrl, - @JsonProperty( - "emergency_status" - ) final Mobile.EmergencyStatus emergencyStatus, - @JsonProperty("emergency_address_sid") final String emergencyAddressSid, - @JsonProperty( - "emergency_address_status" - ) final Mobile.EmergencyAddressStatus emergencyAddressStatus, - @JsonProperty("bundle_sid") final String bundleSid, - @JsonProperty("status") final String status + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("address_requirements") final Mobile.AddressRequirement addressRequirements, + @JsonProperty("address_sid") final String addressSid, + @JsonProperty("api_version") final String apiVersion, + @JsonProperty("beta") final Boolean beta, + @JsonProperty("bundle_sid") final String bundleSid, + @JsonProperty("capabilities") final PhoneNumberCapabilities capabilities, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.RFC2822Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.RFC2822Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("emergency_address_sid") final String emergencyAddressSid, + @JsonProperty("emergency_address_status") final Mobile.EmergencyAddressStatus emergencyAddressStatus, + @JsonProperty("emergency_status") final Mobile.EmergencyStatus emergencyStatus, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("identity_sid") final String identitySid, + @JsonProperty("origin") final String origin, + @JsonProperty("phone_number") final com.twilio.type.PhoneNumber phoneNumber, + @JsonProperty("sid") final String sid, + @JsonProperty("sms_application_sid") final String smsApplicationSid, + @JsonProperty("sms_fallback_method") final HttpMethod smsFallbackMethod, + @JsonProperty("sms_fallback_url") final URI smsFallbackUrl, + @JsonProperty("sms_method") final HttpMethod smsMethod, + @JsonProperty("sms_url") final URI smsUrl, + @JsonProperty("status") final String status, + @JsonProperty("status_callback") final URI statusCallback, + @JsonProperty("status_callback_method") final HttpMethod statusCallbackMethod, + @JsonProperty("trunk_sid") final String trunkSid, + @JsonProperty("uri") final String uri, + @JsonProperty("voice_application_sid") final String voiceApplicationSid, + @JsonProperty("voice_caller_id_lookup") final Boolean voiceCallerIdLookup, + @JsonProperty("voice_fallback_method") final HttpMethod voiceFallbackMethod, + @JsonProperty("voice_fallback_url") final URI voiceFallbackUrl, + @JsonProperty("voice_method") final HttpMethod voiceMethod, + @JsonProperty("voice_receive_mode") final Mobile.VoiceReceiveMode voiceReceiveMode, + @JsonProperty("voice_url") final URI voiceUrl ) { this.accountSid = accountSid; - this.addressSid = addressSid; this.addressRequirements = addressRequirements; + this.addressSid = addressSid; this.apiVersion = apiVersion; this.beta = beta; + this.bundleSid = bundleSid; this.capabilities = capabilities; - this.dateCreated = DateConverter.rfc2822DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.rfc2822DateTimeFromString(dateUpdated); + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; + this.emergencyAddressSid = emergencyAddressSid; + this.emergencyAddressStatus = emergencyAddressStatus; + this.emergencyStatus = emergencyStatus; this.friendlyName = friendlyName; this.identitySid = identitySid; - this.phoneNumber = phoneNumber; this.origin = origin; + this.phoneNumber = phoneNumber; this.sid = sid; this.smsApplicationSid = smsApplicationSid; this.smsFallbackMethod = smsFallbackMethod; this.smsFallbackUrl = smsFallbackUrl; this.smsMethod = smsMethod; this.smsUrl = smsUrl; + this.status = status; this.statusCallback = statusCallback; this.statusCallbackMethod = statusCallbackMethod; this.trunkSid = trunkSid; this.uri = uri; - this.voiceReceiveMode = voiceReceiveMode; this.voiceApplicationSid = voiceApplicationSid; this.voiceCallerIdLookup = voiceCallerIdLookup; this.voiceFallbackMethod = voiceFallbackMethod; this.voiceFallbackUrl = voiceFallbackUrl; this.voiceMethod = voiceMethod; + this.voiceReceiveMode = voiceReceiveMode; this.voiceUrl = voiceUrl; - this.emergencyStatus = emergencyStatus; - this.emergencyAddressSid = emergencyAddressSid; - this.emergencyAddressStatus = emergencyAddressStatus; - this.bundleSid = bundleSid; - this.status = status; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getAddressSid() { - return this.addressSid; - } - - public final Mobile.AddressRequirement getAddressRequirements() { - return this.addressRequirements; - } - - public final String getApiVersion() { - return this.apiVersion; - } - - public final Boolean getBeta() { - return this.beta; - } - - public final PhoneNumberCapabilities getCapabilities() { - return this.capabilities; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final String getIdentitySid() { - return this.identitySid; - } - - public final com.twilio.type.PhoneNumber getPhoneNumber() { - return this.phoneNumber; - } - - public final String getOrigin() { - return this.origin; - } - - public final String getSid() { - return this.sid; - } - - public final String getSmsApplicationSid() { - return this.smsApplicationSid; - } - - public final HttpMethod getSmsFallbackMethod() { - return this.smsFallbackMethod; - } - - public final URI getSmsFallbackUrl() { - return this.smsFallbackUrl; - } - - public final HttpMethod getSmsMethod() { - return this.smsMethod; - } - - public final URI getSmsUrl() { - return this.smsUrl; - } - - public final URI getStatusCallback() { - return this.statusCallback; - } - - public final HttpMethod getStatusCallbackMethod() { - return this.statusCallbackMethod; - } - - public final String getTrunkSid() { - return this.trunkSid; - } - - public final String getUri() { - return this.uri; - } - - public final Mobile.VoiceReceiveMode getVoiceReceiveMode() { - return this.voiceReceiveMode; - } - - public final String getVoiceApplicationSid() { - return this.voiceApplicationSid; - } - - public final Boolean getVoiceCallerIdLookup() { - return this.voiceCallerIdLookup; - } - - public final HttpMethod getVoiceFallbackMethod() { - return this.voiceFallbackMethod; - } - - public final URI getVoiceFallbackUrl() { - return this.voiceFallbackUrl; - } - - public final HttpMethod getVoiceMethod() { - return this.voiceMethod; - } - - public final URI getVoiceUrl() { - return this.voiceUrl; - } - - public final Mobile.EmergencyStatus getEmergencyStatus() { - return this.emergencyStatus; - } - - public final String getEmergencyAddressSid() { - return this.emergencyAddressSid; - } - - public final Mobile.EmergencyAddressStatus getEmergencyAddressStatus() { - return this.emergencyAddressStatus; - } - - public final String getBundleSid() { - return this.bundleSid; - } - - public final String getStatus() { - return this.status; } @Override @@ -378,174 +362,84 @@ public boolean equals(final Object o) { } Mobile other = (Mobile) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(addressSid, other.addressSid) && - Objects.equals(addressRequirements, other.addressRequirements) && - Objects.equals(apiVersion, other.apiVersion) && - Objects.equals(beta, other.beta) && - Objects.equals(capabilities, other.capabilities) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(identitySid, other.identitySid) && - Objects.equals(phoneNumber, other.phoneNumber) && - Objects.equals(origin, other.origin) && - Objects.equals(sid, other.sid) && - Objects.equals(smsApplicationSid, other.smsApplicationSid) && - Objects.equals(smsFallbackMethod, other.smsFallbackMethod) && - Objects.equals(smsFallbackUrl, other.smsFallbackUrl) && - Objects.equals(smsMethod, other.smsMethod) && - Objects.equals(smsUrl, other.smsUrl) && - Objects.equals(statusCallback, other.statusCallback) && - Objects.equals(statusCallbackMethod, other.statusCallbackMethod) && - Objects.equals(trunkSid, other.trunkSid) && - Objects.equals(uri, other.uri) && - Objects.equals(voiceReceiveMode, other.voiceReceiveMode) && - Objects.equals(voiceApplicationSid, other.voiceApplicationSid) && - Objects.equals(voiceCallerIdLookup, other.voiceCallerIdLookup) && - Objects.equals(voiceFallbackMethod, other.voiceFallbackMethod) && - Objects.equals(voiceFallbackUrl, other.voiceFallbackUrl) && - Objects.equals(voiceMethod, other.voiceMethod) && - Objects.equals(voiceUrl, other.voiceUrl) && - Objects.equals(emergencyStatus, other.emergencyStatus) && - Objects.equals(emergencyAddressSid, other.emergencyAddressSid) && - Objects.equals( - emergencyAddressStatus, - other.emergencyAddressStatus - ) && - Objects.equals(bundleSid, other.bundleSid) && - Objects.equals(status, other.status) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(addressRequirements, other.addressRequirements) && + Objects.equals(addressSid, other.addressSid) && + Objects.equals(apiVersion, other.apiVersion) && + Objects.equals(beta, other.beta) && + Objects.equals(bundleSid, other.bundleSid) && + Objects.equals(capabilities, other.capabilities) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(emergencyAddressSid, other.emergencyAddressSid) && + Objects.equals(emergencyAddressStatus, other.emergencyAddressStatus) && + Objects.equals(emergencyStatus, other.emergencyStatus) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(identitySid, other.identitySid) && + Objects.equals(origin, other.origin) && + Objects.equals(phoneNumber, other.phoneNumber) && + Objects.equals(sid, other.sid) && + Objects.equals(smsApplicationSid, other.smsApplicationSid) && + Objects.equals(smsFallbackMethod, other.smsFallbackMethod) && + Objects.equals(smsFallbackUrl, other.smsFallbackUrl) && + Objects.equals(smsMethod, other.smsMethod) && + Objects.equals(smsUrl, other.smsUrl) && + Objects.equals(status, other.status) && + Objects.equals(statusCallback, other.statusCallback) && + Objects.equals(statusCallbackMethod, other.statusCallbackMethod) && + Objects.equals(trunkSid, other.trunkSid) && + Objects.equals(uri, other.uri) && + Objects.equals(voiceApplicationSid, other.voiceApplicationSid) && + Objects.equals(voiceCallerIdLookup, other.voiceCallerIdLookup) && + Objects.equals(voiceFallbackMethod, other.voiceFallbackMethod) && + Objects.equals(voiceFallbackUrl, other.voiceFallbackUrl) && + Objects.equals(voiceMethod, other.voiceMethod) && + Objects.equals(voiceReceiveMode, other.voiceReceiveMode) && + Objects.equals(voiceUrl, other.voiceUrl) ); } @Override public int hashCode() { return Objects.hash( - accountSid, - addressSid, - addressRequirements, - apiVersion, - beta, - capabilities, - dateCreated, - dateUpdated, - friendlyName, - identitySid, - phoneNumber, - origin, - sid, - smsApplicationSid, - smsFallbackMethod, - smsFallbackUrl, - smsMethod, - smsUrl, - statusCallback, - statusCallbackMethod, - trunkSid, - uri, - voiceReceiveMode, - voiceApplicationSid, - voiceCallerIdLookup, - voiceFallbackMethod, - voiceFallbackUrl, - voiceMethod, - voiceUrl, - emergencyStatus, - emergencyAddressSid, - emergencyAddressStatus, - bundleSid, - status + accountSid, + addressRequirements, + addressSid, + apiVersion, + beta, + bundleSid, + capabilities, + dateCreated, + dateUpdated, + emergencyAddressSid, + emergencyAddressStatus, + emergencyStatus, + friendlyName, + identitySid, + origin, + phoneNumber, + sid, + smsApplicationSid, + smsFallbackMethod, + smsFallbackUrl, + smsMethod, + smsUrl, + status, + statusCallback, + statusCallbackMethod, + trunkSid, + uri, + voiceApplicationSid, + voiceCallerIdLookup, + voiceFallbackMethod, + voiceFallbackUrl, + voiceMethod, + voiceReceiveMode, + voiceUrl ); } - public enum EmergencyAddressStatus { - REGISTERED("registered"), - UNREGISTERED("unregistered"), - PENDING_REGISTRATION("pending-registration"), - REGISTRATION_FAILURE("registration-failure"), - PENDING_UNREGISTRATION("pending-unregistration"), - UNREGISTRATION_FAILURE("unregistration-failure"); - - private final String value; - private EmergencyAddressStatus(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static EmergencyAddressStatus forValue(final String value) { - return Promoter.enumFromString( - value, - EmergencyAddressStatus.values() - ); - } - } - - public enum AddressRequirement { - NONE("none"), - ANY("any"), - LOCAL("local"), - FOREIGN("foreign"); - - private final String value; - - private AddressRequirement(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static AddressRequirement forValue(final String value) { - return Promoter.enumFromString(value, AddressRequirement.values()); - } - } - - public enum EmergencyStatus { - ACTIVE("Active"), - INACTIVE("Inactive"); - - private final String value; - - private EmergencyStatus(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static EmergencyStatus forValue(final String value) { - return Promoter.enumFromString(value, EmergencyStatus.values()); - } - } - - public enum VoiceReceiveMode { - VOICE("voice"), - FAX("fax"); - - private final String value; - - private VoiceReceiveMode(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static VoiceReceiveMode forValue(final String value) { - return Promoter.enumFromString(value, VoiceReceiveMode.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/api/v2010/account/incomingphonenumber/MobileCreator.java b/src/main/java/com/twilio/rest/api/v2010/account/incomingphonenumber/MobileCreator.java index 6fe7fa36c0..8d05c9d152 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/incomingphonenumber/MobileCreator.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/incomingphonenumber/MobileCreator.java @@ -14,9 +14,12 @@ package com.twilio.rest.api.v2010.account.incomingphonenumber; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; import com.twilio.converter.Promoter; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,13 +28,13 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -import java.net.URI; + import java.net.URI; public class MobileCreator extends Creator { + private String pathaccountSid; private com.twilio.type.PhoneNumber phoneNumber; - private String pathAccountSid; private String apiVersion; private String friendlyName; private String smsApplicationSid; @@ -59,17 +62,13 @@ public MobileCreator(final com.twilio.type.PhoneNumber phoneNumber) { this.phoneNumber = phoneNumber; } - public MobileCreator( - final String pathAccountSid, - final com.twilio.type.PhoneNumber phoneNumber - ) { - this.pathAccountSid = pathAccountSid; + public MobileCreator(final String pathaccountSid, final com.twilio.type.PhoneNumber phoneNumber) { + this.pathaccountSid = pathaccountSid; this.phoneNumber = phoneNumber; } - public MobileCreator setPhoneNumber( - final com.twilio.type.PhoneNumber phoneNumber - ) { + + public MobileCreator setPhoneNumber(final com.twilio.type.PhoneNumber phoneNumber) { this.phoneNumber = phoneNumber; return this; } @@ -83,189 +82,161 @@ public MobileCreator setApiVersion(final String apiVersion) { return this; } + public MobileCreator setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + public MobileCreator setSmsApplicationSid(final String smsApplicationSid) { this.smsApplicationSid = smsApplicationSid; return this; } - public MobileCreator setSmsFallbackMethod( - final HttpMethod smsFallbackMethod - ) { + + public MobileCreator setSmsFallbackMethod(final HttpMethod smsFallbackMethod) { this.smsFallbackMethod = smsFallbackMethod; return this; } + public MobileCreator setSmsFallbackUrl(final URI smsFallbackUrl) { this.smsFallbackUrl = smsFallbackUrl; return this; } - public MobileCreator setSmsFallbackUrl(final String smsFallbackUrl) { - return setSmsFallbackUrl(Promoter.uriFromString(smsFallbackUrl)); - } public MobileCreator setSmsMethod(final HttpMethod smsMethod) { this.smsMethod = smsMethod; return this; } + public MobileCreator setSmsUrl(final URI smsUrl) { this.smsUrl = smsUrl; return this; } - public MobileCreator setSmsUrl(final String smsUrl) { - return setSmsUrl(Promoter.uriFromString(smsUrl)); - } public MobileCreator setStatusCallback(final URI statusCallback) { this.statusCallback = statusCallback; return this; } - public MobileCreator setStatusCallback(final String statusCallback) { - return setStatusCallback(Promoter.uriFromString(statusCallback)); - } - public MobileCreator setStatusCallbackMethod( - final HttpMethod statusCallbackMethod - ) { + public MobileCreator setStatusCallbackMethod(final HttpMethod statusCallbackMethod) { this.statusCallbackMethod = statusCallbackMethod; return this; } - public MobileCreator setVoiceApplicationSid( - final String voiceApplicationSid - ) { + + public MobileCreator setVoiceApplicationSid(final String voiceApplicationSid) { this.voiceApplicationSid = voiceApplicationSid; return this; } - public MobileCreator setVoiceCallerIdLookup( - final Boolean voiceCallerIdLookup - ) { + + public MobileCreator setVoiceCallerIdLookup(final Boolean voiceCallerIdLookup) { this.voiceCallerIdLookup = voiceCallerIdLookup; return this; } - public MobileCreator setVoiceFallbackMethod( - final HttpMethod voiceFallbackMethod - ) { + + public MobileCreator setVoiceFallbackMethod(final HttpMethod voiceFallbackMethod) { this.voiceFallbackMethod = voiceFallbackMethod; return this; } + public MobileCreator setVoiceFallbackUrl(final URI voiceFallbackUrl) { this.voiceFallbackUrl = voiceFallbackUrl; return this; } - public MobileCreator setVoiceFallbackUrl(final String voiceFallbackUrl) { - return setVoiceFallbackUrl(Promoter.uriFromString(voiceFallbackUrl)); - } public MobileCreator setVoiceMethod(final HttpMethod voiceMethod) { this.voiceMethod = voiceMethod; return this; } + public MobileCreator setVoiceUrl(final URI voiceUrl) { this.voiceUrl = voiceUrl; return this; } - public MobileCreator setVoiceUrl(final String voiceUrl) { - return setVoiceUrl(Promoter.uriFromString(voiceUrl)); - } public MobileCreator setIdentitySid(final String identitySid) { this.identitySid = identitySid; return this; } + public MobileCreator setAddressSid(final String addressSid) { this.addressSid = addressSid; return this; } - public MobileCreator setEmergencyStatus( - final Mobile.EmergencyStatus emergencyStatus - ) { + + public MobileCreator setEmergencyStatus(final Mobile.EmergencyStatus emergencyStatus) { this.emergencyStatus = emergencyStatus; return this; } - public MobileCreator setEmergencyAddressSid( - final String emergencyAddressSid - ) { + + public MobileCreator setEmergencyAddressSid(final String emergencyAddressSid) { this.emergencyAddressSid = emergencyAddressSid; return this; } + public MobileCreator setTrunkSid(final String trunkSid) { this.trunkSid = trunkSid; return this; } - public MobileCreator setVoiceReceiveMode( - final Mobile.VoiceReceiveMode voiceReceiveMode - ) { + + public MobileCreator setVoiceReceiveMode(final Mobile.VoiceReceiveMode voiceReceiveMode) { this.voiceReceiveMode = voiceReceiveMode; return this; } + public MobileCreator setBundleSid(final String bundleSid) { this.bundleSid = bundleSid; return this; } + @Override public Mobile create(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/IncomingPhoneNumbers/Mobile.json"; - - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = - path.replace( - "{" + "PhoneNumber" + "}", - this.phoneNumber.toString() - ); + + String path = "/2010-04-01/Accounts/{AccountSid}/IncomingPhoneNumbers/Mobile.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.API.toString(), - path + HttpMethod.POST, + Domains.API.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Mobile creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("Mobile creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -274,92 +245,121 @@ public Mobile create(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (phoneNumber != null) { - request.addPostParam("PhoneNumber", phoneNumber.toString()); + Serializer.toString(request, "PhoneNumber", phoneNumber, ParameterType.URLENCODED); } + + if (apiVersion != null) { - request.addPostParam("ApiVersion", apiVersion); + Serializer.toString(request, "ApiVersion", apiVersion, ParameterType.URLENCODED); } + + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + if (smsApplicationSid != null) { - request.addPostParam("SmsApplicationSid", smsApplicationSid); + Serializer.toString(request, "SmsApplicationSid", smsApplicationSid, ParameterType.URLENCODED); } + + if (smsFallbackMethod != null) { - request.addPostParam( - "SmsFallbackMethod", - smsFallbackMethod.toString() - ); + Serializer.toString(request, "SmsFallbackMethod", smsFallbackMethod, ParameterType.URLENCODED); } + + if (smsFallbackUrl != null) { - request.addPostParam("SmsFallbackUrl", smsFallbackUrl.toString()); + Serializer.toString(request, "SmsFallbackUrl", smsFallbackUrl, ParameterType.URLENCODED); } + + if (smsMethod != null) { - request.addPostParam("SmsMethod", smsMethod.toString()); + Serializer.toString(request, "SmsMethod", smsMethod, ParameterType.URLENCODED); } + + if (smsUrl != null) { - request.addPostParam("SmsUrl", smsUrl.toString()); + Serializer.toString(request, "SmsUrl", smsUrl, ParameterType.URLENCODED); } + + if (statusCallback != null) { - request.addPostParam("StatusCallback", statusCallback.toString()); + Serializer.toString(request, "StatusCallback", statusCallback, ParameterType.URLENCODED); } + + if (statusCallbackMethod != null) { - request.addPostParam( - "StatusCallbackMethod", - statusCallbackMethod.toString() - ); + Serializer.toString(request, "StatusCallbackMethod", statusCallbackMethod, ParameterType.URLENCODED); } + + if (voiceApplicationSid != null) { - request.addPostParam("VoiceApplicationSid", voiceApplicationSid); + Serializer.toString(request, "VoiceApplicationSid", voiceApplicationSid, ParameterType.URLENCODED); } + + if (voiceCallerIdLookup != null) { - request.addPostParam( - "VoiceCallerIdLookup", - voiceCallerIdLookup.toString() - ); + Serializer.toString(request, "VoiceCallerIdLookup", voiceCallerIdLookup, ParameterType.URLENCODED); } + + if (voiceFallbackMethod != null) { - request.addPostParam( - "VoiceFallbackMethod", - voiceFallbackMethod.toString() - ); + Serializer.toString(request, "VoiceFallbackMethod", voiceFallbackMethod, ParameterType.URLENCODED); } + + if (voiceFallbackUrl != null) { - request.addPostParam( - "VoiceFallbackUrl", - voiceFallbackUrl.toString() - ); + Serializer.toString(request, "VoiceFallbackUrl", voiceFallbackUrl, ParameterType.URLENCODED); } + + if (voiceMethod != null) { - request.addPostParam("VoiceMethod", voiceMethod.toString()); + Serializer.toString(request, "VoiceMethod", voiceMethod, ParameterType.URLENCODED); } + + if (voiceUrl != null) { - request.addPostParam("VoiceUrl", voiceUrl.toString()); + Serializer.toString(request, "VoiceUrl", voiceUrl, ParameterType.URLENCODED); } + + if (identitySid != null) { - request.addPostParam("IdentitySid", identitySid); + Serializer.toString(request, "IdentitySid", identitySid, ParameterType.URLENCODED); } + + if (addressSid != null) { - request.addPostParam("AddressSid", addressSid); + Serializer.toString(request, "AddressSid", addressSid, ParameterType.URLENCODED); } + + if (emergencyStatus != null) { - request.addPostParam("EmergencyStatus", emergencyStatus.toString()); + Serializer.toString(request, "EmergencyStatus", emergencyStatus, ParameterType.URLENCODED); } + + if (emergencyAddressSid != null) { - request.addPostParam("EmergencyAddressSid", emergencyAddressSid); + Serializer.toString(request, "EmergencyAddressSid", emergencyAddressSid, ParameterType.URLENCODED); } + + if (trunkSid != null) { - request.addPostParam("TrunkSid", trunkSid); + Serializer.toString(request, "TrunkSid", trunkSid, ParameterType.URLENCODED); } + + if (voiceReceiveMode != null) { - request.addPostParam( - "VoiceReceiveMode", - voiceReceiveMode.toString() - ); + Serializer.toString(request, "VoiceReceiveMode", voiceReceiveMode, ParameterType.URLENCODED); } + + if (bundleSid != null) { - request.addPostParam("BundleSid", bundleSid); + Serializer.toString(request, "BundleSid", bundleSid, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/incomingphonenumber/MobileReader.java b/src/main/java/com/twilio/rest/api/v2010/account/incomingphonenumber/MobileReader.java index 1a78349e75..165603baa9 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/incomingphonenumber/MobileReader.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/incomingphonenumber/MobileReader.java @@ -17,8 +17,9 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; import com.twilio.converter.Promoter; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -30,32 +31,34 @@ public class MobileReader extends Reader { - private String pathAccountSid; + private String pathaccountSid; private Boolean beta; private String friendlyName; private com.twilio.type.PhoneNumber phoneNumber; private String origin; private Long pageSize; - public MobileReader() {} + public MobileReader() { + } - public MobileReader(final String pathAccountSid) { - this.pathAccountSid = pathAccountSid; + public MobileReader(final String pathaccountSid) { + this.pathaccountSid = pathaccountSid; } + public MobileReader setBeta(final Boolean beta) { this.beta = beta; return this; } + public MobileReader setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } - public MobileReader setPhoneNumber( - final com.twilio.type.PhoneNumber phoneNumber - ) { + + public MobileReader setPhoneNumber(final com.twilio.type.PhoneNumber phoneNumber) { this.phoneNumber = phoneNumber; return this; } @@ -69,125 +72,102 @@ public MobileReader setOrigin(final String origin) { return this; } + public MobileReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/IncomingPhoneNumbers/Mobile.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); + + String path = "/2010-04-01/Accounts/{AccountSid}/IncomingPhoneNumbers/Mobile.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.API.toString(), - path + HttpMethod.GET, + Domains.API.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Mobile read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Mobile read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "incoming_phone_numbers", - response.getContent(), - Mobile.class, - client.getObjectMapper() - ); + "incoming_phone_numbers", + response.getContent(), + Mobile.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.API.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.API.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (beta != null) { - request.addQueryParam("Beta", beta.toString()); + Serializer.toString(request, "Beta", beta, ParameterType.QUERY); } + + if (friendlyName != null) { - request.addQueryParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.QUERY); } + + if (phoneNumber != null) { - request.addQueryParam("PhoneNumber", phoneNumber.toString()); + Serializer.toString(request, "PhoneNumber", phoneNumber, ParameterType.QUERY); } + + if (origin != null) { - request.addQueryParam("Origin", origin); + Serializer.toString(request, "Origin", origin, ParameterType.QUERY); } + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/incomingphonenumber/TollFree.java b/src/main/java/com/twilio/rest/api/v2010/account/incomingphonenumber/TollFree.java index 4e1e3cf74c..e2723de159 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/incomingphonenumber/TollFree.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/incomingphonenumber/TollFree.java @@ -18,61 +18,153 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.http.HttpMethod; import com.twilio.type.PhoneNumberCapabilities; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class TollFree extends Resource { - private static final long serialVersionUID = 90694713647603L; - public static TollFreeCreator creator( - final com.twilio.type.PhoneNumber phoneNumber - ) { - return new TollFreeCreator(phoneNumber); + public static TollFreeCreator creator(final com.twilio.type.PhoneNumber phoneNumber) { + return new TollFreeCreator( + phoneNumber + ); } - public static TollFreeCreator creator( - final String pathAccountSid, - final com.twilio.type.PhoneNumber phoneNumber - ) { - return new TollFreeCreator(pathAccountSid, phoneNumber); + + public static TollFreeCreator creator(final String pathaccountSid, final com.twilio.type.PhoneNumber phoneNumber) { + return new TollFreeCreator( + pathaccountSid, phoneNumber + ); } + public static TollFreeReader reader() { - return new TollFreeReader(); + return new TollFreeReader( + + ); + } + + + public static TollFreeReader reader(final String pathaccountSid) { + return new TollFreeReader( + pathaccountSid + ); + } + + + public enum EmergencyAddressStatus { + REGISTERED("registered"), + UNREGISTERED("unregistered"), + PENDING_REGISTRATION("pending-registration"), + REGISTRATION_FAILURE("registration-failure"), + PENDING_UNREGISTRATION("pending-unregistration"), + UNREGISTRATION_FAILURE("unregistration-failure"); + + private final String value; + + private EmergencyAddressStatus(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static EmergencyAddressStatus forValue(final String value) { + return Promoter.enumFromString(value, EmergencyAddressStatus.values()); + } + } + + public enum VoiceReceiveMode { + VOICE("voice"), + FAX("fax"); + + private final String value; + + private VoiceReceiveMode(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static VoiceReceiveMode forValue(final String value) { + return Promoter.enumFromString(value, VoiceReceiveMode.values()); + } + } + + public enum EmergencyStatus { + ACTIVE("Active"), + INACTIVE("Inactive"); + + private final String value; + + private EmergencyStatus(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static EmergencyStatus forValue(final String value) { + return Promoter.enumFromString(value, EmergencyStatus.values()); + } } - public static TollFreeReader reader(final String pathAccountSid) { - return new TollFreeReader(pathAccountSid); + public enum AddressRequirement { + NONE("none"), + ANY("any"), + LOCAL("local"), + FOREIGN("foreign"); + + private final String value; + + private AddressRequirement(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static AddressRequirement forValue(final String value) { + return Promoter.enumFromString(value, AddressRequirement.values()); + } } + /** * Converts a JSON String into a TollFree object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return TollFree object represented by the provided JSON */ - public static TollFree fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static TollFree fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, TollFree.class); @@ -87,14 +179,11 @@ public static TollFree fromJson( * Converts a JSON InputStream into a TollFree object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return TollFree object represented by the provided JSON */ - public static TollFree fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static TollFree fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, TollFree.class); @@ -105,266 +194,161 @@ public static TollFree fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String addressSid; + @Getter private final TollFree.AddressRequirement addressRequirements; + @Getter + private final String addressSid; + @Getter private final String apiVersion; + @Getter private final Boolean beta; + @Getter + private final String bundleSid; + @Getter private final PhoneNumberCapabilities capabilities; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; + @Getter + private final String emergencyAddressSid; + @Getter + private final TollFree.EmergencyAddressStatus emergencyAddressStatus; + @Getter + private final TollFree.EmergencyStatus emergencyStatus; + @Getter private final String friendlyName; + @Getter private final String identitySid; - private final com.twilio.type.PhoneNumber phoneNumber; + @Getter private final String origin; + @Getter + private final com.twilio.type.PhoneNumber phoneNumber; + @Getter private final String sid; + @Getter private final String smsApplicationSid; + @Getter private final HttpMethod smsFallbackMethod; + @Getter private final URI smsFallbackUrl; + @Getter private final HttpMethod smsMethod; + @Getter private final URI smsUrl; + @Getter + private final String status; + @Getter private final URI statusCallback; + @Getter private final HttpMethod statusCallbackMethod; + @Getter private final String trunkSid; + @Getter private final String uri; - private final TollFree.VoiceReceiveMode voiceReceiveMode; + @Getter private final String voiceApplicationSid; + @Getter private final Boolean voiceCallerIdLookup; + @Getter private final HttpMethod voiceFallbackMethod; + @Getter private final URI voiceFallbackUrl; + @Getter private final HttpMethod voiceMethod; + @Getter + private final TollFree.VoiceReceiveMode voiceReceiveMode; + @Getter private final URI voiceUrl; - private final TollFree.EmergencyStatus emergencyStatus; - private final String emergencyAddressSid; - private final TollFree.EmergencyAddressStatus emergencyAddressStatus; - private final String bundleSid; - private final String status; @JsonCreator private TollFree( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("address_sid") final String addressSid, - @JsonProperty( - "address_requirements" - ) final TollFree.AddressRequirement addressRequirements, - @JsonProperty("api_version") final String apiVersion, - @JsonProperty("beta") final Boolean beta, - @JsonProperty( - "capabilities" - ) final PhoneNumberCapabilities capabilities, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("identity_sid") final String identitySid, - @JsonProperty( - "phone_number" - ) final com.twilio.type.PhoneNumber phoneNumber, - @JsonProperty("origin") final String origin, - @JsonProperty("sid") final String sid, - @JsonProperty("sms_application_sid") final String smsApplicationSid, - @JsonProperty("sms_fallback_method") final HttpMethod smsFallbackMethod, - @JsonProperty("sms_fallback_url") final URI smsFallbackUrl, - @JsonProperty("sms_method") final HttpMethod smsMethod, - @JsonProperty("sms_url") final URI smsUrl, - @JsonProperty("status_callback") final URI statusCallback, - @JsonProperty( - "status_callback_method" - ) final HttpMethod statusCallbackMethod, - @JsonProperty("trunk_sid") final String trunkSid, - @JsonProperty("uri") final String uri, - @JsonProperty( - "voice_receive_mode" - ) final TollFree.VoiceReceiveMode voiceReceiveMode, - @JsonProperty("voice_application_sid") final String voiceApplicationSid, - @JsonProperty( - "voice_caller_id_lookup" - ) final Boolean voiceCallerIdLookup, - @JsonProperty( - "voice_fallback_method" - ) final HttpMethod voiceFallbackMethod, - @JsonProperty("voice_fallback_url") final URI voiceFallbackUrl, - @JsonProperty("voice_method") final HttpMethod voiceMethod, - @JsonProperty("voice_url") final URI voiceUrl, - @JsonProperty( - "emergency_status" - ) final TollFree.EmergencyStatus emergencyStatus, - @JsonProperty("emergency_address_sid") final String emergencyAddressSid, - @JsonProperty( - "emergency_address_status" - ) final TollFree.EmergencyAddressStatus emergencyAddressStatus, - @JsonProperty("bundle_sid") final String bundleSid, - @JsonProperty("status") final String status + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("address_requirements") final TollFree.AddressRequirement addressRequirements, + @JsonProperty("address_sid") final String addressSid, + @JsonProperty("api_version") final String apiVersion, + @JsonProperty("beta") final Boolean beta, + @JsonProperty("bundle_sid") final String bundleSid, + @JsonProperty("capabilities") final PhoneNumberCapabilities capabilities, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.RFC2822Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.RFC2822Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("emergency_address_sid") final String emergencyAddressSid, + @JsonProperty("emergency_address_status") final TollFree.EmergencyAddressStatus emergencyAddressStatus, + @JsonProperty("emergency_status") final TollFree.EmergencyStatus emergencyStatus, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("identity_sid") final String identitySid, + @JsonProperty("origin") final String origin, + @JsonProperty("phone_number") final com.twilio.type.PhoneNumber phoneNumber, + @JsonProperty("sid") final String sid, + @JsonProperty("sms_application_sid") final String smsApplicationSid, + @JsonProperty("sms_fallback_method") final HttpMethod smsFallbackMethod, + @JsonProperty("sms_fallback_url") final URI smsFallbackUrl, + @JsonProperty("sms_method") final HttpMethod smsMethod, + @JsonProperty("sms_url") final URI smsUrl, + @JsonProperty("status") final String status, + @JsonProperty("status_callback") final URI statusCallback, + @JsonProperty("status_callback_method") final HttpMethod statusCallbackMethod, + @JsonProperty("trunk_sid") final String trunkSid, + @JsonProperty("uri") final String uri, + @JsonProperty("voice_application_sid") final String voiceApplicationSid, + @JsonProperty("voice_caller_id_lookup") final Boolean voiceCallerIdLookup, + @JsonProperty("voice_fallback_method") final HttpMethod voiceFallbackMethod, + @JsonProperty("voice_fallback_url") final URI voiceFallbackUrl, + @JsonProperty("voice_method") final HttpMethod voiceMethod, + @JsonProperty("voice_receive_mode") final TollFree.VoiceReceiveMode voiceReceiveMode, + @JsonProperty("voice_url") final URI voiceUrl ) { this.accountSid = accountSid; - this.addressSid = addressSid; this.addressRequirements = addressRequirements; + this.addressSid = addressSid; this.apiVersion = apiVersion; this.beta = beta; + this.bundleSid = bundleSid; this.capabilities = capabilities; - this.dateCreated = DateConverter.rfc2822DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.rfc2822DateTimeFromString(dateUpdated); + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; + this.emergencyAddressSid = emergencyAddressSid; + this.emergencyAddressStatus = emergencyAddressStatus; + this.emergencyStatus = emergencyStatus; this.friendlyName = friendlyName; this.identitySid = identitySid; - this.phoneNumber = phoneNumber; this.origin = origin; + this.phoneNumber = phoneNumber; this.sid = sid; this.smsApplicationSid = smsApplicationSid; this.smsFallbackMethod = smsFallbackMethod; this.smsFallbackUrl = smsFallbackUrl; this.smsMethod = smsMethod; this.smsUrl = smsUrl; + this.status = status; this.statusCallback = statusCallback; this.statusCallbackMethod = statusCallbackMethod; this.trunkSid = trunkSid; this.uri = uri; - this.voiceReceiveMode = voiceReceiveMode; this.voiceApplicationSid = voiceApplicationSid; this.voiceCallerIdLookup = voiceCallerIdLookup; this.voiceFallbackMethod = voiceFallbackMethod; this.voiceFallbackUrl = voiceFallbackUrl; this.voiceMethod = voiceMethod; + this.voiceReceiveMode = voiceReceiveMode; this.voiceUrl = voiceUrl; - this.emergencyStatus = emergencyStatus; - this.emergencyAddressSid = emergencyAddressSid; - this.emergencyAddressStatus = emergencyAddressStatus; - this.bundleSid = bundleSid; - this.status = status; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getAddressSid() { - return this.addressSid; - } - - public final TollFree.AddressRequirement getAddressRequirements() { - return this.addressRequirements; - } - - public final String getApiVersion() { - return this.apiVersion; - } - - public final Boolean getBeta() { - return this.beta; - } - - public final PhoneNumberCapabilities getCapabilities() { - return this.capabilities; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final String getIdentitySid() { - return this.identitySid; - } - - public final com.twilio.type.PhoneNumber getPhoneNumber() { - return this.phoneNumber; - } - - public final String getOrigin() { - return this.origin; - } - - public final String getSid() { - return this.sid; - } - - public final String getSmsApplicationSid() { - return this.smsApplicationSid; - } - - public final HttpMethod getSmsFallbackMethod() { - return this.smsFallbackMethod; - } - - public final URI getSmsFallbackUrl() { - return this.smsFallbackUrl; - } - - public final HttpMethod getSmsMethod() { - return this.smsMethod; - } - - public final URI getSmsUrl() { - return this.smsUrl; - } - - public final URI getStatusCallback() { - return this.statusCallback; - } - - public final HttpMethod getStatusCallbackMethod() { - return this.statusCallbackMethod; - } - - public final String getTrunkSid() { - return this.trunkSid; - } - - public final String getUri() { - return this.uri; - } - - public final TollFree.VoiceReceiveMode getVoiceReceiveMode() { - return this.voiceReceiveMode; - } - - public final String getVoiceApplicationSid() { - return this.voiceApplicationSid; - } - - public final Boolean getVoiceCallerIdLookup() { - return this.voiceCallerIdLookup; - } - - public final HttpMethod getVoiceFallbackMethod() { - return this.voiceFallbackMethod; - } - - public final URI getVoiceFallbackUrl() { - return this.voiceFallbackUrl; - } - - public final HttpMethod getVoiceMethod() { - return this.voiceMethod; - } - - public final URI getVoiceUrl() { - return this.voiceUrl; - } - - public final TollFree.EmergencyStatus getEmergencyStatus() { - return this.emergencyStatus; - } - - public final String getEmergencyAddressSid() { - return this.emergencyAddressSid; - } - - public final TollFree.EmergencyAddressStatus getEmergencyAddressStatus() { - return this.emergencyAddressStatus; - } - - public final String getBundleSid() { - return this.bundleSid; - } - - public final String getStatus() { - return this.status; } @Override @@ -378,174 +362,84 @@ public boolean equals(final Object o) { } TollFree other = (TollFree) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(addressSid, other.addressSid) && - Objects.equals(addressRequirements, other.addressRequirements) && - Objects.equals(apiVersion, other.apiVersion) && - Objects.equals(beta, other.beta) && - Objects.equals(capabilities, other.capabilities) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(identitySid, other.identitySid) && - Objects.equals(phoneNumber, other.phoneNumber) && - Objects.equals(origin, other.origin) && - Objects.equals(sid, other.sid) && - Objects.equals(smsApplicationSid, other.smsApplicationSid) && - Objects.equals(smsFallbackMethod, other.smsFallbackMethod) && - Objects.equals(smsFallbackUrl, other.smsFallbackUrl) && - Objects.equals(smsMethod, other.smsMethod) && - Objects.equals(smsUrl, other.smsUrl) && - Objects.equals(statusCallback, other.statusCallback) && - Objects.equals(statusCallbackMethod, other.statusCallbackMethod) && - Objects.equals(trunkSid, other.trunkSid) && - Objects.equals(uri, other.uri) && - Objects.equals(voiceReceiveMode, other.voiceReceiveMode) && - Objects.equals(voiceApplicationSid, other.voiceApplicationSid) && - Objects.equals(voiceCallerIdLookup, other.voiceCallerIdLookup) && - Objects.equals(voiceFallbackMethod, other.voiceFallbackMethod) && - Objects.equals(voiceFallbackUrl, other.voiceFallbackUrl) && - Objects.equals(voiceMethod, other.voiceMethod) && - Objects.equals(voiceUrl, other.voiceUrl) && - Objects.equals(emergencyStatus, other.emergencyStatus) && - Objects.equals(emergencyAddressSid, other.emergencyAddressSid) && - Objects.equals( - emergencyAddressStatus, - other.emergencyAddressStatus - ) && - Objects.equals(bundleSid, other.bundleSid) && - Objects.equals(status, other.status) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(addressRequirements, other.addressRequirements) && + Objects.equals(addressSid, other.addressSid) && + Objects.equals(apiVersion, other.apiVersion) && + Objects.equals(beta, other.beta) && + Objects.equals(bundleSid, other.bundleSid) && + Objects.equals(capabilities, other.capabilities) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(emergencyAddressSid, other.emergencyAddressSid) && + Objects.equals(emergencyAddressStatus, other.emergencyAddressStatus) && + Objects.equals(emergencyStatus, other.emergencyStatus) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(identitySid, other.identitySid) && + Objects.equals(origin, other.origin) && + Objects.equals(phoneNumber, other.phoneNumber) && + Objects.equals(sid, other.sid) && + Objects.equals(smsApplicationSid, other.smsApplicationSid) && + Objects.equals(smsFallbackMethod, other.smsFallbackMethod) && + Objects.equals(smsFallbackUrl, other.smsFallbackUrl) && + Objects.equals(smsMethod, other.smsMethod) && + Objects.equals(smsUrl, other.smsUrl) && + Objects.equals(status, other.status) && + Objects.equals(statusCallback, other.statusCallback) && + Objects.equals(statusCallbackMethod, other.statusCallbackMethod) && + Objects.equals(trunkSid, other.trunkSid) && + Objects.equals(uri, other.uri) && + Objects.equals(voiceApplicationSid, other.voiceApplicationSid) && + Objects.equals(voiceCallerIdLookup, other.voiceCallerIdLookup) && + Objects.equals(voiceFallbackMethod, other.voiceFallbackMethod) && + Objects.equals(voiceFallbackUrl, other.voiceFallbackUrl) && + Objects.equals(voiceMethod, other.voiceMethod) && + Objects.equals(voiceReceiveMode, other.voiceReceiveMode) && + Objects.equals(voiceUrl, other.voiceUrl) ); } @Override public int hashCode() { return Objects.hash( - accountSid, - addressSid, - addressRequirements, - apiVersion, - beta, - capabilities, - dateCreated, - dateUpdated, - friendlyName, - identitySid, - phoneNumber, - origin, - sid, - smsApplicationSid, - smsFallbackMethod, - smsFallbackUrl, - smsMethod, - smsUrl, - statusCallback, - statusCallbackMethod, - trunkSid, - uri, - voiceReceiveMode, - voiceApplicationSid, - voiceCallerIdLookup, - voiceFallbackMethod, - voiceFallbackUrl, - voiceMethod, - voiceUrl, - emergencyStatus, - emergencyAddressSid, - emergencyAddressStatus, - bundleSid, - status + accountSid, + addressRequirements, + addressSid, + apiVersion, + beta, + bundleSid, + capabilities, + dateCreated, + dateUpdated, + emergencyAddressSid, + emergencyAddressStatus, + emergencyStatus, + friendlyName, + identitySid, + origin, + phoneNumber, + sid, + smsApplicationSid, + smsFallbackMethod, + smsFallbackUrl, + smsMethod, + smsUrl, + status, + statusCallback, + statusCallbackMethod, + trunkSid, + uri, + voiceApplicationSid, + voiceCallerIdLookup, + voiceFallbackMethod, + voiceFallbackUrl, + voiceMethod, + voiceReceiveMode, + voiceUrl ); } - public enum VoiceReceiveMode { - VOICE("voice"), - FAX("fax"); - - private final String value; - private VoiceReceiveMode(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static VoiceReceiveMode forValue(final String value) { - return Promoter.enumFromString(value, VoiceReceiveMode.values()); - } - } - - public enum AddressRequirement { - NONE("none"), - ANY("any"), - LOCAL("local"), - FOREIGN("foreign"); - - private final String value; - - private AddressRequirement(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static AddressRequirement forValue(final String value) { - return Promoter.enumFromString(value, AddressRequirement.values()); - } - } - - public enum EmergencyStatus { - ACTIVE("Active"), - INACTIVE("Inactive"); - - private final String value; - - private EmergencyStatus(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static EmergencyStatus forValue(final String value) { - return Promoter.enumFromString(value, EmergencyStatus.values()); - } - } - - public enum EmergencyAddressStatus { - REGISTERED("registered"), - UNREGISTERED("unregistered"), - PENDING_REGISTRATION("pending-registration"), - REGISTRATION_FAILURE("registration-failure"), - PENDING_UNREGISTRATION("pending-unregistration"), - UNREGISTRATION_FAILURE("unregistration-failure"); - - private final String value; - - private EmergencyAddressStatus(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static EmergencyAddressStatus forValue(final String value) { - return Promoter.enumFromString( - value, - EmergencyAddressStatus.values() - ); - } - } } + diff --git a/src/main/java/com/twilio/rest/api/v2010/account/incomingphonenumber/TollFreeCreator.java b/src/main/java/com/twilio/rest/api/v2010/account/incomingphonenumber/TollFreeCreator.java index 61034d20c3..d14cd8e0d3 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/incomingphonenumber/TollFreeCreator.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/incomingphonenumber/TollFreeCreator.java @@ -14,9 +14,12 @@ package com.twilio.rest.api.v2010.account.incomingphonenumber; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; import com.twilio.converter.Promoter; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,13 +28,13 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -import java.net.URI; + import java.net.URI; public class TollFreeCreator extends Creator { + private String pathaccountSid; private com.twilio.type.PhoneNumber phoneNumber; - private String pathAccountSid; private String apiVersion; private String friendlyName; private String smsApplicationSid; @@ -59,17 +62,13 @@ public TollFreeCreator(final com.twilio.type.PhoneNumber phoneNumber) { this.phoneNumber = phoneNumber; } - public TollFreeCreator( - final String pathAccountSid, - final com.twilio.type.PhoneNumber phoneNumber - ) { - this.pathAccountSid = pathAccountSid; + public TollFreeCreator(final String pathaccountSid, final com.twilio.type.PhoneNumber phoneNumber) { + this.pathaccountSid = pathaccountSid; this.phoneNumber = phoneNumber; } - public TollFreeCreator setPhoneNumber( - final com.twilio.type.PhoneNumber phoneNumber - ) { + + public TollFreeCreator setPhoneNumber(final com.twilio.type.PhoneNumber phoneNumber) { this.phoneNumber = phoneNumber; return this; } @@ -83,288 +82,284 @@ public TollFreeCreator setApiVersion(final String apiVersion) { return this; } + public TollFreeCreator setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } - public TollFreeCreator setSmsApplicationSid( - final String smsApplicationSid - ) { + + public TollFreeCreator setSmsApplicationSid(final String smsApplicationSid) { this.smsApplicationSid = smsApplicationSid; return this; } - public TollFreeCreator setSmsFallbackMethod( - final HttpMethod smsFallbackMethod - ) { + + public TollFreeCreator setSmsFallbackMethod(final HttpMethod smsFallbackMethod) { this.smsFallbackMethod = smsFallbackMethod; return this; } + public TollFreeCreator setSmsFallbackUrl(final URI smsFallbackUrl) { this.smsFallbackUrl = smsFallbackUrl; return this; } - public TollFreeCreator setSmsFallbackUrl(final String smsFallbackUrl) { - return setSmsFallbackUrl(Promoter.uriFromString(smsFallbackUrl)); - } public TollFreeCreator setSmsMethod(final HttpMethod smsMethod) { this.smsMethod = smsMethod; return this; } + public TollFreeCreator setSmsUrl(final URI smsUrl) { this.smsUrl = smsUrl; return this; } - public TollFreeCreator setSmsUrl(final String smsUrl) { - return setSmsUrl(Promoter.uriFromString(smsUrl)); - } public TollFreeCreator setStatusCallback(final URI statusCallback) { this.statusCallback = statusCallback; return this; } - public TollFreeCreator setStatusCallback(final String statusCallback) { - return setStatusCallback(Promoter.uriFromString(statusCallback)); - } - public TollFreeCreator setStatusCallbackMethod( - final HttpMethod statusCallbackMethod - ) { + public TollFreeCreator setStatusCallbackMethod(final HttpMethod statusCallbackMethod) { this.statusCallbackMethod = statusCallbackMethod; return this; } - public TollFreeCreator setVoiceApplicationSid( - final String voiceApplicationSid - ) { + + public TollFreeCreator setVoiceApplicationSid(final String voiceApplicationSid) { this.voiceApplicationSid = voiceApplicationSid; return this; } - public TollFreeCreator setVoiceCallerIdLookup( - final Boolean voiceCallerIdLookup - ) { + + public TollFreeCreator setVoiceCallerIdLookup(final Boolean voiceCallerIdLookup) { this.voiceCallerIdLookup = voiceCallerIdLookup; return this; } - public TollFreeCreator setVoiceFallbackMethod( - final HttpMethod voiceFallbackMethod - ) { + + public TollFreeCreator setVoiceFallbackMethod(final HttpMethod voiceFallbackMethod) { this.voiceFallbackMethod = voiceFallbackMethod; return this; } + public TollFreeCreator setVoiceFallbackUrl(final URI voiceFallbackUrl) { this.voiceFallbackUrl = voiceFallbackUrl; return this; } - public TollFreeCreator setVoiceFallbackUrl(final String voiceFallbackUrl) { - return setVoiceFallbackUrl(Promoter.uriFromString(voiceFallbackUrl)); - } public TollFreeCreator setVoiceMethod(final HttpMethod voiceMethod) { this.voiceMethod = voiceMethod; return this; } + public TollFreeCreator setVoiceUrl(final URI voiceUrl) { this.voiceUrl = voiceUrl; return this; } - public TollFreeCreator setVoiceUrl(final String voiceUrl) { - return setVoiceUrl(Promoter.uriFromString(voiceUrl)); - } public TollFreeCreator setIdentitySid(final String identitySid) { this.identitySid = identitySid; return this; } + public TollFreeCreator setAddressSid(final String addressSid) { this.addressSid = addressSid; return this; } - public TollFreeCreator setEmergencyStatus( - final TollFree.EmergencyStatus emergencyStatus - ) { + + public TollFreeCreator setEmergencyStatus(final TollFree.EmergencyStatus emergencyStatus) { this.emergencyStatus = emergencyStatus; return this; } - public TollFreeCreator setEmergencyAddressSid( - final String emergencyAddressSid - ) { + + public TollFreeCreator setEmergencyAddressSid(final String emergencyAddressSid) { this.emergencyAddressSid = emergencyAddressSid; return this; } + public TollFreeCreator setTrunkSid(final String trunkSid) { this.trunkSid = trunkSid; return this; } - public TollFreeCreator setVoiceReceiveMode( - final TollFree.VoiceReceiveMode voiceReceiveMode - ) { + + public TollFreeCreator setVoiceReceiveMode(final TollFree.VoiceReceiveMode voiceReceiveMode) { this.voiceReceiveMode = voiceReceiveMode; return this; } + public TollFreeCreator setBundleSid(final String bundleSid) { this.bundleSid = bundleSid; return this; } + @Override public TollFree create(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/IncomingPhoneNumbers/TollFree.json"; - - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = - path.replace( - "{" + "PhoneNumber" + "}", - this.phoneNumber.toString() - ); + + String path = "/2010-04-01/Accounts/{AccountSid}/IncomingPhoneNumbers/TollFree.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.API.toString(), - path + HttpMethod.POST, + Domains.API.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "TollFree creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("TollFree creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return TollFree.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return TollFree.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (phoneNumber != null) { - request.addPostParam("PhoneNumber", phoneNumber.toString()); + Serializer.toString(request, "PhoneNumber", phoneNumber, ParameterType.URLENCODED); } + + if (apiVersion != null) { - request.addPostParam("ApiVersion", apiVersion); + Serializer.toString(request, "ApiVersion", apiVersion, ParameterType.URLENCODED); } + + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + if (smsApplicationSid != null) { - request.addPostParam("SmsApplicationSid", smsApplicationSid); + Serializer.toString(request, "SmsApplicationSid", smsApplicationSid, ParameterType.URLENCODED); } + + if (smsFallbackMethod != null) { - request.addPostParam( - "SmsFallbackMethod", - smsFallbackMethod.toString() - ); + Serializer.toString(request, "SmsFallbackMethod", smsFallbackMethod, ParameterType.URLENCODED); } + + if (smsFallbackUrl != null) { - request.addPostParam("SmsFallbackUrl", smsFallbackUrl.toString()); + Serializer.toString(request, "SmsFallbackUrl", smsFallbackUrl, ParameterType.URLENCODED); } + + if (smsMethod != null) { - request.addPostParam("SmsMethod", smsMethod.toString()); + Serializer.toString(request, "SmsMethod", smsMethod, ParameterType.URLENCODED); } + + if (smsUrl != null) { - request.addPostParam("SmsUrl", smsUrl.toString()); + Serializer.toString(request, "SmsUrl", smsUrl, ParameterType.URLENCODED); } + + if (statusCallback != null) { - request.addPostParam("StatusCallback", statusCallback.toString()); + Serializer.toString(request, "StatusCallback", statusCallback, ParameterType.URLENCODED); } + + if (statusCallbackMethod != null) { - request.addPostParam( - "StatusCallbackMethod", - statusCallbackMethod.toString() - ); + Serializer.toString(request, "StatusCallbackMethod", statusCallbackMethod, ParameterType.URLENCODED); } + + if (voiceApplicationSid != null) { - request.addPostParam("VoiceApplicationSid", voiceApplicationSid); + Serializer.toString(request, "VoiceApplicationSid", voiceApplicationSid, ParameterType.URLENCODED); } + + if (voiceCallerIdLookup != null) { - request.addPostParam( - "VoiceCallerIdLookup", - voiceCallerIdLookup.toString() - ); + Serializer.toString(request, "VoiceCallerIdLookup", voiceCallerIdLookup, ParameterType.URLENCODED); } + + if (voiceFallbackMethod != null) { - request.addPostParam( - "VoiceFallbackMethod", - voiceFallbackMethod.toString() - ); + Serializer.toString(request, "VoiceFallbackMethod", voiceFallbackMethod, ParameterType.URLENCODED); } + + if (voiceFallbackUrl != null) { - request.addPostParam( - "VoiceFallbackUrl", - voiceFallbackUrl.toString() - ); + Serializer.toString(request, "VoiceFallbackUrl", voiceFallbackUrl, ParameterType.URLENCODED); } + + if (voiceMethod != null) { - request.addPostParam("VoiceMethod", voiceMethod.toString()); + Serializer.toString(request, "VoiceMethod", voiceMethod, ParameterType.URLENCODED); } + + if (voiceUrl != null) { - request.addPostParam("VoiceUrl", voiceUrl.toString()); + Serializer.toString(request, "VoiceUrl", voiceUrl, ParameterType.URLENCODED); } + + if (identitySid != null) { - request.addPostParam("IdentitySid", identitySid); + Serializer.toString(request, "IdentitySid", identitySid, ParameterType.URLENCODED); } + + if (addressSid != null) { - request.addPostParam("AddressSid", addressSid); + Serializer.toString(request, "AddressSid", addressSid, ParameterType.URLENCODED); } + + if (emergencyStatus != null) { - request.addPostParam("EmergencyStatus", emergencyStatus.toString()); + Serializer.toString(request, "EmergencyStatus", emergencyStatus, ParameterType.URLENCODED); } + + if (emergencyAddressSid != null) { - request.addPostParam("EmergencyAddressSid", emergencyAddressSid); + Serializer.toString(request, "EmergencyAddressSid", emergencyAddressSid, ParameterType.URLENCODED); } + + if (trunkSid != null) { - request.addPostParam("TrunkSid", trunkSid); + Serializer.toString(request, "TrunkSid", trunkSid, ParameterType.URLENCODED); } + + if (voiceReceiveMode != null) { - request.addPostParam( - "VoiceReceiveMode", - voiceReceiveMode.toString() - ); + Serializer.toString(request, "VoiceReceiveMode", voiceReceiveMode, ParameterType.URLENCODED); } + + if (bundleSid != null) { - request.addPostParam("BundleSid", bundleSid); + Serializer.toString(request, "BundleSid", bundleSid, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/incomingphonenumber/TollFreeReader.java b/src/main/java/com/twilio/rest/api/v2010/account/incomingphonenumber/TollFreeReader.java index 3520ddd64e..0b320f25f3 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/incomingphonenumber/TollFreeReader.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/incomingphonenumber/TollFreeReader.java @@ -17,8 +17,9 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; import com.twilio.converter.Promoter; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -30,32 +31,34 @@ public class TollFreeReader extends Reader { - private String pathAccountSid; + private String pathaccountSid; private Boolean beta; private String friendlyName; private com.twilio.type.PhoneNumber phoneNumber; private String origin; private Long pageSize; - public TollFreeReader() {} + public TollFreeReader() { + } - public TollFreeReader(final String pathAccountSid) { - this.pathAccountSid = pathAccountSid; + public TollFreeReader(final String pathaccountSid) { + this.pathaccountSid = pathaccountSid; } + public TollFreeReader setBeta(final Boolean beta) { this.beta = beta; return this; } + public TollFreeReader setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } - public TollFreeReader setPhoneNumber( - final com.twilio.type.PhoneNumber phoneNumber - ) { + + public TollFreeReader setPhoneNumber(final com.twilio.type.PhoneNumber phoneNumber) { this.phoneNumber = phoneNumber; return this; } @@ -69,125 +72,102 @@ public TollFreeReader setOrigin(final String origin) { return this; } + public TollFreeReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/IncomingPhoneNumbers/TollFree.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); + + String path = "/2010-04-01/Accounts/{AccountSid}/IncomingPhoneNumbers/TollFree.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.API.toString(), - path + HttpMethod.GET, + Domains.API.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "TollFree read failed: Unable to connect to server" - ); + throw new ApiConnectionException("TollFree read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "incoming_phone_numbers", - response.getContent(), - TollFree.class, - client.getObjectMapper() - ); + "incoming_phone_numbers", + response.getContent(), + TollFree.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.API.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.API.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (beta != null) { - request.addQueryParam("Beta", beta.toString()); + Serializer.toString(request, "Beta", beta, ParameterType.QUERY); } + + if (friendlyName != null) { - request.addQueryParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.QUERY); } + + if (phoneNumber != null) { - request.addQueryParam("PhoneNumber", phoneNumber.toString()); + Serializer.toString(request, "PhoneNumber", phoneNumber, ParameterType.QUERY); } + + if (origin != null) { - request.addQueryParam("Origin", origin); + Serializer.toString(request, "Origin", origin, ParameterType.QUERY); } + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/incomingphonenumber/assignedaddon/AssignedAddOnExtension.java b/src/main/java/com/twilio/rest/api/v2010/account/incomingphonenumber/assignedaddon/AssignedAddOnExtension.java index 9542116e1e..46b4268439 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/incomingphonenumber/assignedaddon/AssignedAddOnExtension.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/incomingphonenumber/assignedaddon/AssignedAddOnExtension.java @@ -18,82 +18,60 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class AssignedAddOnExtension extends Resource { - private static final long serialVersionUID = 103705040276662L; - public static AssignedAddOnExtensionFetcher fetcher( - final String pathResourceSid, - final String pathAssignedAddOnSid, - final String pathSid - ) { + public static AssignedAddOnExtensionFetcher fetcher(final String pathresourceSid, final String pathassignedAddOnSid, final String pathsid) { return new AssignedAddOnExtensionFetcher( - pathResourceSid, - pathAssignedAddOnSid, - pathSid + pathresourceSid, pathassignedAddOnSid, pathsid ); } - public static AssignedAddOnExtensionFetcher fetcher( - final String pathAccountSid, - final String pathResourceSid, - final String pathAssignedAddOnSid, - final String pathSid - ) { + + public static AssignedAddOnExtensionFetcher fetcher(final String pathaccountSid, final String pathresourceSid, final String pathassignedAddOnSid, final String pathsid) { return new AssignedAddOnExtensionFetcher( - pathAccountSid, - pathResourceSid, - pathAssignedAddOnSid, - pathSid + pathaccountSid, pathresourceSid, pathassignedAddOnSid, pathsid ); } - public static AssignedAddOnExtensionReader reader( - final String pathResourceSid, - final String pathAssignedAddOnSid - ) { + + public static AssignedAddOnExtensionReader reader(final String pathresourceSid, final String pathassignedAddOnSid) { return new AssignedAddOnExtensionReader( - pathResourceSid, - pathAssignedAddOnSid + pathresourceSid, pathassignedAddOnSid ); } - public static AssignedAddOnExtensionReader reader( - final String pathAccountSid, - final String pathResourceSid, - final String pathAssignedAddOnSid - ) { + + public static AssignedAddOnExtensionReader reader(final String pathaccountSid, final String pathresourceSid, final String pathassignedAddOnSid) { return new AssignedAddOnExtensionReader( - pathAccountSid, - pathResourceSid, - pathAssignedAddOnSid + pathaccountSid, pathresourceSid, pathassignedAddOnSid ); } + /** * Converts a JSON String into a AssignedAddOnExtension object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return AssignedAddOnExtension object represented by the provided JSON */ - public static AssignedAddOnExtension fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static AssignedAddOnExtension fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, AssignedAddOnExtension.class); @@ -108,14 +86,11 @@ public static AssignedAddOnExtension fromJson( * Converts a JSON InputStream into a AssignedAddOnExtension object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return AssignedAddOnExtension object represented by the provided JSON */ - public static AssignedAddOnExtension fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static AssignedAddOnExtension fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, AssignedAddOnExtension.class); @@ -126,73 +101,59 @@ public static AssignedAddOnExtension fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String resourceSid; + @Getter private final String assignedAddOnSid; + @Getter + private final Boolean enabled; + @Getter private final String friendlyName; + @Getter private final String productName; + @Getter + private final String resourceSid; + @Getter + private final String sid; + @Getter private final String uniqueName; + @Getter private final String uri; - private final Boolean enabled; @JsonCreator private AssignedAddOnExtension( - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("resource_sid") final String resourceSid, - @JsonProperty("assigned_add_on_sid") final String assignedAddOnSid, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("product_name") final String productName, - @JsonProperty("unique_name") final String uniqueName, - @JsonProperty("uri") final String uri, - @JsonProperty("enabled") final Boolean enabled + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("assigned_add_on_sid") final String assignedAddOnSid, + @JsonProperty("enabled") final Boolean enabled, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("product_name") final String productName, + @JsonProperty("resource_sid") final String resourceSid, + @JsonProperty("sid") final String sid, + @JsonProperty("unique_name") final String uniqueName, + @JsonProperty("uri") final String uri ) { - this.sid = sid; this.accountSid = accountSid; - this.resourceSid = resourceSid; this.assignedAddOnSid = assignedAddOnSid; + this.enabled = enabled; this.friendlyName = friendlyName; this.productName = productName; + this.resourceSid = resourceSid; + this.sid = sid; this.uniqueName = uniqueName; this.uri = uri; - this.enabled = enabled; - } - - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getResourceSid() { - return this.resourceSid; - } - - public final String getAssignedAddOnSid() { - return this.assignedAddOnSid; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final String getProductName() { - return this.productName; - } - - public final String getUniqueName() { - return this.uniqueName; - } - - public final String getUri() { - return this.uri; - } - - public final Boolean getEnabled() { - return this.enabled; } @Override @@ -206,32 +167,34 @@ public boolean equals(final Object o) { } AssignedAddOnExtension other = (AssignedAddOnExtension) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(resourceSid, other.resourceSid) && - Objects.equals(assignedAddOnSid, other.assignedAddOnSid) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(productName, other.productName) && - Objects.equals(uniqueName, other.uniqueName) && - Objects.equals(uri, other.uri) && - Objects.equals(enabled, other.enabled) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(assignedAddOnSid, other.assignedAddOnSid) && + Objects.equals(enabled, other.enabled) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(productName, other.productName) && + Objects.equals(resourceSid, other.resourceSid) && + Objects.equals(sid, other.sid) && + Objects.equals(uniqueName, other.uniqueName) && + Objects.equals(uri, other.uri) ); } @Override public int hashCode() { return Objects.hash( - sid, - accountSid, - resourceSid, - assignedAddOnSid, - friendlyName, - productName, - uniqueName, - uri, - enabled + accountSid, + assignedAddOnSid, + enabled, + friendlyName, + productName, + resourceSid, + sid, + uniqueName, + uri ); } + + } + diff --git a/src/main/java/com/twilio/rest/api/v2010/account/incomingphonenumber/assignedaddon/AssignedAddOnExtensionFetcher.java b/src/main/java/com/twilio/rest/api/v2010/account/incomingphonenumber/assignedaddon/AssignedAddOnExtensionFetcher.java index e0ce28e8ee..b90864c5fe 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/incomingphonenumber/assignedaddon/AssignedAddOnExtensionFetcher.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/incomingphonenumber/assignedaddon/AssignedAddOnExtensionFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.api.v2010.account.incomingphonenumber.assignedaddon; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,91 +24,59 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class AssignedAddOnExtensionFetcher - extends Fetcher { +public class AssignedAddOnExtensionFetcher extends Fetcher { - private String pathResourceSid; - private String pathAssignedAddOnSid; - private String pathSid; - private String pathAccountSid; + private String pathaccountSid; + private String pathresourceSid; + private String pathassignedAddOnSid; + private String pathsid; - public AssignedAddOnExtensionFetcher( - final String pathResourceSid, - final String pathAssignedAddOnSid, - final String pathSid - ) { - this.pathResourceSid = pathResourceSid; - this.pathAssignedAddOnSid = pathAssignedAddOnSid; - this.pathSid = pathSid; + public AssignedAddOnExtensionFetcher(final String pathresourceSid, final String pathassignedAddOnSid, final String pathsid) { + this.pathresourceSid = pathresourceSid; + this.pathassignedAddOnSid = pathassignedAddOnSid; + this.pathsid = pathsid; } - public AssignedAddOnExtensionFetcher( - final String pathAccountSid, - final String pathResourceSid, - final String pathAssignedAddOnSid, - final String pathSid - ) { - this.pathAccountSid = pathAccountSid; - this.pathResourceSid = pathResourceSid; - this.pathAssignedAddOnSid = pathAssignedAddOnSid; - this.pathSid = pathSid; + public AssignedAddOnExtensionFetcher(final String pathaccountSid, final String pathresourceSid, final String pathassignedAddOnSid, final String pathsid) { + this.pathaccountSid = pathaccountSid; + this.pathresourceSid = pathresourceSid; + this.pathassignedAddOnSid = pathassignedAddOnSid; + this.pathsid = pathsid; } + @Override public AssignedAddOnExtension fetch(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/IncomingPhoneNumbers/{ResourceSid}/AssignedAddOns/{AssignedAddOnSid}/Extensions/{Sid}.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = - path.replace( - "{" + "ResourceSid" + "}", - this.pathResourceSid.toString() - ); - path = - path.replace( - "{" + "AssignedAddOnSid" + "}", - this.pathAssignedAddOnSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/2010-04-01/Accounts/{AccountSid}/IncomingPhoneNumbers/{ResourceSid}/AssignedAddOns/{AssignedAddOnSid}/Extensions/{Sid}.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "ResourceSid" + "}", this.pathresourceSid.toString()); + path = path.replace("{" + "AssignedAddOnSid" + "}", this.pathassignedAddOnSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.API.toString(), - path + HttpMethod.GET, + Domains.API.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "AssignedAddOnExtension fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("AssignedAddOnExtension fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return AssignedAddOnExtension.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return AssignedAddOnExtension.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/incomingphonenumber/assignedaddon/AssignedAddOnExtensionReader.java b/src/main/java/com/twilio/rest/api/v2010/account/incomingphonenumber/assignedaddon/AssignedAddOnExtensionReader.java index 509a8f9cd2..6e8be53465 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/incomingphonenumber/assignedaddon/AssignedAddOnExtensionReader.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/incomingphonenumber/assignedaddon/AssignedAddOnExtensionReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,153 +28,102 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class AssignedAddOnExtensionReader - extends Reader { +public class AssignedAddOnExtensionReader extends Reader { - private String pathResourceSid; - private String pathAssignedAddOnSid; - private String pathAccountSid; + private String pathaccountSid; + private String pathresourceSid; + private String pathassignedAddOnSid; private Long pageSize; - public AssignedAddOnExtensionReader( - final String pathResourceSid, - final String pathAssignedAddOnSid - ) { - this.pathResourceSid = pathResourceSid; - this.pathAssignedAddOnSid = pathAssignedAddOnSid; + public AssignedAddOnExtensionReader(final String pathresourceSid, final String pathassignedAddOnSid) { + this.pathresourceSid = pathresourceSid; + this.pathassignedAddOnSid = pathassignedAddOnSid; } - public AssignedAddOnExtensionReader( - final String pathAccountSid, - final String pathResourceSid, - final String pathAssignedAddOnSid - ) { - this.pathAccountSid = pathAccountSid; - this.pathResourceSid = pathResourceSid; - this.pathAssignedAddOnSid = pathAssignedAddOnSid; + public AssignedAddOnExtensionReader(final String pathaccountSid, final String pathresourceSid, final String pathassignedAddOnSid) { + this.pathaccountSid = pathaccountSid; + this.pathresourceSid = pathresourceSid; + this.pathassignedAddOnSid = pathassignedAddOnSid; } + public AssignedAddOnExtensionReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override - public ResourceSet read( - final TwilioRestClient client - ) { + public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } - public Page firstPage( - final TwilioRestClient client - ) { - String path = - "/2010-04-01/Accounts/{AccountSid}/IncomingPhoneNumbers/{ResourceSid}/AssignedAddOns/{AssignedAddOnSid}/Extensions.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = - path.replace( - "{" + "ResourceSid" + "}", - this.pathResourceSid.toString() - ); - path = - path.replace( - "{" + "AssignedAddOnSid" + "}", - this.pathAssignedAddOnSid.toString() - ); + public Page firstPage(final TwilioRestClient client) { + + String path = "/2010-04-01/Accounts/{AccountSid}/IncomingPhoneNumbers/{ResourceSid}/AssignedAddOns/{AssignedAddOnSid}/Extensions.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "ResourceSid" + "}", this.pathresourceSid.toString()); + path = path.replace("{" + "AssignedAddOnSid" + "}", this.pathassignedAddOnSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.API.toString(), - path + HttpMethod.GET, + Domains.API.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "AssignedAddOnExtension read failed: Unable to connect to server" - ); + throw new ApiConnectionException("AssignedAddOnExtension read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "extensions", - response.getContent(), - AssignedAddOnExtension.class, - client.getObjectMapper() - ); + "extensions", + response.getContent(), + AssignedAddOnExtension.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.API.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.API.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/message/Feedback.java b/src/main/java/com/twilio/rest/api/v2010/account/message/Feedback.java index 66db8761d3..96e7e5465f 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/message/Feedback.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/message/Feedback.java @@ -18,48 +18,70 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.time.ZonedDateTime; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Feedback extends Resource { - private static final long serialVersionUID = 229414222116486L; - public static FeedbackCreator creator(final String pathMessageSid) { - return new FeedbackCreator(pathMessageSid); + public static FeedbackCreator creator(final String pathmessageSid) { + return new FeedbackCreator( + pathmessageSid + ); } - public static FeedbackCreator creator( - final String pathAccountSid, - final String pathMessageSid - ) { - return new FeedbackCreator(pathAccountSid, pathMessageSid); + + public static FeedbackCreator creator(final String pathaccountSid, final String pathmessageSid) { + return new FeedbackCreator( + pathaccountSid, pathmessageSid + ); } + + public enum Outcome { + CONFIRMED("confirmed"), + UNCONFIRMED("unconfirmed"); + + private final String value; + + private Outcome(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static Outcome forValue(final String value) { + return Promoter.enumFromString(value, Outcome.values()); + } + } + + /** * Converts a JSON String into a Feedback object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Feedback object represented by the provided JSON */ - public static Feedback fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Feedback fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Feedback.class); @@ -74,14 +96,11 @@ public static Feedback fromJson( * Converts a JSON InputStream into a Feedback object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Feedback object represented by the provided JSON */ - public static Feedback fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Feedback fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Feedback.class); @@ -92,54 +111,51 @@ public static Feedback fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String messageSid; - private final Feedback.Outcome outcome; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; + @Getter + private final String messageSid; + @Getter + private final Feedback.Outcome outcome; + @Getter private final String uri; @JsonCreator private Feedback( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("message_sid") final String messageSid, - @JsonProperty("outcome") final Feedback.Outcome outcome, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("uri") final String uri + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.RFC2822Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.RFC2822Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("message_sid") final String messageSid, + @JsonProperty("outcome") final Feedback.Outcome outcome, + @JsonProperty("uri") final String uri ) { this.accountSid = accountSid; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.messageSid = messageSid; this.outcome = outcome; - this.dateCreated = DateConverter.rfc2822DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.rfc2822DateTimeFromString(dateUpdated); this.uri = uri; } - public final String getAccountSid() { - return this.accountSid; - } - - public final String getMessageSid() { - return this.messageSid; - } - - public final Feedback.Outcome getOutcome() { - return this.outcome; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final String getUri() { - return this.uri; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -151,46 +167,28 @@ public boolean equals(final Object o) { } Feedback other = (Feedback) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(messageSid, other.messageSid) && - Objects.equals(outcome, other.outcome) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(uri, other.uri) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(messageSid, other.messageSid) && + Objects.equals(outcome, other.outcome) && + Objects.equals(uri, other.uri) ); } @Override public int hashCode() { return Objects.hash( - accountSid, - messageSid, - outcome, - dateCreated, - dateUpdated, - uri + accountSid, + dateCreated, + dateUpdated, + messageSid, + outcome, + uri ); } - public enum Outcome { - CONFIRMED("confirmed"), - UNCONFIRMED("unconfirmed"); - - private final String value; - private Outcome(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static Outcome forValue(final String value) { - return Promoter.enumFromString(value, Outcome.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/api/v2010/account/message/FeedbackCreator.java b/src/main/java/com/twilio/rest/api/v2010/account/message/FeedbackCreator.java index 9bbea77e6a..b93a2a62ad 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/message/FeedbackCreator.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/message/FeedbackCreator.java @@ -14,8 +14,11 @@ package com.twilio.rest.api.v2010.account.message; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,82 +30,68 @@ public class FeedbackCreator extends Creator { - private String pathMessageSid; - private String pathAccountSid; + private String pathaccountSid; + private String pathmessageSid; private Feedback.Outcome outcome; - public FeedbackCreator(final String pathMessageSid) { - this.pathMessageSid = pathMessageSid; + public FeedbackCreator(final String pathmessageSid) { + this.pathmessageSid = pathmessageSid; } - public FeedbackCreator( - final String pathAccountSid, - final String pathMessageSid - ) { - this.pathAccountSid = pathAccountSid; - this.pathMessageSid = pathMessageSid; + public FeedbackCreator(final String pathaccountSid, final String pathmessageSid) { + this.pathaccountSid = pathaccountSid; + this.pathmessageSid = pathmessageSid; } + public FeedbackCreator setOutcome(final Feedback.Outcome outcome) { this.outcome = outcome; return this; } + @Override public Feedback create(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/Messages/{MessageSid}/Feedback.json"; - - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = - path.replace( - "{" + "MessageSid" + "}", - this.pathMessageSid.toString() - ); + + String path = "/2010-04-01/Accounts/{AccountSid}/Messages/{MessageSid}/Feedback.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "MessageSid" + "}", this.pathmessageSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.API.toString(), - path + HttpMethod.POST, + Domains.API.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Feedback creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("Feedback creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Feedback.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Feedback.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (outcome != null) { - request.addPostParam("Outcome", outcome.toString()); + Serializer.toString(request, "Outcome", outcome, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/message/Media.java b/src/main/java/com/twilio/rest/api/v2010/account/message/Media.java index 05da369ce0..c6b7b5e2d9 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/message/Media.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/message/Media.java @@ -18,77 +18,76 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.time.ZonedDateTime; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Media extends Resource { - private static final long serialVersionUID = 86856561367712L; - public static MediaDeleter deleter( - final String pathMessageSid, - final String pathSid - ) { - return new MediaDeleter(pathMessageSid, pathSid); + public static MediaDeleter deleter(final String pathmessageSid, final String pathsid) { + return new MediaDeleter( + pathmessageSid, pathsid + ); } - public static MediaDeleter deleter( - final String pathAccountSid, - final String pathMessageSid, - final String pathSid - ) { - return new MediaDeleter(pathAccountSid, pathMessageSid, pathSid); + + public static MediaDeleter deleter(final String pathaccountSid, final String pathmessageSid, final String pathsid) { + return new MediaDeleter( + pathaccountSid, pathmessageSid, pathsid + ); } - public static MediaFetcher fetcher( - final String pathMessageSid, - final String pathSid - ) { - return new MediaFetcher(pathMessageSid, pathSid); + + public static MediaFetcher fetcher(final String pathmessageSid, final String pathsid) { + return new MediaFetcher( + pathmessageSid, pathsid + ); } - public static MediaFetcher fetcher( - final String pathAccountSid, - final String pathMessageSid, - final String pathSid - ) { - return new MediaFetcher(pathAccountSid, pathMessageSid, pathSid); + + public static MediaFetcher fetcher(final String pathaccountSid, final String pathmessageSid, final String pathsid) { + return new MediaFetcher( + pathaccountSid, pathmessageSid, pathsid + ); } - public static MediaReader reader(final String pathMessageSid) { - return new MediaReader(pathMessageSid); + + public static MediaReader reader(final String pathmessageSid) { + return new MediaReader( + pathmessageSid + ); } - public static MediaReader reader( - final String pathAccountSid, - final String pathMessageSid - ) { - return new MediaReader(pathAccountSid, pathMessageSid); + + public static MediaReader reader(final String pathaccountSid, final String pathmessageSid) { + return new MediaReader( + pathaccountSid, pathmessageSid + ); } + /** * Converts a JSON String into a Media object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Media object represented by the provided JSON */ - public static Media fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Media fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Media.class); @@ -103,14 +102,11 @@ public static Media fromJson( * Converts a JSON InputStream into a Media object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Media object represented by the provided JSON */ - public static Media fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Media fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Media.class); @@ -121,61 +117,55 @@ public static Media fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; + @Getter private final String contentType; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; + @Getter private final String parentSid; + @Getter private final String sid; + @Getter private final String uri; @JsonCreator private Media( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("content_type") final String contentType, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("parent_sid") final String parentSid, - @JsonProperty("sid") final String sid, - @JsonProperty("uri") final String uri + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("content_type") final String contentType, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.RFC2822Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.RFC2822Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("parent_sid") final String parentSid, + @JsonProperty("sid") final String sid, + @JsonProperty("uri") final String uri ) { this.accountSid = accountSid; this.contentType = contentType; - this.dateCreated = DateConverter.rfc2822DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.rfc2822DateTimeFromString(dateUpdated); + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.parentSid = parentSid; this.sid = sid; this.uri = uri; } - public final String getAccountSid() { - return this.accountSid; - } - - public final String getContentType() { - return this.contentType; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final String getParentSid() { - return this.parentSid; - } - - public final String getSid() { - return this.sid; - } - - public final String getUri() { - return this.uri; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -187,28 +177,30 @@ public boolean equals(final Object o) { } Media other = (Media) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(contentType, other.contentType) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(parentSid, other.parentSid) && - Objects.equals(sid, other.sid) && - Objects.equals(uri, other.uri) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(contentType, other.contentType) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(parentSid, other.parentSid) && + Objects.equals(sid, other.sid) && + Objects.equals(uri, other.uri) ); } @Override public int hashCode() { return Objects.hash( - accountSid, - contentType, - dateCreated, - dateUpdated, - parentSid, - sid, - uri + accountSid, + contentType, + dateCreated, + dateUpdated, + parentSid, + sid, + uri ); } + + } + diff --git a/src/main/java/com/twilio/rest/api/v2010/account/message/MediaDeleter.java b/src/main/java/com/twilio/rest/api/v2010/account/message/MediaDeleter.java index 170bf2decd..c3ea66a0e6 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/message/MediaDeleter.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/message/MediaDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.api.v2010.account.message; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,68 +26,50 @@ public class MediaDeleter extends Deleter { - private String pathMessageSid; - private String pathSid; - private String pathAccountSid; + private String pathaccountSid; + private String pathmessageSid; + private String pathsid; - public MediaDeleter(final String pathMessageSid, final String pathSid) { - this.pathMessageSid = pathMessageSid; - this.pathSid = pathSid; + public MediaDeleter(final String pathmessageSid, final String pathsid) { + this.pathmessageSid = pathmessageSid; + this.pathsid = pathsid; } - public MediaDeleter( - final String pathAccountSid, - final String pathMessageSid, - final String pathSid - ) { - this.pathAccountSid = pathAccountSid; - this.pathMessageSid = pathMessageSid; - this.pathSid = pathSid; + public MediaDeleter(final String pathaccountSid, final String pathmessageSid, final String pathsid) { + this.pathaccountSid = pathaccountSid; + this.pathmessageSid = pathmessageSid; + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/Messages/{MessageSid}/Media/{Sid}.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = - path.replace( - "{" + "MessageSid" + "}", - this.pathMessageSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/2010-04-01/Accounts/{AccountSid}/Messages/{MessageSid}/Media/{Sid}.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "MessageSid" + "}", this.pathmessageSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.API.toString(), - path + HttpMethod.DELETE, + Domains.API.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Media delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("Media delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/message/MediaFetcher.java b/src/main/java/com/twilio/rest/api/v2010/account/message/MediaFetcher.java index e1b52db522..ca03cd1247 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/message/MediaFetcher.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/message/MediaFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.api.v2010.account.message; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,72 +26,53 @@ public class MediaFetcher extends Fetcher { - private String pathMessageSid; - private String pathSid; - private String pathAccountSid; + private String pathaccountSid; + private String pathmessageSid; + private String pathsid; - public MediaFetcher(final String pathMessageSid, final String pathSid) { - this.pathMessageSid = pathMessageSid; - this.pathSid = pathSid; + public MediaFetcher(final String pathmessageSid, final String pathsid) { + this.pathmessageSid = pathmessageSid; + this.pathsid = pathsid; } - public MediaFetcher( - final String pathAccountSid, - final String pathMessageSid, - final String pathSid - ) { - this.pathAccountSid = pathAccountSid; - this.pathMessageSid = pathMessageSid; - this.pathSid = pathSid; + public MediaFetcher(final String pathaccountSid, final String pathmessageSid, final String pathsid) { + this.pathaccountSid = pathaccountSid; + this.pathmessageSid = pathmessageSid; + this.pathsid = pathsid; } + @Override public Media fetch(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/Messages/{MessageSid}/Media/{Sid}.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = - path.replace( - "{" + "MessageSid" + "}", - this.pathMessageSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/2010-04-01/Accounts/{AccountSid}/Messages/{MessageSid}/Media/{Sid}.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "MessageSid" + "}", this.pathmessageSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.API.toString(), - path + HttpMethod.GET, + Domains.API.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Media fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Media fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Media.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/message/MediaReader.java b/src/main/java/com/twilio/rest/api/v2010/account/message/MediaReader.java index 12bfbf474b..6764a8457d 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/message/MediaReader.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/message/MediaReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -26,177 +27,137 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.time.ZonedDateTime; -import java.time.format.DateTimeFormatter; public class MediaReader extends Reader { - private String pathMessageSid; - private String pathAccountSid; + private String pathaccountSid; + private String pathmessageSid; private ZonedDateTime dateCreated; private ZonedDateTime dateCreatedBefore; private ZonedDateTime dateCreatedAfter; private Long pageSize; - public MediaReader(final String pathMessageSid) { - this.pathMessageSid = pathMessageSid; + public MediaReader(final String pathmessageSid) { + this.pathmessageSid = pathmessageSid; } - public MediaReader( - final String pathAccountSid, - final String pathMessageSid - ) { - this.pathAccountSid = pathAccountSid; - this.pathMessageSid = pathMessageSid; + public MediaReader(final String pathaccountSid, final String pathmessageSid) { + this.pathaccountSid = pathaccountSid; + this.pathmessageSid = pathmessageSid; } + public MediaReader setDateCreated(final ZonedDateTime dateCreated) { this.dateCreated = dateCreated; return this; } - public MediaReader setDateCreatedBefore( - final ZonedDateTime dateCreatedBefore - ) { + + public MediaReader setDateCreatedBefore(final ZonedDateTime dateCreatedBefore) { this.dateCreatedBefore = dateCreatedBefore; return this; } - public MediaReader setDateCreatedAfter( - final ZonedDateTime dateCreatedAfter - ) { + + public MediaReader setDateCreatedAfter(final ZonedDateTime dateCreatedAfter) { this.dateCreatedAfter = dateCreatedAfter; return this; } + public MediaReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/Messages/{MessageSid}/Media.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = - path.replace( - "{" + "MessageSid" + "}", - this.pathMessageSid.toString() - ); + + String path = "/2010-04-01/Accounts/{AccountSid}/Messages/{MessageSid}/Media.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "MessageSid" + "}", this.pathmessageSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.API.toString(), - path + HttpMethod.GET, + Domains.API.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Media read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Media read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "media_list", - response.getContent(), - Media.class, - client.getObjectMapper() - ); + "media_list", + response.getContent(), + Media.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.API.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.API.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (dateCreated != null) { - request.addQueryParam( - "DateCreated", - dateCreated.format( - DateTimeFormatter.ofPattern( - Request.QUERY_STRING_DATE_TIME_FORMAT - ) - ) - ); - } else if (dateCreatedAfter != null || dateCreatedBefore != null) { - request.addQueryDateTimeRange( - "DateCreated", - dateCreatedAfter, - dateCreatedBefore - ); + Serializer.toString(request, "DateCreated", dateCreated, ParameterType.QUERY); } - if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + + + if (dateCreatedBefore != null) { + Serializer.toString(request, "DateCreated<", dateCreatedBefore, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); + + if (dateCreatedAfter != null) { + Serializer.toString(request, "DateCreated>", dateCreatedAfter, ParameterType.QUERY); } + + + if (pageSize != null) { + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); + } + + } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/queue/Member.java b/src/main/java/com/twilio/rest/api/v2010/account/queue/Member.java index 9ce1680c73..50eeb79609 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/queue/Member.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/queue/Member.java @@ -18,85 +18,77 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Member extends Resource { - private static final long serialVersionUID = 196464556782918L; - public static MemberFetcher fetcher( - final String pathQueueSid, - final String pathCallSid - ) { - return new MemberFetcher(pathQueueSid, pathCallSid); + public static MemberFetcher fetcher(final String pathqueueSid, final String pathcallSid) { + return new MemberFetcher( + pathqueueSid, pathcallSid + ); } - public static MemberFetcher fetcher( - final String pathAccountSid, - final String pathQueueSid, - final String pathCallSid - ) { - return new MemberFetcher(pathAccountSid, pathQueueSid, pathCallSid); + + public static MemberFetcher fetcher(final String pathaccountSid, final String pathqueueSid, final String pathcallSid) { + return new MemberFetcher( + pathaccountSid, pathqueueSid, pathcallSid + ); } - public static MemberReader reader(final String pathQueueSid) { - return new MemberReader(pathQueueSid); + + public static MemberReader reader(final String pathqueueSid) { + return new MemberReader( + pathqueueSid + ); } - public static MemberReader reader( - final String pathAccountSid, - final String pathQueueSid - ) { - return new MemberReader(pathAccountSid, pathQueueSid); + + public static MemberReader reader(final String pathaccountSid, final String pathqueueSid) { + return new MemberReader( + pathaccountSid, pathqueueSid + ); } - public static MemberUpdater updater( - final String pathQueueSid, - final String pathCallSid, - final URI url - ) { - return new MemberUpdater(pathQueueSid, pathCallSid, url); + + public static MemberUpdater updater(final String pathqueueSid, final String pathcallSid, final URI url) { + return new MemberUpdater( + pathqueueSid, pathcallSid, url + ); } - public static MemberUpdater updater( - final String pathAccountSid, - final String pathQueueSid, - final String pathCallSid, - final URI url - ) { + + public static MemberUpdater updater(final String pathaccountSid, final String pathqueueSid, final String pathcallSid, final URI url) { return new MemberUpdater( - pathAccountSid, - pathQueueSid, - pathCallSid, - url + pathaccountSid, pathqueueSid, pathcallSid, url ); } + /** * Converts a JSON String into a Member object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Member object represented by the provided JSON */ - public static Member fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Member fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Member.class); @@ -111,14 +103,11 @@ public static Member fromJson( * Converts a JSON InputStream into a Member object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Member object represented by the provided JSON */ - public static Member fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Member fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Member.class); @@ -129,53 +118,48 @@ public static Member fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String callSid; + @Getter private final ZonedDateTime dateEnqueued; + @Getter private final Integer position; + @Getter + private final String queueSid; + @Getter private final String uri; + @Getter private final Integer waitTime; - private final String queueSid; @JsonCreator private Member( - @JsonProperty("call_sid") final String callSid, - @JsonProperty("date_enqueued") final String dateEnqueued, - @JsonProperty("position") final Integer position, - @JsonProperty("uri") final String uri, - @JsonProperty("wait_time") final Integer waitTime, - @JsonProperty("queue_sid") final String queueSid + @JsonProperty("call_sid") final String callSid, + @JsonProperty("date_enqueued") + @JsonDeserialize(using = com.twilio.converter.RFC2822Deserializer.class) final ZonedDateTime dateEnqueued, + @JsonProperty("position") final Integer position, + @JsonProperty("queue_sid") final String queueSid, + @JsonProperty("uri") final String uri, + @JsonProperty("wait_time") final Integer waitTime ) { this.callSid = callSid; - this.dateEnqueued = - DateConverter.rfc2822DateTimeFromString(dateEnqueued); + this.dateEnqueued = dateEnqueued; this.position = position; + this.queueSid = queueSid; this.uri = uri; this.waitTime = waitTime; - this.queueSid = queueSid; - } - - public final String getCallSid() { - return this.callSid; - } - - public final ZonedDateTime getDateEnqueued() { - return this.dateEnqueued; - } - - public final Integer getPosition() { - return this.position; - } - - public final String getUri() { - return this.uri; - } - - public final Integer getWaitTime() { - return this.waitTime; - } - - public final String getQueueSid() { - return this.queueSid; } @Override @@ -189,26 +173,28 @@ public boolean equals(final Object o) { } Member other = (Member) o; - return ( - Objects.equals(callSid, other.callSid) && - Objects.equals(dateEnqueued, other.dateEnqueued) && - Objects.equals(position, other.position) && - Objects.equals(uri, other.uri) && - Objects.equals(waitTime, other.waitTime) && - Objects.equals(queueSid, other.queueSid) + Objects.equals(callSid, other.callSid) && + Objects.equals(dateEnqueued, other.dateEnqueued) && + Objects.equals(position, other.position) && + Objects.equals(queueSid, other.queueSid) && + Objects.equals(uri, other.uri) && + Objects.equals(waitTime, other.waitTime) ); } @Override public int hashCode() { return Objects.hash( - callSid, - dateEnqueued, - position, - uri, - waitTime, - queueSid + callSid, + dateEnqueued, + position, + queueSid, + uri, + waitTime ); } + + } + diff --git a/src/main/java/com/twilio/rest/api/v2010/account/queue/MemberFetcher.java b/src/main/java/com/twilio/rest/api/v2010/account/queue/MemberFetcher.java index 1598e9dca0..2a0c035883 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/queue/MemberFetcher.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/queue/MemberFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.api.v2010.account.queue; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,69 +26,53 @@ public class MemberFetcher extends Fetcher { - private String pathQueueSid; - private String pathCallSid; - private String pathAccountSid; + private String pathaccountSid; + private String pathqueueSid; + private String pathcallSid; - public MemberFetcher(final String pathQueueSid, final String pathCallSid) { - this.pathQueueSid = pathQueueSid; - this.pathCallSid = pathCallSid; + public MemberFetcher(final String pathqueueSid, final String pathcallSid) { + this.pathqueueSid = pathqueueSid; + this.pathcallSid = pathcallSid; } - public MemberFetcher( - final String pathAccountSid, - final String pathQueueSid, - final String pathCallSid - ) { - this.pathAccountSid = pathAccountSid; - this.pathQueueSid = pathQueueSid; - this.pathCallSid = pathCallSid; + public MemberFetcher(final String pathaccountSid, final String pathqueueSid, final String pathcallSid) { + this.pathaccountSid = pathaccountSid; + this.pathqueueSid = pathqueueSid; + this.pathcallSid = pathcallSid; } + @Override public Member fetch(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/Queues/{QueueSid}/Members/{CallSid}.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = - path.replace("{" + "QueueSid" + "}", this.pathQueueSid.toString()); - path = path.replace("{" + "CallSid" + "}", this.pathCallSid.toString()); + String path = "/2010-04-01/Accounts/{AccountSid}/Queues/{QueueSid}/Members/{CallSid}.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "QueueSid" + "}", this.pathqueueSid.toString()); + path = path.replace("{" + "CallSid" + "}", this.pathcallSid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.API.toString(), - path + HttpMethod.GET, + Domains.API.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Member fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Member fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Member.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/queue/MemberReader.java b/src/main/java/com/twilio/rest/api/v2010/account/queue/MemberReader.java index 378ab70f75..91a1835765 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/queue/MemberReader.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/queue/MemberReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,131 +30,96 @@ public class MemberReader extends Reader { - private String pathQueueSid; - private String pathAccountSid; + private String pathaccountSid; + private String pathqueueSid; private Long pageSize; - public MemberReader(final String pathQueueSid) { - this.pathQueueSid = pathQueueSid; + public MemberReader(final String pathqueueSid) { + this.pathqueueSid = pathqueueSid; } - public MemberReader( - final String pathAccountSid, - final String pathQueueSid - ) { - this.pathAccountSid = pathAccountSid; - this.pathQueueSid = pathQueueSid; + public MemberReader(final String pathaccountSid, final String pathqueueSid) { + this.pathaccountSid = pathaccountSid; + this.pathqueueSid = pathqueueSid; } + public MemberReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/Queues/{QueueSid}/Members.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = - path.replace("{" + "QueueSid" + "}", this.pathQueueSid.toString()); + + String path = "/2010-04-01/Accounts/{AccountSid}/Queues/{QueueSid}/Members.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "QueueSid" + "}", this.pathqueueSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.API.toString(), - path + HttpMethod.GET, + Domains.API.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Member read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Member read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "queue_members", - response.getContent(), - Member.class, - client.getObjectMapper() - ); + "queue_members", + response.getContent(), + Member.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.API.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.API.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/queue/MemberUpdater.java b/src/main/java/com/twilio/rest/api/v2010/account/queue/MemberUpdater.java index 26d73df918..32ee1481dd 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/queue/MemberUpdater.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/queue/MemberUpdater.java @@ -16,7 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; -import com.twilio.converter.Promoter; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,93 +26,72 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.net.URI; public class MemberUpdater extends Updater { - - private String pathQueueSid; - private String pathCallSid; + private String pathaccountSid; + private String pathqueueSid; + private String pathcallSid; private URI url; - private String pathAccountSid; private HttpMethod method; - public MemberUpdater( - final String pathQueueSid, - final String pathCallSid, - final URI url - ) { - this.pathQueueSid = pathQueueSid; - this.pathCallSid = pathCallSid; + public MemberUpdater(final String pathqueueSid, final String pathcallSid, final URI url) { + this.pathqueueSid = pathqueueSid; + this.pathcallSid = pathcallSid; this.url = url; } - public MemberUpdater( - final String pathAccountSid, - final String pathQueueSid, - final String pathCallSid, - final URI url - ) { - this.pathAccountSid = pathAccountSid; - this.pathQueueSid = pathQueueSid; - this.pathCallSid = pathCallSid; + public MemberUpdater(final String pathaccountSid, final String pathqueueSid, final String pathcallSid, final URI url) { + this.pathaccountSid = pathaccountSid; + this.pathqueueSid = pathqueueSid; + this.pathcallSid = pathcallSid; this.url = url; } + public MemberUpdater setUrl(final URI url) { this.url = url; return this; } - public MemberUpdater setUrl(final String url) { - return setUrl(Promoter.uriFromString(url)); - } public MemberUpdater setMethod(final HttpMethod method) { this.method = method; return this; } + @Override public Member update(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/Queues/{QueueSid}/Members/{CallSid}.json"; - - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = - path.replace("{" + "QueueSid" + "}", this.pathQueueSid.toString()); - path = path.replace("{" + "CallSid" + "}", this.pathCallSid.toString()); - path = path.replace("{" + "Url" + "}", this.url.toString()); + + String path = "/2010-04-01/Accounts/{AccountSid}/Queues/{QueueSid}/Members/{CallSid}.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "QueueSid" + "}", this.pathqueueSid.toString()); + path = path.replace("{" + "CallSid" + "}", this.pathcallSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.API.toString(), - path + HttpMethod.POST, + Domains.API.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Member update failed: Unable to connect to server" - ); + throw new ApiConnectionException("Member update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -120,11 +100,16 @@ public Member update(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (url != null) { - request.addPostParam("Url", url.toString()); + Serializer.toString(request, "Url", url, ParameterType.URLENCODED); } + + if (method != null) { - request.addPostParam("Method", method.toString()); + Serializer.toString(request, "Method", method, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/recording/AddOnResult.java b/src/main/java/com/twilio/rest/api/v2010/account/recording/AddOnResult.java index c20e30dcb0..30b83cf4d6 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/recording/AddOnResult.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/recording/AddOnResult.java @@ -18,88 +18,105 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.time.ZonedDateTime; import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class AddOnResult extends Resource { - private static final long serialVersionUID = 121199532836736L; - public static AddOnResultDeleter deleter( - final String pathReferenceSid, - final String pathSid - ) { - return new AddOnResultDeleter(pathReferenceSid, pathSid); + public static AddOnResultDeleter deleter(final String pathreferenceSid, final String pathsid) { + return new AddOnResultDeleter( + pathreferenceSid, pathsid + ); } - public static AddOnResultDeleter deleter( - final String pathAccountSid, - final String pathReferenceSid, - final String pathSid - ) { + + public static AddOnResultDeleter deleter(final String pathaccountSid, final String pathreferenceSid, final String pathsid) { return new AddOnResultDeleter( - pathAccountSid, - pathReferenceSid, - pathSid + pathaccountSid, pathreferenceSid, pathsid ); } - public static AddOnResultFetcher fetcher( - final String pathReferenceSid, - final String pathSid - ) { - return new AddOnResultFetcher(pathReferenceSid, pathSid); + + public static AddOnResultFetcher fetcher(final String pathreferenceSid, final String pathsid) { + return new AddOnResultFetcher( + pathreferenceSid, pathsid + ); } - public static AddOnResultFetcher fetcher( - final String pathAccountSid, - final String pathReferenceSid, - final String pathSid - ) { + + public static AddOnResultFetcher fetcher(final String pathaccountSid, final String pathreferenceSid, final String pathsid) { return new AddOnResultFetcher( - pathAccountSid, - pathReferenceSid, - pathSid + pathaccountSid, pathreferenceSid, pathsid ); } - public static AddOnResultReader reader(final String pathReferenceSid) { - return new AddOnResultReader(pathReferenceSid); + + public static AddOnResultReader reader(final String pathreferenceSid) { + return new AddOnResultReader( + pathreferenceSid + ); } - public static AddOnResultReader reader( - final String pathAccountSid, - final String pathReferenceSid - ) { - return new AddOnResultReader(pathAccountSid, pathReferenceSid); + + public static AddOnResultReader reader(final String pathaccountSid, final String pathreferenceSid) { + return new AddOnResultReader( + pathaccountSid, pathreferenceSid + ); } + + public enum Status { + CANCELED("canceled"), + COMPLETED("completed"), + DELETED("deleted"), + FAILED("failed"), + IN_PROGRESS("in-progress"), + INIT("init"), + PROCESSING("processing"), + QUEUED("queued"); + + private final String value; + + private Status(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static Status forValue(final String value) { + return Promoter.enumFromString(value, Status.values()); + } + } + + /** * Converts a JSON String into a AddOnResult object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return AddOnResult object represented by the provided JSON */ - public static AddOnResult fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static AddOnResult fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, AddOnResult.class); @@ -114,14 +131,11 @@ public static AddOnResult fromJson( * Converts a JSON InputStream into a AddOnResult object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return AddOnResult object represented by the provided JSON */ - public static AddOnResult fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static AddOnResult fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, AddOnResult.class); @@ -132,88 +146,68 @@ public static AddOnResult fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final AddOnResult.Status status; - private final String addOnSid; + @Getter private final String addOnConfigurationSid; + @Getter + private final String addOnSid; + @Getter + private final ZonedDateTime dateCompleted; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; - private final ZonedDateTime dateCompleted; + @Getter private final String referenceSid; + @Getter + private final String sid; + @Getter + private final AddOnResult.Status status; + @Getter private final Map subresourceUris; @JsonCreator private AddOnResult( - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("status") final AddOnResult.Status status, - @JsonProperty("add_on_sid") final String addOnSid, - @JsonProperty( - "add_on_configuration_sid" - ) final String addOnConfigurationSid, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("date_completed") final String dateCompleted, - @JsonProperty("reference_sid") final String referenceSid, - @JsonProperty("subresource_uris") final Map< - String, - String - > subresourceUris + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("add_on_configuration_sid") final String addOnConfigurationSid, + @JsonProperty("add_on_sid") final String addOnSid, + @JsonProperty("date_completed") + @JsonDeserialize(using = com.twilio.converter.RFC2822Deserializer.class) final ZonedDateTime dateCompleted, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.RFC2822Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.RFC2822Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("reference_sid") final String referenceSid, + @JsonProperty("sid") final String sid, + @JsonProperty("status") final AddOnResult.Status status, + @JsonProperty("subresource_uris") final Map subresourceUris ) { - this.sid = sid; this.accountSid = accountSid; - this.status = status; - this.addOnSid = addOnSid; this.addOnConfigurationSid = addOnConfigurationSid; - this.dateCreated = DateConverter.rfc2822DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.rfc2822DateTimeFromString(dateUpdated); - this.dateCompleted = - DateConverter.rfc2822DateTimeFromString(dateCompleted); + this.addOnSid = addOnSid; + this.dateCompleted = dateCompleted; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.referenceSid = referenceSid; + this.sid = sid; + this.status = status; this.subresourceUris = subresourceUris; } - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final AddOnResult.Status getStatus() { - return this.status; - } - - public final String getAddOnSid() { - return this.addOnSid; - } - - public final String getAddOnConfigurationSid() { - return this.addOnConfigurationSid; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final ZonedDateTime getDateCompleted() { - return this.dateCompleted; - } - - public final String getReferenceSid() { - return this.referenceSid; - } - - public final Map getSubresourceUris() { - return this.subresourceUris; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -225,63 +219,36 @@ public boolean equals(final Object o) { } AddOnResult other = (AddOnResult) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(status, other.status) && - Objects.equals(addOnSid, other.addOnSid) && - Objects.equals( - addOnConfigurationSid, - other.addOnConfigurationSid - ) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(dateCompleted, other.dateCompleted) && - Objects.equals(referenceSid, other.referenceSid) && - Objects.equals(subresourceUris, other.subresourceUris) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(addOnConfigurationSid, other.addOnConfigurationSid) && + Objects.equals(addOnSid, other.addOnSid) && + Objects.equals(dateCompleted, other.dateCompleted) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(referenceSid, other.referenceSid) && + Objects.equals(sid, other.sid) && + Objects.equals(status, other.status) && + Objects.equals(subresourceUris, other.subresourceUris) ); } @Override public int hashCode() { return Objects.hash( - sid, - accountSid, - status, - addOnSid, - addOnConfigurationSid, - dateCreated, - dateUpdated, - dateCompleted, - referenceSid, - subresourceUris + accountSid, + addOnConfigurationSid, + addOnSid, + dateCompleted, + dateCreated, + dateUpdated, + referenceSid, + sid, + status, + subresourceUris ); } - public enum Status { - CANCELED("canceled"), - COMPLETED("completed"), - DELETED("deleted"), - FAILED("failed"), - IN_PROGRESS("in-progress"), - INIT("init"), - PROCESSING("processing"), - QUEUED("queued"); - - private final String value; - - private Status(final String value) { - this.value = value; - } - public String toString() { - return value; - } - - @JsonCreator - public static Status forValue(final String value) { - return Promoter.enumFromString(value, Status.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/api/v2010/account/recording/AddOnResultDeleter.java b/src/main/java/com/twilio/rest/api/v2010/account/recording/AddOnResultDeleter.java index cf6dd4043b..59055f8c5e 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/recording/AddOnResultDeleter.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/recording/AddOnResultDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.api.v2010.account.recording; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,71 +26,50 @@ public class AddOnResultDeleter extends Deleter { - private String pathReferenceSid; - private String pathSid; - private String pathAccountSid; + private String pathaccountSid; + private String pathreferenceSid; + private String pathsid; - public AddOnResultDeleter( - final String pathReferenceSid, - final String pathSid - ) { - this.pathReferenceSid = pathReferenceSid; - this.pathSid = pathSid; + public AddOnResultDeleter(final String pathreferenceSid, final String pathsid) { + this.pathreferenceSid = pathreferenceSid; + this.pathsid = pathsid; } - public AddOnResultDeleter( - final String pathAccountSid, - final String pathReferenceSid, - final String pathSid - ) { - this.pathAccountSid = pathAccountSid; - this.pathReferenceSid = pathReferenceSid; - this.pathSid = pathSid; + public AddOnResultDeleter(final String pathaccountSid, final String pathreferenceSid, final String pathsid) { + this.pathaccountSid = pathaccountSid; + this.pathreferenceSid = pathreferenceSid; + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/Recordings/{ReferenceSid}/AddOnResults/{Sid}.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = - path.replace( - "{" + "ReferenceSid" + "}", - this.pathReferenceSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/2010-04-01/Accounts/{AccountSid}/Recordings/{ReferenceSid}/AddOnResults/{Sid}.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "ReferenceSid" + "}", this.pathreferenceSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.API.toString(), - path + HttpMethod.DELETE, + Domains.API.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "AddOnResult delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("AddOnResult delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/recording/AddOnResultFetcher.java b/src/main/java/com/twilio/rest/api/v2010/account/recording/AddOnResultFetcher.java index 2cecd3e97e..3e42298bdc 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/recording/AddOnResultFetcher.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/recording/AddOnResultFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.api.v2010.account.recording; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,78 +26,53 @@ public class AddOnResultFetcher extends Fetcher { - private String pathReferenceSid; - private String pathSid; - private String pathAccountSid; + private String pathaccountSid; + private String pathreferenceSid; + private String pathsid; - public AddOnResultFetcher( - final String pathReferenceSid, - final String pathSid - ) { - this.pathReferenceSid = pathReferenceSid; - this.pathSid = pathSid; + public AddOnResultFetcher(final String pathreferenceSid, final String pathsid) { + this.pathreferenceSid = pathreferenceSid; + this.pathsid = pathsid; } - public AddOnResultFetcher( - final String pathAccountSid, - final String pathReferenceSid, - final String pathSid - ) { - this.pathAccountSid = pathAccountSid; - this.pathReferenceSid = pathReferenceSid; - this.pathSid = pathSid; + public AddOnResultFetcher(final String pathaccountSid, final String pathreferenceSid, final String pathsid) { + this.pathaccountSid = pathaccountSid; + this.pathreferenceSid = pathreferenceSid; + this.pathsid = pathsid; } + @Override public AddOnResult fetch(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/Recordings/{ReferenceSid}/AddOnResults/{Sid}.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = - path.replace( - "{" + "ReferenceSid" + "}", - this.pathReferenceSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/2010-04-01/Accounts/{AccountSid}/Recordings/{ReferenceSid}/AddOnResults/{Sid}.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "ReferenceSid" + "}", this.pathreferenceSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.API.toString(), - path + HttpMethod.GET, + Domains.API.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "AddOnResult fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("AddOnResult fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return AddOnResult.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return AddOnResult.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/recording/AddOnResultReader.java b/src/main/java/com/twilio/rest/api/v2010/account/recording/AddOnResultReader.java index aeb874c4cb..80b3c36952 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/recording/AddOnResultReader.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/recording/AddOnResultReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,134 +30,96 @@ public class AddOnResultReader extends Reader { - private String pathReferenceSid; - private String pathAccountSid; + private String pathaccountSid; + private String pathreferenceSid; private Long pageSize; - public AddOnResultReader(final String pathReferenceSid) { - this.pathReferenceSid = pathReferenceSid; + public AddOnResultReader(final String pathreferenceSid) { + this.pathreferenceSid = pathreferenceSid; } - public AddOnResultReader( - final String pathAccountSid, - final String pathReferenceSid - ) { - this.pathAccountSid = pathAccountSid; - this.pathReferenceSid = pathReferenceSid; + public AddOnResultReader(final String pathaccountSid, final String pathreferenceSid) { + this.pathaccountSid = pathaccountSid; + this.pathreferenceSid = pathreferenceSid; } + public AddOnResultReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/Recordings/{ReferenceSid}/AddOnResults.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = - path.replace( - "{" + "ReferenceSid" + "}", - this.pathReferenceSid.toString() - ); + + String path = "/2010-04-01/Accounts/{AccountSid}/Recordings/{ReferenceSid}/AddOnResults.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "ReferenceSid" + "}", this.pathreferenceSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.API.toString(), - path + HttpMethod.GET, + Domains.API.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "AddOnResult read failed: Unable to connect to server" - ); + throw new ApiConnectionException("AddOnResult read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "add_on_results", - response.getContent(), - AddOnResult.class, - client.getObjectMapper() - ); + "add_on_results", + response.getContent(), + AddOnResult.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.API.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.API.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/recording/Transcription.java b/src/main/java/com/twilio/rest/api/v2010/account/recording/Transcription.java index c265b98c28..a8150e7257 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/recording/Transcription.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/recording/Transcription.java @@ -18,90 +18,101 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.CurrencyDeserializer; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.math.BigDecimal; import java.time.ZonedDateTime; import java.util.Currency; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Transcription extends Resource { - private static final long serialVersionUID = 169453036448500L; - public static TranscriptionDeleter deleter( - final String pathRecordingSid, - final String pathSid - ) { - return new TranscriptionDeleter(pathRecordingSid, pathSid); + public static TranscriptionDeleter deleter(final String pathrecordingSid, final String pathsid) { + return new TranscriptionDeleter( + pathrecordingSid, pathsid + ); } - public static TranscriptionDeleter deleter( - final String pathAccountSid, - final String pathRecordingSid, - final String pathSid - ) { + + public static TranscriptionDeleter deleter(final String pathaccountSid, final String pathrecordingSid, final String pathsid) { return new TranscriptionDeleter( - pathAccountSid, - pathRecordingSid, - pathSid + pathaccountSid, pathrecordingSid, pathsid ); } - public static TranscriptionFetcher fetcher( - final String pathRecordingSid, - final String pathSid - ) { - return new TranscriptionFetcher(pathRecordingSid, pathSid); + + public static TranscriptionFetcher fetcher(final String pathrecordingSid, final String pathsid) { + return new TranscriptionFetcher( + pathrecordingSid, pathsid + ); } - public static TranscriptionFetcher fetcher( - final String pathAccountSid, - final String pathRecordingSid, - final String pathSid - ) { + + public static TranscriptionFetcher fetcher(final String pathaccountSid, final String pathrecordingSid, final String pathsid) { return new TranscriptionFetcher( - pathAccountSid, - pathRecordingSid, - pathSid + pathaccountSid, pathrecordingSid, pathsid ); } - public static TranscriptionReader reader(final String pathRecordingSid) { - return new TranscriptionReader(pathRecordingSid); + + public static TranscriptionReader reader(final String pathrecordingSid) { + return new TranscriptionReader( + pathrecordingSid + ); } - public static TranscriptionReader reader( - final String pathAccountSid, - final String pathRecordingSid - ) { - return new TranscriptionReader(pathAccountSid, pathRecordingSid); + + public static TranscriptionReader reader(final String pathaccountSid, final String pathrecordingSid) { + return new TranscriptionReader( + pathaccountSid, pathrecordingSid + ); } + + public enum Status { + IN_PROGRESS("in-progress"), + COMPLETED("completed"), + FAILED("failed"); + + private final String value; + + private Status(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static Status forValue(final String value) { + return Promoter.enumFromString(value, Status.values()); + } + } + + /** * Converts a JSON String into a Transcription object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Transcription object represented by the provided JSON */ - public static Transcription fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Transcription fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Transcription.class); @@ -116,14 +127,11 @@ public static Transcription fromJson( * Converts a JSON InputStream into a Transcription object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Transcription object represented by the provided JSON */ - public static Transcription fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Transcription fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Transcription.class); @@ -134,42 +142,69 @@ public static Transcription fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; + @Getter private final String apiVersion; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; + @Getter private final String duration; + @Getter private final BigDecimal price; + @Getter private final Currency priceUnit; + @Getter private final String recordingSid; + @Getter private final String sid; + @Getter private final Transcription.Status status; + @Getter private final String transcriptionText; + @Getter private final String type; + @Getter private final String uri; @JsonCreator private Transcription( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("api_version") final String apiVersion, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("duration") final String duration, - @JsonProperty("price") final BigDecimal price, - @JsonProperty("price_unit") @JsonDeserialize( - using = com.twilio.converter.CurrencyDeserializer.class - ) final Currency priceUnit, - @JsonProperty("recording_sid") final String recordingSid, - @JsonProperty("sid") final String sid, - @JsonProperty("status") final Transcription.Status status, - @JsonProperty("transcription_text") final String transcriptionText, - @JsonProperty("type") final String type, - @JsonProperty("uri") final String uri + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("api_version") final String apiVersion, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.RFC2822Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.RFC2822Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("duration") final String duration, + @JsonProperty("price") final BigDecimal price, + @JsonProperty("price_unit") + @JsonDeserialize(using = com.twilio.converter.CurrencyDeserializer.class) final Currency priceUnit, + @JsonProperty("recording_sid") final String recordingSid, + @JsonProperty("sid") final String sid, + @JsonProperty("status") final Transcription.Status status, + @JsonProperty("transcription_text") final String transcriptionText, + @JsonProperty("type") final String type, + @JsonProperty("uri") final String uri ) { this.accountSid = accountSid; this.apiVersion = apiVersion; - this.dateCreated = DateConverter.rfc2822DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.rfc2822DateTimeFromString(dateUpdated); + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.duration = duration; this.price = price; this.priceUnit = priceUnit; @@ -181,58 +216,6 @@ private Transcription( this.uri = uri; } - public final String getAccountSid() { - return this.accountSid; - } - - public final String getApiVersion() { - return this.apiVersion; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final String getDuration() { - return this.duration; - } - - public final BigDecimal getPrice() { - return this.price; - } - - public final Currency getPriceUnit() { - return this.priceUnit; - } - - public final String getRecordingSid() { - return this.recordingSid; - } - - public final String getSid() { - return this.sid; - } - - public final Transcription.Status getStatus() { - return this.status; - } - - public final String getTranscriptionText() { - return this.transcriptionText; - } - - public final String getType() { - return this.type; - } - - public final String getUri() { - return this.uri; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -244,61 +227,42 @@ public boolean equals(final Object o) { } Transcription other = (Transcription) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(apiVersion, other.apiVersion) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(duration, other.duration) && - Objects.equals(price, other.price) && - Objects.equals(priceUnit, other.priceUnit) && - Objects.equals(recordingSid, other.recordingSid) && - Objects.equals(sid, other.sid) && - Objects.equals(status, other.status) && - Objects.equals(transcriptionText, other.transcriptionText) && - Objects.equals(type, other.type) && - Objects.equals(uri, other.uri) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(apiVersion, other.apiVersion) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(duration, other.duration) && + Objects.equals(price, other.price) && + Objects.equals(priceUnit, other.priceUnit) && + Objects.equals(recordingSid, other.recordingSid) && + Objects.equals(sid, other.sid) && + Objects.equals(status, other.status) && + Objects.equals(transcriptionText, other.transcriptionText) && + Objects.equals(type, other.type) && + Objects.equals(uri, other.uri) ); } @Override public int hashCode() { return Objects.hash( - accountSid, - apiVersion, - dateCreated, - dateUpdated, - duration, - price, - priceUnit, - recordingSid, - sid, - status, - transcriptionText, - type, - uri + accountSid, + apiVersion, + dateCreated, + dateUpdated, + duration, + price, + priceUnit, + recordingSid, + sid, + status, + transcriptionText, + type, + uri ); } - public enum Status { - IN_PROGRESS("in-progress"), - COMPLETED("completed"), - FAILED("failed"); - - private final String value; - private Status(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static Status forValue(final String value) { - return Promoter.enumFromString(value, Status.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/api/v2010/account/recording/TranscriptionDeleter.java b/src/main/java/com/twilio/rest/api/v2010/account/recording/TranscriptionDeleter.java index e1447ca841..6eaf3e0a90 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/recording/TranscriptionDeleter.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/recording/TranscriptionDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.api.v2010.account.recording; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,71 +26,50 @@ public class TranscriptionDeleter extends Deleter { - private String pathRecordingSid; - private String pathSid; - private String pathAccountSid; + private String pathaccountSid; + private String pathrecordingSid; + private String pathsid; - public TranscriptionDeleter( - final String pathRecordingSid, - final String pathSid - ) { - this.pathRecordingSid = pathRecordingSid; - this.pathSid = pathSid; + public TranscriptionDeleter(final String pathrecordingSid, final String pathsid) { + this.pathrecordingSid = pathrecordingSid; + this.pathsid = pathsid; } - public TranscriptionDeleter( - final String pathAccountSid, - final String pathRecordingSid, - final String pathSid - ) { - this.pathAccountSid = pathAccountSid; - this.pathRecordingSid = pathRecordingSid; - this.pathSid = pathSid; + public TranscriptionDeleter(final String pathaccountSid, final String pathrecordingSid, final String pathsid) { + this.pathaccountSid = pathaccountSid; + this.pathrecordingSid = pathrecordingSid; + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/Recordings/{RecordingSid}/Transcriptions/{Sid}.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = - path.replace( - "{" + "RecordingSid" + "}", - this.pathRecordingSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/2010-04-01/Accounts/{AccountSid}/Recordings/{RecordingSid}/Transcriptions/{Sid}.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "RecordingSid" + "}", this.pathrecordingSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.API.toString(), - path + HttpMethod.DELETE, + Domains.API.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Transcription delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("Transcription delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/recording/TranscriptionFetcher.java b/src/main/java/com/twilio/rest/api/v2010/account/recording/TranscriptionFetcher.java index e2d393d08c..7fbd519eb6 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/recording/TranscriptionFetcher.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/recording/TranscriptionFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.api.v2010.account.recording; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,78 +26,53 @@ public class TranscriptionFetcher extends Fetcher { - private String pathRecordingSid; - private String pathSid; - private String pathAccountSid; + private String pathaccountSid; + private String pathrecordingSid; + private String pathsid; - public TranscriptionFetcher( - final String pathRecordingSid, - final String pathSid - ) { - this.pathRecordingSid = pathRecordingSid; - this.pathSid = pathSid; + public TranscriptionFetcher(final String pathrecordingSid, final String pathsid) { + this.pathrecordingSid = pathrecordingSid; + this.pathsid = pathsid; } - public TranscriptionFetcher( - final String pathAccountSid, - final String pathRecordingSid, - final String pathSid - ) { - this.pathAccountSid = pathAccountSid; - this.pathRecordingSid = pathRecordingSid; - this.pathSid = pathSid; + public TranscriptionFetcher(final String pathaccountSid, final String pathrecordingSid, final String pathsid) { + this.pathaccountSid = pathaccountSid; + this.pathrecordingSid = pathrecordingSid; + this.pathsid = pathsid; } + @Override public Transcription fetch(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/Recordings/{RecordingSid}/Transcriptions/{Sid}.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = - path.replace( - "{" + "RecordingSid" + "}", - this.pathRecordingSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/2010-04-01/Accounts/{AccountSid}/Recordings/{RecordingSid}/Transcriptions/{Sid}.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "RecordingSid" + "}", this.pathrecordingSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.API.toString(), - path + HttpMethod.GET, + Domains.API.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Transcription fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Transcription fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return Transcription.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Transcription.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/recording/TranscriptionReader.java b/src/main/java/com/twilio/rest/api/v2010/account/recording/TranscriptionReader.java index 679722bfd2..4c10cee1f9 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/recording/TranscriptionReader.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/recording/TranscriptionReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,134 +30,96 @@ public class TranscriptionReader extends Reader { - private String pathRecordingSid; - private String pathAccountSid; + private String pathaccountSid; + private String pathrecordingSid; private Long pageSize; - public TranscriptionReader(final String pathRecordingSid) { - this.pathRecordingSid = pathRecordingSid; + public TranscriptionReader(final String pathrecordingSid) { + this.pathrecordingSid = pathrecordingSid; } - public TranscriptionReader( - final String pathAccountSid, - final String pathRecordingSid - ) { - this.pathAccountSid = pathAccountSid; - this.pathRecordingSid = pathRecordingSid; + public TranscriptionReader(final String pathaccountSid, final String pathrecordingSid) { + this.pathaccountSid = pathaccountSid; + this.pathrecordingSid = pathrecordingSid; } + public TranscriptionReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/Recordings/{RecordingSid}/Transcriptions.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = - path.replace( - "{" + "RecordingSid" + "}", - this.pathRecordingSid.toString() - ); + + String path = "/2010-04-01/Accounts/{AccountSid}/Recordings/{RecordingSid}/Transcriptions.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "RecordingSid" + "}", this.pathrecordingSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.API.toString(), - path + HttpMethod.GET, + Domains.API.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Transcription read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Transcription read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "transcriptions", - response.getContent(), - Transcription.class, - client.getObjectMapper() - ); + "transcriptions", + response.getContent(), + Transcription.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.API.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.API.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/recording/addonresult/Payload.java b/src/main/java/com/twilio/rest/api/v2010/account/recording/addonresult/Payload.java index 81d25db9c4..c81c0ba253 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/recording/addonresult/Payload.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/recording/addonresult/Payload.java @@ -18,109 +18,77 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.time.ZonedDateTime; import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Payload extends Resource { - private static final long serialVersionUID = 241774798598483L; - public static PayloadDeleter deleter( - final String pathReferenceSid, - final String pathAddOnResultSid, - final String pathSid - ) { + public static PayloadDeleter deleter(final String pathreferenceSid, final String pathaddOnResultSid, final String pathsid) { return new PayloadDeleter( - pathReferenceSid, - pathAddOnResultSid, - pathSid + pathreferenceSid, pathaddOnResultSid, pathsid ); } - public static PayloadDeleter deleter( - final String pathAccountSid, - final String pathReferenceSid, - final String pathAddOnResultSid, - final String pathSid - ) { + + public static PayloadDeleter deleter(final String pathaccountSid, final String pathreferenceSid, final String pathaddOnResultSid, final String pathsid) { return new PayloadDeleter( - pathAccountSid, - pathReferenceSid, - pathAddOnResultSid, - pathSid + pathaccountSid, pathreferenceSid, pathaddOnResultSid, pathsid ); } - public static PayloadFetcher fetcher( - final String pathReferenceSid, - final String pathAddOnResultSid, - final String pathSid - ) { + + public static PayloadFetcher fetcher(final String pathreferenceSid, final String pathaddOnResultSid, final String pathsid) { return new PayloadFetcher( - pathReferenceSid, - pathAddOnResultSid, - pathSid + pathreferenceSid, pathaddOnResultSid, pathsid ); } - public static PayloadFetcher fetcher( - final String pathAccountSid, - final String pathReferenceSid, - final String pathAddOnResultSid, - final String pathSid - ) { + + public static PayloadFetcher fetcher(final String pathaccountSid, final String pathreferenceSid, final String pathaddOnResultSid, final String pathsid) { return new PayloadFetcher( - pathAccountSid, - pathReferenceSid, - pathAddOnResultSid, - pathSid + pathaccountSid, pathreferenceSid, pathaddOnResultSid, pathsid ); } - public static PayloadReader reader( - final String pathReferenceSid, - final String pathAddOnResultSid - ) { - return new PayloadReader(pathReferenceSid, pathAddOnResultSid); + + public static PayloadReader reader(final String pathreferenceSid, final String pathaddOnResultSid) { + return new PayloadReader( + pathreferenceSid, pathaddOnResultSid + ); } - public static PayloadReader reader( - final String pathAccountSid, - final String pathReferenceSid, - final String pathAddOnResultSid - ) { + + public static PayloadReader reader(final String pathaccountSid, final String pathreferenceSid, final String pathaddOnResultSid) { return new PayloadReader( - pathAccountSid, - pathReferenceSid, - pathAddOnResultSid + pathaccountSid, pathreferenceSid, pathaddOnResultSid ); } + /** * Converts a JSON String into a Payload object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Payload object represented by the provided JSON */ - public static Payload fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Payload fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Payload.class); @@ -135,14 +103,11 @@ public static Payload fromJson( * Converts a JSON InputStream into a Payload object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Payload object represented by the provided JSON */ - public static Payload fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Payload fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Payload.class); @@ -153,94 +118,71 @@ public static Payload fromJson( } } - private final String sid; - private final String addOnResultSid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String label; - private final String addOnSid; + @Getter private final String addOnConfigurationSid; + @Getter + private final String addOnResultSid; + @Getter + private final String addOnSid; + @Getter private final String contentType; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; + @Getter + private final String label; + @Getter private final String referenceSid; + @Getter + private final String sid; + @Getter private final Map subresourceUris; @JsonCreator private Payload( - @JsonProperty("sid") final String sid, - @JsonProperty("add_on_result_sid") final String addOnResultSid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("label") final String label, - @JsonProperty("add_on_sid") final String addOnSid, - @JsonProperty( - "add_on_configuration_sid" - ) final String addOnConfigurationSid, - @JsonProperty("content_type") final String contentType, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("reference_sid") final String referenceSid, - @JsonProperty("subresource_uris") final Map< - String, - String - > subresourceUris + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("add_on_configuration_sid") final String addOnConfigurationSid, + @JsonProperty("add_on_result_sid") final String addOnResultSid, + @JsonProperty("add_on_sid") final String addOnSid, + @JsonProperty("content_type") final String contentType, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.RFC2822Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.RFC2822Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("label") final String label, + @JsonProperty("reference_sid") final String referenceSid, + @JsonProperty("sid") final String sid, + @JsonProperty("subresource_uris") final Map subresourceUris ) { - this.sid = sid; - this.addOnResultSid = addOnResultSid; this.accountSid = accountSid; - this.label = label; - this.addOnSid = addOnSid; this.addOnConfigurationSid = addOnConfigurationSid; + this.addOnResultSid = addOnResultSid; + this.addOnSid = addOnSid; this.contentType = contentType; - this.dateCreated = DateConverter.rfc2822DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.rfc2822DateTimeFromString(dateUpdated); + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; + this.label = label; this.referenceSid = referenceSid; + this.sid = sid; this.subresourceUris = subresourceUris; } - public final String getSid() { - return this.sid; - } - - public final String getAddOnResultSid() { - return this.addOnResultSid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getLabel() { - return this.label; - } - - public final String getAddOnSid() { - return this.addOnSid; - } - - public final String getAddOnConfigurationSid() { - return this.addOnConfigurationSid; - } - - public final String getContentType() { - return this.contentType; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final String getReferenceSid() { - return this.referenceSid; - } - - public final Map getSubresourceUris() { - return this.subresourceUris; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -252,39 +194,38 @@ public boolean equals(final Object o) { } Payload other = (Payload) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(addOnResultSid, other.addOnResultSid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(label, other.label) && - Objects.equals(addOnSid, other.addOnSid) && - Objects.equals( - addOnConfigurationSid, - other.addOnConfigurationSid - ) && - Objects.equals(contentType, other.contentType) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(referenceSid, other.referenceSid) && - Objects.equals(subresourceUris, other.subresourceUris) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(addOnConfigurationSid, other.addOnConfigurationSid) && + Objects.equals(addOnResultSid, other.addOnResultSid) && + Objects.equals(addOnSid, other.addOnSid) && + Objects.equals(contentType, other.contentType) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(label, other.label) && + Objects.equals(referenceSid, other.referenceSid) && + Objects.equals(sid, other.sid) && + Objects.equals(subresourceUris, other.subresourceUris) ); } @Override public int hashCode() { return Objects.hash( - sid, - addOnResultSid, - accountSid, - label, - addOnSid, - addOnConfigurationSid, - contentType, - dateCreated, - dateUpdated, - referenceSid, - subresourceUris + accountSid, + addOnConfigurationSid, + addOnResultSid, + addOnSid, + contentType, + dateCreated, + dateUpdated, + label, + referenceSid, + sid, + subresourceUris ); } + + } + diff --git a/src/main/java/com/twilio/rest/api/v2010/account/recording/addonresult/PayloadDeleter.java b/src/main/java/com/twilio/rest/api/v2010/account/recording/addonresult/PayloadDeleter.java index 8d28decf45..18363fca70 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/recording/addonresult/PayloadDeleter.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/recording/addonresult/PayloadDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.api.v2010.account.recording.addonresult; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,81 +26,54 @@ public class PayloadDeleter extends Deleter { - private String pathReferenceSid; - private String pathAddOnResultSid; - private String pathSid; - private String pathAccountSid; + private String pathaccountSid; + private String pathreferenceSid; + private String pathaddOnResultSid; + private String pathsid; - public PayloadDeleter( - final String pathReferenceSid, - final String pathAddOnResultSid, - final String pathSid - ) { - this.pathReferenceSid = pathReferenceSid; - this.pathAddOnResultSid = pathAddOnResultSid; - this.pathSid = pathSid; + public PayloadDeleter(final String pathreferenceSid, final String pathaddOnResultSid, final String pathsid) { + this.pathreferenceSid = pathreferenceSid; + this.pathaddOnResultSid = pathaddOnResultSid; + this.pathsid = pathsid; } - public PayloadDeleter( - final String pathAccountSid, - final String pathReferenceSid, - final String pathAddOnResultSid, - final String pathSid - ) { - this.pathAccountSid = pathAccountSid; - this.pathReferenceSid = pathReferenceSid; - this.pathAddOnResultSid = pathAddOnResultSid; - this.pathSid = pathSid; + public PayloadDeleter(final String pathaccountSid, final String pathreferenceSid, final String pathaddOnResultSid, final String pathsid) { + this.pathaccountSid = pathaccountSid; + this.pathreferenceSid = pathreferenceSid; + this.pathaddOnResultSid = pathaddOnResultSid; + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/Recordings/{ReferenceSid}/AddOnResults/{AddOnResultSid}/Payloads/{Sid}.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = - path.replace( - "{" + "ReferenceSid" + "}", - this.pathReferenceSid.toString() - ); - path = - path.replace( - "{" + "AddOnResultSid" + "}", - this.pathAddOnResultSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/2010-04-01/Accounts/{AccountSid}/Recordings/{ReferenceSid}/AddOnResults/{AddOnResultSid}/Payloads/{Sid}.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "ReferenceSid" + "}", this.pathreferenceSid.toString()); + path = path.replace("{" + "AddOnResultSid" + "}", this.pathaddOnResultSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.API.toString(), - path + HttpMethod.DELETE, + Domains.API.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Payload delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("Payload delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/recording/addonresult/PayloadFetcher.java b/src/main/java/com/twilio/rest/api/v2010/account/recording/addonresult/PayloadFetcher.java index c21fda72d6..6cee47d7bc 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/recording/addonresult/PayloadFetcher.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/recording/addonresult/PayloadFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.api.v2010.account.recording.addonresult; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,85 +26,57 @@ public class PayloadFetcher extends Fetcher { - private String pathReferenceSid; - private String pathAddOnResultSid; - private String pathSid; - private String pathAccountSid; + private String pathaccountSid; + private String pathreferenceSid; + private String pathaddOnResultSid; + private String pathsid; - public PayloadFetcher( - final String pathReferenceSid, - final String pathAddOnResultSid, - final String pathSid - ) { - this.pathReferenceSid = pathReferenceSid; - this.pathAddOnResultSid = pathAddOnResultSid; - this.pathSid = pathSid; + public PayloadFetcher(final String pathreferenceSid, final String pathaddOnResultSid, final String pathsid) { + this.pathreferenceSid = pathreferenceSid; + this.pathaddOnResultSid = pathaddOnResultSid; + this.pathsid = pathsid; } - public PayloadFetcher( - final String pathAccountSid, - final String pathReferenceSid, - final String pathAddOnResultSid, - final String pathSid - ) { - this.pathAccountSid = pathAccountSid; - this.pathReferenceSid = pathReferenceSid; - this.pathAddOnResultSid = pathAddOnResultSid; - this.pathSid = pathSid; + public PayloadFetcher(final String pathaccountSid, final String pathreferenceSid, final String pathaddOnResultSid, final String pathsid) { + this.pathaccountSid = pathaccountSid; + this.pathreferenceSid = pathreferenceSid; + this.pathaddOnResultSid = pathaddOnResultSid; + this.pathsid = pathsid; } + @Override public Payload fetch(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/Recordings/{ReferenceSid}/AddOnResults/{AddOnResultSid}/Payloads/{Sid}.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = - path.replace( - "{" + "ReferenceSid" + "}", - this.pathReferenceSid.toString() - ); - path = - path.replace( - "{" + "AddOnResultSid" + "}", - this.pathAddOnResultSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/2010-04-01/Accounts/{AccountSid}/Recordings/{ReferenceSid}/AddOnResults/{AddOnResultSid}/Payloads/{Sid}.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "ReferenceSid" + "}", this.pathreferenceSid.toString()); + path = path.replace("{" + "AddOnResultSid" + "}", this.pathaddOnResultSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.API.toString(), - path + HttpMethod.GET, + Domains.API.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Payload fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Payload fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Payload.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/recording/addonresult/PayloadReader.java b/src/main/java/com/twilio/rest/api/v2010/account/recording/addonresult/PayloadReader.java index ea335545a7..89518cb85a 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/recording/addonresult/PayloadReader.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/recording/addonresult/PayloadReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,146 +30,100 @@ public class PayloadReader extends Reader { - private String pathReferenceSid; - private String pathAddOnResultSid; - private String pathAccountSid; + private String pathaccountSid; + private String pathreferenceSid; + private String pathaddOnResultSid; private Long pageSize; - public PayloadReader( - final String pathReferenceSid, - final String pathAddOnResultSid - ) { - this.pathReferenceSid = pathReferenceSid; - this.pathAddOnResultSid = pathAddOnResultSid; + public PayloadReader(final String pathreferenceSid, final String pathaddOnResultSid) { + this.pathreferenceSid = pathreferenceSid; + this.pathaddOnResultSid = pathaddOnResultSid; } - public PayloadReader( - final String pathAccountSid, - final String pathReferenceSid, - final String pathAddOnResultSid - ) { - this.pathAccountSid = pathAccountSid; - this.pathReferenceSid = pathReferenceSid; - this.pathAddOnResultSid = pathAddOnResultSid; + public PayloadReader(final String pathaccountSid, final String pathreferenceSid, final String pathaddOnResultSid) { + this.pathaccountSid = pathaccountSid; + this.pathreferenceSid = pathreferenceSid; + this.pathaddOnResultSid = pathaddOnResultSid; } + public PayloadReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/Recordings/{ReferenceSid}/AddOnResults/{AddOnResultSid}/Payloads.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = - path.replace( - "{" + "ReferenceSid" + "}", - this.pathReferenceSid.toString() - ); - path = - path.replace( - "{" + "AddOnResultSid" + "}", - this.pathAddOnResultSid.toString() - ); + + String path = "/2010-04-01/Accounts/{AccountSid}/Recordings/{ReferenceSid}/AddOnResults/{AddOnResultSid}/Payloads.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "ReferenceSid" + "}", this.pathreferenceSid.toString()); + path = path.replace("{" + "AddOnResultSid" + "}", this.pathaddOnResultSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.API.toString(), - path + HttpMethod.GET, + Domains.API.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Payload read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Payload read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "payloads", - response.getContent(), - Payload.class, - client.getObjectMapper() - ); + "payloads", + response.getContent(), + Payload.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.API.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.API.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/recording/addonresult/payload/Data.java b/src/main/java/com/twilio/rest/api/v2010/account/recording/addonresult/payload/Data.java index d6b0887557..430dd82f3c 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/recording/addonresult/payload/Data.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/recording/addonresult/payload/Data.java @@ -18,61 +18,47 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Data extends Resource { - private static final long serialVersionUID = 245900587626041L; - public static DataFetcher fetcher( - final String pathReferenceSid, - final String pathAddOnResultSid, - final String pathPayloadSid - ) { + public static DataFetcher fetcher(final String pathreferenceSid, final String pathaddOnResultSid, final String pathpayloadSid) { return new DataFetcher( - pathReferenceSid, - pathAddOnResultSid, - pathPayloadSid + pathreferenceSid, pathaddOnResultSid, pathpayloadSid ); } - public static DataFetcher fetcher( - final String pathAccountSid, - final String pathReferenceSid, - final String pathAddOnResultSid, - final String pathPayloadSid - ) { + + public static DataFetcher fetcher(final String pathaccountSid, final String pathreferenceSid, final String pathaddOnResultSid, final String pathpayloadSid) { return new DataFetcher( - pathAccountSid, - pathReferenceSid, - pathAddOnResultSid, - pathPayloadSid + pathaccountSid, pathreferenceSid, pathaddOnResultSid, pathpayloadSid ); } + /** * Converts a JSON String into a Data object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Data object represented by the provided JSON */ - public static Data fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Data fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Data.class); @@ -87,14 +73,11 @@ public static Data fromJson( * Converts a JSON InputStream into a Data object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Data object represented by the provided JSON */ - public static Data fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Data fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Data.class); @@ -105,17 +88,29 @@ public static Data fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final URI redirectTo; @JsonCreator - private Data(@JsonProperty("redirect_to") final URI redirectTo) { + private Data( + @JsonProperty("redirect_to") final URI redirectTo + ) { this.redirectTo = redirectTo; } - public final URI getRedirectTo() { - return this.redirectTo; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -127,12 +122,18 @@ public boolean equals(final Object o) { } Data other = (Data) o; - - return Objects.equals(redirectTo, other.redirectTo); + return ( + Objects.equals(redirectTo, other.redirectTo) + ); } @Override public int hashCode() { - return Objects.hash(redirectTo); + return Objects.hash( + redirectTo + ); } + + } + diff --git a/src/main/java/com/twilio/rest/api/v2010/account/recording/addonresult/payload/DataFetcher.java b/src/main/java/com/twilio/rest/api/v2010/account/recording/addonresult/payload/DataFetcher.java index 6fba4bd96e..d1b0919e39 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/recording/addonresult/payload/DataFetcher.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/recording/addonresult/payload/DataFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.api.v2010.account.recording.addonresult.payload; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,89 +26,57 @@ public class DataFetcher extends Fetcher { - private String pathReferenceSid; - private String pathAddOnResultSid; - private String pathPayloadSid; - private String pathAccountSid; + private String pathaccountSid; + private String pathreferenceSid; + private String pathaddOnResultSid; + private String pathpayloadSid; - public DataFetcher( - final String pathReferenceSid, - final String pathAddOnResultSid, - final String pathPayloadSid - ) { - this.pathReferenceSid = pathReferenceSid; - this.pathAddOnResultSid = pathAddOnResultSid; - this.pathPayloadSid = pathPayloadSid; + public DataFetcher(final String pathreferenceSid, final String pathaddOnResultSid, final String pathpayloadSid) { + this.pathreferenceSid = pathreferenceSid; + this.pathaddOnResultSid = pathaddOnResultSid; + this.pathpayloadSid = pathpayloadSid; } - public DataFetcher( - final String pathAccountSid, - final String pathReferenceSid, - final String pathAddOnResultSid, - final String pathPayloadSid - ) { - this.pathAccountSid = pathAccountSid; - this.pathReferenceSid = pathReferenceSid; - this.pathAddOnResultSid = pathAddOnResultSid; - this.pathPayloadSid = pathPayloadSid; + public DataFetcher(final String pathaccountSid, final String pathreferenceSid, final String pathaddOnResultSid, final String pathpayloadSid) { + this.pathaccountSid = pathaccountSid; + this.pathreferenceSid = pathreferenceSid; + this.pathaddOnResultSid = pathaddOnResultSid; + this.pathpayloadSid = pathpayloadSid; } + @Override public Data fetch(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/Recordings/{ReferenceSid}/AddOnResults/{AddOnResultSid}/Payloads/{PayloadSid}/Data.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = - path.replace( - "{" + "ReferenceSid" + "}", - this.pathReferenceSid.toString() - ); - path = - path.replace( - "{" + "AddOnResultSid" + "}", - this.pathAddOnResultSid.toString() - ); - path = - path.replace( - "{" + "PayloadSid" + "}", - this.pathPayloadSid.toString() - ); + String path = "/2010-04-01/Accounts/{AccountSid}/Recordings/{ReferenceSid}/AddOnResults/{AddOnResultSid}/Payloads/{PayloadSid}/Data.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "ReferenceSid" + "}", this.pathreferenceSid.toString()); + path = path.replace("{" + "AddOnResultSid" + "}", this.pathaddOnResultSid.toString()); + path = path.replace("{" + "PayloadSid" + "}", this.pathpayloadSid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.API.toString(), - path + HttpMethod.GET, + Domains.API.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Data fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Data fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Data.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/sip/CredentialList.java b/src/main/java/com/twilio/rest/api/v2010/account/sip/CredentialList.java index cc2df1ef54..ec40dc678d 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/sip/CredentialList.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/sip/CredentialList.java @@ -18,94 +18,105 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.time.ZonedDateTime; import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class CredentialList extends Resource { - private static final long serialVersionUID = 178395545365846L; public static CredentialListCreator creator(final String friendlyName) { - return new CredentialListCreator(friendlyName); + return new CredentialListCreator( + friendlyName + ); } - public static CredentialListCreator creator( - final String pathAccountSid, - final String friendlyName - ) { - return new CredentialListCreator(pathAccountSid, friendlyName); + + public static CredentialListCreator creator(final String pathaccountSid, final String friendlyName) { + return new CredentialListCreator( + pathaccountSid, friendlyName + ); } - public static CredentialListDeleter deleter(final String pathSid) { - return new CredentialListDeleter(pathSid); + + public static CredentialListDeleter deleter(final String pathsid) { + return new CredentialListDeleter( + pathsid + ); } - public static CredentialListDeleter deleter( - final String pathAccountSid, - final String pathSid - ) { - return new CredentialListDeleter(pathAccountSid, pathSid); + + public static CredentialListDeleter deleter(final String pathaccountSid, final String pathsid) { + return new CredentialListDeleter( + pathaccountSid, pathsid + ); } - public static CredentialListFetcher fetcher(final String pathSid) { - return new CredentialListFetcher(pathSid); + + public static CredentialListFetcher fetcher(final String pathsid) { + return new CredentialListFetcher( + pathsid + ); } - public static CredentialListFetcher fetcher( - final String pathAccountSid, - final String pathSid - ) { - return new CredentialListFetcher(pathAccountSid, pathSid); + + public static CredentialListFetcher fetcher(final String pathaccountSid, final String pathsid) { + return new CredentialListFetcher( + pathaccountSid, pathsid + ); } + public static CredentialListReader reader() { - return new CredentialListReader(); + return new CredentialListReader( + + ); } - public static CredentialListReader reader(final String pathAccountSid) { - return new CredentialListReader(pathAccountSid); + + public static CredentialListReader reader(final String pathaccountSid) { + return new CredentialListReader( + pathaccountSid + ); } - public static CredentialListUpdater updater( - final String pathSid, - final String friendlyName - ) { - return new CredentialListUpdater(pathSid, friendlyName); + + public static CredentialListUpdater updater(final String pathsid, final String friendlyName) { + return new CredentialListUpdater( + pathsid, friendlyName + ); } - public static CredentialListUpdater updater( - final String pathAccountSid, - final String pathSid, - final String friendlyName - ) { - return new CredentialListUpdater(pathAccountSid, pathSid, friendlyName); + + public static CredentialListUpdater updater(final String pathaccountSid, final String pathsid, final String friendlyName) { + return new CredentialListUpdater( + pathaccountSid, pathsid, friendlyName + ); } + /** * Converts a JSON String into a CredentialList object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return CredentialList object represented by the provided JSON */ - public static CredentialList fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static CredentialList fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, CredentialList.class); @@ -120,14 +131,11 @@ public static CredentialList fromJson( * Converts a JSON InputStream into a CredentialList object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return CredentialList object represented by the provided JSON */ - public static CredentialList fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static CredentialList fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, CredentialList.class); @@ -138,64 +146,55 @@ public static CredentialList fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; + @Getter private final String friendlyName; + @Getter private final String sid; + @Getter private final Map subresourceUris; + @Getter private final String uri; @JsonCreator private CredentialList( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("sid") final String sid, - @JsonProperty("subresource_uris") final Map< - String, - String - > subresourceUris, - @JsonProperty("uri") final String uri + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.RFC2822Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.RFC2822Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("sid") final String sid, + @JsonProperty("subresource_uris") final Map subresourceUris, + @JsonProperty("uri") final String uri ) { this.accountSid = accountSid; - this.dateCreated = DateConverter.rfc2822DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.rfc2822DateTimeFromString(dateUpdated); + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.friendlyName = friendlyName; this.sid = sid; this.subresourceUris = subresourceUris; this.uri = uri; } - public final String getAccountSid() { - return this.accountSid; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final String getSid() { - return this.sid; - } - - public final Map getSubresourceUris() { - return this.subresourceUris; - } - - public final String getUri() { - return this.uri; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -207,28 +206,30 @@ public boolean equals(final Object o) { } CredentialList other = (CredentialList) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(sid, other.sid) && - Objects.equals(subresourceUris, other.subresourceUris) && - Objects.equals(uri, other.uri) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(sid, other.sid) && + Objects.equals(subresourceUris, other.subresourceUris) && + Objects.equals(uri, other.uri) ); } @Override public int hashCode() { return Objects.hash( - accountSid, - dateCreated, - dateUpdated, - friendlyName, - sid, - subresourceUris, - uri + accountSid, + dateCreated, + dateUpdated, + friendlyName, + sid, + subresourceUris, + uri ); } + + } + diff --git a/src/main/java/com/twilio/rest/api/v2010/account/sip/CredentialListCreator.java b/src/main/java/com/twilio/rest/api/v2010/account/sip/CredentialListCreator.java index 90e7fde88b..57af08657a 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/sip/CredentialListCreator.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/sip/CredentialListCreator.java @@ -14,8 +14,11 @@ package com.twilio.rest.api.v2010.account.sip; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,81 +30,66 @@ public class CredentialListCreator extends Creator { + private String pathaccountSid; private String friendlyName; - private String pathAccountSid; public CredentialListCreator(final String friendlyName) { this.friendlyName = friendlyName; } - public CredentialListCreator( - final String pathAccountSid, - final String friendlyName - ) { - this.pathAccountSid = pathAccountSid; + public CredentialListCreator(final String pathaccountSid, final String friendlyName) { + this.pathaccountSid = pathaccountSid; this.friendlyName = friendlyName; } + public CredentialListCreator setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + @Override public CredentialList create(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/SIP/CredentialLists.json"; - - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = - path.replace( - "{" + "FriendlyName" + "}", - this.friendlyName.toString() - ); + + String path = "/2010-04-01/Accounts/{AccountSid}/SIP/CredentialLists.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.API.toString(), - path + HttpMethod.POST, + Domains.API.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "CredentialList creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("CredentialList creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return CredentialList.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return CredentialList.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/sip/CredentialListDeleter.java b/src/main/java/com/twilio/rest/api/v2010/account/sip/CredentialListDeleter.java index 9ceae45522..94c2223ea8 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/sip/CredentialListDeleter.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/sip/CredentialListDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.api.v2010.account.sip; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,59 +26,46 @@ public class CredentialListDeleter extends Deleter { - private String pathSid; - private String pathAccountSid; + private String pathaccountSid; + private String pathsid; - public CredentialListDeleter(final String pathSid) { - this.pathSid = pathSid; + public CredentialListDeleter(final String pathsid) { + this.pathsid = pathsid; } - public CredentialListDeleter( - final String pathAccountSid, - final String pathSid - ) { - this.pathAccountSid = pathAccountSid; - this.pathSid = pathSid; + public CredentialListDeleter(final String pathaccountSid, final String pathsid) { + this.pathaccountSid = pathaccountSid; + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/SIP/CredentialLists/{Sid}.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/2010-04-01/Accounts/{AccountSid}/SIP/CredentialLists/{Sid}.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.API.toString(), - path + HttpMethod.DELETE, + Domains.API.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "CredentialList delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("CredentialList delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/sip/CredentialListFetcher.java b/src/main/java/com/twilio/rest/api/v2010/account/sip/CredentialListFetcher.java index 2e11db57e2..80f9cc7f23 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/sip/CredentialListFetcher.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/sip/CredentialListFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.api.v2010.account.sip; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,66 +26,49 @@ public class CredentialListFetcher extends Fetcher { - private String pathSid; - private String pathAccountSid; + private String pathaccountSid; + private String pathsid; - public CredentialListFetcher(final String pathSid) { - this.pathSid = pathSid; + public CredentialListFetcher(final String pathsid) { + this.pathsid = pathsid; } - public CredentialListFetcher( - final String pathAccountSid, - final String pathSid - ) { - this.pathAccountSid = pathAccountSid; - this.pathSid = pathSid; + public CredentialListFetcher(final String pathaccountSid, final String pathsid) { + this.pathaccountSid = pathaccountSid; + this.pathsid = pathsid; } + @Override public CredentialList fetch(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/SIP/CredentialLists/{Sid}.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/2010-04-01/Accounts/{AccountSid}/SIP/CredentialLists/{Sid}.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.API.toString(), - path + HttpMethod.GET, + Domains.API.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "CredentialList fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("CredentialList fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return CredentialList.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return CredentialList.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/sip/CredentialListReader.java b/src/main/java/com/twilio/rest/api/v2010/account/sip/CredentialListReader.java index 1ef522bcd4..59ef2342bd 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/sip/CredentialListReader.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/sip/CredentialListReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,122 +30,92 @@ public class CredentialListReader extends Reader { - private String pathAccountSid; + private String pathaccountSid; private Long pageSize; - public CredentialListReader() {} + public CredentialListReader() { + } - public CredentialListReader(final String pathAccountSid) { - this.pathAccountSid = pathAccountSid; + public CredentialListReader(final String pathaccountSid) { + this.pathaccountSid = pathaccountSid; } + public CredentialListReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/SIP/CredentialLists.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); + + String path = "/2010-04-01/Accounts/{AccountSid}/SIP/CredentialLists.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.API.toString(), - path + HttpMethod.GET, + Domains.API.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "CredentialList read failed: Unable to connect to server" - ); + throw new ApiConnectionException("CredentialList read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "credential_lists", - response.getContent(), - CredentialList.class, - client.getObjectMapper() - ); + "credential_lists", + response.getContent(), + CredentialList.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.API.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.API.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/sip/CredentialListUpdater.java b/src/main/java/com/twilio/rest/api/v2010/account/sip/CredentialListUpdater.java index cc2df603aa..ea3727a849 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/sip/CredentialListUpdater.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/sip/CredentialListUpdater.java @@ -16,6 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -26,90 +28,70 @@ import com.twilio.rest.Domains; public class CredentialListUpdater extends Updater { - - private String pathSid; + private String pathaccountSid; + private String pathsid; private String friendlyName; - private String pathAccountSid; - public CredentialListUpdater( - final String pathSid, - final String friendlyName - ) { - this.pathSid = pathSid; + public CredentialListUpdater(final String pathsid, final String friendlyName) { + this.pathsid = pathsid; this.friendlyName = friendlyName; } - public CredentialListUpdater( - final String pathAccountSid, - final String pathSid, - final String friendlyName - ) { - this.pathAccountSid = pathAccountSid; - this.pathSid = pathSid; + public CredentialListUpdater(final String pathaccountSid, final String pathsid, final String friendlyName) { + this.pathaccountSid = pathaccountSid; + this.pathsid = pathsid; this.friendlyName = friendlyName; } + public CredentialListUpdater setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + @Override public CredentialList update(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/SIP/CredentialLists/{Sid}.json"; - - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); - path = - path.replace( - "{" + "FriendlyName" + "}", - this.friendlyName.toString() - ); + + String path = "/2010-04-01/Accounts/{AccountSid}/SIP/CredentialLists/{Sid}.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.API.toString(), - path + HttpMethod.POST, + Domains.API.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "CredentialList update failed: Unable to connect to server" - ); + throw new ApiConnectionException("CredentialList update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return CredentialList.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return CredentialList.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/sip/Domain.java b/src/main/java/com/twilio/rest/api/v2010/account/sip/Domain.java index 3b5772e611..ace7824d27 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/sip/Domain.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/sip/Domain.java @@ -18,92 +18,107 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.http.HttpMethod; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Domain extends Resource { - private static final long serialVersionUID = 8213004596487L; public static DomainCreator creator(final String domainName) { - return new DomainCreator(domainName); + return new DomainCreator( + domainName + ); } - public static DomainCreator creator( - final String pathAccountSid, - final String domainName - ) { - return new DomainCreator(pathAccountSid, domainName); + + public static DomainCreator creator(final String pathaccountSid, final String domainName) { + return new DomainCreator( + pathaccountSid, domainName + ); } - public static DomainDeleter deleter(final String pathSid) { - return new DomainDeleter(pathSid); + + public static DomainDeleter deleter(final String pathsid) { + return new DomainDeleter( + pathsid + ); } - public static DomainDeleter deleter( - final String pathAccountSid, - final String pathSid - ) { - return new DomainDeleter(pathAccountSid, pathSid); + + public static DomainDeleter deleter(final String pathaccountSid, final String pathsid) { + return new DomainDeleter( + pathaccountSid, pathsid + ); } - public static DomainFetcher fetcher(final String pathSid) { - return new DomainFetcher(pathSid); + + public static DomainFetcher fetcher(final String pathsid) { + return new DomainFetcher( + pathsid + ); } - public static DomainFetcher fetcher( - final String pathAccountSid, - final String pathSid - ) { - return new DomainFetcher(pathAccountSid, pathSid); + + public static DomainFetcher fetcher(final String pathaccountSid, final String pathsid) { + return new DomainFetcher( + pathaccountSid, pathsid + ); } + public static DomainReader reader() { - return new DomainReader(); + return new DomainReader( + + ); } - public static DomainReader reader(final String pathAccountSid) { - return new DomainReader(pathAccountSid); + + public static DomainReader reader(final String pathaccountSid) { + return new DomainReader( + pathaccountSid + ); } - public static DomainUpdater updater(final String pathSid) { - return new DomainUpdater(pathSid); + + public static DomainUpdater updater(final String pathsid) { + return new DomainUpdater( + pathsid + ); } - public static DomainUpdater updater( - final String pathAccountSid, - final String pathSid - ) { - return new DomainUpdater(pathAccountSid, pathSid); + + public static DomainUpdater updater(final String pathaccountSid, final String pathsid) { + return new DomainUpdater( + pathaccountSid, pathsid + ); } + /** * Converts a JSON String into a Domain object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Domain object represented by the provided JSON */ - public static Domain fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Domain fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Domain.class); @@ -118,14 +133,11 @@ public static Domain fromJson( * Converts a JSON InputStream into a Domain object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Domain object represented by the provided JSON */ - public static Domain fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Domain fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Domain.class); @@ -136,71 +148,102 @@ public static Domain fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; + @Getter private final String apiVersion; + @Getter private final String authType; + @Getter + private final String byocTrunkSid; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; + @Getter private final String domainName; + @Getter + private final String emergencyCallerSid; + @Getter + private final Boolean emergencyCallingEnabled; + @Getter private final String friendlyName; + @Getter + private final Boolean secure; + @Getter private final String sid; + @Getter + private final Boolean sipRegistration; + @Getter + private final Map subresourceUris; + @Getter private final String uri; + @Getter private final HttpMethod voiceFallbackMethod; + @Getter private final URI voiceFallbackUrl; + @Getter private final HttpMethod voiceMethod; + @Getter private final HttpMethod voiceStatusCallbackMethod; + @Getter private final URI voiceStatusCallbackUrl; + @Getter private final URI voiceUrl; - private final Map subresourceUris; - private final Boolean sipRegistration; - private final Boolean emergencyCallingEnabled; - private final Boolean secure; - private final String byocTrunkSid; - private final String emergencyCallerSid; @JsonCreator private Domain( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("api_version") final String apiVersion, - @JsonProperty("auth_type") final String authType, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("domain_name") final String domainName, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("sid") final String sid, - @JsonProperty("uri") final String uri, - @JsonProperty( - "voice_fallback_method" - ) final HttpMethod voiceFallbackMethod, - @JsonProperty("voice_fallback_url") final URI voiceFallbackUrl, - @JsonProperty("voice_method") final HttpMethod voiceMethod, - @JsonProperty( - "voice_status_callback_method" - ) final HttpMethod voiceStatusCallbackMethod, - @JsonProperty( - "voice_status_callback_url" - ) final URI voiceStatusCallbackUrl, - @JsonProperty("voice_url") final URI voiceUrl, - @JsonProperty("subresource_uris") final Map< - String, - String - > subresourceUris, - @JsonProperty("sip_registration") final Boolean sipRegistration, - @JsonProperty( - "emergency_calling_enabled" - ) final Boolean emergencyCallingEnabled, - @JsonProperty("secure") final Boolean secure, - @JsonProperty("byoc_trunk_sid") final String byocTrunkSid, - @JsonProperty("emergency_caller_sid") final String emergencyCallerSid + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("api_version") final String apiVersion, + @JsonProperty("auth_type") final String authType, + @JsonProperty("byoc_trunk_sid") final String byocTrunkSid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.RFC2822Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.RFC2822Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("domain_name") final String domainName, + @JsonProperty("emergency_caller_sid") final String emergencyCallerSid, + @JsonProperty("emergency_calling_enabled") final Boolean emergencyCallingEnabled, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("secure") final Boolean secure, + @JsonProperty("sid") final String sid, + @JsonProperty("sip_registration") final Boolean sipRegistration, + @JsonProperty("subresource_uris") final Map subresourceUris, + @JsonProperty("uri") final String uri, + @JsonProperty("voice_fallback_method") final HttpMethod voiceFallbackMethod, + @JsonProperty("voice_fallback_url") final URI voiceFallbackUrl, + @JsonProperty("voice_method") final HttpMethod voiceMethod, + @JsonProperty("voice_status_callback_method") final HttpMethod voiceStatusCallbackMethod, + @JsonProperty("voice_status_callback_url") final URI voiceStatusCallbackUrl, + @JsonProperty("voice_url") final URI voiceUrl ) { this.accountSid = accountSid; this.apiVersion = apiVersion; this.authType = authType; - this.dateCreated = DateConverter.rfc2822DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.rfc2822DateTimeFromString(dateUpdated); + this.byocTrunkSid = byocTrunkSid; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.domainName = domainName; + this.emergencyCallerSid = emergencyCallerSid; + this.emergencyCallingEnabled = emergencyCallingEnabled; this.friendlyName = friendlyName; + this.secure = secure; this.sid = sid; + this.sipRegistration = sipRegistration; + this.subresourceUris = subresourceUris; this.uri = uri; this.voiceFallbackMethod = voiceFallbackMethod; this.voiceFallbackUrl = voiceFallbackUrl; @@ -208,96 +251,6 @@ private Domain( this.voiceStatusCallbackMethod = voiceStatusCallbackMethod; this.voiceStatusCallbackUrl = voiceStatusCallbackUrl; this.voiceUrl = voiceUrl; - this.subresourceUris = subresourceUris; - this.sipRegistration = sipRegistration; - this.emergencyCallingEnabled = emergencyCallingEnabled; - this.secure = secure; - this.byocTrunkSid = byocTrunkSid; - this.emergencyCallerSid = emergencyCallerSid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getApiVersion() { - return this.apiVersion; - } - - public final String getAuthType() { - return this.authType; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final String getDomainName() { - return this.domainName; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final String getSid() { - return this.sid; - } - - public final String getUri() { - return this.uri; - } - - public final HttpMethod getVoiceFallbackMethod() { - return this.voiceFallbackMethod; - } - - public final URI getVoiceFallbackUrl() { - return this.voiceFallbackUrl; - } - - public final HttpMethod getVoiceMethod() { - return this.voiceMethod; - } - - public final HttpMethod getVoiceStatusCallbackMethod() { - return this.voiceStatusCallbackMethod; - } - - public final URI getVoiceStatusCallbackUrl() { - return this.voiceStatusCallbackUrl; - } - - public final URI getVoiceUrl() { - return this.voiceUrl; - } - - public final Map getSubresourceUris() { - return this.subresourceUris; - } - - public final Boolean getSipRegistration() { - return this.sipRegistration; - } - - public final Boolean getEmergencyCallingEnabled() { - return this.emergencyCallingEnabled; - } - - public final Boolean getSecure() { - return this.secure; - } - - public final String getByocTrunkSid() { - return this.byocTrunkSid; - } - - public final String getEmergencyCallerSid() { - return this.emergencyCallerSid; } @Override @@ -311,65 +264,58 @@ public boolean equals(final Object o) { } Domain other = (Domain) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(apiVersion, other.apiVersion) && - Objects.equals(authType, other.authType) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(domainName, other.domainName) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(sid, other.sid) && - Objects.equals(uri, other.uri) && - Objects.equals(voiceFallbackMethod, other.voiceFallbackMethod) && - Objects.equals(voiceFallbackUrl, other.voiceFallbackUrl) && - Objects.equals(voiceMethod, other.voiceMethod) && - Objects.equals( - voiceStatusCallbackMethod, - other.voiceStatusCallbackMethod - ) && - Objects.equals( - voiceStatusCallbackUrl, - other.voiceStatusCallbackUrl - ) && - Objects.equals(voiceUrl, other.voiceUrl) && - Objects.equals(subresourceUris, other.subresourceUris) && - Objects.equals(sipRegistration, other.sipRegistration) && - Objects.equals( - emergencyCallingEnabled, - other.emergencyCallingEnabled - ) && - Objects.equals(secure, other.secure) && - Objects.equals(byocTrunkSid, other.byocTrunkSid) && - Objects.equals(emergencyCallerSid, other.emergencyCallerSid) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(apiVersion, other.apiVersion) && + Objects.equals(authType, other.authType) && + Objects.equals(byocTrunkSid, other.byocTrunkSid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(domainName, other.domainName) && + Objects.equals(emergencyCallerSid, other.emergencyCallerSid) && + Objects.equals(emergencyCallingEnabled, other.emergencyCallingEnabled) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(secure, other.secure) && + Objects.equals(sid, other.sid) && + Objects.equals(sipRegistration, other.sipRegistration) && + Objects.equals(subresourceUris, other.subresourceUris) && + Objects.equals(uri, other.uri) && + Objects.equals(voiceFallbackMethod, other.voiceFallbackMethod) && + Objects.equals(voiceFallbackUrl, other.voiceFallbackUrl) && + Objects.equals(voiceMethod, other.voiceMethod) && + Objects.equals(voiceStatusCallbackMethod, other.voiceStatusCallbackMethod) && + Objects.equals(voiceStatusCallbackUrl, other.voiceStatusCallbackUrl) && + Objects.equals(voiceUrl, other.voiceUrl) ); } @Override public int hashCode() { return Objects.hash( - accountSid, - apiVersion, - authType, - dateCreated, - dateUpdated, - domainName, - friendlyName, - sid, - uri, - voiceFallbackMethod, - voiceFallbackUrl, - voiceMethod, - voiceStatusCallbackMethod, - voiceStatusCallbackUrl, - voiceUrl, - subresourceUris, - sipRegistration, - emergencyCallingEnabled, - secure, - byocTrunkSid, - emergencyCallerSid + accountSid, + apiVersion, + authType, + byocTrunkSid, + dateCreated, + dateUpdated, + domainName, + emergencyCallerSid, + emergencyCallingEnabled, + friendlyName, + secure, + sid, + sipRegistration, + subresourceUris, + uri, + voiceFallbackMethod, + voiceFallbackUrl, + voiceMethod, + voiceStatusCallbackMethod, + voiceStatusCallbackUrl, + voiceUrl ); } + + } + diff --git a/src/main/java/com/twilio/rest/api/v2010/account/sip/DomainCreator.java b/src/main/java/com/twilio/rest/api/v2010/account/sip/DomainCreator.java index 009b4d4b48..911aec0ec5 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/sip/DomainCreator.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/sip/DomainCreator.java @@ -14,9 +14,11 @@ package com.twilio.rest.api.v2010.account.sip; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; -import com.twilio.converter.Promoter; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,13 +27,13 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -import java.net.URI; + import java.net.URI; public class DomainCreator extends Creator { + private String pathaccountSid; private String domainName; - private String pathAccountSid; private String friendlyName; private URI voiceUrl; private HttpMethod voiceMethod; @@ -49,140 +51,118 @@ public DomainCreator(final String domainName) { this.domainName = domainName; } - public DomainCreator(final String pathAccountSid, final String domainName) { - this.pathAccountSid = pathAccountSid; + public DomainCreator(final String pathaccountSid, final String domainName) { + this.pathaccountSid = pathaccountSid; this.domainName = domainName; } + public DomainCreator setDomainName(final String domainName) { this.domainName = domainName; return this; } + public DomainCreator setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + public DomainCreator setVoiceUrl(final URI voiceUrl) { this.voiceUrl = voiceUrl; return this; } - public DomainCreator setVoiceUrl(final String voiceUrl) { - return setVoiceUrl(Promoter.uriFromString(voiceUrl)); - } public DomainCreator setVoiceMethod(final HttpMethod voiceMethod) { this.voiceMethod = voiceMethod; return this; } + public DomainCreator setVoiceFallbackUrl(final URI voiceFallbackUrl) { this.voiceFallbackUrl = voiceFallbackUrl; return this; } - public DomainCreator setVoiceFallbackUrl(final String voiceFallbackUrl) { - return setVoiceFallbackUrl(Promoter.uriFromString(voiceFallbackUrl)); - } - public DomainCreator setVoiceFallbackMethod( - final HttpMethod voiceFallbackMethod - ) { + public DomainCreator setVoiceFallbackMethod(final HttpMethod voiceFallbackMethod) { this.voiceFallbackMethod = voiceFallbackMethod; return this; } - public DomainCreator setVoiceStatusCallbackUrl( - final URI voiceStatusCallbackUrl - ) { + + public DomainCreator setVoiceStatusCallbackUrl(final URI voiceStatusCallbackUrl) { this.voiceStatusCallbackUrl = voiceStatusCallbackUrl; return this; } - public DomainCreator setVoiceStatusCallbackUrl( - final String voiceStatusCallbackUrl - ) { - return setVoiceStatusCallbackUrl( - Promoter.uriFromString(voiceStatusCallbackUrl) - ); - } - public DomainCreator setVoiceStatusCallbackMethod( - final HttpMethod voiceStatusCallbackMethod - ) { + public DomainCreator setVoiceStatusCallbackMethod(final HttpMethod voiceStatusCallbackMethod) { this.voiceStatusCallbackMethod = voiceStatusCallbackMethod; return this; } + public DomainCreator setSipRegistration(final Boolean sipRegistration) { this.sipRegistration = sipRegistration; return this; } - public DomainCreator setEmergencyCallingEnabled( - final Boolean emergencyCallingEnabled - ) { + + public DomainCreator setEmergencyCallingEnabled(final Boolean emergencyCallingEnabled) { this.emergencyCallingEnabled = emergencyCallingEnabled; return this; } + public DomainCreator setSecure(final Boolean secure) { this.secure = secure; return this; } + public DomainCreator setByocTrunkSid(final String byocTrunkSid) { this.byocTrunkSid = byocTrunkSid; return this; } - public DomainCreator setEmergencyCallerSid( - final String emergencyCallerSid - ) { + + public DomainCreator setEmergencyCallerSid(final String emergencyCallerSid) { this.emergencyCallerSid = emergencyCallerSid; return this; } + @Override public Domain create(final TwilioRestClient client) { + String path = "/2010-04-01/Accounts/{AccountSid}/SIP/Domains.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = - path.replace("{" + "DomainName" + "}", this.domainName.toString()); + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.API.toString(), - path + HttpMethod.POST, + Domains.API.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Domain creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("Domain creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -191,59 +171,71 @@ public Domain create(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (domainName != null) { - request.addPostParam("DomainName", domainName); + Serializer.toString(request, "DomainName", domainName, ParameterType.URLENCODED); } + + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + if (voiceUrl != null) { - request.addPostParam("VoiceUrl", voiceUrl.toString()); + Serializer.toString(request, "VoiceUrl", voiceUrl, ParameterType.URLENCODED); } + + if (voiceMethod != null) { - request.addPostParam("VoiceMethod", voiceMethod.toString()); + Serializer.toString(request, "VoiceMethod", voiceMethod, ParameterType.URLENCODED); } + + if (voiceFallbackUrl != null) { - request.addPostParam( - "VoiceFallbackUrl", - voiceFallbackUrl.toString() - ); + Serializer.toString(request, "VoiceFallbackUrl", voiceFallbackUrl, ParameterType.URLENCODED); } + + if (voiceFallbackMethod != null) { - request.addPostParam( - "VoiceFallbackMethod", - voiceFallbackMethod.toString() - ); + Serializer.toString(request, "VoiceFallbackMethod", voiceFallbackMethod, ParameterType.URLENCODED); } + + if (voiceStatusCallbackUrl != null) { - request.addPostParam( - "VoiceStatusCallbackUrl", - voiceStatusCallbackUrl.toString() - ); + Serializer.toString(request, "VoiceStatusCallbackUrl", voiceStatusCallbackUrl, ParameterType.URLENCODED); } + + if (voiceStatusCallbackMethod != null) { - request.addPostParam( - "VoiceStatusCallbackMethod", - voiceStatusCallbackMethod.toString() - ); + Serializer.toString(request, "VoiceStatusCallbackMethod", voiceStatusCallbackMethod, ParameterType.URLENCODED); } + + if (sipRegistration != null) { - request.addPostParam("SipRegistration", sipRegistration.toString()); + Serializer.toString(request, "SipRegistration", sipRegistration, ParameterType.URLENCODED); } + + if (emergencyCallingEnabled != null) { - request.addPostParam( - "EmergencyCallingEnabled", - emergencyCallingEnabled.toString() - ); + Serializer.toString(request, "EmergencyCallingEnabled", emergencyCallingEnabled, ParameterType.URLENCODED); } + + if (secure != null) { - request.addPostParam("Secure", secure.toString()); + Serializer.toString(request, "Secure", secure, ParameterType.URLENCODED); } + + if (byocTrunkSid != null) { - request.addPostParam("ByocTrunkSid", byocTrunkSid); + Serializer.toString(request, "ByocTrunkSid", byocTrunkSid, ParameterType.URLENCODED); } + + if (emergencyCallerSid != null) { - request.addPostParam("EmergencyCallerSid", emergencyCallerSid); + Serializer.toString(request, "EmergencyCallerSid", emergencyCallerSid, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/sip/DomainDeleter.java b/src/main/java/com/twilio/rest/api/v2010/account/sip/DomainDeleter.java index 2e1f632240..adad02bafa 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/sip/DomainDeleter.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/sip/DomainDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.api.v2010.account.sip; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,56 +26,46 @@ public class DomainDeleter extends Deleter { - private String pathSid; - private String pathAccountSid; + private String pathaccountSid; + private String pathsid; - public DomainDeleter(final String pathSid) { - this.pathSid = pathSid; + public DomainDeleter(final String pathsid) { + this.pathsid = pathsid; } - public DomainDeleter(final String pathAccountSid, final String pathSid) { - this.pathAccountSid = pathAccountSid; - this.pathSid = pathSid; + public DomainDeleter(final String pathaccountSid, final String pathsid) { + this.pathaccountSid = pathaccountSid; + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/SIP/Domains/{Sid}.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/2010-04-01/Accounts/{AccountSid}/SIP/Domains/{Sid}.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.API.toString(), - path + HttpMethod.DELETE, + Domains.API.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Domain delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("Domain delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/sip/DomainFetcher.java b/src/main/java/com/twilio/rest/api/v2010/account/sip/DomainFetcher.java index bc903ed02d..2353177b84 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/sip/DomainFetcher.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/sip/DomainFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.api.v2010.account.sip; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,60 +26,49 @@ public class DomainFetcher extends Fetcher { - private String pathSid; - private String pathAccountSid; + private String pathaccountSid; + private String pathsid; - public DomainFetcher(final String pathSid) { - this.pathSid = pathSid; + public DomainFetcher(final String pathsid) { + this.pathsid = pathsid; } - public DomainFetcher(final String pathAccountSid, final String pathSid) { - this.pathAccountSid = pathAccountSid; - this.pathSid = pathSid; + public DomainFetcher(final String pathaccountSid, final String pathsid) { + this.pathaccountSid = pathaccountSid; + this.pathsid = pathsid; } + @Override public Domain fetch(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/SIP/Domains/{Sid}.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/2010-04-01/Accounts/{AccountSid}/SIP/Domains/{Sid}.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.API.toString(), - path + HttpMethod.GET, + Domains.API.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Domain fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Domain fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Domain.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/sip/DomainReader.java b/src/main/java/com/twilio/rest/api/v2010/account/sip/DomainReader.java index 4ebda33797..95648f352d 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/sip/DomainReader.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/sip/DomainReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,121 +30,92 @@ public class DomainReader extends Reader { - private String pathAccountSid; + private String pathaccountSid; private Long pageSize; - public DomainReader() {} + public DomainReader() { + } - public DomainReader(final String pathAccountSid) { - this.pathAccountSid = pathAccountSid; + public DomainReader(final String pathaccountSid) { + this.pathaccountSid = pathaccountSid; } + public DomainReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/2010-04-01/Accounts/{AccountSid}/SIP/Domains.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.API.toString(), - path + HttpMethod.GET, + Domains.API.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Domain read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Domain read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "domains", - response.getContent(), - Domain.class, - client.getObjectMapper() - ); + "domains", + response.getContent(), + Domain.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.API.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.API.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/sip/DomainUpdater.java b/src/main/java/com/twilio/rest/api/v2010/account/sip/DomainUpdater.java index 709c43d45f..873b32af53 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/sip/DomainUpdater.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/sip/DomainUpdater.java @@ -16,7 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; -import com.twilio.converter.Promoter; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,12 +26,12 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.net.URI; public class DomainUpdater extends Updater { - - private String pathSid; - private String pathAccountSid; + private String pathaccountSid; + private String pathsid; private String friendlyName; private HttpMethod voiceFallbackMethod; private URI voiceFallbackUrl; @@ -45,144 +46,123 @@ public class DomainUpdater extends Updater { private String byocTrunkSid; private String emergencyCallerSid; - public DomainUpdater(final String pathSid) { - this.pathSid = pathSid; + public DomainUpdater(final String pathsid) { + this.pathsid = pathsid; } - public DomainUpdater(final String pathAccountSid, final String pathSid) { - this.pathAccountSid = pathAccountSid; - this.pathSid = pathSid; + public DomainUpdater(final String pathaccountSid, final String pathsid) { + this.pathaccountSid = pathaccountSid; + this.pathsid = pathsid; } + public DomainUpdater setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } - public DomainUpdater setVoiceFallbackMethod( - final HttpMethod voiceFallbackMethod - ) { + + public DomainUpdater setVoiceFallbackMethod(final HttpMethod voiceFallbackMethod) { this.voiceFallbackMethod = voiceFallbackMethod; return this; } + public DomainUpdater setVoiceFallbackUrl(final URI voiceFallbackUrl) { this.voiceFallbackUrl = voiceFallbackUrl; return this; } - public DomainUpdater setVoiceFallbackUrl(final String voiceFallbackUrl) { - return setVoiceFallbackUrl(Promoter.uriFromString(voiceFallbackUrl)); - } public DomainUpdater setVoiceMethod(final HttpMethod voiceMethod) { this.voiceMethod = voiceMethod; return this; } - public DomainUpdater setVoiceStatusCallbackMethod( - final HttpMethod voiceStatusCallbackMethod - ) { + + public DomainUpdater setVoiceStatusCallbackMethod(final HttpMethod voiceStatusCallbackMethod) { this.voiceStatusCallbackMethod = voiceStatusCallbackMethod; return this; } - public DomainUpdater setVoiceStatusCallbackUrl( - final URI voiceStatusCallbackUrl - ) { + + public DomainUpdater setVoiceStatusCallbackUrl(final URI voiceStatusCallbackUrl) { this.voiceStatusCallbackUrl = voiceStatusCallbackUrl; return this; } - public DomainUpdater setVoiceStatusCallbackUrl( - final String voiceStatusCallbackUrl - ) { - return setVoiceStatusCallbackUrl( - Promoter.uriFromString(voiceStatusCallbackUrl) - ); - } public DomainUpdater setVoiceUrl(final URI voiceUrl) { this.voiceUrl = voiceUrl; return this; } - public DomainUpdater setVoiceUrl(final String voiceUrl) { - return setVoiceUrl(Promoter.uriFromString(voiceUrl)); - } public DomainUpdater setSipRegistration(final Boolean sipRegistration) { this.sipRegistration = sipRegistration; return this; } + public DomainUpdater setDomainName(final String domainName) { this.domainName = domainName; return this; } - public DomainUpdater setEmergencyCallingEnabled( - final Boolean emergencyCallingEnabled - ) { + + public DomainUpdater setEmergencyCallingEnabled(final Boolean emergencyCallingEnabled) { this.emergencyCallingEnabled = emergencyCallingEnabled; return this; } + public DomainUpdater setSecure(final Boolean secure) { this.secure = secure; return this; } + public DomainUpdater setByocTrunkSid(final String byocTrunkSid) { this.byocTrunkSid = byocTrunkSid; return this; } - public DomainUpdater setEmergencyCallerSid( - final String emergencyCallerSid - ) { + + public DomainUpdater setEmergencyCallerSid(final String emergencyCallerSid) { this.emergencyCallerSid = emergencyCallerSid; return this; } + @Override public Domain update(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/SIP/Domains/{Sid}.json"; - - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + + String path = "/2010-04-01/Accounts/{AccountSid}/SIP/Domains/{Sid}.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.API.toString(), - path + HttpMethod.POST, + Domains.API.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Domain update failed: Unable to connect to server" - ); + throw new ApiConnectionException("Domain update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -191,59 +171,71 @@ public Domain update(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + if (voiceFallbackMethod != null) { - request.addPostParam( - "VoiceFallbackMethod", - voiceFallbackMethod.toString() - ); + Serializer.toString(request, "VoiceFallbackMethod", voiceFallbackMethod, ParameterType.URLENCODED); } + + if (voiceFallbackUrl != null) { - request.addPostParam( - "VoiceFallbackUrl", - voiceFallbackUrl.toString() - ); + Serializer.toString(request, "VoiceFallbackUrl", voiceFallbackUrl, ParameterType.URLENCODED); } + + if (voiceMethod != null) { - request.addPostParam("VoiceMethod", voiceMethod.toString()); + Serializer.toString(request, "VoiceMethod", voiceMethod, ParameterType.URLENCODED); } + + if (voiceStatusCallbackMethod != null) { - request.addPostParam( - "VoiceStatusCallbackMethod", - voiceStatusCallbackMethod.toString() - ); + Serializer.toString(request, "VoiceStatusCallbackMethod", voiceStatusCallbackMethod, ParameterType.URLENCODED); } + + if (voiceStatusCallbackUrl != null) { - request.addPostParam( - "VoiceStatusCallbackUrl", - voiceStatusCallbackUrl.toString() - ); + Serializer.toString(request, "VoiceStatusCallbackUrl", voiceStatusCallbackUrl, ParameterType.URLENCODED); } + + if (voiceUrl != null) { - request.addPostParam("VoiceUrl", voiceUrl.toString()); + Serializer.toString(request, "VoiceUrl", voiceUrl, ParameterType.URLENCODED); } + + if (sipRegistration != null) { - request.addPostParam("SipRegistration", sipRegistration.toString()); + Serializer.toString(request, "SipRegistration", sipRegistration, ParameterType.URLENCODED); } + + if (domainName != null) { - request.addPostParam("DomainName", domainName); + Serializer.toString(request, "DomainName", domainName, ParameterType.URLENCODED); } + + if (emergencyCallingEnabled != null) { - request.addPostParam( - "EmergencyCallingEnabled", - emergencyCallingEnabled.toString() - ); + Serializer.toString(request, "EmergencyCallingEnabled", emergencyCallingEnabled, ParameterType.URLENCODED); } + + if (secure != null) { - request.addPostParam("Secure", secure.toString()); + Serializer.toString(request, "Secure", secure, ParameterType.URLENCODED); } + + if (byocTrunkSid != null) { - request.addPostParam("ByocTrunkSid", byocTrunkSid); + Serializer.toString(request, "ByocTrunkSid", byocTrunkSid, ParameterType.URLENCODED); } + + if (emergencyCallerSid != null) { - request.addPostParam("EmergencyCallerSid", emergencyCallerSid); + Serializer.toString(request, "EmergencyCallerSid", emergencyCallerSid, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/sip/IpAccessControlList.java b/src/main/java/com/twilio/rest/api/v2010/account/sip/IpAccessControlList.java index eb5a974952..256179cb4f 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/sip/IpAccessControlList.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/sip/IpAccessControlList.java @@ -18,102 +18,105 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.time.ZonedDateTime; import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class IpAccessControlList extends Resource { - private static final long serialVersionUID = 178395545365846L; - public static IpAccessControlListCreator creator( - final String friendlyName - ) { - return new IpAccessControlListCreator(friendlyName); + public static IpAccessControlListCreator creator(final String friendlyName) { + return new IpAccessControlListCreator( + friendlyName + ); } - public static IpAccessControlListCreator creator( - final String pathAccountSid, - final String friendlyName - ) { - return new IpAccessControlListCreator(pathAccountSid, friendlyName); + + public static IpAccessControlListCreator creator(final String pathaccountSid, final String friendlyName) { + return new IpAccessControlListCreator( + pathaccountSid, friendlyName + ); } - public static IpAccessControlListDeleter deleter(final String pathSid) { - return new IpAccessControlListDeleter(pathSid); + + public static IpAccessControlListDeleter deleter(final String pathsid) { + return new IpAccessControlListDeleter( + pathsid + ); } - public static IpAccessControlListDeleter deleter( - final String pathAccountSid, - final String pathSid - ) { - return new IpAccessControlListDeleter(pathAccountSid, pathSid); + + public static IpAccessControlListDeleter deleter(final String pathaccountSid, final String pathsid) { + return new IpAccessControlListDeleter( + pathaccountSid, pathsid + ); } - public static IpAccessControlListFetcher fetcher(final String pathSid) { - return new IpAccessControlListFetcher(pathSid); + + public static IpAccessControlListFetcher fetcher(final String pathsid) { + return new IpAccessControlListFetcher( + pathsid + ); } - public static IpAccessControlListFetcher fetcher( - final String pathAccountSid, - final String pathSid - ) { - return new IpAccessControlListFetcher(pathAccountSid, pathSid); + + public static IpAccessControlListFetcher fetcher(final String pathaccountSid, final String pathsid) { + return new IpAccessControlListFetcher( + pathaccountSid, pathsid + ); } + public static IpAccessControlListReader reader() { - return new IpAccessControlListReader(); + return new IpAccessControlListReader( + + ); } - public static IpAccessControlListReader reader( - final String pathAccountSid - ) { - return new IpAccessControlListReader(pathAccountSid); + + public static IpAccessControlListReader reader(final String pathaccountSid) { + return new IpAccessControlListReader( + pathaccountSid + ); } - public static IpAccessControlListUpdater updater( - final String pathSid, - final String friendlyName - ) { - return new IpAccessControlListUpdater(pathSid, friendlyName); + + public static IpAccessControlListUpdater updater(final String pathsid, final String friendlyName) { + return new IpAccessControlListUpdater( + pathsid, friendlyName + ); } - public static IpAccessControlListUpdater updater( - final String pathAccountSid, - final String pathSid, - final String friendlyName - ) { + + public static IpAccessControlListUpdater updater(final String pathaccountSid, final String pathsid, final String friendlyName) { return new IpAccessControlListUpdater( - pathAccountSid, - pathSid, - friendlyName + pathaccountSid, pathsid, friendlyName ); } + /** * Converts a JSON String into a IpAccessControlList object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return IpAccessControlList object represented by the provided JSON */ - public static IpAccessControlList fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static IpAccessControlList fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, IpAccessControlList.class); @@ -128,14 +131,11 @@ public static IpAccessControlList fromJson( * Converts a JSON InputStream into a IpAccessControlList object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return IpAccessControlList object represented by the provided JSON */ - public static IpAccessControlList fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static IpAccessControlList fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, IpAccessControlList.class); @@ -146,64 +146,55 @@ public static IpAccessControlList fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String friendlyName; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; + @Getter + private final String friendlyName; + @Getter + private final String sid; + @Getter private final Map subresourceUris; + @Getter private final String uri; @JsonCreator private IpAccessControlList( - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("subresource_uris") final Map< - String, - String - > subresourceUris, - @JsonProperty("uri") final String uri + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.RFC2822Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.RFC2822Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("sid") final String sid, + @JsonProperty("subresource_uris") final Map subresourceUris, + @JsonProperty("uri") final String uri ) { - this.sid = sid; this.accountSid = accountSid; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.friendlyName = friendlyName; - this.dateCreated = DateConverter.rfc2822DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.rfc2822DateTimeFromString(dateUpdated); + this.sid = sid; this.subresourceUris = subresourceUris; this.uri = uri; } - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final Map getSubresourceUris() { - return this.subresourceUris; - } - - public final String getUri() { - return this.uri; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -215,28 +206,30 @@ public boolean equals(final Object o) { } IpAccessControlList other = (IpAccessControlList) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(subresourceUris, other.subresourceUris) && - Objects.equals(uri, other.uri) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(sid, other.sid) && + Objects.equals(subresourceUris, other.subresourceUris) && + Objects.equals(uri, other.uri) ); } @Override public int hashCode() { return Objects.hash( - sid, - accountSid, - friendlyName, - dateCreated, - dateUpdated, - subresourceUris, - uri + accountSid, + dateCreated, + dateUpdated, + friendlyName, + sid, + subresourceUris, + uri ); } + + } + diff --git a/src/main/java/com/twilio/rest/api/v2010/account/sip/IpAccessControlListCreator.java b/src/main/java/com/twilio/rest/api/v2010/account/sip/IpAccessControlListCreator.java index 3116a6030d..48027f248f 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/sip/IpAccessControlListCreator.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/sip/IpAccessControlListCreator.java @@ -14,8 +14,11 @@ package com.twilio.rest.api.v2010.account.sip; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,83 +30,66 @@ public class IpAccessControlListCreator extends Creator { + private String pathaccountSid; private String friendlyName; - private String pathAccountSid; public IpAccessControlListCreator(final String friendlyName) { this.friendlyName = friendlyName; } - public IpAccessControlListCreator( - final String pathAccountSid, - final String friendlyName - ) { - this.pathAccountSid = pathAccountSid; + public IpAccessControlListCreator(final String pathaccountSid, final String friendlyName) { + this.pathaccountSid = pathaccountSid; this.friendlyName = friendlyName; } - public IpAccessControlListCreator setFriendlyName( - final String friendlyName - ) { + + public IpAccessControlListCreator setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + @Override public IpAccessControlList create(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/SIP/IpAccessControlLists.json"; - - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = - path.replace( - "{" + "FriendlyName" + "}", - this.friendlyName.toString() - ); + + String path = "/2010-04-01/Accounts/{AccountSid}/SIP/IpAccessControlLists.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.API.toString(), - path + HttpMethod.POST, + Domains.API.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "IpAccessControlList creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("IpAccessControlList creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return IpAccessControlList.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return IpAccessControlList.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/sip/IpAccessControlListDeleter.java b/src/main/java/com/twilio/rest/api/v2010/account/sip/IpAccessControlListDeleter.java index bb16514d25..ac74c02606 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/sip/IpAccessControlListDeleter.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/sip/IpAccessControlListDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.api.v2010.account.sip; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,59 +26,46 @@ public class IpAccessControlListDeleter extends Deleter { - private String pathSid; - private String pathAccountSid; + private String pathaccountSid; + private String pathsid; - public IpAccessControlListDeleter(final String pathSid) { - this.pathSid = pathSid; + public IpAccessControlListDeleter(final String pathsid) { + this.pathsid = pathsid; } - public IpAccessControlListDeleter( - final String pathAccountSid, - final String pathSid - ) { - this.pathAccountSid = pathAccountSid; - this.pathSid = pathSid; + public IpAccessControlListDeleter(final String pathaccountSid, final String pathsid) { + this.pathaccountSid = pathaccountSid; + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/SIP/IpAccessControlLists/{Sid}.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/2010-04-01/Accounts/{AccountSid}/SIP/IpAccessControlLists/{Sid}.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.API.toString(), - path + HttpMethod.DELETE, + Domains.API.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "IpAccessControlList delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("IpAccessControlList delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/sip/IpAccessControlListFetcher.java b/src/main/java/com/twilio/rest/api/v2010/account/sip/IpAccessControlListFetcher.java index 8a6440133a..87ef9b2e43 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/sip/IpAccessControlListFetcher.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/sip/IpAccessControlListFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.api.v2010.account.sip; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,66 +26,49 @@ public class IpAccessControlListFetcher extends Fetcher { - private String pathSid; - private String pathAccountSid; + private String pathaccountSid; + private String pathsid; - public IpAccessControlListFetcher(final String pathSid) { - this.pathSid = pathSid; + public IpAccessControlListFetcher(final String pathsid) { + this.pathsid = pathsid; } - public IpAccessControlListFetcher( - final String pathAccountSid, - final String pathSid - ) { - this.pathAccountSid = pathAccountSid; - this.pathSid = pathSid; + public IpAccessControlListFetcher(final String pathaccountSid, final String pathsid) { + this.pathaccountSid = pathaccountSid; + this.pathsid = pathsid; } + @Override public IpAccessControlList fetch(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/SIP/IpAccessControlLists/{Sid}.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/2010-04-01/Accounts/{AccountSid}/SIP/IpAccessControlLists/{Sid}.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.API.toString(), - path + HttpMethod.GET, + Domains.API.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "IpAccessControlList fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("IpAccessControlList fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return IpAccessControlList.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return IpAccessControlList.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/sip/IpAccessControlListReader.java b/src/main/java/com/twilio/rest/api/v2010/account/sip/IpAccessControlListReader.java index b5d59a4b82..c2bea1ce68 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/sip/IpAccessControlListReader.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/sip/IpAccessControlListReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,124 +30,92 @@ public class IpAccessControlListReader extends Reader { - private String pathAccountSid; + private String pathaccountSid; private Long pageSize; - public IpAccessControlListReader() {} + public IpAccessControlListReader() { + } - public IpAccessControlListReader(final String pathAccountSid) { - this.pathAccountSid = pathAccountSid; + public IpAccessControlListReader(final String pathaccountSid) { + this.pathaccountSid = pathaccountSid; } + public IpAccessControlListReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override - public ResourceSet read( - final TwilioRestClient client - ) { + public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/SIP/IpAccessControlLists.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); + + String path = "/2010-04-01/Accounts/{AccountSid}/SIP/IpAccessControlLists.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.API.toString(), - path + HttpMethod.GET, + Domains.API.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "IpAccessControlList read failed: Unable to connect to server" - ); + throw new ApiConnectionException("IpAccessControlList read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "ip_access_control_lists", - response.getContent(), - IpAccessControlList.class, - client.getObjectMapper() - ); + "ip_access_control_lists", + response.getContent(), + IpAccessControlList.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.API.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.API.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/sip/IpAccessControlListUpdater.java b/src/main/java/com/twilio/rest/api/v2010/account/sip/IpAccessControlListUpdater.java index fa794b0183..31c9b43bba 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/sip/IpAccessControlListUpdater.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/sip/IpAccessControlListUpdater.java @@ -16,6 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -26,92 +28,70 @@ import com.twilio.rest.Domains; public class IpAccessControlListUpdater extends Updater { - - private String pathSid; + private String pathaccountSid; + private String pathsid; private String friendlyName; - private String pathAccountSid; - public IpAccessControlListUpdater( - final String pathSid, - final String friendlyName - ) { - this.pathSid = pathSid; + public IpAccessControlListUpdater(final String pathsid, final String friendlyName) { + this.pathsid = pathsid; this.friendlyName = friendlyName; } - public IpAccessControlListUpdater( - final String pathAccountSid, - final String pathSid, - final String friendlyName - ) { - this.pathAccountSid = pathAccountSid; - this.pathSid = pathSid; + public IpAccessControlListUpdater(final String pathaccountSid, final String pathsid, final String friendlyName) { + this.pathaccountSid = pathaccountSid; + this.pathsid = pathsid; this.friendlyName = friendlyName; } - public IpAccessControlListUpdater setFriendlyName( - final String friendlyName - ) { + + public IpAccessControlListUpdater setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + @Override public IpAccessControlList update(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/SIP/IpAccessControlLists/{Sid}.json"; - - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); - path = - path.replace( - "{" + "FriendlyName" + "}", - this.friendlyName.toString() - ); + + String path = "/2010-04-01/Accounts/{AccountSid}/SIP/IpAccessControlLists/{Sid}.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.API.toString(), - path + HttpMethod.POST, + Domains.API.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "IpAccessControlList update failed: Unable to connect to server" - ); + throw new ApiConnectionException("IpAccessControlList update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return IpAccessControlList.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return IpAccessControlList.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/sip/credentiallist/Credential.java b/src/main/java/com/twilio/rest/api/v2010/account/sip/credentiallist/Credential.java index a249e91e92..76487b3e16 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/sip/credentiallist/Credential.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/sip/credentiallist/Credential.java @@ -18,126 +18,104 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.time.ZonedDateTime; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Credential extends Resource { - private static final long serialVersionUID = 238688210273177L; - public static CredentialCreator creator( - final String pathCredentialListSid, - final String username, - final String password - ) { - return new CredentialCreator(pathCredentialListSid, username, password); + public static CredentialCreator creator(final String pathcredentialListSid, final String username, final String password) { + return new CredentialCreator( + pathcredentialListSid, username, password + ); } - public static CredentialCreator creator( - final String pathAccountSid, - final String pathCredentialListSid, - final String username, - final String password - ) { + + public static CredentialCreator creator(final String pathaccountSid, final String pathcredentialListSid, final String username, final String password) { return new CredentialCreator( - pathAccountSid, - pathCredentialListSid, - username, - password + pathaccountSid, pathcredentialListSid, username, password ); } - public static CredentialDeleter deleter( - final String pathCredentialListSid, - final String pathSid - ) { - return new CredentialDeleter(pathCredentialListSid, pathSid); + + public static CredentialDeleter deleter(final String pathcredentialListSid, final String pathsid) { + return new CredentialDeleter( + pathcredentialListSid, pathsid + ); } - public static CredentialDeleter deleter( - final String pathAccountSid, - final String pathCredentialListSid, - final String pathSid - ) { + + public static CredentialDeleter deleter(final String pathaccountSid, final String pathcredentialListSid, final String pathsid) { return new CredentialDeleter( - pathAccountSid, - pathCredentialListSid, - pathSid + pathaccountSid, pathcredentialListSid, pathsid ); } - public static CredentialFetcher fetcher( - final String pathCredentialListSid, - final String pathSid - ) { - return new CredentialFetcher(pathCredentialListSid, pathSid); + + public static CredentialFetcher fetcher(final String pathcredentialListSid, final String pathsid) { + return new CredentialFetcher( + pathcredentialListSid, pathsid + ); } - public static CredentialFetcher fetcher( - final String pathAccountSid, - final String pathCredentialListSid, - final String pathSid - ) { + + public static CredentialFetcher fetcher(final String pathaccountSid, final String pathcredentialListSid, final String pathsid) { return new CredentialFetcher( - pathAccountSid, - pathCredentialListSid, - pathSid + pathaccountSid, pathcredentialListSid, pathsid ); } - public static CredentialReader reader(final String pathCredentialListSid) { - return new CredentialReader(pathCredentialListSid); + + public static CredentialReader reader(final String pathcredentialListSid) { + return new CredentialReader( + pathcredentialListSid + ); } - public static CredentialReader reader( - final String pathAccountSid, - final String pathCredentialListSid - ) { - return new CredentialReader(pathAccountSid, pathCredentialListSid); + + public static CredentialReader reader(final String pathaccountSid, final String pathcredentialListSid) { + return new CredentialReader( + pathaccountSid, pathcredentialListSid + ); } - public static CredentialUpdater updater( - final String pathCredentialListSid, - final String pathSid - ) { - return new CredentialUpdater(pathCredentialListSid, pathSid); + + public static CredentialUpdater updater(final String pathcredentialListSid, final String pathsid) { + return new CredentialUpdater( + pathcredentialListSid, pathsid + ); } - public static CredentialUpdater updater( - final String pathAccountSid, - final String pathCredentialListSid, - final String pathSid - ) { + + public static CredentialUpdater updater(final String pathaccountSid, final String pathcredentialListSid, final String pathsid) { return new CredentialUpdater( - pathAccountSid, - pathCredentialListSid, - pathSid + pathaccountSid, pathcredentialListSid, pathsid ); } + /** * Converts a JSON String into a Credential object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Credential object represented by the provided JSON */ - public static Credential fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Credential fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Credential.class); @@ -152,14 +130,11 @@ public static Credential fromJson( * Converts a JSON InputStream into a Credential object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Credential object represented by the provided JSON */ - public static Credential fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Credential fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Credential.class); @@ -170,59 +145,53 @@ public static Credential fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; + @Getter private final String credentialListSid; - private final String username; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; + @Getter + private final String sid; + @Getter private final String uri; + @Getter + private final String username; @JsonCreator private Credential( - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("credential_list_sid") final String credentialListSid, - @JsonProperty("username") final String username, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("uri") final String uri + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("credential_list_sid") final String credentialListSid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.RFC2822Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.RFC2822Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("sid") final String sid, + @JsonProperty("uri") final String uri, + @JsonProperty("username") final String username ) { - this.sid = sid; this.accountSid = accountSid; this.credentialListSid = credentialListSid; - this.username = username; - this.dateCreated = DateConverter.rfc2822DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.rfc2822DateTimeFromString(dateUpdated); + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; + this.sid = sid; this.uri = uri; - } - - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getCredentialListSid() { - return this.credentialListSid; - } - - public final String getUsername() { - return this.username; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final String getUri() { - return this.uri; + this.username = username; } @Override @@ -236,28 +205,30 @@ public boolean equals(final Object o) { } Credential other = (Credential) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(credentialListSid, other.credentialListSid) && - Objects.equals(username, other.username) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(uri, other.uri) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(credentialListSid, other.credentialListSid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(sid, other.sid) && + Objects.equals(uri, other.uri) && + Objects.equals(username, other.username) ); } @Override public int hashCode() { return Objects.hash( - sid, - accountSid, - credentialListSid, - username, - dateCreated, - dateUpdated, - uri + accountSid, + credentialListSid, + dateCreated, + dateUpdated, + sid, + uri, + username ); } + + } + diff --git a/src/main/java/com/twilio/rest/api/v2010/account/sip/credentiallist/CredentialCreator.java b/src/main/java/com/twilio/rest/api/v2010/account/sip/credentiallist/CredentialCreator.java index 4911022746..0a0d35daf3 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/sip/credentiallist/CredentialCreator.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/sip/credentiallist/CredentialCreator.java @@ -14,8 +14,11 @@ package com.twilio.rest.api.v2010.account.sip.credentiallist; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,103 +30,84 @@ public class CredentialCreator extends Creator { - private String pathCredentialListSid; + private String pathaccountSid; + private String pathcredentialListSid; private String username; private String password; - private String pathAccountSid; - - public CredentialCreator( - final String pathCredentialListSid, - final String username, - final String password - ) { - this.pathCredentialListSid = pathCredentialListSid; + + public CredentialCreator(final String pathcredentialListSid, final String username, final String password) { + this.pathcredentialListSid = pathcredentialListSid; this.username = username; this.password = password; } - public CredentialCreator( - final String pathAccountSid, - final String pathCredentialListSid, - final String username, - final String password - ) { - this.pathAccountSid = pathAccountSid; - this.pathCredentialListSid = pathCredentialListSid; + public CredentialCreator(final String pathaccountSid, final String pathcredentialListSid, final String username, final String password) { + this.pathaccountSid = pathaccountSid; + this.pathcredentialListSid = pathcredentialListSid; this.username = username; this.password = password; } + public CredentialCreator setUsername(final String username) { this.username = username; return this; } + public CredentialCreator setPassword(final String password) { this.password = password; return this; } + @Override public Credential create(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/SIP/CredentialLists/{CredentialListSid}/Credentials.json"; - - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = - path.replace( - "{" + "CredentialListSid" + "}", - this.pathCredentialListSid.toString() - ); - path = path.replace("{" + "Username" + "}", this.username.toString()); - path = path.replace("{" + "Password" + "}", this.password.toString()); + + String path = "/2010-04-01/Accounts/{AccountSid}/SIP/CredentialLists/{CredentialListSid}/Credentials.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "CredentialListSid" + "}", this.pathcredentialListSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.API.toString(), - path + HttpMethod.POST, + Domains.API.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Credential creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("Credential creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Credential.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Credential.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (username != null) { - request.addPostParam("Username", username); + Serializer.toString(request, "Username", username, ParameterType.URLENCODED); } + + if (password != null) { - request.addPostParam("Password", password); + Serializer.toString(request, "Password", password, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/sip/credentiallist/CredentialDeleter.java b/src/main/java/com/twilio/rest/api/v2010/account/sip/credentiallist/CredentialDeleter.java index c08368035c..bb30c22256 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/sip/credentiallist/CredentialDeleter.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/sip/credentiallist/CredentialDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.api.v2010.account.sip.credentiallist; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,71 +26,50 @@ public class CredentialDeleter extends Deleter { - private String pathCredentialListSid; - private String pathSid; - private String pathAccountSid; + private String pathaccountSid; + private String pathcredentialListSid; + private String pathsid; - public CredentialDeleter( - final String pathCredentialListSid, - final String pathSid - ) { - this.pathCredentialListSid = pathCredentialListSid; - this.pathSid = pathSid; + public CredentialDeleter(final String pathcredentialListSid, final String pathsid) { + this.pathcredentialListSid = pathcredentialListSid; + this.pathsid = pathsid; } - public CredentialDeleter( - final String pathAccountSid, - final String pathCredentialListSid, - final String pathSid - ) { - this.pathAccountSid = pathAccountSid; - this.pathCredentialListSid = pathCredentialListSid; - this.pathSid = pathSid; + public CredentialDeleter(final String pathaccountSid, final String pathcredentialListSid, final String pathsid) { + this.pathaccountSid = pathaccountSid; + this.pathcredentialListSid = pathcredentialListSid; + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/SIP/CredentialLists/{CredentialListSid}/Credentials/{Sid}.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = - path.replace( - "{" + "CredentialListSid" + "}", - this.pathCredentialListSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/2010-04-01/Accounts/{AccountSid}/SIP/CredentialLists/{CredentialListSid}/Credentials/{Sid}.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "CredentialListSid" + "}", this.pathcredentialListSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.API.toString(), - path + HttpMethod.DELETE, + Domains.API.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Credential delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("Credential delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/sip/credentiallist/CredentialFetcher.java b/src/main/java/com/twilio/rest/api/v2010/account/sip/credentiallist/CredentialFetcher.java index f83e3256c8..f1c0f327fc 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/sip/credentiallist/CredentialFetcher.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/sip/credentiallist/CredentialFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.api.v2010.account.sip.credentiallist; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,78 +26,53 @@ public class CredentialFetcher extends Fetcher { - private String pathCredentialListSid; - private String pathSid; - private String pathAccountSid; + private String pathaccountSid; + private String pathcredentialListSid; + private String pathsid; - public CredentialFetcher( - final String pathCredentialListSid, - final String pathSid - ) { - this.pathCredentialListSid = pathCredentialListSid; - this.pathSid = pathSid; + public CredentialFetcher(final String pathcredentialListSid, final String pathsid) { + this.pathcredentialListSid = pathcredentialListSid; + this.pathsid = pathsid; } - public CredentialFetcher( - final String pathAccountSid, - final String pathCredentialListSid, - final String pathSid - ) { - this.pathAccountSid = pathAccountSid; - this.pathCredentialListSid = pathCredentialListSid; - this.pathSid = pathSid; + public CredentialFetcher(final String pathaccountSid, final String pathcredentialListSid, final String pathsid) { + this.pathaccountSid = pathaccountSid; + this.pathcredentialListSid = pathcredentialListSid; + this.pathsid = pathsid; } + @Override public Credential fetch(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/SIP/CredentialLists/{CredentialListSid}/Credentials/{Sid}.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = - path.replace( - "{" + "CredentialListSid" + "}", - this.pathCredentialListSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/2010-04-01/Accounts/{AccountSid}/SIP/CredentialLists/{CredentialListSid}/Credentials/{Sid}.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "CredentialListSid" + "}", this.pathcredentialListSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.API.toString(), - path + HttpMethod.GET, + Domains.API.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Credential fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Credential fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return Credential.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Credential.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/sip/credentiallist/CredentialReader.java b/src/main/java/com/twilio/rest/api/v2010/account/sip/credentiallist/CredentialReader.java index 8c26826732..36f7fdae90 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/sip/credentiallist/CredentialReader.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/sip/credentiallist/CredentialReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,134 +30,96 @@ public class CredentialReader extends Reader { - private String pathCredentialListSid; - private String pathAccountSid; + private String pathaccountSid; + private String pathcredentialListSid; private Long pageSize; - public CredentialReader(final String pathCredentialListSid) { - this.pathCredentialListSid = pathCredentialListSid; + public CredentialReader(final String pathcredentialListSid) { + this.pathcredentialListSid = pathcredentialListSid; } - public CredentialReader( - final String pathAccountSid, - final String pathCredentialListSid - ) { - this.pathAccountSid = pathAccountSid; - this.pathCredentialListSid = pathCredentialListSid; + public CredentialReader(final String pathaccountSid, final String pathcredentialListSid) { + this.pathaccountSid = pathaccountSid; + this.pathcredentialListSid = pathcredentialListSid; } + public CredentialReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/SIP/CredentialLists/{CredentialListSid}/Credentials.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = - path.replace( - "{" + "CredentialListSid" + "}", - this.pathCredentialListSid.toString() - ); + + String path = "/2010-04-01/Accounts/{AccountSid}/SIP/CredentialLists/{CredentialListSid}/Credentials.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "CredentialListSid" + "}", this.pathcredentialListSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.API.toString(), - path + HttpMethod.GET, + Domains.API.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Credential read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Credential read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "credentials", - response.getContent(), - Credential.class, - client.getObjectMapper() - ); + "credentials", + response.getContent(), + Credential.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.API.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.API.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/sip/credentiallist/CredentialUpdater.java b/src/main/java/com/twilio/rest/api/v2010/account/sip/credentiallist/CredentialUpdater.java index 770dcbe8f9..3759c940db 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/sip/credentiallist/CredentialUpdater.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/sip/credentiallist/CredentialUpdater.java @@ -16,6 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -26,91 +28,72 @@ import com.twilio.rest.Domains; public class CredentialUpdater extends Updater { - - private String pathCredentialListSid; - private String pathSid; - private String pathAccountSid; + private String pathaccountSid; + private String pathcredentialListSid; + private String pathsid; private String password; - public CredentialUpdater( - final String pathCredentialListSid, - final String pathSid - ) { - this.pathCredentialListSid = pathCredentialListSid; - this.pathSid = pathSid; + public CredentialUpdater(final String pathcredentialListSid, final String pathsid) { + this.pathcredentialListSid = pathcredentialListSid; + this.pathsid = pathsid; } - public CredentialUpdater( - final String pathAccountSid, - final String pathCredentialListSid, - final String pathSid - ) { - this.pathAccountSid = pathAccountSid; - this.pathCredentialListSid = pathCredentialListSid; - this.pathSid = pathSid; + public CredentialUpdater(final String pathaccountSid, final String pathcredentialListSid, final String pathsid) { + this.pathaccountSid = pathaccountSid; + this.pathcredentialListSid = pathcredentialListSid; + this.pathsid = pathsid; } + public CredentialUpdater setPassword(final String password) { this.password = password; return this; } + @Override public Credential update(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/SIP/CredentialLists/{CredentialListSid}/Credentials/{Sid}.json"; - - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = - path.replace( - "{" + "CredentialListSid" + "}", - this.pathCredentialListSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + + String path = "/2010-04-01/Accounts/{AccountSid}/SIP/CredentialLists/{CredentialListSid}/Credentials/{Sid}.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "CredentialListSid" + "}", this.pathcredentialListSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.API.toString(), - path + HttpMethod.POST, + Domains.API.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Credential update failed: Unable to connect to server" - ); + throw new ApiConnectionException("Credential update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Credential.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Credential.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (password != null) { - request.addPostParam("Password", password); + Serializer.toString(request, "Password", password, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/sip/domain/CredentialListMapping.java b/src/main/java/com/twilio/rest/api/v2010/account/sip/domain/CredentialListMapping.java index 090d71d493..d972463958 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/sip/domain/CredentialListMapping.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/sip/domain/CredentialListMapping.java @@ -18,109 +18,90 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.time.ZonedDateTime; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class CredentialListMapping extends Resource { - private static final long serialVersionUID = 220550473371145L; - public static CredentialListMappingCreator creator( - final String pathDomainSid, - final String credentialListSid - ) { + public static CredentialListMappingCreator creator(final String pathdomainSid, final String credentialListSid) { return new CredentialListMappingCreator( - pathDomainSid, - credentialListSid + pathdomainSid, credentialListSid ); } - public static CredentialListMappingCreator creator( - final String pathAccountSid, - final String pathDomainSid, - final String credentialListSid - ) { + + public static CredentialListMappingCreator creator(final String pathaccountSid, final String pathdomainSid, final String credentialListSid) { return new CredentialListMappingCreator( - pathAccountSid, - pathDomainSid, - credentialListSid + pathaccountSid, pathdomainSid, credentialListSid ); } - public static CredentialListMappingDeleter deleter( - final String pathDomainSid, - final String pathSid - ) { - return new CredentialListMappingDeleter(pathDomainSid, pathSid); + + public static CredentialListMappingDeleter deleter(final String pathdomainSid, final String pathsid) { + return new CredentialListMappingDeleter( + pathdomainSid, pathsid + ); } - public static CredentialListMappingDeleter deleter( - final String pathAccountSid, - final String pathDomainSid, - final String pathSid - ) { + + public static CredentialListMappingDeleter deleter(final String pathaccountSid, final String pathdomainSid, final String pathsid) { return new CredentialListMappingDeleter( - pathAccountSid, - pathDomainSid, - pathSid + pathaccountSid, pathdomainSid, pathsid ); } - public static CredentialListMappingFetcher fetcher( - final String pathDomainSid, - final String pathSid - ) { - return new CredentialListMappingFetcher(pathDomainSid, pathSid); + + public static CredentialListMappingFetcher fetcher(final String pathdomainSid, final String pathsid) { + return new CredentialListMappingFetcher( + pathdomainSid, pathsid + ); } - public static CredentialListMappingFetcher fetcher( - final String pathAccountSid, - final String pathDomainSid, - final String pathSid - ) { + + public static CredentialListMappingFetcher fetcher(final String pathaccountSid, final String pathdomainSid, final String pathsid) { return new CredentialListMappingFetcher( - pathAccountSid, - pathDomainSid, - pathSid + pathaccountSid, pathdomainSid, pathsid ); } - public static CredentialListMappingReader reader( - final String pathDomainSid - ) { - return new CredentialListMappingReader(pathDomainSid); + + public static CredentialListMappingReader reader(final String pathdomainSid) { + return new CredentialListMappingReader( + pathdomainSid + ); } - public static CredentialListMappingReader reader( - final String pathAccountSid, - final String pathDomainSid - ) { - return new CredentialListMappingReader(pathAccountSid, pathDomainSid); + + public static CredentialListMappingReader reader(final String pathaccountSid, final String pathdomainSid) { + return new CredentialListMappingReader( + pathaccountSid, pathdomainSid + ); } + /** * Converts a JSON String into a CredentialListMapping object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return CredentialListMapping object represented by the provided JSON */ - public static CredentialListMapping fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static CredentialListMapping fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, CredentialListMapping.class); @@ -135,14 +116,11 @@ public static CredentialListMapping fromJson( * Converts a JSON InputStream into a CredentialListMapping object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return CredentialListMapping object represented by the provided JSON */ - public static CredentialListMapping fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static CredentialListMapping fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, CredentialListMapping.class); @@ -153,61 +131,55 @@ public static CredentialListMapping fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; + @Getter private final String domainSid; + @Getter private final String friendlyName; + @Getter private final String sid; + @Getter private final String uri; @JsonCreator private CredentialListMapping( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("domain_sid") final String domainSid, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("sid") final String sid, - @JsonProperty("uri") final String uri + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.RFC2822Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.RFC2822Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("domain_sid") final String domainSid, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("sid") final String sid, + @JsonProperty("uri") final String uri ) { this.accountSid = accountSid; - this.dateCreated = DateConverter.rfc2822DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.rfc2822DateTimeFromString(dateUpdated); + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.domainSid = domainSid; this.friendlyName = friendlyName; this.sid = sid; this.uri = uri; } - public final String getAccountSid() { - return this.accountSid; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final String getDomainSid() { - return this.domainSid; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final String getSid() { - return this.sid; - } - - public final String getUri() { - return this.uri; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -219,28 +191,30 @@ public boolean equals(final Object o) { } CredentialListMapping other = (CredentialListMapping) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(domainSid, other.domainSid) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(sid, other.sid) && - Objects.equals(uri, other.uri) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(domainSid, other.domainSid) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(sid, other.sid) && + Objects.equals(uri, other.uri) ); } @Override public int hashCode() { return Objects.hash( - accountSid, - dateCreated, - dateUpdated, - domainSid, - friendlyName, - sid, - uri + accountSid, + dateCreated, + dateUpdated, + domainSid, + friendlyName, + sid, + uri ); } + + } + diff --git a/src/main/java/com/twilio/rest/api/v2010/account/sip/domain/CredentialListMappingCreator.java b/src/main/java/com/twilio/rest/api/v2010/account/sip/domain/CredentialListMappingCreator.java index 599db538ab..cef0105b22 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/sip/domain/CredentialListMappingCreator.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/sip/domain/CredentialListMappingCreator.java @@ -14,8 +14,11 @@ package com.twilio.rest.api.v2010.account.sip.domain; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,98 +28,72 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class CredentialListMappingCreator - extends Creator { +public class CredentialListMappingCreator extends Creator { - private String pathDomainSid; + private String pathaccountSid; + private String pathdomainSid; private String credentialListSid; - private String pathAccountSid; - public CredentialListMappingCreator( - final String pathDomainSid, - final String credentialListSid - ) { - this.pathDomainSid = pathDomainSid; + public CredentialListMappingCreator(final String pathdomainSid, final String credentialListSid) { + this.pathdomainSid = pathdomainSid; this.credentialListSid = credentialListSid; } - public CredentialListMappingCreator( - final String pathAccountSid, - final String pathDomainSid, - final String credentialListSid - ) { - this.pathAccountSid = pathAccountSid; - this.pathDomainSid = pathDomainSid; + public CredentialListMappingCreator(final String pathaccountSid, final String pathdomainSid, final String credentialListSid) { + this.pathaccountSid = pathaccountSid; + this.pathdomainSid = pathdomainSid; this.credentialListSid = credentialListSid; } - public CredentialListMappingCreator setCredentialListSid( - final String credentialListSid - ) { + + public CredentialListMappingCreator setCredentialListSid(final String credentialListSid) { this.credentialListSid = credentialListSid; return this; } + @Override public CredentialListMapping create(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/SIP/Domains/{DomainSid}/CredentialListMappings.json"; - - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = - path.replace( - "{" + "DomainSid" + "}", - this.pathDomainSid.toString() - ); - path = - path.replace( - "{" + "CredentialListSid" + "}", - this.credentialListSid.toString() - ); + + String path = "/2010-04-01/Accounts/{AccountSid}/SIP/Domains/{DomainSid}/CredentialListMappings.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "DomainSid" + "}", this.pathdomainSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.API.toString(), - path + HttpMethod.POST, + Domains.API.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "CredentialListMapping creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("CredentialListMapping creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return CredentialListMapping.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return CredentialListMapping.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (credentialListSid != null) { - request.addPostParam("CredentialListSid", credentialListSid); + Serializer.toString(request, "CredentialListSid", credentialListSid, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/sip/domain/CredentialListMappingDeleter.java b/src/main/java/com/twilio/rest/api/v2010/account/sip/domain/CredentialListMappingDeleter.java index 3434014756..22bd055bc1 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/sip/domain/CredentialListMappingDeleter.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/sip/domain/CredentialListMappingDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.api.v2010.account.sip.domain; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,74 +24,52 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class CredentialListMappingDeleter - extends Deleter { +public class CredentialListMappingDeleter extends Deleter { - private String pathDomainSid; - private String pathSid; - private String pathAccountSid; + private String pathaccountSid; + private String pathdomainSid; + private String pathsid; - public CredentialListMappingDeleter( - final String pathDomainSid, - final String pathSid - ) { - this.pathDomainSid = pathDomainSid; - this.pathSid = pathSid; + public CredentialListMappingDeleter(final String pathdomainSid, final String pathsid) { + this.pathdomainSid = pathdomainSid; + this.pathsid = pathsid; } - public CredentialListMappingDeleter( - final String pathAccountSid, - final String pathDomainSid, - final String pathSid - ) { - this.pathAccountSid = pathAccountSid; - this.pathDomainSid = pathDomainSid; - this.pathSid = pathSid; + public CredentialListMappingDeleter(final String pathaccountSid, final String pathdomainSid, final String pathsid) { + this.pathaccountSid = pathaccountSid; + this.pathdomainSid = pathdomainSid; + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/SIP/Domains/{DomainSid}/CredentialListMappings/{Sid}.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = - path.replace( - "{" + "DomainSid" + "}", - this.pathDomainSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/2010-04-01/Accounts/{AccountSid}/SIP/Domains/{DomainSid}/CredentialListMappings/{Sid}.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "DomainSid" + "}", this.pathdomainSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.API.toString(), - path + HttpMethod.DELETE, + Domains.API.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "CredentialListMapping delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("CredentialListMapping delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/sip/domain/CredentialListMappingFetcher.java b/src/main/java/com/twilio/rest/api/v2010/account/sip/domain/CredentialListMappingFetcher.java index 32c1769d3f..cdaedee45c 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/sip/domain/CredentialListMappingFetcher.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/sip/domain/CredentialListMappingFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.api.v2010.account.sip.domain; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,81 +24,55 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class CredentialListMappingFetcher - extends Fetcher { +public class CredentialListMappingFetcher extends Fetcher { - private String pathDomainSid; - private String pathSid; - private String pathAccountSid; + private String pathaccountSid; + private String pathdomainSid; + private String pathsid; - public CredentialListMappingFetcher( - final String pathDomainSid, - final String pathSid - ) { - this.pathDomainSid = pathDomainSid; - this.pathSid = pathSid; + public CredentialListMappingFetcher(final String pathdomainSid, final String pathsid) { + this.pathdomainSid = pathdomainSid; + this.pathsid = pathsid; } - public CredentialListMappingFetcher( - final String pathAccountSid, - final String pathDomainSid, - final String pathSid - ) { - this.pathAccountSid = pathAccountSid; - this.pathDomainSid = pathDomainSid; - this.pathSid = pathSid; + public CredentialListMappingFetcher(final String pathaccountSid, final String pathdomainSid, final String pathsid) { + this.pathaccountSid = pathaccountSid; + this.pathdomainSid = pathdomainSid; + this.pathsid = pathsid; } + @Override public CredentialListMapping fetch(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/SIP/Domains/{DomainSid}/CredentialListMappings/{Sid}.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = - path.replace( - "{" + "DomainSid" + "}", - this.pathDomainSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/2010-04-01/Accounts/{AccountSid}/SIP/Domains/{DomainSid}/CredentialListMappings/{Sid}.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "DomainSid" + "}", this.pathdomainSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.API.toString(), - path + HttpMethod.GET, + Domains.API.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "CredentialListMapping fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("CredentialListMapping fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return CredentialListMapping.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return CredentialListMapping.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/sip/domain/CredentialListMappingReader.java b/src/main/java/com/twilio/rest/api/v2010/account/sip/domain/CredentialListMappingReader.java index edeb28ee1b..ac5efa37bc 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/sip/domain/CredentialListMappingReader.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/sip/domain/CredentialListMappingReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,138 +30,96 @@ public class CredentialListMappingReader extends Reader { - private String pathDomainSid; - private String pathAccountSid; + private String pathaccountSid; + private String pathdomainSid; private Long pageSize; - public CredentialListMappingReader(final String pathDomainSid) { - this.pathDomainSid = pathDomainSid; + public CredentialListMappingReader(final String pathdomainSid) { + this.pathdomainSid = pathdomainSid; } - public CredentialListMappingReader( - final String pathAccountSid, - final String pathDomainSid - ) { - this.pathAccountSid = pathAccountSid; - this.pathDomainSid = pathDomainSid; + public CredentialListMappingReader(final String pathaccountSid, final String pathdomainSid) { + this.pathaccountSid = pathaccountSid; + this.pathdomainSid = pathdomainSid; } + public CredentialListMappingReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override - public ResourceSet read( - final TwilioRestClient client - ) { + public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } - public Page firstPage( - final TwilioRestClient client - ) { - String path = - "/2010-04-01/Accounts/{AccountSid}/SIP/Domains/{DomainSid}/CredentialListMappings.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = - path.replace( - "{" + "DomainSid" + "}", - this.pathDomainSid.toString() - ); + public Page firstPage(final TwilioRestClient client) { + + String path = "/2010-04-01/Accounts/{AccountSid}/SIP/Domains/{DomainSid}/CredentialListMappings.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "DomainSid" + "}", this.pathdomainSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.API.toString(), - path + HttpMethod.GET, + Domains.API.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "CredentialListMapping read failed: Unable to connect to server" - ); + throw new ApiConnectionException("CredentialListMapping read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "credential_list_mappings", - response.getContent(), - CredentialListMapping.class, - client.getObjectMapper() - ); + "credential_list_mappings", + response.getContent(), + CredentialListMapping.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.API.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.API.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/sip/domain/IpAccessControlListMapping.java b/src/main/java/com/twilio/rest/api/v2010/account/sip/domain/IpAccessControlListMapping.java index a1e6f04654..ddc3bb8cae 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/sip/domain/IpAccessControlListMapping.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/sip/domain/IpAccessControlListMapping.java @@ -18,118 +18,93 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.time.ZonedDateTime; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class IpAccessControlListMapping extends Resource { - private static final long serialVersionUID = 220550473371145L; - public static IpAccessControlListMappingCreator creator( - final String pathDomainSid, - final String ipAccessControlListSid - ) { + public static IpAccessControlListMappingCreator creator(final String pathdomainSid, final String ipAccessControlListSid) { return new IpAccessControlListMappingCreator( - pathDomainSid, - ipAccessControlListSid + pathdomainSid, ipAccessControlListSid ); } - public static IpAccessControlListMappingCreator creator( - final String pathAccountSid, - final String pathDomainSid, - final String ipAccessControlListSid - ) { + + public static IpAccessControlListMappingCreator creator(final String pathaccountSid, final String pathdomainSid, final String ipAccessControlListSid) { return new IpAccessControlListMappingCreator( - pathAccountSid, - pathDomainSid, - ipAccessControlListSid + pathaccountSid, pathdomainSid, ipAccessControlListSid ); } - public static IpAccessControlListMappingDeleter deleter( - final String pathDomainSid, - final String pathSid - ) { - return new IpAccessControlListMappingDeleter(pathDomainSid, pathSid); + + public static IpAccessControlListMappingDeleter deleter(final String pathdomainSid, final String pathsid) { + return new IpAccessControlListMappingDeleter( + pathdomainSid, pathsid + ); } - public static IpAccessControlListMappingDeleter deleter( - final String pathAccountSid, - final String pathDomainSid, - final String pathSid - ) { + + public static IpAccessControlListMappingDeleter deleter(final String pathaccountSid, final String pathdomainSid, final String pathsid) { return new IpAccessControlListMappingDeleter( - pathAccountSid, - pathDomainSid, - pathSid + pathaccountSid, pathdomainSid, pathsid ); } - public static IpAccessControlListMappingFetcher fetcher( - final String pathDomainSid, - final String pathSid - ) { - return new IpAccessControlListMappingFetcher(pathDomainSid, pathSid); + + public static IpAccessControlListMappingFetcher fetcher(final String pathdomainSid, final String pathsid) { + return new IpAccessControlListMappingFetcher( + pathdomainSid, pathsid + ); } - public static IpAccessControlListMappingFetcher fetcher( - final String pathAccountSid, - final String pathDomainSid, - final String pathSid - ) { + + public static IpAccessControlListMappingFetcher fetcher(final String pathaccountSid, final String pathdomainSid, final String pathsid) { return new IpAccessControlListMappingFetcher( - pathAccountSid, - pathDomainSid, - pathSid + pathaccountSid, pathdomainSid, pathsid ); } - public static IpAccessControlListMappingReader reader( - final String pathDomainSid - ) { - return new IpAccessControlListMappingReader(pathDomainSid); + + public static IpAccessControlListMappingReader reader(final String pathdomainSid) { + return new IpAccessControlListMappingReader( + pathdomainSid + ); } - public static IpAccessControlListMappingReader reader( - final String pathAccountSid, - final String pathDomainSid - ) { + + public static IpAccessControlListMappingReader reader(final String pathaccountSid, final String pathdomainSid) { return new IpAccessControlListMappingReader( - pathAccountSid, - pathDomainSid + pathaccountSid, pathdomainSid ); } + /** * Converts a JSON String into a IpAccessControlListMapping object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return IpAccessControlListMapping object represented by the provided JSON */ - public static IpAccessControlListMapping fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static IpAccessControlListMapping fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { - return objectMapper.readValue( - json, - IpAccessControlListMapping.class - ); + return objectMapper.readValue(json, IpAccessControlListMapping.class); } catch (final JsonMappingException | JsonParseException e) { throw new ApiException(e.getMessage(), e); } catch (final IOException e) { @@ -141,20 +116,14 @@ public static IpAccessControlListMapping fromJson( * Converts a JSON InputStream into a IpAccessControlListMapping object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return IpAccessControlListMapping object represented by the provided JSON */ - public static IpAccessControlListMapping fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static IpAccessControlListMapping fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { - return objectMapper.readValue( - json, - IpAccessControlListMapping.class - ); + return objectMapper.readValue(json, IpAccessControlListMapping.class); } catch (final JsonMappingException | JsonParseException e) { throw new ApiException(e.getMessage(), e); } catch (final IOException e) { @@ -162,61 +131,55 @@ public static IpAccessControlListMapping fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; + @Getter private final String domainSid; + @Getter private final String friendlyName; + @Getter private final String sid; + @Getter private final String uri; @JsonCreator private IpAccessControlListMapping( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("domain_sid") final String domainSid, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("sid") final String sid, - @JsonProperty("uri") final String uri + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.RFC2822Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.RFC2822Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("domain_sid") final String domainSid, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("sid") final String sid, + @JsonProperty("uri") final String uri ) { this.accountSid = accountSid; - this.dateCreated = DateConverter.rfc2822DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.rfc2822DateTimeFromString(dateUpdated); + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.domainSid = domainSid; this.friendlyName = friendlyName; this.sid = sid; this.uri = uri; } - public final String getAccountSid() { - return this.accountSid; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final String getDomainSid() { - return this.domainSid; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final String getSid() { - return this.sid; - } - - public final String getUri() { - return this.uri; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -228,28 +191,30 @@ public boolean equals(final Object o) { } IpAccessControlListMapping other = (IpAccessControlListMapping) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(domainSid, other.domainSid) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(sid, other.sid) && - Objects.equals(uri, other.uri) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(domainSid, other.domainSid) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(sid, other.sid) && + Objects.equals(uri, other.uri) ); } @Override public int hashCode() { return Objects.hash( - accountSid, - dateCreated, - dateUpdated, - domainSid, - friendlyName, - sid, - uri + accountSid, + dateCreated, + dateUpdated, + domainSid, + friendlyName, + sid, + uri ); } + + } + diff --git a/src/main/java/com/twilio/rest/api/v2010/account/sip/domain/IpAccessControlListMappingCreator.java b/src/main/java/com/twilio/rest/api/v2010/account/sip/domain/IpAccessControlListMappingCreator.java index b580f815fe..e8a699d878 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/sip/domain/IpAccessControlListMappingCreator.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/sip/domain/IpAccessControlListMappingCreator.java @@ -14,8 +14,11 @@ package com.twilio.rest.api.v2010.account.sip.domain; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,101 +28,72 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class IpAccessControlListMappingCreator - extends Creator { +public class IpAccessControlListMappingCreator extends Creator { - private String pathDomainSid; + private String pathaccountSid; + private String pathdomainSid; private String ipAccessControlListSid; - private String pathAccountSid; - public IpAccessControlListMappingCreator( - final String pathDomainSid, - final String ipAccessControlListSid - ) { - this.pathDomainSid = pathDomainSid; + public IpAccessControlListMappingCreator(final String pathdomainSid, final String ipAccessControlListSid) { + this.pathdomainSid = pathdomainSid; this.ipAccessControlListSid = ipAccessControlListSid; } - public IpAccessControlListMappingCreator( - final String pathAccountSid, - final String pathDomainSid, - final String ipAccessControlListSid - ) { - this.pathAccountSid = pathAccountSid; - this.pathDomainSid = pathDomainSid; + public IpAccessControlListMappingCreator(final String pathaccountSid, final String pathdomainSid, final String ipAccessControlListSid) { + this.pathaccountSid = pathaccountSid; + this.pathdomainSid = pathdomainSid; this.ipAccessControlListSid = ipAccessControlListSid; } - public IpAccessControlListMappingCreator setIpAccessControlListSid( - final String ipAccessControlListSid - ) { + + public IpAccessControlListMappingCreator setIpAccessControlListSid(final String ipAccessControlListSid) { this.ipAccessControlListSid = ipAccessControlListSid; return this; } + @Override public IpAccessControlListMapping create(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/SIP/Domains/{DomainSid}/IpAccessControlListMappings.json"; - - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = - path.replace( - "{" + "DomainSid" + "}", - this.pathDomainSid.toString() - ); - path = - path.replace( - "{" + "IpAccessControlListSid" + "}", - this.ipAccessControlListSid.toString() - ); + + String path = "/2010-04-01/Accounts/{AccountSid}/SIP/Domains/{DomainSid}/IpAccessControlListMappings.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "DomainSid" + "}", this.pathdomainSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.API.toString(), - path + HttpMethod.POST, + Domains.API.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "IpAccessControlListMapping creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("IpAccessControlListMapping creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return IpAccessControlListMapping.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return IpAccessControlListMapping.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (ipAccessControlListSid != null) { - request.addPostParam( - "IpAccessControlListSid", - ipAccessControlListSid - ); + Serializer.toString(request, "IpAccessControlListSid", ipAccessControlListSid, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/sip/domain/IpAccessControlListMappingDeleter.java b/src/main/java/com/twilio/rest/api/v2010/account/sip/domain/IpAccessControlListMappingDeleter.java index 79f2a081b7..834e8f1d87 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/sip/domain/IpAccessControlListMappingDeleter.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/sip/domain/IpAccessControlListMappingDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.api.v2010.account.sip.domain; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,74 +24,52 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class IpAccessControlListMappingDeleter - extends Deleter { +public class IpAccessControlListMappingDeleter extends Deleter { - private String pathDomainSid; - private String pathSid; - private String pathAccountSid; + private String pathaccountSid; + private String pathdomainSid; + private String pathsid; - public IpAccessControlListMappingDeleter( - final String pathDomainSid, - final String pathSid - ) { - this.pathDomainSid = pathDomainSid; - this.pathSid = pathSid; + public IpAccessControlListMappingDeleter(final String pathdomainSid, final String pathsid) { + this.pathdomainSid = pathdomainSid; + this.pathsid = pathsid; } - public IpAccessControlListMappingDeleter( - final String pathAccountSid, - final String pathDomainSid, - final String pathSid - ) { - this.pathAccountSid = pathAccountSid; - this.pathDomainSid = pathDomainSid; - this.pathSid = pathSid; + public IpAccessControlListMappingDeleter(final String pathaccountSid, final String pathdomainSid, final String pathsid) { + this.pathaccountSid = pathaccountSid; + this.pathdomainSid = pathdomainSid; + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/SIP/Domains/{DomainSid}/IpAccessControlListMappings/{Sid}.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = - path.replace( - "{" + "DomainSid" + "}", - this.pathDomainSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/2010-04-01/Accounts/{AccountSid}/SIP/Domains/{DomainSid}/IpAccessControlListMappings/{Sid}.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "DomainSid" + "}", this.pathdomainSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.API.toString(), - path + HttpMethod.DELETE, + Domains.API.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "IpAccessControlListMapping delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("IpAccessControlListMapping delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/sip/domain/IpAccessControlListMappingFetcher.java b/src/main/java/com/twilio/rest/api/v2010/account/sip/domain/IpAccessControlListMappingFetcher.java index 13e2d954a3..9672dd89b1 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/sip/domain/IpAccessControlListMappingFetcher.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/sip/domain/IpAccessControlListMappingFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.api.v2010.account.sip.domain; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,81 +24,55 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class IpAccessControlListMappingFetcher - extends Fetcher { +public class IpAccessControlListMappingFetcher extends Fetcher { - private String pathDomainSid; - private String pathSid; - private String pathAccountSid; + private String pathaccountSid; + private String pathdomainSid; + private String pathsid; - public IpAccessControlListMappingFetcher( - final String pathDomainSid, - final String pathSid - ) { - this.pathDomainSid = pathDomainSid; - this.pathSid = pathSid; + public IpAccessControlListMappingFetcher(final String pathdomainSid, final String pathsid) { + this.pathdomainSid = pathdomainSid; + this.pathsid = pathsid; } - public IpAccessControlListMappingFetcher( - final String pathAccountSid, - final String pathDomainSid, - final String pathSid - ) { - this.pathAccountSid = pathAccountSid; - this.pathDomainSid = pathDomainSid; - this.pathSid = pathSid; + public IpAccessControlListMappingFetcher(final String pathaccountSid, final String pathdomainSid, final String pathsid) { + this.pathaccountSid = pathaccountSid; + this.pathdomainSid = pathdomainSid; + this.pathsid = pathsid; } + @Override public IpAccessControlListMapping fetch(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/SIP/Domains/{DomainSid}/IpAccessControlListMappings/{Sid}.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = - path.replace( - "{" + "DomainSid" + "}", - this.pathDomainSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/2010-04-01/Accounts/{AccountSid}/SIP/Domains/{DomainSid}/IpAccessControlListMappings/{Sid}.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "DomainSid" + "}", this.pathdomainSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.API.toString(), - path + HttpMethod.GET, + Domains.API.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "IpAccessControlListMapping fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("IpAccessControlListMapping fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return IpAccessControlListMapping.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return IpAccessControlListMapping.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/sip/domain/IpAccessControlListMappingReader.java b/src/main/java/com/twilio/rest/api/v2010/account/sip/domain/IpAccessControlListMappingReader.java index 938416090b..574fcbec9a 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/sip/domain/IpAccessControlListMappingReader.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/sip/domain/IpAccessControlListMappingReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,141 +28,98 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class IpAccessControlListMappingReader - extends Reader { +public class IpAccessControlListMappingReader extends Reader { - private String pathDomainSid; - private String pathAccountSid; + private String pathaccountSid; + private String pathdomainSid; private Long pageSize; - public IpAccessControlListMappingReader(final String pathDomainSid) { - this.pathDomainSid = pathDomainSid; + public IpAccessControlListMappingReader(final String pathdomainSid) { + this.pathdomainSid = pathdomainSid; } - public IpAccessControlListMappingReader( - final String pathAccountSid, - final String pathDomainSid - ) { - this.pathAccountSid = pathAccountSid; - this.pathDomainSid = pathDomainSid; + public IpAccessControlListMappingReader(final String pathaccountSid, final String pathdomainSid) { + this.pathaccountSid = pathaccountSid; + this.pathdomainSid = pathdomainSid; } + public IpAccessControlListMappingReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override - public ResourceSet read( - final TwilioRestClient client - ) { + public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } - public Page firstPage( - final TwilioRestClient client - ) { - String path = - "/2010-04-01/Accounts/{AccountSid}/SIP/Domains/{DomainSid}/IpAccessControlListMappings.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = - path.replace( - "{" + "DomainSid" + "}", - this.pathDomainSid.toString() - ); + public Page firstPage(final TwilioRestClient client) { + + String path = "/2010-04-01/Accounts/{AccountSid}/SIP/Domains/{DomainSid}/IpAccessControlListMappings.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "DomainSid" + "}", this.pathdomainSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.API.toString(), - path + HttpMethod.GET, + Domains.API.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "IpAccessControlListMapping read failed: Unable to connect to server" - ); + throw new ApiConnectionException("IpAccessControlListMapping read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "ip_access_control_list_mappings", - response.getContent(), - IpAccessControlListMapping.class, - client.getObjectMapper() - ); + "ip_access_control_list_mappings", + response.getContent(), + IpAccessControlListMapping.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.API.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.API.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/sip/domain/authtypes/authtypecalls/AuthCallsCredentialListMapping.java b/src/main/java/com/twilio/rest/api/v2010/account/sip/domain/authtypes/authtypecalls/AuthCallsCredentialListMapping.java index 902b4cda8d..3122256fed 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/sip/domain/authtypes/authtypecalls/AuthCallsCredentialListMapping.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/sip/domain/authtypes/authtypecalls/AuthCallsCredentialListMapping.java @@ -18,124 +18,93 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.time.ZonedDateTime; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class AuthCallsCredentialListMapping extends Resource { - private static final long serialVersionUID = 16012497789519L; - public static AuthCallsCredentialListMappingCreator creator( - final String pathDomainSid, - final String credentialListSid - ) { + public static AuthCallsCredentialListMappingCreator creator(final String pathdomainSid, final String credentialListSid) { return new AuthCallsCredentialListMappingCreator( - pathDomainSid, - credentialListSid + pathdomainSid, credentialListSid ); } - public static AuthCallsCredentialListMappingCreator creator( - final String pathAccountSid, - final String pathDomainSid, - final String credentialListSid - ) { + + public static AuthCallsCredentialListMappingCreator creator(final String pathaccountSid, final String pathdomainSid, final String credentialListSid) { return new AuthCallsCredentialListMappingCreator( - pathAccountSid, - pathDomainSid, - credentialListSid + pathaccountSid, pathdomainSid, credentialListSid ); } - public static AuthCallsCredentialListMappingDeleter deleter( - final String pathDomainSid, - final String pathSid - ) { + + public static AuthCallsCredentialListMappingDeleter deleter(final String pathdomainSid, final String pathsid) { return new AuthCallsCredentialListMappingDeleter( - pathDomainSid, - pathSid + pathdomainSid, pathsid ); } - public static AuthCallsCredentialListMappingDeleter deleter( - final String pathAccountSid, - final String pathDomainSid, - final String pathSid - ) { + + public static AuthCallsCredentialListMappingDeleter deleter(final String pathaccountSid, final String pathdomainSid, final String pathsid) { return new AuthCallsCredentialListMappingDeleter( - pathAccountSid, - pathDomainSid, - pathSid + pathaccountSid, pathdomainSid, pathsid ); } - public static AuthCallsCredentialListMappingFetcher fetcher( - final String pathDomainSid, - final String pathSid - ) { + + public static AuthCallsCredentialListMappingFetcher fetcher(final String pathdomainSid, final String pathsid) { return new AuthCallsCredentialListMappingFetcher( - pathDomainSid, - pathSid + pathdomainSid, pathsid ); } - public static AuthCallsCredentialListMappingFetcher fetcher( - final String pathAccountSid, - final String pathDomainSid, - final String pathSid - ) { + + public static AuthCallsCredentialListMappingFetcher fetcher(final String pathaccountSid, final String pathdomainSid, final String pathsid) { return new AuthCallsCredentialListMappingFetcher( - pathAccountSid, - pathDomainSid, - pathSid + pathaccountSid, pathdomainSid, pathsid ); } - public static AuthCallsCredentialListMappingReader reader( - final String pathDomainSid - ) { - return new AuthCallsCredentialListMappingReader(pathDomainSid); + + public static AuthCallsCredentialListMappingReader reader(final String pathdomainSid) { + return new AuthCallsCredentialListMappingReader( + pathdomainSid + ); } - public static AuthCallsCredentialListMappingReader reader( - final String pathAccountSid, - final String pathDomainSid - ) { + + public static AuthCallsCredentialListMappingReader reader(final String pathaccountSid, final String pathdomainSid) { return new AuthCallsCredentialListMappingReader( - pathAccountSid, - pathDomainSid + pathaccountSid, pathdomainSid ); } + /** * Converts a JSON String into a AuthCallsCredentialListMapping object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return AuthCallsCredentialListMapping object represented by the provided JSON */ - public static AuthCallsCredentialListMapping fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static AuthCallsCredentialListMapping fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { - return objectMapper.readValue( - json, - AuthCallsCredentialListMapping.class - ); + return objectMapper.readValue(json, AuthCallsCredentialListMapping.class); } catch (final JsonMappingException | JsonParseException e) { throw new ApiException(e.getMessage(), e); } catch (final IOException e) { @@ -147,20 +116,14 @@ public static AuthCallsCredentialListMapping fromJson( * Converts a JSON InputStream into a AuthCallsCredentialListMapping object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return AuthCallsCredentialListMapping object represented by the provided JSON */ - public static AuthCallsCredentialListMapping fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static AuthCallsCredentialListMapping fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { - return objectMapper.readValue( - json, - AuthCallsCredentialListMapping.class - ); + return objectMapper.readValue(json, AuthCallsCredentialListMapping.class); } catch (final JsonMappingException | JsonParseException e) { throw new ApiException(e.getMessage(), e); } catch (final IOException e) { @@ -168,47 +131,47 @@ public static AuthCallsCredentialListMapping fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; + @Getter private final String friendlyName; + @Getter private final String sid; @JsonCreator private AuthCallsCredentialListMapping( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("sid") final String sid + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.RFC2822Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.RFC2822Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("sid") final String sid ) { this.accountSid = accountSid; - this.dateCreated = DateConverter.rfc2822DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.rfc2822DateTimeFromString(dateUpdated); + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.friendlyName = friendlyName; this.sid = sid; } - public final String getAccountSid() { - return this.accountSid; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final String getSid() { - return this.sid; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -219,26 +182,27 @@ public boolean equals(final Object o) { return false; } - AuthCallsCredentialListMapping other = - (AuthCallsCredentialListMapping) o; - + AuthCallsCredentialListMapping other = (AuthCallsCredentialListMapping) o; return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(sid, other.sid) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(sid, other.sid) ); } @Override public int hashCode() { return Objects.hash( - accountSid, - dateCreated, - dateUpdated, - friendlyName, - sid + accountSid, + dateCreated, + dateUpdated, + friendlyName, + sid ); } + + } + diff --git a/src/main/java/com/twilio/rest/api/v2010/account/sip/domain/authtypes/authtypecalls/AuthCallsCredentialListMappingCreator.java b/src/main/java/com/twilio/rest/api/v2010/account/sip/domain/authtypes/authtypecalls/AuthCallsCredentialListMappingCreator.java index 0ff1d57469..1e2d18999a 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/sip/domain/authtypes/authtypecalls/AuthCallsCredentialListMappingCreator.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/sip/domain/authtypes/authtypecalls/AuthCallsCredentialListMappingCreator.java @@ -14,8 +14,11 @@ package com.twilio.rest.api.v2010.account.sip.domain.authtypes.authtypecalls; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,100 +28,72 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class AuthCallsCredentialListMappingCreator - extends Creator { +public class AuthCallsCredentialListMappingCreator extends Creator { - private String pathDomainSid; + private String pathaccountSid; + private String pathdomainSid; private String credentialListSid; - private String pathAccountSid; - public AuthCallsCredentialListMappingCreator( - final String pathDomainSid, - final String credentialListSid - ) { - this.pathDomainSid = pathDomainSid; + public AuthCallsCredentialListMappingCreator(final String pathdomainSid, final String credentialListSid) { + this.pathdomainSid = pathdomainSid; this.credentialListSid = credentialListSid; } - public AuthCallsCredentialListMappingCreator( - final String pathAccountSid, - final String pathDomainSid, - final String credentialListSid - ) { - this.pathAccountSid = pathAccountSid; - this.pathDomainSid = pathDomainSid; + public AuthCallsCredentialListMappingCreator(final String pathaccountSid, final String pathdomainSid, final String credentialListSid) { + this.pathaccountSid = pathaccountSid; + this.pathdomainSid = pathdomainSid; this.credentialListSid = credentialListSid; } - public AuthCallsCredentialListMappingCreator setCredentialListSid( - final String credentialListSid - ) { + + public AuthCallsCredentialListMappingCreator setCredentialListSid(final String credentialListSid) { this.credentialListSid = credentialListSid; return this; } + @Override - public AuthCallsCredentialListMapping create( - final TwilioRestClient client - ) { - String path = - "/2010-04-01/Accounts/{AccountSid}/SIP/Domains/{DomainSid}/Auth/Calls/CredentialListMappings.json"; - - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = - path.replace( - "{" + "DomainSid" + "}", - this.pathDomainSid.toString() - ); - path = - path.replace( - "{" + "CredentialListSid" + "}", - this.credentialListSid.toString() - ); + public AuthCallsCredentialListMapping create(final TwilioRestClient client) { + + String path = "/2010-04-01/Accounts/{AccountSid}/SIP/Domains/{DomainSid}/Auth/Calls/CredentialListMappings.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "DomainSid" + "}", this.pathdomainSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.API.toString(), - path + HttpMethod.POST, + Domains.API.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "AuthCallsCredentialListMapping creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("AuthCallsCredentialListMapping creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return AuthCallsCredentialListMapping.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return AuthCallsCredentialListMapping.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (credentialListSid != null) { - request.addPostParam("CredentialListSid", credentialListSid); + Serializer.toString(request, "CredentialListSid", credentialListSid, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/sip/domain/authtypes/authtypecalls/AuthCallsCredentialListMappingDeleter.java b/src/main/java/com/twilio/rest/api/v2010/account/sip/domain/authtypes/authtypecalls/AuthCallsCredentialListMappingDeleter.java index 7779c39a50..73124dd791 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/sip/domain/authtypes/authtypecalls/AuthCallsCredentialListMappingDeleter.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/sip/domain/authtypes/authtypecalls/AuthCallsCredentialListMappingDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.api.v2010.account.sip.domain.authtypes.authtypecalls; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,74 +24,52 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class AuthCallsCredentialListMappingDeleter - extends Deleter { +public class AuthCallsCredentialListMappingDeleter extends Deleter { - private String pathDomainSid; - private String pathSid; - private String pathAccountSid; + private String pathaccountSid; + private String pathdomainSid; + private String pathsid; - public AuthCallsCredentialListMappingDeleter( - final String pathDomainSid, - final String pathSid - ) { - this.pathDomainSid = pathDomainSid; - this.pathSid = pathSid; + public AuthCallsCredentialListMappingDeleter(final String pathdomainSid, final String pathsid) { + this.pathdomainSid = pathdomainSid; + this.pathsid = pathsid; } - public AuthCallsCredentialListMappingDeleter( - final String pathAccountSid, - final String pathDomainSid, - final String pathSid - ) { - this.pathAccountSid = pathAccountSid; - this.pathDomainSid = pathDomainSid; - this.pathSid = pathSid; + public AuthCallsCredentialListMappingDeleter(final String pathaccountSid, final String pathdomainSid, final String pathsid) { + this.pathaccountSid = pathaccountSid; + this.pathdomainSid = pathdomainSid; + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/SIP/Domains/{DomainSid}/Auth/Calls/CredentialListMappings/{Sid}.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = - path.replace( - "{" + "DomainSid" + "}", - this.pathDomainSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/2010-04-01/Accounts/{AccountSid}/SIP/Domains/{DomainSid}/Auth/Calls/CredentialListMappings/{Sid}.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "DomainSid" + "}", this.pathdomainSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.API.toString(), - path + HttpMethod.DELETE, + Domains.API.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "AuthCallsCredentialListMapping delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("AuthCallsCredentialListMapping delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/sip/domain/authtypes/authtypecalls/AuthCallsCredentialListMappingFetcher.java b/src/main/java/com/twilio/rest/api/v2010/account/sip/domain/authtypes/authtypecalls/AuthCallsCredentialListMappingFetcher.java index 40067eaa26..2edbf921b8 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/sip/domain/authtypes/authtypecalls/AuthCallsCredentialListMappingFetcher.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/sip/domain/authtypes/authtypecalls/AuthCallsCredentialListMappingFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.api.v2010.account.sip.domain.authtypes.authtypecalls; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,81 +24,55 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class AuthCallsCredentialListMappingFetcher - extends Fetcher { +public class AuthCallsCredentialListMappingFetcher extends Fetcher { - private String pathDomainSid; - private String pathSid; - private String pathAccountSid; + private String pathaccountSid; + private String pathdomainSid; + private String pathsid; - public AuthCallsCredentialListMappingFetcher( - final String pathDomainSid, - final String pathSid - ) { - this.pathDomainSid = pathDomainSid; - this.pathSid = pathSid; + public AuthCallsCredentialListMappingFetcher(final String pathdomainSid, final String pathsid) { + this.pathdomainSid = pathdomainSid; + this.pathsid = pathsid; } - public AuthCallsCredentialListMappingFetcher( - final String pathAccountSid, - final String pathDomainSid, - final String pathSid - ) { - this.pathAccountSid = pathAccountSid; - this.pathDomainSid = pathDomainSid; - this.pathSid = pathSid; + public AuthCallsCredentialListMappingFetcher(final String pathaccountSid, final String pathdomainSid, final String pathsid) { + this.pathaccountSid = pathaccountSid; + this.pathdomainSid = pathdomainSid; + this.pathsid = pathsid; } + @Override public AuthCallsCredentialListMapping fetch(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/SIP/Domains/{DomainSid}/Auth/Calls/CredentialListMappings/{Sid}.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = - path.replace( - "{" + "DomainSid" + "}", - this.pathDomainSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/2010-04-01/Accounts/{AccountSid}/SIP/Domains/{DomainSid}/Auth/Calls/CredentialListMappings/{Sid}.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "DomainSid" + "}", this.pathdomainSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.API.toString(), - path + HttpMethod.GET, + Domains.API.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "AuthCallsCredentialListMapping fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("AuthCallsCredentialListMapping fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return AuthCallsCredentialListMapping.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return AuthCallsCredentialListMapping.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/sip/domain/authtypes/authtypecalls/AuthCallsCredentialListMappingReader.java b/src/main/java/com/twilio/rest/api/v2010/account/sip/domain/authtypes/authtypecalls/AuthCallsCredentialListMappingReader.java index 9f05af3057..d25475306d 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/sip/domain/authtypes/authtypecalls/AuthCallsCredentialListMappingReader.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/sip/domain/authtypes/authtypecalls/AuthCallsCredentialListMappingReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,143 +28,98 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class AuthCallsCredentialListMappingReader - extends Reader { +public class AuthCallsCredentialListMappingReader extends Reader { - private String pathDomainSid; - private String pathAccountSid; + private String pathaccountSid; + private String pathdomainSid; private Long pageSize; - public AuthCallsCredentialListMappingReader(final String pathDomainSid) { - this.pathDomainSid = pathDomainSid; + public AuthCallsCredentialListMappingReader(final String pathdomainSid) { + this.pathdomainSid = pathdomainSid; } - public AuthCallsCredentialListMappingReader( - final String pathAccountSid, - final String pathDomainSid - ) { - this.pathAccountSid = pathAccountSid; - this.pathDomainSid = pathDomainSid; + public AuthCallsCredentialListMappingReader(final String pathaccountSid, final String pathdomainSid) { + this.pathaccountSid = pathaccountSid; + this.pathdomainSid = pathdomainSid; } - public AuthCallsCredentialListMappingReader setPageSize( - final Long pageSize - ) { + + public AuthCallsCredentialListMappingReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override - public ResourceSet read( - final TwilioRestClient client - ) { + public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } - public Page firstPage( - final TwilioRestClient client - ) { - String path = - "/2010-04-01/Accounts/{AccountSid}/SIP/Domains/{DomainSid}/Auth/Calls/CredentialListMappings.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = - path.replace( - "{" + "DomainSid" + "}", - this.pathDomainSid.toString() - ); + public Page firstPage(final TwilioRestClient client) { + + String path = "/2010-04-01/Accounts/{AccountSid}/SIP/Domains/{DomainSid}/Auth/Calls/CredentialListMappings.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "DomainSid" + "}", this.pathdomainSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.API.toString(), - path + HttpMethod.GET, + Domains.API.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "AuthCallsCredentialListMapping read failed: Unable to connect to server" - ); + throw new ApiConnectionException("AuthCallsCredentialListMapping read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "contents", - response.getContent(), - AuthCallsCredentialListMapping.class, - client.getObjectMapper() - ); + "contents", + response.getContent(), + AuthCallsCredentialListMapping.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.API.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.API.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/sip/domain/authtypes/authtypecalls/AuthCallsIpAccessControlListMapping.java b/src/main/java/com/twilio/rest/api/v2010/account/sip/domain/authtypes/authtypecalls/AuthCallsIpAccessControlListMapping.java index a3d646a11c..2e1f80f128 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/sip/domain/authtypes/authtypecalls/AuthCallsIpAccessControlListMapping.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/sip/domain/authtypes/authtypecalls/AuthCallsIpAccessControlListMapping.java @@ -18,124 +18,93 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.time.ZonedDateTime; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class AuthCallsIpAccessControlListMapping extends Resource { - private static final long serialVersionUID = 16012497789519L; - public static AuthCallsIpAccessControlListMappingCreator creator( - final String pathDomainSid, - final String ipAccessControlListSid - ) { + public static AuthCallsIpAccessControlListMappingCreator creator(final String pathdomainSid, final String ipAccessControlListSid) { return new AuthCallsIpAccessControlListMappingCreator( - pathDomainSid, - ipAccessControlListSid + pathdomainSid, ipAccessControlListSid ); } - public static AuthCallsIpAccessControlListMappingCreator creator( - final String pathAccountSid, - final String pathDomainSid, - final String ipAccessControlListSid - ) { + + public static AuthCallsIpAccessControlListMappingCreator creator(final String pathaccountSid, final String pathdomainSid, final String ipAccessControlListSid) { return new AuthCallsIpAccessControlListMappingCreator( - pathAccountSid, - pathDomainSid, - ipAccessControlListSid + pathaccountSid, pathdomainSid, ipAccessControlListSid ); } - public static AuthCallsIpAccessControlListMappingDeleter deleter( - final String pathDomainSid, - final String pathSid - ) { + + public static AuthCallsIpAccessControlListMappingDeleter deleter(final String pathdomainSid, final String pathsid) { return new AuthCallsIpAccessControlListMappingDeleter( - pathDomainSid, - pathSid + pathdomainSid, pathsid ); } - public static AuthCallsIpAccessControlListMappingDeleter deleter( - final String pathAccountSid, - final String pathDomainSid, - final String pathSid - ) { + + public static AuthCallsIpAccessControlListMappingDeleter deleter(final String pathaccountSid, final String pathdomainSid, final String pathsid) { return new AuthCallsIpAccessControlListMappingDeleter( - pathAccountSid, - pathDomainSid, - pathSid + pathaccountSid, pathdomainSid, pathsid ); } - public static AuthCallsIpAccessControlListMappingFetcher fetcher( - final String pathDomainSid, - final String pathSid - ) { + + public static AuthCallsIpAccessControlListMappingFetcher fetcher(final String pathdomainSid, final String pathsid) { return new AuthCallsIpAccessControlListMappingFetcher( - pathDomainSid, - pathSid + pathdomainSid, pathsid ); } - public static AuthCallsIpAccessControlListMappingFetcher fetcher( - final String pathAccountSid, - final String pathDomainSid, - final String pathSid - ) { + + public static AuthCallsIpAccessControlListMappingFetcher fetcher(final String pathaccountSid, final String pathdomainSid, final String pathsid) { return new AuthCallsIpAccessControlListMappingFetcher( - pathAccountSid, - pathDomainSid, - pathSid + pathaccountSid, pathdomainSid, pathsid ); } - public static AuthCallsIpAccessControlListMappingReader reader( - final String pathDomainSid - ) { - return new AuthCallsIpAccessControlListMappingReader(pathDomainSid); + + public static AuthCallsIpAccessControlListMappingReader reader(final String pathdomainSid) { + return new AuthCallsIpAccessControlListMappingReader( + pathdomainSid + ); } - public static AuthCallsIpAccessControlListMappingReader reader( - final String pathAccountSid, - final String pathDomainSid - ) { + + public static AuthCallsIpAccessControlListMappingReader reader(final String pathaccountSid, final String pathdomainSid) { return new AuthCallsIpAccessControlListMappingReader( - pathAccountSid, - pathDomainSid + pathaccountSid, pathdomainSid ); } + /** * Converts a JSON String into a AuthCallsIpAccessControlListMapping object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return AuthCallsIpAccessControlListMapping object represented by the provided JSON */ - public static AuthCallsIpAccessControlListMapping fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static AuthCallsIpAccessControlListMapping fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { - return objectMapper.readValue( - json, - AuthCallsIpAccessControlListMapping.class - ); + return objectMapper.readValue(json, AuthCallsIpAccessControlListMapping.class); } catch (final JsonMappingException | JsonParseException e) { throw new ApiException(e.getMessage(), e); } catch (final IOException e) { @@ -147,20 +116,14 @@ public static AuthCallsIpAccessControlListMapping fromJson( * Converts a JSON InputStream into a AuthCallsIpAccessControlListMapping object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return AuthCallsIpAccessControlListMapping object represented by the provided JSON */ - public static AuthCallsIpAccessControlListMapping fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static AuthCallsIpAccessControlListMapping fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { - return objectMapper.readValue( - json, - AuthCallsIpAccessControlListMapping.class - ); + return objectMapper.readValue(json, AuthCallsIpAccessControlListMapping.class); } catch (final JsonMappingException | JsonParseException e) { throw new ApiException(e.getMessage(), e); } catch (final IOException e) { @@ -168,47 +131,47 @@ public static AuthCallsIpAccessControlListMapping fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; + @Getter private final String friendlyName; + @Getter private final String sid; @JsonCreator private AuthCallsIpAccessControlListMapping( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("sid") final String sid + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.RFC2822Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.RFC2822Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("sid") final String sid ) { this.accountSid = accountSid; - this.dateCreated = DateConverter.rfc2822DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.rfc2822DateTimeFromString(dateUpdated); + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.friendlyName = friendlyName; this.sid = sid; } - public final String getAccountSid() { - return this.accountSid; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final String getSid() { - return this.sid; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -219,26 +182,27 @@ public boolean equals(final Object o) { return false; } - AuthCallsIpAccessControlListMapping other = - (AuthCallsIpAccessControlListMapping) o; - + AuthCallsIpAccessControlListMapping other = (AuthCallsIpAccessControlListMapping) o; return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(sid, other.sid) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(sid, other.sid) ); } @Override public int hashCode() { return Objects.hash( - accountSid, - dateCreated, - dateUpdated, - friendlyName, - sid + accountSid, + dateCreated, + dateUpdated, + friendlyName, + sid ); } + + } + diff --git a/src/main/java/com/twilio/rest/api/v2010/account/sip/domain/authtypes/authtypecalls/AuthCallsIpAccessControlListMappingCreator.java b/src/main/java/com/twilio/rest/api/v2010/account/sip/domain/authtypes/authtypecalls/AuthCallsIpAccessControlListMappingCreator.java index 6f4d1f9692..1b7c0f19b7 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/sip/domain/authtypes/authtypecalls/AuthCallsIpAccessControlListMappingCreator.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/sip/domain/authtypes/authtypecalls/AuthCallsIpAccessControlListMappingCreator.java @@ -14,8 +14,11 @@ package com.twilio.rest.api.v2010.account.sip.domain.authtypes.authtypecalls; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,103 +28,72 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class AuthCallsIpAccessControlListMappingCreator - extends Creator { +public class AuthCallsIpAccessControlListMappingCreator extends Creator { - private String pathDomainSid; + private String pathaccountSid; + private String pathdomainSid; private String ipAccessControlListSid; - private String pathAccountSid; - public AuthCallsIpAccessControlListMappingCreator( - final String pathDomainSid, - final String ipAccessControlListSid - ) { - this.pathDomainSid = pathDomainSid; + public AuthCallsIpAccessControlListMappingCreator(final String pathdomainSid, final String ipAccessControlListSid) { + this.pathdomainSid = pathdomainSid; this.ipAccessControlListSid = ipAccessControlListSid; } - public AuthCallsIpAccessControlListMappingCreator( - final String pathAccountSid, - final String pathDomainSid, - final String ipAccessControlListSid - ) { - this.pathAccountSid = pathAccountSid; - this.pathDomainSid = pathDomainSid; + public AuthCallsIpAccessControlListMappingCreator(final String pathaccountSid, final String pathdomainSid, final String ipAccessControlListSid) { + this.pathaccountSid = pathaccountSid; + this.pathdomainSid = pathdomainSid; this.ipAccessControlListSid = ipAccessControlListSid; } - public AuthCallsIpAccessControlListMappingCreator setIpAccessControlListSid( - final String ipAccessControlListSid - ) { + + public AuthCallsIpAccessControlListMappingCreator setIpAccessControlListSid(final String ipAccessControlListSid) { this.ipAccessControlListSid = ipAccessControlListSid; return this; } + @Override - public AuthCallsIpAccessControlListMapping create( - final TwilioRestClient client - ) { - String path = - "/2010-04-01/Accounts/{AccountSid}/SIP/Domains/{DomainSid}/Auth/Calls/IpAccessControlListMappings.json"; - - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = - path.replace( - "{" + "DomainSid" + "}", - this.pathDomainSid.toString() - ); - path = - path.replace( - "{" + "IpAccessControlListSid" + "}", - this.ipAccessControlListSid.toString() - ); + public AuthCallsIpAccessControlListMapping create(final TwilioRestClient client) { + + String path = "/2010-04-01/Accounts/{AccountSid}/SIP/Domains/{DomainSid}/Auth/Calls/IpAccessControlListMappings.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "DomainSid" + "}", this.pathdomainSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.API.toString(), - path + HttpMethod.POST, + Domains.API.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "AuthCallsIpAccessControlListMapping creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("AuthCallsIpAccessControlListMapping creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return AuthCallsIpAccessControlListMapping.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return AuthCallsIpAccessControlListMapping.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (ipAccessControlListSid != null) { - request.addPostParam( - "IpAccessControlListSid", - ipAccessControlListSid - ); + Serializer.toString(request, "IpAccessControlListSid", ipAccessControlListSid, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/sip/domain/authtypes/authtypecalls/AuthCallsIpAccessControlListMappingDeleter.java b/src/main/java/com/twilio/rest/api/v2010/account/sip/domain/authtypes/authtypecalls/AuthCallsIpAccessControlListMappingDeleter.java index 6d69b6ebb9..5e70f3bbbf 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/sip/domain/authtypes/authtypecalls/AuthCallsIpAccessControlListMappingDeleter.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/sip/domain/authtypes/authtypecalls/AuthCallsIpAccessControlListMappingDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.api.v2010.account.sip.domain.authtypes.authtypecalls; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,74 +24,52 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class AuthCallsIpAccessControlListMappingDeleter - extends Deleter { +public class AuthCallsIpAccessControlListMappingDeleter extends Deleter { - private String pathDomainSid; - private String pathSid; - private String pathAccountSid; + private String pathaccountSid; + private String pathdomainSid; + private String pathsid; - public AuthCallsIpAccessControlListMappingDeleter( - final String pathDomainSid, - final String pathSid - ) { - this.pathDomainSid = pathDomainSid; - this.pathSid = pathSid; + public AuthCallsIpAccessControlListMappingDeleter(final String pathdomainSid, final String pathsid) { + this.pathdomainSid = pathdomainSid; + this.pathsid = pathsid; } - public AuthCallsIpAccessControlListMappingDeleter( - final String pathAccountSid, - final String pathDomainSid, - final String pathSid - ) { - this.pathAccountSid = pathAccountSid; - this.pathDomainSid = pathDomainSid; - this.pathSid = pathSid; + public AuthCallsIpAccessControlListMappingDeleter(final String pathaccountSid, final String pathdomainSid, final String pathsid) { + this.pathaccountSid = pathaccountSid; + this.pathdomainSid = pathdomainSid; + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/SIP/Domains/{DomainSid}/Auth/Calls/IpAccessControlListMappings/{Sid}.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = - path.replace( - "{" + "DomainSid" + "}", - this.pathDomainSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/2010-04-01/Accounts/{AccountSid}/SIP/Domains/{DomainSid}/Auth/Calls/IpAccessControlListMappings/{Sid}.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "DomainSid" + "}", this.pathdomainSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.API.toString(), - path + HttpMethod.DELETE, + Domains.API.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "AuthCallsIpAccessControlListMapping delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("AuthCallsIpAccessControlListMapping delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/sip/domain/authtypes/authtypecalls/AuthCallsIpAccessControlListMappingFetcher.java b/src/main/java/com/twilio/rest/api/v2010/account/sip/domain/authtypes/authtypecalls/AuthCallsIpAccessControlListMappingFetcher.java index 84afa4fbe4..e7f0ec0fd2 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/sip/domain/authtypes/authtypecalls/AuthCallsIpAccessControlListMappingFetcher.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/sip/domain/authtypes/authtypecalls/AuthCallsIpAccessControlListMappingFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.api.v2010.account.sip.domain.authtypes.authtypecalls; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,83 +24,55 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class AuthCallsIpAccessControlListMappingFetcher - extends Fetcher { +public class AuthCallsIpAccessControlListMappingFetcher extends Fetcher { - private String pathDomainSid; - private String pathSid; - private String pathAccountSid; + private String pathaccountSid; + private String pathdomainSid; + private String pathsid; - public AuthCallsIpAccessControlListMappingFetcher( - final String pathDomainSid, - final String pathSid - ) { - this.pathDomainSid = pathDomainSid; - this.pathSid = pathSid; + public AuthCallsIpAccessControlListMappingFetcher(final String pathdomainSid, final String pathsid) { + this.pathdomainSid = pathdomainSid; + this.pathsid = pathsid; } - public AuthCallsIpAccessControlListMappingFetcher( - final String pathAccountSid, - final String pathDomainSid, - final String pathSid - ) { - this.pathAccountSid = pathAccountSid; - this.pathDomainSid = pathDomainSid; - this.pathSid = pathSid; + public AuthCallsIpAccessControlListMappingFetcher(final String pathaccountSid, final String pathdomainSid, final String pathsid) { + this.pathaccountSid = pathaccountSid; + this.pathdomainSid = pathdomainSid; + this.pathsid = pathsid; } + @Override - public AuthCallsIpAccessControlListMapping fetch( - final TwilioRestClient client - ) { - String path = - "/2010-04-01/Accounts/{AccountSid}/SIP/Domains/{DomainSid}/Auth/Calls/IpAccessControlListMappings/{Sid}.json"; + public AuthCallsIpAccessControlListMapping fetch(final TwilioRestClient client) { + + String path = "/2010-04-01/Accounts/{AccountSid}/SIP/Domains/{DomainSid}/Auth/Calls/IpAccessControlListMappings/{Sid}.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "DomainSid" + "}", this.pathdomainSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = - path.replace( - "{" + "DomainSid" + "}", - this.pathDomainSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.API.toString(), - path + HttpMethod.GET, + Domains.API.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "AuthCallsIpAccessControlListMapping fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("AuthCallsIpAccessControlListMapping fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return AuthCallsIpAccessControlListMapping.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return AuthCallsIpAccessControlListMapping.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/sip/domain/authtypes/authtypecalls/AuthCallsIpAccessControlListMappingReader.java b/src/main/java/com/twilio/rest/api/v2010/account/sip/domain/authtypes/authtypecalls/AuthCallsIpAccessControlListMappingReader.java index e7e3a7d029..ddef0c2a96 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/sip/domain/authtypes/authtypecalls/AuthCallsIpAccessControlListMappingReader.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/sip/domain/authtypes/authtypecalls/AuthCallsIpAccessControlListMappingReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,145 +28,98 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class AuthCallsIpAccessControlListMappingReader - extends Reader { +public class AuthCallsIpAccessControlListMappingReader extends Reader { - private String pathDomainSid; - private String pathAccountSid; + private String pathaccountSid; + private String pathdomainSid; private Long pageSize; - public AuthCallsIpAccessControlListMappingReader( - final String pathDomainSid - ) { - this.pathDomainSid = pathDomainSid; + public AuthCallsIpAccessControlListMappingReader(final String pathdomainSid) { + this.pathdomainSid = pathdomainSid; } - public AuthCallsIpAccessControlListMappingReader( - final String pathAccountSid, - final String pathDomainSid - ) { - this.pathAccountSid = pathAccountSid; - this.pathDomainSid = pathDomainSid; + public AuthCallsIpAccessControlListMappingReader(final String pathaccountSid, final String pathdomainSid) { + this.pathaccountSid = pathaccountSid; + this.pathdomainSid = pathdomainSid; } - public AuthCallsIpAccessControlListMappingReader setPageSize( - final Long pageSize - ) { + + public AuthCallsIpAccessControlListMappingReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override - public ResourceSet read( - final TwilioRestClient client - ) { + public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } - public Page firstPage( - final TwilioRestClient client - ) { - String path = - "/2010-04-01/Accounts/{AccountSid}/SIP/Domains/{DomainSid}/Auth/Calls/IpAccessControlListMappings.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = - path.replace( - "{" + "DomainSid" + "}", - this.pathDomainSid.toString() - ); + public Page firstPage(final TwilioRestClient client) { + + String path = "/2010-04-01/Accounts/{AccountSid}/SIP/Domains/{DomainSid}/Auth/Calls/IpAccessControlListMappings.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "DomainSid" + "}", this.pathdomainSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.API.toString(), - path + HttpMethod.GET, + Domains.API.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "AuthCallsIpAccessControlListMapping read failed: Unable to connect to server" - ); + throw new ApiConnectionException("AuthCallsIpAccessControlListMapping read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "contents", - response.getContent(), - AuthCallsIpAccessControlListMapping.class, - client.getObjectMapper() - ); + "contents", + response.getContent(), + AuthCallsIpAccessControlListMapping.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.API.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.API.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/sip/domain/authtypes/authtyperegistrations/AuthRegistrationsCredentialListMapping.java b/src/main/java/com/twilio/rest/api/v2010/account/sip/domain/authtypes/authtyperegistrations/AuthRegistrationsCredentialListMapping.java index 24efcfa23d..5d83045fc5 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/sip/domain/authtypes/authtyperegistrations/AuthRegistrationsCredentialListMapping.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/sip/domain/authtypes/authtyperegistrations/AuthRegistrationsCredentialListMapping.java @@ -18,124 +18,93 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.time.ZonedDateTime; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class AuthRegistrationsCredentialListMapping extends Resource { - private static final long serialVersionUID = 16012497789519L; - public static AuthRegistrationsCredentialListMappingCreator creator( - final String pathDomainSid, - final String credentialListSid - ) { + public static AuthRegistrationsCredentialListMappingCreator creator(final String pathdomainSid, final String credentialListSid) { return new AuthRegistrationsCredentialListMappingCreator( - pathDomainSid, - credentialListSid + pathdomainSid, credentialListSid ); } - public static AuthRegistrationsCredentialListMappingCreator creator( - final String pathAccountSid, - final String pathDomainSid, - final String credentialListSid - ) { + + public static AuthRegistrationsCredentialListMappingCreator creator(final String pathaccountSid, final String pathdomainSid, final String credentialListSid) { return new AuthRegistrationsCredentialListMappingCreator( - pathAccountSid, - pathDomainSid, - credentialListSid + pathaccountSid, pathdomainSid, credentialListSid ); } - public static AuthRegistrationsCredentialListMappingDeleter deleter( - final String pathDomainSid, - final String pathSid - ) { + + public static AuthRegistrationsCredentialListMappingDeleter deleter(final String pathdomainSid, final String pathsid) { return new AuthRegistrationsCredentialListMappingDeleter( - pathDomainSid, - pathSid + pathdomainSid, pathsid ); } - public static AuthRegistrationsCredentialListMappingDeleter deleter( - final String pathAccountSid, - final String pathDomainSid, - final String pathSid - ) { + + public static AuthRegistrationsCredentialListMappingDeleter deleter(final String pathaccountSid, final String pathdomainSid, final String pathsid) { return new AuthRegistrationsCredentialListMappingDeleter( - pathAccountSid, - pathDomainSid, - pathSid + pathaccountSid, pathdomainSid, pathsid ); } - public static AuthRegistrationsCredentialListMappingFetcher fetcher( - final String pathDomainSid, - final String pathSid - ) { + + public static AuthRegistrationsCredentialListMappingFetcher fetcher(final String pathdomainSid, final String pathsid) { return new AuthRegistrationsCredentialListMappingFetcher( - pathDomainSid, - pathSid + pathdomainSid, pathsid ); } - public static AuthRegistrationsCredentialListMappingFetcher fetcher( - final String pathAccountSid, - final String pathDomainSid, - final String pathSid - ) { + + public static AuthRegistrationsCredentialListMappingFetcher fetcher(final String pathaccountSid, final String pathdomainSid, final String pathsid) { return new AuthRegistrationsCredentialListMappingFetcher( - pathAccountSid, - pathDomainSid, - pathSid + pathaccountSid, pathdomainSid, pathsid ); } - public static AuthRegistrationsCredentialListMappingReader reader( - final String pathDomainSid - ) { - return new AuthRegistrationsCredentialListMappingReader(pathDomainSid); + + public static AuthRegistrationsCredentialListMappingReader reader(final String pathdomainSid) { + return new AuthRegistrationsCredentialListMappingReader( + pathdomainSid + ); } - public static AuthRegistrationsCredentialListMappingReader reader( - final String pathAccountSid, - final String pathDomainSid - ) { + + public static AuthRegistrationsCredentialListMappingReader reader(final String pathaccountSid, final String pathdomainSid) { return new AuthRegistrationsCredentialListMappingReader( - pathAccountSid, - pathDomainSid + pathaccountSid, pathdomainSid ); } + /** * Converts a JSON String into a AuthRegistrationsCredentialListMapping object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return AuthRegistrationsCredentialListMapping object represented by the provided JSON */ - public static AuthRegistrationsCredentialListMapping fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static AuthRegistrationsCredentialListMapping fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { - return objectMapper.readValue( - json, - AuthRegistrationsCredentialListMapping.class - ); + return objectMapper.readValue(json, AuthRegistrationsCredentialListMapping.class); } catch (final JsonMappingException | JsonParseException e) { throw new ApiException(e.getMessage(), e); } catch (final IOException e) { @@ -147,20 +116,14 @@ public static AuthRegistrationsCredentialListMapping fromJson( * Converts a JSON InputStream into a AuthRegistrationsCredentialListMapping object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return AuthRegistrationsCredentialListMapping object represented by the provided JSON */ - public static AuthRegistrationsCredentialListMapping fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static AuthRegistrationsCredentialListMapping fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { - return objectMapper.readValue( - json, - AuthRegistrationsCredentialListMapping.class - ); + return objectMapper.readValue(json, AuthRegistrationsCredentialListMapping.class); } catch (final JsonMappingException | JsonParseException e) { throw new ApiException(e.getMessage(), e); } catch (final IOException e) { @@ -168,47 +131,47 @@ public static AuthRegistrationsCredentialListMapping fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; + @Getter private final String friendlyName; + @Getter private final String sid; @JsonCreator private AuthRegistrationsCredentialListMapping( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("sid") final String sid + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.RFC2822Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.RFC2822Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("sid") final String sid ) { this.accountSid = accountSid; - this.dateCreated = DateConverter.rfc2822DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.rfc2822DateTimeFromString(dateUpdated); + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.friendlyName = friendlyName; this.sid = sid; } - public final String getAccountSid() { - return this.accountSid; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final String getSid() { - return this.sid; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -219,26 +182,27 @@ public boolean equals(final Object o) { return false; } - AuthRegistrationsCredentialListMapping other = - (AuthRegistrationsCredentialListMapping) o; - + AuthRegistrationsCredentialListMapping other = (AuthRegistrationsCredentialListMapping) o; return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(sid, other.sid) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(sid, other.sid) ); } @Override public int hashCode() { return Objects.hash( - accountSid, - dateCreated, - dateUpdated, - friendlyName, - sid + accountSid, + dateCreated, + dateUpdated, + friendlyName, + sid ); } + + } + diff --git a/src/main/java/com/twilio/rest/api/v2010/account/sip/domain/authtypes/authtyperegistrations/AuthRegistrationsCredentialListMappingCreator.java b/src/main/java/com/twilio/rest/api/v2010/account/sip/domain/authtypes/authtyperegistrations/AuthRegistrationsCredentialListMappingCreator.java index be98b5d6b9..406196cdcf 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/sip/domain/authtypes/authtyperegistrations/AuthRegistrationsCredentialListMappingCreator.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/sip/domain/authtypes/authtyperegistrations/AuthRegistrationsCredentialListMappingCreator.java @@ -14,8 +14,11 @@ package com.twilio.rest.api.v2010.account.sip.domain.authtypes.authtyperegistrations; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,100 +28,72 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class AuthRegistrationsCredentialListMappingCreator - extends Creator { +public class AuthRegistrationsCredentialListMappingCreator extends Creator { - private String pathDomainSid; + private String pathaccountSid; + private String pathdomainSid; private String credentialListSid; - private String pathAccountSid; - public AuthRegistrationsCredentialListMappingCreator( - final String pathDomainSid, - final String credentialListSid - ) { - this.pathDomainSid = pathDomainSid; + public AuthRegistrationsCredentialListMappingCreator(final String pathdomainSid, final String credentialListSid) { + this.pathdomainSid = pathdomainSid; this.credentialListSid = credentialListSid; } - public AuthRegistrationsCredentialListMappingCreator( - final String pathAccountSid, - final String pathDomainSid, - final String credentialListSid - ) { - this.pathAccountSid = pathAccountSid; - this.pathDomainSid = pathDomainSid; + public AuthRegistrationsCredentialListMappingCreator(final String pathaccountSid, final String pathdomainSid, final String credentialListSid) { + this.pathaccountSid = pathaccountSid; + this.pathdomainSid = pathdomainSid; this.credentialListSid = credentialListSid; } - public AuthRegistrationsCredentialListMappingCreator setCredentialListSid( - final String credentialListSid - ) { + + public AuthRegistrationsCredentialListMappingCreator setCredentialListSid(final String credentialListSid) { this.credentialListSid = credentialListSid; return this; } + @Override - public AuthRegistrationsCredentialListMapping create( - final TwilioRestClient client - ) { - String path = - "/2010-04-01/Accounts/{AccountSid}/SIP/Domains/{DomainSid}/Auth/Registrations/CredentialListMappings.json"; - - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = - path.replace( - "{" + "DomainSid" + "}", - this.pathDomainSid.toString() - ); - path = - path.replace( - "{" + "CredentialListSid" + "}", - this.credentialListSid.toString() - ); + public AuthRegistrationsCredentialListMapping create(final TwilioRestClient client) { + + String path = "/2010-04-01/Accounts/{AccountSid}/SIP/Domains/{DomainSid}/Auth/Registrations/CredentialListMappings.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "DomainSid" + "}", this.pathdomainSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.API.toString(), - path + HttpMethod.POST, + Domains.API.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "AuthRegistrationsCredentialListMapping creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("AuthRegistrationsCredentialListMapping creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return AuthRegistrationsCredentialListMapping.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return AuthRegistrationsCredentialListMapping.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (credentialListSid != null) { - request.addPostParam("CredentialListSid", credentialListSid); + Serializer.toString(request, "CredentialListSid", credentialListSid, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/sip/domain/authtypes/authtyperegistrations/AuthRegistrationsCredentialListMappingDeleter.java b/src/main/java/com/twilio/rest/api/v2010/account/sip/domain/authtypes/authtyperegistrations/AuthRegistrationsCredentialListMappingDeleter.java index ce7cae7df0..0ef5d68fae 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/sip/domain/authtypes/authtyperegistrations/AuthRegistrationsCredentialListMappingDeleter.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/sip/domain/authtypes/authtyperegistrations/AuthRegistrationsCredentialListMappingDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.api.v2010.account.sip.domain.authtypes.authtyperegistrations; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,74 +24,52 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class AuthRegistrationsCredentialListMappingDeleter - extends Deleter { +public class AuthRegistrationsCredentialListMappingDeleter extends Deleter { - private String pathDomainSid; - private String pathSid; - private String pathAccountSid; + private String pathaccountSid; + private String pathdomainSid; + private String pathsid; - public AuthRegistrationsCredentialListMappingDeleter( - final String pathDomainSid, - final String pathSid - ) { - this.pathDomainSid = pathDomainSid; - this.pathSid = pathSid; + public AuthRegistrationsCredentialListMappingDeleter(final String pathdomainSid, final String pathsid) { + this.pathdomainSid = pathdomainSid; + this.pathsid = pathsid; } - public AuthRegistrationsCredentialListMappingDeleter( - final String pathAccountSid, - final String pathDomainSid, - final String pathSid - ) { - this.pathAccountSid = pathAccountSid; - this.pathDomainSid = pathDomainSid; - this.pathSid = pathSid; + public AuthRegistrationsCredentialListMappingDeleter(final String pathaccountSid, final String pathdomainSid, final String pathsid) { + this.pathaccountSid = pathaccountSid; + this.pathdomainSid = pathdomainSid; + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/SIP/Domains/{DomainSid}/Auth/Registrations/CredentialListMappings/{Sid}.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = - path.replace( - "{" + "DomainSid" + "}", - this.pathDomainSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/2010-04-01/Accounts/{AccountSid}/SIP/Domains/{DomainSid}/Auth/Registrations/CredentialListMappings/{Sid}.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "DomainSid" + "}", this.pathdomainSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.API.toString(), - path + HttpMethod.DELETE, + Domains.API.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "AuthRegistrationsCredentialListMapping delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("AuthRegistrationsCredentialListMapping delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/sip/domain/authtypes/authtyperegistrations/AuthRegistrationsCredentialListMappingFetcher.java b/src/main/java/com/twilio/rest/api/v2010/account/sip/domain/authtypes/authtyperegistrations/AuthRegistrationsCredentialListMappingFetcher.java index e0f65b1af2..ba7b1f72a3 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/sip/domain/authtypes/authtyperegistrations/AuthRegistrationsCredentialListMappingFetcher.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/sip/domain/authtypes/authtyperegistrations/AuthRegistrationsCredentialListMappingFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.api.v2010.account.sip.domain.authtypes.authtyperegistrations; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,83 +24,55 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class AuthRegistrationsCredentialListMappingFetcher - extends Fetcher { +public class AuthRegistrationsCredentialListMappingFetcher extends Fetcher { - private String pathDomainSid; - private String pathSid; - private String pathAccountSid; + private String pathaccountSid; + private String pathdomainSid; + private String pathsid; - public AuthRegistrationsCredentialListMappingFetcher( - final String pathDomainSid, - final String pathSid - ) { - this.pathDomainSid = pathDomainSid; - this.pathSid = pathSid; + public AuthRegistrationsCredentialListMappingFetcher(final String pathdomainSid, final String pathsid) { + this.pathdomainSid = pathdomainSid; + this.pathsid = pathsid; } - public AuthRegistrationsCredentialListMappingFetcher( - final String pathAccountSid, - final String pathDomainSid, - final String pathSid - ) { - this.pathAccountSid = pathAccountSid; - this.pathDomainSid = pathDomainSid; - this.pathSid = pathSid; + public AuthRegistrationsCredentialListMappingFetcher(final String pathaccountSid, final String pathdomainSid, final String pathsid) { + this.pathaccountSid = pathaccountSid; + this.pathdomainSid = pathdomainSid; + this.pathsid = pathsid; } + @Override - public AuthRegistrationsCredentialListMapping fetch( - final TwilioRestClient client - ) { - String path = - "/2010-04-01/Accounts/{AccountSid}/SIP/Domains/{DomainSid}/Auth/Registrations/CredentialListMappings/{Sid}.json"; + public AuthRegistrationsCredentialListMapping fetch(final TwilioRestClient client) { + + String path = "/2010-04-01/Accounts/{AccountSid}/SIP/Domains/{DomainSid}/Auth/Registrations/CredentialListMappings/{Sid}.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "DomainSid" + "}", this.pathdomainSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = - path.replace( - "{" + "DomainSid" + "}", - this.pathDomainSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.API.toString(), - path + HttpMethod.GET, + Domains.API.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "AuthRegistrationsCredentialListMapping fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("AuthRegistrationsCredentialListMapping fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return AuthRegistrationsCredentialListMapping.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return AuthRegistrationsCredentialListMapping.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/sip/domain/authtypes/authtyperegistrations/AuthRegistrationsCredentialListMappingReader.java b/src/main/java/com/twilio/rest/api/v2010/account/sip/domain/authtypes/authtyperegistrations/AuthRegistrationsCredentialListMappingReader.java index 1be51ba227..cc975a0a20 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/sip/domain/authtypes/authtyperegistrations/AuthRegistrationsCredentialListMappingReader.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/sip/domain/authtypes/authtyperegistrations/AuthRegistrationsCredentialListMappingReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,145 +28,98 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class AuthRegistrationsCredentialListMappingReader - extends Reader { +public class AuthRegistrationsCredentialListMappingReader extends Reader { - private String pathDomainSid; - private String pathAccountSid; + private String pathaccountSid; + private String pathdomainSid; private Long pageSize; - public AuthRegistrationsCredentialListMappingReader( - final String pathDomainSid - ) { - this.pathDomainSid = pathDomainSid; + public AuthRegistrationsCredentialListMappingReader(final String pathdomainSid) { + this.pathdomainSid = pathdomainSid; } - public AuthRegistrationsCredentialListMappingReader( - final String pathAccountSid, - final String pathDomainSid - ) { - this.pathAccountSid = pathAccountSid; - this.pathDomainSid = pathDomainSid; + public AuthRegistrationsCredentialListMappingReader(final String pathaccountSid, final String pathdomainSid) { + this.pathaccountSid = pathaccountSid; + this.pathdomainSid = pathdomainSid; } - public AuthRegistrationsCredentialListMappingReader setPageSize( - final Long pageSize - ) { + + public AuthRegistrationsCredentialListMappingReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override - public ResourceSet read( - final TwilioRestClient client - ) { + public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } - public Page firstPage( - final TwilioRestClient client - ) { - String path = - "/2010-04-01/Accounts/{AccountSid}/SIP/Domains/{DomainSid}/Auth/Registrations/CredentialListMappings.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = - path.replace( - "{" + "DomainSid" + "}", - this.pathDomainSid.toString() - ); + public Page firstPage(final TwilioRestClient client) { + + String path = "/2010-04-01/Accounts/{AccountSid}/SIP/Domains/{DomainSid}/Auth/Registrations/CredentialListMappings.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "DomainSid" + "}", this.pathdomainSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.API.toString(), - path + HttpMethod.GET, + Domains.API.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "AuthRegistrationsCredentialListMapping read failed: Unable to connect to server" - ); + throw new ApiConnectionException("AuthRegistrationsCredentialListMapping read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "contents", - response.getContent(), - AuthRegistrationsCredentialListMapping.class, - client.getObjectMapper() - ); + "contents", + response.getContent(), + AuthRegistrationsCredentialListMapping.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.API.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.API.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/sip/ipaccesscontrollist/IpAddress.java b/src/main/java/com/twilio/rest/api/v2010/account/sip/ipaccesscontrollist/IpAddress.java index 4f7db3b4ad..9f977708d7 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/sip/ipaccesscontrollist/IpAddress.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/sip/ipaccesscontrollist/IpAddress.java @@ -18,132 +18,104 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.time.ZonedDateTime; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class IpAddress extends Resource { - private static final long serialVersionUID = 125766891149812L; - public static IpAddressCreator creator( - final String pathIpAccessControlListSid, - final String friendlyName, - final String ipAddress - ) { + public static IpAddressCreator creator(final String pathipAccessControlListSid, final String friendlyName, final String ipAddress) { return new IpAddressCreator( - pathIpAccessControlListSid, - friendlyName, - ipAddress + pathipAccessControlListSid, friendlyName, ipAddress ); } - public static IpAddressCreator creator( - final String pathAccountSid, - final String pathIpAccessControlListSid, - final String friendlyName, - final String ipAddress - ) { + + public static IpAddressCreator creator(final String pathaccountSid, final String pathipAccessControlListSid, final String friendlyName, final String ipAddress) { return new IpAddressCreator( - pathAccountSid, - pathIpAccessControlListSid, - friendlyName, - ipAddress + pathaccountSid, pathipAccessControlListSid, friendlyName, ipAddress ); } - public static IpAddressDeleter deleter( - final String pathIpAccessControlListSid, - final String pathSid - ) { - return new IpAddressDeleter(pathIpAccessControlListSid, pathSid); + + public static IpAddressDeleter deleter(final String pathipAccessControlListSid, final String pathsid) { + return new IpAddressDeleter( + pathipAccessControlListSid, pathsid + ); } - public static IpAddressDeleter deleter( - final String pathAccountSid, - final String pathIpAccessControlListSid, - final String pathSid - ) { + + public static IpAddressDeleter deleter(final String pathaccountSid, final String pathipAccessControlListSid, final String pathsid) { return new IpAddressDeleter( - pathAccountSid, - pathIpAccessControlListSid, - pathSid + pathaccountSid, pathipAccessControlListSid, pathsid ); } - public static IpAddressFetcher fetcher( - final String pathIpAccessControlListSid, - final String pathSid - ) { - return new IpAddressFetcher(pathIpAccessControlListSid, pathSid); + + public static IpAddressFetcher fetcher(final String pathipAccessControlListSid, final String pathsid) { + return new IpAddressFetcher( + pathipAccessControlListSid, pathsid + ); } - public static IpAddressFetcher fetcher( - final String pathAccountSid, - final String pathIpAccessControlListSid, - final String pathSid - ) { + + public static IpAddressFetcher fetcher(final String pathaccountSid, final String pathipAccessControlListSid, final String pathsid) { return new IpAddressFetcher( - pathAccountSid, - pathIpAccessControlListSid, - pathSid + pathaccountSid, pathipAccessControlListSid, pathsid ); } - public static IpAddressReader reader( - final String pathIpAccessControlListSid - ) { - return new IpAddressReader(pathIpAccessControlListSid); + + public static IpAddressReader reader(final String pathipAccessControlListSid) { + return new IpAddressReader( + pathipAccessControlListSid + ); } - public static IpAddressReader reader( - final String pathAccountSid, - final String pathIpAccessControlListSid - ) { - return new IpAddressReader(pathAccountSid, pathIpAccessControlListSid); + + public static IpAddressReader reader(final String pathaccountSid, final String pathipAccessControlListSid) { + return new IpAddressReader( + pathaccountSid, pathipAccessControlListSid + ); } - public static IpAddressUpdater updater( - final String pathIpAccessControlListSid, - final String pathSid - ) { - return new IpAddressUpdater(pathIpAccessControlListSid, pathSid); + + public static IpAddressUpdater updater(final String pathipAccessControlListSid, final String pathsid) { + return new IpAddressUpdater( + pathipAccessControlListSid, pathsid + ); } - public static IpAddressUpdater updater( - final String pathAccountSid, - final String pathIpAccessControlListSid, - final String pathSid - ) { + + public static IpAddressUpdater updater(final String pathaccountSid, final String pathipAccessControlListSid, final String pathsid) { return new IpAddressUpdater( - pathAccountSid, - pathIpAccessControlListSid, - pathSid + pathaccountSid, pathipAccessControlListSid, pathsid ); } + /** * Converts a JSON String into a IpAddress object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return IpAddress object represented by the provided JSON */ - public static IpAddress fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static IpAddress fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, IpAddress.class); @@ -158,14 +130,11 @@ public static IpAddress fromJson( * Converts a JSON InputStream into a IpAddress object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return IpAddress object represented by the provided JSON */ - public static IpAddress fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static IpAddress fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, IpAddress.class); @@ -176,77 +145,63 @@ public static IpAddress fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String friendlyName; - private final String ipAddress; + @Getter private final Integer cidrPrefixLength; - private final String ipAccessControlListSid; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; + @Getter + private final String friendlyName; + @Getter + private final String ipAccessControlListSid; + @Getter + private final String ipAddress; + @Getter + private final String sid; + @Getter private final String uri; @JsonCreator private IpAddress( - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("ip_address") final String ipAddress, - @JsonProperty("cidr_prefix_length") final Integer cidrPrefixLength, - @JsonProperty( - "ip_access_control_list_sid" - ) final String ipAccessControlListSid, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("uri") final String uri + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("cidr_prefix_length") final Integer cidrPrefixLength, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.RFC2822Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.RFC2822Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("ip_access_control_list_sid") final String ipAccessControlListSid, + @JsonProperty("ip_address") final String ipAddress, + @JsonProperty("sid") final String sid, + @JsonProperty("uri") final String uri ) { - this.sid = sid; this.accountSid = accountSid; - this.friendlyName = friendlyName; - this.ipAddress = ipAddress; this.cidrPrefixLength = cidrPrefixLength; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; + this.friendlyName = friendlyName; this.ipAccessControlListSid = ipAccessControlListSid; - this.dateCreated = DateConverter.rfc2822DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.rfc2822DateTimeFromString(dateUpdated); + this.ipAddress = ipAddress; + this.sid = sid; this.uri = uri; } - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final String getIpAddress() { - return this.ipAddress; - } - - public final Integer getCidrPrefixLength() { - return this.cidrPrefixLength; - } - - public final String getIpAccessControlListSid() { - return this.ipAccessControlListSid; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final String getUri() { - return this.uri; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -258,35 +213,34 @@ public boolean equals(final Object o) { } IpAddress other = (IpAddress) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(ipAddress, other.ipAddress) && - Objects.equals(cidrPrefixLength, other.cidrPrefixLength) && - Objects.equals( - ipAccessControlListSid, - other.ipAccessControlListSid - ) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(uri, other.uri) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(cidrPrefixLength, other.cidrPrefixLength) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(ipAccessControlListSid, other.ipAccessControlListSid) && + Objects.equals(ipAddress, other.ipAddress) && + Objects.equals(sid, other.sid) && + Objects.equals(uri, other.uri) ); } @Override public int hashCode() { return Objects.hash( - sid, - accountSid, - friendlyName, - ipAddress, - cidrPrefixLength, - ipAccessControlListSid, - dateCreated, - dateUpdated, - uri + accountSid, + cidrPrefixLength, + dateCreated, + dateUpdated, + friendlyName, + ipAccessControlListSid, + ipAddress, + sid, + uri ); } + + } + diff --git a/src/main/java/com/twilio/rest/api/v2010/account/sip/ipaccesscontrollist/IpAddressCreator.java b/src/main/java/com/twilio/rest/api/v2010/account/sip/ipaccesscontrollist/IpAddressCreator.java index 5c64f9c982..fe2b60443b 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/sip/ipaccesscontrollist/IpAddressCreator.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/sip/ipaccesscontrollist/IpAddressCreator.java @@ -14,8 +14,11 @@ package com.twilio.rest.api.v2010.account.sip.ipaccesscontrollist; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,121 +30,96 @@ public class IpAddressCreator extends Creator { - private String pathIpAccessControlListSid; + private String pathaccountSid; + private String pathipAccessControlListSid; private String friendlyName; private String ipAddress; - private String pathAccountSid; private Integer cidrPrefixLength; - public IpAddressCreator( - final String pathIpAccessControlListSid, - final String friendlyName, - final String ipAddress - ) { - this.pathIpAccessControlListSid = pathIpAccessControlListSid; + public IpAddressCreator(final String pathipAccessControlListSid, final String friendlyName, final String ipAddress) { + this.pathipAccessControlListSid = pathipAccessControlListSid; this.friendlyName = friendlyName; this.ipAddress = ipAddress; } - public IpAddressCreator( - final String pathAccountSid, - final String pathIpAccessControlListSid, - final String friendlyName, - final String ipAddress - ) { - this.pathAccountSid = pathAccountSid; - this.pathIpAccessControlListSid = pathIpAccessControlListSid; + public IpAddressCreator(final String pathaccountSid, final String pathipAccessControlListSid, final String friendlyName, final String ipAddress) { + this.pathaccountSid = pathaccountSid; + this.pathipAccessControlListSid = pathipAccessControlListSid; this.friendlyName = friendlyName; this.ipAddress = ipAddress; } + public IpAddressCreator setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + public IpAddressCreator setIpAddress(final String ipAddress) { this.ipAddress = ipAddress; return this; } - public IpAddressCreator setCidrPrefixLength( - final Integer cidrPrefixLength - ) { + + public IpAddressCreator setCidrPrefixLength(final Integer cidrPrefixLength) { this.cidrPrefixLength = cidrPrefixLength; return this; } + @Override public IpAddress create(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/SIP/IpAccessControlLists/{IpAccessControlListSid}/IpAddresses.json"; - - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = - path.replace( - "{" + "IpAccessControlListSid" + "}", - this.pathIpAccessControlListSid.toString() - ); - path = - path.replace( - "{" + "FriendlyName" + "}", - this.friendlyName.toString() - ); - path = path.replace("{" + "IpAddress" + "}", this.ipAddress.toString()); + + String path = "/2010-04-01/Accounts/{AccountSid}/SIP/IpAccessControlLists/{IpAccessControlListSid}/IpAddresses.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "IpAccessControlListSid" + "}", this.pathipAccessControlListSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.API.toString(), - path + HttpMethod.POST, + Domains.API.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "IpAddress creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("IpAddress creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return IpAddress.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return IpAddress.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + if (ipAddress != null) { - request.addPostParam("IpAddress", ipAddress); + Serializer.toString(request, "IpAddress", ipAddress, ParameterType.URLENCODED); } + + if (cidrPrefixLength != null) { - request.addPostParam( - "CidrPrefixLength", - cidrPrefixLength.toString() - ); + Serializer.toString(request, "CidrPrefixLength", cidrPrefixLength, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/sip/ipaccesscontrollist/IpAddressDeleter.java b/src/main/java/com/twilio/rest/api/v2010/account/sip/ipaccesscontrollist/IpAddressDeleter.java index 837d3ba35c..054cdf7498 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/sip/ipaccesscontrollist/IpAddressDeleter.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/sip/ipaccesscontrollist/IpAddressDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.api.v2010.account.sip.ipaccesscontrollist; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,71 +26,50 @@ public class IpAddressDeleter extends Deleter { - private String pathIpAccessControlListSid; - private String pathSid; - private String pathAccountSid; + private String pathaccountSid; + private String pathipAccessControlListSid; + private String pathsid; - public IpAddressDeleter( - final String pathIpAccessControlListSid, - final String pathSid - ) { - this.pathIpAccessControlListSid = pathIpAccessControlListSid; - this.pathSid = pathSid; + public IpAddressDeleter(final String pathipAccessControlListSid, final String pathsid) { + this.pathipAccessControlListSid = pathipAccessControlListSid; + this.pathsid = pathsid; } - public IpAddressDeleter( - final String pathAccountSid, - final String pathIpAccessControlListSid, - final String pathSid - ) { - this.pathAccountSid = pathAccountSid; - this.pathIpAccessControlListSid = pathIpAccessControlListSid; - this.pathSid = pathSid; + public IpAddressDeleter(final String pathaccountSid, final String pathipAccessControlListSid, final String pathsid) { + this.pathaccountSid = pathaccountSid; + this.pathipAccessControlListSid = pathipAccessControlListSid; + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/SIP/IpAccessControlLists/{IpAccessControlListSid}/IpAddresses/{Sid}.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = - path.replace( - "{" + "IpAccessControlListSid" + "}", - this.pathIpAccessControlListSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/2010-04-01/Accounts/{AccountSid}/SIP/IpAccessControlLists/{IpAccessControlListSid}/IpAddresses/{Sid}.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "IpAccessControlListSid" + "}", this.pathipAccessControlListSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.API.toString(), - path + HttpMethod.DELETE, + Domains.API.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "IpAddress delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("IpAddress delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/sip/ipaccesscontrollist/IpAddressFetcher.java b/src/main/java/com/twilio/rest/api/v2010/account/sip/ipaccesscontrollist/IpAddressFetcher.java index 2f2cdcd6d0..761330cb4c 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/sip/ipaccesscontrollist/IpAddressFetcher.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/sip/ipaccesscontrollist/IpAddressFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.api.v2010.account.sip.ipaccesscontrollist; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,78 +26,53 @@ public class IpAddressFetcher extends Fetcher { - private String pathIpAccessControlListSid; - private String pathSid; - private String pathAccountSid; + private String pathaccountSid; + private String pathipAccessControlListSid; + private String pathsid; - public IpAddressFetcher( - final String pathIpAccessControlListSid, - final String pathSid - ) { - this.pathIpAccessControlListSid = pathIpAccessControlListSid; - this.pathSid = pathSid; + public IpAddressFetcher(final String pathipAccessControlListSid, final String pathsid) { + this.pathipAccessControlListSid = pathipAccessControlListSid; + this.pathsid = pathsid; } - public IpAddressFetcher( - final String pathAccountSid, - final String pathIpAccessControlListSid, - final String pathSid - ) { - this.pathAccountSid = pathAccountSid; - this.pathIpAccessControlListSid = pathIpAccessControlListSid; - this.pathSid = pathSid; + public IpAddressFetcher(final String pathaccountSid, final String pathipAccessControlListSid, final String pathsid) { + this.pathaccountSid = pathaccountSid; + this.pathipAccessControlListSid = pathipAccessControlListSid; + this.pathsid = pathsid; } + @Override public IpAddress fetch(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/SIP/IpAccessControlLists/{IpAccessControlListSid}/IpAddresses/{Sid}.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = - path.replace( - "{" + "IpAccessControlListSid" + "}", - this.pathIpAccessControlListSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/2010-04-01/Accounts/{AccountSid}/SIP/IpAccessControlLists/{IpAccessControlListSid}/IpAddresses/{Sid}.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "IpAccessControlListSid" + "}", this.pathipAccessControlListSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.API.toString(), - path + HttpMethod.GET, + Domains.API.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "IpAddress fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("IpAddress fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return IpAddress.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return IpAddress.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/sip/ipaccesscontrollist/IpAddressReader.java b/src/main/java/com/twilio/rest/api/v2010/account/sip/ipaccesscontrollist/IpAddressReader.java index e16beeec7f..3ee24567e2 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/sip/ipaccesscontrollist/IpAddressReader.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/sip/ipaccesscontrollist/IpAddressReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,134 +30,96 @@ public class IpAddressReader extends Reader { - private String pathIpAccessControlListSid; - private String pathAccountSid; + private String pathaccountSid; + private String pathipAccessControlListSid; private Long pageSize; - public IpAddressReader(final String pathIpAccessControlListSid) { - this.pathIpAccessControlListSid = pathIpAccessControlListSid; + public IpAddressReader(final String pathipAccessControlListSid) { + this.pathipAccessControlListSid = pathipAccessControlListSid; } - public IpAddressReader( - final String pathAccountSid, - final String pathIpAccessControlListSid - ) { - this.pathAccountSid = pathAccountSid; - this.pathIpAccessControlListSid = pathIpAccessControlListSid; + public IpAddressReader(final String pathaccountSid, final String pathipAccessControlListSid) { + this.pathaccountSid = pathaccountSid; + this.pathipAccessControlListSid = pathipAccessControlListSid; } + public IpAddressReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/SIP/IpAccessControlLists/{IpAccessControlListSid}/IpAddresses.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = - path.replace( - "{" + "IpAccessControlListSid" + "}", - this.pathIpAccessControlListSid.toString() - ); + + String path = "/2010-04-01/Accounts/{AccountSid}/SIP/IpAccessControlLists/{IpAccessControlListSid}/IpAddresses.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "IpAccessControlListSid" + "}", this.pathipAccessControlListSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.API.toString(), - path + HttpMethod.GET, + Domains.API.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "IpAddress read failed: Unable to connect to server" - ); + throw new ApiConnectionException("IpAddress read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "ip_addresses", - response.getContent(), - IpAddress.class, - client.getObjectMapper() - ); + "ip_addresses", + response.getContent(), + IpAddress.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.API.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.API.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/sip/ipaccesscontrollist/IpAddressUpdater.java b/src/main/java/com/twilio/rest/api/v2010/account/sip/ipaccesscontrollist/IpAddressUpdater.java index ef9db07752..56aaacd6fb 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/sip/ipaccesscontrollist/IpAddressUpdater.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/sip/ipaccesscontrollist/IpAddressUpdater.java @@ -16,6 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -26,114 +28,96 @@ import com.twilio.rest.Domains; public class IpAddressUpdater extends Updater { - - private String pathIpAccessControlListSid; - private String pathSid; - private String pathAccountSid; + private String pathaccountSid; + private String pathipAccessControlListSid; + private String pathsid; private String ipAddress; private String friendlyName; private Integer cidrPrefixLength; - public IpAddressUpdater( - final String pathIpAccessControlListSid, - final String pathSid - ) { - this.pathIpAccessControlListSid = pathIpAccessControlListSid; - this.pathSid = pathSid; + public IpAddressUpdater(final String pathipAccessControlListSid, final String pathsid) { + this.pathipAccessControlListSid = pathipAccessControlListSid; + this.pathsid = pathsid; } - public IpAddressUpdater( - final String pathAccountSid, - final String pathIpAccessControlListSid, - final String pathSid - ) { - this.pathAccountSid = pathAccountSid; - this.pathIpAccessControlListSid = pathIpAccessControlListSid; - this.pathSid = pathSid; + public IpAddressUpdater(final String pathaccountSid, final String pathipAccessControlListSid, final String pathsid) { + this.pathaccountSid = pathaccountSid; + this.pathipAccessControlListSid = pathipAccessControlListSid; + this.pathsid = pathsid; } + public IpAddressUpdater setIpAddress(final String ipAddress) { this.ipAddress = ipAddress; return this; } + public IpAddressUpdater setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } - public IpAddressUpdater setCidrPrefixLength( - final Integer cidrPrefixLength - ) { + + public IpAddressUpdater setCidrPrefixLength(final Integer cidrPrefixLength) { this.cidrPrefixLength = cidrPrefixLength; return this; } + @Override public IpAddress update(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/SIP/IpAccessControlLists/{IpAccessControlListSid}/IpAddresses/{Sid}.json"; - - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = - path.replace( - "{" + "IpAccessControlListSid" + "}", - this.pathIpAccessControlListSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + + String path = "/2010-04-01/Accounts/{AccountSid}/SIP/IpAccessControlLists/{IpAccessControlListSid}/IpAddresses/{Sid}.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "IpAccessControlListSid" + "}", this.pathipAccessControlListSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.API.toString(), - path + HttpMethod.POST, + Domains.API.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "IpAddress update failed: Unable to connect to server" - ); + throw new ApiConnectionException("IpAddress update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return IpAddress.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return IpAddress.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (ipAddress != null) { - request.addPostParam("IpAddress", ipAddress); + Serializer.toString(request, "IpAddress", ipAddress, ParameterType.URLENCODED); } + + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + if (cidrPrefixLength != null) { - request.addPostParam( - "CidrPrefixLength", - cidrPrefixLength.toString() - ); + Serializer.toString(request, "CidrPrefixLength", cidrPrefixLength, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/usage/Record.java b/src/main/java/com/twilio/rest/api/v2010/account/usage/Record.java index 26d3c3d8bf..5247ee15ad 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/usage/Record.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/usage/Record.java @@ -18,50 +18,51 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.CurrencyDeserializer; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.math.BigDecimal; import java.time.LocalDate; import java.util.Currency; import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Record extends Resource { - private static final long serialVersionUID = 158026917970511L; public static RecordReader reader() { - return new RecordReader(); + return new RecordReader( + + ); } - public static RecordReader reader(final String pathAccountSid) { - return new RecordReader(pathAccountSid); + + public static RecordReader reader(final String pathaccountSid) { + return new RecordReader( + pathaccountSid + ); } + /** * Converts a JSON String into a Record object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Record object represented by the provided JSON */ - public static Record fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Record fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Record.class); @@ -76,14 +77,11 @@ public static Record fromJson( * Converts a JSON InputStream into a Record object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Record object represented by the provided JSON */ - public static Record fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Record fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Record.class); @@ -94,44 +92,70 @@ public static Record fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; + @Getter private final String apiVersion; + @Getter private final String asOf; + @Getter private final String category; + @Getter private final String count; + @Getter private final String countUnit; + @Getter private final String description; + @Getter private final LocalDate endDate; + @Getter private final BigDecimal price; + @Getter private final Currency priceUnit; + @Getter private final LocalDate startDate; + @Getter private final Map subresourceUris; + @Getter private final String uri; + @Getter private final String usage; + @Getter private final String usageUnit; @JsonCreator private Record( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("api_version") final String apiVersion, - @JsonProperty("as_of") final String asOf, - @JsonProperty("category") final String category, - @JsonProperty("count") final String count, - @JsonProperty("count_unit") final String countUnit, - @JsonProperty("description") final String description, - @JsonProperty("end_date") final String endDate, - @JsonProperty("price") final BigDecimal price, - @JsonProperty("price_unit") @JsonDeserialize( - using = com.twilio.converter.CurrencyDeserializer.class - ) final Currency priceUnit, - @JsonProperty("start_date") final String startDate, - @JsonProperty("subresource_uris") final Map< - String, - String - > subresourceUris, - @JsonProperty("uri") final String uri, - @JsonProperty("usage") final String usage, - @JsonProperty("usage_unit") final String usageUnit + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("api_version") final String apiVersion, + @JsonProperty("as_of") final String asOf, + @JsonProperty("category") final String category, + @JsonProperty("count") final String count, + @JsonProperty("count_unit") final String countUnit, + @JsonProperty("description") final String description, + @JsonProperty("end_date") + @JsonDeserialize(using = com.twilio.converter.LocalDateDeserializer.class) final LocalDate endDate, + @JsonProperty("price") final BigDecimal price, + @JsonProperty("price_unit") + @JsonDeserialize(using = com.twilio.converter.CurrencyDeserializer.class) final Currency priceUnit, + @JsonProperty("start_date") + @JsonDeserialize(using = com.twilio.converter.LocalDateDeserializer.class) final LocalDate startDate, + @JsonProperty("subresource_uris") final Map subresourceUris, + @JsonProperty("uri") final String uri, + @JsonProperty("usage") final String usage, + @JsonProperty("usage_unit") final String usageUnit ) { this.accountSid = accountSid; this.apiVersion = apiVersion; @@ -140,76 +164,16 @@ private Record( this.count = count; this.countUnit = countUnit; this.description = description; - this.endDate = DateConverter.localDateFromString(endDate); + this.endDate = endDate; this.price = price; this.priceUnit = priceUnit; - this.startDate = DateConverter.localDateFromString(startDate); + this.startDate = startDate; this.subresourceUris = subresourceUris; this.uri = uri; this.usage = usage; this.usageUnit = usageUnit; } - public final String getAccountSid() { - return this.accountSid; - } - - public final String getApiVersion() { - return this.apiVersion; - } - - public final String getAsOf() { - return this.asOf; - } - - public final String getCategory() { - return this.category; - } - - public final String getCount() { - return this.count; - } - - public final String getCountUnit() { - return this.countUnit; - } - - public final String getDescription() { - return this.description; - } - - public final LocalDate getEndDate() { - return this.endDate; - } - - public final BigDecimal getPrice() { - return this.price; - } - - public final Currency getPriceUnit() { - return this.priceUnit; - } - - public final LocalDate getStartDate() { - return this.startDate; - } - - public final Map getSubresourceUris() { - return this.subresourceUris; - } - - public final String getUri() { - return this.uri; - } - - public final String getUsage() { - return this.usage; - } - - public final String getUsageUnit() { - return this.usageUnit; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -221,44 +185,46 @@ public boolean equals(final Object o) { } Record other = (Record) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(apiVersion, other.apiVersion) && - Objects.equals(asOf, other.asOf) && - Objects.equals(category, other.category) && - Objects.equals(count, other.count) && - Objects.equals(countUnit, other.countUnit) && - Objects.equals(description, other.description) && - Objects.equals(endDate, other.endDate) && - Objects.equals(price, other.price) && - Objects.equals(priceUnit, other.priceUnit) && - Objects.equals(startDate, other.startDate) && - Objects.equals(subresourceUris, other.subresourceUris) && - Objects.equals(uri, other.uri) && - Objects.equals(usage, other.usage) && - Objects.equals(usageUnit, other.usageUnit) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(apiVersion, other.apiVersion) && + Objects.equals(asOf, other.asOf) && + Objects.equals(category, other.category) && + Objects.equals(count, other.count) && + Objects.equals(countUnit, other.countUnit) && + Objects.equals(description, other.description) && + Objects.equals(endDate, other.endDate) && + Objects.equals(price, other.price) && + Objects.equals(priceUnit, other.priceUnit) && + Objects.equals(startDate, other.startDate) && + Objects.equals(subresourceUris, other.subresourceUris) && + Objects.equals(uri, other.uri) && + Objects.equals(usage, other.usage) && + Objects.equals(usageUnit, other.usageUnit) ); } @Override public int hashCode() { return Objects.hash( - accountSid, - apiVersion, - asOf, - category, - count, - countUnit, - description, - endDate, - price, - priceUnit, - startDate, - subresourceUris, - uri, - usage, - usageUnit + accountSid, + apiVersion, + asOf, + category, + count, + countUnit, + description, + endDate, + price, + priceUnit, + startDate, + subresourceUris, + uri, + usage, + usageUnit ); } + + } + diff --git a/src/main/java/com/twilio/rest/api/v2010/account/usage/RecordReader.java b/src/main/java/com/twilio/rest/api/v2010/account/usage/RecordReader.java index 69dea74697..38ef6117c1 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/usage/RecordReader.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/usage/RecordReader.java @@ -17,8 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; -import com.twilio.converter.DateConverter; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,174 +27,145 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.time.LocalDate; public class RecordReader extends Reader { - private String pathAccountSid; + private String pathaccountSid; private String category; private LocalDate startDate; private LocalDate endDate; private Boolean includeSubaccounts; private Long pageSize; - public RecordReader() {} + public RecordReader() { + } - public RecordReader(final String pathAccountSid) { - this.pathAccountSid = pathAccountSid; + public RecordReader(final String pathaccountSid) { + this.pathaccountSid = pathaccountSid; } + public RecordReader setCategory(final String category) { this.category = category; return this; } + public RecordReader setStartDate(final LocalDate startDate) { this.startDate = startDate; return this; } + public RecordReader setEndDate(final LocalDate endDate) { this.endDate = endDate; return this; } - public RecordReader setIncludeSubaccounts( - final Boolean includeSubaccounts - ) { + + public RecordReader setIncludeSubaccounts(final Boolean includeSubaccounts) { this.includeSubaccounts = includeSubaccounts; return this; } + public RecordReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/2010-04-01/Accounts/{AccountSid}/Usage/Records.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.API.toString(), - path + HttpMethod.GET, + Domains.API.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Record read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Record read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "usage_records", - response.getContent(), - Record.class, - client.getObjectMapper() - ); + "usage_records", + response.getContent(), + Record.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.API.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.API.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (category != null) { - request.addQueryParam("Category", category); + Serializer.toString(request, "Category", category, ParameterType.QUERY); } + + if (startDate != null) { - request.addQueryParam( - "StartDate", - DateConverter.dateStringFromLocalDate(startDate) - ); + Serializer.toString(request, "StartDate", startDate, ParameterType.QUERY); } + if (endDate != null) { - request.addQueryParam( - "EndDate", - DateConverter.dateStringFromLocalDate(endDate) - ); + Serializer.toString(request, "EndDate", endDate, ParameterType.QUERY); } + if (includeSubaccounts != null) { - request.addQueryParam( - "IncludeSubaccounts", - includeSubaccounts.toString() - ); + Serializer.toString(request, "IncludeSubaccounts", includeSubaccounts, ParameterType.QUERY); } + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/usage/Trigger.java b/src/main/java/com/twilio/rest/api/v2010/account/usage/Trigger.java index 9e548a35d4..fa769c322a 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/usage/Trigger.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/usage/Trigger.java @@ -18,102 +18,151 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.http.HttpMethod; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Trigger extends Resource { - private static final long serialVersionUID = 156058914793532L; - public static TriggerCreator creator( - final URI callbackUrl, - final String triggerValue, - final String usageCategory - ) { - return new TriggerCreator(callbackUrl, triggerValue, usageCategory); + public static TriggerCreator creator(final URI callbackUrl, final String triggerValue, final String usageCategory) { + return new TriggerCreator( + callbackUrl, triggerValue, usageCategory + ); } - public static TriggerCreator creator( - final String pathAccountSid, - final URI callbackUrl, - final String triggerValue, - final String usageCategory - ) { + + public static TriggerCreator creator(final String pathaccountSid, final URI callbackUrl, final String triggerValue, final String usageCategory) { return new TriggerCreator( - pathAccountSid, - callbackUrl, - triggerValue, - usageCategory + pathaccountSid, callbackUrl, triggerValue, usageCategory ); } - public static TriggerDeleter deleter(final String pathSid) { - return new TriggerDeleter(pathSid); + + public static TriggerDeleter deleter(final String pathsid) { + return new TriggerDeleter( + pathsid + ); } - public static TriggerDeleter deleter( - final String pathAccountSid, - final String pathSid - ) { - return new TriggerDeleter(pathAccountSid, pathSid); + + public static TriggerDeleter deleter(final String pathaccountSid, final String pathsid) { + return new TriggerDeleter( + pathaccountSid, pathsid + ); } - public static TriggerFetcher fetcher(final String pathSid) { - return new TriggerFetcher(pathSid); + + public static TriggerFetcher fetcher(final String pathsid) { + return new TriggerFetcher( + pathsid + ); } - public static TriggerFetcher fetcher( - final String pathAccountSid, - final String pathSid - ) { - return new TriggerFetcher(pathAccountSid, pathSid); + + public static TriggerFetcher fetcher(final String pathaccountSid, final String pathsid) { + return new TriggerFetcher( + pathaccountSid, pathsid + ); } + public static TriggerReader reader() { - return new TriggerReader(); + return new TriggerReader( + + ); } - public static TriggerReader reader(final String pathAccountSid) { - return new TriggerReader(pathAccountSid); + + public static TriggerReader reader(final String pathaccountSid) { + return new TriggerReader( + pathaccountSid + ); } - public static TriggerUpdater updater(final String pathSid) { - return new TriggerUpdater(pathSid); + + public static TriggerUpdater updater(final String pathsid) { + return new TriggerUpdater( + pathsid + ); } - public static TriggerUpdater updater( - final String pathAccountSid, - final String pathSid - ) { - return new TriggerUpdater(pathAccountSid, pathSid); + + public static TriggerUpdater updater(final String pathaccountSid, final String pathsid) { + return new TriggerUpdater( + pathaccountSid, pathsid + ); + } + + + public enum Recurring { + DAILY("daily"), + MONTHLY("monthly"), + YEARLY("yearly"), + ALLTIME("alltime"); + + private final String value; + + private Recurring(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static Recurring forValue(final String value) { + return Promoter.enumFromString(value, Recurring.values()); + } + } + + public enum TriggerField { + COUNT("count"), + USAGE("usage"), + PRICE("price"); + + private final String value; + + private TriggerField(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static TriggerField forValue(final String value) { + return Promoter.enumFromString(value, TriggerField.values()); + } } + /** * Converts a JSON String into a Trigger object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Trigger object represented by the provided JSON */ - public static Trigger fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Trigger fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Trigger.class); @@ -128,14 +177,11 @@ public static Trigger fromJson( * Converts a JSON InputStream into a Trigger object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Trigger object represented by the provided JSON */ - public static Trigger fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Trigger fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Trigger.class); @@ -146,50 +192,82 @@ public static Trigger fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; + @Getter private final String apiVersion; + @Getter private final HttpMethod callbackMethod; + @Getter private final URI callbackUrl; + @Getter private final String currentValue; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateFired; + @Getter private final ZonedDateTime dateUpdated; + @Getter private final String friendlyName; + @Getter private final Trigger.Recurring recurring; + @Getter private final String sid; + @Getter private final Trigger.TriggerField triggerBy; + @Getter private final String triggerValue; + @Getter private final String uri; + @Getter private final String usageCategory; + @Getter private final String usageRecordUri; @JsonCreator private Trigger( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("api_version") final String apiVersion, - @JsonProperty("callback_method") final HttpMethod callbackMethod, - @JsonProperty("callback_url") final URI callbackUrl, - @JsonProperty("current_value") final String currentValue, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_fired") final String dateFired, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("recurring") final Trigger.Recurring recurring, - @JsonProperty("sid") final String sid, - @JsonProperty("trigger_by") final Trigger.TriggerField triggerBy, - @JsonProperty("trigger_value") final String triggerValue, - @JsonProperty("uri") final String uri, - @JsonProperty("usage_category") final String usageCategory, - @JsonProperty("usage_record_uri") final String usageRecordUri + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("api_version") final String apiVersion, + @JsonProperty("callback_method") final HttpMethod callbackMethod, + @JsonProperty("callback_url") final URI callbackUrl, + @JsonProperty("current_value") final String currentValue, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.RFC2822Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_fired") + @JsonDeserialize(using = com.twilio.converter.RFC2822Deserializer.class) final ZonedDateTime dateFired, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.RFC2822Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("recurring") final Trigger.Recurring recurring, + @JsonProperty("sid") final String sid, + @JsonProperty("trigger_by") final Trigger.TriggerField triggerBy, + @JsonProperty("trigger_value") final String triggerValue, + @JsonProperty("uri") final String uri, + @JsonProperty("usage_category") final String usageCategory, + @JsonProperty("usage_record_uri") final String usageRecordUri ) { this.accountSid = accountSid; this.apiVersion = apiVersion; this.callbackMethod = callbackMethod; this.callbackUrl = callbackUrl; this.currentValue = currentValue; - this.dateCreated = DateConverter.rfc2822DateTimeFromString(dateCreated); - this.dateFired = DateConverter.rfc2822DateTimeFromString(dateFired); - this.dateUpdated = DateConverter.rfc2822DateTimeFromString(dateUpdated); + this.dateCreated = dateCreated; + this.dateFired = dateFired; + this.dateUpdated = dateUpdated; this.friendlyName = friendlyName; this.recurring = recurring; this.sid = sid; @@ -200,70 +278,6 @@ private Trigger( this.usageRecordUri = usageRecordUri; } - public final String getAccountSid() { - return this.accountSid; - } - - public final String getApiVersion() { - return this.apiVersion; - } - - public final HttpMethod getCallbackMethod() { - return this.callbackMethod; - } - - public final URI getCallbackUrl() { - return this.callbackUrl; - } - - public final String getCurrentValue() { - return this.currentValue; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateFired() { - return this.dateFired; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final Trigger.Recurring getRecurring() { - return this.recurring; - } - - public final String getSid() { - return this.sid; - } - - public final Trigger.TriggerField getTriggerBy() { - return this.triggerBy; - } - - public final String getTriggerValue() { - return this.triggerValue; - } - - public final String getUri() { - return this.uri; - } - - public final String getUsageCategory() { - return this.usageCategory; - } - - public final String getUsageRecordUri() { - return this.usageRecordUri; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -275,89 +289,48 @@ public boolean equals(final Object o) { } Trigger other = (Trigger) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(apiVersion, other.apiVersion) && - Objects.equals(callbackMethod, other.callbackMethod) && - Objects.equals(callbackUrl, other.callbackUrl) && - Objects.equals(currentValue, other.currentValue) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateFired, other.dateFired) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(recurring, other.recurring) && - Objects.equals(sid, other.sid) && - Objects.equals(triggerBy, other.triggerBy) && - Objects.equals(triggerValue, other.triggerValue) && - Objects.equals(uri, other.uri) && - Objects.equals(usageCategory, other.usageCategory) && - Objects.equals(usageRecordUri, other.usageRecordUri) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(apiVersion, other.apiVersion) && + Objects.equals(callbackMethod, other.callbackMethod) && + Objects.equals(callbackUrl, other.callbackUrl) && + Objects.equals(currentValue, other.currentValue) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateFired, other.dateFired) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(recurring, other.recurring) && + Objects.equals(sid, other.sid) && + Objects.equals(triggerBy, other.triggerBy) && + Objects.equals(triggerValue, other.triggerValue) && + Objects.equals(uri, other.uri) && + Objects.equals(usageCategory, other.usageCategory) && + Objects.equals(usageRecordUri, other.usageRecordUri) ); } @Override public int hashCode() { return Objects.hash( - accountSid, - apiVersion, - callbackMethod, - callbackUrl, - currentValue, - dateCreated, - dateFired, - dateUpdated, - friendlyName, - recurring, - sid, - triggerBy, - triggerValue, - uri, - usageCategory, - usageRecordUri + accountSid, + apiVersion, + callbackMethod, + callbackUrl, + currentValue, + dateCreated, + dateFired, + dateUpdated, + friendlyName, + recurring, + sid, + triggerBy, + triggerValue, + uri, + usageCategory, + usageRecordUri ); } - public enum Recurring { - DAILY("daily"), - MONTHLY("monthly"), - YEARLY("yearly"), - ALLTIME("alltime"); - - private final String value; - - private Recurring(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static Recurring forValue(final String value) { - return Promoter.enumFromString(value, Recurring.values()); - } - } - - public enum TriggerField { - COUNT("count"), - USAGE("usage"), - PRICE("price"); - - private final String value; - - private TriggerField(final String value) { - this.value = value; - } - public String toString() { - return value; - } - - @JsonCreator - public static TriggerField forValue(final String value) { - return Promoter.enumFromString(value, TriggerField.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/api/v2010/account/usage/TriggerCreator.java b/src/main/java/com/twilio/rest/api/v2010/account/usage/TriggerCreator.java index 1609ff12a8..9263a90ecc 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/usage/TriggerCreator.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/usage/TriggerCreator.java @@ -14,9 +14,11 @@ package com.twilio.rest.api.v2010.account.usage; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; -import com.twilio.converter.Promoter; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,132 +27,104 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -import java.net.URI; + import java.net.URI; public class TriggerCreator extends Creator { + private String pathaccountSid; private URI callbackUrl; private String triggerValue; private String usageCategory; - private String pathAccountSid; private HttpMethod callbackMethod; private String friendlyName; private Trigger.Recurring recurring; private Trigger.TriggerField triggerBy; - public TriggerCreator( - final URI callbackUrl, - final String triggerValue, - final String usageCategory - ) { + public TriggerCreator(final URI callbackUrl, final String triggerValue, final String usageCategory) { this.callbackUrl = callbackUrl; this.triggerValue = triggerValue; this.usageCategory = usageCategory; } - public TriggerCreator( - final String pathAccountSid, - final URI callbackUrl, - final String triggerValue, - final String usageCategory - ) { - this.pathAccountSid = pathAccountSid; + public TriggerCreator(final String pathaccountSid, final URI callbackUrl, final String triggerValue, final String usageCategory) { + this.pathaccountSid = pathaccountSid; this.callbackUrl = callbackUrl; this.triggerValue = triggerValue; this.usageCategory = usageCategory; } + public TriggerCreator setCallbackUrl(final URI callbackUrl) { this.callbackUrl = callbackUrl; return this; } - public TriggerCreator setCallbackUrl(final String callbackUrl) { - return setCallbackUrl(Promoter.uriFromString(callbackUrl)); - } public TriggerCreator setTriggerValue(final String triggerValue) { this.triggerValue = triggerValue; return this; } + public TriggerCreator setUsageCategory(final String usageCategory) { this.usageCategory = usageCategory; return this; } + public TriggerCreator setCallbackMethod(final HttpMethod callbackMethod) { this.callbackMethod = callbackMethod; return this; } + public TriggerCreator setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + public TriggerCreator setRecurring(final Trigger.Recurring recurring) { this.recurring = recurring; return this; } + public TriggerCreator setTriggerBy(final Trigger.TriggerField triggerBy) { this.triggerBy = triggerBy; return this; } + @Override public Trigger create(final TwilioRestClient client) { + String path = "/2010-04-01/Accounts/{AccountSid}/Usage/Triggers.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = - path.replace( - "{" + "CallbackUrl" + "}", - this.callbackUrl.toString() - ); - path = - path.replace( - "{" + "TriggerValue" + "}", - this.triggerValue.toString() - ); - path = - path.replace( - "{" + "UsageCategory" + "}", - this.usageCategory.toString() - ); + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.API.toString(), - path + HttpMethod.POST, + Domains.API.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Trigger creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("Trigger creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -159,26 +133,41 @@ public Trigger create(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (callbackUrl != null) { - request.addPostParam("CallbackUrl", callbackUrl.toString()); + Serializer.toString(request, "CallbackUrl", callbackUrl, ParameterType.URLENCODED); } + + if (triggerValue != null) { - request.addPostParam("TriggerValue", triggerValue); + Serializer.toString(request, "TriggerValue", triggerValue, ParameterType.URLENCODED); } + + if (usageCategory != null) { - request.addPostParam("UsageCategory", usageCategory); + Serializer.toString(request, "UsageCategory", usageCategory, ParameterType.URLENCODED); } + + if (callbackMethod != null) { - request.addPostParam("CallbackMethod", callbackMethod.toString()); + Serializer.toString(request, "CallbackMethod", callbackMethod, ParameterType.URLENCODED); } + + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + if (recurring != null) { - request.addPostParam("Recurring", recurring.toString()); + Serializer.toString(request, "Recurring", recurring, ParameterType.URLENCODED); } + + if (triggerBy != null) { - request.addPostParam("TriggerBy", triggerBy.toString()); + Serializer.toString(request, "TriggerBy", triggerBy, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/usage/TriggerDeleter.java b/src/main/java/com/twilio/rest/api/v2010/account/usage/TriggerDeleter.java index f85f5a189e..02ea51a1d7 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/usage/TriggerDeleter.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/usage/TriggerDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.api.v2010.account.usage; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,56 +26,46 @@ public class TriggerDeleter extends Deleter { - private String pathSid; - private String pathAccountSid; + private String pathaccountSid; + private String pathsid; - public TriggerDeleter(final String pathSid) { - this.pathSid = pathSid; + public TriggerDeleter(final String pathsid) { + this.pathsid = pathsid; } - public TriggerDeleter(final String pathAccountSid, final String pathSid) { - this.pathAccountSid = pathAccountSid; - this.pathSid = pathSid; + public TriggerDeleter(final String pathaccountSid, final String pathsid) { + this.pathaccountSid = pathaccountSid; + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/Usage/Triggers/{Sid}.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/2010-04-01/Accounts/{AccountSid}/Usage/Triggers/{Sid}.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.API.toString(), - path + HttpMethod.DELETE, + Domains.API.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Trigger delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("Trigger delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/usage/TriggerFetcher.java b/src/main/java/com/twilio/rest/api/v2010/account/usage/TriggerFetcher.java index 51fd8cd720..ea99d45fe9 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/usage/TriggerFetcher.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/usage/TriggerFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.api.v2010.account.usage; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,60 +26,49 @@ public class TriggerFetcher extends Fetcher { - private String pathSid; - private String pathAccountSid; + private String pathaccountSid; + private String pathsid; - public TriggerFetcher(final String pathSid) { - this.pathSid = pathSid; + public TriggerFetcher(final String pathsid) { + this.pathsid = pathsid; } - public TriggerFetcher(final String pathAccountSid, final String pathSid) { - this.pathAccountSid = pathAccountSid; - this.pathSid = pathSid; + public TriggerFetcher(final String pathaccountSid, final String pathsid) { + this.pathaccountSid = pathaccountSid; + this.pathsid = pathsid; } + @Override public Trigger fetch(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/Usage/Triggers/{Sid}.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/2010-04-01/Accounts/{AccountSid}/Usage/Triggers/{Sid}.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.API.toString(), - path + HttpMethod.GET, + Domains.API.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Trigger fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Trigger fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Trigger.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/usage/TriggerReader.java b/src/main/java/com/twilio/rest/api/v2010/account/usage/TriggerReader.java index 6e839f3bcd..da844f412b 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/usage/TriggerReader.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/usage/TriggerReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,148 +30,128 @@ public class TriggerReader extends Reader { - private String pathAccountSid; + private String pathaccountSid; private Trigger.Recurring recurring; private Trigger.TriggerField triggerBy; private String usageCategory; private Long pageSize; - public TriggerReader() {} + public TriggerReader() { + } - public TriggerReader(final String pathAccountSid) { - this.pathAccountSid = pathAccountSid; + public TriggerReader(final String pathaccountSid) { + this.pathaccountSid = pathaccountSid; } + public TriggerReader setRecurring(final Trigger.Recurring recurring) { this.recurring = recurring; return this; } + public TriggerReader setTriggerBy(final Trigger.TriggerField triggerBy) { this.triggerBy = triggerBy; return this; } + public TriggerReader setUsageCategory(final String usageCategory) { this.usageCategory = usageCategory; return this; } + public TriggerReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/2010-04-01/Accounts/{AccountSid}/Usage/Triggers.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.API.toString(), - path + HttpMethod.GET, + Domains.API.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Trigger read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Trigger read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "usage_triggers", - response.getContent(), - Trigger.class, - client.getObjectMapper() - ); + "usage_triggers", + response.getContent(), + Trigger.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.API.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.API.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (recurring != null) { - request.addQueryParam("Recurring", recurring.toString()); + Serializer.toString(request, "Recurring", recurring, ParameterType.QUERY); } + + if (triggerBy != null) { - request.addQueryParam("TriggerBy", triggerBy.toString()); + Serializer.toString(request, "TriggerBy", triggerBy, ParameterType.QUERY); } + + if (usageCategory != null) { - request.addQueryParam("UsageCategory", usageCategory); + Serializer.toString(request, "UsageCategory", usageCategory, ParameterType.QUERY); } + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/usage/TriggerUpdater.java b/src/main/java/com/twilio/rest/api/v2010/account/usage/TriggerUpdater.java index e1216c30dc..48c6609e83 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/usage/TriggerUpdater.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/usage/TriggerUpdater.java @@ -16,7 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; -import com.twilio.converter.Promoter; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,82 +26,73 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.net.URI; public class TriggerUpdater extends Updater { - - private String pathSid; - private String pathAccountSid; + private String pathaccountSid; + private String pathsid; private HttpMethod callbackMethod; private URI callbackUrl; private String friendlyName; - public TriggerUpdater(final String pathSid) { - this.pathSid = pathSid; + public TriggerUpdater(final String pathsid) { + this.pathsid = pathsid; } - public TriggerUpdater(final String pathAccountSid, final String pathSid) { - this.pathAccountSid = pathAccountSid; - this.pathSid = pathSid; + public TriggerUpdater(final String pathaccountSid, final String pathsid) { + this.pathaccountSid = pathaccountSid; + this.pathsid = pathsid; } + public TriggerUpdater setCallbackMethod(final HttpMethod callbackMethod) { this.callbackMethod = callbackMethod; return this; } + public TriggerUpdater setCallbackUrl(final URI callbackUrl) { this.callbackUrl = callbackUrl; return this; } - public TriggerUpdater setCallbackUrl(final String callbackUrl) { - return setCallbackUrl(Promoter.uriFromString(callbackUrl)); - } public TriggerUpdater setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + @Override public Trigger update(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/Usage/Triggers/{Sid}.json"; - - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + + String path = "/2010-04-01/Accounts/{AccountSid}/Usage/Triggers/{Sid}.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.API.toString(), - path + HttpMethod.POST, + Domains.API.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Trigger update failed: Unable to connect to server" - ); + throw new ApiConnectionException("Trigger update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -109,14 +101,21 @@ public Trigger update(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (callbackMethod != null) { - request.addPostParam("CallbackMethod", callbackMethod.toString()); + Serializer.toString(request, "CallbackMethod", callbackMethod, ParameterType.URLENCODED); } + + if (callbackUrl != null) { - request.addPostParam("CallbackUrl", callbackUrl.toString()); + Serializer.toString(request, "CallbackUrl", callbackUrl, ParameterType.URLENCODED); } + + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/usage/record/AllTime.java b/src/main/java/com/twilio/rest/api/v2010/account/usage/record/AllTime.java index bf2f4409bf..9e8ffa3490 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/usage/record/AllTime.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/usage/record/AllTime.java @@ -18,50 +18,51 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.CurrencyDeserializer; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.math.BigDecimal; import java.time.LocalDate; import java.util.Currency; import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class AllTime extends Resource { - private static final long serialVersionUID = 158026917970511L; public static AllTimeReader reader() { - return new AllTimeReader(); + return new AllTimeReader( + + ); } - public static AllTimeReader reader(final String pathAccountSid) { - return new AllTimeReader(pathAccountSid); + + public static AllTimeReader reader(final String pathaccountSid) { + return new AllTimeReader( + pathaccountSid + ); } + /** * Converts a JSON String into a AllTime object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return AllTime object represented by the provided JSON */ - public static AllTime fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static AllTime fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, AllTime.class); @@ -76,14 +77,11 @@ public static AllTime fromJson( * Converts a JSON InputStream into a AllTime object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return AllTime object represented by the provided JSON */ - public static AllTime fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static AllTime fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, AllTime.class); @@ -94,44 +92,70 @@ public static AllTime fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; + @Getter private final String apiVersion; + @Getter private final String asOf; + @Getter private final String category; + @Getter private final String count; + @Getter private final String countUnit; + @Getter private final String description; + @Getter private final LocalDate endDate; + @Getter private final BigDecimal price; + @Getter private final Currency priceUnit; + @Getter private final LocalDate startDate; + @Getter private final Map subresourceUris; + @Getter private final String uri; + @Getter private final String usage; + @Getter private final String usageUnit; @JsonCreator private AllTime( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("api_version") final String apiVersion, - @JsonProperty("as_of") final String asOf, - @JsonProperty("category") final String category, - @JsonProperty("count") final String count, - @JsonProperty("count_unit") final String countUnit, - @JsonProperty("description") final String description, - @JsonProperty("end_date") final String endDate, - @JsonProperty("price") final BigDecimal price, - @JsonProperty("price_unit") @JsonDeserialize( - using = com.twilio.converter.CurrencyDeserializer.class - ) final Currency priceUnit, - @JsonProperty("start_date") final String startDate, - @JsonProperty("subresource_uris") final Map< - String, - String - > subresourceUris, - @JsonProperty("uri") final String uri, - @JsonProperty("usage") final String usage, - @JsonProperty("usage_unit") final String usageUnit + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("api_version") final String apiVersion, + @JsonProperty("as_of") final String asOf, + @JsonProperty("category") final String category, + @JsonProperty("count") final String count, + @JsonProperty("count_unit") final String countUnit, + @JsonProperty("description") final String description, + @JsonProperty("end_date") + @JsonDeserialize(using = com.twilio.converter.LocalDateDeserializer.class) final LocalDate endDate, + @JsonProperty("price") final BigDecimal price, + @JsonProperty("price_unit") + @JsonDeserialize(using = com.twilio.converter.CurrencyDeserializer.class) final Currency priceUnit, + @JsonProperty("start_date") + @JsonDeserialize(using = com.twilio.converter.LocalDateDeserializer.class) final LocalDate startDate, + @JsonProperty("subresource_uris") final Map subresourceUris, + @JsonProperty("uri") final String uri, + @JsonProperty("usage") final String usage, + @JsonProperty("usage_unit") final String usageUnit ) { this.accountSid = accountSid; this.apiVersion = apiVersion; @@ -140,76 +164,16 @@ private AllTime( this.count = count; this.countUnit = countUnit; this.description = description; - this.endDate = DateConverter.localDateFromString(endDate); + this.endDate = endDate; this.price = price; this.priceUnit = priceUnit; - this.startDate = DateConverter.localDateFromString(startDate); + this.startDate = startDate; this.subresourceUris = subresourceUris; this.uri = uri; this.usage = usage; this.usageUnit = usageUnit; } - public final String getAccountSid() { - return this.accountSid; - } - - public final String getApiVersion() { - return this.apiVersion; - } - - public final String getAsOf() { - return this.asOf; - } - - public final String getCategory() { - return this.category; - } - - public final String getCount() { - return this.count; - } - - public final String getCountUnit() { - return this.countUnit; - } - - public final String getDescription() { - return this.description; - } - - public final LocalDate getEndDate() { - return this.endDate; - } - - public final BigDecimal getPrice() { - return this.price; - } - - public final Currency getPriceUnit() { - return this.priceUnit; - } - - public final LocalDate getStartDate() { - return this.startDate; - } - - public final Map getSubresourceUris() { - return this.subresourceUris; - } - - public final String getUri() { - return this.uri; - } - - public final String getUsage() { - return this.usage; - } - - public final String getUsageUnit() { - return this.usageUnit; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -221,44 +185,46 @@ public boolean equals(final Object o) { } AllTime other = (AllTime) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(apiVersion, other.apiVersion) && - Objects.equals(asOf, other.asOf) && - Objects.equals(category, other.category) && - Objects.equals(count, other.count) && - Objects.equals(countUnit, other.countUnit) && - Objects.equals(description, other.description) && - Objects.equals(endDate, other.endDate) && - Objects.equals(price, other.price) && - Objects.equals(priceUnit, other.priceUnit) && - Objects.equals(startDate, other.startDate) && - Objects.equals(subresourceUris, other.subresourceUris) && - Objects.equals(uri, other.uri) && - Objects.equals(usage, other.usage) && - Objects.equals(usageUnit, other.usageUnit) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(apiVersion, other.apiVersion) && + Objects.equals(asOf, other.asOf) && + Objects.equals(category, other.category) && + Objects.equals(count, other.count) && + Objects.equals(countUnit, other.countUnit) && + Objects.equals(description, other.description) && + Objects.equals(endDate, other.endDate) && + Objects.equals(price, other.price) && + Objects.equals(priceUnit, other.priceUnit) && + Objects.equals(startDate, other.startDate) && + Objects.equals(subresourceUris, other.subresourceUris) && + Objects.equals(uri, other.uri) && + Objects.equals(usage, other.usage) && + Objects.equals(usageUnit, other.usageUnit) ); } @Override public int hashCode() { return Objects.hash( - accountSid, - apiVersion, - asOf, - category, - count, - countUnit, - description, - endDate, - price, - priceUnit, - startDate, - subresourceUris, - uri, - usage, - usageUnit + accountSid, + apiVersion, + asOf, + category, + count, + countUnit, + description, + endDate, + price, + priceUnit, + startDate, + subresourceUris, + uri, + usage, + usageUnit ); } + + } + diff --git a/src/main/java/com/twilio/rest/api/v2010/account/usage/record/AllTimeReader.java b/src/main/java/com/twilio/rest/api/v2010/account/usage/record/AllTimeReader.java index 5d8d1e2f79..f37dce38f4 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/usage/record/AllTimeReader.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/usage/record/AllTimeReader.java @@ -17,8 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; -import com.twilio.converter.DateConverter; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,175 +27,145 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.time.LocalDate; public class AllTimeReader extends Reader { - private String pathAccountSid; + private String pathaccountSid; private String category; private LocalDate startDate; private LocalDate endDate; private Boolean includeSubaccounts; private Long pageSize; - public AllTimeReader() {} + public AllTimeReader() { + } - public AllTimeReader(final String pathAccountSid) { - this.pathAccountSid = pathAccountSid; + public AllTimeReader(final String pathaccountSid) { + this.pathaccountSid = pathaccountSid; } + public AllTimeReader setCategory(final String category) { this.category = category; return this; } + public AllTimeReader setStartDate(final LocalDate startDate) { this.startDate = startDate; return this; } + public AllTimeReader setEndDate(final LocalDate endDate) { this.endDate = endDate; return this; } - public AllTimeReader setIncludeSubaccounts( - final Boolean includeSubaccounts - ) { + + public AllTimeReader setIncludeSubaccounts(final Boolean includeSubaccounts) { this.includeSubaccounts = includeSubaccounts; return this; } + public AllTimeReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/Usage/Records/AllTime.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); + + String path = "/2010-04-01/Accounts/{AccountSid}/Usage/Records/AllTime.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.API.toString(), - path + HttpMethod.GET, + Domains.API.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "AllTime read failed: Unable to connect to server" - ); + throw new ApiConnectionException("AllTime read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "usage_records", - response.getContent(), - AllTime.class, - client.getObjectMapper() - ); + "usage_records", + response.getContent(), + AllTime.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.API.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.API.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (category != null) { - request.addQueryParam("Category", category); + Serializer.toString(request, "Category", category, ParameterType.QUERY); } + + if (startDate != null) { - request.addQueryParam( - "StartDate", - DateConverter.dateStringFromLocalDate(startDate) - ); + Serializer.toString(request, "StartDate", startDate, ParameterType.QUERY); } + if (endDate != null) { - request.addQueryParam( - "EndDate", - DateConverter.dateStringFromLocalDate(endDate) - ); + Serializer.toString(request, "EndDate", endDate, ParameterType.QUERY); } + if (includeSubaccounts != null) { - request.addQueryParam( - "IncludeSubaccounts", - includeSubaccounts.toString() - ); + Serializer.toString(request, "IncludeSubaccounts", includeSubaccounts, ParameterType.QUERY); } + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/usage/record/Daily.java b/src/main/java/com/twilio/rest/api/v2010/account/usage/record/Daily.java index 34441ee37d..d1bf22a48b 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/usage/record/Daily.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/usage/record/Daily.java @@ -18,50 +18,51 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.CurrencyDeserializer; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.math.BigDecimal; import java.time.LocalDate; import java.util.Currency; import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Daily extends Resource { - private static final long serialVersionUID = 158026917970511L; public static DailyReader reader() { - return new DailyReader(); + return new DailyReader( + + ); } - public static DailyReader reader(final String pathAccountSid) { - return new DailyReader(pathAccountSid); + + public static DailyReader reader(final String pathaccountSid) { + return new DailyReader( + pathaccountSid + ); } + /** * Converts a JSON String into a Daily object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Daily object represented by the provided JSON */ - public static Daily fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Daily fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Daily.class); @@ -76,14 +77,11 @@ public static Daily fromJson( * Converts a JSON InputStream into a Daily object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Daily object represented by the provided JSON */ - public static Daily fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Daily fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Daily.class); @@ -94,44 +92,70 @@ public static Daily fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; + @Getter private final String apiVersion; + @Getter private final String asOf; + @Getter private final String category; + @Getter private final String count; + @Getter private final String countUnit; + @Getter private final String description; + @Getter private final LocalDate endDate; + @Getter private final BigDecimal price; + @Getter private final Currency priceUnit; + @Getter private final LocalDate startDate; + @Getter private final Map subresourceUris; + @Getter private final String uri; + @Getter private final String usage; + @Getter private final String usageUnit; @JsonCreator private Daily( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("api_version") final String apiVersion, - @JsonProperty("as_of") final String asOf, - @JsonProperty("category") final String category, - @JsonProperty("count") final String count, - @JsonProperty("count_unit") final String countUnit, - @JsonProperty("description") final String description, - @JsonProperty("end_date") final String endDate, - @JsonProperty("price") final BigDecimal price, - @JsonProperty("price_unit") @JsonDeserialize( - using = com.twilio.converter.CurrencyDeserializer.class - ) final Currency priceUnit, - @JsonProperty("start_date") final String startDate, - @JsonProperty("subresource_uris") final Map< - String, - String - > subresourceUris, - @JsonProperty("uri") final String uri, - @JsonProperty("usage") final String usage, - @JsonProperty("usage_unit") final String usageUnit + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("api_version") final String apiVersion, + @JsonProperty("as_of") final String asOf, + @JsonProperty("category") final String category, + @JsonProperty("count") final String count, + @JsonProperty("count_unit") final String countUnit, + @JsonProperty("description") final String description, + @JsonProperty("end_date") + @JsonDeserialize(using = com.twilio.converter.LocalDateDeserializer.class) final LocalDate endDate, + @JsonProperty("price") final BigDecimal price, + @JsonProperty("price_unit") + @JsonDeserialize(using = com.twilio.converter.CurrencyDeserializer.class) final Currency priceUnit, + @JsonProperty("start_date") + @JsonDeserialize(using = com.twilio.converter.LocalDateDeserializer.class) final LocalDate startDate, + @JsonProperty("subresource_uris") final Map subresourceUris, + @JsonProperty("uri") final String uri, + @JsonProperty("usage") final String usage, + @JsonProperty("usage_unit") final String usageUnit ) { this.accountSid = accountSid; this.apiVersion = apiVersion; @@ -140,76 +164,16 @@ private Daily( this.count = count; this.countUnit = countUnit; this.description = description; - this.endDate = DateConverter.localDateFromString(endDate); + this.endDate = endDate; this.price = price; this.priceUnit = priceUnit; - this.startDate = DateConverter.localDateFromString(startDate); + this.startDate = startDate; this.subresourceUris = subresourceUris; this.uri = uri; this.usage = usage; this.usageUnit = usageUnit; } - public final String getAccountSid() { - return this.accountSid; - } - - public final String getApiVersion() { - return this.apiVersion; - } - - public final String getAsOf() { - return this.asOf; - } - - public final String getCategory() { - return this.category; - } - - public final String getCount() { - return this.count; - } - - public final String getCountUnit() { - return this.countUnit; - } - - public final String getDescription() { - return this.description; - } - - public final LocalDate getEndDate() { - return this.endDate; - } - - public final BigDecimal getPrice() { - return this.price; - } - - public final Currency getPriceUnit() { - return this.priceUnit; - } - - public final LocalDate getStartDate() { - return this.startDate; - } - - public final Map getSubresourceUris() { - return this.subresourceUris; - } - - public final String getUri() { - return this.uri; - } - - public final String getUsage() { - return this.usage; - } - - public final String getUsageUnit() { - return this.usageUnit; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -221,44 +185,46 @@ public boolean equals(final Object o) { } Daily other = (Daily) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(apiVersion, other.apiVersion) && - Objects.equals(asOf, other.asOf) && - Objects.equals(category, other.category) && - Objects.equals(count, other.count) && - Objects.equals(countUnit, other.countUnit) && - Objects.equals(description, other.description) && - Objects.equals(endDate, other.endDate) && - Objects.equals(price, other.price) && - Objects.equals(priceUnit, other.priceUnit) && - Objects.equals(startDate, other.startDate) && - Objects.equals(subresourceUris, other.subresourceUris) && - Objects.equals(uri, other.uri) && - Objects.equals(usage, other.usage) && - Objects.equals(usageUnit, other.usageUnit) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(apiVersion, other.apiVersion) && + Objects.equals(asOf, other.asOf) && + Objects.equals(category, other.category) && + Objects.equals(count, other.count) && + Objects.equals(countUnit, other.countUnit) && + Objects.equals(description, other.description) && + Objects.equals(endDate, other.endDate) && + Objects.equals(price, other.price) && + Objects.equals(priceUnit, other.priceUnit) && + Objects.equals(startDate, other.startDate) && + Objects.equals(subresourceUris, other.subresourceUris) && + Objects.equals(uri, other.uri) && + Objects.equals(usage, other.usage) && + Objects.equals(usageUnit, other.usageUnit) ); } @Override public int hashCode() { return Objects.hash( - accountSid, - apiVersion, - asOf, - category, - count, - countUnit, - description, - endDate, - price, - priceUnit, - startDate, - subresourceUris, - uri, - usage, - usageUnit + accountSid, + apiVersion, + asOf, + category, + count, + countUnit, + description, + endDate, + price, + priceUnit, + startDate, + subresourceUris, + uri, + usage, + usageUnit ); } + + } + diff --git a/src/main/java/com/twilio/rest/api/v2010/account/usage/record/DailyReader.java b/src/main/java/com/twilio/rest/api/v2010/account/usage/record/DailyReader.java index a62bbfe107..a5b7c0e07a 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/usage/record/DailyReader.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/usage/record/DailyReader.java @@ -17,8 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; -import com.twilio.converter.DateConverter; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,173 +27,145 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.time.LocalDate; public class DailyReader extends Reader { - private String pathAccountSid; + private String pathaccountSid; private String category; private LocalDate startDate; private LocalDate endDate; private Boolean includeSubaccounts; private Long pageSize; - public DailyReader() {} + public DailyReader() { + } - public DailyReader(final String pathAccountSid) { - this.pathAccountSid = pathAccountSid; + public DailyReader(final String pathaccountSid) { + this.pathaccountSid = pathaccountSid; } + public DailyReader setCategory(final String category) { this.category = category; return this; } + public DailyReader setStartDate(final LocalDate startDate) { this.startDate = startDate; return this; } + public DailyReader setEndDate(final LocalDate endDate) { this.endDate = endDate; return this; } + public DailyReader setIncludeSubaccounts(final Boolean includeSubaccounts) { this.includeSubaccounts = includeSubaccounts; return this; } + public DailyReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/Usage/Records/Daily.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); + + String path = "/2010-04-01/Accounts/{AccountSid}/Usage/Records/Daily.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.API.toString(), - path + HttpMethod.GET, + Domains.API.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Daily read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Daily read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "usage_records", - response.getContent(), - Daily.class, - client.getObjectMapper() - ); + "usage_records", + response.getContent(), + Daily.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.API.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.API.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (category != null) { - request.addQueryParam("Category", category); + Serializer.toString(request, "Category", category, ParameterType.QUERY); } + + if (startDate != null) { - request.addQueryParam( - "StartDate", - DateConverter.dateStringFromLocalDate(startDate) - ); + Serializer.toString(request, "StartDate", startDate, ParameterType.QUERY); } + if (endDate != null) { - request.addQueryParam( - "EndDate", - DateConverter.dateStringFromLocalDate(endDate) - ); + Serializer.toString(request, "EndDate", endDate, ParameterType.QUERY); } + if (includeSubaccounts != null) { - request.addQueryParam( - "IncludeSubaccounts", - includeSubaccounts.toString() - ); + Serializer.toString(request, "IncludeSubaccounts", includeSubaccounts, ParameterType.QUERY); } + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/usage/record/LastMonth.java b/src/main/java/com/twilio/rest/api/v2010/account/usage/record/LastMonth.java index 920a2a555f..2efed40f67 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/usage/record/LastMonth.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/usage/record/LastMonth.java @@ -18,50 +18,51 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.CurrencyDeserializer; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.math.BigDecimal; import java.time.LocalDate; import java.util.Currency; import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class LastMonth extends Resource { - private static final long serialVersionUID = 158026917970511L; public static LastMonthReader reader() { - return new LastMonthReader(); + return new LastMonthReader( + + ); } - public static LastMonthReader reader(final String pathAccountSid) { - return new LastMonthReader(pathAccountSid); + + public static LastMonthReader reader(final String pathaccountSid) { + return new LastMonthReader( + pathaccountSid + ); } + /** * Converts a JSON String into a LastMonth object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return LastMonth object represented by the provided JSON */ - public static LastMonth fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static LastMonth fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, LastMonth.class); @@ -76,14 +77,11 @@ public static LastMonth fromJson( * Converts a JSON InputStream into a LastMonth object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return LastMonth object represented by the provided JSON */ - public static LastMonth fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static LastMonth fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, LastMonth.class); @@ -94,44 +92,70 @@ public static LastMonth fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; + @Getter private final String apiVersion; + @Getter private final String asOf; + @Getter private final String category; + @Getter private final String count; + @Getter private final String countUnit; + @Getter private final String description; + @Getter private final LocalDate endDate; + @Getter private final BigDecimal price; + @Getter private final Currency priceUnit; + @Getter private final LocalDate startDate; + @Getter private final Map subresourceUris; + @Getter private final String uri; + @Getter private final String usage; + @Getter private final String usageUnit; @JsonCreator private LastMonth( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("api_version") final String apiVersion, - @JsonProperty("as_of") final String asOf, - @JsonProperty("category") final String category, - @JsonProperty("count") final String count, - @JsonProperty("count_unit") final String countUnit, - @JsonProperty("description") final String description, - @JsonProperty("end_date") final String endDate, - @JsonProperty("price") final BigDecimal price, - @JsonProperty("price_unit") @JsonDeserialize( - using = com.twilio.converter.CurrencyDeserializer.class - ) final Currency priceUnit, - @JsonProperty("start_date") final String startDate, - @JsonProperty("subresource_uris") final Map< - String, - String - > subresourceUris, - @JsonProperty("uri") final String uri, - @JsonProperty("usage") final String usage, - @JsonProperty("usage_unit") final String usageUnit + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("api_version") final String apiVersion, + @JsonProperty("as_of") final String asOf, + @JsonProperty("category") final String category, + @JsonProperty("count") final String count, + @JsonProperty("count_unit") final String countUnit, + @JsonProperty("description") final String description, + @JsonProperty("end_date") + @JsonDeserialize(using = com.twilio.converter.LocalDateDeserializer.class) final LocalDate endDate, + @JsonProperty("price") final BigDecimal price, + @JsonProperty("price_unit") + @JsonDeserialize(using = com.twilio.converter.CurrencyDeserializer.class) final Currency priceUnit, + @JsonProperty("start_date") + @JsonDeserialize(using = com.twilio.converter.LocalDateDeserializer.class) final LocalDate startDate, + @JsonProperty("subresource_uris") final Map subresourceUris, + @JsonProperty("uri") final String uri, + @JsonProperty("usage") final String usage, + @JsonProperty("usage_unit") final String usageUnit ) { this.accountSid = accountSid; this.apiVersion = apiVersion; @@ -140,76 +164,16 @@ private LastMonth( this.count = count; this.countUnit = countUnit; this.description = description; - this.endDate = DateConverter.localDateFromString(endDate); + this.endDate = endDate; this.price = price; this.priceUnit = priceUnit; - this.startDate = DateConverter.localDateFromString(startDate); + this.startDate = startDate; this.subresourceUris = subresourceUris; this.uri = uri; this.usage = usage; this.usageUnit = usageUnit; } - public final String getAccountSid() { - return this.accountSid; - } - - public final String getApiVersion() { - return this.apiVersion; - } - - public final String getAsOf() { - return this.asOf; - } - - public final String getCategory() { - return this.category; - } - - public final String getCount() { - return this.count; - } - - public final String getCountUnit() { - return this.countUnit; - } - - public final String getDescription() { - return this.description; - } - - public final LocalDate getEndDate() { - return this.endDate; - } - - public final BigDecimal getPrice() { - return this.price; - } - - public final Currency getPriceUnit() { - return this.priceUnit; - } - - public final LocalDate getStartDate() { - return this.startDate; - } - - public final Map getSubresourceUris() { - return this.subresourceUris; - } - - public final String getUri() { - return this.uri; - } - - public final String getUsage() { - return this.usage; - } - - public final String getUsageUnit() { - return this.usageUnit; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -221,44 +185,46 @@ public boolean equals(final Object o) { } LastMonth other = (LastMonth) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(apiVersion, other.apiVersion) && - Objects.equals(asOf, other.asOf) && - Objects.equals(category, other.category) && - Objects.equals(count, other.count) && - Objects.equals(countUnit, other.countUnit) && - Objects.equals(description, other.description) && - Objects.equals(endDate, other.endDate) && - Objects.equals(price, other.price) && - Objects.equals(priceUnit, other.priceUnit) && - Objects.equals(startDate, other.startDate) && - Objects.equals(subresourceUris, other.subresourceUris) && - Objects.equals(uri, other.uri) && - Objects.equals(usage, other.usage) && - Objects.equals(usageUnit, other.usageUnit) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(apiVersion, other.apiVersion) && + Objects.equals(asOf, other.asOf) && + Objects.equals(category, other.category) && + Objects.equals(count, other.count) && + Objects.equals(countUnit, other.countUnit) && + Objects.equals(description, other.description) && + Objects.equals(endDate, other.endDate) && + Objects.equals(price, other.price) && + Objects.equals(priceUnit, other.priceUnit) && + Objects.equals(startDate, other.startDate) && + Objects.equals(subresourceUris, other.subresourceUris) && + Objects.equals(uri, other.uri) && + Objects.equals(usage, other.usage) && + Objects.equals(usageUnit, other.usageUnit) ); } @Override public int hashCode() { return Objects.hash( - accountSid, - apiVersion, - asOf, - category, - count, - countUnit, - description, - endDate, - price, - priceUnit, - startDate, - subresourceUris, - uri, - usage, - usageUnit + accountSid, + apiVersion, + asOf, + category, + count, + countUnit, + description, + endDate, + price, + priceUnit, + startDate, + subresourceUris, + uri, + usage, + usageUnit ); } + + } + diff --git a/src/main/java/com/twilio/rest/api/v2010/account/usage/record/LastMonthReader.java b/src/main/java/com/twilio/rest/api/v2010/account/usage/record/LastMonthReader.java index b7e7e08fae..ce7e40bddd 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/usage/record/LastMonthReader.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/usage/record/LastMonthReader.java @@ -17,8 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; -import com.twilio.converter.DateConverter; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,175 +27,145 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.time.LocalDate; public class LastMonthReader extends Reader { - private String pathAccountSid; + private String pathaccountSid; private String category; private LocalDate startDate; private LocalDate endDate; private Boolean includeSubaccounts; private Long pageSize; - public LastMonthReader() {} + public LastMonthReader() { + } - public LastMonthReader(final String pathAccountSid) { - this.pathAccountSid = pathAccountSid; + public LastMonthReader(final String pathaccountSid) { + this.pathaccountSid = pathaccountSid; } + public LastMonthReader setCategory(final String category) { this.category = category; return this; } + public LastMonthReader setStartDate(final LocalDate startDate) { this.startDate = startDate; return this; } + public LastMonthReader setEndDate(final LocalDate endDate) { this.endDate = endDate; return this; } - public LastMonthReader setIncludeSubaccounts( - final Boolean includeSubaccounts - ) { + + public LastMonthReader setIncludeSubaccounts(final Boolean includeSubaccounts) { this.includeSubaccounts = includeSubaccounts; return this; } + public LastMonthReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/Usage/Records/LastMonth.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); + + String path = "/2010-04-01/Accounts/{AccountSid}/Usage/Records/LastMonth.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.API.toString(), - path + HttpMethod.GET, + Domains.API.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "LastMonth read failed: Unable to connect to server" - ); + throw new ApiConnectionException("LastMonth read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "usage_records", - response.getContent(), - LastMonth.class, - client.getObjectMapper() - ); + "usage_records", + response.getContent(), + LastMonth.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.API.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.API.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (category != null) { - request.addQueryParam("Category", category); + Serializer.toString(request, "Category", category, ParameterType.QUERY); } + + if (startDate != null) { - request.addQueryParam( - "StartDate", - DateConverter.dateStringFromLocalDate(startDate) - ); + Serializer.toString(request, "StartDate", startDate, ParameterType.QUERY); } + if (endDate != null) { - request.addQueryParam( - "EndDate", - DateConverter.dateStringFromLocalDate(endDate) - ); + Serializer.toString(request, "EndDate", endDate, ParameterType.QUERY); } + if (includeSubaccounts != null) { - request.addQueryParam( - "IncludeSubaccounts", - includeSubaccounts.toString() - ); + Serializer.toString(request, "IncludeSubaccounts", includeSubaccounts, ParameterType.QUERY); } + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/usage/record/Monthly.java b/src/main/java/com/twilio/rest/api/v2010/account/usage/record/Monthly.java index 9394d8b01a..8c49e3a4a0 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/usage/record/Monthly.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/usage/record/Monthly.java @@ -18,50 +18,51 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.CurrencyDeserializer; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.math.BigDecimal; import java.time.LocalDate; import java.util.Currency; import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Monthly extends Resource { - private static final long serialVersionUID = 158026917970511L; public static MonthlyReader reader() { - return new MonthlyReader(); + return new MonthlyReader( + + ); } - public static MonthlyReader reader(final String pathAccountSid) { - return new MonthlyReader(pathAccountSid); + + public static MonthlyReader reader(final String pathaccountSid) { + return new MonthlyReader( + pathaccountSid + ); } + /** * Converts a JSON String into a Monthly object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Monthly object represented by the provided JSON */ - public static Monthly fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Monthly fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Monthly.class); @@ -76,14 +77,11 @@ public static Monthly fromJson( * Converts a JSON InputStream into a Monthly object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Monthly object represented by the provided JSON */ - public static Monthly fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Monthly fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Monthly.class); @@ -94,44 +92,70 @@ public static Monthly fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; + @Getter private final String apiVersion; + @Getter private final String asOf; + @Getter private final String category; + @Getter private final String count; + @Getter private final String countUnit; + @Getter private final String description; + @Getter private final LocalDate endDate; + @Getter private final BigDecimal price; + @Getter private final Currency priceUnit; + @Getter private final LocalDate startDate; + @Getter private final Map subresourceUris; + @Getter private final String uri; + @Getter private final String usage; + @Getter private final String usageUnit; @JsonCreator private Monthly( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("api_version") final String apiVersion, - @JsonProperty("as_of") final String asOf, - @JsonProperty("category") final String category, - @JsonProperty("count") final String count, - @JsonProperty("count_unit") final String countUnit, - @JsonProperty("description") final String description, - @JsonProperty("end_date") final String endDate, - @JsonProperty("price") final BigDecimal price, - @JsonProperty("price_unit") @JsonDeserialize( - using = com.twilio.converter.CurrencyDeserializer.class - ) final Currency priceUnit, - @JsonProperty("start_date") final String startDate, - @JsonProperty("subresource_uris") final Map< - String, - String - > subresourceUris, - @JsonProperty("uri") final String uri, - @JsonProperty("usage") final String usage, - @JsonProperty("usage_unit") final String usageUnit + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("api_version") final String apiVersion, + @JsonProperty("as_of") final String asOf, + @JsonProperty("category") final String category, + @JsonProperty("count") final String count, + @JsonProperty("count_unit") final String countUnit, + @JsonProperty("description") final String description, + @JsonProperty("end_date") + @JsonDeserialize(using = com.twilio.converter.LocalDateDeserializer.class) final LocalDate endDate, + @JsonProperty("price") final BigDecimal price, + @JsonProperty("price_unit") + @JsonDeserialize(using = com.twilio.converter.CurrencyDeserializer.class) final Currency priceUnit, + @JsonProperty("start_date") + @JsonDeserialize(using = com.twilio.converter.LocalDateDeserializer.class) final LocalDate startDate, + @JsonProperty("subresource_uris") final Map subresourceUris, + @JsonProperty("uri") final String uri, + @JsonProperty("usage") final String usage, + @JsonProperty("usage_unit") final String usageUnit ) { this.accountSid = accountSid; this.apiVersion = apiVersion; @@ -140,76 +164,16 @@ private Monthly( this.count = count; this.countUnit = countUnit; this.description = description; - this.endDate = DateConverter.localDateFromString(endDate); + this.endDate = endDate; this.price = price; this.priceUnit = priceUnit; - this.startDate = DateConverter.localDateFromString(startDate); + this.startDate = startDate; this.subresourceUris = subresourceUris; this.uri = uri; this.usage = usage; this.usageUnit = usageUnit; } - public final String getAccountSid() { - return this.accountSid; - } - - public final String getApiVersion() { - return this.apiVersion; - } - - public final String getAsOf() { - return this.asOf; - } - - public final String getCategory() { - return this.category; - } - - public final String getCount() { - return this.count; - } - - public final String getCountUnit() { - return this.countUnit; - } - - public final String getDescription() { - return this.description; - } - - public final LocalDate getEndDate() { - return this.endDate; - } - - public final BigDecimal getPrice() { - return this.price; - } - - public final Currency getPriceUnit() { - return this.priceUnit; - } - - public final LocalDate getStartDate() { - return this.startDate; - } - - public final Map getSubresourceUris() { - return this.subresourceUris; - } - - public final String getUri() { - return this.uri; - } - - public final String getUsage() { - return this.usage; - } - - public final String getUsageUnit() { - return this.usageUnit; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -221,44 +185,46 @@ public boolean equals(final Object o) { } Monthly other = (Monthly) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(apiVersion, other.apiVersion) && - Objects.equals(asOf, other.asOf) && - Objects.equals(category, other.category) && - Objects.equals(count, other.count) && - Objects.equals(countUnit, other.countUnit) && - Objects.equals(description, other.description) && - Objects.equals(endDate, other.endDate) && - Objects.equals(price, other.price) && - Objects.equals(priceUnit, other.priceUnit) && - Objects.equals(startDate, other.startDate) && - Objects.equals(subresourceUris, other.subresourceUris) && - Objects.equals(uri, other.uri) && - Objects.equals(usage, other.usage) && - Objects.equals(usageUnit, other.usageUnit) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(apiVersion, other.apiVersion) && + Objects.equals(asOf, other.asOf) && + Objects.equals(category, other.category) && + Objects.equals(count, other.count) && + Objects.equals(countUnit, other.countUnit) && + Objects.equals(description, other.description) && + Objects.equals(endDate, other.endDate) && + Objects.equals(price, other.price) && + Objects.equals(priceUnit, other.priceUnit) && + Objects.equals(startDate, other.startDate) && + Objects.equals(subresourceUris, other.subresourceUris) && + Objects.equals(uri, other.uri) && + Objects.equals(usage, other.usage) && + Objects.equals(usageUnit, other.usageUnit) ); } @Override public int hashCode() { return Objects.hash( - accountSid, - apiVersion, - asOf, - category, - count, - countUnit, - description, - endDate, - price, - priceUnit, - startDate, - subresourceUris, - uri, - usage, - usageUnit + accountSid, + apiVersion, + asOf, + category, + count, + countUnit, + description, + endDate, + price, + priceUnit, + startDate, + subresourceUris, + uri, + usage, + usageUnit ); } + + } + diff --git a/src/main/java/com/twilio/rest/api/v2010/account/usage/record/MonthlyReader.java b/src/main/java/com/twilio/rest/api/v2010/account/usage/record/MonthlyReader.java index a6e596d267..f63311027b 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/usage/record/MonthlyReader.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/usage/record/MonthlyReader.java @@ -17,8 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; -import com.twilio.converter.DateConverter; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,175 +27,145 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.time.LocalDate; public class MonthlyReader extends Reader { - private String pathAccountSid; + private String pathaccountSid; private String category; private LocalDate startDate; private LocalDate endDate; private Boolean includeSubaccounts; private Long pageSize; - public MonthlyReader() {} + public MonthlyReader() { + } - public MonthlyReader(final String pathAccountSid) { - this.pathAccountSid = pathAccountSid; + public MonthlyReader(final String pathaccountSid) { + this.pathaccountSid = pathaccountSid; } + public MonthlyReader setCategory(final String category) { this.category = category; return this; } + public MonthlyReader setStartDate(final LocalDate startDate) { this.startDate = startDate; return this; } + public MonthlyReader setEndDate(final LocalDate endDate) { this.endDate = endDate; return this; } - public MonthlyReader setIncludeSubaccounts( - final Boolean includeSubaccounts - ) { + + public MonthlyReader setIncludeSubaccounts(final Boolean includeSubaccounts) { this.includeSubaccounts = includeSubaccounts; return this; } + public MonthlyReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/Usage/Records/Monthly.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); + + String path = "/2010-04-01/Accounts/{AccountSid}/Usage/Records/Monthly.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.API.toString(), - path + HttpMethod.GET, + Domains.API.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Monthly read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Monthly read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "usage_records", - response.getContent(), - Monthly.class, - client.getObjectMapper() - ); + "usage_records", + response.getContent(), + Monthly.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.API.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.API.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (category != null) { - request.addQueryParam("Category", category); + Serializer.toString(request, "Category", category, ParameterType.QUERY); } + + if (startDate != null) { - request.addQueryParam( - "StartDate", - DateConverter.dateStringFromLocalDate(startDate) - ); + Serializer.toString(request, "StartDate", startDate, ParameterType.QUERY); } + if (endDate != null) { - request.addQueryParam( - "EndDate", - DateConverter.dateStringFromLocalDate(endDate) - ); + Serializer.toString(request, "EndDate", endDate, ParameterType.QUERY); } + if (includeSubaccounts != null) { - request.addQueryParam( - "IncludeSubaccounts", - includeSubaccounts.toString() - ); + Serializer.toString(request, "IncludeSubaccounts", includeSubaccounts, ParameterType.QUERY); } + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/usage/record/ThisMonth.java b/src/main/java/com/twilio/rest/api/v2010/account/usage/record/ThisMonth.java index ebd25dee79..dbcb9e0538 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/usage/record/ThisMonth.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/usage/record/ThisMonth.java @@ -18,50 +18,51 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.CurrencyDeserializer; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.math.BigDecimal; import java.time.LocalDate; import java.util.Currency; import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class ThisMonth extends Resource { - private static final long serialVersionUID = 158026917970511L; public static ThisMonthReader reader() { - return new ThisMonthReader(); + return new ThisMonthReader( + + ); } - public static ThisMonthReader reader(final String pathAccountSid) { - return new ThisMonthReader(pathAccountSid); + + public static ThisMonthReader reader(final String pathaccountSid) { + return new ThisMonthReader( + pathaccountSid + ); } + /** * Converts a JSON String into a ThisMonth object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return ThisMonth object represented by the provided JSON */ - public static ThisMonth fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static ThisMonth fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, ThisMonth.class); @@ -76,14 +77,11 @@ public static ThisMonth fromJson( * Converts a JSON InputStream into a ThisMonth object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return ThisMonth object represented by the provided JSON */ - public static ThisMonth fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static ThisMonth fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, ThisMonth.class); @@ -94,44 +92,70 @@ public static ThisMonth fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; + @Getter private final String apiVersion; + @Getter private final String asOf; + @Getter private final String category; + @Getter private final String count; + @Getter private final String countUnit; + @Getter private final String description; + @Getter private final LocalDate endDate; + @Getter private final BigDecimal price; + @Getter private final Currency priceUnit; + @Getter private final LocalDate startDate; + @Getter private final Map subresourceUris; + @Getter private final String uri; + @Getter private final String usage; + @Getter private final String usageUnit; @JsonCreator private ThisMonth( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("api_version") final String apiVersion, - @JsonProperty("as_of") final String asOf, - @JsonProperty("category") final String category, - @JsonProperty("count") final String count, - @JsonProperty("count_unit") final String countUnit, - @JsonProperty("description") final String description, - @JsonProperty("end_date") final String endDate, - @JsonProperty("price") final BigDecimal price, - @JsonProperty("price_unit") @JsonDeserialize( - using = com.twilio.converter.CurrencyDeserializer.class - ) final Currency priceUnit, - @JsonProperty("start_date") final String startDate, - @JsonProperty("subresource_uris") final Map< - String, - String - > subresourceUris, - @JsonProperty("uri") final String uri, - @JsonProperty("usage") final String usage, - @JsonProperty("usage_unit") final String usageUnit + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("api_version") final String apiVersion, + @JsonProperty("as_of") final String asOf, + @JsonProperty("category") final String category, + @JsonProperty("count") final String count, + @JsonProperty("count_unit") final String countUnit, + @JsonProperty("description") final String description, + @JsonProperty("end_date") + @JsonDeserialize(using = com.twilio.converter.LocalDateDeserializer.class) final LocalDate endDate, + @JsonProperty("price") final BigDecimal price, + @JsonProperty("price_unit") + @JsonDeserialize(using = com.twilio.converter.CurrencyDeserializer.class) final Currency priceUnit, + @JsonProperty("start_date") + @JsonDeserialize(using = com.twilio.converter.LocalDateDeserializer.class) final LocalDate startDate, + @JsonProperty("subresource_uris") final Map subresourceUris, + @JsonProperty("uri") final String uri, + @JsonProperty("usage") final String usage, + @JsonProperty("usage_unit") final String usageUnit ) { this.accountSid = accountSid; this.apiVersion = apiVersion; @@ -140,76 +164,16 @@ private ThisMonth( this.count = count; this.countUnit = countUnit; this.description = description; - this.endDate = DateConverter.localDateFromString(endDate); + this.endDate = endDate; this.price = price; this.priceUnit = priceUnit; - this.startDate = DateConverter.localDateFromString(startDate); + this.startDate = startDate; this.subresourceUris = subresourceUris; this.uri = uri; this.usage = usage; this.usageUnit = usageUnit; } - public final String getAccountSid() { - return this.accountSid; - } - - public final String getApiVersion() { - return this.apiVersion; - } - - public final String getAsOf() { - return this.asOf; - } - - public final String getCategory() { - return this.category; - } - - public final String getCount() { - return this.count; - } - - public final String getCountUnit() { - return this.countUnit; - } - - public final String getDescription() { - return this.description; - } - - public final LocalDate getEndDate() { - return this.endDate; - } - - public final BigDecimal getPrice() { - return this.price; - } - - public final Currency getPriceUnit() { - return this.priceUnit; - } - - public final LocalDate getStartDate() { - return this.startDate; - } - - public final Map getSubresourceUris() { - return this.subresourceUris; - } - - public final String getUri() { - return this.uri; - } - - public final String getUsage() { - return this.usage; - } - - public final String getUsageUnit() { - return this.usageUnit; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -221,44 +185,46 @@ public boolean equals(final Object o) { } ThisMonth other = (ThisMonth) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(apiVersion, other.apiVersion) && - Objects.equals(asOf, other.asOf) && - Objects.equals(category, other.category) && - Objects.equals(count, other.count) && - Objects.equals(countUnit, other.countUnit) && - Objects.equals(description, other.description) && - Objects.equals(endDate, other.endDate) && - Objects.equals(price, other.price) && - Objects.equals(priceUnit, other.priceUnit) && - Objects.equals(startDate, other.startDate) && - Objects.equals(subresourceUris, other.subresourceUris) && - Objects.equals(uri, other.uri) && - Objects.equals(usage, other.usage) && - Objects.equals(usageUnit, other.usageUnit) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(apiVersion, other.apiVersion) && + Objects.equals(asOf, other.asOf) && + Objects.equals(category, other.category) && + Objects.equals(count, other.count) && + Objects.equals(countUnit, other.countUnit) && + Objects.equals(description, other.description) && + Objects.equals(endDate, other.endDate) && + Objects.equals(price, other.price) && + Objects.equals(priceUnit, other.priceUnit) && + Objects.equals(startDate, other.startDate) && + Objects.equals(subresourceUris, other.subresourceUris) && + Objects.equals(uri, other.uri) && + Objects.equals(usage, other.usage) && + Objects.equals(usageUnit, other.usageUnit) ); } @Override public int hashCode() { return Objects.hash( - accountSid, - apiVersion, - asOf, - category, - count, - countUnit, - description, - endDate, - price, - priceUnit, - startDate, - subresourceUris, - uri, - usage, - usageUnit + accountSid, + apiVersion, + asOf, + category, + count, + countUnit, + description, + endDate, + price, + priceUnit, + startDate, + subresourceUris, + uri, + usage, + usageUnit ); } + + } + diff --git a/src/main/java/com/twilio/rest/api/v2010/account/usage/record/ThisMonthReader.java b/src/main/java/com/twilio/rest/api/v2010/account/usage/record/ThisMonthReader.java index c68527fae5..2efaf8162b 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/usage/record/ThisMonthReader.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/usage/record/ThisMonthReader.java @@ -17,8 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; -import com.twilio.converter.DateConverter; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,175 +27,145 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.time.LocalDate; public class ThisMonthReader extends Reader { - private String pathAccountSid; + private String pathaccountSid; private String category; private LocalDate startDate; private LocalDate endDate; private Boolean includeSubaccounts; private Long pageSize; - public ThisMonthReader() {} + public ThisMonthReader() { + } - public ThisMonthReader(final String pathAccountSid) { - this.pathAccountSid = pathAccountSid; + public ThisMonthReader(final String pathaccountSid) { + this.pathaccountSid = pathaccountSid; } + public ThisMonthReader setCategory(final String category) { this.category = category; return this; } + public ThisMonthReader setStartDate(final LocalDate startDate) { this.startDate = startDate; return this; } + public ThisMonthReader setEndDate(final LocalDate endDate) { this.endDate = endDate; return this; } - public ThisMonthReader setIncludeSubaccounts( - final Boolean includeSubaccounts - ) { + + public ThisMonthReader setIncludeSubaccounts(final Boolean includeSubaccounts) { this.includeSubaccounts = includeSubaccounts; return this; } + public ThisMonthReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/Usage/Records/ThisMonth.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); + + String path = "/2010-04-01/Accounts/{AccountSid}/Usage/Records/ThisMonth.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.API.toString(), - path + HttpMethod.GET, + Domains.API.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "ThisMonth read failed: Unable to connect to server" - ); + throw new ApiConnectionException("ThisMonth read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "usage_records", - response.getContent(), - ThisMonth.class, - client.getObjectMapper() - ); + "usage_records", + response.getContent(), + ThisMonth.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.API.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.API.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (category != null) { - request.addQueryParam("Category", category); + Serializer.toString(request, "Category", category, ParameterType.QUERY); } + + if (startDate != null) { - request.addQueryParam( - "StartDate", - DateConverter.dateStringFromLocalDate(startDate) - ); + Serializer.toString(request, "StartDate", startDate, ParameterType.QUERY); } + if (endDate != null) { - request.addQueryParam( - "EndDate", - DateConverter.dateStringFromLocalDate(endDate) - ); + Serializer.toString(request, "EndDate", endDate, ParameterType.QUERY); } + if (includeSubaccounts != null) { - request.addQueryParam( - "IncludeSubaccounts", - includeSubaccounts.toString() - ); + Serializer.toString(request, "IncludeSubaccounts", includeSubaccounts, ParameterType.QUERY); } + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/usage/record/Today.java b/src/main/java/com/twilio/rest/api/v2010/account/usage/record/Today.java index 61c98c4bc3..1dc48cce20 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/usage/record/Today.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/usage/record/Today.java @@ -18,50 +18,51 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.CurrencyDeserializer; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.math.BigDecimal; import java.time.LocalDate; import java.util.Currency; import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Today extends Resource { - private static final long serialVersionUID = 158026917970511L; public static TodayReader reader() { - return new TodayReader(); + return new TodayReader( + + ); } - public static TodayReader reader(final String pathAccountSid) { - return new TodayReader(pathAccountSid); + + public static TodayReader reader(final String pathaccountSid) { + return new TodayReader( + pathaccountSid + ); } + /** * Converts a JSON String into a Today object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Today object represented by the provided JSON */ - public static Today fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Today fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Today.class); @@ -76,14 +77,11 @@ public static Today fromJson( * Converts a JSON InputStream into a Today object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Today object represented by the provided JSON */ - public static Today fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Today fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Today.class); @@ -94,44 +92,70 @@ public static Today fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; + @Getter private final String apiVersion; + @Getter private final String asOf; + @Getter private final String category; + @Getter private final String count; + @Getter private final String countUnit; + @Getter private final String description; + @Getter private final LocalDate endDate; + @Getter private final BigDecimal price; + @Getter private final Currency priceUnit; + @Getter private final LocalDate startDate; + @Getter private final Map subresourceUris; + @Getter private final String uri; + @Getter private final String usage; + @Getter private final String usageUnit; @JsonCreator private Today( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("api_version") final String apiVersion, - @JsonProperty("as_of") final String asOf, - @JsonProperty("category") final String category, - @JsonProperty("count") final String count, - @JsonProperty("count_unit") final String countUnit, - @JsonProperty("description") final String description, - @JsonProperty("end_date") final String endDate, - @JsonProperty("price") final BigDecimal price, - @JsonProperty("price_unit") @JsonDeserialize( - using = com.twilio.converter.CurrencyDeserializer.class - ) final Currency priceUnit, - @JsonProperty("start_date") final String startDate, - @JsonProperty("subresource_uris") final Map< - String, - String - > subresourceUris, - @JsonProperty("uri") final String uri, - @JsonProperty("usage") final String usage, - @JsonProperty("usage_unit") final String usageUnit + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("api_version") final String apiVersion, + @JsonProperty("as_of") final String asOf, + @JsonProperty("category") final String category, + @JsonProperty("count") final String count, + @JsonProperty("count_unit") final String countUnit, + @JsonProperty("description") final String description, + @JsonProperty("end_date") + @JsonDeserialize(using = com.twilio.converter.LocalDateDeserializer.class) final LocalDate endDate, + @JsonProperty("price") final BigDecimal price, + @JsonProperty("price_unit") + @JsonDeserialize(using = com.twilio.converter.CurrencyDeserializer.class) final Currency priceUnit, + @JsonProperty("start_date") + @JsonDeserialize(using = com.twilio.converter.LocalDateDeserializer.class) final LocalDate startDate, + @JsonProperty("subresource_uris") final Map subresourceUris, + @JsonProperty("uri") final String uri, + @JsonProperty("usage") final String usage, + @JsonProperty("usage_unit") final String usageUnit ) { this.accountSid = accountSid; this.apiVersion = apiVersion; @@ -140,76 +164,16 @@ private Today( this.count = count; this.countUnit = countUnit; this.description = description; - this.endDate = DateConverter.localDateFromString(endDate); + this.endDate = endDate; this.price = price; this.priceUnit = priceUnit; - this.startDate = DateConverter.localDateFromString(startDate); + this.startDate = startDate; this.subresourceUris = subresourceUris; this.uri = uri; this.usage = usage; this.usageUnit = usageUnit; } - public final String getAccountSid() { - return this.accountSid; - } - - public final String getApiVersion() { - return this.apiVersion; - } - - public final String getAsOf() { - return this.asOf; - } - - public final String getCategory() { - return this.category; - } - - public final String getCount() { - return this.count; - } - - public final String getCountUnit() { - return this.countUnit; - } - - public final String getDescription() { - return this.description; - } - - public final LocalDate getEndDate() { - return this.endDate; - } - - public final BigDecimal getPrice() { - return this.price; - } - - public final Currency getPriceUnit() { - return this.priceUnit; - } - - public final LocalDate getStartDate() { - return this.startDate; - } - - public final Map getSubresourceUris() { - return this.subresourceUris; - } - - public final String getUri() { - return this.uri; - } - - public final String getUsage() { - return this.usage; - } - - public final String getUsageUnit() { - return this.usageUnit; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -221,44 +185,46 @@ public boolean equals(final Object o) { } Today other = (Today) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(apiVersion, other.apiVersion) && - Objects.equals(asOf, other.asOf) && - Objects.equals(category, other.category) && - Objects.equals(count, other.count) && - Objects.equals(countUnit, other.countUnit) && - Objects.equals(description, other.description) && - Objects.equals(endDate, other.endDate) && - Objects.equals(price, other.price) && - Objects.equals(priceUnit, other.priceUnit) && - Objects.equals(startDate, other.startDate) && - Objects.equals(subresourceUris, other.subresourceUris) && - Objects.equals(uri, other.uri) && - Objects.equals(usage, other.usage) && - Objects.equals(usageUnit, other.usageUnit) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(apiVersion, other.apiVersion) && + Objects.equals(asOf, other.asOf) && + Objects.equals(category, other.category) && + Objects.equals(count, other.count) && + Objects.equals(countUnit, other.countUnit) && + Objects.equals(description, other.description) && + Objects.equals(endDate, other.endDate) && + Objects.equals(price, other.price) && + Objects.equals(priceUnit, other.priceUnit) && + Objects.equals(startDate, other.startDate) && + Objects.equals(subresourceUris, other.subresourceUris) && + Objects.equals(uri, other.uri) && + Objects.equals(usage, other.usage) && + Objects.equals(usageUnit, other.usageUnit) ); } @Override public int hashCode() { return Objects.hash( - accountSid, - apiVersion, - asOf, - category, - count, - countUnit, - description, - endDate, - price, - priceUnit, - startDate, - subresourceUris, - uri, - usage, - usageUnit + accountSid, + apiVersion, + asOf, + category, + count, + countUnit, + description, + endDate, + price, + priceUnit, + startDate, + subresourceUris, + uri, + usage, + usageUnit ); } + + } + diff --git a/src/main/java/com/twilio/rest/api/v2010/account/usage/record/TodayReader.java b/src/main/java/com/twilio/rest/api/v2010/account/usage/record/TodayReader.java index daac07498b..c9fe765bd7 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/usage/record/TodayReader.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/usage/record/TodayReader.java @@ -17,8 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; -import com.twilio.converter.DateConverter; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,173 +27,145 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.time.LocalDate; public class TodayReader extends Reader { - private String pathAccountSid; + private String pathaccountSid; private String category; private LocalDate startDate; private LocalDate endDate; private Boolean includeSubaccounts; private Long pageSize; - public TodayReader() {} + public TodayReader() { + } - public TodayReader(final String pathAccountSid) { - this.pathAccountSid = pathAccountSid; + public TodayReader(final String pathaccountSid) { + this.pathaccountSid = pathaccountSid; } + public TodayReader setCategory(final String category) { this.category = category; return this; } + public TodayReader setStartDate(final LocalDate startDate) { this.startDate = startDate; return this; } + public TodayReader setEndDate(final LocalDate endDate) { this.endDate = endDate; return this; } + public TodayReader setIncludeSubaccounts(final Boolean includeSubaccounts) { this.includeSubaccounts = includeSubaccounts; return this; } + public TodayReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/Usage/Records/Today.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); + + String path = "/2010-04-01/Accounts/{AccountSid}/Usage/Records/Today.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.API.toString(), - path + HttpMethod.GET, + Domains.API.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Today read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Today read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "usage_records", - response.getContent(), - Today.class, - client.getObjectMapper() - ); + "usage_records", + response.getContent(), + Today.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.API.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.API.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (category != null) { - request.addQueryParam("Category", category); + Serializer.toString(request, "Category", category, ParameterType.QUERY); } + + if (startDate != null) { - request.addQueryParam( - "StartDate", - DateConverter.dateStringFromLocalDate(startDate) - ); + Serializer.toString(request, "StartDate", startDate, ParameterType.QUERY); } + if (endDate != null) { - request.addQueryParam( - "EndDate", - DateConverter.dateStringFromLocalDate(endDate) - ); + Serializer.toString(request, "EndDate", endDate, ParameterType.QUERY); } + if (includeSubaccounts != null) { - request.addQueryParam( - "IncludeSubaccounts", - includeSubaccounts.toString() - ); + Serializer.toString(request, "IncludeSubaccounts", includeSubaccounts, ParameterType.QUERY); } + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/usage/record/Yearly.java b/src/main/java/com/twilio/rest/api/v2010/account/usage/record/Yearly.java index aea93b7084..1eb840efcd 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/usage/record/Yearly.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/usage/record/Yearly.java @@ -18,50 +18,51 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.CurrencyDeserializer; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.math.BigDecimal; import java.time.LocalDate; import java.util.Currency; import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Yearly extends Resource { - private static final long serialVersionUID = 158026917970511L; public static YearlyReader reader() { - return new YearlyReader(); + return new YearlyReader( + + ); } - public static YearlyReader reader(final String pathAccountSid) { - return new YearlyReader(pathAccountSid); + + public static YearlyReader reader(final String pathaccountSid) { + return new YearlyReader( + pathaccountSid + ); } + /** * Converts a JSON String into a Yearly object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Yearly object represented by the provided JSON */ - public static Yearly fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Yearly fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Yearly.class); @@ -76,14 +77,11 @@ public static Yearly fromJson( * Converts a JSON InputStream into a Yearly object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Yearly object represented by the provided JSON */ - public static Yearly fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Yearly fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Yearly.class); @@ -94,44 +92,70 @@ public static Yearly fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; + @Getter private final String apiVersion; + @Getter private final String asOf; + @Getter private final String category; + @Getter private final String count; + @Getter private final String countUnit; + @Getter private final String description; + @Getter private final LocalDate endDate; + @Getter private final BigDecimal price; + @Getter private final Currency priceUnit; + @Getter private final LocalDate startDate; + @Getter private final Map subresourceUris; + @Getter private final String uri; + @Getter private final String usage; + @Getter private final String usageUnit; @JsonCreator private Yearly( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("api_version") final String apiVersion, - @JsonProperty("as_of") final String asOf, - @JsonProperty("category") final String category, - @JsonProperty("count") final String count, - @JsonProperty("count_unit") final String countUnit, - @JsonProperty("description") final String description, - @JsonProperty("end_date") final String endDate, - @JsonProperty("price") final BigDecimal price, - @JsonProperty("price_unit") @JsonDeserialize( - using = com.twilio.converter.CurrencyDeserializer.class - ) final Currency priceUnit, - @JsonProperty("start_date") final String startDate, - @JsonProperty("subresource_uris") final Map< - String, - String - > subresourceUris, - @JsonProperty("uri") final String uri, - @JsonProperty("usage") final String usage, - @JsonProperty("usage_unit") final String usageUnit + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("api_version") final String apiVersion, + @JsonProperty("as_of") final String asOf, + @JsonProperty("category") final String category, + @JsonProperty("count") final String count, + @JsonProperty("count_unit") final String countUnit, + @JsonProperty("description") final String description, + @JsonProperty("end_date") + @JsonDeserialize(using = com.twilio.converter.LocalDateDeserializer.class) final LocalDate endDate, + @JsonProperty("price") final BigDecimal price, + @JsonProperty("price_unit") + @JsonDeserialize(using = com.twilio.converter.CurrencyDeserializer.class) final Currency priceUnit, + @JsonProperty("start_date") + @JsonDeserialize(using = com.twilio.converter.LocalDateDeserializer.class) final LocalDate startDate, + @JsonProperty("subresource_uris") final Map subresourceUris, + @JsonProperty("uri") final String uri, + @JsonProperty("usage") final String usage, + @JsonProperty("usage_unit") final String usageUnit ) { this.accountSid = accountSid; this.apiVersion = apiVersion; @@ -140,76 +164,16 @@ private Yearly( this.count = count; this.countUnit = countUnit; this.description = description; - this.endDate = DateConverter.localDateFromString(endDate); + this.endDate = endDate; this.price = price; this.priceUnit = priceUnit; - this.startDate = DateConverter.localDateFromString(startDate); + this.startDate = startDate; this.subresourceUris = subresourceUris; this.uri = uri; this.usage = usage; this.usageUnit = usageUnit; } - public final String getAccountSid() { - return this.accountSid; - } - - public final String getApiVersion() { - return this.apiVersion; - } - - public final String getAsOf() { - return this.asOf; - } - - public final String getCategory() { - return this.category; - } - - public final String getCount() { - return this.count; - } - - public final String getCountUnit() { - return this.countUnit; - } - - public final String getDescription() { - return this.description; - } - - public final LocalDate getEndDate() { - return this.endDate; - } - - public final BigDecimal getPrice() { - return this.price; - } - - public final Currency getPriceUnit() { - return this.priceUnit; - } - - public final LocalDate getStartDate() { - return this.startDate; - } - - public final Map getSubresourceUris() { - return this.subresourceUris; - } - - public final String getUri() { - return this.uri; - } - - public final String getUsage() { - return this.usage; - } - - public final String getUsageUnit() { - return this.usageUnit; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -221,44 +185,46 @@ public boolean equals(final Object o) { } Yearly other = (Yearly) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(apiVersion, other.apiVersion) && - Objects.equals(asOf, other.asOf) && - Objects.equals(category, other.category) && - Objects.equals(count, other.count) && - Objects.equals(countUnit, other.countUnit) && - Objects.equals(description, other.description) && - Objects.equals(endDate, other.endDate) && - Objects.equals(price, other.price) && - Objects.equals(priceUnit, other.priceUnit) && - Objects.equals(startDate, other.startDate) && - Objects.equals(subresourceUris, other.subresourceUris) && - Objects.equals(uri, other.uri) && - Objects.equals(usage, other.usage) && - Objects.equals(usageUnit, other.usageUnit) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(apiVersion, other.apiVersion) && + Objects.equals(asOf, other.asOf) && + Objects.equals(category, other.category) && + Objects.equals(count, other.count) && + Objects.equals(countUnit, other.countUnit) && + Objects.equals(description, other.description) && + Objects.equals(endDate, other.endDate) && + Objects.equals(price, other.price) && + Objects.equals(priceUnit, other.priceUnit) && + Objects.equals(startDate, other.startDate) && + Objects.equals(subresourceUris, other.subresourceUris) && + Objects.equals(uri, other.uri) && + Objects.equals(usage, other.usage) && + Objects.equals(usageUnit, other.usageUnit) ); } @Override public int hashCode() { return Objects.hash( - accountSid, - apiVersion, - asOf, - category, - count, - countUnit, - description, - endDate, - price, - priceUnit, - startDate, - subresourceUris, - uri, - usage, - usageUnit + accountSid, + apiVersion, + asOf, + category, + count, + countUnit, + description, + endDate, + price, + priceUnit, + startDate, + subresourceUris, + uri, + usage, + usageUnit ); } + + } + diff --git a/src/main/java/com/twilio/rest/api/v2010/account/usage/record/YearlyReader.java b/src/main/java/com/twilio/rest/api/v2010/account/usage/record/YearlyReader.java index 2c0d681587..71ca7a7258 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/usage/record/YearlyReader.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/usage/record/YearlyReader.java @@ -17,8 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; -import com.twilio.converter.DateConverter; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,175 +27,145 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.time.LocalDate; public class YearlyReader extends Reader { - private String pathAccountSid; + private String pathaccountSid; private String category; private LocalDate startDate; private LocalDate endDate; private Boolean includeSubaccounts; private Long pageSize; - public YearlyReader() {} + public YearlyReader() { + } - public YearlyReader(final String pathAccountSid) { - this.pathAccountSid = pathAccountSid; + public YearlyReader(final String pathaccountSid) { + this.pathaccountSid = pathaccountSid; } + public YearlyReader setCategory(final String category) { this.category = category; return this; } + public YearlyReader setStartDate(final LocalDate startDate) { this.startDate = startDate; return this; } + public YearlyReader setEndDate(final LocalDate endDate) { this.endDate = endDate; return this; } - public YearlyReader setIncludeSubaccounts( - final Boolean includeSubaccounts - ) { + + public YearlyReader setIncludeSubaccounts(final Boolean includeSubaccounts) { this.includeSubaccounts = includeSubaccounts; return this; } + public YearlyReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/Usage/Records/Yearly.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); + + String path = "/2010-04-01/Accounts/{AccountSid}/Usage/Records/Yearly.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.API.toString(), - path + HttpMethod.GET, + Domains.API.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Yearly read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Yearly read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "usage_records", - response.getContent(), - Yearly.class, - client.getObjectMapper() - ); + "usage_records", + response.getContent(), + Yearly.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.API.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.API.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (category != null) { - request.addQueryParam("Category", category); + Serializer.toString(request, "Category", category, ParameterType.QUERY); } + + if (startDate != null) { - request.addQueryParam( - "StartDate", - DateConverter.dateStringFromLocalDate(startDate) - ); + Serializer.toString(request, "StartDate", startDate, ParameterType.QUERY); } + if (endDate != null) { - request.addQueryParam( - "EndDate", - DateConverter.dateStringFromLocalDate(endDate) - ); + Serializer.toString(request, "EndDate", endDate, ParameterType.QUERY); } + if (includeSubaccounts != null) { - request.addQueryParam( - "IncludeSubaccounts", - includeSubaccounts.toString() - ); + Serializer.toString(request, "IncludeSubaccounts", includeSubaccounts, ParameterType.QUERY); } + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/api/v2010/account/usage/record/Yesterday.java b/src/main/java/com/twilio/rest/api/v2010/account/usage/record/Yesterday.java index 50d71c25ab..7c6f718fbe 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/usage/record/Yesterday.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/usage/record/Yesterday.java @@ -18,50 +18,51 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.CurrencyDeserializer; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.math.BigDecimal; import java.time.LocalDate; import java.util.Currency; import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Yesterday extends Resource { - private static final long serialVersionUID = 158026917970511L; public static YesterdayReader reader() { - return new YesterdayReader(); + return new YesterdayReader( + + ); } - public static YesterdayReader reader(final String pathAccountSid) { - return new YesterdayReader(pathAccountSid); + + public static YesterdayReader reader(final String pathaccountSid) { + return new YesterdayReader( + pathaccountSid + ); } + /** * Converts a JSON String into a Yesterday object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Yesterday object represented by the provided JSON */ - public static Yesterday fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Yesterday fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Yesterday.class); @@ -76,14 +77,11 @@ public static Yesterday fromJson( * Converts a JSON InputStream into a Yesterday object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Yesterday object represented by the provided JSON */ - public static Yesterday fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Yesterday fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Yesterday.class); @@ -94,44 +92,70 @@ public static Yesterday fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; + @Getter private final String apiVersion; + @Getter private final String asOf; + @Getter private final String category; + @Getter private final String count; + @Getter private final String countUnit; + @Getter private final String description; + @Getter private final LocalDate endDate; + @Getter private final BigDecimal price; + @Getter private final Currency priceUnit; + @Getter private final LocalDate startDate; + @Getter private final Map subresourceUris; + @Getter private final String uri; + @Getter private final String usage; + @Getter private final String usageUnit; @JsonCreator private Yesterday( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("api_version") final String apiVersion, - @JsonProperty("as_of") final String asOf, - @JsonProperty("category") final String category, - @JsonProperty("count") final String count, - @JsonProperty("count_unit") final String countUnit, - @JsonProperty("description") final String description, - @JsonProperty("end_date") final String endDate, - @JsonProperty("price") final BigDecimal price, - @JsonProperty("price_unit") @JsonDeserialize( - using = com.twilio.converter.CurrencyDeserializer.class - ) final Currency priceUnit, - @JsonProperty("start_date") final String startDate, - @JsonProperty("subresource_uris") final Map< - String, - String - > subresourceUris, - @JsonProperty("uri") final String uri, - @JsonProperty("usage") final String usage, - @JsonProperty("usage_unit") final String usageUnit + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("api_version") final String apiVersion, + @JsonProperty("as_of") final String asOf, + @JsonProperty("category") final String category, + @JsonProperty("count") final String count, + @JsonProperty("count_unit") final String countUnit, + @JsonProperty("description") final String description, + @JsonProperty("end_date") + @JsonDeserialize(using = com.twilio.converter.LocalDateDeserializer.class) final LocalDate endDate, + @JsonProperty("price") final BigDecimal price, + @JsonProperty("price_unit") + @JsonDeserialize(using = com.twilio.converter.CurrencyDeserializer.class) final Currency priceUnit, + @JsonProperty("start_date") + @JsonDeserialize(using = com.twilio.converter.LocalDateDeserializer.class) final LocalDate startDate, + @JsonProperty("subresource_uris") final Map subresourceUris, + @JsonProperty("uri") final String uri, + @JsonProperty("usage") final String usage, + @JsonProperty("usage_unit") final String usageUnit ) { this.accountSid = accountSid; this.apiVersion = apiVersion; @@ -140,76 +164,16 @@ private Yesterday( this.count = count; this.countUnit = countUnit; this.description = description; - this.endDate = DateConverter.localDateFromString(endDate); + this.endDate = endDate; this.price = price; this.priceUnit = priceUnit; - this.startDate = DateConverter.localDateFromString(startDate); + this.startDate = startDate; this.subresourceUris = subresourceUris; this.uri = uri; this.usage = usage; this.usageUnit = usageUnit; } - public final String getAccountSid() { - return this.accountSid; - } - - public final String getApiVersion() { - return this.apiVersion; - } - - public final String getAsOf() { - return this.asOf; - } - - public final String getCategory() { - return this.category; - } - - public final String getCount() { - return this.count; - } - - public final String getCountUnit() { - return this.countUnit; - } - - public final String getDescription() { - return this.description; - } - - public final LocalDate getEndDate() { - return this.endDate; - } - - public final BigDecimal getPrice() { - return this.price; - } - - public final Currency getPriceUnit() { - return this.priceUnit; - } - - public final LocalDate getStartDate() { - return this.startDate; - } - - public final Map getSubresourceUris() { - return this.subresourceUris; - } - - public final String getUri() { - return this.uri; - } - - public final String getUsage() { - return this.usage; - } - - public final String getUsageUnit() { - return this.usageUnit; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -221,44 +185,46 @@ public boolean equals(final Object o) { } Yesterday other = (Yesterday) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(apiVersion, other.apiVersion) && - Objects.equals(asOf, other.asOf) && - Objects.equals(category, other.category) && - Objects.equals(count, other.count) && - Objects.equals(countUnit, other.countUnit) && - Objects.equals(description, other.description) && - Objects.equals(endDate, other.endDate) && - Objects.equals(price, other.price) && - Objects.equals(priceUnit, other.priceUnit) && - Objects.equals(startDate, other.startDate) && - Objects.equals(subresourceUris, other.subresourceUris) && - Objects.equals(uri, other.uri) && - Objects.equals(usage, other.usage) && - Objects.equals(usageUnit, other.usageUnit) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(apiVersion, other.apiVersion) && + Objects.equals(asOf, other.asOf) && + Objects.equals(category, other.category) && + Objects.equals(count, other.count) && + Objects.equals(countUnit, other.countUnit) && + Objects.equals(description, other.description) && + Objects.equals(endDate, other.endDate) && + Objects.equals(price, other.price) && + Objects.equals(priceUnit, other.priceUnit) && + Objects.equals(startDate, other.startDate) && + Objects.equals(subresourceUris, other.subresourceUris) && + Objects.equals(uri, other.uri) && + Objects.equals(usage, other.usage) && + Objects.equals(usageUnit, other.usageUnit) ); } @Override public int hashCode() { return Objects.hash( - accountSid, - apiVersion, - asOf, - category, - count, - countUnit, - description, - endDate, - price, - priceUnit, - startDate, - subresourceUris, - uri, - usage, - usageUnit + accountSid, + apiVersion, + asOf, + category, + count, + countUnit, + description, + endDate, + price, + priceUnit, + startDate, + subresourceUris, + uri, + usage, + usageUnit ); } + + } + diff --git a/src/main/java/com/twilio/rest/api/v2010/account/usage/record/YesterdayReader.java b/src/main/java/com/twilio/rest/api/v2010/account/usage/record/YesterdayReader.java index 08ea9f7fe9..ecd6e33813 100644 --- a/src/main/java/com/twilio/rest/api/v2010/account/usage/record/YesterdayReader.java +++ b/src/main/java/com/twilio/rest/api/v2010/account/usage/record/YesterdayReader.java @@ -17,8 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; -import com.twilio.converter.DateConverter; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,175 +27,145 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.time.LocalDate; public class YesterdayReader extends Reader { - private String pathAccountSid; + private String pathaccountSid; private String category; private LocalDate startDate; private LocalDate endDate; private Boolean includeSubaccounts; private Long pageSize; - public YesterdayReader() {} + public YesterdayReader() { + } - public YesterdayReader(final String pathAccountSid) { - this.pathAccountSid = pathAccountSid; + public YesterdayReader(final String pathaccountSid) { + this.pathaccountSid = pathaccountSid; } + public YesterdayReader setCategory(final String category) { this.category = category; return this; } + public YesterdayReader setStartDate(final LocalDate startDate) { this.startDate = startDate; return this; } + public YesterdayReader setEndDate(final LocalDate endDate) { this.endDate = endDate; return this; } - public YesterdayReader setIncludeSubaccounts( - final Boolean includeSubaccounts - ) { + + public YesterdayReader setIncludeSubaccounts(final Boolean includeSubaccounts) { this.includeSubaccounts = includeSubaccounts; return this; } + public YesterdayReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { - String path = - "/2010-04-01/Accounts/{AccountSid}/Usage/Records/Yesterday.json"; - this.pathAccountSid = - this.pathAccountSid == null - ? client.getAccountSid() - : this.pathAccountSid; - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); + + String path = "/2010-04-01/Accounts/{AccountSid}/Usage/Records/Yesterday.json"; + + this.pathaccountSid = this.pathaccountSid == null ? client.getAccountSid() : this.pathaccountSid; + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.API.toString(), - path + HttpMethod.GET, + Domains.API.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Yesterday read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Yesterday read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "usage_records", - response.getContent(), - Yesterday.class, - client.getObjectMapper() - ); + "usage_records", + response.getContent(), + Yesterday.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.API.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.API.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (category != null) { - request.addQueryParam("Category", category); + Serializer.toString(request, "Category", category, ParameterType.QUERY); } + + if (startDate != null) { - request.addQueryParam( - "StartDate", - DateConverter.dateStringFromLocalDate(startDate) - ); + Serializer.toString(request, "StartDate", startDate, ParameterType.QUERY); } + if (endDate != null) { - request.addQueryParam( - "EndDate", - DateConverter.dateStringFromLocalDate(endDate) - ); + Serializer.toString(request, "EndDate", endDate, ParameterType.QUERY); } + if (includeSubaccounts != null) { - request.addQueryParam( - "IncludeSubaccounts", - includeSubaccounts.toString() - ); + Serializer.toString(request, "IncludeSubaccounts", includeSubaccounts, ParameterType.QUERY); } + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/assistants/v1/Assistant.java b/src/main/java/com/twilio/rest/assistants/v1/Assistant.java index 0c4ed48947..712911ab15 100644 --- a/src/main/java/com/twilio/rest/assistants/v1/Assistant.java +++ b/src/main/java/com/twilio/rest/assistants/v1/Assistant.java @@ -22,134 +22,171 @@ import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.time.ZonedDateTime; import java.util.List; -import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.Getter; -import lombok.Setter; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Assistant extends Resource { - private static final long serialVersionUID = 5177924616338L; + public static AssistantCreator creator(final Assistant.AssistantsV1ServiceCreateAssistantRequest assistantsV1ServiceCreateAssistantRequest) { + return new AssistantCreator( + assistantsV1ServiceCreateAssistantRequest + ); + } + + + public static AssistantDeleter deleter(final String pathid) { + return new AssistantDeleter( + pathid + ); + } + + + public static AssistantFetcher fetcher(final String pathid) { + return new AssistantFetcher( + pathid + ); + } + + + public static AssistantReader reader() { + return new AssistantReader( + + ); + } + + + public static AssistantUpdater updater(final String pathid) { + return new AssistantUpdater( + pathid + ); + } + + + //@JsonDeserialize(builder = AssistantsV1ServiceTool.Builder.class) + @JsonInclude(JsonInclude.Include.NON_EMPTY) @ToString - public static class AssistantsV1ServiceCustomerAi { + public static class AssistantsV1ServiceTool { + public AssistantsV1ServiceTool(final String description, final Boolean enabled, final String id, final Object meta, final String name, final Boolean requiresAuth, final String type, final ZonedDateTime dateCreated, final ZonedDateTime dateUpdated) { + this.description = description; + this.enabled = enabled; + this.id = id; + this.meta = meta; + this.name = name; + this.requiresAuth = requiresAuth; + this.type = type; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; + } @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("perception_engine_enabled") + @JsonProperty("account_sid") @Getter @Setter - private Boolean perceptionEngineEnabled; + private String accountSid; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("personalization_engine_enabled") + @JsonProperty("description") @Getter @Setter - private Boolean personalizationEngineEnabled; - - public static AssistantsV1ServiceCustomerAi fromJson( - String jsonString, - ObjectMapper mapper - ) throws IOException { - return mapper.readValue( - jsonString, - AssistantsV1ServiceCustomerAi.class - ); - } - } - - @ToString - public static class AssistantsV1ServiceSegmentCredential { + private String description; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("profile_api_key") + @JsonProperty("enabled") @Getter @Setter - private String profileApiKey; + private Boolean enabled; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("space_id") + @JsonProperty("id") @Getter @Setter - private String spaceId; + private String id; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("write_key") + @JsonProperty("meta") @Getter @Setter - private String writeKey; - - public static AssistantsV1ServiceSegmentCredential fromJson( - String jsonString, - ObjectMapper mapper - ) throws IOException { - return mapper.readValue( - jsonString, - AssistantsV1ServiceSegmentCredential.class - ); - } - } + private Object meta; - @ToString - public static class AssistantsV1ServiceCreateAssistantRequest { + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("name") + @Getter + @Setter + private String name; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("customer_ai") + @JsonProperty("requires_auth") @Getter @Setter - private AssistantsV1ServiceCustomerAi customerAi; + private Boolean requiresAuth; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("name") + @JsonProperty("type") @Getter @Setter - private String name; + private String type; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("owner") + @JsonProperty("url") @Getter @Setter - private String owner; + private String url; + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("personality_prompt") + @JsonProperty("date_created") @Getter @Setter - private String personalityPrompt; + private ZonedDateTime dateCreated; + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("segment_credential") + @JsonProperty("date_updated") @Getter @Setter - private AssistantsV1ServiceSegmentCredential segmentCredential; + private ZonedDateTime dateUpdated; - public AssistantsV1ServiceCreateAssistantRequest(final String name) { - this.name = name; - } + } - public static AssistantsV1ServiceCreateAssistantRequest fromJson( - String jsonString, - ObjectMapper mapper - ) throws IOException { - return mapper.readValue( - jsonString, - AssistantsV1ServiceCreateAssistantRequest.class - ); + //@JsonDeserialize(builder = AssistantsV1ServiceCustomerAi.Builder.class) + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @ToString + public static class AssistantsV1ServiceCustomerAi { + public AssistantsV1ServiceCustomerAi(final Boolean perceptionEngineEnabled, final Boolean personalizationEngineEnabled) { + this.perceptionEngineEnabled = perceptionEngineEnabled; + this.personalizationEngineEnabled = personalizationEngineEnabled; } + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("perception_engine_enabled") + @Getter + @Setter + private Boolean perceptionEngineEnabled; + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("personalization_engine_enabled") + @Getter + @Setter + private Boolean personalizationEngineEnabled; + } + //@JsonDeserialize(builder = AssistantsV1ServiceUpdateAssistantRequest.Builder.class) + @JsonInclude(JsonInclude.Include.NON_EMPTY) @ToString public static class AssistantsV1ServiceUpdateAssistantRequest { @@ -183,45 +220,21 @@ public static class AssistantsV1ServiceUpdateAssistantRequest { @Setter private AssistantsV1ServiceSegmentCredential segmentCredential; - public AssistantsV1ServiceUpdateAssistantRequest() {} - - public static AssistantsV1ServiceUpdateAssistantRequest fromJson( - String jsonString, - ObjectMapper mapper - ) throws IOException { - return mapper.readValue( - jsonString, - AssistantsV1ServiceUpdateAssistantRequest.class - ); - } } + //@JsonDeserialize(builder = AssistantsV1ServiceCreateAssistantRequest.Builder.class) + @JsonInclude(JsonInclude.Include.NON_EMPTY) @ToString - public static class AssistantsV1ServiceKnowledge { - - @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("description") - @Getter - @Setter - private String description; - - @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("id") - @Getter - @Setter - private String id; - - @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("account_sid") - @Getter - @Setter - private String accountSid; + public static class AssistantsV1ServiceCreateAssistantRequest { + public AssistantsV1ServiceCreateAssistantRequest(final String name) { + this.name = name; + } @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("knowledge_source_details") + @JsonProperty("customer_ai") @Getter @Setter - private Map knowledgeSourceDetails; + private AssistantsV1ServiceCustomerAi customerAi; @JsonInclude(JsonInclude.Include.NON_EMPTY) @JsonProperty("name") @@ -230,68 +243,61 @@ public static class AssistantsV1ServiceKnowledge { private String name; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("status") + @JsonProperty("owner") @Getter @Setter - private String status; + private String owner; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("type") + @JsonProperty("personality_prompt") @Getter @Setter - private String type; + private String personalityPrompt; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("url") + @JsonProperty("segment_credential") @Getter @Setter - private String url; + private AssistantsV1ServiceSegmentCredential segmentCredential; + + } + + //@JsonDeserialize(builder = AssistantsV1ServiceSegmentCredential.Builder.class) + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @ToString + public static class AssistantsV1ServiceSegmentCredential { @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("embedding_model") + @JsonProperty("profile_api_key") @Getter @Setter - private String embeddingModel; + private String profileApiKey; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("date_created") + @JsonProperty("space_id") @Getter @Setter - private ZonedDateTime dateCreated; - - public String getDateCreated() { - return dateCreated.toInstant().toString(); - } + private String spaceId; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("date_updated") + @JsonProperty("write_key") @Getter @Setter - private ZonedDateTime dateUpdated; - - public String getDateUpdated() { - return dateUpdated.toInstant().toString(); - } + private String writeKey; - public static AssistantsV1ServiceKnowledge fromJson( - String jsonString, - ObjectMapper mapper - ) throws IOException { - return mapper.readValue( - jsonString, - AssistantsV1ServiceKnowledge.class - ); - } } + //@JsonDeserialize(builder = AssistantsV1ServiceKnowledge.Builder.class) + @JsonInclude(JsonInclude.Include.NON_EMPTY) @ToString - public static class AssistantsV1ServiceTool { - - @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("account_sid") - @Getter - @Setter - private String accountSid; + public static class AssistantsV1ServiceKnowledge { + public AssistantsV1ServiceKnowledge(final String id, final String name, final String type, final ZonedDateTime dateCreated, final ZonedDateTime dateUpdated) { + this.id = id; + this.name = name; + this.type = type; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; + } @JsonInclude(JsonInclude.Include.NON_EMPTY) @JsonProperty("description") @@ -300,22 +306,22 @@ public static class AssistantsV1ServiceTool { private String description; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("enabled") + @JsonProperty("id") @Getter @Setter - private Boolean enabled; + private String id; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("id") + @JsonProperty("account_sid") @Getter @Setter - private String id; + private String accountSid; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("meta") + @JsonProperty("knowledge_source_details") @Getter @Setter - private Map meta; + private Object knowledgeSourceDetails; @JsonInclude(JsonInclude.Include.NON_EMPTY) @JsonProperty("name") @@ -324,10 +330,10 @@ public static class AssistantsV1ServiceTool { private String name; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("requires_auth") + @JsonProperty("status") @Getter @Setter - private Boolean requiresAuth; + private String status; @JsonInclude(JsonInclude.Include.NON_EMPTY) @JsonProperty("type") @@ -341,67 +347,36 @@ public static class AssistantsV1ServiceTool { @Setter private String url; + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("embedding_model") + @Getter + @Setter + private String embeddingModel; + + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) @JsonInclude(JsonInclude.Include.NON_EMPTY) @JsonProperty("date_created") @Getter @Setter private ZonedDateTime dateCreated; - public String getDateCreated() { - return dateCreated.toInstant().toString(); - } - + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) @JsonInclude(JsonInclude.Include.NON_EMPTY) @JsonProperty("date_updated") @Getter @Setter private ZonedDateTime dateUpdated; - public String getDateUpdated() { - return dateUpdated.toInstant().toString(); - } - - public static AssistantsV1ServiceTool fromJson( - String jsonString, - ObjectMapper mapper - ) throws IOException { - return mapper.readValue(jsonString, AssistantsV1ServiceTool.class); - } - } - - public static AssistantCreator creator( - final Assistant.AssistantsV1ServiceCreateAssistantRequest assistantsV1ServiceCreateAssistantRequest - ) { - return new AssistantCreator(assistantsV1ServiceCreateAssistantRequest); - } - - public static AssistantDeleter deleter(final String pathId) { - return new AssistantDeleter(pathId); - } - - public static AssistantFetcher fetcher(final String pathId) { - return new AssistantFetcher(pathId); - } - - public static AssistantReader reader() { - return new AssistantReader(); - } - - public static AssistantUpdater updater(final String pathId) { - return new AssistantUpdater(pathId); } /** * Converts a JSON String into a Assistant object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Assistant object represented by the provided JSON */ - public static Assistant fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Assistant fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Assistant.class); @@ -416,14 +391,11 @@ public static Assistant fromJson( * Converts a JSON InputStream into a Assistant object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Assistant object represented by the provided JSON */ - public static Assistant fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Assistant fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Assistant.class); @@ -446,96 +418,61 @@ public static String toJson(Object object, ObjectMapper mapper) { } } + + @Getter private final String accountSid; - private final Map customerAi; + @Getter + private final Object customerAi; + @Getter + private final ZonedDateTime dateCreated; + @Getter + private final ZonedDateTime dateUpdated; + @Getter private final String id; + @Getter + private final List knowledge; + @Getter private final String model; + @Getter private final String name; + @Getter private final String owner; - private final String url; + @Getter private final String personalityPrompt; - private final ZonedDateTime dateCreated; - private final ZonedDateTime dateUpdated; - private final List knowledge; + @Getter private final List tools; + @Getter + private final String url; @JsonCreator private Assistant( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("customer_ai") final Map customerAi, - @JsonProperty("id") final String id, - @JsonProperty("model") final String model, - @JsonProperty("name") final String name, - @JsonProperty("owner") final String owner, - @JsonProperty("url") final String url, - @JsonProperty("personality_prompt") final String personalityPrompt, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("knowledge") final List< - AssistantsV1ServiceKnowledge - > knowledge, - @JsonProperty("tools") final List tools + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("customer_ai") final Object customerAi, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("id") final String id, + @JsonProperty("knowledge") final List knowledge, + @JsonProperty("model") final String model, + @JsonProperty("name") final String name, + @JsonProperty("owner") final String owner, + @JsonProperty("personality_prompt") final String personalityPrompt, + @JsonProperty("tools") final List tools, + @JsonProperty("url") final String url ) { this.accountSid = accountSid; this.customerAi = customerAi; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.id = id; + this.knowledge = knowledge; this.model = model; this.name = name; this.owner = owner; - this.url = url; this.personalityPrompt = personalityPrompt; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); - this.knowledge = knowledge; this.tools = tools; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final Map getCustomerAi() { - return this.customerAi; - } - - public final String getId() { - return this.id; - } - - public final String getModel() { - return this.model; - } - - public final String getName() { - return this.name; - } - - public final String getOwner() { - return this.owner; - } - - public final String getUrl() { - return this.url; - } - - public final String getPersonalityPrompt() { - return this.personalityPrompt; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final List getKnowledge() { - return this.knowledge; - } - - public final List getTools() { - return this.tools; + this.url = url; } @Override @@ -549,38 +486,40 @@ public boolean equals(final Object o) { } Assistant other = (Assistant) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(customerAi, other.customerAi) && - Objects.equals(id, other.id) && - Objects.equals(model, other.model) && - Objects.equals(name, other.name) && - Objects.equals(owner, other.owner) && - Objects.equals(url, other.url) && - Objects.equals(personalityPrompt, other.personalityPrompt) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(knowledge, other.knowledge) && - Objects.equals(tools, other.tools) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(customerAi, other.customerAi) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(id, other.id) && + Objects.equals(knowledge, other.knowledge) && + Objects.equals(model, other.model) && + Objects.equals(name, other.name) && + Objects.equals(owner, other.owner) && + Objects.equals(personalityPrompt, other.personalityPrompt) && + Objects.equals(tools, other.tools) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - accountSid, - customerAi, - id, - model, - name, - owner, - url, - personalityPrompt, - dateCreated, - dateUpdated, - knowledge, - tools + accountSid, + customerAi, + dateCreated, + dateUpdated, + id, + knowledge, + model, + name, + owner, + personalityPrompt, + tools, + url ); } + + } + diff --git a/src/main/java/com/twilio/rest/assistants/v1/AssistantCreator.java b/src/main/java/com/twilio/rest/assistants/v1/AssistantCreator.java index 255b68ce0a..42fdce7fc7 100644 --- a/src/main/java/com/twilio/rest/assistants/v1/AssistantCreator.java +++ b/src/main/java/com/twilio/rest/assistants/v1/AssistantCreator.java @@ -30,72 +30,53 @@ public class AssistantCreator extends Creator { private Assistant.AssistantsV1ServiceCreateAssistantRequest assistantsV1ServiceCreateAssistantRequest; - public AssistantCreator( - final Assistant.AssistantsV1ServiceCreateAssistantRequest assistantsV1ServiceCreateAssistantRequest - ) { - this.assistantsV1ServiceCreateAssistantRequest = - assistantsV1ServiceCreateAssistantRequest; + public AssistantCreator(final Assistant.AssistantsV1ServiceCreateAssistantRequest assistantsV1ServiceCreateAssistantRequest) { + this.assistantsV1ServiceCreateAssistantRequest = assistantsV1ServiceCreateAssistantRequest; } - public AssistantCreator setAssistantsV1ServiceCreateAssistantRequest( - final Assistant.AssistantsV1ServiceCreateAssistantRequest assistantsV1ServiceCreateAssistantRequest - ) { - this.assistantsV1ServiceCreateAssistantRequest = - assistantsV1ServiceCreateAssistantRequest; + + public AssistantCreator setAssistantsV1ServiceCreateAssistantRequest(final Assistant.AssistantsV1ServiceCreateAssistantRequest assistantsV1ServiceCreateAssistantRequest) { + this.assistantsV1ServiceCreateAssistantRequest = assistantsV1ServiceCreateAssistantRequest; return this; } + @Override public Assistant create(final TwilioRestClient client) { + String path = "/v1/Assistants"; - path = - path.replace( - "{" + "AssistantsV1ServiceCreateAssistantRequest" + "}", - this.assistantsV1ServiceCreateAssistantRequest.toString() - ); Request request = new Request( - HttpMethod.POST, - Domains.ASSISTANTS.toString(), - path + HttpMethod.POST, + Domains.ASSISTANTS.toString(), + path ); request.setContentType(EnumConstants.ContentType.JSON); addPostParams(request, client); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Assistant creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("Assistant creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Assistant.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Assistant.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request, TwilioRestClient client) { ObjectMapper objectMapper = client.getObjectMapper(); if (assistantsV1ServiceCreateAssistantRequest != null) { - request.setBody( - Assistant.toJson( - assistantsV1ServiceCreateAssistantRequest, - objectMapper - ) - ); + request.setBody(Assistant.toJson(assistantsV1ServiceCreateAssistantRequest, objectMapper)); } } } diff --git a/src/main/java/com/twilio/rest/assistants/v1/AssistantDeleter.java b/src/main/java/com/twilio/rest/assistants/v1/AssistantDeleter.java index fdac762673..0cf606ec49 100644 --- a/src/main/java/com/twilio/rest/assistants/v1/AssistantDeleter.java +++ b/src/main/java/com/twilio/rest/assistants/v1/AssistantDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.assistants.v1; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,40 +26,38 @@ public class AssistantDeleter extends Deleter { - private String pathId; + private String pathid; - public AssistantDeleter(final String pathId) { - this.pathId = pathId; + public AssistantDeleter(final String pathid) { + this.pathid = pathid; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/v1/Assistants/{id}"; - path = path.replace("{" + "id" + "}", this.pathId.toString()); + path = path.replace("{" + "id" + "}", this.pathid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.ASSISTANTS.toString(), - path + HttpMethod.DELETE, + Domains.ASSISTANTS.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Assistant delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("Assistant delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/assistants/v1/AssistantFetcher.java b/src/main/java/com/twilio/rest/assistants/v1/AssistantFetcher.java index f05d4ed235..6c76ab2a7f 100644 --- a/src/main/java/com/twilio/rest/assistants/v1/AssistantFetcher.java +++ b/src/main/java/com/twilio/rest/assistants/v1/AssistantFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.assistants.v1; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,47 +26,41 @@ public class AssistantFetcher extends Fetcher { - private String pathId; + private String pathid; - public AssistantFetcher(final String pathId) { - this.pathId = pathId; + public AssistantFetcher(final String pathid) { + this.pathid = pathid; } + @Override public Assistant fetch(final TwilioRestClient client) { + String path = "/v1/Assistants/{id}"; - path = path.replace("{" + "id" + "}", this.pathId.toString()); + path = path.replace("{" + "id" + "}", this.pathid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.ASSISTANTS.toString(), - path + HttpMethod.GET, + Domains.ASSISTANTS.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Assistant fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Assistant fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return Assistant.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Assistant.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/assistants/v1/AssistantReader.java b/src/main/java/com/twilio/rest/assistants/v1/AssistantReader.java index 3ab3635317..7c2d02d55e 100644 --- a/src/main/java/com/twilio/rest/assistants/v1/AssistantReader.java +++ b/src/main/java/com/twilio/rest/assistants/v1/AssistantReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -31,105 +32,83 @@ public class AssistantReader extends Reader { private Integer pageSize; - public AssistantReader() {} + public AssistantReader() { + } + public AssistantReader setPageSize(final Integer pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/Assistants"; + Request request = new Request( - HttpMethod.GET, - Domains.ASSISTANTS.toString(), - path + HttpMethod.GET, + Domains.ASSISTANTS.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Assistant read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Assistant read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "assistants", - response.getContent(), - Assistant.class, - client.getObjectMapper() - ); + "assistants", + response.getContent(), + Assistant.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.ASSISTANTS.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.ASSISTANTS.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/assistants/v1/AssistantUpdater.java b/src/main/java/com/twilio/rest/assistants/v1/AssistantUpdater.java index dd27f7c127..e397227a8a 100644 --- a/src/main/java/com/twilio/rest/assistants/v1/AssistantUpdater.java +++ b/src/main/java/com/twilio/rest/assistants/v1/AssistantUpdater.java @@ -27,69 +27,58 @@ import com.twilio.rest.Domains; public class AssistantUpdater extends Updater { - - private String pathId; + private String pathid; private Assistant.AssistantsV1ServiceUpdateAssistantRequest assistantsV1ServiceUpdateAssistantRequest; - public AssistantUpdater(final String pathId) { - this.pathId = pathId; + public AssistantUpdater(final String pathid) { + this.pathid = pathid; } - public AssistantUpdater setAssistantsV1ServiceUpdateAssistantRequest( - final Assistant.AssistantsV1ServiceUpdateAssistantRequest assistantsV1ServiceUpdateAssistantRequest - ) { - this.assistantsV1ServiceUpdateAssistantRequest = - assistantsV1ServiceUpdateAssistantRequest; + + public AssistantUpdater setAssistantsV1ServiceUpdateAssistantRequest(final Assistant.AssistantsV1ServiceUpdateAssistantRequest assistantsV1ServiceUpdateAssistantRequest) { + this.assistantsV1ServiceUpdateAssistantRequest = assistantsV1ServiceUpdateAssistantRequest; return this; } + @Override public Assistant update(final TwilioRestClient client) { + String path = "/v1/Assistants/{id}"; - path = path.replace("{" + "id" + "}", this.pathId.toString()); + path = path.replace("{" + "id" + "}", this.pathid.toString()); + Request request = new Request( - HttpMethod.PUT, - Domains.ASSISTANTS.toString(), - path + HttpMethod.PUT, + Domains.ASSISTANTS.toString(), + path ); request.setContentType(EnumConstants.ContentType.JSON); addPostParams(request, client); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Assistant update failed: Unable to connect to server" - ); + throw new ApiConnectionException("Assistant update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Assistant.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Assistant.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request, TwilioRestClient client) { ObjectMapper objectMapper = client.getObjectMapper(); if (assistantsV1ServiceUpdateAssistantRequest != null) { - request.setBody( - Assistant.toJson( - assistantsV1ServiceUpdateAssistantRequest, - objectMapper - ) - ); + request.setBody(Assistant.toJson(assistantsV1ServiceUpdateAssistantRequest, objectMapper)); } } } diff --git a/src/main/java/com/twilio/rest/assistants/v1/Knowledge.java b/src/main/java/com/twilio/rest/assistants/v1/Knowledge.java index a899609713..fff991d1f5 100644 --- a/src/main/java/com/twilio/rest/assistants/v1/Knowledge.java +++ b/src/main/java/com/twilio/rest/assistants/v1/Knowledge.java @@ -22,29 +22,63 @@ import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.time.ZonedDateTime; -import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.Getter; -import lombok.Setter; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Knowledge extends Resource { - private static final long serialVersionUID = 142704301669097L; + public static KnowledgeCreator creator(final Knowledge.AssistantsV1ServiceCreateKnowledgeRequest assistantsV1ServiceCreateKnowledgeRequest) { + return new KnowledgeCreator( + assistantsV1ServiceCreateKnowledgeRequest + ); + } + + + public static KnowledgeDeleter deleter(final String pathid) { + return new KnowledgeDeleter( + pathid + ); + } + + + public static KnowledgeFetcher fetcher(final String pathid) { + return new KnowledgeFetcher( + pathid + ); + } + + + public static KnowledgeReader reader() { + return new KnowledgeReader( + + ); + } + + + public static KnowledgeUpdater updater(final String pathid) { + return new KnowledgeUpdater( + pathid + ); + } + + + //@JsonDeserialize(builder = AssistantsV1ServiceUpdateKnowledgeRequest.Builder.class) + @JsonInclude(JsonInclude.Include.NON_EMPTY) @ToString - public static class AssistantsV1ServiceCreatePolicyRequest { + public static class AssistantsV1ServiceUpdateKnowledgeRequest { @JsonInclude(JsonInclude.Include.NON_EMPTY) @JsonProperty("description") @@ -53,10 +87,10 @@ public static class AssistantsV1ServiceCreatePolicyRequest { private String description; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("id") + @JsonProperty("knowledge_source_details") @Getter @Setter - private String id; + private Object knowledgeSourceDetails; @JsonInclude(JsonInclude.Include.NON_EMPTY) @JsonProperty("name") @@ -65,10 +99,10 @@ public static class AssistantsV1ServiceCreatePolicyRequest { private String name; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("policy_details") + @JsonProperty("policy") @Getter @Setter - private Object policyDetails; + private AssistantsV1ServiceCreatePolicyRequest policy; @JsonInclude(JsonInclude.Include.NON_EMPTY) @JsonProperty("type") @@ -76,25 +110,21 @@ public static class AssistantsV1ServiceCreatePolicyRequest { @Setter private String type; - public static AssistantsV1ServiceCreatePolicyRequest fromJson( - String jsonString, - ObjectMapper mapper - ) throws IOException { - return mapper.readValue( - jsonString, - AssistantsV1ServiceCreatePolicyRequest.class - ); - } - } - - @ToString - public static class AssistantsV1ServiceCreateKnowledgeRequest { - @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("assistant_id") + @JsonProperty("embedding_model") @Getter @Setter - private String assistantId; + private String embeddingModel; + + } + + //@JsonDeserialize(builder = AssistantsV1ServiceCreatePolicyRequest.Builder.class) + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @ToString + public static class AssistantsV1ServiceCreatePolicyRequest { + public AssistantsV1ServiceCreatePolicyRequest(final Object policyDetails) { + this.policyDetails = policyDetails; + } @JsonInclude(JsonInclude.Include.NON_EMPTY) @JsonProperty("description") @@ -103,10 +133,10 @@ public static class AssistantsV1ServiceCreateKnowledgeRequest { private String description; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("knowledge_source_details") + @JsonProperty("id") @Getter @Setter - private Map knowledgeSourceDetails; + private String id; @JsonInclude(JsonInclude.Include.NON_EMPTY) @JsonProperty("name") @@ -115,10 +145,10 @@ public static class AssistantsV1ServiceCreateKnowledgeRequest { private String name; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("policy") + @JsonProperty("policy_details") @Getter @Setter - private AssistantsV1ServiceCreatePolicyRequest policy; + private Object policyDetails; @JsonInclude(JsonInclude.Include.NON_EMPTY) @JsonProperty("type") @@ -126,33 +156,22 @@ public static class AssistantsV1ServiceCreateKnowledgeRequest { @Setter private String type; - @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("embedding_model") - @Getter - @Setter - private String embeddingModel; + } - public AssistantsV1ServiceCreateKnowledgeRequest( - final String name, - final String type - ) { + //@JsonDeserialize(builder = AssistantsV1ServiceCreateKnowledgeRequest.Builder.class) + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @ToString + public static class AssistantsV1ServiceCreateKnowledgeRequest { + public AssistantsV1ServiceCreateKnowledgeRequest(final String name, final String type) { this.name = name; this.type = type; } - public static AssistantsV1ServiceCreateKnowledgeRequest fromJson( - String jsonString, - ObjectMapper mapper - ) throws IOException { - return mapper.readValue( - jsonString, - AssistantsV1ServiceCreateKnowledgeRequest.class - ); - } - } - - @ToString - public static class AssistantsV1ServiceUpdateKnowledgeRequest { + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("assistant_id") + @Getter + @Setter + private String assistantId; @JsonInclude(JsonInclude.Include.NON_EMPTY) @JsonProperty("description") @@ -164,7 +183,7 @@ public static class AssistantsV1ServiceUpdateKnowledgeRequest { @JsonProperty("knowledge_source_details") @Getter @Setter - private Map knowledgeSourceDetails; + private Object knowledgeSourceDetails; @JsonInclude(JsonInclude.Include.NON_EMPTY) @JsonProperty("name") @@ -190,52 +209,16 @@ public static class AssistantsV1ServiceUpdateKnowledgeRequest { @Setter private String embeddingModel; - public AssistantsV1ServiceUpdateKnowledgeRequest() {} - - public static AssistantsV1ServiceUpdateKnowledgeRequest fromJson( - String jsonString, - ObjectMapper mapper - ) throws IOException { - return mapper.readValue( - jsonString, - AssistantsV1ServiceUpdateKnowledgeRequest.class - ); - } - } - - public static KnowledgeCreator creator( - final Knowledge.AssistantsV1ServiceCreateKnowledgeRequest assistantsV1ServiceCreateKnowledgeRequest - ) { - return new KnowledgeCreator(assistantsV1ServiceCreateKnowledgeRequest); - } - - public static KnowledgeDeleter deleter(final String pathId) { - return new KnowledgeDeleter(pathId); - } - - public static KnowledgeFetcher fetcher(final String pathId) { - return new KnowledgeFetcher(pathId); - } - - public static KnowledgeReader reader() { - return new KnowledgeReader(); - } - - public static KnowledgeUpdater updater(final String pathId) { - return new KnowledgeUpdater(pathId); } /** * Converts a JSON String into a Knowledge object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Knowledge object represented by the provided JSON */ - public static Knowledge fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Knowledge fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Knowledge.class); @@ -250,14 +233,11 @@ public static Knowledge fromJson( * Converts a JSON InputStream into a Knowledge object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Knowledge object represented by the provided JSON */ - public static Knowledge fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Knowledge fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Knowledge.class); @@ -280,90 +260,57 @@ public static String toJson(Object object, ObjectMapper mapper) { } } + + @Getter + private final String accountSid; + @Getter + private final ZonedDateTime dateCreated; + @Getter + private final ZonedDateTime dateUpdated; + @Getter private final String description; + @Getter + private final String embeddingModel; + @Getter private final String id; - private final String accountSid; - private final Map knowledgeSourceDetails; + @Getter + private final Object knowledgeSourceDetails; + @Getter private final String name; + @Getter private final String status; + @Getter private final String type; + @Getter private final String url; - private final String embeddingModel; - private final ZonedDateTime dateCreated; - private final ZonedDateTime dateUpdated; @JsonCreator private Knowledge( - @JsonProperty("description") final String description, - @JsonProperty("id") final String id, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("knowledge_source_details") final Map< - String, - Object - > knowledgeSourceDetails, - @JsonProperty("name") final String name, - @JsonProperty("status") final String status, - @JsonProperty("type") final String type, - @JsonProperty("url") final String url, - @JsonProperty("embedding_model") final String embeddingModel, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("description") final String description, + @JsonProperty("embedding_model") final String embeddingModel, + @JsonProperty("id") final String id, + @JsonProperty("knowledge_source_details") final Object knowledgeSourceDetails, + @JsonProperty("name") final String name, + @JsonProperty("status") final String status, + @JsonProperty("type") final String type, + @JsonProperty("url") final String url ) { + this.accountSid = accountSid; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.description = description; + this.embeddingModel = embeddingModel; this.id = id; - this.accountSid = accountSid; this.knowledgeSourceDetails = knowledgeSourceDetails; this.name = name; this.status = status; this.type = type; this.url = url; - this.embeddingModel = embeddingModel; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); - } - - public final String getDescription() { - return this.description; - } - - public final String getId() { - return this.id; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final Map getKnowledgeSourceDetails() { - return this.knowledgeSourceDetails; - } - - public final String getName() { - return this.name; - } - - public final String getStatus() { - return this.status; - } - - public final String getType() { - return this.type; - } - - public final String getUrl() { - return this.url; - } - - public final String getEmbeddingModel() { - return this.embeddingModel; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; } @Override @@ -377,39 +324,38 @@ public boolean equals(final Object o) { } Knowledge other = (Knowledge) o; - return ( - Objects.equals(description, other.description) && - Objects.equals(id, other.id) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals( - knowledgeSourceDetails, - other.knowledgeSourceDetails - ) && - Objects.equals(name, other.name) && - Objects.equals(status, other.status) && - Objects.equals(type, other.type) && - Objects.equals(url, other.url) && - Objects.equals(embeddingModel, other.embeddingModel) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(description, other.description) && + Objects.equals(embeddingModel, other.embeddingModel) && + Objects.equals(id, other.id) && + Objects.equals(knowledgeSourceDetails, other.knowledgeSourceDetails) && + Objects.equals(name, other.name) && + Objects.equals(status, other.status) && + Objects.equals(type, other.type) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - description, - id, - accountSid, - knowledgeSourceDetails, - name, - status, - type, - url, - embeddingModel, - dateCreated, - dateUpdated + accountSid, + dateCreated, + dateUpdated, + description, + embeddingModel, + id, + knowledgeSourceDetails, + name, + status, + type, + url ); } + + } + diff --git a/src/main/java/com/twilio/rest/assistants/v1/KnowledgeCreator.java b/src/main/java/com/twilio/rest/assistants/v1/KnowledgeCreator.java index 73da89e2fa..ab75935407 100644 --- a/src/main/java/com/twilio/rest/assistants/v1/KnowledgeCreator.java +++ b/src/main/java/com/twilio/rest/assistants/v1/KnowledgeCreator.java @@ -30,72 +30,53 @@ public class KnowledgeCreator extends Creator { private Knowledge.AssistantsV1ServiceCreateKnowledgeRequest assistantsV1ServiceCreateKnowledgeRequest; - public KnowledgeCreator( - final Knowledge.AssistantsV1ServiceCreateKnowledgeRequest assistantsV1ServiceCreateKnowledgeRequest - ) { - this.assistantsV1ServiceCreateKnowledgeRequest = - assistantsV1ServiceCreateKnowledgeRequest; + public KnowledgeCreator(final Knowledge.AssistantsV1ServiceCreateKnowledgeRequest assistantsV1ServiceCreateKnowledgeRequest) { + this.assistantsV1ServiceCreateKnowledgeRequest = assistantsV1ServiceCreateKnowledgeRequest; } - public KnowledgeCreator setAssistantsV1ServiceCreateKnowledgeRequest( - final Knowledge.AssistantsV1ServiceCreateKnowledgeRequest assistantsV1ServiceCreateKnowledgeRequest - ) { - this.assistantsV1ServiceCreateKnowledgeRequest = - assistantsV1ServiceCreateKnowledgeRequest; + + public KnowledgeCreator setAssistantsV1ServiceCreateKnowledgeRequest(final Knowledge.AssistantsV1ServiceCreateKnowledgeRequest assistantsV1ServiceCreateKnowledgeRequest) { + this.assistantsV1ServiceCreateKnowledgeRequest = assistantsV1ServiceCreateKnowledgeRequest; return this; } + @Override public Knowledge create(final TwilioRestClient client) { + String path = "/v1/Knowledge"; - path = - path.replace( - "{" + "AssistantsV1ServiceCreateKnowledgeRequest" + "}", - this.assistantsV1ServiceCreateKnowledgeRequest.toString() - ); Request request = new Request( - HttpMethod.POST, - Domains.ASSISTANTS.toString(), - path + HttpMethod.POST, + Domains.ASSISTANTS.toString(), + path ); request.setContentType(EnumConstants.ContentType.JSON); addPostParams(request, client); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Knowledge creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("Knowledge creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Knowledge.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Knowledge.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request, TwilioRestClient client) { ObjectMapper objectMapper = client.getObjectMapper(); if (assistantsV1ServiceCreateKnowledgeRequest != null) { - request.setBody( - Knowledge.toJson( - assistantsV1ServiceCreateKnowledgeRequest, - objectMapper - ) - ); + request.setBody(Knowledge.toJson(assistantsV1ServiceCreateKnowledgeRequest, objectMapper)); } } } diff --git a/src/main/java/com/twilio/rest/assistants/v1/KnowledgeDeleter.java b/src/main/java/com/twilio/rest/assistants/v1/KnowledgeDeleter.java index 99a0057c51..ad1373a7e7 100644 --- a/src/main/java/com/twilio/rest/assistants/v1/KnowledgeDeleter.java +++ b/src/main/java/com/twilio/rest/assistants/v1/KnowledgeDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.assistants.v1; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,40 +26,38 @@ public class KnowledgeDeleter extends Deleter { - private String pathId; + private String pathid; - public KnowledgeDeleter(final String pathId) { - this.pathId = pathId; + public KnowledgeDeleter(final String pathid) { + this.pathid = pathid; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/v1/Knowledge/{id}"; - path = path.replace("{" + "id" + "}", this.pathId.toString()); + path = path.replace("{" + "id" + "}", this.pathid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.ASSISTANTS.toString(), - path + HttpMethod.DELETE, + Domains.ASSISTANTS.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Knowledge delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("Knowledge delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/assistants/v1/KnowledgeFetcher.java b/src/main/java/com/twilio/rest/assistants/v1/KnowledgeFetcher.java index 16a9d19745..66f9dca473 100644 --- a/src/main/java/com/twilio/rest/assistants/v1/KnowledgeFetcher.java +++ b/src/main/java/com/twilio/rest/assistants/v1/KnowledgeFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.assistants.v1; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,47 +26,41 @@ public class KnowledgeFetcher extends Fetcher { - private String pathId; + private String pathid; - public KnowledgeFetcher(final String pathId) { - this.pathId = pathId; + public KnowledgeFetcher(final String pathid) { + this.pathid = pathid; } + @Override public Knowledge fetch(final TwilioRestClient client) { + String path = "/v1/Knowledge/{id}"; - path = path.replace("{" + "id" + "}", this.pathId.toString()); + path = path.replace("{" + "id" + "}", this.pathid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.ASSISTANTS.toString(), - path + HttpMethod.GET, + Domains.ASSISTANTS.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Knowledge fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Knowledge fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return Knowledge.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Knowledge.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/assistants/v1/KnowledgeReader.java b/src/main/java/com/twilio/rest/assistants/v1/KnowledgeReader.java index aa784ccf77..b29242ff3e 100644 --- a/src/main/java/com/twilio/rest/assistants/v1/KnowledgeReader.java +++ b/src/main/java/com/twilio/rest/assistants/v1/KnowledgeReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -32,113 +33,94 @@ public class KnowledgeReader extends Reader { private String assistantId; private Integer pageSize; - public KnowledgeReader() {} + public KnowledgeReader() { + } + public KnowledgeReader setAssistantId(final String assistantId) { this.assistantId = assistantId; return this; } + public KnowledgeReader setPageSize(final Integer pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/Knowledge"; + Request request = new Request( - HttpMethod.GET, - Domains.ASSISTANTS.toString(), - path + HttpMethod.GET, + Domains.ASSISTANTS.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Knowledge read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Knowledge read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "knowledge", - response.getContent(), - Knowledge.class, - client.getObjectMapper() - ); + "knowledge", + response.getContent(), + Knowledge.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.ASSISTANTS.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.ASSISTANTS.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (assistantId != null) { - request.addQueryParam("AssistantId", assistantId); + Serializer.toString(request, "AssistantId", assistantId, ParameterType.QUERY); } + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/assistants/v1/KnowledgeUpdater.java b/src/main/java/com/twilio/rest/assistants/v1/KnowledgeUpdater.java index 773dbf4099..80ec10d959 100644 --- a/src/main/java/com/twilio/rest/assistants/v1/KnowledgeUpdater.java +++ b/src/main/java/com/twilio/rest/assistants/v1/KnowledgeUpdater.java @@ -27,69 +27,58 @@ import com.twilio.rest.Domains; public class KnowledgeUpdater extends Updater { - - private String pathId; + private String pathid; private Knowledge.AssistantsV1ServiceUpdateKnowledgeRequest assistantsV1ServiceUpdateKnowledgeRequest; - public KnowledgeUpdater(final String pathId) { - this.pathId = pathId; + public KnowledgeUpdater(final String pathid) { + this.pathid = pathid; } - public KnowledgeUpdater setAssistantsV1ServiceUpdateKnowledgeRequest( - final Knowledge.AssistantsV1ServiceUpdateKnowledgeRequest assistantsV1ServiceUpdateKnowledgeRequest - ) { - this.assistantsV1ServiceUpdateKnowledgeRequest = - assistantsV1ServiceUpdateKnowledgeRequest; + + public KnowledgeUpdater setAssistantsV1ServiceUpdateKnowledgeRequest(final Knowledge.AssistantsV1ServiceUpdateKnowledgeRequest assistantsV1ServiceUpdateKnowledgeRequest) { + this.assistantsV1ServiceUpdateKnowledgeRequest = assistantsV1ServiceUpdateKnowledgeRequest; return this; } + @Override public Knowledge update(final TwilioRestClient client) { + String path = "/v1/Knowledge/{id}"; - path = path.replace("{" + "id" + "}", this.pathId.toString()); + path = path.replace("{" + "id" + "}", this.pathid.toString()); + Request request = new Request( - HttpMethod.PUT, - Domains.ASSISTANTS.toString(), - path + HttpMethod.PUT, + Domains.ASSISTANTS.toString(), + path ); request.setContentType(EnumConstants.ContentType.JSON); addPostParams(request, client); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Knowledge update failed: Unable to connect to server" - ); + throw new ApiConnectionException("Knowledge update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Knowledge.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Knowledge.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request, TwilioRestClient client) { ObjectMapper objectMapper = client.getObjectMapper(); if (assistantsV1ServiceUpdateKnowledgeRequest != null) { - request.setBody( - Knowledge.toJson( - assistantsV1ServiceUpdateKnowledgeRequest, - objectMapper - ) - ); + request.setBody(Knowledge.toJson(assistantsV1ServiceUpdateKnowledgeRequest, objectMapper)); } } } diff --git a/src/main/java/com/twilio/rest/assistants/v1/Policy.java b/src/main/java/com/twilio/rest/assistants/v1/Policy.java index aad952fdda..70dacd22f1 100644 --- a/src/main/java/com/twilio/rest/assistants/v1/Policy.java +++ b/src/main/java/com/twilio/rest/assistants/v1/Policy.java @@ -18,42 +18,41 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.time.ZonedDateTime; -import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Policy extends Resource { - private static final long serialVersionUID = 15658572271109L; public static PolicyReader reader() { - return new PolicyReader(); + return new PolicyReader( + + ); } + /** * Converts a JSON String into a Policy object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Policy object represented by the provided JSON */ - public static Policy fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Policy fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Policy.class); @@ -68,14 +67,11 @@ public static Policy fromJson( * Converts a JSON InputStream into a Policy object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Policy object represented by the provided JSON */ - public static Policy fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Policy fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Policy.class); @@ -86,73 +82,61 @@ public static Policy fromJson( } } - private final String id; - private final String name; - private final String description; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String userSid; - private final String type; - private final Map policyDetails; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; + @Getter + private final String description; + @Getter + private final String id; + @Getter + private final String name; + @Getter + private final Object policyDetails; + @Getter + private final String type; + @Getter + private final String userSid; @JsonCreator private Policy( - @JsonProperty("id") final String id, - @JsonProperty("name") final String name, - @JsonProperty("description") final String description, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("user_sid") final String userSid, - @JsonProperty("type") final String type, - @JsonProperty("policy_details") final Map policyDetails, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("description") final String description, + @JsonProperty("id") final String id, + @JsonProperty("name") final String name, + @JsonProperty("policy_details") final Object policyDetails, + @JsonProperty("type") final String type, + @JsonProperty("user_sid") final String userSid ) { + this.accountSid = accountSid; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; + this.description = description; this.id = id; this.name = name; - this.description = description; - this.accountSid = accountSid; - this.userSid = userSid; - this.type = type; this.policyDetails = policyDetails; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); - } - - public final String getId() { - return this.id; - } - - public final String getName() { - return this.name; - } - - public final String getDescription() { - return this.description; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getUserSid() { - return this.userSid; - } - - public final String getType() { - return this.type; - } - - public final Map getPolicyDetails() { - return this.policyDetails; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; + this.type = type; + this.userSid = userSid; } @Override @@ -166,32 +150,34 @@ public boolean equals(final Object o) { } Policy other = (Policy) o; - return ( - Objects.equals(id, other.id) && - Objects.equals(name, other.name) && - Objects.equals(description, other.description) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(userSid, other.userSid) && - Objects.equals(type, other.type) && - Objects.equals(policyDetails, other.policyDetails) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(description, other.description) && + Objects.equals(id, other.id) && + Objects.equals(name, other.name) && + Objects.equals(policyDetails, other.policyDetails) && + Objects.equals(type, other.type) && + Objects.equals(userSid, other.userSid) ); } @Override public int hashCode() { return Objects.hash( - id, - name, - description, - accountSid, - userSid, - type, - policyDetails, - dateCreated, - dateUpdated + accountSid, + dateCreated, + dateUpdated, + description, + id, + name, + policyDetails, + type, + userSid ); } + + } + diff --git a/src/main/java/com/twilio/rest/assistants/v1/PolicyReader.java b/src/main/java/com/twilio/rest/assistants/v1/PolicyReader.java index c216cafe42..c146c41230 100644 --- a/src/main/java/com/twilio/rest/assistants/v1/PolicyReader.java +++ b/src/main/java/com/twilio/rest/assistants/v1/PolicyReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -33,121 +34,105 @@ public class PolicyReader extends Reader { private String knowledgeId; private Integer pageSize; - public PolicyReader() {} + public PolicyReader() { + } + public PolicyReader setToolId(final String toolId) { this.toolId = toolId; return this; } + public PolicyReader setKnowledgeId(final String knowledgeId) { this.knowledgeId = knowledgeId; return this; } + public PolicyReader setPageSize(final Integer pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/Policies"; + Request request = new Request( - HttpMethod.GET, - Domains.ASSISTANTS.toString(), - path + HttpMethod.GET, + Domains.ASSISTANTS.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Policy read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Policy read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "policies", - response.getContent(), - Policy.class, - client.getObjectMapper() - ); + "policies", + response.getContent(), + Policy.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.ASSISTANTS.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.ASSISTANTS.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (toolId != null) { - request.addQueryParam("ToolId", toolId); + Serializer.toString(request, "ToolId", toolId, ParameterType.QUERY); } + + if (knowledgeId != null) { - request.addQueryParam("KnowledgeId", knowledgeId); + Serializer.toString(request, "KnowledgeId", knowledgeId, ParameterType.QUERY); } + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/assistants/v1/Session.java b/src/main/java/com/twilio/rest/assistants/v1/Session.java index c42f56ba6e..e2f715985e 100644 --- a/src/main/java/com/twilio/rest/assistants/v1/Session.java +++ b/src/main/java/com/twilio/rest/assistants/v1/Session.java @@ -18,44 +18,48 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.time.ZonedDateTime; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Session extends Resource { - private static final long serialVersionUID = 32443356464816L; - public static SessionFetcher fetcher(final String pathId) { - return new SessionFetcher(pathId); + public static SessionFetcher fetcher(final String pathid) { + return new SessionFetcher( + pathid + ); } + public static SessionReader reader() { - return new SessionReader(); + return new SessionReader( + + ); } + /** * Converts a JSON String into a Session object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Session object represented by the provided JSON */ - public static Session fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Session fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Session.class); @@ -70,14 +74,11 @@ public static Session fromJson( * Converts a JSON InputStream into a Session object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Session object represented by the provided JSON */ - public static Session fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Session fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Session.class); @@ -88,59 +89,53 @@ public static Session fromJson( } } - private final String id; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; + @Getter private final String assistantId; - private final Boolean verified; - private final String identity; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; + @Getter + private final String id; + @Getter + private final String identity; + @Getter + private final Boolean verified; @JsonCreator private Session( - @JsonProperty("id") final String id, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("assistant_id") final String assistantId, - @JsonProperty("verified") final Boolean verified, - @JsonProperty("identity") final String identity, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("assistant_id") final String assistantId, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("id") final String id, + @JsonProperty("identity") final String identity, + @JsonProperty("verified") final Boolean verified ) { - this.id = id; this.accountSid = accountSid; this.assistantId = assistantId; - this.verified = verified; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; + this.id = id; this.identity = identity; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); - } - - public final String getId() { - return this.id; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getAssistantId() { - return this.assistantId; - } - - public final Boolean getVerified() { - return this.verified; - } - - public final String getIdentity() { - return this.identity; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; + this.verified = verified; } @Override @@ -154,28 +149,30 @@ public boolean equals(final Object o) { } Session other = (Session) o; - return ( - Objects.equals(id, other.id) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(assistantId, other.assistantId) && - Objects.equals(verified, other.verified) && - Objects.equals(identity, other.identity) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(assistantId, other.assistantId) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(id, other.id) && + Objects.equals(identity, other.identity) && + Objects.equals(verified, other.verified) ); } @Override public int hashCode() { return Objects.hash( - id, - accountSid, - assistantId, - verified, - identity, - dateCreated, - dateUpdated + accountSid, + assistantId, + dateCreated, + dateUpdated, + id, + identity, + verified ); } + + } + diff --git a/src/main/java/com/twilio/rest/assistants/v1/SessionFetcher.java b/src/main/java/com/twilio/rest/assistants/v1/SessionFetcher.java index 92eaa1f146..dbf6435c01 100644 --- a/src/main/java/com/twilio/rest/assistants/v1/SessionFetcher.java +++ b/src/main/java/com/twilio/rest/assistants/v1/SessionFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.assistants.v1; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,44 +26,41 @@ public class SessionFetcher extends Fetcher { - private String pathId; + private String pathid; - public SessionFetcher(final String pathId) { - this.pathId = pathId; + public SessionFetcher(final String pathid) { + this.pathid = pathid; } + @Override public Session fetch(final TwilioRestClient client) { + String path = "/v1/Sessions/{id}"; - path = path.replace("{" + "id" + "}", this.pathId.toString()); + path = path.replace("{" + "id" + "}", this.pathid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.ASSISTANTS.toString(), - path + HttpMethod.GET, + Domains.ASSISTANTS.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Session fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Session fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Session.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/assistants/v1/SessionReader.java b/src/main/java/com/twilio/rest/assistants/v1/SessionReader.java index 05a8c72660..d6324349b6 100644 --- a/src/main/java/com/twilio/rest/assistants/v1/SessionReader.java +++ b/src/main/java/com/twilio/rest/assistants/v1/SessionReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -31,105 +32,83 @@ public class SessionReader extends Reader { private Integer pageSize; - public SessionReader() {} + public SessionReader() { + } + public SessionReader setPageSize(final Integer pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/Sessions"; + Request request = new Request( - HttpMethod.GET, - Domains.ASSISTANTS.toString(), - path + HttpMethod.GET, + Domains.ASSISTANTS.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Session read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Session read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "sessions", - response.getContent(), - Session.class, - client.getObjectMapper() - ); + "sessions", + response.getContent(), + Session.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.ASSISTANTS.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.ASSISTANTS.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/assistants/v1/Tool.java b/src/main/java/com/twilio/rest/assistants/v1/Tool.java index 48770ad6a1..883c041341 100644 --- a/src/main/java/com/twilio/rest/assistants/v1/Tool.java +++ b/src/main/java/com/twilio/rest/assistants/v1/Tool.java @@ -22,30 +22,67 @@ import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.time.ZonedDateTime; import java.util.List; -import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.Getter; -import lombok.Setter; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Tool extends Resource { - private static final long serialVersionUID = 65943663776562L; + public static ToolCreator creator(final Tool.AssistantsV1ServiceCreateToolRequest assistantsV1ServiceCreateToolRequest) { + return new ToolCreator( + assistantsV1ServiceCreateToolRequest + ); + } + + + public static ToolDeleter deleter(final String pathid) { + return new ToolDeleter( + pathid + ); + } + + + public static ToolFetcher fetcher(final String pathid) { + return new ToolFetcher( + pathid + ); + } + + + public static ToolReader reader() { + return new ToolReader( + + ); + } + + + public static ToolUpdater updater(final String pathid) { + return new ToolUpdater( + pathid + ); + } + + + //@JsonDeserialize(builder = AssistantsV1ServiceCreatePolicyRequest.Builder.class) + @JsonInclude(JsonInclude.Include.NON_EMPTY) @ToString public static class AssistantsV1ServiceCreatePolicyRequest { + public AssistantsV1ServiceCreatePolicyRequest(final Object policyDetails) { + this.policyDetails = policyDetails; + } @JsonInclude(JsonInclude.Include.NON_EMPTY) @JsonProperty("description") @@ -77,19 +114,12 @@ public static class AssistantsV1ServiceCreatePolicyRequest { @Setter private String type; - public static AssistantsV1ServiceCreatePolicyRequest fromJson( - String jsonString, - ObjectMapper mapper - ) throws IOException { - return mapper.readValue( - jsonString, - AssistantsV1ServiceCreatePolicyRequest.class - ); - } } + //@JsonDeserialize(builder = AssistantsV1ServiceUpdateToolRequest.Builder.class) + @JsonInclude(JsonInclude.Include.NON_EMPTY) @ToString - public static class AssistantsV1ServiceCreateToolRequest { + public static class AssistantsV1ServiceUpdateToolRequest { @JsonInclude(JsonInclude.Include.NON_EMPTY) @JsonProperty("assistant_id") @@ -113,7 +143,7 @@ public static class AssistantsV1ServiceCreateToolRequest { @JsonProperty("meta") @Getter @Setter - private Map meta; + private Object meta; @JsonInclude(JsonInclude.Include.NON_EMPTY) @JsonProperty("name") @@ -133,30 +163,18 @@ public static class AssistantsV1ServiceCreateToolRequest { @Setter private String type; - public AssistantsV1ServiceCreateToolRequest( - final Boolean enabled, - final String name, - final String type - ) { + } + + //@JsonDeserialize(builder = AssistantsV1ServiceCreateToolRequest.Builder.class) + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @ToString + public static class AssistantsV1ServiceCreateToolRequest { + public AssistantsV1ServiceCreateToolRequest(final Boolean enabled, final String name, final String type) { this.enabled = enabled; this.name = name; this.type = type; } - public static AssistantsV1ServiceCreateToolRequest fromJson( - String jsonString, - ObjectMapper mapper - ) throws IOException { - return mapper.readValue( - jsonString, - AssistantsV1ServiceCreateToolRequest.class - ); - } - } - - @ToString - public static class AssistantsV1ServiceUpdateToolRequest { - @JsonInclude(JsonInclude.Include.NON_EMPTY) @JsonProperty("assistant_id") @Getter @@ -179,7 +197,7 @@ public static class AssistantsV1ServiceUpdateToolRequest { @JsonProperty("meta") @Getter @Setter - private Map meta; + private Object meta; @JsonInclude(JsonInclude.Include.NON_EMPTY) @JsonProperty("name") @@ -199,21 +217,16 @@ public static class AssistantsV1ServiceUpdateToolRequest { @Setter private String type; - public AssistantsV1ServiceUpdateToolRequest() {} - - public static AssistantsV1ServiceUpdateToolRequest fromJson( - String jsonString, - ObjectMapper mapper - ) throws IOException { - return mapper.readValue( - jsonString, - AssistantsV1ServiceUpdateToolRequest.class - ); - } } + //@JsonDeserialize(builder = AssistantsV1ServicePolicy.Builder.class) + @JsonInclude(JsonInclude.Include.NON_EMPTY) @ToString public static class AssistantsV1ServicePolicy { + public AssistantsV1ServicePolicy(final String type, final Object policyDetails) { + this.type = type; + this.policyDetails = policyDetails; + } @JsonInclude(JsonInclude.Include.NON_EMPTY) @JsonProperty("id") @@ -234,13 +247,13 @@ public static class AssistantsV1ServicePolicy { private String description; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("accountSid") + @JsonProperty("account_sid") @Getter @Setter private String accountSid; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("userSid") + @JsonProperty("user_sid") @Getter @Setter private String userSid; @@ -252,75 +265,35 @@ public static class AssistantsV1ServicePolicy { private String type; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("policyDetails") + @JsonProperty("policy_details") @Getter @Setter - private Map policyDetails; + private Object policyDetails; + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("dateCreated") + @JsonProperty("date_created") @Getter @Setter private ZonedDateTime dateCreated; - public String getDateCreated() { - return dateCreated.toInstant().toString(); - } - + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("dateUpdated") + @JsonProperty("date_updated") @Getter @Setter private ZonedDateTime dateUpdated; - public String getDateUpdated() { - return dateUpdated.toInstant().toString(); - } - - public static AssistantsV1ServicePolicy fromJson( - String jsonString, - ObjectMapper mapper - ) throws IOException { - return mapper.readValue( - jsonString, - AssistantsV1ServicePolicy.class - ); - } - } - - public static ToolCreator creator( - final Tool.AssistantsV1ServiceCreateToolRequest assistantsV1ServiceCreateToolRequest - ) { - return new ToolCreator(assistantsV1ServiceCreateToolRequest); - } - - public static ToolDeleter deleter(final String pathId) { - return new ToolDeleter(pathId); - } - - public static ToolFetcher fetcher(final String pathId) { - return new ToolFetcher(pathId); - } - - public static ToolReader reader() { - return new ToolReader(); - } - - public static ToolUpdater updater(final String pathId) { - return new ToolUpdater(pathId); } /** * Converts a JSON String into a Tool object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Tool object represented by the provided JSON */ - public static Tool fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Tool fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Tool.class); @@ -335,14 +308,11 @@ public static Tool fromJson( * Converts a JSON InputStream into a Tool object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Tool object represented by the provided JSON */ - public static Tool fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Tool fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Tool.class); @@ -365,94 +335,61 @@ public static String toJson(Object object, ObjectMapper mapper) { } } + + @Getter private final String accountSid; + @Getter + private final ZonedDateTime dateCreated; + @Getter + private final ZonedDateTime dateUpdated; + @Getter private final String description; + @Getter private final Boolean enabled; + @Getter private final String id; - private final Map meta; + @Getter + private final Object meta; + @Getter private final String name; + @Getter + private final List policies; + @Getter private final Boolean requiresAuth; + @Getter private final String type; + @Getter private final String url; - private final ZonedDateTime dateCreated; - private final ZonedDateTime dateUpdated; - private final List policies; @JsonCreator private Tool( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("description") final String description, - @JsonProperty("enabled") final Boolean enabled, - @JsonProperty("id") final String id, - @JsonProperty("meta") final Map meta, - @JsonProperty("name") final String name, - @JsonProperty("requires_auth") final Boolean requiresAuth, - @JsonProperty("type") final String type, - @JsonProperty("url") final String url, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("policies") final List policies + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("description") final String description, + @JsonProperty("enabled") final Boolean enabled, + @JsonProperty("id") final String id, + @JsonProperty("meta") final Object meta, + @JsonProperty("name") final String name, + @JsonProperty("policies") final List policies, + @JsonProperty("requires_auth") final Boolean requiresAuth, + @JsonProperty("type") final String type, + @JsonProperty("url") final String url ) { this.accountSid = accountSid; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.description = description; this.enabled = enabled; this.id = id; this.meta = meta; this.name = name; + this.policies = policies; this.requiresAuth = requiresAuth; this.type = type; this.url = url; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); - this.policies = policies; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getDescription() { - return this.description; - } - - public final Boolean getEnabled() { - return this.enabled; - } - - public final String getId() { - return this.id; - } - - public final Map getMeta() { - return this.meta; - } - - public final String getName() { - return this.name; - } - - public final Boolean getRequiresAuth() { - return this.requiresAuth; - } - - public final String getType() { - return this.type; - } - - public final String getUrl() { - return this.url; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final List getPolicies() { - return this.policies; } @Override @@ -466,38 +403,40 @@ public boolean equals(final Object o) { } Tool other = (Tool) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(description, other.description) && - Objects.equals(enabled, other.enabled) && - Objects.equals(id, other.id) && - Objects.equals(meta, other.meta) && - Objects.equals(name, other.name) && - Objects.equals(requiresAuth, other.requiresAuth) && - Objects.equals(type, other.type) && - Objects.equals(url, other.url) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(policies, other.policies) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(description, other.description) && + Objects.equals(enabled, other.enabled) && + Objects.equals(id, other.id) && + Objects.equals(meta, other.meta) && + Objects.equals(name, other.name) && + Objects.equals(policies, other.policies) && + Objects.equals(requiresAuth, other.requiresAuth) && + Objects.equals(type, other.type) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - accountSid, - description, - enabled, - id, - meta, - name, - requiresAuth, - type, - url, - dateCreated, - dateUpdated, - policies + accountSid, + dateCreated, + dateUpdated, + description, + enabled, + id, + meta, + name, + policies, + requiresAuth, + type, + url ); } + + } + diff --git a/src/main/java/com/twilio/rest/assistants/v1/ToolCreator.java b/src/main/java/com/twilio/rest/assistants/v1/ToolCreator.java index 0b841a7264..0fa6382cc7 100644 --- a/src/main/java/com/twilio/rest/assistants/v1/ToolCreator.java +++ b/src/main/java/com/twilio/rest/assistants/v1/ToolCreator.java @@ -30,53 +30,42 @@ public class ToolCreator extends Creator { private Tool.AssistantsV1ServiceCreateToolRequest assistantsV1ServiceCreateToolRequest; - public ToolCreator( - final Tool.AssistantsV1ServiceCreateToolRequest assistantsV1ServiceCreateToolRequest - ) { - this.assistantsV1ServiceCreateToolRequest = - assistantsV1ServiceCreateToolRequest; + public ToolCreator(final Tool.AssistantsV1ServiceCreateToolRequest assistantsV1ServiceCreateToolRequest) { + this.assistantsV1ServiceCreateToolRequest = assistantsV1ServiceCreateToolRequest; } - public ToolCreator setAssistantsV1ServiceCreateToolRequest( - final Tool.AssistantsV1ServiceCreateToolRequest assistantsV1ServiceCreateToolRequest - ) { - this.assistantsV1ServiceCreateToolRequest = - assistantsV1ServiceCreateToolRequest; + + public ToolCreator setAssistantsV1ServiceCreateToolRequest(final Tool.AssistantsV1ServiceCreateToolRequest assistantsV1ServiceCreateToolRequest) { + this.assistantsV1ServiceCreateToolRequest = assistantsV1ServiceCreateToolRequest; return this; } + @Override public Tool create(final TwilioRestClient client) { + String path = "/v1/Tools"; - path = - path.replace( - "{" + "AssistantsV1ServiceCreateToolRequest" + "}", - this.assistantsV1ServiceCreateToolRequest.toString() - ); Request request = new Request( - HttpMethod.POST, - Domains.ASSISTANTS.toString(), - path + HttpMethod.POST, + Domains.ASSISTANTS.toString(), + path ); request.setContentType(EnumConstants.ContentType.JSON); addPostParams(request, client); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Tool creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("Tool creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -87,9 +76,7 @@ public Tool create(final TwilioRestClient client) { private void addPostParams(final Request request, TwilioRestClient client) { ObjectMapper objectMapper = client.getObjectMapper(); if (assistantsV1ServiceCreateToolRequest != null) { - request.setBody( - Tool.toJson(assistantsV1ServiceCreateToolRequest, objectMapper) - ); + request.setBody(Tool.toJson(assistantsV1ServiceCreateToolRequest, objectMapper)); } } } diff --git a/src/main/java/com/twilio/rest/assistants/v1/ToolDeleter.java b/src/main/java/com/twilio/rest/assistants/v1/ToolDeleter.java index 7ef83721f7..1f57f4c111 100644 --- a/src/main/java/com/twilio/rest/assistants/v1/ToolDeleter.java +++ b/src/main/java/com/twilio/rest/assistants/v1/ToolDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.assistants.v1; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,40 +26,38 @@ public class ToolDeleter extends Deleter { - private String pathId; + private String pathid; - public ToolDeleter(final String pathId) { - this.pathId = pathId; + public ToolDeleter(final String pathid) { + this.pathid = pathid; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/v1/Tools/{id}"; - path = path.replace("{" + "id" + "}", this.pathId.toString()); + path = path.replace("{" + "id" + "}", this.pathid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.ASSISTANTS.toString(), - path + HttpMethod.DELETE, + Domains.ASSISTANTS.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Tool delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("Tool delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/assistants/v1/ToolFetcher.java b/src/main/java/com/twilio/rest/assistants/v1/ToolFetcher.java index d1adfc8f4a..b88620b891 100644 --- a/src/main/java/com/twilio/rest/assistants/v1/ToolFetcher.java +++ b/src/main/java/com/twilio/rest/assistants/v1/ToolFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.assistants.v1; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,44 +26,41 @@ public class ToolFetcher extends Fetcher { - private String pathId; + private String pathid; - public ToolFetcher(final String pathId) { - this.pathId = pathId; + public ToolFetcher(final String pathid) { + this.pathid = pathid; } + @Override public Tool fetch(final TwilioRestClient client) { + String path = "/v1/Tools/{id}"; - path = path.replace("{" + "id" + "}", this.pathId.toString()); + path = path.replace("{" + "id" + "}", this.pathid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.ASSISTANTS.toString(), - path + HttpMethod.GET, + Domains.ASSISTANTS.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Tool fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Tool fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Tool.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/assistants/v1/ToolReader.java b/src/main/java/com/twilio/rest/assistants/v1/ToolReader.java index 7b8e49a7d8..4d51e0f95d 100644 --- a/src/main/java/com/twilio/rest/assistants/v1/ToolReader.java +++ b/src/main/java/com/twilio/rest/assistants/v1/ToolReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -32,113 +33,94 @@ public class ToolReader extends Reader { private String assistantId; private Integer pageSize; - public ToolReader() {} + public ToolReader() { + } + public ToolReader setAssistantId(final String assistantId) { this.assistantId = assistantId; return this; } + public ToolReader setPageSize(final Integer pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/Tools"; + Request request = new Request( - HttpMethod.GET, - Domains.ASSISTANTS.toString(), - path + HttpMethod.GET, + Domains.ASSISTANTS.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Tool read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Tool read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "tools", - response.getContent(), - Tool.class, - client.getObjectMapper() - ); + "tools", + response.getContent(), + Tool.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.ASSISTANTS.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.ASSISTANTS.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (assistantId != null) { - request.addQueryParam("AssistantId", assistantId); + Serializer.toString(request, "AssistantId", assistantId, ParameterType.QUERY); } + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/assistants/v1/ToolUpdater.java b/src/main/java/com/twilio/rest/assistants/v1/ToolUpdater.java index eb5293917b..c8982b5bad 100644 --- a/src/main/java/com/twilio/rest/assistants/v1/ToolUpdater.java +++ b/src/main/java/com/twilio/rest/assistants/v1/ToolUpdater.java @@ -27,50 +27,47 @@ import com.twilio.rest.Domains; public class ToolUpdater extends Updater { - - private String pathId; + private String pathid; private Tool.AssistantsV1ServiceUpdateToolRequest assistantsV1ServiceUpdateToolRequest; - public ToolUpdater(final String pathId) { - this.pathId = pathId; + public ToolUpdater(final String pathid) { + this.pathid = pathid; } - public ToolUpdater setAssistantsV1ServiceUpdateToolRequest( - final Tool.AssistantsV1ServiceUpdateToolRequest assistantsV1ServiceUpdateToolRequest - ) { - this.assistantsV1ServiceUpdateToolRequest = - assistantsV1ServiceUpdateToolRequest; + + public ToolUpdater setAssistantsV1ServiceUpdateToolRequest(final Tool.AssistantsV1ServiceUpdateToolRequest assistantsV1ServiceUpdateToolRequest) { + this.assistantsV1ServiceUpdateToolRequest = assistantsV1ServiceUpdateToolRequest; return this; } + @Override public Tool update(final TwilioRestClient client) { + String path = "/v1/Tools/{id}"; - path = path.replace("{" + "id" + "}", this.pathId.toString()); + path = path.replace("{" + "id" + "}", this.pathid.toString()); + Request request = new Request( - HttpMethod.PUT, - Domains.ASSISTANTS.toString(), - path + HttpMethod.PUT, + Domains.ASSISTANTS.toString(), + path ); request.setContentType(EnumConstants.ContentType.JSON); addPostParams(request, client); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Tool update failed: Unable to connect to server" - ); + throw new ApiConnectionException("Tool update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -81,9 +78,7 @@ public Tool update(final TwilioRestClient client) { private void addPostParams(final Request request, TwilioRestClient client) { ObjectMapper objectMapper = client.getObjectMapper(); if (assistantsV1ServiceUpdateToolRequest != null) { - request.setBody( - Tool.toJson(assistantsV1ServiceUpdateToolRequest, objectMapper) - ); + request.setBody(Tool.toJson(assistantsV1ServiceUpdateToolRequest, objectMapper)); } } } diff --git a/src/main/java/com/twilio/rest/assistants/v1/assistant/AssistantsKnowledge.java b/src/main/java/com/twilio/rest/assistants/v1/assistant/AssistantsKnowledge.java index 2cd1846d11..8574ba9a17 100644 --- a/src/main/java/com/twilio/rest/assistants/v1/assistant/AssistantsKnowledge.java +++ b/src/main/java/com/twilio/rest/assistants/v1/assistant/AssistantsKnowledge.java @@ -18,58 +18,55 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.time.ZonedDateTime; -import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class AssistantsKnowledge extends Resource { - private static final long serialVersionUID = 142704301669097L; - public static AssistantsKnowledgeCreator creator( - final String pathAssistantId, - final String pathId - ) { - return new AssistantsKnowledgeCreator(pathAssistantId, pathId); + public static AssistantsKnowledgeCreator creator(final String pathassistantId, final String pathid) { + return new AssistantsKnowledgeCreator( + pathassistantId, pathid + ); } - public static AssistantsKnowledgeDeleter deleter( - final String pathAssistantId, - final String pathId - ) { - return new AssistantsKnowledgeDeleter(pathAssistantId, pathId); + + public static AssistantsKnowledgeDeleter deleter(final String pathassistantId, final String pathid) { + return new AssistantsKnowledgeDeleter( + pathassistantId, pathid + ); } - public static AssistantsKnowledgeReader reader( - final String pathAssistantId - ) { - return new AssistantsKnowledgeReader(pathAssistantId); + + public static AssistantsKnowledgeReader reader(final String pathassistantId) { + return new AssistantsKnowledgeReader( + pathassistantId + ); } + /** * Converts a JSON String into a AssistantsKnowledge object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return AssistantsKnowledge object represented by the provided JSON */ - public static AssistantsKnowledge fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static AssistantsKnowledge fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, AssistantsKnowledge.class); @@ -84,14 +81,11 @@ public static AssistantsKnowledge fromJson( * Converts a JSON InputStream into a AssistantsKnowledge object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return AssistantsKnowledge object represented by the provided JSON */ - public static AssistantsKnowledge fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static AssistantsKnowledge fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, AssistantsKnowledge.class); @@ -102,90 +96,69 @@ public static AssistantsKnowledge fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter + private final String accountSid; + @Getter + private final ZonedDateTime dateCreated; + @Getter + private final ZonedDateTime dateUpdated; + @Getter private final String description; + @Getter + private final String embeddingModel; + @Getter private final String id; - private final String accountSid; - private final Map knowledgeSourceDetails; + @Getter + private final Object knowledgeSourceDetails; + @Getter private final String name; + @Getter private final String status; + @Getter private final String type; + @Getter private final String url; - private final String embeddingModel; - private final ZonedDateTime dateCreated; - private final ZonedDateTime dateUpdated; @JsonCreator private AssistantsKnowledge( - @JsonProperty("description") final String description, - @JsonProperty("id") final String id, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("knowledge_source_details") final Map< - String, - Object - > knowledgeSourceDetails, - @JsonProperty("name") final String name, - @JsonProperty("status") final String status, - @JsonProperty("type") final String type, - @JsonProperty("url") final String url, - @JsonProperty("embedding_model") final String embeddingModel, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("description") final String description, + @JsonProperty("embedding_model") final String embeddingModel, + @JsonProperty("id") final String id, + @JsonProperty("knowledge_source_details") final Object knowledgeSourceDetails, + @JsonProperty("name") final String name, + @JsonProperty("status") final String status, + @JsonProperty("type") final String type, + @JsonProperty("url") final String url ) { + this.accountSid = accountSid; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.description = description; + this.embeddingModel = embeddingModel; this.id = id; - this.accountSid = accountSid; this.knowledgeSourceDetails = knowledgeSourceDetails; this.name = name; this.status = status; this.type = type; this.url = url; - this.embeddingModel = embeddingModel; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); - } - - public final String getDescription() { - return this.description; - } - - public final String getId() { - return this.id; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final Map getKnowledgeSourceDetails() { - return this.knowledgeSourceDetails; - } - - public final String getName() { - return this.name; - } - - public final String getStatus() { - return this.status; - } - - public final String getType() { - return this.type; - } - - public final String getUrl() { - return this.url; - } - - public final String getEmbeddingModel() { - return this.embeddingModel; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; } @Override @@ -199,39 +172,38 @@ public boolean equals(final Object o) { } AssistantsKnowledge other = (AssistantsKnowledge) o; - return ( - Objects.equals(description, other.description) && - Objects.equals(id, other.id) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals( - knowledgeSourceDetails, - other.knowledgeSourceDetails - ) && - Objects.equals(name, other.name) && - Objects.equals(status, other.status) && - Objects.equals(type, other.type) && - Objects.equals(url, other.url) && - Objects.equals(embeddingModel, other.embeddingModel) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(description, other.description) && + Objects.equals(embeddingModel, other.embeddingModel) && + Objects.equals(id, other.id) && + Objects.equals(knowledgeSourceDetails, other.knowledgeSourceDetails) && + Objects.equals(name, other.name) && + Objects.equals(status, other.status) && + Objects.equals(type, other.type) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - description, - id, - accountSid, - knowledgeSourceDetails, - name, - status, - type, - url, - embeddingModel, - dateCreated, - dateUpdated + accountSid, + dateCreated, + dateUpdated, + description, + embeddingModel, + id, + knowledgeSourceDetails, + name, + status, + type, + url ); } + + } + diff --git a/src/main/java/com/twilio/rest/assistants/v1/assistant/AssistantsKnowledgeCreator.java b/src/main/java/com/twilio/rest/assistants/v1/assistant/AssistantsKnowledgeCreator.java index 06accb38c0..571cad6e27 100644 --- a/src/main/java/com/twilio/rest/assistants/v1/assistant/AssistantsKnowledgeCreator.java +++ b/src/main/java/com/twilio/rest/assistants/v1/assistant/AssistantsKnowledgeCreator.java @@ -14,8 +14,8 @@ package com.twilio.rest.assistants.v1.assistant; + import com.twilio.base.Creator; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,56 +27,45 @@ public class AssistantsKnowledgeCreator extends Creator { - private String pathAssistantId; - private String pathId; + private String pathassistantId; + private String pathid; - public AssistantsKnowledgeCreator( - final String pathAssistantId, - final String pathId - ) { - this.pathAssistantId = pathAssistantId; - this.pathId = pathId; + public AssistantsKnowledgeCreator(final String pathassistantId, final String pathid) { + this.pathassistantId = pathassistantId; + this.pathid = pathid; } + @Override public AssistantsKnowledge create(final TwilioRestClient client) { + String path = "/v1/Assistants/{assistantId}/Knowledge/{id}"; - path = - path.replace( - "{" + "assistantId" + "}", - this.pathAssistantId.toString() - ); - path = path.replace("{" + "id" + "}", this.pathId.toString()); + path = path.replace("{" + "assistantId" + "}", this.pathassistantId.toString()); + path = path.replace("{" + "id" + "}", this.pathid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.ASSISTANTS.toString(), - path + HttpMethod.POST, + Domains.ASSISTANTS.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "AssistantsKnowledge creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("AssistantsKnowledge creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return AssistantsKnowledge.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return AssistantsKnowledge.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/assistants/v1/assistant/AssistantsKnowledgeDeleter.java b/src/main/java/com/twilio/rest/assistants/v1/assistant/AssistantsKnowledgeDeleter.java index 112ecccd82..e0c671bf9c 100644 --- a/src/main/java/com/twilio/rest/assistants/v1/assistant/AssistantsKnowledgeDeleter.java +++ b/src/main/java/com/twilio/rest/assistants/v1/assistant/AssistantsKnowledgeDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.assistants.v1.assistant; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,50 +26,41 @@ public class AssistantsKnowledgeDeleter extends Deleter { - private String pathAssistantId; - private String pathId; + private String pathassistantId; + private String pathid; - public AssistantsKnowledgeDeleter( - final String pathAssistantId, - final String pathId - ) { - this.pathAssistantId = pathAssistantId; - this.pathId = pathId; + public AssistantsKnowledgeDeleter(final String pathassistantId, final String pathid) { + this.pathassistantId = pathassistantId; + this.pathid = pathid; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/v1/Assistants/{assistantId}/Knowledge/{id}"; - path = - path.replace( - "{" + "assistantId" + "}", - this.pathAssistantId.toString() - ); - path = path.replace("{" + "id" + "}", this.pathId.toString()); + path = path.replace("{" + "assistantId" + "}", this.pathassistantId.toString()); + path = path.replace("{" + "id" + "}", this.pathid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.ASSISTANTS.toString(), - path + HttpMethod.DELETE, + Domains.ASSISTANTS.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "AssistantsKnowledge delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("AssistantsKnowledge delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/assistants/v1/assistant/AssistantsKnowledgeReader.java b/src/main/java/com/twilio/rest/assistants/v1/assistant/AssistantsKnowledgeReader.java index a605002d0e..152207bdc2 100644 --- a/src/main/java/com/twilio/rest/assistants/v1/assistant/AssistantsKnowledgeReader.java +++ b/src/main/java/com/twilio/rest/assistants/v1/assistant/AssistantsKnowledgeReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,117 +30,88 @@ public class AssistantsKnowledgeReader extends Reader { - private String pathAssistantId; + private String pathassistantId; private Integer pageSize; - public AssistantsKnowledgeReader(final String pathAssistantId) { - this.pathAssistantId = pathAssistantId; + public AssistantsKnowledgeReader(final String pathassistantId) { + this.pathassistantId = pathassistantId; } + public AssistantsKnowledgeReader setPageSize(final Integer pageSize) { this.pageSize = pageSize; return this; } + @Override - public ResourceSet read( - final TwilioRestClient client - ) { + public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/Assistants/{assistantId}/Knowledge"; - path = - path.replace( - "{" + "assistantId" + "}", - this.pathAssistantId.toString() - ); + + path = path.replace("{" + "assistantId" + "}", this.pathassistantId.toString()); Request request = new Request( - HttpMethod.GET, - Domains.ASSISTANTS.toString(), - path + HttpMethod.GET, + Domains.ASSISTANTS.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "AssistantsKnowledge read failed: Unable to connect to server" - ); + throw new ApiConnectionException("AssistantsKnowledge read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "knowledge", - response.getContent(), - AssistantsKnowledge.class, - client.getObjectMapper() - ); + "knowledge", + response.getContent(), + AssistantsKnowledge.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.ASSISTANTS.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.ASSISTANTS.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/assistants/v1/assistant/AssistantsTool.java b/src/main/java/com/twilio/rest/assistants/v1/assistant/AssistantsTool.java index c3114a8a11..29d19ef49d 100644 --- a/src/main/java/com/twilio/rest/assistants/v1/assistant/AssistantsTool.java +++ b/src/main/java/com/twilio/rest/assistants/v1/assistant/AssistantsTool.java @@ -18,56 +18,55 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.time.ZonedDateTime; -import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class AssistantsTool extends Resource { - private static final long serialVersionUID = 65943663776562L; - public static AssistantsToolCreator creator( - final String pathAssistantId, - final String pathId - ) { - return new AssistantsToolCreator(pathAssistantId, pathId); + public static AssistantsToolCreator creator(final String pathassistantId, final String pathid) { + return new AssistantsToolCreator( + pathassistantId, pathid + ); } - public static AssistantsToolDeleter deleter( - final String pathAssistantId, - final String pathId - ) { - return new AssistantsToolDeleter(pathAssistantId, pathId); + + public static AssistantsToolDeleter deleter(final String pathassistantId, final String pathid) { + return new AssistantsToolDeleter( + pathassistantId, pathid + ); } - public static AssistantsToolReader reader(final String pathAssistantId) { - return new AssistantsToolReader(pathAssistantId); + + public static AssistantsToolReader reader(final String pathassistantId) { + return new AssistantsToolReader( + pathassistantId + ); } + /** * Converts a JSON String into a AssistantsTool object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return AssistantsTool object represented by the provided JSON */ - public static AssistantsTool fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static AssistantsTool fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, AssistantsTool.class); @@ -82,14 +81,11 @@ public static AssistantsTool fromJson( * Converts a JSON InputStream into a AssistantsTool object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return AssistantsTool object represented by the provided JSON */ - public static AssistantsTool fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static AssistantsTool fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, AssistantsTool.class); @@ -100,33 +96,61 @@ public static AssistantsTool fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; + @Getter + private final ZonedDateTime dateCreated; + @Getter + private final ZonedDateTime dateUpdated; + @Getter private final String description; + @Getter private final Boolean enabled; + @Getter private final String id; - private final Map meta; + @Getter + private final Object meta; + @Getter private final String name; + @Getter private final Boolean requiresAuth; + @Getter private final String type; + @Getter private final String url; - private final ZonedDateTime dateCreated; - private final ZonedDateTime dateUpdated; @JsonCreator private AssistantsTool( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("description") final String description, - @JsonProperty("enabled") final Boolean enabled, - @JsonProperty("id") final String id, - @JsonProperty("meta") final Map meta, - @JsonProperty("name") final String name, - @JsonProperty("requires_auth") final Boolean requiresAuth, - @JsonProperty("type") final String type, - @JsonProperty("url") final String url, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("description") final String description, + @JsonProperty("enabled") final Boolean enabled, + @JsonProperty("id") final String id, + @JsonProperty("meta") final Object meta, + @JsonProperty("name") final String name, + @JsonProperty("requires_auth") final Boolean requiresAuth, + @JsonProperty("type") final String type, + @JsonProperty("url") final String url ) { this.accountSid = accountSid; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.description = description; this.enabled = enabled; this.id = id; @@ -135,52 +159,6 @@ private AssistantsTool( this.requiresAuth = requiresAuth; this.type = type; this.url = url; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getDescription() { - return this.description; - } - - public final Boolean getEnabled() { - return this.enabled; - } - - public final String getId() { - return this.id; - } - - public final Map getMeta() { - return this.meta; - } - - public final String getName() { - return this.name; - } - - public final Boolean getRequiresAuth() { - return this.requiresAuth; - } - - public final String getType() { - return this.type; - } - - public final String getUrl() { - return this.url; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; } @Override @@ -194,36 +172,38 @@ public boolean equals(final Object o) { } AssistantsTool other = (AssistantsTool) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(description, other.description) && - Objects.equals(enabled, other.enabled) && - Objects.equals(id, other.id) && - Objects.equals(meta, other.meta) && - Objects.equals(name, other.name) && - Objects.equals(requiresAuth, other.requiresAuth) && - Objects.equals(type, other.type) && - Objects.equals(url, other.url) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(description, other.description) && + Objects.equals(enabled, other.enabled) && + Objects.equals(id, other.id) && + Objects.equals(meta, other.meta) && + Objects.equals(name, other.name) && + Objects.equals(requiresAuth, other.requiresAuth) && + Objects.equals(type, other.type) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - accountSid, - description, - enabled, - id, - meta, - name, - requiresAuth, - type, - url, - dateCreated, - dateUpdated + accountSid, + dateCreated, + dateUpdated, + description, + enabled, + id, + meta, + name, + requiresAuth, + type, + url ); } + + } + diff --git a/src/main/java/com/twilio/rest/assistants/v1/assistant/AssistantsToolCreator.java b/src/main/java/com/twilio/rest/assistants/v1/assistant/AssistantsToolCreator.java index 8b2b1a87d5..391f0d5285 100644 --- a/src/main/java/com/twilio/rest/assistants/v1/assistant/AssistantsToolCreator.java +++ b/src/main/java/com/twilio/rest/assistants/v1/assistant/AssistantsToolCreator.java @@ -14,8 +14,8 @@ package com.twilio.rest.assistants.v1.assistant; + import com.twilio.base.Creator; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,56 +27,45 @@ public class AssistantsToolCreator extends Creator { - private String pathAssistantId; - private String pathId; + private String pathassistantId; + private String pathid; - public AssistantsToolCreator( - final String pathAssistantId, - final String pathId - ) { - this.pathAssistantId = pathAssistantId; - this.pathId = pathId; + public AssistantsToolCreator(final String pathassistantId, final String pathid) { + this.pathassistantId = pathassistantId; + this.pathid = pathid; } + @Override public AssistantsTool create(final TwilioRestClient client) { + String path = "/v1/Assistants/{assistantId}/Tools/{id}"; - path = - path.replace( - "{" + "assistantId" + "}", - this.pathAssistantId.toString() - ); - path = path.replace("{" + "id" + "}", this.pathId.toString()); + path = path.replace("{" + "assistantId" + "}", this.pathassistantId.toString()); + path = path.replace("{" + "id" + "}", this.pathid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.ASSISTANTS.toString(), - path + HttpMethod.POST, + Domains.ASSISTANTS.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "AssistantsTool creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("AssistantsTool creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return AssistantsTool.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return AssistantsTool.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/assistants/v1/assistant/AssistantsToolDeleter.java b/src/main/java/com/twilio/rest/assistants/v1/assistant/AssistantsToolDeleter.java index 7093946dc7..f8d713b49a 100644 --- a/src/main/java/com/twilio/rest/assistants/v1/assistant/AssistantsToolDeleter.java +++ b/src/main/java/com/twilio/rest/assistants/v1/assistant/AssistantsToolDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.assistants.v1.assistant; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,50 +26,41 @@ public class AssistantsToolDeleter extends Deleter { - private String pathAssistantId; - private String pathId; + private String pathassistantId; + private String pathid; - public AssistantsToolDeleter( - final String pathAssistantId, - final String pathId - ) { - this.pathAssistantId = pathAssistantId; - this.pathId = pathId; + public AssistantsToolDeleter(final String pathassistantId, final String pathid) { + this.pathassistantId = pathassistantId; + this.pathid = pathid; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/v1/Assistants/{assistantId}/Tools/{id}"; - path = - path.replace( - "{" + "assistantId" + "}", - this.pathAssistantId.toString() - ); - path = path.replace("{" + "id" + "}", this.pathId.toString()); + path = path.replace("{" + "assistantId" + "}", this.pathassistantId.toString()); + path = path.replace("{" + "id" + "}", this.pathid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.ASSISTANTS.toString(), - path + HttpMethod.DELETE, + Domains.ASSISTANTS.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "AssistantsTool delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("AssistantsTool delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/assistants/v1/assistant/AssistantsToolReader.java b/src/main/java/com/twilio/rest/assistants/v1/assistant/AssistantsToolReader.java index 73fed075b1..39c81f0c9a 100644 --- a/src/main/java/com/twilio/rest/assistants/v1/assistant/AssistantsToolReader.java +++ b/src/main/java/com/twilio/rest/assistants/v1/assistant/AssistantsToolReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,115 +30,88 @@ public class AssistantsToolReader extends Reader { - private String pathAssistantId; + private String pathassistantId; private Integer pageSize; - public AssistantsToolReader(final String pathAssistantId) { - this.pathAssistantId = pathAssistantId; + public AssistantsToolReader(final String pathassistantId) { + this.pathassistantId = pathassistantId; } + public AssistantsToolReader setPageSize(final Integer pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/Assistants/{assistantId}/Tools"; - path = - path.replace( - "{" + "assistantId" + "}", - this.pathAssistantId.toString() - ); + + path = path.replace("{" + "assistantId" + "}", this.pathassistantId.toString()); Request request = new Request( - HttpMethod.GET, - Domains.ASSISTANTS.toString(), - path + HttpMethod.GET, + Domains.ASSISTANTS.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "AssistantsTool read failed: Unable to connect to server" - ); + throw new ApiConnectionException("AssistantsTool read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "tools", - response.getContent(), - AssistantsTool.class, - client.getObjectMapper() - ); + "tools", + response.getContent(), + AssistantsTool.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.ASSISTANTS.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.ASSISTANTS.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/assistants/v1/assistant/Feedback.java b/src/main/java/com/twilio/rest/assistants/v1/assistant/Feedback.java index c607c9c472..3cd1a39267 100644 --- a/src/main/java/com/twilio/rest/assistants/v1/assistant/Feedback.java +++ b/src/main/java/com/twilio/rest/assistants/v1/assistant/Feedback.java @@ -22,27 +22,45 @@ import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.time.ZonedDateTime; import java.util.Objects; -import lombok.Getter; -import lombok.Setter; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Feedback extends Resource { - private static final long serialVersionUID = 81835402394387L; + public static FeedbackCreator creator(final String pathid, final Feedback.AssistantsV1ServiceCreateFeedbackRequest assistantsV1ServiceCreateFeedbackRequest) { + return new FeedbackCreator( + pathid, assistantsV1ServiceCreateFeedbackRequest + ); + } + + + public static FeedbackReader reader(final String pathid) { + return new FeedbackReader( + pathid + ); + } + + + //@JsonDeserialize(builder = AssistantsV1ServiceCreateFeedbackRequest.Builder.class) + @JsonInclude(JsonInclude.Include.NON_EMPTY) @ToString public static class AssistantsV1ServiceCreateFeedbackRequest { + public AssistantsV1ServiceCreateFeedbackRequest(final String sessionId) { + this.sessionId = sessionId; + } @JsonInclude(JsonInclude.Include.NON_EMPTY) @JsonProperty("message_id") @@ -68,48 +86,16 @@ public static class AssistantsV1ServiceCreateFeedbackRequest { @Setter private String text; - public AssistantsV1ServiceCreateFeedbackRequest( - final String sessionId - ) { - this.sessionId = sessionId; - } - - public static AssistantsV1ServiceCreateFeedbackRequest fromJson( - String jsonString, - ObjectMapper mapper - ) throws IOException { - return mapper.readValue( - jsonString, - AssistantsV1ServiceCreateFeedbackRequest.class - ); - } - } - - public static FeedbackCreator creator( - final String pathId, - final Feedback.AssistantsV1ServiceCreateFeedbackRequest assistantsV1ServiceCreateFeedbackRequest - ) { - return new FeedbackCreator( - pathId, - assistantsV1ServiceCreateFeedbackRequest - ); - } - - public static FeedbackReader reader(final String pathId) { - return new FeedbackReader(pathId); } /** * Converts a JSON String into a Feedback object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Feedback object represented by the provided JSON */ - public static Feedback fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Feedback fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Feedback.class); @@ -124,14 +110,11 @@ public static Feedback fromJson( * Converts a JSON InputStream into a Feedback object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Feedback object represented by the provided JSON */ - public static Feedback fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Feedback fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Feedback.class); @@ -154,80 +137,53 @@ public static String toJson(Object object, ObjectMapper mapper) { } } + + @Getter + private final String accountSid; + @Getter private final String assistantId; + @Getter + private final ZonedDateTime dateCreated; + @Getter + private final ZonedDateTime dateUpdated; + @Getter private final String id; - private final String accountSid; - private final String userSid; + @Getter private final String messageId; + @Getter private final Float score; + @Getter private final String sessionId; + @Getter private final String text; - private final ZonedDateTime dateCreated; - private final ZonedDateTime dateUpdated; + @Getter + private final String userSid; @JsonCreator private Feedback( - @JsonProperty("assistant_id") final String assistantId, - @JsonProperty("id") final String id, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("user_sid") final String userSid, - @JsonProperty("message_id") final String messageId, - @JsonProperty("score") final Float score, - @JsonProperty("session_id") final String sessionId, - @JsonProperty("text") final String text, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("assistant_id") final String assistantId, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("id") final String id, + @JsonProperty("message_id") final String messageId, + @JsonProperty("score") final Float score, + @JsonProperty("session_id") final String sessionId, + @JsonProperty("text") final String text, + @JsonProperty("user_sid") final String userSid ) { + this.accountSid = accountSid; this.assistantId = assistantId; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.id = id; - this.accountSid = accountSid; - this.userSid = userSid; this.messageId = messageId; this.score = score; this.sessionId = sessionId; this.text = text; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); - } - - public final String getAssistantId() { - return this.assistantId; - } - - public final String getId() { - return this.id; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getUserSid() { - return this.userSid; - } - - public final String getMessageId() { - return this.messageId; - } - - public final Float getScore() { - return this.score; - } - - public final String getSessionId() { - return this.sessionId; - } - - public final String getText() { - return this.text; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; + this.userSid = userSid; } @Override @@ -241,34 +197,36 @@ public boolean equals(final Object o) { } Feedback other = (Feedback) o; - return ( - Objects.equals(assistantId, other.assistantId) && - Objects.equals(id, other.id) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(userSid, other.userSid) && - Objects.equals(messageId, other.messageId) && - Objects.equals(score, other.score) && - Objects.equals(sessionId, other.sessionId) && - Objects.equals(text, other.text) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(assistantId, other.assistantId) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(id, other.id) && + Objects.equals(messageId, other.messageId) && + Objects.equals(score, other.score) && + Objects.equals(sessionId, other.sessionId) && + Objects.equals(text, other.text) && + Objects.equals(userSid, other.userSid) ); } @Override public int hashCode() { return Objects.hash( - assistantId, - id, - accountSid, - userSid, - messageId, - score, - sessionId, - text, - dateCreated, - dateUpdated + accountSid, + assistantId, + dateCreated, + dateUpdated, + id, + messageId, + score, + sessionId, + text, + userSid ); } + + } + diff --git a/src/main/java/com/twilio/rest/assistants/v1/assistant/FeedbackCreator.java b/src/main/java/com/twilio/rest/assistants/v1/assistant/FeedbackCreator.java index 86a729120d..91685b2731 100644 --- a/src/main/java/com/twilio/rest/assistants/v1/assistant/FeedbackCreator.java +++ b/src/main/java/com/twilio/rest/assistants/v1/assistant/FeedbackCreator.java @@ -28,78 +28,59 @@ public class FeedbackCreator extends Creator { - private String pathId; + private String pathid; private Feedback.AssistantsV1ServiceCreateFeedbackRequest assistantsV1ServiceCreateFeedbackRequest; - public FeedbackCreator( - final String pathId, - final Feedback.AssistantsV1ServiceCreateFeedbackRequest assistantsV1ServiceCreateFeedbackRequest - ) { - this.pathId = pathId; - this.assistantsV1ServiceCreateFeedbackRequest = - assistantsV1ServiceCreateFeedbackRequest; + public FeedbackCreator(final String pathid, final Feedback.AssistantsV1ServiceCreateFeedbackRequest assistantsV1ServiceCreateFeedbackRequest) { + this.pathid = pathid; + this.assistantsV1ServiceCreateFeedbackRequest = assistantsV1ServiceCreateFeedbackRequest; } - public FeedbackCreator setAssistantsV1ServiceCreateFeedbackRequest( - final Feedback.AssistantsV1ServiceCreateFeedbackRequest assistantsV1ServiceCreateFeedbackRequest - ) { - this.assistantsV1ServiceCreateFeedbackRequest = - assistantsV1ServiceCreateFeedbackRequest; + + public FeedbackCreator setAssistantsV1ServiceCreateFeedbackRequest(final Feedback.AssistantsV1ServiceCreateFeedbackRequest assistantsV1ServiceCreateFeedbackRequest) { + this.assistantsV1ServiceCreateFeedbackRequest = assistantsV1ServiceCreateFeedbackRequest; return this; } + @Override public Feedback create(final TwilioRestClient client) { + String path = "/v1/Assistants/{id}/Feedbacks"; - path = path.replace("{" + "id" + "}", this.pathId.toString()); - path = - path.replace( - "{" + "AssistantsV1ServiceCreateFeedbackRequest" + "}", - this.assistantsV1ServiceCreateFeedbackRequest.toString() - ); + path = path.replace("{" + "id" + "}", this.pathid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.ASSISTANTS.toString(), - path + HttpMethod.POST, + Domains.ASSISTANTS.toString(), + path ); request.setContentType(EnumConstants.ContentType.JSON); addPostParams(request, client); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Feedback creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("Feedback creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Feedback.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Feedback.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request, TwilioRestClient client) { ObjectMapper objectMapper = client.getObjectMapper(); if (assistantsV1ServiceCreateFeedbackRequest != null) { - request.setBody( - Feedback.toJson( - assistantsV1ServiceCreateFeedbackRequest, - objectMapper - ) - ); + request.setBody(Feedback.toJson(assistantsV1ServiceCreateFeedbackRequest, objectMapper)); } } } diff --git a/src/main/java/com/twilio/rest/assistants/v1/assistant/FeedbackReader.java b/src/main/java/com/twilio/rest/assistants/v1/assistant/FeedbackReader.java index 4dee076a8b..7a3fca834f 100644 --- a/src/main/java/com/twilio/rest/assistants/v1/assistant/FeedbackReader.java +++ b/src/main/java/com/twilio/rest/assistants/v1/assistant/FeedbackReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,111 +30,88 @@ public class FeedbackReader extends Reader { - private String pathId; + private String pathid; private Integer pageSize; - public FeedbackReader(final String pathId) { - this.pathId = pathId; + public FeedbackReader(final String pathid) { + this.pathid = pathid; } + public FeedbackReader setPageSize(final Integer pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/Assistants/{id}/Feedbacks"; - path = path.replace("{" + "id" + "}", this.pathId.toString()); + + path = path.replace("{" + "id" + "}", this.pathid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.ASSISTANTS.toString(), - path + HttpMethod.GET, + Domains.ASSISTANTS.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Feedback read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Feedback read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "feedbacks", - response.getContent(), - Feedback.class, - client.getObjectMapper() - ); + "feedbacks", + response.getContent(), + Feedback.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.ASSISTANTS.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.ASSISTANTS.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/assistants/v1/assistant/Message.java b/src/main/java/com/twilio/rest/assistants/v1/assistant/Message.java index 3891e48b3e..f9c078dab3 100644 --- a/src/main/java/com/twilio/rest/assistants/v1/assistant/Message.java +++ b/src/main/java/com/twilio/rest/assistants/v1/assistant/Message.java @@ -25,22 +25,34 @@ import com.twilio.base.Resource; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; -import java.io.IOException; -import java.io.InputStream; -import java.util.Objects; import lombok.Getter; import lombok.Setter; import lombok.ToString; -import lombok.ToString; + +import java.io.IOException; +import java.io.InputStream; +import java.util.Objects; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Message extends Resource { - private static final long serialVersionUID = 131790089402244L; + public static MessageCreator creator(final String pathid, final Message.AssistantsV1ServiceAssistantSendMessageRequest assistantsV1ServiceAssistantSendMessageRequest) { + return new MessageCreator( + pathid, assistantsV1ServiceAssistantSendMessageRequest + ); + } + + + //@JsonDeserialize(builder = AssistantsV1ServiceAssistantSendMessageRequest.Builder.class) + @JsonInclude(JsonInclude.Include.NON_EMPTY) @ToString public static class AssistantsV1ServiceAssistantSendMessageRequest { + public AssistantsV1ServiceAssistantSendMessageRequest(final String identity, final String body) { + this.identity = identity; + this.body = body; + } @JsonInclude(JsonInclude.Include.NON_EMPTY) @JsonProperty("identity") @@ -72,46 +84,16 @@ public static class AssistantsV1ServiceAssistantSendMessageRequest { @Setter private String mode; - public AssistantsV1ServiceAssistantSendMessageRequest( - final String identity, - final String body - ) { - this.identity = identity; - this.body = body; - } - - public static AssistantsV1ServiceAssistantSendMessageRequest fromJson( - String jsonString, - ObjectMapper mapper - ) throws IOException { - return mapper.readValue( - jsonString, - AssistantsV1ServiceAssistantSendMessageRequest.class - ); - } - } - - public static MessageCreator creator( - final String pathId, - final Message.AssistantsV1ServiceAssistantSendMessageRequest assistantsV1ServiceAssistantSendMessageRequest - ) { - return new MessageCreator( - pathId, - assistantsV1ServiceAssistantSendMessageRequest - ); } /** * Converts a JSON String into a Message object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Message object represented by the provided JSON */ - public static Message fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Message fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Message.class); @@ -126,14 +108,11 @@ public static Message fromJson( * Converts a JSON InputStream into a Message object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Message object represented by the provided JSON */ - public static Message fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Message fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Message.class); @@ -156,59 +135,39 @@ public static String toJson(Object object, ObjectMapper mapper) { } } - private final String status; - private final Boolean flagged; + + @Getter private final Boolean aborted; - private final String sessionId; + @Getter private final String accountSid; + @Getter private final String body; + @Getter private final String error; + @Getter + private final Boolean flagged; + @Getter + private final String sessionId; + @Getter + private final String status; @JsonCreator private Message( - @JsonProperty("status") final String status, - @JsonProperty("flagged") final Boolean flagged, - @JsonProperty("aborted") final Boolean aborted, - @JsonProperty("session_id") final String sessionId, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("body") final String body, - @JsonProperty("error") final String error + @JsonProperty("aborted") final Boolean aborted, + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("body") final String body, + @JsonProperty("error") final String error, + @JsonProperty("flagged") final Boolean flagged, + @JsonProperty("session_id") final String sessionId, + @JsonProperty("status") final String status ) { - this.status = status; - this.flagged = flagged; this.aborted = aborted; - this.sessionId = sessionId; this.accountSid = accountSid; this.body = body; this.error = error; - } - - public final String getStatus() { - return this.status; - } - - public final Boolean getFlagged() { - return this.flagged; - } - - public final Boolean getAborted() { - return this.aborted; - } - - public final String getSessionId() { - return this.sessionId; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getBody() { - return this.body; - } - - public final String getError() { - return this.error; + this.flagged = flagged; + this.sessionId = sessionId; + this.status = status; } @Override @@ -222,28 +181,30 @@ public boolean equals(final Object o) { } Message other = (Message) o; - return ( - Objects.equals(status, other.status) && - Objects.equals(flagged, other.flagged) && - Objects.equals(aborted, other.aborted) && - Objects.equals(sessionId, other.sessionId) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(body, other.body) && - Objects.equals(error, other.error) + Objects.equals(aborted, other.aborted) && + Objects.equals(accountSid, other.accountSid) && + Objects.equals(body, other.body) && + Objects.equals(error, other.error) && + Objects.equals(flagged, other.flagged) && + Objects.equals(sessionId, other.sessionId) && + Objects.equals(status, other.status) ); } @Override public int hashCode() { return Objects.hash( - status, - flagged, - aborted, - sessionId, - accountSid, - body, - error + aborted, + accountSid, + body, + error, + flagged, + sessionId, + status ); } + + } + diff --git a/src/main/java/com/twilio/rest/assistants/v1/assistant/MessageCreator.java b/src/main/java/com/twilio/rest/assistants/v1/assistant/MessageCreator.java index 3862f76d3e..e33d339b68 100644 --- a/src/main/java/com/twilio/rest/assistants/v1/assistant/MessageCreator.java +++ b/src/main/java/com/twilio/rest/assistants/v1/assistant/MessageCreator.java @@ -28,59 +28,48 @@ public class MessageCreator extends Creator { - private String pathId; + private String pathid; private Message.AssistantsV1ServiceAssistantSendMessageRequest assistantsV1ServiceAssistantSendMessageRequest; - public MessageCreator( - final String pathId, - final Message.AssistantsV1ServiceAssistantSendMessageRequest assistantsV1ServiceAssistantSendMessageRequest - ) { - this.pathId = pathId; - this.assistantsV1ServiceAssistantSendMessageRequest = - assistantsV1ServiceAssistantSendMessageRequest; + public MessageCreator(final String pathid, final Message.AssistantsV1ServiceAssistantSendMessageRequest assistantsV1ServiceAssistantSendMessageRequest) { + this.pathid = pathid; + this.assistantsV1ServiceAssistantSendMessageRequest = assistantsV1ServiceAssistantSendMessageRequest; } - public MessageCreator setAssistantsV1ServiceAssistantSendMessageRequest( - final Message.AssistantsV1ServiceAssistantSendMessageRequest assistantsV1ServiceAssistantSendMessageRequest - ) { - this.assistantsV1ServiceAssistantSendMessageRequest = - assistantsV1ServiceAssistantSendMessageRequest; + + public MessageCreator setAssistantsV1ServiceAssistantSendMessageRequest(final Message.AssistantsV1ServiceAssistantSendMessageRequest assistantsV1ServiceAssistantSendMessageRequest) { + this.assistantsV1ServiceAssistantSendMessageRequest = assistantsV1ServiceAssistantSendMessageRequest; return this; } + @Override public Message create(final TwilioRestClient client) { + String path = "/v1/Assistants/{id}/Messages"; - path = path.replace("{" + "id" + "}", this.pathId.toString()); - path = - path.replace( - "{" + "AssistantsV1ServiceAssistantSendMessageRequest" + "}", - this.assistantsV1ServiceAssistantSendMessageRequest.toString() - ); + path = path.replace("{" + "id" + "}", this.pathid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.ASSISTANTS.toString(), - path + HttpMethod.POST, + Domains.ASSISTANTS.toString(), + path ); request.setContentType(EnumConstants.ContentType.JSON); addPostParams(request, client); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Message creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("Message creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -91,12 +80,7 @@ public Message create(final TwilioRestClient client) { private void addPostParams(final Request request, TwilioRestClient client) { ObjectMapper objectMapper = client.getObjectMapper(); if (assistantsV1ServiceAssistantSendMessageRequest != null) { - request.setBody( - Message.toJson( - assistantsV1ServiceAssistantSendMessageRequest, - objectMapper - ) - ); + request.setBody(Message.toJson(assistantsV1ServiceAssistantSendMessageRequest, objectMapper)); } } } diff --git a/src/main/java/com/twilio/rest/assistants/v1/knowledge/Chunk.java b/src/main/java/com/twilio/rest/assistants/v1/knowledge/Chunk.java index 85668dd2c2..6a50bbe446 100644 --- a/src/main/java/com/twilio/rest/assistants/v1/knowledge/Chunk.java +++ b/src/main/java/com/twilio/rest/assistants/v1/knowledge/Chunk.java @@ -18,42 +18,41 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.time.ZonedDateTime; -import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Chunk extends Resource { - private static final long serialVersionUID = 152804488582909L; - public static ChunkReader reader(final String pathId) { - return new ChunkReader(pathId); + public static ChunkReader reader(final String pathid) { + return new ChunkReader( + pathid + ); } + /** * Converts a JSON String into a Chunk object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Chunk object represented by the provided JSON */ - public static Chunk fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Chunk fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Chunk.class); @@ -68,14 +67,11 @@ public static Chunk fromJson( * Converts a JSON InputStream into a Chunk object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Chunk object represented by the provided JSON */ - public static Chunk fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Chunk fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Chunk.class); @@ -86,45 +82,45 @@ public static Chunk fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; + @Getter private final String content; - private final Map metadata; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; + @Getter + private final Object metadata; @JsonCreator private Chunk( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("content") final String content, - @JsonProperty("metadata") final Map metadata, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("content") final String content, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("metadata") final Object metadata ) { this.accountSid = accountSid; this.content = content; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.metadata = metadata; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getContent() { - return this.content; - } - - public final Map getMetadata() { - return this.metadata; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; } @Override @@ -138,24 +134,26 @@ public boolean equals(final Object o) { } Chunk other = (Chunk) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(content, other.content) && - Objects.equals(metadata, other.metadata) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(content, other.content) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(metadata, other.metadata) ); } @Override public int hashCode() { return Objects.hash( - accountSid, - content, - metadata, - dateCreated, - dateUpdated + accountSid, + content, + dateCreated, + dateUpdated, + metadata ); } + + } + diff --git a/src/main/java/com/twilio/rest/assistants/v1/knowledge/ChunkReader.java b/src/main/java/com/twilio/rest/assistants/v1/knowledge/ChunkReader.java index ed0d3a7b2d..9c84aa66a4 100644 --- a/src/main/java/com/twilio/rest/assistants/v1/knowledge/ChunkReader.java +++ b/src/main/java/com/twilio/rest/assistants/v1/knowledge/ChunkReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,111 +30,88 @@ public class ChunkReader extends Reader { - private String pathId; + private String pathid; private Integer pageSize; - public ChunkReader(final String pathId) { - this.pathId = pathId; + public ChunkReader(final String pathid) { + this.pathid = pathid; } + public ChunkReader setPageSize(final Integer pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/Knowledge/{id}/Chunks"; - path = path.replace("{" + "id" + "}", this.pathId.toString()); + + path = path.replace("{" + "id" + "}", this.pathid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.ASSISTANTS.toString(), - path + HttpMethod.GET, + Domains.ASSISTANTS.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Chunk read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Chunk read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "chunks", - response.getContent(), - Chunk.class, - client.getObjectMapper() - ); + "chunks", + response.getContent(), + Chunk.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.ASSISTANTS.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.ASSISTANTS.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/assistants/v1/knowledge/KnowledgeStatus.java b/src/main/java/com/twilio/rest/assistants/v1/knowledge/KnowledgeStatus.java index 53b6a90e58..76ea254100 100644 --- a/src/main/java/com/twilio/rest/assistants/v1/knowledge/KnowledgeStatus.java +++ b/src/main/java/com/twilio/rest/assistants/v1/knowledge/KnowledgeStatus.java @@ -18,40 +18,41 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.time.ZonedDateTime; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class KnowledgeStatus extends Resource { - private static final long serialVersionUID = 178959927465400L; - public static KnowledgeStatusFetcher fetcher(final String pathId) { - return new KnowledgeStatusFetcher(pathId); + public static KnowledgeStatusFetcher fetcher(final String pathid) { + return new KnowledgeStatusFetcher( + pathid + ); } + /** * Converts a JSON String into a KnowledgeStatus object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return KnowledgeStatus object represented by the provided JSON */ - public static KnowledgeStatus fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static KnowledgeStatus fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, KnowledgeStatus.class); @@ -66,14 +67,11 @@ public static KnowledgeStatus fromJson( * Converts a JSON InputStream into a KnowledgeStatus object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return KnowledgeStatus object represented by the provided JSON */ - public static KnowledgeStatus fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static KnowledgeStatus fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, KnowledgeStatus.class); @@ -84,38 +82,40 @@ public static KnowledgeStatus fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String status; - private final String lastStatus; + @Getter private final ZonedDateTime dateUpdated; + @Getter + private final String lastStatus; + @Getter + private final String status; @JsonCreator private KnowledgeStatus( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("status") final String status, - @JsonProperty("last_status") final String lastStatus, - @JsonProperty("date_updated") final String dateUpdated + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("last_status") final String lastStatus, + @JsonProperty("status") final String status ) { this.accountSid = accountSid; - this.status = status; + this.dateUpdated = dateUpdated; this.lastStatus = lastStatus; - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getStatus() { - return this.status; - } - - public final String getLastStatus() { - return this.lastStatus; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; + this.status = status; } @Override @@ -129,17 +129,24 @@ public boolean equals(final Object o) { } KnowledgeStatus other = (KnowledgeStatus) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(status, other.status) && - Objects.equals(lastStatus, other.lastStatus) && - Objects.equals(dateUpdated, other.dateUpdated) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(lastStatus, other.lastStatus) && + Objects.equals(status, other.status) ); } @Override public int hashCode() { - return Objects.hash(accountSid, status, lastStatus, dateUpdated); + return Objects.hash( + accountSid, + dateUpdated, + lastStatus, + status + ); } + + } + diff --git a/src/main/java/com/twilio/rest/assistants/v1/knowledge/KnowledgeStatusFetcher.java b/src/main/java/com/twilio/rest/assistants/v1/knowledge/KnowledgeStatusFetcher.java index bfd9bc2dac..b446031b48 100644 --- a/src/main/java/com/twilio/rest/assistants/v1/knowledge/KnowledgeStatusFetcher.java +++ b/src/main/java/com/twilio/rest/assistants/v1/knowledge/KnowledgeStatusFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.assistants.v1.knowledge; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,47 +26,41 @@ public class KnowledgeStatusFetcher extends Fetcher { - private String pathId; + private String pathid; - public KnowledgeStatusFetcher(final String pathId) { - this.pathId = pathId; + public KnowledgeStatusFetcher(final String pathid) { + this.pathid = pathid; } + @Override public KnowledgeStatus fetch(final TwilioRestClient client) { + String path = "/v1/Knowledge/{id}/Status"; - path = path.replace("{" + "id" + "}", this.pathId.toString()); + path = path.replace("{" + "id" + "}", this.pathid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.ASSISTANTS.toString(), - path + HttpMethod.GET, + Domains.ASSISTANTS.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "KnowledgeStatus fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("KnowledgeStatus fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return KnowledgeStatus.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return KnowledgeStatus.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/assistants/v1/session/Message.java b/src/main/java/com/twilio/rest/assistants/v1/session/Message.java index 8f5ade962d..884f07d689 100644 --- a/src/main/java/com/twilio/rest/assistants/v1/session/Message.java +++ b/src/main/java/com/twilio/rest/assistants/v1/session/Message.java @@ -18,42 +18,41 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.time.ZonedDateTime; -import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Message extends Resource { - private static final long serialVersionUID = 88120971522058L; - public static MessageReader reader(final String pathSessionId) { - return new MessageReader(pathSessionId); + public static MessageReader reader(final String pathsessionId) { + return new MessageReader( + pathsessionId + ); } + /** * Converts a JSON String into a Message object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Message object represented by the provided JSON */ - public static Message fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Message fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Message.class); @@ -68,14 +67,11 @@ public static Message fromJson( * Converts a JSON InputStream into a Message object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Message object represented by the provided JSON */ - public static Message fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Message fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Message.class); @@ -86,80 +82,65 @@ public static Message fromJson( } } - private final String id; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; + @Getter private final String assistantId; - private final String sessionId; - private final String identity; - private final String role; - private final Map content; - private final Map meta; + @Getter + private final Object content; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; + @Getter + private final String id; + @Getter + private final String identity; + @Getter + private final Object meta; + @Getter + private final String role; + @Getter + private final String sessionId; @JsonCreator private Message( - @JsonProperty("id") final String id, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("assistant_id") final String assistantId, - @JsonProperty("session_id") final String sessionId, - @JsonProperty("identity") final String identity, - @JsonProperty("role") final String role, - @JsonProperty("content") final Map content, - @JsonProperty("meta") final Map meta, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("assistant_id") final String assistantId, + @JsonProperty("content") final Object content, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("id") final String id, + @JsonProperty("identity") final String identity, + @JsonProperty("meta") final Object meta, + @JsonProperty("role") final String role, + @JsonProperty("session_id") final String sessionId ) { - this.id = id; this.accountSid = accountSid; this.assistantId = assistantId; - this.sessionId = sessionId; - this.identity = identity; - this.role = role; this.content = content; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; + this.id = id; + this.identity = identity; this.meta = meta; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); - } - - public final String getId() { - return this.id; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getAssistantId() { - return this.assistantId; - } - - public final String getSessionId() { - return this.sessionId; - } - - public final String getIdentity() { - return this.identity; - } - - public final String getRole() { - return this.role; - } - - public final Map getContent() { - return this.content; - } - - public final Map getMeta() { - return this.meta; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; + this.role = role; + this.sessionId = sessionId; } @Override @@ -173,34 +154,36 @@ public boolean equals(final Object o) { } Message other = (Message) o; - return ( - Objects.equals(id, other.id) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(assistantId, other.assistantId) && - Objects.equals(sessionId, other.sessionId) && - Objects.equals(identity, other.identity) && - Objects.equals(role, other.role) && - Objects.equals(content, other.content) && - Objects.equals(meta, other.meta) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(assistantId, other.assistantId) && + Objects.equals(content, other.content) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(id, other.id) && + Objects.equals(identity, other.identity) && + Objects.equals(meta, other.meta) && + Objects.equals(role, other.role) && + Objects.equals(sessionId, other.sessionId) ); } @Override public int hashCode() { return Objects.hash( - id, - accountSid, - assistantId, - sessionId, - identity, - role, - content, - meta, - dateCreated, - dateUpdated + accountSid, + assistantId, + content, + dateCreated, + dateUpdated, + id, + identity, + meta, + role, + sessionId ); } + + } + diff --git a/src/main/java/com/twilio/rest/assistants/v1/session/MessageReader.java b/src/main/java/com/twilio/rest/assistants/v1/session/MessageReader.java index a4efe9d8ac..51f70878bc 100644 --- a/src/main/java/com/twilio/rest/assistants/v1/session/MessageReader.java +++ b/src/main/java/com/twilio/rest/assistants/v1/session/MessageReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,115 +30,88 @@ public class MessageReader extends Reader { - private String pathSessionId; + private String pathsessionId; private Integer pageSize; - public MessageReader(final String pathSessionId) { - this.pathSessionId = pathSessionId; + public MessageReader(final String pathsessionId) { + this.pathsessionId = pathsessionId; } + public MessageReader setPageSize(final Integer pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/Sessions/{sessionId}/Messages"; - path = - path.replace( - "{" + "sessionId" + "}", - this.pathSessionId.toString() - ); + + path = path.replace("{" + "sessionId" + "}", this.pathsessionId.toString()); Request request = new Request( - HttpMethod.GET, - Domains.ASSISTANTS.toString(), - path + HttpMethod.GET, + Domains.ASSISTANTS.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Message read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Message read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "messages", - response.getContent(), - Message.class, - client.getObjectMapper() - ); + "messages", + response.getContent(), + Message.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.ASSISTANTS.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.ASSISTANTS.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/bulkexports/v1/Export.java b/src/main/java/com/twilio/rest/bulkexports/v1/Export.java index 79abf7db2b..68912e92a8 100644 --- a/src/main/java/com/twilio/rest/bulkexports/v1/Export.java +++ b/src/main/java/com/twilio/rest/bulkexports/v1/Export.java @@ -18,41 +18,41 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Export extends Resource { - private static final long serialVersionUID = 148899891151757L; - public static ExportFetcher fetcher(final String pathResourceType) { - return new ExportFetcher(pathResourceType); + public static ExportFetcher fetcher(final String pathresourceType) { + return new ExportFetcher( + pathresourceType + ); } + /** * Converts a JSON String into a Export object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Export object represented by the provided JSON */ - public static Export fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Export fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Export.class); @@ -67,14 +67,11 @@ public static Export fromJson( * Converts a JSON InputStream into a Export object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Export object represented by the provided JSON */ - public static Export fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Export fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Export.class); @@ -85,31 +82,35 @@ public static Export fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter + private final Map links; + @Getter private final String resourceType; + @Getter private final URI url; - private final Map links; @JsonCreator private Export( - @JsonProperty("resource_type") final String resourceType, - @JsonProperty("url") final URI url, - @JsonProperty("links") final Map links + @JsonProperty("links") final Map links, + @JsonProperty("resource_type") final String resourceType, + @JsonProperty("url") final URI url ) { + this.links = links; this.resourceType = resourceType; this.url = url; - this.links = links; - } - - public final String getResourceType() { - return this.resourceType; - } - - public final URI getUrl() { - return this.url; - } - - public final Map getLinks() { - return this.links; } @Override @@ -123,16 +124,22 @@ public boolean equals(final Object o) { } Export other = (Export) o; - return ( - Objects.equals(resourceType, other.resourceType) && - Objects.equals(url, other.url) && - Objects.equals(links, other.links) + Objects.equals(links, other.links) && + Objects.equals(resourceType, other.resourceType) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { - return Objects.hash(resourceType, url, links); + return Objects.hash( + links, + resourceType, + url + ); } + + } + diff --git a/src/main/java/com/twilio/rest/bulkexports/v1/ExportConfiguration.java b/src/main/java/com/twilio/rest/bulkexports/v1/ExportConfiguration.java index a1c21404ba..9e367ca34f 100644 --- a/src/main/java/com/twilio/rest/bulkexports/v1/ExportConfiguration.java +++ b/src/main/java/com/twilio/rest/bulkexports/v1/ExportConfiguration.java @@ -18,47 +18,47 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class ExportConfiguration extends Resource { - private static final long serialVersionUID = 268277535772365L; - public static ExportConfigurationFetcher fetcher( - final String pathResourceType - ) { - return new ExportConfigurationFetcher(pathResourceType); + public static ExportConfigurationFetcher fetcher(final String pathresourceType) { + return new ExportConfigurationFetcher( + pathresourceType + ); } - public static ExportConfigurationUpdater updater( - final String pathResourceType - ) { - return new ExportConfigurationUpdater(pathResourceType); + + public static ExportConfigurationUpdater updater(final String pathresourceType) { + return new ExportConfigurationUpdater( + pathresourceType + ); } + /** * Converts a JSON String into a ExportConfiguration object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return ExportConfiguration object represented by the provided JSON */ - public static ExportConfiguration fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static ExportConfiguration fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, ExportConfiguration.class); @@ -73,14 +73,11 @@ public static ExportConfiguration fromJson( * Converts a JSON InputStream into a ExportConfiguration object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return ExportConfiguration object represented by the provided JSON */ - public static ExportConfiguration fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static ExportConfiguration fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, ExportConfiguration.class); @@ -91,45 +88,43 @@ public static ExportConfiguration fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final Boolean enabled; - private final URI webhookUrl; - private final String webhookMethod; + @Getter private final String resourceType; + @Getter private final URI url; + @Getter + private final String webhookMethod; + @Getter + private final URI webhookUrl; @JsonCreator private ExportConfiguration( - @JsonProperty("enabled") final Boolean enabled, - @JsonProperty("webhook_url") final URI webhookUrl, - @JsonProperty("webhook_method") final String webhookMethod, - @JsonProperty("resource_type") final String resourceType, - @JsonProperty("url") final URI url + @JsonProperty("enabled") final Boolean enabled, + @JsonProperty("resource_type") final String resourceType, + @JsonProperty("url") final URI url, + @JsonProperty("webhook_method") final String webhookMethod, + @JsonProperty("webhook_url") final URI webhookUrl ) { this.enabled = enabled; - this.webhookUrl = webhookUrl; - this.webhookMethod = webhookMethod; this.resourceType = resourceType; this.url = url; - } - - public final Boolean getEnabled() { - return this.enabled; - } - - public final URI getWebhookUrl() { - return this.webhookUrl; - } - - public final String getWebhookMethod() { - return this.webhookMethod; - } - - public final String getResourceType() { - return this.resourceType; - } - - public final URI getUrl() { - return this.url; + this.webhookMethod = webhookMethod; + this.webhookUrl = webhookUrl; } @Override @@ -143,24 +138,26 @@ public boolean equals(final Object o) { } ExportConfiguration other = (ExportConfiguration) o; - return ( - Objects.equals(enabled, other.enabled) && - Objects.equals(webhookUrl, other.webhookUrl) && - Objects.equals(webhookMethod, other.webhookMethod) && - Objects.equals(resourceType, other.resourceType) && - Objects.equals(url, other.url) + Objects.equals(enabled, other.enabled) && + Objects.equals(resourceType, other.resourceType) && + Objects.equals(url, other.url) && + Objects.equals(webhookMethod, other.webhookMethod) && + Objects.equals(webhookUrl, other.webhookUrl) ); } @Override public int hashCode() { return Objects.hash( - enabled, - webhookUrl, - webhookMethod, - resourceType, - url + enabled, + resourceType, + url, + webhookMethod, + webhookUrl ); } + + } + diff --git a/src/main/java/com/twilio/rest/bulkexports/v1/ExportConfigurationFetcher.java b/src/main/java/com/twilio/rest/bulkexports/v1/ExportConfigurationFetcher.java index 7c1b840680..56384a1e70 100644 --- a/src/main/java/com/twilio/rest/bulkexports/v1/ExportConfigurationFetcher.java +++ b/src/main/java/com/twilio/rest/bulkexports/v1/ExportConfigurationFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.bulkexports.v1; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,51 +26,41 @@ public class ExportConfigurationFetcher extends Fetcher { - private String pathResourceType; + private String pathresourceType; - public ExportConfigurationFetcher(final String pathResourceType) { - this.pathResourceType = pathResourceType; + public ExportConfigurationFetcher(final String pathresourceType) { + this.pathresourceType = pathresourceType; } + @Override public ExportConfiguration fetch(final TwilioRestClient client) { + String path = "/v1/Exports/{ResourceType}/Configuration"; - path = - path.replace( - "{" + "ResourceType" + "}", - this.pathResourceType.toString() - ); + path = path.replace("{" + "ResourceType" + "}", this.pathresourceType.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.BULKEXPORTS.toString(), - path + HttpMethod.GET, + Domains.BULKEXPORTS.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "ExportConfiguration fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("ExportConfiguration fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return ExportConfiguration.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return ExportConfiguration.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/bulkexports/v1/ExportConfigurationUpdater.java b/src/main/java/com/twilio/rest/bulkexports/v1/ExportConfigurationUpdater.java index 4df31b692f..e195dcfc0f 100644 --- a/src/main/java/com/twilio/rest/bulkexports/v1/ExportConfigurationUpdater.java +++ b/src/main/java/com/twilio/rest/bulkexports/v1/ExportConfigurationUpdater.java @@ -16,7 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; -import com.twilio.converter.Promoter; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,91 +26,88 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.net.URI; public class ExportConfigurationUpdater extends Updater { - - private String pathResourceType; + private String pathresourceType; private Boolean enabled; private URI webhookUrl; private String webhookMethod; - public ExportConfigurationUpdater(final String pathResourceType) { - this.pathResourceType = pathResourceType; + public ExportConfigurationUpdater(final String pathresourceType) { + this.pathresourceType = pathresourceType; } + public ExportConfigurationUpdater setEnabled(final Boolean enabled) { this.enabled = enabled; return this; } + public ExportConfigurationUpdater setWebhookUrl(final URI webhookUrl) { this.webhookUrl = webhookUrl; return this; } - public ExportConfigurationUpdater setWebhookUrl(final String webhookUrl) { - return setWebhookUrl(Promoter.uriFromString(webhookUrl)); - } - public ExportConfigurationUpdater setWebhookMethod( - final String webhookMethod - ) { + public ExportConfigurationUpdater setWebhookMethod(final String webhookMethod) { this.webhookMethod = webhookMethod; return this; } + @Override public ExportConfiguration update(final TwilioRestClient client) { + String path = "/v1/Exports/{ResourceType}/Configuration"; - path = - path.replace( - "{" + "ResourceType" + "}", - this.pathResourceType.toString() - ); + path = path.replace("{" + "ResourceType" + "}", this.pathresourceType.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.BULKEXPORTS.toString(), - path + HttpMethod.POST, + Domains.BULKEXPORTS.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "ExportConfiguration update failed: Unable to connect to server" - ); + throw new ApiConnectionException("ExportConfiguration update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return ExportConfiguration.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return ExportConfiguration.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (enabled != null) { - request.addPostParam("Enabled", enabled.toString()); + Serializer.toString(request, "Enabled", enabled, ParameterType.URLENCODED); } + + if (webhookUrl != null) { - request.addPostParam("WebhookUrl", webhookUrl.toString()); + Serializer.toString(request, "WebhookUrl", webhookUrl, ParameterType.URLENCODED); } + + if (webhookMethod != null) { - request.addPostParam("WebhookMethod", webhookMethod); + Serializer.toString(request, "WebhookMethod", webhookMethod, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/bulkexports/v1/ExportFetcher.java b/src/main/java/com/twilio/rest/bulkexports/v1/ExportFetcher.java index c0c0ab6636..058ed17770 100644 --- a/src/main/java/com/twilio/rest/bulkexports/v1/ExportFetcher.java +++ b/src/main/java/com/twilio/rest/bulkexports/v1/ExportFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.bulkexports.v1; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,48 +26,41 @@ public class ExportFetcher extends Fetcher { - private String pathResourceType; + private String pathresourceType; - public ExportFetcher(final String pathResourceType) { - this.pathResourceType = pathResourceType; + public ExportFetcher(final String pathresourceType) { + this.pathresourceType = pathresourceType; } + @Override public Export fetch(final TwilioRestClient client) { + String path = "/v1/Exports/{ResourceType}"; - path = - path.replace( - "{" + "ResourceType" + "}", - this.pathResourceType.toString() - ); + path = path.replace("{" + "ResourceType" + "}", this.pathresourceType.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.BULKEXPORTS.toString(), - path + HttpMethod.GET, + Domains.BULKEXPORTS.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Export fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Export fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Export.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/bulkexports/v1/export/Day.java b/src/main/java/com/twilio/rest/bulkexports/v1/export/Day.java index 200be912d9..10226fdb9f 100644 --- a/src/main/java/com/twilio/rest/bulkexports/v1/export/Day.java +++ b/src/main/java/com/twilio/rest/bulkexports/v1/export/Day.java @@ -18,46 +18,47 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Day extends Resource { - private static final long serialVersionUID = 277630118297206L; - public static DayFetcher fetcher( - final String pathResourceType, - final String pathDay - ) { - return new DayFetcher(pathResourceType, pathDay); + public static DayFetcher fetcher(final String pathresourceType, final String pathday) { + return new DayFetcher( + pathresourceType, pathday + ); } - public static DayReader reader(final String pathResourceType) { - return new DayReader(pathResourceType); + + public static DayReader reader(final String pathresourceType) { + return new DayReader( + pathresourceType + ); } + /** * Converts a JSON String into a Day object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Day object represented by the provided JSON */ - public static Day fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Day fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Day.class); @@ -72,14 +73,11 @@ public static Day fromJson( * Converts a JSON InputStream into a Day object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Day object represented by the provided JSON */ - public static Day fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Day fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Day.class); @@ -90,52 +88,47 @@ public static Day fromJson( } } - private final URI redirectTo; - private final String day; - private final Integer size; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String createDate; + @Getter + private final String day; + @Getter private final String friendlyName; + @Getter + private final URI redirectTo; + @Getter private final String resourceType; + @Getter + private final Integer size; @JsonCreator private Day( - @JsonProperty("redirect_to") final URI redirectTo, - @JsonProperty("day") final String day, - @JsonProperty("size") final Integer size, - @JsonProperty("create_date") final String createDate, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("resource_type") final String resourceType + @JsonProperty("create_date") final String createDate, + @JsonProperty("day") final String day, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("redirect_to") final URI redirectTo, + @JsonProperty("resource_type") final String resourceType, + @JsonProperty("size") final Integer size ) { - this.redirectTo = redirectTo; - this.day = day; - this.size = size; this.createDate = createDate; + this.day = day; this.friendlyName = friendlyName; + this.redirectTo = redirectTo; this.resourceType = resourceType; - } - - public final URI getRedirectTo() { - return this.redirectTo; - } - - public final String getDay() { - return this.day; - } - - public final Integer getSize() { - return this.size; - } - - public final String getCreateDate() { - return this.createDate; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final String getResourceType() { - return this.resourceType; + this.size = size; } @Override @@ -149,26 +142,28 @@ public boolean equals(final Object o) { } Day other = (Day) o; - return ( - Objects.equals(redirectTo, other.redirectTo) && - Objects.equals(day, other.day) && - Objects.equals(size, other.size) && - Objects.equals(createDate, other.createDate) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(resourceType, other.resourceType) + Objects.equals(createDate, other.createDate) && + Objects.equals(day, other.day) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(redirectTo, other.redirectTo) && + Objects.equals(resourceType, other.resourceType) && + Objects.equals(size, other.size) ); } @Override public int hashCode() { return Objects.hash( - redirectTo, - day, - size, - createDate, - friendlyName, - resourceType + createDate, + day, + friendlyName, + redirectTo, + resourceType, + size ); } + + } + diff --git a/src/main/java/com/twilio/rest/bulkexports/v1/export/DayFetcher.java b/src/main/java/com/twilio/rest/bulkexports/v1/export/DayFetcher.java index 5072e5355f..bb3954d788 100644 --- a/src/main/java/com/twilio/rest/bulkexports/v1/export/DayFetcher.java +++ b/src/main/java/com/twilio/rest/bulkexports/v1/export/DayFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.bulkexports.v1.export; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,51 +26,44 @@ public class DayFetcher extends Fetcher { - private String pathResourceType; - private String pathDay; + private String pathresourceType; + private String pathday; - public DayFetcher(final String pathResourceType, final String pathDay) { - this.pathResourceType = pathResourceType; - this.pathDay = pathDay; + public DayFetcher(final String pathresourceType, final String pathday) { + this.pathresourceType = pathresourceType; + this.pathday = pathday; } + @Override public Day fetch(final TwilioRestClient client) { + String path = "/v1/Exports/{ResourceType}/Days/{Day}"; - path = - path.replace( - "{" + "ResourceType" + "}", - this.pathResourceType.toString() - ); - path = path.replace("{" + "Day" + "}", this.pathDay.toString()); + path = path.replace("{" + "ResourceType" + "}", this.pathresourceType.toString()); + path = path.replace("{" + "Day" + "}", this.pathday.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.BULKEXPORTS.toString(), - path + HttpMethod.GET, + Domains.BULKEXPORTS.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Day fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Day fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Day.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/bulkexports/v1/export/DayReader.java b/src/main/java/com/twilio/rest/bulkexports/v1/export/DayReader.java index e8b2c1ab24..b080c20b24 100644 --- a/src/main/java/com/twilio/rest/bulkexports/v1/export/DayReader.java +++ b/src/main/java/com/twilio/rest/bulkexports/v1/export/DayReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,115 +30,88 @@ public class DayReader extends Reader { - private String pathResourceType; + private String pathresourceType; private Long pageSize; - public DayReader(final String pathResourceType) { - this.pathResourceType = pathResourceType; + public DayReader(final String pathresourceType) { + this.pathresourceType = pathresourceType; } + public DayReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/Exports/{ResourceType}/Days"; - path = - path.replace( - "{" + "ResourceType" + "}", - this.pathResourceType.toString() - ); + + path = path.replace("{" + "ResourceType" + "}", this.pathresourceType.toString()); Request request = new Request( - HttpMethod.GET, - Domains.BULKEXPORTS.toString(), - path + HttpMethod.GET, + Domains.BULKEXPORTS.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Day read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Day read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "days", - response.getContent(), - Day.class, - client.getObjectMapper() - ); + "days", + response.getContent(), + Day.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.BULKEXPORTS.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.BULKEXPORTS.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/bulkexports/v1/export/ExportCustomJob.java b/src/main/java/com/twilio/rest/bulkexports/v1/export/ExportCustomJob.java index ee3bc089bb..24c091eff6 100644 --- a/src/main/java/com/twilio/rest/bulkexports/v1/export/ExportCustomJob.java +++ b/src/main/java/com/twilio/rest/bulkexports/v1/export/ExportCustomJob.java @@ -18,55 +18,47 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.util.List; -import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class ExportCustomJob extends Resource { - private static final long serialVersionUID = 87737406045908L; - public static ExportCustomJobCreator creator( - final String pathResourceType, - final String startDay, - final String endDay, - final String friendlyName - ) { + public static ExportCustomJobCreator creator(final String pathresourceType, final String startDay, final String endDay, final String friendlyName) { return new ExportCustomJobCreator( - pathResourceType, - startDay, - endDay, - friendlyName + pathresourceType, startDay, endDay, friendlyName ); } - public static ExportCustomJobReader reader(final String pathResourceType) { - return new ExportCustomJobReader(pathResourceType); + + public static ExportCustomJobReader reader(final String pathresourceType) { + return new ExportCustomJobReader( + pathresourceType + ); } + /** * Converts a JSON String into a ExportCustomJob object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return ExportCustomJob object represented by the provided JSON */ - public static ExportCustomJob fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static ExportCustomJob fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, ExportCustomJob.class); @@ -81,14 +73,11 @@ public static ExportCustomJob fromJson( * Converts a JSON InputStream into a ExportCustomJob object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return ExportCustomJob object represented by the provided JSON */ - public static ExportCustomJob fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static ExportCustomJob fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, ExportCustomJob.class); @@ -99,89 +88,67 @@ public static ExportCustomJob fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter + private final List details; + @Getter + private final String email; + @Getter + private final String endDay; + @Getter + private final String estimatedCompletionTime; + @Getter private final String friendlyName; + @Getter + private final String jobQueuePosition; + @Getter + private final String jobSid; + @Getter private final String resourceType; + @Getter private final String startDay; - private final String endDay; - private final String webhookUrl; + @Getter private final String webhookMethod; - private final String email; - private final String jobSid; - private final List> details; - private final String jobQueuePosition; - private final String estimatedCompletionTime; + @Getter + private final String webhookUrl; @JsonCreator private ExportCustomJob( - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("resource_type") final String resourceType, - @JsonProperty("start_day") final String startDay, - @JsonProperty("end_day") final String endDay, - @JsonProperty("webhook_url") final String webhookUrl, - @JsonProperty("webhook_method") final String webhookMethod, - @JsonProperty("email") final String email, - @JsonProperty("job_sid") final String jobSid, - @JsonProperty("details") final List> details, - @JsonProperty("job_queue_position") final String jobQueuePosition, - @JsonProperty( - "estimated_completion_time" - ) final String estimatedCompletionTime + @JsonProperty("details") final List details, + @JsonProperty("email") final String email, + @JsonProperty("end_day") final String endDay, + @JsonProperty("estimated_completion_time") final String estimatedCompletionTime, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("job_queue_position") final String jobQueuePosition, + @JsonProperty("job_sid") final String jobSid, + @JsonProperty("resource_type") final String resourceType, + @JsonProperty("start_day") final String startDay, + @JsonProperty("webhook_method") final String webhookMethod, + @JsonProperty("webhook_url") final String webhookUrl ) { + this.details = details; + this.email = email; + this.endDay = endDay; + this.estimatedCompletionTime = estimatedCompletionTime; this.friendlyName = friendlyName; + this.jobQueuePosition = jobQueuePosition; + this.jobSid = jobSid; this.resourceType = resourceType; this.startDay = startDay; - this.endDay = endDay; - this.webhookUrl = webhookUrl; this.webhookMethod = webhookMethod; - this.email = email; - this.jobSid = jobSid; - this.details = details; - this.jobQueuePosition = jobQueuePosition; - this.estimatedCompletionTime = estimatedCompletionTime; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final String getResourceType() { - return this.resourceType; - } - - public final String getStartDay() { - return this.startDay; - } - - public final String getEndDay() { - return this.endDay; - } - - public final String getWebhookUrl() { - return this.webhookUrl; - } - - public final String getWebhookMethod() { - return this.webhookMethod; - } - - public final String getEmail() { - return this.email; - } - - public final String getJobSid() { - return this.jobSid; - } - - public final List> getDetails() { - return this.details; - } - - public final String getJobQueuePosition() { - return this.jobQueuePosition; - } - - public final String getEstimatedCompletionTime() { - return this.estimatedCompletionTime; + this.webhookUrl = webhookUrl; } @Override @@ -195,39 +162,38 @@ public boolean equals(final Object o) { } ExportCustomJob other = (ExportCustomJob) o; - return ( - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(resourceType, other.resourceType) && - Objects.equals(startDay, other.startDay) && - Objects.equals(endDay, other.endDay) && - Objects.equals(webhookUrl, other.webhookUrl) && - Objects.equals(webhookMethod, other.webhookMethod) && - Objects.equals(email, other.email) && - Objects.equals(jobSid, other.jobSid) && - Objects.equals(details, other.details) && - Objects.equals(jobQueuePosition, other.jobQueuePosition) && - Objects.equals( - estimatedCompletionTime, - other.estimatedCompletionTime - ) + Objects.equals(details, other.details) && + Objects.equals(email, other.email) && + Objects.equals(endDay, other.endDay) && + Objects.equals(estimatedCompletionTime, other.estimatedCompletionTime) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(jobQueuePosition, other.jobQueuePosition) && + Objects.equals(jobSid, other.jobSid) && + Objects.equals(resourceType, other.resourceType) && + Objects.equals(startDay, other.startDay) && + Objects.equals(webhookMethod, other.webhookMethod) && + Objects.equals(webhookUrl, other.webhookUrl) ); } @Override public int hashCode() { return Objects.hash( - friendlyName, - resourceType, - startDay, - endDay, - webhookUrl, - webhookMethod, - email, - jobSid, - details, - jobQueuePosition, - estimatedCompletionTime + details, + email, + endDay, + estimatedCompletionTime, + friendlyName, + jobQueuePosition, + jobSid, + resourceType, + startDay, + webhookMethod, + webhookUrl ); } + + } + diff --git a/src/main/java/com/twilio/rest/bulkexports/v1/export/ExportCustomJobCreator.java b/src/main/java/com/twilio/rest/bulkexports/v1/export/ExportCustomJobCreator.java index d99396816b..64615554f9 100644 --- a/src/main/java/com/twilio/rest/bulkexports/v1/export/ExportCustomJobCreator.java +++ b/src/main/java/com/twilio/rest/bulkexports/v1/export/ExportCustomJobCreator.java @@ -14,8 +14,11 @@ package com.twilio.rest.bulkexports.v1.export; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,7 +30,7 @@ public class ExportCustomJobCreator extends Creator { - private String pathResourceType; + private String pathresourceType; private String startDay; private String endDay; private String friendlyName; @@ -35,115 +38,115 @@ public class ExportCustomJobCreator extends Creator { private String webhookMethod; private String email; - public ExportCustomJobCreator( - final String pathResourceType, - final String startDay, - final String endDay, - final String friendlyName - ) { - this.pathResourceType = pathResourceType; + public ExportCustomJobCreator(final String pathresourceType, final String startDay, final String endDay, final String friendlyName) { + this.pathresourceType = pathresourceType; this.startDay = startDay; this.endDay = endDay; this.friendlyName = friendlyName; } + public ExportCustomJobCreator setStartDay(final String startDay) { this.startDay = startDay; return this; } + public ExportCustomJobCreator setEndDay(final String endDay) { this.endDay = endDay; return this; } + public ExportCustomJobCreator setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + public ExportCustomJobCreator setWebhookUrl(final String webhookUrl) { this.webhookUrl = webhookUrl; return this; } + public ExportCustomJobCreator setWebhookMethod(final String webhookMethod) { this.webhookMethod = webhookMethod; return this; } + public ExportCustomJobCreator setEmail(final String email) { this.email = email; return this; } + @Override public ExportCustomJob create(final TwilioRestClient client) { + String path = "/v1/Exports/{ResourceType}/Jobs"; - path = - path.replace( - "{" + "ResourceType" + "}", - this.pathResourceType.toString() - ); - path = path.replace("{" + "StartDay" + "}", this.startDay.toString()); - path = path.replace("{" + "EndDay" + "}", this.endDay.toString()); - path = - path.replace( - "{" + "FriendlyName" + "}", - this.friendlyName.toString() - ); + path = path.replace("{" + "ResourceType" + "}", this.pathresourceType.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.BULKEXPORTS.toString(), - path + HttpMethod.POST, + Domains.BULKEXPORTS.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "ExportCustomJob creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("ExportCustomJob creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return ExportCustomJob.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return ExportCustomJob.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (startDay != null) { - request.addPostParam("StartDay", startDay); + Serializer.toString(request, "StartDay", startDay, ParameterType.URLENCODED); } + + if (endDay != null) { - request.addPostParam("EndDay", endDay); + Serializer.toString(request, "EndDay", endDay, ParameterType.URLENCODED); } + + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + if (webhookUrl != null) { - request.addPostParam("WebhookUrl", webhookUrl); + Serializer.toString(request, "WebhookUrl", webhookUrl, ParameterType.URLENCODED); } + + if (webhookMethod != null) { - request.addPostParam("WebhookMethod", webhookMethod); + Serializer.toString(request, "WebhookMethod", webhookMethod, ParameterType.URLENCODED); } + + if (email != null) { - request.addPostParam("Email", email); + Serializer.toString(request, "Email", email, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/bulkexports/v1/export/ExportCustomJobReader.java b/src/main/java/com/twilio/rest/bulkexports/v1/export/ExportCustomJobReader.java index a0fb3f88ee..987acb172f 100644 --- a/src/main/java/com/twilio/rest/bulkexports/v1/export/ExportCustomJobReader.java +++ b/src/main/java/com/twilio/rest/bulkexports/v1/export/ExportCustomJobReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,115 +30,88 @@ public class ExportCustomJobReader extends Reader { - private String pathResourceType; + private String pathresourceType; private Long pageSize; - public ExportCustomJobReader(final String pathResourceType) { - this.pathResourceType = pathResourceType; + public ExportCustomJobReader(final String pathresourceType) { + this.pathresourceType = pathresourceType; } + public ExportCustomJobReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/Exports/{ResourceType}/Jobs"; - path = - path.replace( - "{" + "ResourceType" + "}", - this.pathResourceType.toString() - ); + + path = path.replace("{" + "ResourceType" + "}", this.pathresourceType.toString()); Request request = new Request( - HttpMethod.GET, - Domains.BULKEXPORTS.toString(), - path + HttpMethod.GET, + Domains.BULKEXPORTS.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "ExportCustomJob read failed: Unable to connect to server" - ); + throw new ApiConnectionException("ExportCustomJob read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "jobs", - response.getContent(), - ExportCustomJob.class, - client.getObjectMapper() - ); + "jobs", + response.getContent(), + ExportCustomJob.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.BULKEXPORTS.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.BULKEXPORTS.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/bulkexports/v1/export/Job.java b/src/main/java/com/twilio/rest/bulkexports/v1/export/Job.java index 685913964b..25cec6e7d4 100644 --- a/src/main/java/com/twilio/rest/bulkexports/v1/export/Job.java +++ b/src/main/java/com/twilio/rest/bulkexports/v1/export/Job.java @@ -18,46 +18,48 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.util.List; -import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Job extends Resource { - private static final long serialVersionUID = 152000944333983L; - public static JobDeleter deleter(final String pathJobSid) { - return new JobDeleter(pathJobSid); + public static JobDeleter deleter(final String pathjobSid) { + return new JobDeleter( + pathjobSid + ); } - public static JobFetcher fetcher(final String pathJobSid) { - return new JobFetcher(pathJobSid); + + public static JobFetcher fetcher(final String pathjobSid) { + return new JobFetcher( + pathjobSid + ); } + /** * Converts a JSON String into a Job object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Job object represented by the provided JSON */ - public static Job fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Job fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Job.class); @@ -72,14 +74,11 @@ public static Job fromJson( * Converts a JSON InputStream into a Job object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Job object represented by the provided JSON */ - public static Job fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Job fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Job.class); @@ -90,96 +89,71 @@ public static Job fromJson( } } - private final String resourceType; - private final String friendlyName; - private final List> details; - private final String startDay; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter + private final List details; + @Getter + private final String email; + @Getter private final String endDay; + @Getter + private final String estimatedCompletionTime; + @Getter + private final String friendlyName; + @Getter + private final String jobQueuePosition; + @Getter private final String jobSid; - private final String webhookUrl; - private final String webhookMethod; - private final String email; + @Getter + private final String resourceType; + @Getter + private final String startDay; + @Getter private final URI url; - private final String jobQueuePosition; - private final String estimatedCompletionTime; + @Getter + private final String webhookMethod; + @Getter + private final String webhookUrl; @JsonCreator private Job( - @JsonProperty("resource_type") final String resourceType, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("details") final List> details, - @JsonProperty("start_day") final String startDay, - @JsonProperty("end_day") final String endDay, - @JsonProperty("job_sid") final String jobSid, - @JsonProperty("webhook_url") final String webhookUrl, - @JsonProperty("webhook_method") final String webhookMethod, - @JsonProperty("email") final String email, - @JsonProperty("url") final URI url, - @JsonProperty("job_queue_position") final String jobQueuePosition, - @JsonProperty( - "estimated_completion_time" - ) final String estimatedCompletionTime + @JsonProperty("details") final List details, + @JsonProperty("email") final String email, + @JsonProperty("end_day") final String endDay, + @JsonProperty("estimated_completion_time") final String estimatedCompletionTime, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("job_queue_position") final String jobQueuePosition, + @JsonProperty("job_sid") final String jobSid, + @JsonProperty("resource_type") final String resourceType, + @JsonProperty("start_day") final String startDay, + @JsonProperty("url") final URI url, + @JsonProperty("webhook_method") final String webhookMethod, + @JsonProperty("webhook_url") final String webhookUrl ) { - this.resourceType = resourceType; - this.friendlyName = friendlyName; this.details = details; - this.startDay = startDay; + this.email = email; this.endDay = endDay; + this.estimatedCompletionTime = estimatedCompletionTime; + this.friendlyName = friendlyName; + this.jobQueuePosition = jobQueuePosition; this.jobSid = jobSid; - this.webhookUrl = webhookUrl; - this.webhookMethod = webhookMethod; - this.email = email; + this.resourceType = resourceType; + this.startDay = startDay; this.url = url; - this.jobQueuePosition = jobQueuePosition; - this.estimatedCompletionTime = estimatedCompletionTime; - } - - public final String getResourceType() { - return this.resourceType; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final List> getDetails() { - return this.details; - } - - public final String getStartDay() { - return this.startDay; - } - - public final String getEndDay() { - return this.endDay; - } - - public final String getJobSid() { - return this.jobSid; - } - - public final String getWebhookUrl() { - return this.webhookUrl; - } - - public final String getWebhookMethod() { - return this.webhookMethod; - } - - public final String getEmail() { - return this.email; - } - - public final URI getUrl() { - return this.url; - } - - public final String getJobQueuePosition() { - return this.jobQueuePosition; - } - - public final String getEstimatedCompletionTime() { - return this.estimatedCompletionTime; + this.webhookMethod = webhookMethod; + this.webhookUrl = webhookUrl; } @Override @@ -193,41 +167,40 @@ public boolean equals(final Object o) { } Job other = (Job) o; - return ( - Objects.equals(resourceType, other.resourceType) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(details, other.details) && - Objects.equals(startDay, other.startDay) && - Objects.equals(endDay, other.endDay) && - Objects.equals(jobSid, other.jobSid) && - Objects.equals(webhookUrl, other.webhookUrl) && - Objects.equals(webhookMethod, other.webhookMethod) && - Objects.equals(email, other.email) && - Objects.equals(url, other.url) && - Objects.equals(jobQueuePosition, other.jobQueuePosition) && - Objects.equals( - estimatedCompletionTime, - other.estimatedCompletionTime - ) + Objects.equals(details, other.details) && + Objects.equals(email, other.email) && + Objects.equals(endDay, other.endDay) && + Objects.equals(estimatedCompletionTime, other.estimatedCompletionTime) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(jobQueuePosition, other.jobQueuePosition) && + Objects.equals(jobSid, other.jobSid) && + Objects.equals(resourceType, other.resourceType) && + Objects.equals(startDay, other.startDay) && + Objects.equals(url, other.url) && + Objects.equals(webhookMethod, other.webhookMethod) && + Objects.equals(webhookUrl, other.webhookUrl) ); } @Override public int hashCode() { return Objects.hash( - resourceType, - friendlyName, - details, - startDay, - endDay, - jobSid, - webhookUrl, - webhookMethod, - email, - url, - jobQueuePosition, - estimatedCompletionTime + details, + email, + endDay, + estimatedCompletionTime, + friendlyName, + jobQueuePosition, + jobSid, + resourceType, + startDay, + url, + webhookMethod, + webhookUrl ); } + + } + diff --git a/src/main/java/com/twilio/rest/bulkexports/v1/export/JobDeleter.java b/src/main/java/com/twilio/rest/bulkexports/v1/export/JobDeleter.java index 9d9465bc1d..387ec0afae 100644 --- a/src/main/java/com/twilio/rest/bulkexports/v1/export/JobDeleter.java +++ b/src/main/java/com/twilio/rest/bulkexports/v1/export/JobDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.bulkexports.v1.export; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,40 +26,38 @@ public class JobDeleter extends Deleter { - private String pathJobSid; + private String pathjobSid; - public JobDeleter(final String pathJobSid) { - this.pathJobSid = pathJobSid; + public JobDeleter(final String pathjobSid) { + this.pathjobSid = pathjobSid; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/v1/Exports/Jobs/{JobSid}"; - path = path.replace("{" + "JobSid" + "}", this.pathJobSid.toString()); + path = path.replace("{" + "JobSid" + "}", this.pathjobSid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.BULKEXPORTS.toString(), - path + HttpMethod.DELETE, + Domains.BULKEXPORTS.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Job delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("Job delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/bulkexports/v1/export/JobFetcher.java b/src/main/java/com/twilio/rest/bulkexports/v1/export/JobFetcher.java index 695494073f..c53b7e6ac8 100644 --- a/src/main/java/com/twilio/rest/bulkexports/v1/export/JobFetcher.java +++ b/src/main/java/com/twilio/rest/bulkexports/v1/export/JobFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.bulkexports.v1.export; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,44 +26,41 @@ public class JobFetcher extends Fetcher { - private String pathJobSid; + private String pathjobSid; - public JobFetcher(final String pathJobSid) { - this.pathJobSid = pathJobSid; + public JobFetcher(final String pathjobSid) { + this.pathjobSid = pathjobSid; } + @Override public Job fetch(final TwilioRestClient client) { + String path = "/v1/Exports/Jobs/{JobSid}"; - path = path.replace("{" + "JobSid" + "}", this.pathJobSid.toString()); + path = path.replace("{" + "JobSid" + "}", this.pathjobSid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.BULKEXPORTS.toString(), - path + HttpMethod.GET, + Domains.BULKEXPORTS.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Job fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Job fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Job.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/chat/v1/Credential.java b/src/main/java/com/twilio/rest/chat/v1/Credential.java index 270e61e3fe..5f14922750 100644 --- a/src/main/java/com/twilio/rest/chat/v1/Credential.java +++ b/src/main/java/com/twilio/rest/chat/v1/Credential.java @@ -18,58 +18,93 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Credential extends Resource { - private static final long serialVersionUID = 161183169234848L; public static CredentialCreator creator(final Credential.PushService type) { - return new CredentialCreator(type); + return new CredentialCreator( + type + ); } - public static CredentialDeleter deleter(final String pathSid) { - return new CredentialDeleter(pathSid); + + public static CredentialDeleter deleter(final String pathsid) { + return new CredentialDeleter( + pathsid + ); } - public static CredentialFetcher fetcher(final String pathSid) { - return new CredentialFetcher(pathSid); + + public static CredentialFetcher fetcher(final String pathsid) { + return new CredentialFetcher( + pathsid + ); } + public static CredentialReader reader() { - return new CredentialReader(); + return new CredentialReader( + + ); } - public static CredentialUpdater updater(final String pathSid) { - return new CredentialUpdater(pathSid); + + public static CredentialUpdater updater(final String pathsid) { + return new CredentialUpdater( + pathsid + ); } + + public enum PushService { + GCM("gcm"), + APN("apn"), + FCM("fcm"); + + private final String value; + + private PushService(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static PushService forValue(final String value) { + return Promoter.enumFromString(value, PushService.values()); + } + } + + /** * Converts a JSON String into a Credential object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Credential object represented by the provided JSON */ - public static Credential fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Credential fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Credential.class); @@ -84,14 +119,11 @@ public static Credential fromJson( * Converts a JSON InputStream into a Credential object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Credential object represented by the provided JSON */ - public static Credential fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Credential fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Credential.class); @@ -102,68 +134,59 @@ public static Credential fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String friendlyName; - private final Credential.PushService type; - private final String sandbox; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; + @Getter + private final String friendlyName; + @Getter + private final String sandbox; + @Getter + private final String sid; + @Getter + private final Credential.PushService type; + @Getter private final URI url; @JsonCreator private Credential( - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("type") final Credential.PushService type, - @JsonProperty("sandbox") final String sandbox, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("url") final URI url + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("sandbox") final String sandbox, + @JsonProperty("sid") final String sid, + @JsonProperty("type") final Credential.PushService type, + @JsonProperty("url") final URI url ) { - this.sid = sid; this.accountSid = accountSid; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.friendlyName = friendlyName; - this.type = type; this.sandbox = sandbox; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); + this.sid = sid; + this.type = type; this.url = url; } - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final Credential.PushService getType() { - return this.type; - } - - public final String getSandbox() { - return this.sandbox; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final URI getUrl() { - return this.url; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -175,51 +198,32 @@ public boolean equals(final Object o) { } Credential other = (Credential) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(type, other.type) && - Objects.equals(sandbox, other.sandbox) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(url, other.url) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(sandbox, other.sandbox) && + Objects.equals(sid, other.sid) && + Objects.equals(type, other.type) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - sid, - accountSid, - friendlyName, - type, - sandbox, - dateCreated, - dateUpdated, - url + accountSid, + dateCreated, + dateUpdated, + friendlyName, + sandbox, + sid, + type, + url ); } - public enum PushService { - GCM("gcm"), - APN("apn"), - FCM("fcm"); - - private final String value; - - private PushService(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - @JsonCreator - public static PushService forValue(final String value) { - return Promoter.enumFromString(value, PushService.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/chat/v1/CredentialCreator.java b/src/main/java/com/twilio/rest/chat/v1/CredentialCreator.java index 7e776d88f1..5bd4af141e 100644 --- a/src/main/java/com/twilio/rest/chat/v1/CredentialCreator.java +++ b/src/main/java/com/twilio/rest/chat/v1/CredentialCreator.java @@ -14,8 +14,11 @@ package com.twilio.rest.chat.v1; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -39,100 +42,117 @@ public CredentialCreator(final Credential.PushService type) { this.type = type; } + public CredentialCreator setType(final Credential.PushService type) { this.type = type; return this; } + public CredentialCreator setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + public CredentialCreator setCertificate(final String certificate) { this.certificate = certificate; return this; } + public CredentialCreator setPrivateKey(final String privateKey) { this.privateKey = privateKey; return this; } + public CredentialCreator setSandbox(final Boolean sandbox) { this.sandbox = sandbox; return this; } + public CredentialCreator setApiKey(final String apiKey) { this.apiKey = apiKey; return this; } + public CredentialCreator setSecret(final String secret) { this.secret = secret; return this; } + @Override public Credential create(final TwilioRestClient client) { + String path = "/v1/Credentials"; - path = path.replace("{" + "Type" + "}", this.type.toString()); Request request = new Request( - HttpMethod.POST, - Domains.CHAT.toString(), - path + HttpMethod.POST, + Domains.CHAT.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Credential creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("Credential creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Credential.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Credential.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (type != null) { - request.addPostParam("Type", type.toString()); + Serializer.toString(request, "Type", type, ParameterType.URLENCODED); } + + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + if (certificate != null) { - request.addPostParam("Certificate", certificate); + Serializer.toString(request, "Certificate", certificate, ParameterType.URLENCODED); } + + if (privateKey != null) { - request.addPostParam("PrivateKey", privateKey); + Serializer.toString(request, "PrivateKey", privateKey, ParameterType.URLENCODED); } + + if (sandbox != null) { - request.addPostParam("Sandbox", sandbox.toString()); + Serializer.toString(request, "Sandbox", sandbox, ParameterType.URLENCODED); } + + if (apiKey != null) { - request.addPostParam("ApiKey", apiKey); + Serializer.toString(request, "ApiKey", apiKey, ParameterType.URLENCODED); } + + if (secret != null) { - request.addPostParam("Secret", secret); + Serializer.toString(request, "Secret", secret, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/chat/v1/CredentialDeleter.java b/src/main/java/com/twilio/rest/chat/v1/CredentialDeleter.java index 01967ddaff..7415578e99 100644 --- a/src/main/java/com/twilio/rest/chat/v1/CredentialDeleter.java +++ b/src/main/java/com/twilio/rest/chat/v1/CredentialDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.chat.v1; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,40 +26,38 @@ public class CredentialDeleter extends Deleter { - private String pathSid; + private String pathsid; - public CredentialDeleter(final String pathSid) { - this.pathSid = pathSid; + public CredentialDeleter(final String pathsid) { + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/v1/Credentials/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.CHAT.toString(), - path + HttpMethod.DELETE, + Domains.CHAT.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Credential delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("Credential delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/chat/v1/CredentialFetcher.java b/src/main/java/com/twilio/rest/chat/v1/CredentialFetcher.java index bdf3d1f021..46e805015d 100644 --- a/src/main/java/com/twilio/rest/chat/v1/CredentialFetcher.java +++ b/src/main/java/com/twilio/rest/chat/v1/CredentialFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.chat.v1; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,47 +26,41 @@ public class CredentialFetcher extends Fetcher { - private String pathSid; + private String pathsid; - public CredentialFetcher(final String pathSid) { - this.pathSid = pathSid; + public CredentialFetcher(final String pathsid) { + this.pathsid = pathsid; } + @Override public Credential fetch(final TwilioRestClient client) { + String path = "/v1/Credentials/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.CHAT.toString(), - path + HttpMethod.GET, + Domains.CHAT.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Credential fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Credential fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return Credential.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Credential.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/chat/v1/CredentialReader.java b/src/main/java/com/twilio/rest/chat/v1/CredentialReader.java index 551a34265d..957983103b 100644 --- a/src/main/java/com/twilio/rest/chat/v1/CredentialReader.java +++ b/src/main/java/com/twilio/rest/chat/v1/CredentialReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -31,105 +32,83 @@ public class CredentialReader extends Reader { private Long pageSize; - public CredentialReader() {} + public CredentialReader() { + } + public CredentialReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/Credentials"; + Request request = new Request( - HttpMethod.GET, - Domains.CHAT.toString(), - path + HttpMethod.GET, + Domains.CHAT.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Credential read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Credential read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "credentials", - response.getContent(), - Credential.class, - client.getObjectMapper() - ); + "credentials", + response.getContent(), + Credential.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.CHAT.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.CHAT.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/chat/v1/CredentialUpdater.java b/src/main/java/com/twilio/rest/chat/v1/CredentialUpdater.java index 3c045ad2ea..6cf43fbd82 100644 --- a/src/main/java/com/twilio/rest/chat/v1/CredentialUpdater.java +++ b/src/main/java/com/twilio/rest/chat/v1/CredentialUpdater.java @@ -16,6 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -26,8 +28,7 @@ import com.twilio.rest.Domains; public class CredentialUpdater extends Updater { - - private String pathSid; + private String pathsid; private String friendlyName; private String certificate; private String privateKey; @@ -35,96 +36,112 @@ public class CredentialUpdater extends Updater { private String apiKey; private String secret; - public CredentialUpdater(final String pathSid) { - this.pathSid = pathSid; + public CredentialUpdater(final String pathsid) { + this.pathsid = pathsid; } + public CredentialUpdater setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + public CredentialUpdater setCertificate(final String certificate) { this.certificate = certificate; return this; } + public CredentialUpdater setPrivateKey(final String privateKey) { this.privateKey = privateKey; return this; } + public CredentialUpdater setSandbox(final Boolean sandbox) { this.sandbox = sandbox; return this; } + public CredentialUpdater setApiKey(final String apiKey) { this.apiKey = apiKey; return this; } + public CredentialUpdater setSecret(final String secret) { this.secret = secret; return this; } + @Override public Credential update(final TwilioRestClient client) { + String path = "/v1/Credentials/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.CHAT.toString(), - path + HttpMethod.POST, + Domains.CHAT.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Credential update failed: Unable to connect to server" - ); + throw new ApiConnectionException("Credential update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Credential.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Credential.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + if (certificate != null) { - request.addPostParam("Certificate", certificate); + Serializer.toString(request, "Certificate", certificate, ParameterType.URLENCODED); } + + if (privateKey != null) { - request.addPostParam("PrivateKey", privateKey); + Serializer.toString(request, "PrivateKey", privateKey, ParameterType.URLENCODED); } + + if (sandbox != null) { - request.addPostParam("Sandbox", sandbox.toString()); + Serializer.toString(request, "Sandbox", sandbox, ParameterType.URLENCODED); } + + if (apiKey != null) { - request.addPostParam("ApiKey", apiKey); + Serializer.toString(request, "ApiKey", apiKey, ParameterType.URLENCODED); } + + if (secret != null) { - request.addPostParam("Secret", secret); + Serializer.toString(request, "Secret", secret, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/chat/v1/Service.java b/src/main/java/com/twilio/rest/chat/v1/Service.java index c018f90a12..11298eb35d 100644 --- a/src/main/java/com/twilio/rest/chat/v1/Service.java +++ b/src/main/java/com/twilio/rest/chat/v1/Service.java @@ -18,60 +18,72 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.List; import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Service extends Resource { - private static final long serialVersionUID = 258386577185944L; public static ServiceCreator creator(final String friendlyName) { - return new ServiceCreator(friendlyName); + return new ServiceCreator( + friendlyName + ); } - public static ServiceDeleter deleter(final String pathSid) { - return new ServiceDeleter(pathSid); + + public static ServiceDeleter deleter(final String pathsid) { + return new ServiceDeleter( + pathsid + ); } - public static ServiceFetcher fetcher(final String pathSid) { - return new ServiceFetcher(pathSid); + + public static ServiceFetcher fetcher(final String pathsid) { + return new ServiceFetcher( + pathsid + ); } + public static ServiceReader reader() { - return new ServiceReader(); + return new ServiceReader( + + ); } - public static ServiceUpdater updater(final String pathSid) { - return new ServiceUpdater(pathSid); + + public static ServiceUpdater updater(final String pathsid) { + return new ServiceUpdater( + pathsid + ); } + /** * Converts a JSON String into a Service object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Service object represented by the provided JSON */ - public static Service fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Service fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Service.class); @@ -86,14 +98,11 @@ public static Service fromJson( * Converts a JSON InputStream into a Service object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Service object represented by the provided JSON */ - public static Service fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Service fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Service.class); @@ -104,167 +113,109 @@ public static Service fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String friendlyName; + @Getter + private final Integer consumptionReportInterval; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; - private final String defaultServiceRoleSid; - private final String defaultChannelRoleSid; + @Getter private final String defaultChannelCreatorRoleSid; - private final Boolean readStatusEnabled; + @Getter + private final String defaultChannelRoleSid; + @Getter + private final String defaultServiceRoleSid; + @Getter + private final String friendlyName; + @Getter + private final Object limits; + @Getter + private final Map links; + @Getter + private final Object notifications; + @Getter + private final String postWebhookUrl; + @Getter + private final String preWebhookUrl; + @Getter private final Boolean reachabilityEnabled; + @Getter + private final Boolean readStatusEnabled; + @Getter + private final String sid; + @Getter private final Integer typingIndicatorTimeout; - private final Integer consumptionReportInterval; - private final Map limits; - private final Map webhooks; - private final String preWebhookUrl; - private final String postWebhookUrl; - private final String webhookMethod; - private final List webhookFilters; - private final Map notifications; + @Getter private final URI url; - private final Map links; + @Getter + private final List webhookFilters; + @Getter + private final String webhookMethod; + @Getter + private final Object webhooks; @JsonCreator private Service( - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty( - "default_service_role_sid" - ) final String defaultServiceRoleSid, - @JsonProperty( - "default_channel_role_sid" - ) final String defaultChannelRoleSid, - @JsonProperty( - "default_channel_creator_role_sid" - ) final String defaultChannelCreatorRoleSid, - @JsonProperty("read_status_enabled") final Boolean readStatusEnabled, - @JsonProperty("reachability_enabled") final Boolean reachabilityEnabled, - @JsonProperty( - "typing_indicator_timeout" - ) final Integer typingIndicatorTimeout, - @JsonProperty( - "consumption_report_interval" - ) final Integer consumptionReportInterval, - @JsonProperty("limits") final Map limits, - @JsonProperty("webhooks") final Map webhooks, - @JsonProperty("pre_webhook_url") final String preWebhookUrl, - @JsonProperty("post_webhook_url") final String postWebhookUrl, - @JsonProperty("webhook_method") final String webhookMethod, - @JsonProperty("webhook_filters") final List webhookFilters, - @JsonProperty("notifications") final Map notifications, - @JsonProperty("url") final URI url, - @JsonProperty("links") final Map links + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("consumption_report_interval") final Integer consumptionReportInterval, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("default_channel_creator_role_sid") final String defaultChannelCreatorRoleSid, + @JsonProperty("default_channel_role_sid") final String defaultChannelRoleSid, + @JsonProperty("default_service_role_sid") final String defaultServiceRoleSid, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("limits") final Object limits, + @JsonProperty("links") final Map links, + @JsonProperty("notifications") final Object notifications, + @JsonProperty("post_webhook_url") final String postWebhookUrl, + @JsonProperty("pre_webhook_url") final String preWebhookUrl, + @JsonProperty("reachability_enabled") final Boolean reachabilityEnabled, + @JsonProperty("read_status_enabled") final Boolean readStatusEnabled, + @JsonProperty("sid") final String sid, + @JsonProperty("typing_indicator_timeout") final Integer typingIndicatorTimeout, + @JsonProperty("url") final URI url, + @JsonProperty("webhook_filters") final List webhookFilters, + @JsonProperty("webhook_method") final String webhookMethod, + @JsonProperty("webhooks") final Object webhooks ) { - this.sid = sid; this.accountSid = accountSid; - this.friendlyName = friendlyName; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); - this.defaultServiceRoleSid = defaultServiceRoleSid; - this.defaultChannelRoleSid = defaultChannelRoleSid; - this.defaultChannelCreatorRoleSid = defaultChannelCreatorRoleSid; - this.readStatusEnabled = readStatusEnabled; - this.reachabilityEnabled = reachabilityEnabled; - this.typingIndicatorTimeout = typingIndicatorTimeout; this.consumptionReportInterval = consumptionReportInterval; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; + this.defaultChannelCreatorRoleSid = defaultChannelCreatorRoleSid; + this.defaultChannelRoleSid = defaultChannelRoleSid; + this.defaultServiceRoleSid = defaultServiceRoleSid; + this.friendlyName = friendlyName; this.limits = limits; - this.webhooks = webhooks; - this.preWebhookUrl = preWebhookUrl; - this.postWebhookUrl = postWebhookUrl; - this.webhookMethod = webhookMethod; - this.webhookFilters = webhookFilters; + this.links = links; this.notifications = notifications; + this.postWebhookUrl = postWebhookUrl; + this.preWebhookUrl = preWebhookUrl; + this.reachabilityEnabled = reachabilityEnabled; + this.readStatusEnabled = readStatusEnabled; + this.sid = sid; + this.typingIndicatorTimeout = typingIndicatorTimeout; this.url = url; - this.links = links; - } - - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final String getDefaultServiceRoleSid() { - return this.defaultServiceRoleSid; - } - - public final String getDefaultChannelRoleSid() { - return this.defaultChannelRoleSid; - } - - public final String getDefaultChannelCreatorRoleSid() { - return this.defaultChannelCreatorRoleSid; - } - - public final Boolean getReadStatusEnabled() { - return this.readStatusEnabled; - } - - public final Boolean getReachabilityEnabled() { - return this.reachabilityEnabled; - } - - public final Integer getTypingIndicatorTimeout() { - return this.typingIndicatorTimeout; - } - - public final Integer getConsumptionReportInterval() { - return this.consumptionReportInterval; - } - - public final Map getLimits() { - return this.limits; - } - - public final Map getWebhooks() { - return this.webhooks; - } - - public final String getPreWebhookUrl() { - return this.preWebhookUrl; - } - - public final String getPostWebhookUrl() { - return this.postWebhookUrl; - } - - public final String getWebhookMethod() { - return this.webhookMethod; - } - - public final List getWebhookFilters() { - return this.webhookFilters; - } - - public final Map getNotifications() { - return this.notifications; - } - - public final URI getUrl() { - return this.url; - } - - public final Map getLinks() { - return this.links; + this.webhookFilters = webhookFilters; + this.webhookMethod = webhookMethod; + this.webhooks = webhooks; } @Override @@ -278,71 +229,58 @@ public boolean equals(final Object o) { } Service other = (Service) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals( - defaultServiceRoleSid, - other.defaultServiceRoleSid - ) && - Objects.equals( - defaultChannelRoleSid, - other.defaultChannelRoleSid - ) && - Objects.equals( - defaultChannelCreatorRoleSid, - other.defaultChannelCreatorRoleSid - ) && - Objects.equals(readStatusEnabled, other.readStatusEnabled) && - Objects.equals(reachabilityEnabled, other.reachabilityEnabled) && - Objects.equals( - typingIndicatorTimeout, - other.typingIndicatorTimeout - ) && - Objects.equals( - consumptionReportInterval, - other.consumptionReportInterval - ) && - Objects.equals(limits, other.limits) && - Objects.equals(webhooks, other.webhooks) && - Objects.equals(preWebhookUrl, other.preWebhookUrl) && - Objects.equals(postWebhookUrl, other.postWebhookUrl) && - Objects.equals(webhookMethod, other.webhookMethod) && - Objects.equals(webhookFilters, other.webhookFilters) && - Objects.equals(notifications, other.notifications) && - Objects.equals(url, other.url) && - Objects.equals(links, other.links) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(consumptionReportInterval, other.consumptionReportInterval) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(defaultChannelCreatorRoleSid, other.defaultChannelCreatorRoleSid) && + Objects.equals(defaultChannelRoleSid, other.defaultChannelRoleSid) && + Objects.equals(defaultServiceRoleSid, other.defaultServiceRoleSid) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(limits, other.limits) && + Objects.equals(links, other.links) && + Objects.equals(notifications, other.notifications) && + Objects.equals(postWebhookUrl, other.postWebhookUrl) && + Objects.equals(preWebhookUrl, other.preWebhookUrl) && + Objects.equals(reachabilityEnabled, other.reachabilityEnabled) && + Objects.equals(readStatusEnabled, other.readStatusEnabled) && + Objects.equals(sid, other.sid) && + Objects.equals(typingIndicatorTimeout, other.typingIndicatorTimeout) && + Objects.equals(url, other.url) && + Objects.equals(webhookFilters, other.webhookFilters) && + Objects.equals(webhookMethod, other.webhookMethod) && + Objects.equals(webhooks, other.webhooks) ); } @Override public int hashCode() { return Objects.hash( - sid, - accountSid, - friendlyName, - dateCreated, - dateUpdated, - defaultServiceRoleSid, - defaultChannelRoleSid, - defaultChannelCreatorRoleSid, - readStatusEnabled, - reachabilityEnabled, - typingIndicatorTimeout, - consumptionReportInterval, - limits, - webhooks, - preWebhookUrl, - postWebhookUrl, - webhookMethod, - webhookFilters, - notifications, - url, - links + accountSid, + consumptionReportInterval, + dateCreated, + dateUpdated, + defaultChannelCreatorRoleSid, + defaultChannelRoleSid, + defaultServiceRoleSid, + friendlyName, + limits, + links, + notifications, + postWebhookUrl, + preWebhookUrl, + reachabilityEnabled, + readStatusEnabled, + sid, + typingIndicatorTimeout, + url, + webhookFilters, + webhookMethod, + webhooks ); } + + } + diff --git a/src/main/java/com/twilio/rest/chat/v1/ServiceCreator.java b/src/main/java/com/twilio/rest/chat/v1/ServiceCreator.java index 22e07c6739..468153b94e 100644 --- a/src/main/java/com/twilio/rest/chat/v1/ServiceCreator.java +++ b/src/main/java/com/twilio/rest/chat/v1/ServiceCreator.java @@ -14,8 +14,11 @@ package com.twilio.rest.chat.v1; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -33,43 +36,38 @@ public ServiceCreator(final String friendlyName) { this.friendlyName = friendlyName; } + public ServiceCreator setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + @Override public Service create(final TwilioRestClient client) { + String path = "/v1/Services"; - path = - path.replace( - "{" + "FriendlyName" + "}", - this.friendlyName.toString() - ); Request request = new Request( - HttpMethod.POST, - Domains.CHAT.toString(), - path + HttpMethod.POST, + Domains.CHAT.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Service creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("Service creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -78,8 +76,11 @@ public Service create(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/chat/v1/ServiceDeleter.java b/src/main/java/com/twilio/rest/chat/v1/ServiceDeleter.java index 809c1b608c..00a7b4702d 100644 --- a/src/main/java/com/twilio/rest/chat/v1/ServiceDeleter.java +++ b/src/main/java/com/twilio/rest/chat/v1/ServiceDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.chat.v1; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,40 +26,38 @@ public class ServiceDeleter extends Deleter { - private String pathSid; + private String pathsid; - public ServiceDeleter(final String pathSid) { - this.pathSid = pathSid; + public ServiceDeleter(final String pathsid) { + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/v1/Services/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.CHAT.toString(), - path + HttpMethod.DELETE, + Domains.CHAT.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Service delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("Service delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/chat/v1/ServiceFetcher.java b/src/main/java/com/twilio/rest/chat/v1/ServiceFetcher.java index 142dcf0f93..f9ef150dd2 100644 --- a/src/main/java/com/twilio/rest/chat/v1/ServiceFetcher.java +++ b/src/main/java/com/twilio/rest/chat/v1/ServiceFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.chat.v1; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,44 +26,41 @@ public class ServiceFetcher extends Fetcher { - private String pathSid; + private String pathsid; - public ServiceFetcher(final String pathSid) { - this.pathSid = pathSid; + public ServiceFetcher(final String pathsid) { + this.pathsid = pathsid; } + @Override public Service fetch(final TwilioRestClient client) { + String path = "/v1/Services/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.CHAT.toString(), - path + HttpMethod.GET, + Domains.CHAT.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Service fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Service fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Service.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/chat/v1/ServiceReader.java b/src/main/java/com/twilio/rest/chat/v1/ServiceReader.java index 5b763f0f41..e28c08db4e 100644 --- a/src/main/java/com/twilio/rest/chat/v1/ServiceReader.java +++ b/src/main/java/com/twilio/rest/chat/v1/ServiceReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -31,105 +32,83 @@ public class ServiceReader extends Reader { private Long pageSize; - public ServiceReader() {} + public ServiceReader() { + } + public ServiceReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/Services"; + Request request = new Request( - HttpMethod.GET, - Domains.CHAT.toString(), - path + HttpMethod.GET, + Domains.CHAT.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Service read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Service read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "services", - response.getContent(), - Service.class, - client.getObjectMapper() - ); + "services", + response.getContent(), + Service.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.CHAT.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.CHAT.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/chat/v1/ServiceUpdater.java b/src/main/java/com/twilio/rest/chat/v1/ServiceUpdater.java index 6223c428ea..43c582ed63 100644 --- a/src/main/java/com/twilio/rest/chat/v1/ServiceUpdater.java +++ b/src/main/java/com/twilio/rest/chat/v1/ServiceUpdater.java @@ -16,7 +16,9 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; import com.twilio.converter.Promoter; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,12 +27,12 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.net.URI; import java.util.List; public class ServiceUpdater extends Updater { - - private String pathSid; + private String pathsid; private String friendlyName; private String defaultServiceRoleSid; private String defaultChannelRoleSid; @@ -86,149 +88,125 @@ public class ServiceUpdater extends Updater { private Integer limitsChannelMembers; private Integer limitsUserChannels; - public ServiceUpdater(final String pathSid) { - this.pathSid = pathSid; + public ServiceUpdater(final String pathsid) { + this.pathsid = pathsid; } + public ServiceUpdater setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } - public ServiceUpdater setDefaultServiceRoleSid( - final String defaultServiceRoleSid - ) { + + public ServiceUpdater setDefaultServiceRoleSid(final String defaultServiceRoleSid) { this.defaultServiceRoleSid = defaultServiceRoleSid; return this; } - public ServiceUpdater setDefaultChannelRoleSid( - final String defaultChannelRoleSid - ) { + + public ServiceUpdater setDefaultChannelRoleSid(final String defaultChannelRoleSid) { this.defaultChannelRoleSid = defaultChannelRoleSid; return this; } - public ServiceUpdater setDefaultChannelCreatorRoleSid( - final String defaultChannelCreatorRoleSid - ) { + + public ServiceUpdater setDefaultChannelCreatorRoleSid(final String defaultChannelCreatorRoleSid) { this.defaultChannelCreatorRoleSid = defaultChannelCreatorRoleSid; return this; } - public ServiceUpdater setReadStatusEnabled( - final Boolean readStatusEnabled - ) { + + public ServiceUpdater setReadStatusEnabled(final Boolean readStatusEnabled) { this.readStatusEnabled = readStatusEnabled; return this; } - public ServiceUpdater setReachabilityEnabled( - final Boolean reachabilityEnabled - ) { + + public ServiceUpdater setReachabilityEnabled(final Boolean reachabilityEnabled) { this.reachabilityEnabled = reachabilityEnabled; return this; } - public ServiceUpdater setTypingIndicatorTimeout( - final Integer typingIndicatorTimeout - ) { + + public ServiceUpdater setTypingIndicatorTimeout(final Integer typingIndicatorTimeout) { this.typingIndicatorTimeout = typingIndicatorTimeout; return this; } - public ServiceUpdater setConsumptionReportInterval( - final Integer consumptionReportInterval - ) { + + public ServiceUpdater setConsumptionReportInterval(final Integer consumptionReportInterval) { this.consumptionReportInterval = consumptionReportInterval; return this; } - public ServiceUpdater setNotificationsNewMessageEnabled( - final Boolean notificationsNewMessageEnabled - ) { + + public ServiceUpdater setNotificationsNewMessageEnabled(final Boolean notificationsNewMessageEnabled) { this.notificationsNewMessageEnabled = notificationsNewMessageEnabled; return this; } - public ServiceUpdater setNotificationsNewMessageTemplate( - final String notificationsNewMessageTemplate - ) { + + public ServiceUpdater setNotificationsNewMessageTemplate(final String notificationsNewMessageTemplate) { this.notificationsNewMessageTemplate = notificationsNewMessageTemplate; return this; } - public ServiceUpdater setNotificationsAddedToChannelEnabled( - final Boolean notificationsAddedToChannelEnabled - ) { - this.notificationsAddedToChannelEnabled = - notificationsAddedToChannelEnabled; + + public ServiceUpdater setNotificationsAddedToChannelEnabled(final Boolean notificationsAddedToChannelEnabled) { + this.notificationsAddedToChannelEnabled = notificationsAddedToChannelEnabled; return this; } - public ServiceUpdater setNotificationsAddedToChannelTemplate( - final String notificationsAddedToChannelTemplate - ) { - this.notificationsAddedToChannelTemplate = - notificationsAddedToChannelTemplate; + + public ServiceUpdater setNotificationsAddedToChannelTemplate(final String notificationsAddedToChannelTemplate) { + this.notificationsAddedToChannelTemplate = notificationsAddedToChannelTemplate; return this; } - public ServiceUpdater setNotificationsRemovedFromChannelEnabled( - final Boolean notificationsRemovedFromChannelEnabled - ) { - this.notificationsRemovedFromChannelEnabled = - notificationsRemovedFromChannelEnabled; + + public ServiceUpdater setNotificationsRemovedFromChannelEnabled(final Boolean notificationsRemovedFromChannelEnabled) { + this.notificationsRemovedFromChannelEnabled = notificationsRemovedFromChannelEnabled; return this; } - public ServiceUpdater setNotificationsRemovedFromChannelTemplate( - final String notificationsRemovedFromChannelTemplate - ) { - this.notificationsRemovedFromChannelTemplate = - notificationsRemovedFromChannelTemplate; + + public ServiceUpdater setNotificationsRemovedFromChannelTemplate(final String notificationsRemovedFromChannelTemplate) { + this.notificationsRemovedFromChannelTemplate = notificationsRemovedFromChannelTemplate; return this; } - public ServiceUpdater setNotificationsInvitedToChannelEnabled( - final Boolean notificationsInvitedToChannelEnabled - ) { - this.notificationsInvitedToChannelEnabled = - notificationsInvitedToChannelEnabled; + + public ServiceUpdater setNotificationsInvitedToChannelEnabled(final Boolean notificationsInvitedToChannelEnabled) { + this.notificationsInvitedToChannelEnabled = notificationsInvitedToChannelEnabled; return this; } - public ServiceUpdater setNotificationsInvitedToChannelTemplate( - final String notificationsInvitedToChannelTemplate - ) { - this.notificationsInvitedToChannelTemplate = - notificationsInvitedToChannelTemplate; + + public ServiceUpdater setNotificationsInvitedToChannelTemplate(final String notificationsInvitedToChannelTemplate) { + this.notificationsInvitedToChannelTemplate = notificationsInvitedToChannelTemplate; return this; } + public ServiceUpdater setPreWebhookUrl(final URI preWebhookUrl) { this.preWebhookUrl = preWebhookUrl; return this; } - public ServiceUpdater setPreWebhookUrl(final String preWebhookUrl) { - return setPreWebhookUrl(Promoter.uriFromString(preWebhookUrl)); - } public ServiceUpdater setPostWebhookUrl(final URI postWebhookUrl) { this.postWebhookUrl = postWebhookUrl; return this; } - public ServiceUpdater setPostWebhookUrl(final String postWebhookUrl) { - return setPostWebhookUrl(Promoter.uriFromString(postWebhookUrl)); - } public ServiceUpdater setWebhookMethod(final HttpMethod webhookMethod) { this.webhookMethod = webhookMethod; return this; } + public ServiceUpdater setWebhookFilters(final List webhookFilters) { this.webhookFilters = webhookFilters; return this; @@ -238,401 +216,237 @@ public ServiceUpdater setWebhookFilters(final String webhookFilters) { return setWebhookFilters(Promoter.listOfOne(webhookFilters)); } - public ServiceUpdater setWebhooksOnMessageSendUrl( - final URI webhooksOnMessageSendUrl - ) { + public ServiceUpdater setWebhooksOnMessageSendUrl(final URI webhooksOnMessageSendUrl) { this.webhooksOnMessageSendUrl = webhooksOnMessageSendUrl; return this; } - public ServiceUpdater setWebhooksOnMessageSendUrl( - final String webhooksOnMessageSendUrl - ) { - return setWebhooksOnMessageSendUrl( - Promoter.uriFromString(webhooksOnMessageSendUrl) - ); - } - public ServiceUpdater setWebhooksOnMessageSendMethod( - final HttpMethod webhooksOnMessageSendMethod - ) { + public ServiceUpdater setWebhooksOnMessageSendMethod(final HttpMethod webhooksOnMessageSendMethod) { this.webhooksOnMessageSendMethod = webhooksOnMessageSendMethod; return this; } - public ServiceUpdater setWebhooksOnMessageUpdateUrl( - final URI webhooksOnMessageUpdateUrl - ) { + + public ServiceUpdater setWebhooksOnMessageUpdateUrl(final URI webhooksOnMessageUpdateUrl) { this.webhooksOnMessageUpdateUrl = webhooksOnMessageUpdateUrl; return this; } - public ServiceUpdater setWebhooksOnMessageUpdateUrl( - final String webhooksOnMessageUpdateUrl - ) { - return setWebhooksOnMessageUpdateUrl( - Promoter.uriFromString(webhooksOnMessageUpdateUrl) - ); - } - public ServiceUpdater setWebhooksOnMessageUpdateMethod( - final HttpMethod webhooksOnMessageUpdateMethod - ) { + public ServiceUpdater setWebhooksOnMessageUpdateMethod(final HttpMethod webhooksOnMessageUpdateMethod) { this.webhooksOnMessageUpdateMethod = webhooksOnMessageUpdateMethod; return this; } - public ServiceUpdater setWebhooksOnMessageRemoveUrl( - final URI webhooksOnMessageRemoveUrl - ) { + + public ServiceUpdater setWebhooksOnMessageRemoveUrl(final URI webhooksOnMessageRemoveUrl) { this.webhooksOnMessageRemoveUrl = webhooksOnMessageRemoveUrl; return this; } - public ServiceUpdater setWebhooksOnMessageRemoveUrl( - final String webhooksOnMessageRemoveUrl - ) { - return setWebhooksOnMessageRemoveUrl( - Promoter.uriFromString(webhooksOnMessageRemoveUrl) - ); - } - public ServiceUpdater setWebhooksOnMessageRemoveMethod( - final HttpMethod webhooksOnMessageRemoveMethod - ) { + public ServiceUpdater setWebhooksOnMessageRemoveMethod(final HttpMethod webhooksOnMessageRemoveMethod) { this.webhooksOnMessageRemoveMethod = webhooksOnMessageRemoveMethod; return this; } - public ServiceUpdater setWebhooksOnChannelAddUrl( - final URI webhooksOnChannelAddUrl - ) { + + public ServiceUpdater setWebhooksOnChannelAddUrl(final URI webhooksOnChannelAddUrl) { this.webhooksOnChannelAddUrl = webhooksOnChannelAddUrl; return this; } - public ServiceUpdater setWebhooksOnChannelAddUrl( - final String webhooksOnChannelAddUrl - ) { - return setWebhooksOnChannelAddUrl( - Promoter.uriFromString(webhooksOnChannelAddUrl) - ); - } - public ServiceUpdater setWebhooksOnChannelAddMethod( - final HttpMethod webhooksOnChannelAddMethod - ) { + public ServiceUpdater setWebhooksOnChannelAddMethod(final HttpMethod webhooksOnChannelAddMethod) { this.webhooksOnChannelAddMethod = webhooksOnChannelAddMethod; return this; } - public ServiceUpdater setWebhooksOnChannelDestroyUrl( - final URI webhooksOnChannelDestroyUrl - ) { + + public ServiceUpdater setWebhooksOnChannelDestroyUrl(final URI webhooksOnChannelDestroyUrl) { this.webhooksOnChannelDestroyUrl = webhooksOnChannelDestroyUrl; return this; } - public ServiceUpdater setWebhooksOnChannelDestroyUrl( - final String webhooksOnChannelDestroyUrl - ) { - return setWebhooksOnChannelDestroyUrl( - Promoter.uriFromString(webhooksOnChannelDestroyUrl) - ); - } - public ServiceUpdater setWebhooksOnChannelDestroyMethod( - final HttpMethod webhooksOnChannelDestroyMethod - ) { + public ServiceUpdater setWebhooksOnChannelDestroyMethod(final HttpMethod webhooksOnChannelDestroyMethod) { this.webhooksOnChannelDestroyMethod = webhooksOnChannelDestroyMethod; return this; } - public ServiceUpdater setWebhooksOnChannelUpdateUrl( - final URI webhooksOnChannelUpdateUrl - ) { + + public ServiceUpdater setWebhooksOnChannelUpdateUrl(final URI webhooksOnChannelUpdateUrl) { this.webhooksOnChannelUpdateUrl = webhooksOnChannelUpdateUrl; return this; } - public ServiceUpdater setWebhooksOnChannelUpdateUrl( - final String webhooksOnChannelUpdateUrl - ) { - return setWebhooksOnChannelUpdateUrl( - Promoter.uriFromString(webhooksOnChannelUpdateUrl) - ); - } - public ServiceUpdater setWebhooksOnChannelUpdateMethod( - final HttpMethod webhooksOnChannelUpdateMethod - ) { + public ServiceUpdater setWebhooksOnChannelUpdateMethod(final HttpMethod webhooksOnChannelUpdateMethod) { this.webhooksOnChannelUpdateMethod = webhooksOnChannelUpdateMethod; return this; } - public ServiceUpdater setWebhooksOnMemberAddUrl( - final URI webhooksOnMemberAddUrl - ) { + + public ServiceUpdater setWebhooksOnMemberAddUrl(final URI webhooksOnMemberAddUrl) { this.webhooksOnMemberAddUrl = webhooksOnMemberAddUrl; return this; } - public ServiceUpdater setWebhooksOnMemberAddUrl( - final String webhooksOnMemberAddUrl - ) { - return setWebhooksOnMemberAddUrl( - Promoter.uriFromString(webhooksOnMemberAddUrl) - ); - } - public ServiceUpdater setWebhooksOnMemberAddMethod( - final HttpMethod webhooksOnMemberAddMethod - ) { + public ServiceUpdater setWebhooksOnMemberAddMethod(final HttpMethod webhooksOnMemberAddMethod) { this.webhooksOnMemberAddMethod = webhooksOnMemberAddMethod; return this; } - public ServiceUpdater setWebhooksOnMemberRemoveUrl( - final URI webhooksOnMemberRemoveUrl - ) { + + public ServiceUpdater setWebhooksOnMemberRemoveUrl(final URI webhooksOnMemberRemoveUrl) { this.webhooksOnMemberRemoveUrl = webhooksOnMemberRemoveUrl; return this; } - public ServiceUpdater setWebhooksOnMemberRemoveUrl( - final String webhooksOnMemberRemoveUrl - ) { - return setWebhooksOnMemberRemoveUrl( - Promoter.uriFromString(webhooksOnMemberRemoveUrl) - ); - } - public ServiceUpdater setWebhooksOnMemberRemoveMethod( - final HttpMethod webhooksOnMemberRemoveMethod - ) { + public ServiceUpdater setWebhooksOnMemberRemoveMethod(final HttpMethod webhooksOnMemberRemoveMethod) { this.webhooksOnMemberRemoveMethod = webhooksOnMemberRemoveMethod; return this; } - public ServiceUpdater setWebhooksOnMessageSentUrl( - final URI webhooksOnMessageSentUrl - ) { + + public ServiceUpdater setWebhooksOnMessageSentUrl(final URI webhooksOnMessageSentUrl) { this.webhooksOnMessageSentUrl = webhooksOnMessageSentUrl; return this; } - public ServiceUpdater setWebhooksOnMessageSentUrl( - final String webhooksOnMessageSentUrl - ) { - return setWebhooksOnMessageSentUrl( - Promoter.uriFromString(webhooksOnMessageSentUrl) - ); - } - public ServiceUpdater setWebhooksOnMessageSentMethod( - final HttpMethod webhooksOnMessageSentMethod - ) { + public ServiceUpdater setWebhooksOnMessageSentMethod(final HttpMethod webhooksOnMessageSentMethod) { this.webhooksOnMessageSentMethod = webhooksOnMessageSentMethod; return this; } - public ServiceUpdater setWebhooksOnMessageUpdatedUrl( - final URI webhooksOnMessageUpdatedUrl - ) { + + public ServiceUpdater setWebhooksOnMessageUpdatedUrl(final URI webhooksOnMessageUpdatedUrl) { this.webhooksOnMessageUpdatedUrl = webhooksOnMessageUpdatedUrl; return this; } - public ServiceUpdater setWebhooksOnMessageUpdatedUrl( - final String webhooksOnMessageUpdatedUrl - ) { - return setWebhooksOnMessageUpdatedUrl( - Promoter.uriFromString(webhooksOnMessageUpdatedUrl) - ); - } - public ServiceUpdater setWebhooksOnMessageUpdatedMethod( - final HttpMethod webhooksOnMessageUpdatedMethod - ) { + public ServiceUpdater setWebhooksOnMessageUpdatedMethod(final HttpMethod webhooksOnMessageUpdatedMethod) { this.webhooksOnMessageUpdatedMethod = webhooksOnMessageUpdatedMethod; return this; } - public ServiceUpdater setWebhooksOnMessageRemovedUrl( - final URI webhooksOnMessageRemovedUrl - ) { + + public ServiceUpdater setWebhooksOnMessageRemovedUrl(final URI webhooksOnMessageRemovedUrl) { this.webhooksOnMessageRemovedUrl = webhooksOnMessageRemovedUrl; return this; } - public ServiceUpdater setWebhooksOnMessageRemovedUrl( - final String webhooksOnMessageRemovedUrl - ) { - return setWebhooksOnMessageRemovedUrl( - Promoter.uriFromString(webhooksOnMessageRemovedUrl) - ); - } - public ServiceUpdater setWebhooksOnMessageRemovedMethod( - final HttpMethod webhooksOnMessageRemovedMethod - ) { + public ServiceUpdater setWebhooksOnMessageRemovedMethod(final HttpMethod webhooksOnMessageRemovedMethod) { this.webhooksOnMessageRemovedMethod = webhooksOnMessageRemovedMethod; return this; } - public ServiceUpdater setWebhooksOnChannelAddedUrl( - final URI webhooksOnChannelAddedUrl - ) { + + public ServiceUpdater setWebhooksOnChannelAddedUrl(final URI webhooksOnChannelAddedUrl) { this.webhooksOnChannelAddedUrl = webhooksOnChannelAddedUrl; return this; } - public ServiceUpdater setWebhooksOnChannelAddedUrl( - final String webhooksOnChannelAddedUrl - ) { - return setWebhooksOnChannelAddedUrl( - Promoter.uriFromString(webhooksOnChannelAddedUrl) - ); - } - public ServiceUpdater setWebhooksOnChannelAddedMethod( - final HttpMethod webhooksOnChannelAddedMethod - ) { + public ServiceUpdater setWebhooksOnChannelAddedMethod(final HttpMethod webhooksOnChannelAddedMethod) { this.webhooksOnChannelAddedMethod = webhooksOnChannelAddedMethod; return this; } - public ServiceUpdater setWebhooksOnChannelDestroyedUrl( - final URI webhooksOnChannelDestroyedUrl - ) { + + public ServiceUpdater setWebhooksOnChannelDestroyedUrl(final URI webhooksOnChannelDestroyedUrl) { this.webhooksOnChannelDestroyedUrl = webhooksOnChannelDestroyedUrl; return this; } - public ServiceUpdater setWebhooksOnChannelDestroyedUrl( - final String webhooksOnChannelDestroyedUrl - ) { - return setWebhooksOnChannelDestroyedUrl( - Promoter.uriFromString(webhooksOnChannelDestroyedUrl) - ); - } - public ServiceUpdater setWebhooksOnChannelDestroyedMethod( - final HttpMethod webhooksOnChannelDestroyedMethod - ) { - this.webhooksOnChannelDestroyedMethod = - webhooksOnChannelDestroyedMethod; + public ServiceUpdater setWebhooksOnChannelDestroyedMethod(final HttpMethod webhooksOnChannelDestroyedMethod) { + this.webhooksOnChannelDestroyedMethod = webhooksOnChannelDestroyedMethod; return this; } - public ServiceUpdater setWebhooksOnChannelUpdatedUrl( - final URI webhooksOnChannelUpdatedUrl - ) { + + public ServiceUpdater setWebhooksOnChannelUpdatedUrl(final URI webhooksOnChannelUpdatedUrl) { this.webhooksOnChannelUpdatedUrl = webhooksOnChannelUpdatedUrl; return this; } - public ServiceUpdater setWebhooksOnChannelUpdatedUrl( - final String webhooksOnChannelUpdatedUrl - ) { - return setWebhooksOnChannelUpdatedUrl( - Promoter.uriFromString(webhooksOnChannelUpdatedUrl) - ); - } - public ServiceUpdater setWebhooksOnChannelUpdatedMethod( - final HttpMethod webhooksOnChannelUpdatedMethod - ) { + public ServiceUpdater setWebhooksOnChannelUpdatedMethod(final HttpMethod webhooksOnChannelUpdatedMethod) { this.webhooksOnChannelUpdatedMethod = webhooksOnChannelUpdatedMethod; return this; } - public ServiceUpdater setWebhooksOnMemberAddedUrl( - final URI webhooksOnMemberAddedUrl - ) { + + public ServiceUpdater setWebhooksOnMemberAddedUrl(final URI webhooksOnMemberAddedUrl) { this.webhooksOnMemberAddedUrl = webhooksOnMemberAddedUrl; return this; } - public ServiceUpdater setWebhooksOnMemberAddedUrl( - final String webhooksOnMemberAddedUrl - ) { - return setWebhooksOnMemberAddedUrl( - Promoter.uriFromString(webhooksOnMemberAddedUrl) - ); - } - public ServiceUpdater setWebhooksOnMemberAddedMethod( - final HttpMethod webhooksOnMemberAddedMethod - ) { + public ServiceUpdater setWebhooksOnMemberAddedMethod(final HttpMethod webhooksOnMemberAddedMethod) { this.webhooksOnMemberAddedMethod = webhooksOnMemberAddedMethod; return this; } - public ServiceUpdater setWebhooksOnMemberRemovedUrl( - final URI webhooksOnMemberRemovedUrl - ) { + + public ServiceUpdater setWebhooksOnMemberRemovedUrl(final URI webhooksOnMemberRemovedUrl) { this.webhooksOnMemberRemovedUrl = webhooksOnMemberRemovedUrl; return this; } - public ServiceUpdater setWebhooksOnMemberRemovedUrl( - final String webhooksOnMemberRemovedUrl - ) { - return setWebhooksOnMemberRemovedUrl( - Promoter.uriFromString(webhooksOnMemberRemovedUrl) - ); - } - public ServiceUpdater setWebhooksOnMemberRemovedMethod( - final HttpMethod webhooksOnMemberRemovedMethod - ) { + public ServiceUpdater setWebhooksOnMemberRemovedMethod(final HttpMethod webhooksOnMemberRemovedMethod) { this.webhooksOnMemberRemovedMethod = webhooksOnMemberRemovedMethod; return this; } - public ServiceUpdater setLimitsChannelMembers( - final Integer limitsChannelMembers - ) { + + public ServiceUpdater setLimitsChannelMembers(final Integer limitsChannelMembers) { this.limitsChannelMembers = limitsChannelMembers; return this; } - public ServiceUpdater setLimitsUserChannels( - final Integer limitsUserChannels - ) { + + public ServiceUpdater setLimitsUserChannels(final Integer limitsUserChannels) { this.limitsUserChannels = limitsUserChannels; return this; } + @Override public Service update(final TwilioRestClient client) { + String path = "/v1/Services/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.CHAT.toString(), - path + HttpMethod.POST, + Domains.CHAT.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Service update failed: Unable to connect to server" - ); + throw new ApiConnectionException("Service update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -641,316 +455,278 @@ public Service update(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + if (defaultServiceRoleSid != null) { - request.addPostParam( - "DefaultServiceRoleSid", - defaultServiceRoleSid - ); + Serializer.toString(request, "DefaultServiceRoleSid", defaultServiceRoleSid, ParameterType.URLENCODED); } + + if (defaultChannelRoleSid != null) { - request.addPostParam( - "DefaultChannelRoleSid", - defaultChannelRoleSid - ); + Serializer.toString(request, "DefaultChannelRoleSid", defaultChannelRoleSid, ParameterType.URLENCODED); } + + if (defaultChannelCreatorRoleSid != null) { - request.addPostParam( - "DefaultChannelCreatorRoleSid", - defaultChannelCreatorRoleSid - ); + Serializer.toString(request, "DefaultChannelCreatorRoleSid", defaultChannelCreatorRoleSid, ParameterType.URLENCODED); } + + if (readStatusEnabled != null) { - request.addPostParam( - "ReadStatusEnabled", - readStatusEnabled.toString() - ); + Serializer.toString(request, "ReadStatusEnabled", readStatusEnabled, ParameterType.URLENCODED); } + + if (reachabilityEnabled != null) { - request.addPostParam( - "ReachabilityEnabled", - reachabilityEnabled.toString() - ); + Serializer.toString(request, "ReachabilityEnabled", reachabilityEnabled, ParameterType.URLENCODED); } + + if (typingIndicatorTimeout != null) { - request.addPostParam( - "TypingIndicatorTimeout", - typingIndicatorTimeout.toString() - ); + Serializer.toString(request, "TypingIndicatorTimeout", typingIndicatorTimeout, ParameterType.URLENCODED); } + + if (consumptionReportInterval != null) { - request.addPostParam( - "ConsumptionReportInterval", - consumptionReportInterval.toString() - ); + Serializer.toString(request, "ConsumptionReportInterval", consumptionReportInterval, ParameterType.URLENCODED); } + + if (notificationsNewMessageEnabled != null) { - request.addPostParam( - "Notifications.NewMessage.Enabled", - notificationsNewMessageEnabled.toString() - ); + Serializer.toString(request, "Notifications.NewMessage.Enabled", notificationsNewMessageEnabled, ParameterType.URLENCODED); } + + if (notificationsNewMessageTemplate != null) { - request.addPostParam( - "Notifications.NewMessage.Template", - notificationsNewMessageTemplate - ); + Serializer.toString(request, "Notifications.NewMessage.Template", notificationsNewMessageTemplate, ParameterType.URLENCODED); } + + if (notificationsAddedToChannelEnabled != null) { - request.addPostParam( - "Notifications.AddedToChannel.Enabled", - notificationsAddedToChannelEnabled.toString() - ); + Serializer.toString(request, "Notifications.AddedToChannel.Enabled", notificationsAddedToChannelEnabled, ParameterType.URLENCODED); } + + if (notificationsAddedToChannelTemplate != null) { - request.addPostParam( - "Notifications.AddedToChannel.Template", - notificationsAddedToChannelTemplate - ); + Serializer.toString(request, "Notifications.AddedToChannel.Template", notificationsAddedToChannelTemplate, ParameterType.URLENCODED); } + + if (notificationsRemovedFromChannelEnabled != null) { - request.addPostParam( - "Notifications.RemovedFromChannel.Enabled", - notificationsRemovedFromChannelEnabled.toString() - ); + Serializer.toString(request, "Notifications.RemovedFromChannel.Enabled", notificationsRemovedFromChannelEnabled, ParameterType.URLENCODED); } + + if (notificationsRemovedFromChannelTemplate != null) { - request.addPostParam( - "Notifications.RemovedFromChannel.Template", - notificationsRemovedFromChannelTemplate - ); + Serializer.toString(request, "Notifications.RemovedFromChannel.Template", notificationsRemovedFromChannelTemplate, ParameterType.URLENCODED); } + + if (notificationsInvitedToChannelEnabled != null) { - request.addPostParam( - "Notifications.InvitedToChannel.Enabled", - notificationsInvitedToChannelEnabled.toString() - ); + Serializer.toString(request, "Notifications.InvitedToChannel.Enabled", notificationsInvitedToChannelEnabled, ParameterType.URLENCODED); } + + if (notificationsInvitedToChannelTemplate != null) { - request.addPostParam( - "Notifications.InvitedToChannel.Template", - notificationsInvitedToChannelTemplate - ); + Serializer.toString(request, "Notifications.InvitedToChannel.Template", notificationsInvitedToChannelTemplate, ParameterType.URLENCODED); } + + if (preWebhookUrl != null) { - request.addPostParam("PreWebhookUrl", preWebhookUrl.toString()); + Serializer.toString(request, "PreWebhookUrl", preWebhookUrl, ParameterType.URLENCODED); } + + if (postWebhookUrl != null) { - request.addPostParam("PostWebhookUrl", postWebhookUrl.toString()); + Serializer.toString(request, "PostWebhookUrl", postWebhookUrl, ParameterType.URLENCODED); } + + if (webhookMethod != null) { - request.addPostParam("WebhookMethod", webhookMethod.toString()); + Serializer.toString(request, "WebhookMethod", webhookMethod, ParameterType.URLENCODED); } + + if (webhookFilters != null) { - for (String prop : webhookFilters) { - request.addPostParam("WebhookFilters", prop); + for (String param : webhookFilters) { + Serializer.toString(request, "WebhookFilters", param, ParameterType.URLENCODED); } } + + if (webhooksOnMessageSendUrl != null) { - request.addPostParam( - "Webhooks.OnMessageSend.Url", - webhooksOnMessageSendUrl.toString() - ); + Serializer.toString(request, "Webhooks.OnMessageSend.Url", webhooksOnMessageSendUrl, ParameterType.URLENCODED); } + + if (webhooksOnMessageSendMethod != null) { - request.addPostParam( - "Webhooks.OnMessageSend.Method", - webhooksOnMessageSendMethod.toString() - ); + Serializer.toString(request, "Webhooks.OnMessageSend.Method", webhooksOnMessageSendMethod, ParameterType.URLENCODED); } + + if (webhooksOnMessageUpdateUrl != null) { - request.addPostParam( - "Webhooks.OnMessageUpdate.Url", - webhooksOnMessageUpdateUrl.toString() - ); + Serializer.toString(request, "Webhooks.OnMessageUpdate.Url", webhooksOnMessageUpdateUrl, ParameterType.URLENCODED); } + + if (webhooksOnMessageUpdateMethod != null) { - request.addPostParam( - "Webhooks.OnMessageUpdate.Method", - webhooksOnMessageUpdateMethod.toString() - ); + Serializer.toString(request, "Webhooks.OnMessageUpdate.Method", webhooksOnMessageUpdateMethod, ParameterType.URLENCODED); } + + if (webhooksOnMessageRemoveUrl != null) { - request.addPostParam( - "Webhooks.OnMessageRemove.Url", - webhooksOnMessageRemoveUrl.toString() - ); + Serializer.toString(request, "Webhooks.OnMessageRemove.Url", webhooksOnMessageRemoveUrl, ParameterType.URLENCODED); } + + if (webhooksOnMessageRemoveMethod != null) { - request.addPostParam( - "Webhooks.OnMessageRemove.Method", - webhooksOnMessageRemoveMethod.toString() - ); + Serializer.toString(request, "Webhooks.OnMessageRemove.Method", webhooksOnMessageRemoveMethod, ParameterType.URLENCODED); } + + if (webhooksOnChannelAddUrl != null) { - request.addPostParam( - "Webhooks.OnChannelAdd.Url", - webhooksOnChannelAddUrl.toString() - ); + Serializer.toString(request, "Webhooks.OnChannelAdd.Url", webhooksOnChannelAddUrl, ParameterType.URLENCODED); } + + if (webhooksOnChannelAddMethod != null) { - request.addPostParam( - "Webhooks.OnChannelAdd.Method", - webhooksOnChannelAddMethod.toString() - ); + Serializer.toString(request, "Webhooks.OnChannelAdd.Method", webhooksOnChannelAddMethod, ParameterType.URLENCODED); } + + if (webhooksOnChannelDestroyUrl != null) { - request.addPostParam( - "Webhooks.OnChannelDestroy.Url", - webhooksOnChannelDestroyUrl.toString() - ); + Serializer.toString(request, "Webhooks.OnChannelDestroy.Url", webhooksOnChannelDestroyUrl, ParameterType.URLENCODED); } + + if (webhooksOnChannelDestroyMethod != null) { - request.addPostParam( - "Webhooks.OnChannelDestroy.Method", - webhooksOnChannelDestroyMethod.toString() - ); + Serializer.toString(request, "Webhooks.OnChannelDestroy.Method", webhooksOnChannelDestroyMethod, ParameterType.URLENCODED); } + + if (webhooksOnChannelUpdateUrl != null) { - request.addPostParam( - "Webhooks.OnChannelUpdate.Url", - webhooksOnChannelUpdateUrl.toString() - ); + Serializer.toString(request, "Webhooks.OnChannelUpdate.Url", webhooksOnChannelUpdateUrl, ParameterType.URLENCODED); } + + if (webhooksOnChannelUpdateMethod != null) { - request.addPostParam( - "Webhooks.OnChannelUpdate.Method", - webhooksOnChannelUpdateMethod.toString() - ); + Serializer.toString(request, "Webhooks.OnChannelUpdate.Method", webhooksOnChannelUpdateMethod, ParameterType.URLENCODED); } + + if (webhooksOnMemberAddUrl != null) { - request.addPostParam( - "Webhooks.OnMemberAdd.Url", - webhooksOnMemberAddUrl.toString() - ); + Serializer.toString(request, "Webhooks.OnMemberAdd.Url", webhooksOnMemberAddUrl, ParameterType.URLENCODED); } + + if (webhooksOnMemberAddMethod != null) { - request.addPostParam( - "Webhooks.OnMemberAdd.Method", - webhooksOnMemberAddMethod.toString() - ); + Serializer.toString(request, "Webhooks.OnMemberAdd.Method", webhooksOnMemberAddMethod, ParameterType.URLENCODED); } + + if (webhooksOnMemberRemoveUrl != null) { - request.addPostParam( - "Webhooks.OnMemberRemove.Url", - webhooksOnMemberRemoveUrl.toString() - ); + Serializer.toString(request, "Webhooks.OnMemberRemove.Url", webhooksOnMemberRemoveUrl, ParameterType.URLENCODED); } + + if (webhooksOnMemberRemoveMethod != null) { - request.addPostParam( - "Webhooks.OnMemberRemove.Method", - webhooksOnMemberRemoveMethod.toString() - ); + Serializer.toString(request, "Webhooks.OnMemberRemove.Method", webhooksOnMemberRemoveMethod, ParameterType.URLENCODED); } + + if (webhooksOnMessageSentUrl != null) { - request.addPostParam( - "Webhooks.OnMessageSent.Url", - webhooksOnMessageSentUrl.toString() - ); + Serializer.toString(request, "Webhooks.OnMessageSent.Url", webhooksOnMessageSentUrl, ParameterType.URLENCODED); } + + if (webhooksOnMessageSentMethod != null) { - request.addPostParam( - "Webhooks.OnMessageSent.Method", - webhooksOnMessageSentMethod.toString() - ); + Serializer.toString(request, "Webhooks.OnMessageSent.Method", webhooksOnMessageSentMethod, ParameterType.URLENCODED); } + + if (webhooksOnMessageUpdatedUrl != null) { - request.addPostParam( - "Webhooks.OnMessageUpdated.Url", - webhooksOnMessageUpdatedUrl.toString() - ); + Serializer.toString(request, "Webhooks.OnMessageUpdated.Url", webhooksOnMessageUpdatedUrl, ParameterType.URLENCODED); } + + if (webhooksOnMessageUpdatedMethod != null) { - request.addPostParam( - "Webhooks.OnMessageUpdated.Method", - webhooksOnMessageUpdatedMethod.toString() - ); + Serializer.toString(request, "Webhooks.OnMessageUpdated.Method", webhooksOnMessageUpdatedMethod, ParameterType.URLENCODED); } + + if (webhooksOnMessageRemovedUrl != null) { - request.addPostParam( - "Webhooks.OnMessageRemoved.Url", - webhooksOnMessageRemovedUrl.toString() - ); + Serializer.toString(request, "Webhooks.OnMessageRemoved.Url", webhooksOnMessageRemovedUrl, ParameterType.URLENCODED); } + + if (webhooksOnMessageRemovedMethod != null) { - request.addPostParam( - "Webhooks.OnMessageRemoved.Method", - webhooksOnMessageRemovedMethod.toString() - ); + Serializer.toString(request, "Webhooks.OnMessageRemoved.Method", webhooksOnMessageRemovedMethod, ParameterType.URLENCODED); } + + if (webhooksOnChannelAddedUrl != null) { - request.addPostParam( - "Webhooks.OnChannelAdded.Url", - webhooksOnChannelAddedUrl.toString() - ); + Serializer.toString(request, "Webhooks.OnChannelAdded.Url", webhooksOnChannelAddedUrl, ParameterType.URLENCODED); } + + if (webhooksOnChannelAddedMethod != null) { - request.addPostParam( - "Webhooks.OnChannelAdded.Method", - webhooksOnChannelAddedMethod.toString() - ); + Serializer.toString(request, "Webhooks.OnChannelAdded.Method", webhooksOnChannelAddedMethod, ParameterType.URLENCODED); } + + if (webhooksOnChannelDestroyedUrl != null) { - request.addPostParam( - "Webhooks.OnChannelDestroyed.Url", - webhooksOnChannelDestroyedUrl.toString() - ); + Serializer.toString(request, "Webhooks.OnChannelDestroyed.Url", webhooksOnChannelDestroyedUrl, ParameterType.URLENCODED); } + + if (webhooksOnChannelDestroyedMethod != null) { - request.addPostParam( - "Webhooks.OnChannelDestroyed.Method", - webhooksOnChannelDestroyedMethod.toString() - ); + Serializer.toString(request, "Webhooks.OnChannelDestroyed.Method", webhooksOnChannelDestroyedMethod, ParameterType.URLENCODED); } + + if (webhooksOnChannelUpdatedUrl != null) { - request.addPostParam( - "Webhooks.OnChannelUpdated.Url", - webhooksOnChannelUpdatedUrl.toString() - ); + Serializer.toString(request, "Webhooks.OnChannelUpdated.Url", webhooksOnChannelUpdatedUrl, ParameterType.URLENCODED); } + + if (webhooksOnChannelUpdatedMethod != null) { - request.addPostParam( - "Webhooks.OnChannelUpdated.Method", - webhooksOnChannelUpdatedMethod.toString() - ); + Serializer.toString(request, "Webhooks.OnChannelUpdated.Method", webhooksOnChannelUpdatedMethod, ParameterType.URLENCODED); } + + if (webhooksOnMemberAddedUrl != null) { - request.addPostParam( - "Webhooks.OnMemberAdded.Url", - webhooksOnMemberAddedUrl.toString() - ); + Serializer.toString(request, "Webhooks.OnMemberAdded.Url", webhooksOnMemberAddedUrl, ParameterType.URLENCODED); } + + if (webhooksOnMemberAddedMethod != null) { - request.addPostParam( - "Webhooks.OnMemberAdded.Method", - webhooksOnMemberAddedMethod.toString() - ); + Serializer.toString(request, "Webhooks.OnMemberAdded.Method", webhooksOnMemberAddedMethod, ParameterType.URLENCODED); } + + if (webhooksOnMemberRemovedUrl != null) { - request.addPostParam( - "Webhooks.OnMemberRemoved.Url", - webhooksOnMemberRemovedUrl.toString() - ); + Serializer.toString(request, "Webhooks.OnMemberRemoved.Url", webhooksOnMemberRemovedUrl, ParameterType.URLENCODED); } + + if (webhooksOnMemberRemovedMethod != null) { - request.addPostParam( - "Webhooks.OnMemberRemoved.Method", - webhooksOnMemberRemovedMethod.toString() - ); + Serializer.toString(request, "Webhooks.OnMemberRemoved.Method", webhooksOnMemberRemovedMethod, ParameterType.URLENCODED); } + + if (limitsChannelMembers != null) { - request.addPostParam( - "Limits.ChannelMembers", - limitsChannelMembers.toString() - ); + Serializer.toString(request, "Limits.ChannelMembers", limitsChannelMembers, ParameterType.URLENCODED); } + + if (limitsUserChannels != null) { - request.addPostParam( - "Limits.UserChannels", - limitsUserChannels.toString() - ); + Serializer.toString(request, "Limits.UserChannels", limitsUserChannels, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/chat/v1/service/Channel.java b/src/main/java/com/twilio/rest/chat/v1/service/Channel.java index d8f46724b0..7980cb6b1e 100644 --- a/src/main/java/com/twilio/rest/chat/v1/service/Channel.java +++ b/src/main/java/com/twilio/rest/chat/v1/service/Channel.java @@ -18,69 +18,93 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Channel extends Resource { - private static final long serialVersionUID = 188288773259274L; - public static ChannelCreator creator(final String pathServiceSid) { - return new ChannelCreator(pathServiceSid); + public static ChannelCreator creator(final String pathserviceSid) { + return new ChannelCreator( + pathserviceSid + ); } - public static ChannelDeleter deleter( - final String pathServiceSid, - final String pathSid - ) { - return new ChannelDeleter(pathServiceSid, pathSid); + + public static ChannelDeleter deleter(final String pathserviceSid, final String pathsid) { + return new ChannelDeleter( + pathserviceSid, pathsid + ); } - public static ChannelFetcher fetcher( - final String pathServiceSid, - final String pathSid - ) { - return new ChannelFetcher(pathServiceSid, pathSid); + + public static ChannelFetcher fetcher(final String pathserviceSid, final String pathsid) { + return new ChannelFetcher( + pathserviceSid, pathsid + ); } - public static ChannelReader reader(final String pathServiceSid) { - return new ChannelReader(pathServiceSid); + + public static ChannelReader reader(final String pathserviceSid) { + return new ChannelReader( + pathserviceSid + ); } - public static ChannelUpdater updater( - final String pathServiceSid, - final String pathSid - ) { - return new ChannelUpdater(pathServiceSid, pathSid); + + public static ChannelUpdater updater(final String pathserviceSid, final String pathsid) { + return new ChannelUpdater( + pathserviceSid, pathsid + ); + } + + + public enum ChannelType { + PUBLIC("public"), + PRIVATE("private"); + + private final String value; + + private ChannelType(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static ChannelType forValue(final String value) { + return Promoter.enumFromString(value, ChannelType.values()); + } } + /** * Converts a JSON String into a Channel object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Channel object represented by the provided JSON */ - public static Channel fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Channel fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Channel.class); @@ -95,14 +119,11 @@ public static Channel fromJson( * Converts a JSON InputStream into a Channel object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Channel object represented by the provided JSON */ - public static Channel fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Channel fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Channel.class); @@ -113,108 +134,81 @@ public static Channel fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String serviceSid; - private final String friendlyName; - private final String uniqueName; + @Getter private final String attributes; - private final Channel.ChannelType type; + @Getter + private final String createdBy; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; - private final String createdBy; + @Getter + private final String friendlyName; + @Getter + private final Map links; + @Getter private final Integer membersCount; + @Getter private final Integer messagesCount; + @Getter + private final String serviceSid; + @Getter + private final String sid; + @Getter + private final Channel.ChannelType type; + @Getter + private final String uniqueName; + @Getter private final URI url; - private final Map links; @JsonCreator private Channel( - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("service_sid") final String serviceSid, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("unique_name") final String uniqueName, - @JsonProperty("attributes") final String attributes, - @JsonProperty("type") final Channel.ChannelType type, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("created_by") final String createdBy, - @JsonProperty("members_count") final Integer membersCount, - @JsonProperty("messages_count") final Integer messagesCount, - @JsonProperty("url") final URI url, - @JsonProperty("links") final Map links + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("attributes") final String attributes, + @JsonProperty("created_by") final String createdBy, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("links") final Map links, + @JsonProperty("members_count") final Integer membersCount, + @JsonProperty("messages_count") final Integer messagesCount, + @JsonProperty("service_sid") final String serviceSid, + @JsonProperty("sid") final String sid, + @JsonProperty("type") final Channel.ChannelType type, + @JsonProperty("unique_name") final String uniqueName, + @JsonProperty("url") final URI url ) { - this.sid = sid; this.accountSid = accountSid; - this.serviceSid = serviceSid; - this.friendlyName = friendlyName; - this.uniqueName = uniqueName; this.attributes = attributes; - this.type = type; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); this.createdBy = createdBy; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; + this.friendlyName = friendlyName; + this.links = links; this.membersCount = membersCount; this.messagesCount = messagesCount; + this.serviceSid = serviceSid; + this.sid = sid; + this.type = type; + this.uniqueName = uniqueName; this.url = url; - this.links = links; - } - - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getServiceSid() { - return this.serviceSid; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final String getUniqueName() { - return this.uniqueName; - } - - public final String getAttributes() { - return this.attributes; - } - - public final Channel.ChannelType getType() { - return this.type; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final String getCreatedBy() { - return this.createdBy; - } - - public final Integer getMembersCount() { - return this.membersCount; - } - - public final Integer getMessagesCount() { - return this.messagesCount; - } - - public final URI getUrl() { - return this.url; - } - - public final Map getLinks() { - return this.links; } @Override @@ -228,62 +222,44 @@ public boolean equals(final Object o) { } Channel other = (Channel) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(serviceSid, other.serviceSid) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(uniqueName, other.uniqueName) && - Objects.equals(attributes, other.attributes) && - Objects.equals(type, other.type) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(createdBy, other.createdBy) && - Objects.equals(membersCount, other.membersCount) && - Objects.equals(messagesCount, other.messagesCount) && - Objects.equals(url, other.url) && - Objects.equals(links, other.links) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(attributes, other.attributes) && + Objects.equals(createdBy, other.createdBy) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(links, other.links) && + Objects.equals(membersCount, other.membersCount) && + Objects.equals(messagesCount, other.messagesCount) && + Objects.equals(serviceSid, other.serviceSid) && + Objects.equals(sid, other.sid) && + Objects.equals(type, other.type) && + Objects.equals(uniqueName, other.uniqueName) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - sid, - accountSid, - serviceSid, - friendlyName, - uniqueName, - attributes, - type, - dateCreated, - dateUpdated, - createdBy, - membersCount, - messagesCount, - url, - links + accountSid, + attributes, + createdBy, + dateCreated, + dateUpdated, + friendlyName, + links, + membersCount, + messagesCount, + serviceSid, + sid, + type, + uniqueName, + url ); } - public enum ChannelType { - PUBLIC("public"), - PRIVATE("private"); - private final String value; - - private ChannelType(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static ChannelType forValue(final String value) { - return Promoter.enumFromString(value, ChannelType.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/chat/v1/service/ChannelCreator.java b/src/main/java/com/twilio/rest/chat/v1/service/ChannelCreator.java index 095eaa4680..6fd32e6516 100644 --- a/src/main/java/com/twilio/rest/chat/v1/service/ChannelCreator.java +++ b/src/main/java/com/twilio/rest/chat/v1/service/ChannelCreator.java @@ -14,8 +14,11 @@ package com.twilio.rest.chat.v1.service; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,68 +30,68 @@ public class ChannelCreator extends Creator { - private String pathServiceSid; + private String pathserviceSid; private String friendlyName; private String uniqueName; private String attributes; private Channel.ChannelType type; - public ChannelCreator(final String pathServiceSid) { - this.pathServiceSid = pathServiceSid; + public ChannelCreator(final String pathserviceSid) { + this.pathserviceSid = pathserviceSid; } + public ChannelCreator setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + public ChannelCreator setUniqueName(final String uniqueName) { this.uniqueName = uniqueName; return this; } + public ChannelCreator setAttributes(final String attributes) { this.attributes = attributes; return this; } + public ChannelCreator setType(final Channel.ChannelType type) { this.type = type; return this; } + @Override public Channel create(final TwilioRestClient client) { + String path = "/v1/Services/{ServiceSid}/Channels"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.CHAT.toString(), - path + HttpMethod.POST, + Domains.CHAT.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Channel creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("Channel creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -97,17 +100,26 @@ public Channel create(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + if (uniqueName != null) { - request.addPostParam("UniqueName", uniqueName); + Serializer.toString(request, "UniqueName", uniqueName, ParameterType.URLENCODED); } + + if (attributes != null) { - request.addPostParam("Attributes", attributes); + Serializer.toString(request, "Attributes", attributes, ParameterType.URLENCODED); } + + if (type != null) { - request.addPostParam("Type", type.toString()); + Serializer.toString(request, "Type", type, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/chat/v1/service/ChannelDeleter.java b/src/main/java/com/twilio/rest/chat/v1/service/ChannelDeleter.java index bebff04726..29f7e9631e 100644 --- a/src/main/java/com/twilio/rest/chat/v1/service/ChannelDeleter.java +++ b/src/main/java/com/twilio/rest/chat/v1/service/ChannelDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.chat.v1.service; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,47 +26,41 @@ public class ChannelDeleter extends Deleter { - private String pathServiceSid; - private String pathSid; + private String pathserviceSid; + private String pathsid; - public ChannelDeleter(final String pathServiceSid, final String pathSid) { - this.pathServiceSid = pathServiceSid; - this.pathSid = pathSid; + public ChannelDeleter(final String pathserviceSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/v1/Services/{ServiceSid}/Channels/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.CHAT.toString(), - path + HttpMethod.DELETE, + Domains.CHAT.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Channel delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("Channel delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/chat/v1/service/ChannelFetcher.java b/src/main/java/com/twilio/rest/chat/v1/service/ChannelFetcher.java index c5cbfccd22..1a4c1e02c3 100644 --- a/src/main/java/com/twilio/rest/chat/v1/service/ChannelFetcher.java +++ b/src/main/java/com/twilio/rest/chat/v1/service/ChannelFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.chat.v1.service; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,51 +26,44 @@ public class ChannelFetcher extends Fetcher { - private String pathServiceSid; - private String pathSid; + private String pathserviceSid; + private String pathsid; - public ChannelFetcher(final String pathServiceSid, final String pathSid) { - this.pathServiceSid = pathServiceSid; - this.pathSid = pathSid; + public ChannelFetcher(final String pathserviceSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathsid = pathsid; } + @Override public Channel fetch(final TwilioRestClient client) { + String path = "/v1/Services/{ServiceSid}/Channels/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.CHAT.toString(), - path + HttpMethod.GET, + Domains.CHAT.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Channel fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Channel fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Channel.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/chat/v1/service/ChannelReader.java b/src/main/java/com/twilio/rest/chat/v1/service/ChannelReader.java index 42b4c384cb..e4ca1cb30b 100644 --- a/src/main/java/com/twilio/rest/chat/v1/service/ChannelReader.java +++ b/src/main/java/com/twilio/rest/chat/v1/service/ChannelReader.java @@ -17,8 +17,9 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; import com.twilio.converter.Promoter; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,18 +28,20 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.util.List; public class ChannelReader extends Reader { - private String pathServiceSid; + private String pathserviceSid; private List type; private Long pageSize; - public ChannelReader(final String pathServiceSid) { - this.pathServiceSid = pathServiceSid; + public ChannelReader(final String pathserviceSid) { + this.pathserviceSid = pathserviceSid; } + public ChannelReader setType(final List type) { this.type = type; return this; @@ -53,108 +56,82 @@ public ChannelReader setPageSize(final Long pageSize) { return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/Services/{ServiceSid}/Channels"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.CHAT.toString(), - path + HttpMethod.GET, + Domains.CHAT.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Channel read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Channel read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "channels", - response.getContent(), - Channel.class, - client.getObjectMapper() - ); + "channels", + response.getContent(), + Channel.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.CHAT.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.CHAT.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (type != null) { - for (Channel.ChannelType prop : type) { - request.addQueryParam("Type", prop.toString()); + for (Channel.ChannelType param : type) { + Serializer.toString(request, "Type", param, ParameterType.QUERY); } } + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/chat/v1/service/ChannelUpdater.java b/src/main/java/com/twilio/rest/chat/v1/service/ChannelUpdater.java index 0deeb8f709..8f958052b8 100644 --- a/src/main/java/com/twilio/rest/chat/v1/service/ChannelUpdater.java +++ b/src/main/java/com/twilio/rest/chat/v1/service/ChannelUpdater.java @@ -16,6 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -26,66 +28,64 @@ import com.twilio.rest.Domains; public class ChannelUpdater extends Updater { - - private String pathServiceSid; - private String pathSid; + private String pathserviceSid; + private String pathsid; private String friendlyName; private String uniqueName; private String attributes; - public ChannelUpdater(final String pathServiceSid, final String pathSid) { - this.pathServiceSid = pathServiceSid; - this.pathSid = pathSid; + public ChannelUpdater(final String pathserviceSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathsid = pathsid; } + public ChannelUpdater setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + public ChannelUpdater setUniqueName(final String uniqueName) { this.uniqueName = uniqueName; return this; } + public ChannelUpdater setAttributes(final String attributes) { this.attributes = attributes; return this; } + @Override public Channel update(final TwilioRestClient client) { + String path = "/v1/Services/{ServiceSid}/Channels/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.CHAT.toString(), - path + HttpMethod.POST, + Domains.CHAT.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Channel update failed: Unable to connect to server" - ); + throw new ApiConnectionException("Channel update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -94,14 +94,21 @@ public Channel update(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + if (uniqueName != null) { - request.addPostParam("UniqueName", uniqueName); + Serializer.toString(request, "UniqueName", uniqueName, ParameterType.URLENCODED); } + + if (attributes != null) { - request.addPostParam("Attributes", attributes); + Serializer.toString(request, "Attributes", attributes, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/chat/v1/service/Role.java b/src/main/java/com/twilio/rest/chat/v1/service/Role.java index eaf3e01555..5f6e202e0c 100644 --- a/src/main/java/com/twilio/rest/chat/v1/service/Role.java +++ b/src/main/java/com/twilio/rest/chat/v1/service/Role.java @@ -18,74 +18,93 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.List; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Role extends Resource { - private static final long serialVersionUID = 252065084446046L; - public static RoleCreator creator( - final String pathServiceSid, - final String friendlyName, - final Role.RoleType type, - final List permission - ) { - return new RoleCreator(pathServiceSid, friendlyName, type, permission); + public static RoleCreator creator(final String pathserviceSid, final String friendlyName, final Role.RoleType type, final List permission) { + return new RoleCreator( + pathserviceSid, friendlyName, type, permission + ); } - public static RoleDeleter deleter( - final String pathServiceSid, - final String pathSid - ) { - return new RoleDeleter(pathServiceSid, pathSid); + + public static RoleDeleter deleter(final String pathserviceSid, final String pathsid) { + return new RoleDeleter( + pathserviceSid, pathsid + ); } - public static RoleFetcher fetcher( - final String pathServiceSid, - final String pathSid - ) { - return new RoleFetcher(pathServiceSid, pathSid); + + public static RoleFetcher fetcher(final String pathserviceSid, final String pathsid) { + return new RoleFetcher( + pathserviceSid, pathsid + ); + } + + + public static RoleReader reader(final String pathserviceSid) { + return new RoleReader( + pathserviceSid + ); } - public static RoleReader reader(final String pathServiceSid) { - return new RoleReader(pathServiceSid); + + public static RoleUpdater updater(final String pathserviceSid, final String pathsid, final List permission) { + return new RoleUpdater( + pathserviceSid, pathsid, permission + ); } - public static RoleUpdater updater( - final String pathServiceSid, - final String pathSid, - final List permission - ) { - return new RoleUpdater(pathServiceSid, pathSid, permission); + + public enum RoleType { + CHANNEL("channel"), + DEPLOYMENT("deployment"); + + private final String value; + + private RoleType(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static RoleType forValue(final String value) { + return Promoter.enumFromString(value, RoleType.values()); + } } + /** * Converts a JSON String into a Role object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Role object represented by the provided JSON */ - public static Role fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Role fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Role.class); @@ -100,14 +119,11 @@ public static Role fromJson( * Converts a JSON InputStream into a Role object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Role object represented by the provided JSON */ - public static Role fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Role fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Role.class); @@ -118,75 +134,63 @@ public static Role fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String serviceSid; - private final String friendlyName; - private final Role.RoleType type; - private final List permissions; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; + @Getter + private final String friendlyName; + @Getter + private final List permissions; + @Getter + private final String serviceSid; + @Getter + private final String sid; + @Getter + private final Role.RoleType type; + @Getter private final URI url; @JsonCreator private Role( - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("service_sid") final String serviceSid, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("type") final Role.RoleType type, - @JsonProperty("permissions") final List permissions, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("url") final URI url + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("permissions") final List permissions, + @JsonProperty("service_sid") final String serviceSid, + @JsonProperty("sid") final String sid, + @JsonProperty("type") final Role.RoleType type, + @JsonProperty("url") final URI url ) { - this.sid = sid; this.accountSid = accountSid; - this.serviceSid = serviceSid; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.friendlyName = friendlyName; - this.type = type; this.permissions = permissions; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); + this.serviceSid = serviceSid; + this.sid = sid; + this.type = type; this.url = url; } - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getServiceSid() { - return this.serviceSid; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final Role.RoleType getType() { - return this.type; - } - - public final List getPermissions() { - return this.permissions; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final URI getUrl() { - return this.url; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -198,52 +202,34 @@ public boolean equals(final Object o) { } Role other = (Role) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(serviceSid, other.serviceSid) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(type, other.type) && - Objects.equals(permissions, other.permissions) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(url, other.url) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(permissions, other.permissions) && + Objects.equals(serviceSid, other.serviceSid) && + Objects.equals(sid, other.sid) && + Objects.equals(type, other.type) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - sid, - accountSid, - serviceSid, - friendlyName, - type, - permissions, - dateCreated, - dateUpdated, - url + accountSid, + dateCreated, + dateUpdated, + friendlyName, + permissions, + serviceSid, + sid, + type, + url ); } - public enum RoleType { - CHANNEL("channel"), - DEPLOYMENT("deployment"); - - private final String value; - - private RoleType(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - @JsonCreator - public static RoleType forValue(final String value) { - return Promoter.enumFromString(value, RoleType.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/chat/v1/service/RoleCreator.java b/src/main/java/com/twilio/rest/chat/v1/service/RoleCreator.java index 33ac5741b3..0c060fb740 100644 --- a/src/main/java/com/twilio/rest/chat/v1/service/RoleCreator.java +++ b/src/main/java/com/twilio/rest/chat/v1/service/RoleCreator.java @@ -14,9 +14,12 @@ package com.twilio.rest.chat.v1.service; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; import com.twilio.converter.Promoter; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,38 +28,36 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -import java.util.List; + import java.util.List; public class RoleCreator extends Creator { - private String pathServiceSid; + private String pathserviceSid; private String friendlyName; private Role.RoleType type; private List permission; - public RoleCreator( - final String pathServiceSid, - final String friendlyName, - final Role.RoleType type, - final List permission - ) { - this.pathServiceSid = pathServiceSid; + public RoleCreator(final String pathserviceSid, final String friendlyName, final Role.RoleType type, final List permission) { + this.pathserviceSid = pathserviceSid; this.friendlyName = friendlyName; this.type = type; this.permission = permission; } + public RoleCreator setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + public RoleCreator setType(final Role.RoleType type) { this.type = type; return this; } + public RoleCreator setPermission(final List permission) { this.permission = permission; return this; @@ -68,44 +69,31 @@ public RoleCreator setPermission(final String permission) { @Override public Role create(final TwilioRestClient client) { + String path = "/v1/Services/{ServiceSid}/Roles"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = - path.replace( - "{" + "FriendlyName" + "}", - this.friendlyName.toString() - ); - path = path.replace("{" + "Type" + "}", this.type.toString()); - path = - path.replace("{" + "Permission" + "}", this.permission.toString()); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.CHAT.toString(), - path + HttpMethod.POST, + Domains.CHAT.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Role creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("Role creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -114,16 +102,22 @@ public Role create(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + if (type != null) { - request.addPostParam("Type", type.toString()); + Serializer.toString(request, "Type", type, ParameterType.URLENCODED); } + + if (permission != null) { - for (String prop : permission) { - request.addPostParam("Permission", prop); + for (String param : permission) { + Serializer.toString(request, "Permission", param, ParameterType.URLENCODED); } } + } } diff --git a/src/main/java/com/twilio/rest/chat/v1/service/RoleDeleter.java b/src/main/java/com/twilio/rest/chat/v1/service/RoleDeleter.java index a87252c795..8d40af80f9 100644 --- a/src/main/java/com/twilio/rest/chat/v1/service/RoleDeleter.java +++ b/src/main/java/com/twilio/rest/chat/v1/service/RoleDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.chat.v1.service; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,47 +26,41 @@ public class RoleDeleter extends Deleter { - private String pathServiceSid; - private String pathSid; + private String pathserviceSid; + private String pathsid; - public RoleDeleter(final String pathServiceSid, final String pathSid) { - this.pathServiceSid = pathServiceSid; - this.pathSid = pathSid; + public RoleDeleter(final String pathserviceSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/v1/Services/{ServiceSid}/Roles/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.CHAT.toString(), - path + HttpMethod.DELETE, + Domains.CHAT.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Role delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("Role delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/chat/v1/service/RoleFetcher.java b/src/main/java/com/twilio/rest/chat/v1/service/RoleFetcher.java index bf33555a80..c6d300b80a 100644 --- a/src/main/java/com/twilio/rest/chat/v1/service/RoleFetcher.java +++ b/src/main/java/com/twilio/rest/chat/v1/service/RoleFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.chat.v1.service; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,51 +26,44 @@ public class RoleFetcher extends Fetcher { - private String pathServiceSid; - private String pathSid; + private String pathserviceSid; + private String pathsid; - public RoleFetcher(final String pathServiceSid, final String pathSid) { - this.pathServiceSid = pathServiceSid; - this.pathSid = pathSid; + public RoleFetcher(final String pathserviceSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathsid = pathsid; } + @Override public Role fetch(final TwilioRestClient client) { + String path = "/v1/Services/{ServiceSid}/Roles/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.CHAT.toString(), - path + HttpMethod.GET, + Domains.CHAT.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Role fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Role fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Role.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/chat/v1/service/RoleReader.java b/src/main/java/com/twilio/rest/chat/v1/service/RoleReader.java index 2fb01073ac..2e772e8041 100644 --- a/src/main/java/com/twilio/rest/chat/v1/service/RoleReader.java +++ b/src/main/java/com/twilio/rest/chat/v1/service/RoleReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,115 +30,88 @@ public class RoleReader extends Reader { - private String pathServiceSid; + private String pathserviceSid; private Long pageSize; - public RoleReader(final String pathServiceSid) { - this.pathServiceSid = pathServiceSid; + public RoleReader(final String pathserviceSid) { + this.pathserviceSid = pathserviceSid; } + public RoleReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/Services/{ServiceSid}/Roles"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.CHAT.toString(), - path + HttpMethod.GET, + Domains.CHAT.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Role read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Role read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "roles", - response.getContent(), - Role.class, - client.getObjectMapper() - ); + "roles", + response.getContent(), + Role.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.CHAT.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.CHAT.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/chat/v1/service/RoleUpdater.java b/src/main/java/com/twilio/rest/chat/v1/service/RoleUpdater.java index b9cea8c8c2..869815046f 100644 --- a/src/main/java/com/twilio/rest/chat/v1/service/RoleUpdater.java +++ b/src/main/java/com/twilio/rest/chat/v1/service/RoleUpdater.java @@ -16,7 +16,9 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; import com.twilio.converter.Promoter; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,24 +27,21 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.util.List; public class RoleUpdater extends Updater { - - private String pathServiceSid; - private String pathSid; + private String pathserviceSid; + private String pathsid; private List permission; - public RoleUpdater( - final String pathServiceSid, - final String pathSid, - final List permission - ) { - this.pathServiceSid = pathServiceSid; - this.pathSid = pathSid; + public RoleUpdater(final String pathserviceSid, final String pathsid, final List permission) { + this.pathserviceSid = pathserviceSid; + this.pathsid = pathsid; this.permission = permission; } + public RoleUpdater setPermission(final List permission) { this.permission = permission; return this; @@ -54,39 +53,32 @@ public RoleUpdater setPermission(final String permission) { @Override public Role update(final TwilioRestClient client) { + String path = "/v1/Services/{ServiceSid}/Roles/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); - path = - path.replace("{" + "Permission" + "}", this.permission.toString()); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.CHAT.toString(), - path + HttpMethod.POST, + Domains.CHAT.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Role update failed: Unable to connect to server" - ); + throw new ApiConnectionException("Role update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -95,10 +87,13 @@ public Role update(final TwilioRestClient client) { } private void addPostParams(final Request request) { + + if (permission != null) { - for (String prop : permission) { - request.addPostParam("Permission", prop); + for (String param : permission) { + Serializer.toString(request, "Permission", param, ParameterType.URLENCODED); } } + } } diff --git a/src/main/java/com/twilio/rest/chat/v1/service/User.java b/src/main/java/com/twilio/rest/chat/v1/service/User.java index f0c59969fc..7b1508fe52 100644 --- a/src/main/java/com/twilio/rest/chat/v1/service/User.java +++ b/src/main/java/com/twilio/rest/chat/v1/service/User.java @@ -18,71 +18,71 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class User extends Resource { - private static final long serialVersionUID = 136391609300437L; - public static UserCreator creator( - final String pathServiceSid, - final String identity - ) { - return new UserCreator(pathServiceSid, identity); + public static UserCreator creator(final String pathserviceSid, final String identity) { + return new UserCreator( + pathserviceSid, identity + ); } - public static UserDeleter deleter( - final String pathServiceSid, - final String pathSid - ) { - return new UserDeleter(pathServiceSid, pathSid); + + public static UserDeleter deleter(final String pathserviceSid, final String pathsid) { + return new UserDeleter( + pathserviceSid, pathsid + ); } - public static UserFetcher fetcher( - final String pathServiceSid, - final String pathSid - ) { - return new UserFetcher(pathServiceSid, pathSid); + + public static UserFetcher fetcher(final String pathserviceSid, final String pathsid) { + return new UserFetcher( + pathserviceSid, pathsid + ); } - public static UserReader reader(final String pathServiceSid) { - return new UserReader(pathServiceSid); + + public static UserReader reader(final String pathserviceSid) { + return new UserReader( + pathserviceSid + ); } - public static UserUpdater updater( - final String pathServiceSid, - final String pathSid - ) { - return new UserUpdater(pathServiceSid, pathSid); + + public static UserUpdater updater(final String pathserviceSid, final String pathsid) { + return new UserUpdater( + pathserviceSid, pathsid + ); } + /** * Converts a JSON String into a User object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return User object represented by the provided JSON */ - public static User fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static User fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, User.class); @@ -97,14 +97,11 @@ public static User fromJson( * Converts a JSON InputStream into a User object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return User object represented by the provided JSON */ - public static User fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static User fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, User.class); @@ -115,112 +112,83 @@ public static User fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String serviceSid; + @Getter private final String attributes; + @Getter + private final ZonedDateTime dateCreated; + @Getter + private final ZonedDateTime dateUpdated; + @Getter private final String friendlyName; - private final String roleSid; + @Getter private final String identity; - private final Boolean isOnline; + @Getter private final Boolean isNotifiable; - private final ZonedDateTime dateCreated; - private final ZonedDateTime dateUpdated; + @Getter + private final Boolean isOnline; + @Getter private final Integer joinedChannelsCount; + @Getter private final Map links; + @Getter + private final String roleSid; + @Getter + private final String serviceSid; + @Getter + private final String sid; + @Getter private final URI url; @JsonCreator private User( - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("service_sid") final String serviceSid, - @JsonProperty("attributes") final String attributes, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("role_sid") final String roleSid, - @JsonProperty("identity") final String identity, - @JsonProperty("is_online") final Boolean isOnline, - @JsonProperty("is_notifiable") final Boolean isNotifiable, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty( - "joined_channels_count" - ) final Integer joinedChannelsCount, - @JsonProperty("links") final Map links, - @JsonProperty("url") final URI url + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("attributes") final String attributes, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("identity") final String identity, + @JsonProperty("is_notifiable") final Boolean isNotifiable, + @JsonProperty("is_online") final Boolean isOnline, + @JsonProperty("joined_channels_count") final Integer joinedChannelsCount, + @JsonProperty("links") final Map links, + @JsonProperty("role_sid") final String roleSid, + @JsonProperty("service_sid") final String serviceSid, + @JsonProperty("sid") final String sid, + @JsonProperty("url") final URI url ) { - this.sid = sid; this.accountSid = accountSid; - this.serviceSid = serviceSid; this.attributes = attributes; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.friendlyName = friendlyName; - this.roleSid = roleSid; this.identity = identity; - this.isOnline = isOnline; this.isNotifiable = isNotifiable; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); + this.isOnline = isOnline; this.joinedChannelsCount = joinedChannelsCount; this.links = links; + this.roleSid = roleSid; + this.serviceSid = serviceSid; + this.sid = sid; this.url = url; } - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getServiceSid() { - return this.serviceSid; - } - - public final String getAttributes() { - return this.attributes; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final String getRoleSid() { - return this.roleSid; - } - - public final String getIdentity() { - return this.identity; - } - - public final Boolean getIsOnline() { - return this.isOnline; - } - - public final Boolean getIsNotifiable() { - return this.isNotifiable; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final Integer getJoinedChannelsCount() { - return this.joinedChannelsCount; - } - - public final Map getLinks() { - return this.links; - } - - public final URI getUrl() { - return this.url; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -232,42 +200,44 @@ public boolean equals(final Object o) { } User other = (User) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(serviceSid, other.serviceSid) && - Objects.equals(attributes, other.attributes) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(roleSid, other.roleSid) && - Objects.equals(identity, other.identity) && - Objects.equals(isOnline, other.isOnline) && - Objects.equals(isNotifiable, other.isNotifiable) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(joinedChannelsCount, other.joinedChannelsCount) && - Objects.equals(links, other.links) && - Objects.equals(url, other.url) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(attributes, other.attributes) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(identity, other.identity) && + Objects.equals(isNotifiable, other.isNotifiable) && + Objects.equals(isOnline, other.isOnline) && + Objects.equals(joinedChannelsCount, other.joinedChannelsCount) && + Objects.equals(links, other.links) && + Objects.equals(roleSid, other.roleSid) && + Objects.equals(serviceSid, other.serviceSid) && + Objects.equals(sid, other.sid) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - sid, - accountSid, - serviceSid, - attributes, - friendlyName, - roleSid, - identity, - isOnline, - isNotifiable, - dateCreated, - dateUpdated, - joinedChannelsCount, - links, - url + accountSid, + attributes, + dateCreated, + dateUpdated, + friendlyName, + identity, + isNotifiable, + isOnline, + joinedChannelsCount, + links, + roleSid, + serviceSid, + sid, + url ); } + + } + diff --git a/src/main/java/com/twilio/rest/chat/v1/service/UserCreator.java b/src/main/java/com/twilio/rest/chat/v1/service/UserCreator.java index 577bfd7609..413f8cf33d 100644 --- a/src/main/java/com/twilio/rest/chat/v1/service/UserCreator.java +++ b/src/main/java/com/twilio/rest/chat/v1/service/UserCreator.java @@ -14,8 +14,11 @@ package com.twilio.rest.chat.v1.service; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,70 +30,69 @@ public class UserCreator extends Creator { - private String pathServiceSid; + private String pathserviceSid; private String identity; private String roleSid; private String attributes; private String friendlyName; - public UserCreator(final String pathServiceSid, final String identity) { - this.pathServiceSid = pathServiceSid; + public UserCreator(final String pathserviceSid, final String identity) { + this.pathserviceSid = pathserviceSid; this.identity = identity; } + public UserCreator setIdentity(final String identity) { this.identity = identity; return this; } + public UserCreator setRoleSid(final String roleSid) { this.roleSid = roleSid; return this; } + public UserCreator setAttributes(final String attributes) { this.attributes = attributes; return this; } + public UserCreator setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + @Override public User create(final TwilioRestClient client) { + String path = "/v1/Services/{ServiceSid}/Users"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = path.replace("{" + "Identity" + "}", this.identity.toString()); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.CHAT.toString(), - path + HttpMethod.POST, + Domains.CHAT.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "User creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("User creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -99,17 +101,26 @@ public User create(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (identity != null) { - request.addPostParam("Identity", identity); + Serializer.toString(request, "Identity", identity, ParameterType.URLENCODED); } + + if (roleSid != null) { - request.addPostParam("RoleSid", roleSid); + Serializer.toString(request, "RoleSid", roleSid, ParameterType.URLENCODED); } + + if (attributes != null) { - request.addPostParam("Attributes", attributes); + Serializer.toString(request, "Attributes", attributes, ParameterType.URLENCODED); } + + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/chat/v1/service/UserDeleter.java b/src/main/java/com/twilio/rest/chat/v1/service/UserDeleter.java index 331a4e5e46..25e428e391 100644 --- a/src/main/java/com/twilio/rest/chat/v1/service/UserDeleter.java +++ b/src/main/java/com/twilio/rest/chat/v1/service/UserDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.chat.v1.service; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,47 +26,41 @@ public class UserDeleter extends Deleter { - private String pathServiceSid; - private String pathSid; + private String pathserviceSid; + private String pathsid; - public UserDeleter(final String pathServiceSid, final String pathSid) { - this.pathServiceSid = pathServiceSid; - this.pathSid = pathSid; + public UserDeleter(final String pathserviceSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/v1/Services/{ServiceSid}/Users/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.CHAT.toString(), - path + HttpMethod.DELETE, + Domains.CHAT.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "User delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("User delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/chat/v1/service/UserFetcher.java b/src/main/java/com/twilio/rest/chat/v1/service/UserFetcher.java index 6f0e1d86b2..129d129bd3 100644 --- a/src/main/java/com/twilio/rest/chat/v1/service/UserFetcher.java +++ b/src/main/java/com/twilio/rest/chat/v1/service/UserFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.chat.v1.service; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,51 +26,44 @@ public class UserFetcher extends Fetcher { - private String pathServiceSid; - private String pathSid; + private String pathserviceSid; + private String pathsid; - public UserFetcher(final String pathServiceSid, final String pathSid) { - this.pathServiceSid = pathServiceSid; - this.pathSid = pathSid; + public UserFetcher(final String pathserviceSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathsid = pathsid; } + @Override public User fetch(final TwilioRestClient client) { + String path = "/v1/Services/{ServiceSid}/Users/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.CHAT.toString(), - path + HttpMethod.GET, + Domains.CHAT.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "User fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("User fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return User.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/chat/v1/service/UserReader.java b/src/main/java/com/twilio/rest/chat/v1/service/UserReader.java index 230320c524..185f2798ca 100644 --- a/src/main/java/com/twilio/rest/chat/v1/service/UserReader.java +++ b/src/main/java/com/twilio/rest/chat/v1/service/UserReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,115 +30,88 @@ public class UserReader extends Reader { - private String pathServiceSid; + private String pathserviceSid; private Long pageSize; - public UserReader(final String pathServiceSid) { - this.pathServiceSid = pathServiceSid; + public UserReader(final String pathserviceSid) { + this.pathserviceSid = pathserviceSid; } + public UserReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/Services/{ServiceSid}/Users"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.CHAT.toString(), - path + HttpMethod.GET, + Domains.CHAT.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "User read failed: Unable to connect to server" - ); + throw new ApiConnectionException("User read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "users", - response.getContent(), - User.class, - client.getObjectMapper() - ); + "users", + response.getContent(), + User.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.CHAT.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.CHAT.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/chat/v1/service/UserUpdater.java b/src/main/java/com/twilio/rest/chat/v1/service/UserUpdater.java index 53aed961ff..476ca5cb29 100644 --- a/src/main/java/com/twilio/rest/chat/v1/service/UserUpdater.java +++ b/src/main/java/com/twilio/rest/chat/v1/service/UserUpdater.java @@ -16,6 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -26,66 +28,64 @@ import com.twilio.rest.Domains; public class UserUpdater extends Updater { - - private String pathServiceSid; - private String pathSid; + private String pathserviceSid; + private String pathsid; private String roleSid; private String attributes; private String friendlyName; - public UserUpdater(final String pathServiceSid, final String pathSid) { - this.pathServiceSid = pathServiceSid; - this.pathSid = pathSid; + public UserUpdater(final String pathserviceSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathsid = pathsid; } + public UserUpdater setRoleSid(final String roleSid) { this.roleSid = roleSid; return this; } + public UserUpdater setAttributes(final String attributes) { this.attributes = attributes; return this; } + public UserUpdater setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + @Override public User update(final TwilioRestClient client) { + String path = "/v1/Services/{ServiceSid}/Users/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.CHAT.toString(), - path + HttpMethod.POST, + Domains.CHAT.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "User update failed: Unable to connect to server" - ); + throw new ApiConnectionException("User update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -94,14 +94,21 @@ public User update(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (roleSid != null) { - request.addPostParam("RoleSid", roleSid); + Serializer.toString(request, "RoleSid", roleSid, ParameterType.URLENCODED); } + + if (attributes != null) { - request.addPostParam("Attributes", attributes); + Serializer.toString(request, "Attributes", attributes, ParameterType.URLENCODED); } + + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/chat/v1/service/channel/Invite.java b/src/main/java/com/twilio/rest/chat/v1/service/channel/Invite.java index daf4f4701f..a6419426ac 100644 --- a/src/main/java/com/twilio/rest/chat/v1/service/channel/Invite.java +++ b/src/main/java/com/twilio/rest/chat/v1/service/channel/Invite.java @@ -18,68 +18,63 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Invite extends Resource { - private static final long serialVersionUID = 148273166902210L; - public static InviteCreator creator( - final String pathServiceSid, - final String pathChannelSid, - final String identity - ) { - return new InviteCreator(pathServiceSid, pathChannelSid, identity); + public static InviteCreator creator(final String pathserviceSid, final String pathchannelSid, final String identity) { + return new InviteCreator( + pathserviceSid, pathchannelSid, identity + ); } - public static InviteDeleter deleter( - final String pathServiceSid, - final String pathChannelSid, - final String pathSid - ) { - return new InviteDeleter(pathServiceSid, pathChannelSid, pathSid); + + public static InviteDeleter deleter(final String pathserviceSid, final String pathchannelSid, final String pathsid) { + return new InviteDeleter( + pathserviceSid, pathchannelSid, pathsid + ); } - public static InviteFetcher fetcher( - final String pathServiceSid, - final String pathChannelSid, - final String pathSid - ) { - return new InviteFetcher(pathServiceSid, pathChannelSid, pathSid); + + public static InviteFetcher fetcher(final String pathserviceSid, final String pathchannelSid, final String pathsid) { + return new InviteFetcher( + pathserviceSid, pathchannelSid, pathsid + ); } - public static InviteReader reader( - final String pathServiceSid, - final String pathChannelSid - ) { - return new InviteReader(pathServiceSid, pathChannelSid); + + public static InviteReader reader(final String pathserviceSid, final String pathchannelSid) { + return new InviteReader( + pathserviceSid, pathchannelSid + ); } + /** * Converts a JSON String into a Invite object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Invite object represented by the provided JSON */ - public static Invite fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Invite fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Invite.class); @@ -94,14 +89,11 @@ public static Invite fromJson( * Converts a JSON InputStream into a Invite object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Invite object represented by the provided JSON */ - public static Invite fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Invite fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Invite.class); @@ -112,82 +104,67 @@ public static Invite fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; + @Getter private final String channelSid; - private final String serviceSid; - private final String identity; + @Getter + private final String createdBy; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; + @Getter + private final String identity; + @Getter private final String roleSid; - private final String createdBy; + @Getter + private final String serviceSid; + @Getter + private final String sid; + @Getter private final URI url; @JsonCreator private Invite( - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("channel_sid") final String channelSid, - @JsonProperty("service_sid") final String serviceSid, - @JsonProperty("identity") final String identity, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("role_sid") final String roleSid, - @JsonProperty("created_by") final String createdBy, - @JsonProperty("url") final URI url + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("channel_sid") final String channelSid, + @JsonProperty("created_by") final String createdBy, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("identity") final String identity, + @JsonProperty("role_sid") final String roleSid, + @JsonProperty("service_sid") final String serviceSid, + @JsonProperty("sid") final String sid, + @JsonProperty("url") final URI url ) { - this.sid = sid; this.accountSid = accountSid; this.channelSid = channelSid; - this.serviceSid = serviceSid; + this.createdBy = createdBy; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.identity = identity; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); this.roleSid = roleSid; - this.createdBy = createdBy; + this.serviceSid = serviceSid; + this.sid = sid; this.url = url; } - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getChannelSid() { - return this.channelSid; - } - - public final String getServiceSid() { - return this.serviceSid; - } - - public final String getIdentity() { - return this.identity; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final String getRoleSid() { - return this.roleSid; - } - - public final String getCreatedBy() { - return this.createdBy; - } - - public final URI getUrl() { - return this.url; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -199,34 +176,36 @@ public boolean equals(final Object o) { } Invite other = (Invite) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(channelSid, other.channelSid) && - Objects.equals(serviceSid, other.serviceSid) && - Objects.equals(identity, other.identity) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(roleSid, other.roleSid) && - Objects.equals(createdBy, other.createdBy) && - Objects.equals(url, other.url) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(channelSid, other.channelSid) && + Objects.equals(createdBy, other.createdBy) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(identity, other.identity) && + Objects.equals(roleSid, other.roleSid) && + Objects.equals(serviceSid, other.serviceSid) && + Objects.equals(sid, other.sid) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - sid, - accountSid, - channelSid, - serviceSid, - identity, - dateCreated, - dateUpdated, - roleSid, - createdBy, - url + accountSid, + channelSid, + createdBy, + dateCreated, + dateUpdated, + identity, + roleSid, + serviceSid, + sid, + url ); } + + } + diff --git a/src/main/java/com/twilio/rest/chat/v1/service/channel/InviteCreator.java b/src/main/java/com/twilio/rest/chat/v1/service/channel/InviteCreator.java index 9acefa3fd5..88bd25d6c6 100644 --- a/src/main/java/com/twilio/rest/chat/v1/service/channel/InviteCreator.java +++ b/src/main/java/com/twilio/rest/chat/v1/service/channel/InviteCreator.java @@ -14,8 +14,11 @@ package com.twilio.rest.chat.v1.service.channel; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,69 +30,58 @@ public class InviteCreator extends Creator { - private String pathServiceSid; - private String pathChannelSid; + private String pathserviceSid; + private String pathchannelSid; private String identity; private String roleSid; - public InviteCreator( - final String pathServiceSid, - final String pathChannelSid, - final String identity - ) { - this.pathServiceSid = pathServiceSid; - this.pathChannelSid = pathChannelSid; + public InviteCreator(final String pathserviceSid, final String pathchannelSid, final String identity) { + this.pathserviceSid = pathserviceSid; + this.pathchannelSid = pathchannelSid; this.identity = identity; } + public InviteCreator setIdentity(final String identity) { this.identity = identity; return this; } + public InviteCreator setRoleSid(final String roleSid) { this.roleSid = roleSid; return this; } + @Override public Invite create(final TwilioRestClient client) { + String path = "/v1/Services/{ServiceSid}/Channels/{ChannelSid}/Invites"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = - path.replace( - "{" + "ChannelSid" + "}", - this.pathChannelSid.toString() - ); - path = path.replace("{" + "Identity" + "}", this.identity.toString()); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "ChannelSid" + "}", this.pathchannelSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.CHAT.toString(), - path + HttpMethod.POST, + Domains.CHAT.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Invite creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("Invite creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -98,11 +90,16 @@ public Invite create(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (identity != null) { - request.addPostParam("Identity", identity); + Serializer.toString(request, "Identity", identity, ParameterType.URLENCODED); } + + if (roleSid != null) { - request.addPostParam("RoleSid", roleSid); + Serializer.toString(request, "RoleSid", roleSid, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/chat/v1/service/channel/InviteDeleter.java b/src/main/java/com/twilio/rest/chat/v1/service/channel/InviteDeleter.java index eca318c1f5..d96f0fcd43 100644 --- a/src/main/java/com/twilio/rest/chat/v1/service/channel/InviteDeleter.java +++ b/src/main/java/com/twilio/rest/chat/v1/service/channel/InviteDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.chat.v1.service.channel; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,59 +26,44 @@ public class InviteDeleter extends Deleter { - private String pathServiceSid; - private String pathChannelSid; - private String pathSid; + private String pathserviceSid; + private String pathchannelSid; + private String pathsid; - public InviteDeleter( - final String pathServiceSid, - final String pathChannelSid, - final String pathSid - ) { - this.pathServiceSid = pathServiceSid; - this.pathChannelSid = pathChannelSid; - this.pathSid = pathSid; + public InviteDeleter(final String pathserviceSid, final String pathchannelSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathchannelSid = pathchannelSid; + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { - String path = - "/v1/Services/{ServiceSid}/Channels/{ChannelSid}/Invites/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = - path.replace( - "{" + "ChannelSid" + "}", - this.pathChannelSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/v1/Services/{ServiceSid}/Channels/{ChannelSid}/Invites/{Sid}"; + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "ChannelSid" + "}", this.pathchannelSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.CHAT.toString(), - path + HttpMethod.DELETE, + Domains.CHAT.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Invite delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("Invite delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/chat/v1/service/channel/InviteFetcher.java b/src/main/java/com/twilio/rest/chat/v1/service/channel/InviteFetcher.java index 860a50ae49..76df1d3804 100644 --- a/src/main/java/com/twilio/rest/chat/v1/service/channel/InviteFetcher.java +++ b/src/main/java/com/twilio/rest/chat/v1/service/channel/InviteFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.chat.v1.service.channel; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,63 +26,47 @@ public class InviteFetcher extends Fetcher { - private String pathServiceSid; - private String pathChannelSid; - private String pathSid; + private String pathserviceSid; + private String pathchannelSid; + private String pathsid; - public InviteFetcher( - final String pathServiceSid, - final String pathChannelSid, - final String pathSid - ) { - this.pathServiceSid = pathServiceSid; - this.pathChannelSid = pathChannelSid; - this.pathSid = pathSid; + public InviteFetcher(final String pathserviceSid, final String pathchannelSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathchannelSid = pathchannelSid; + this.pathsid = pathsid; } + @Override public Invite fetch(final TwilioRestClient client) { - String path = - "/v1/Services/{ServiceSid}/Channels/{ChannelSid}/Invites/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = - path.replace( - "{" + "ChannelSid" + "}", - this.pathChannelSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/v1/Services/{ServiceSid}/Channels/{ChannelSid}/Invites/{Sid}"; + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "ChannelSid" + "}", this.pathchannelSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.CHAT.toString(), - path + HttpMethod.GET, + Domains.CHAT.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Invite fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Invite fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Invite.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/chat/v1/service/channel/InviteReader.java b/src/main/java/com/twilio/rest/chat/v1/service/channel/InviteReader.java index 6af434d380..2153d441cc 100644 --- a/src/main/java/com/twilio/rest/chat/v1/service/channel/InviteReader.java +++ b/src/main/java/com/twilio/rest/chat/v1/service/channel/InviteReader.java @@ -17,8 +17,9 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; import com.twilio.converter.Promoter; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,23 +28,22 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.util.List; public class InviteReader extends Reader { - private String pathServiceSid; - private String pathChannelSid; + private String pathserviceSid; + private String pathchannelSid; private List identity; private Long pageSize; - public InviteReader( - final String pathServiceSid, - final String pathChannelSid - ) { - this.pathServiceSid = pathServiceSid; - this.pathChannelSid = pathChannelSid; + public InviteReader(final String pathserviceSid, final String pathchannelSid) { + this.pathserviceSid = pathserviceSid; + this.pathchannelSid = pathchannelSid; } + public InviteReader setIdentity(final List identity) { this.identity = identity; return this; @@ -58,113 +58,83 @@ public InviteReader setPageSize(final Long pageSize) { return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/Services/{ServiceSid}/Channels/{ChannelSid}/Invites"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = - path.replace( - "{" + "ChannelSid" + "}", - this.pathChannelSid.toString() - ); + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "ChannelSid" + "}", this.pathchannelSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.CHAT.toString(), - path + HttpMethod.GET, + Domains.CHAT.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Invite read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Invite read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "invites", - response.getContent(), - Invite.class, - client.getObjectMapper() - ); + "invites", + response.getContent(), + Invite.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.CHAT.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.CHAT.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (identity != null) { - for (String prop : identity) { - request.addQueryParam("Identity", prop); + for (String param : identity) { + Serializer.toString(request, "Identity", param, ParameterType.QUERY); } } + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/chat/v1/service/channel/Member.java b/src/main/java/com/twilio/rest/chat/v1/service/channel/Member.java index 166f46e1e2..0a882da580 100644 --- a/src/main/java/com/twilio/rest/chat/v1/service/channel/Member.java +++ b/src/main/java/com/twilio/rest/chat/v1/service/channel/Member.java @@ -18,76 +18,70 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Member extends Resource { - private static final long serialVersionUID = 102757132179124L; - public static MemberCreator creator( - final String pathServiceSid, - final String pathChannelSid, - final String identity - ) { - return new MemberCreator(pathServiceSid, pathChannelSid, identity); + public static MemberCreator creator(final String pathserviceSid, final String pathchannelSid, final String identity) { + return new MemberCreator( + pathserviceSid, pathchannelSid, identity + ); } - public static MemberDeleter deleter( - final String pathServiceSid, - final String pathChannelSid, - final String pathSid - ) { - return new MemberDeleter(pathServiceSid, pathChannelSid, pathSid); + + public static MemberDeleter deleter(final String pathserviceSid, final String pathchannelSid, final String pathsid) { + return new MemberDeleter( + pathserviceSid, pathchannelSid, pathsid + ); } - public static MemberFetcher fetcher( - final String pathServiceSid, - final String pathChannelSid, - final String pathSid - ) { - return new MemberFetcher(pathServiceSid, pathChannelSid, pathSid); + + public static MemberFetcher fetcher(final String pathserviceSid, final String pathchannelSid, final String pathsid) { + return new MemberFetcher( + pathserviceSid, pathchannelSid, pathsid + ); } - public static MemberReader reader( - final String pathServiceSid, - final String pathChannelSid - ) { - return new MemberReader(pathServiceSid, pathChannelSid); + + public static MemberReader reader(final String pathserviceSid, final String pathchannelSid) { + return new MemberReader( + pathserviceSid, pathchannelSid + ); } - public static MemberUpdater updater( - final String pathServiceSid, - final String pathChannelSid, - final String pathSid - ) { - return new MemberUpdater(pathServiceSid, pathChannelSid, pathSid); + + public static MemberUpdater updater(final String pathserviceSid, final String pathchannelSid, final String pathsid) { + return new MemberUpdater( + pathserviceSid, pathchannelSid, pathsid + ); } + /** * Converts a JSON String into a Member object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Member object represented by the provided JSON */ - public static Member fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Member fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Member.class); @@ -102,14 +96,11 @@ public static Member fromJson( * Converts a JSON InputStream into a Member object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Member object represented by the provided JSON */ - public static Member fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Member fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Member.class); @@ -120,94 +111,72 @@ public static Member fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; + @Getter private final String channelSid; - private final String serviceSid; - private final String identity; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; - private final String roleSid; + @Getter + private final String identity; + @Getter private final Integer lastConsumedMessageIndex; + @Getter private final ZonedDateTime lastConsumptionTimestamp; + @Getter + private final String roleSid; + @Getter + private final String serviceSid; + @Getter + private final String sid; + @Getter private final URI url; @JsonCreator private Member( - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("channel_sid") final String channelSid, - @JsonProperty("service_sid") final String serviceSid, - @JsonProperty("identity") final String identity, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("role_sid") final String roleSid, - @JsonProperty( - "last_consumed_message_index" - ) final Integer lastConsumedMessageIndex, - @JsonProperty( - "last_consumption_timestamp" - ) final String lastConsumptionTimestamp, - @JsonProperty("url") final URI url + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("channel_sid") final String channelSid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("identity") final String identity, + @JsonProperty("last_consumed_message_index") final Integer lastConsumedMessageIndex, + @JsonProperty("last_consumption_timestamp") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime lastConsumptionTimestamp, + @JsonProperty("role_sid") final String roleSid, + @JsonProperty("service_sid") final String serviceSid, + @JsonProperty("sid") final String sid, + @JsonProperty("url") final URI url ) { - this.sid = sid; this.accountSid = accountSid; this.channelSid = channelSid; - this.serviceSid = serviceSid; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.identity = identity; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); - this.roleSid = roleSid; this.lastConsumedMessageIndex = lastConsumedMessageIndex; - this.lastConsumptionTimestamp = - DateConverter.iso8601DateTimeFromString(lastConsumptionTimestamp); + this.lastConsumptionTimestamp = lastConsumptionTimestamp; + this.roleSid = roleSid; + this.serviceSid = serviceSid; + this.sid = sid; this.url = url; } - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getChannelSid() { - return this.channelSid; - } - - public final String getServiceSid() { - return this.serviceSid; - } - - public final String getIdentity() { - return this.identity; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final String getRoleSid() { - return this.roleSid; - } - - public final Integer getLastConsumedMessageIndex() { - return this.lastConsumedMessageIndex; - } - - public final ZonedDateTime getLastConsumptionTimestamp() { - return this.lastConsumptionTimestamp; - } - - public final URI getUrl() { - return this.url; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -219,42 +188,38 @@ public boolean equals(final Object o) { } Member other = (Member) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(channelSid, other.channelSid) && - Objects.equals(serviceSid, other.serviceSid) && - Objects.equals(identity, other.identity) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(roleSid, other.roleSid) && - Objects.equals( - lastConsumedMessageIndex, - other.lastConsumedMessageIndex - ) && - Objects.equals( - lastConsumptionTimestamp, - other.lastConsumptionTimestamp - ) && - Objects.equals(url, other.url) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(channelSid, other.channelSid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(identity, other.identity) && + Objects.equals(lastConsumedMessageIndex, other.lastConsumedMessageIndex) && + Objects.equals(lastConsumptionTimestamp, other.lastConsumptionTimestamp) && + Objects.equals(roleSid, other.roleSid) && + Objects.equals(serviceSid, other.serviceSid) && + Objects.equals(sid, other.sid) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - sid, - accountSid, - channelSid, - serviceSid, - identity, - dateCreated, - dateUpdated, - roleSid, - lastConsumedMessageIndex, - lastConsumptionTimestamp, - url + accountSid, + channelSid, + dateCreated, + dateUpdated, + identity, + lastConsumedMessageIndex, + lastConsumptionTimestamp, + roleSid, + serviceSid, + sid, + url ); } + + } + diff --git a/src/main/java/com/twilio/rest/chat/v1/service/channel/MemberCreator.java b/src/main/java/com/twilio/rest/chat/v1/service/channel/MemberCreator.java index c5ffc99c8b..a6678f655d 100644 --- a/src/main/java/com/twilio/rest/chat/v1/service/channel/MemberCreator.java +++ b/src/main/java/com/twilio/rest/chat/v1/service/channel/MemberCreator.java @@ -14,8 +14,11 @@ package com.twilio.rest.chat.v1.service.channel; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,69 +30,58 @@ public class MemberCreator extends Creator { - private String pathServiceSid; - private String pathChannelSid; + private String pathserviceSid; + private String pathchannelSid; private String identity; private String roleSid; - public MemberCreator( - final String pathServiceSid, - final String pathChannelSid, - final String identity - ) { - this.pathServiceSid = pathServiceSid; - this.pathChannelSid = pathChannelSid; + public MemberCreator(final String pathserviceSid, final String pathchannelSid, final String identity) { + this.pathserviceSid = pathserviceSid; + this.pathchannelSid = pathchannelSid; this.identity = identity; } + public MemberCreator setIdentity(final String identity) { this.identity = identity; return this; } + public MemberCreator setRoleSid(final String roleSid) { this.roleSid = roleSid; return this; } + @Override public Member create(final TwilioRestClient client) { + String path = "/v1/Services/{ServiceSid}/Channels/{ChannelSid}/Members"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = - path.replace( - "{" + "ChannelSid" + "}", - this.pathChannelSid.toString() - ); - path = path.replace("{" + "Identity" + "}", this.identity.toString()); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "ChannelSid" + "}", this.pathchannelSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.CHAT.toString(), - path + HttpMethod.POST, + Domains.CHAT.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Member creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("Member creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -98,11 +90,16 @@ public Member create(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (identity != null) { - request.addPostParam("Identity", identity); + Serializer.toString(request, "Identity", identity, ParameterType.URLENCODED); } + + if (roleSid != null) { - request.addPostParam("RoleSid", roleSid); + Serializer.toString(request, "RoleSid", roleSid, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/chat/v1/service/channel/MemberDeleter.java b/src/main/java/com/twilio/rest/chat/v1/service/channel/MemberDeleter.java index 06df8253ea..d93c1affa5 100644 --- a/src/main/java/com/twilio/rest/chat/v1/service/channel/MemberDeleter.java +++ b/src/main/java/com/twilio/rest/chat/v1/service/channel/MemberDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.chat.v1.service.channel; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,59 +26,44 @@ public class MemberDeleter extends Deleter { - private String pathServiceSid; - private String pathChannelSid; - private String pathSid; + private String pathserviceSid; + private String pathchannelSid; + private String pathsid; - public MemberDeleter( - final String pathServiceSid, - final String pathChannelSid, - final String pathSid - ) { - this.pathServiceSid = pathServiceSid; - this.pathChannelSid = pathChannelSid; - this.pathSid = pathSid; + public MemberDeleter(final String pathserviceSid, final String pathchannelSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathchannelSid = pathchannelSid; + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { - String path = - "/v1/Services/{ServiceSid}/Channels/{ChannelSid}/Members/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = - path.replace( - "{" + "ChannelSid" + "}", - this.pathChannelSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/v1/Services/{ServiceSid}/Channels/{ChannelSid}/Members/{Sid}"; + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "ChannelSid" + "}", this.pathchannelSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.CHAT.toString(), - path + HttpMethod.DELETE, + Domains.CHAT.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Member delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("Member delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/chat/v1/service/channel/MemberFetcher.java b/src/main/java/com/twilio/rest/chat/v1/service/channel/MemberFetcher.java index 80866c841b..c96ad55044 100644 --- a/src/main/java/com/twilio/rest/chat/v1/service/channel/MemberFetcher.java +++ b/src/main/java/com/twilio/rest/chat/v1/service/channel/MemberFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.chat.v1.service.channel; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,63 +26,47 @@ public class MemberFetcher extends Fetcher { - private String pathServiceSid; - private String pathChannelSid; - private String pathSid; + private String pathserviceSid; + private String pathchannelSid; + private String pathsid; - public MemberFetcher( - final String pathServiceSid, - final String pathChannelSid, - final String pathSid - ) { - this.pathServiceSid = pathServiceSid; - this.pathChannelSid = pathChannelSid; - this.pathSid = pathSid; + public MemberFetcher(final String pathserviceSid, final String pathchannelSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathchannelSid = pathchannelSid; + this.pathsid = pathsid; } + @Override public Member fetch(final TwilioRestClient client) { - String path = - "/v1/Services/{ServiceSid}/Channels/{ChannelSid}/Members/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = - path.replace( - "{" + "ChannelSid" + "}", - this.pathChannelSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/v1/Services/{ServiceSid}/Channels/{ChannelSid}/Members/{Sid}"; + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "ChannelSid" + "}", this.pathchannelSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.CHAT.toString(), - path + HttpMethod.GET, + Domains.CHAT.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Member fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Member fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Member.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/chat/v1/service/channel/MemberReader.java b/src/main/java/com/twilio/rest/chat/v1/service/channel/MemberReader.java index 8fc0c3fc80..76b538d788 100644 --- a/src/main/java/com/twilio/rest/chat/v1/service/channel/MemberReader.java +++ b/src/main/java/com/twilio/rest/chat/v1/service/channel/MemberReader.java @@ -17,8 +17,9 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; import com.twilio.converter.Promoter; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,23 +28,22 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.util.List; public class MemberReader extends Reader { - private String pathServiceSid; - private String pathChannelSid; + private String pathserviceSid; + private String pathchannelSid; private List identity; private Long pageSize; - public MemberReader( - final String pathServiceSid, - final String pathChannelSid - ) { - this.pathServiceSid = pathServiceSid; - this.pathChannelSid = pathChannelSid; + public MemberReader(final String pathserviceSid, final String pathchannelSid) { + this.pathserviceSid = pathserviceSid; + this.pathchannelSid = pathchannelSid; } + public MemberReader setIdentity(final List identity) { this.identity = identity; return this; @@ -58,113 +58,83 @@ public MemberReader setPageSize(final Long pageSize) { return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/Services/{ServiceSid}/Channels/{ChannelSid}/Members"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = - path.replace( - "{" + "ChannelSid" + "}", - this.pathChannelSid.toString() - ); + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "ChannelSid" + "}", this.pathchannelSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.CHAT.toString(), - path + HttpMethod.GET, + Domains.CHAT.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Member read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Member read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "members", - response.getContent(), - Member.class, - client.getObjectMapper() - ); + "members", + response.getContent(), + Member.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.CHAT.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.CHAT.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (identity != null) { - for (String prop : identity) { - request.addQueryParam("Identity", prop); + for (String param : identity) { + Serializer.toString(request, "Identity", param, ParameterType.QUERY); } } + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/chat/v1/service/channel/MemberUpdater.java b/src/main/java/com/twilio/rest/chat/v1/service/channel/MemberUpdater.java index c556cca07b..db9b0ee102 100644 --- a/src/main/java/com/twilio/rest/chat/v1/service/channel/MemberUpdater.java +++ b/src/main/java/com/twilio/rest/chat/v1/service/channel/MemberUpdater.java @@ -16,6 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -26,74 +28,60 @@ import com.twilio.rest.Domains; public class MemberUpdater extends Updater { - - private String pathServiceSid; - private String pathChannelSid; - private String pathSid; + private String pathserviceSid; + private String pathchannelSid; + private String pathsid; private String roleSid; private Integer lastConsumedMessageIndex; - public MemberUpdater( - final String pathServiceSid, - final String pathChannelSid, - final String pathSid - ) { - this.pathServiceSid = pathServiceSid; - this.pathChannelSid = pathChannelSid; - this.pathSid = pathSid; + public MemberUpdater(final String pathserviceSid, final String pathchannelSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathchannelSid = pathchannelSid; + this.pathsid = pathsid; } + public MemberUpdater setRoleSid(final String roleSid) { this.roleSid = roleSid; return this; } - public MemberUpdater setLastConsumedMessageIndex( - final Integer lastConsumedMessageIndex - ) { + + public MemberUpdater setLastConsumedMessageIndex(final Integer lastConsumedMessageIndex) { this.lastConsumedMessageIndex = lastConsumedMessageIndex; return this; } + @Override public Member update(final TwilioRestClient client) { - String path = - "/v1/Services/{ServiceSid}/Channels/{ChannelSid}/Members/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = - path.replace( - "{" + "ChannelSid" + "}", - this.pathChannelSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/v1/Services/{ServiceSid}/Channels/{ChannelSid}/Members/{Sid}"; + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "ChannelSid" + "}", this.pathchannelSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.CHAT.toString(), - path + HttpMethod.POST, + Domains.CHAT.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Member update failed: Unable to connect to server" - ); + throw new ApiConnectionException("Member update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -102,14 +90,16 @@ public Member update(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (roleSid != null) { - request.addPostParam("RoleSid", roleSid); + Serializer.toString(request, "RoleSid", roleSid, ParameterType.URLENCODED); } + + if (lastConsumedMessageIndex != null) { - request.addPostParam( - "LastConsumedMessageIndex", - lastConsumedMessageIndex.toString() - ); + Serializer.toString(request, "LastConsumedMessageIndex", lastConsumedMessageIndex, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/chat/v1/service/channel/Message.java b/src/main/java/com/twilio/rest/chat/v1/service/channel/Message.java index 286f9952bf..8384a7e4f5 100644 --- a/src/main/java/com/twilio/rest/chat/v1/service/channel/Message.java +++ b/src/main/java/com/twilio/rest/chat/v1/service/channel/Message.java @@ -18,77 +18,92 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Message extends Resource { - private static final long serialVersionUID = 148235601690422L; - public static MessageCreator creator( - final String pathServiceSid, - final String pathChannelSid, - final String body - ) { - return new MessageCreator(pathServiceSid, pathChannelSid, body); + public static MessageCreator creator(final String pathserviceSid, final String pathchannelSid, final String body) { + return new MessageCreator( + pathserviceSid, pathchannelSid, body + ); } - public static MessageDeleter deleter( - final String pathServiceSid, - final String pathChannelSid, - final String pathSid - ) { - return new MessageDeleter(pathServiceSid, pathChannelSid, pathSid); + + public static MessageDeleter deleter(final String pathserviceSid, final String pathchannelSid, final String pathsid) { + return new MessageDeleter( + pathserviceSid, pathchannelSid, pathsid + ); } - public static MessageFetcher fetcher( - final String pathServiceSid, - final String pathChannelSid, - final String pathSid - ) { - return new MessageFetcher(pathServiceSid, pathChannelSid, pathSid); + + public static MessageFetcher fetcher(final String pathserviceSid, final String pathchannelSid, final String pathsid) { + return new MessageFetcher( + pathserviceSid, pathchannelSid, pathsid + ); } - public static MessageReader reader( - final String pathServiceSid, - final String pathChannelSid - ) { - return new MessageReader(pathServiceSid, pathChannelSid); + + public static MessageReader reader(final String pathserviceSid, final String pathchannelSid) { + return new MessageReader( + pathserviceSid, pathchannelSid + ); } - public static MessageUpdater updater( - final String pathServiceSid, - final String pathChannelSid, - final String pathSid - ) { - return new MessageUpdater(pathServiceSid, pathChannelSid, pathSid); + + public static MessageUpdater updater(final String pathserviceSid, final String pathchannelSid, final String pathsid) { + return new MessageUpdater( + pathserviceSid, pathchannelSid, pathsid + ); } + + public enum OrderType { + ASC("asc"), + DESC("desc"); + + private final String value; + + private OrderType(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static OrderType forValue(final String value) { + return Promoter.enumFromString(value, OrderType.values()); + } + } + + /** * Converts a JSON String into a Message object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Message object represented by the provided JSON */ - public static Message fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Message fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Message.class); @@ -103,14 +118,11 @@ public static Message fromJson( * Converts a JSON InputStream into a Message object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Message object represented by the provided JSON */ - public static Message fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Message fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Message.class); @@ -121,101 +133,77 @@ public static Message fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; + @Getter private final String attributes; - private final String serviceSid; - private final String to; + @Getter + private final String body; + @Getter private final String channelSid; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; - private final Boolean wasEdited; + @Getter private final String from; - private final String body; + @Getter private final Integer index; + @Getter + private final String serviceSid; + @Getter + private final String sid; + @Getter + private final String to; + @Getter private final URI url; + @Getter + private final Boolean wasEdited; @JsonCreator private Message( - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("attributes") final String attributes, - @JsonProperty("service_sid") final String serviceSid, - @JsonProperty("to") final String to, - @JsonProperty("channel_sid") final String channelSid, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("was_edited") final Boolean wasEdited, - @JsonProperty("from") final String from, - @JsonProperty("body") final String body, - @JsonProperty("index") final Integer index, - @JsonProperty("url") final URI url + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("attributes") final String attributes, + @JsonProperty("body") final String body, + @JsonProperty("channel_sid") final String channelSid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("from") final String from, + @JsonProperty("index") final Integer index, + @JsonProperty("service_sid") final String serviceSid, + @JsonProperty("sid") final String sid, + @JsonProperty("to") final String to, + @JsonProperty("url") final URI url, + @JsonProperty("was_edited") final Boolean wasEdited ) { - this.sid = sid; this.accountSid = accountSid; this.attributes = attributes; - this.serviceSid = serviceSid; - this.to = to; + this.body = body; this.channelSid = channelSid; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); - this.wasEdited = wasEdited; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.from = from; - this.body = body; this.index = index; + this.serviceSid = serviceSid; + this.sid = sid; + this.to = to; this.url = url; - } - - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getAttributes() { - return this.attributes; - } - - public final String getServiceSid() { - return this.serviceSid; - } - - public final String getTo() { - return this.to; - } - - public final String getChannelSid() { - return this.channelSid; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final Boolean getWasEdited() { - return this.wasEdited; - } - - public final String getFrom() { - return this.from; - } - - public final String getBody() { - return this.body; - } - - public final Integer getIndex() { - return this.index; - } - - public final URI getUrl() { - return this.url; + this.wasEdited = wasEdited; } @Override @@ -229,60 +217,42 @@ public boolean equals(final Object o) { } Message other = (Message) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(attributes, other.attributes) && - Objects.equals(serviceSid, other.serviceSid) && - Objects.equals(to, other.to) && - Objects.equals(channelSid, other.channelSid) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(wasEdited, other.wasEdited) && - Objects.equals(from, other.from) && - Objects.equals(body, other.body) && - Objects.equals(index, other.index) && - Objects.equals(url, other.url) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(attributes, other.attributes) && + Objects.equals(body, other.body) && + Objects.equals(channelSid, other.channelSid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(from, other.from) && + Objects.equals(index, other.index) && + Objects.equals(serviceSid, other.serviceSid) && + Objects.equals(sid, other.sid) && + Objects.equals(to, other.to) && + Objects.equals(url, other.url) && + Objects.equals(wasEdited, other.wasEdited) ); } @Override public int hashCode() { return Objects.hash( - sid, - accountSid, - attributes, - serviceSid, - to, - channelSid, - dateCreated, - dateUpdated, - wasEdited, - from, - body, - index, - url + accountSid, + attributes, + body, + channelSid, + dateCreated, + dateUpdated, + from, + index, + serviceSid, + sid, + to, + url, + wasEdited ); } - public enum OrderType { - ASC("asc"), - DESC("desc"); - - private final String value; - private OrderType(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static OrderType forValue(final String value) { - return Promoter.enumFromString(value, OrderType.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/chat/v1/service/channel/MessageCreator.java b/src/main/java/com/twilio/rest/chat/v1/service/channel/MessageCreator.java index fa7e750e09..e2dfd505a7 100644 --- a/src/main/java/com/twilio/rest/chat/v1/service/channel/MessageCreator.java +++ b/src/main/java/com/twilio/rest/chat/v1/service/channel/MessageCreator.java @@ -14,8 +14,11 @@ package com.twilio.rest.chat.v1.service.channel; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,76 +30,65 @@ public class MessageCreator extends Creator { - private String pathServiceSid; - private String pathChannelSid; + private String pathserviceSid; + private String pathchannelSid; private String body; private String from; private String attributes; - public MessageCreator( - final String pathServiceSid, - final String pathChannelSid, - final String body - ) { - this.pathServiceSid = pathServiceSid; - this.pathChannelSid = pathChannelSid; + public MessageCreator(final String pathserviceSid, final String pathchannelSid, final String body) { + this.pathserviceSid = pathserviceSid; + this.pathchannelSid = pathchannelSid; this.body = body; } + public MessageCreator setBody(final String body) { this.body = body; return this; } + public MessageCreator setFrom(final String from) { this.from = from; return this; } + public MessageCreator setAttributes(final String attributes) { this.attributes = attributes; return this; } + @Override public Message create(final TwilioRestClient client) { - String path = - "/v1/Services/{ServiceSid}/Channels/{ChannelSid}/Messages"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = - path.replace( - "{" + "ChannelSid" + "}", - this.pathChannelSid.toString() - ); - path = path.replace("{" + "Body" + "}", this.body.toString()); + String path = "/v1/Services/{ServiceSid}/Channels/{ChannelSid}/Messages"; + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "ChannelSid" + "}", this.pathchannelSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.CHAT.toString(), - path + HttpMethod.POST, + Domains.CHAT.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Message creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("Message creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -105,14 +97,21 @@ public Message create(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (body != null) { - request.addPostParam("Body", body); + Serializer.toString(request, "Body", body, ParameterType.URLENCODED); } + + if (from != null) { - request.addPostParam("From", from); + Serializer.toString(request, "From", from, ParameterType.URLENCODED); } + + if (attributes != null) { - request.addPostParam("Attributes", attributes); + Serializer.toString(request, "Attributes", attributes, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/chat/v1/service/channel/MessageDeleter.java b/src/main/java/com/twilio/rest/chat/v1/service/channel/MessageDeleter.java index 5cd37c4b27..f7e771007d 100644 --- a/src/main/java/com/twilio/rest/chat/v1/service/channel/MessageDeleter.java +++ b/src/main/java/com/twilio/rest/chat/v1/service/channel/MessageDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.chat.v1.service.channel; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,59 +26,44 @@ public class MessageDeleter extends Deleter { - private String pathServiceSid; - private String pathChannelSid; - private String pathSid; + private String pathserviceSid; + private String pathchannelSid; + private String pathsid; - public MessageDeleter( - final String pathServiceSid, - final String pathChannelSid, - final String pathSid - ) { - this.pathServiceSid = pathServiceSid; - this.pathChannelSid = pathChannelSid; - this.pathSid = pathSid; + public MessageDeleter(final String pathserviceSid, final String pathchannelSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathchannelSid = pathchannelSid; + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { - String path = - "/v1/Services/{ServiceSid}/Channels/{ChannelSid}/Messages/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = - path.replace( - "{" + "ChannelSid" + "}", - this.pathChannelSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/v1/Services/{ServiceSid}/Channels/{ChannelSid}/Messages/{Sid}"; + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "ChannelSid" + "}", this.pathchannelSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.CHAT.toString(), - path + HttpMethod.DELETE, + Domains.CHAT.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Message delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("Message delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/chat/v1/service/channel/MessageFetcher.java b/src/main/java/com/twilio/rest/chat/v1/service/channel/MessageFetcher.java index 12fae22cf3..cd78cbbc3d 100644 --- a/src/main/java/com/twilio/rest/chat/v1/service/channel/MessageFetcher.java +++ b/src/main/java/com/twilio/rest/chat/v1/service/channel/MessageFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.chat.v1.service.channel; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,63 +26,47 @@ public class MessageFetcher extends Fetcher { - private String pathServiceSid; - private String pathChannelSid; - private String pathSid; + private String pathserviceSid; + private String pathchannelSid; + private String pathsid; - public MessageFetcher( - final String pathServiceSid, - final String pathChannelSid, - final String pathSid - ) { - this.pathServiceSid = pathServiceSid; - this.pathChannelSid = pathChannelSid; - this.pathSid = pathSid; + public MessageFetcher(final String pathserviceSid, final String pathchannelSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathchannelSid = pathchannelSid; + this.pathsid = pathsid; } + @Override public Message fetch(final TwilioRestClient client) { - String path = - "/v1/Services/{ServiceSid}/Channels/{ChannelSid}/Messages/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = - path.replace( - "{" + "ChannelSid" + "}", - this.pathChannelSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/v1/Services/{ServiceSid}/Channels/{ChannelSid}/Messages/{Sid}"; + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "ChannelSid" + "}", this.pathchannelSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.CHAT.toString(), - path + HttpMethod.GET, + Domains.CHAT.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Message fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Message fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Message.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/chat/v1/service/channel/MessageReader.java b/src/main/java/com/twilio/rest/chat/v1/service/channel/MessageReader.java index 7bcb10256e..f6e01cc7f7 100644 --- a/src/main/java/com/twilio/rest/chat/v1/service/channel/MessageReader.java +++ b/src/main/java/com/twilio/rest/chat/v1/service/channel/MessageReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,135 +30,103 @@ public class MessageReader extends Reader { - private String pathServiceSid; - private String pathChannelSid; + private String pathserviceSid; + private String pathchannelSid; private Message.OrderType order; private Long pageSize; - public MessageReader( - final String pathServiceSid, - final String pathChannelSid - ) { - this.pathServiceSid = pathServiceSid; - this.pathChannelSid = pathChannelSid; + public MessageReader(final String pathserviceSid, final String pathchannelSid) { + this.pathserviceSid = pathserviceSid; + this.pathchannelSid = pathchannelSid; } + public MessageReader setOrder(final Message.OrderType order) { this.order = order; return this; } + public MessageReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { - String path = - "/v1/Services/{ServiceSid}/Channels/{ChannelSid}/Messages"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = - path.replace( - "{" + "ChannelSid" + "}", - this.pathChannelSid.toString() - ); + + String path = "/v1/Services/{ServiceSid}/Channels/{ChannelSid}/Messages"; + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "ChannelSid" + "}", this.pathchannelSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.CHAT.toString(), - path + HttpMethod.GET, + Domains.CHAT.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Message read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Message read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "messages", - response.getContent(), - Message.class, - client.getObjectMapper() - ); + "messages", + response.getContent(), + Message.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.CHAT.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.CHAT.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (order != null) { - request.addQueryParam("Order", order.toString()); + Serializer.toString(request, "Order", order, ParameterType.QUERY); } + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/chat/v1/service/channel/MessageUpdater.java b/src/main/java/com/twilio/rest/chat/v1/service/channel/MessageUpdater.java index 242dc7a274..19bf998efa 100644 --- a/src/main/java/com/twilio/rest/chat/v1/service/channel/MessageUpdater.java +++ b/src/main/java/com/twilio/rest/chat/v1/service/channel/MessageUpdater.java @@ -16,6 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -26,72 +28,60 @@ import com.twilio.rest.Domains; public class MessageUpdater extends Updater { - - private String pathServiceSid; - private String pathChannelSid; - private String pathSid; + private String pathserviceSid; + private String pathchannelSid; + private String pathsid; private String body; private String attributes; - public MessageUpdater( - final String pathServiceSid, - final String pathChannelSid, - final String pathSid - ) { - this.pathServiceSid = pathServiceSid; - this.pathChannelSid = pathChannelSid; - this.pathSid = pathSid; + public MessageUpdater(final String pathserviceSid, final String pathchannelSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathchannelSid = pathchannelSid; + this.pathsid = pathsid; } + public MessageUpdater setBody(final String body) { this.body = body; return this; } + public MessageUpdater setAttributes(final String attributes) { this.attributes = attributes; return this; } + @Override public Message update(final TwilioRestClient client) { - String path = - "/v1/Services/{ServiceSid}/Channels/{ChannelSid}/Messages/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = - path.replace( - "{" + "ChannelSid" + "}", - this.pathChannelSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/v1/Services/{ServiceSid}/Channels/{ChannelSid}/Messages/{Sid}"; + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "ChannelSid" + "}", this.pathchannelSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.CHAT.toString(), - path + HttpMethod.POST, + Domains.CHAT.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Message update failed: Unable to connect to server" - ); + throw new ApiConnectionException("Message update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -100,11 +90,16 @@ public Message update(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (body != null) { - request.addPostParam("Body", body); + Serializer.toString(request, "Body", body, ParameterType.URLENCODED); } + + if (attributes != null) { - request.addPostParam("Attributes", attributes); + Serializer.toString(request, "Attributes", attributes, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/chat/v1/service/user/UserChannel.java b/src/main/java/com/twilio/rest/chat/v1/service/user/UserChannel.java index 245f4d1b5d..c786d777f9 100644 --- a/src/main/java/com/twilio/rest/chat/v1/service/user/UserChannel.java +++ b/src/main/java/com/twilio/rest/chat/v1/service/user/UserChannel.java @@ -18,44 +18,63 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class UserChannel extends Resource { - private static final long serialVersionUID = 5311313114138L; - public static UserChannelReader reader( - final String pathServiceSid, - final String pathUserSid - ) { - return new UserChannelReader(pathServiceSid, pathUserSid); + public static UserChannelReader reader(final String pathserviceSid, final String pathuserSid) { + return new UserChannelReader( + pathserviceSid, pathuserSid + ); + } + + + public enum ChannelStatus { + JOINED("joined"), + INVITED("invited"), + NOT_PARTICIPATING("not_participating"); + + private final String value; + + private ChannelStatus(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static ChannelStatus forValue(final String value) { + return Promoter.enumFromString(value, ChannelStatus.values()); + } } + /** * Converts a JSON String into a UserChannel object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return UserChannel object represented by the provided JSON */ - public static UserChannel fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static UserChannel fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, UserChannel.class); @@ -70,14 +89,11 @@ public static UserChannel fromJson( * Converts a JSON InputStream into a UserChannel object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return UserChannel object represented by the provided JSON */ - public static UserChannel fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static UserChannel fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, UserChannel.class); @@ -88,70 +104,55 @@ public static UserChannel fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String serviceSid; + @Getter private final String channelSid; + @Getter + private final Integer lastConsumedMessageIndex; + @Getter + private final Map links; + @Getter private final String memberSid; + @Getter + private final String serviceSid; + @Getter private final UserChannel.ChannelStatus status; - private final Integer lastConsumedMessageIndex; + @Getter private final Integer unreadMessagesCount; - private final Map links; @JsonCreator private UserChannel( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("service_sid") final String serviceSid, - @JsonProperty("channel_sid") final String channelSid, - @JsonProperty("member_sid") final String memberSid, - @JsonProperty("status") final UserChannel.ChannelStatus status, - @JsonProperty( - "last_consumed_message_index" - ) final Integer lastConsumedMessageIndex, - @JsonProperty( - "unread_messages_count" - ) final Integer unreadMessagesCount, - @JsonProperty("links") final Map links + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("channel_sid") final String channelSid, + @JsonProperty("last_consumed_message_index") final Integer lastConsumedMessageIndex, + @JsonProperty("links") final Map links, + @JsonProperty("member_sid") final String memberSid, + @JsonProperty("service_sid") final String serviceSid, + @JsonProperty("status") final UserChannel.ChannelStatus status, + @JsonProperty("unread_messages_count") final Integer unreadMessagesCount ) { this.accountSid = accountSid; - this.serviceSid = serviceSid; this.channelSid = channelSid; + this.lastConsumedMessageIndex = lastConsumedMessageIndex; + this.links = links; this.memberSid = memberSid; + this.serviceSid = serviceSid; this.status = status; - this.lastConsumedMessageIndex = lastConsumedMessageIndex; this.unreadMessagesCount = unreadMessagesCount; - this.links = links; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getServiceSid() { - return this.serviceSid; - } - - public final String getChannelSid() { - return this.channelSid; - } - - public final String getMemberSid() { - return this.memberSid; - } - - public final UserChannel.ChannelStatus getStatus() { - return this.status; - } - - public final Integer getLastConsumedMessageIndex() { - return this.lastConsumedMessageIndex; - } - - public final Integer getUnreadMessagesCount() { - return this.unreadMessagesCount; - } - - public final Map getLinks() { - return this.links; } @Override @@ -165,54 +166,32 @@ public boolean equals(final Object o) { } UserChannel other = (UserChannel) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(serviceSid, other.serviceSid) && - Objects.equals(channelSid, other.channelSid) && - Objects.equals(memberSid, other.memberSid) && - Objects.equals(status, other.status) && - Objects.equals( - lastConsumedMessageIndex, - other.lastConsumedMessageIndex - ) && - Objects.equals(unreadMessagesCount, other.unreadMessagesCount) && - Objects.equals(links, other.links) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(channelSid, other.channelSid) && + Objects.equals(lastConsumedMessageIndex, other.lastConsumedMessageIndex) && + Objects.equals(links, other.links) && + Objects.equals(memberSid, other.memberSid) && + Objects.equals(serviceSid, other.serviceSid) && + Objects.equals(status, other.status) && + Objects.equals(unreadMessagesCount, other.unreadMessagesCount) ); } @Override public int hashCode() { return Objects.hash( - accountSid, - serviceSid, - channelSid, - memberSid, - status, - lastConsumedMessageIndex, - unreadMessagesCount, - links + accountSid, + channelSid, + lastConsumedMessageIndex, + links, + memberSid, + serviceSid, + status, + unreadMessagesCount ); } - public enum ChannelStatus { - JOINED("joined"), - INVITED("invited"), - NOT_PARTICIPATING("not_participating"); - - private final String value; - private ChannelStatus(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static ChannelStatus forValue(final String value) { - return Promoter.enumFromString(value, ChannelStatus.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/chat/v1/service/user/UserChannelReader.java b/src/main/java/com/twilio/rest/chat/v1/service/user/UserChannelReader.java index 58f12651a2..bd8b31814e 100644 --- a/src/main/java/com/twilio/rest/chat/v1/service/user/UserChannelReader.java +++ b/src/main/java/com/twilio/rest/chat/v1/service/user/UserChannelReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,121 +30,91 @@ public class UserChannelReader extends Reader { - private String pathServiceSid; - private String pathUserSid; + private String pathserviceSid; + private String pathuserSid; private Long pageSize; - public UserChannelReader( - final String pathServiceSid, - final String pathUserSid - ) { - this.pathServiceSid = pathServiceSid; - this.pathUserSid = pathUserSid; + public UserChannelReader(final String pathserviceSid, final String pathuserSid) { + this.pathserviceSid = pathserviceSid; + this.pathuserSid = pathuserSid; } + public UserChannelReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/Services/{ServiceSid}/Users/{UserSid}/Channels"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = path.replace("{" + "UserSid" + "}", this.pathUserSid.toString()); + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "UserSid" + "}", this.pathuserSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.CHAT.toString(), - path + HttpMethod.GET, + Domains.CHAT.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "UserChannel read failed: Unable to connect to server" - ); + throw new ApiConnectionException("UserChannel read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "channels", - response.getContent(), - UserChannel.class, - client.getObjectMapper() - ); + "channels", + response.getContent(), + UserChannel.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.CHAT.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.CHAT.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/chat/v2/Credential.java b/src/main/java/com/twilio/rest/chat/v2/Credential.java index b02f30cb1e..3f80eb0c4a 100644 --- a/src/main/java/com/twilio/rest/chat/v2/Credential.java +++ b/src/main/java/com/twilio/rest/chat/v2/Credential.java @@ -18,58 +18,93 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Credential extends Resource { - private static final long serialVersionUID = 161183169234848L; public static CredentialCreator creator(final Credential.PushService type) { - return new CredentialCreator(type); + return new CredentialCreator( + type + ); } - public static CredentialDeleter deleter(final String pathSid) { - return new CredentialDeleter(pathSid); + + public static CredentialDeleter deleter(final String pathsid) { + return new CredentialDeleter( + pathsid + ); } - public static CredentialFetcher fetcher(final String pathSid) { - return new CredentialFetcher(pathSid); + + public static CredentialFetcher fetcher(final String pathsid) { + return new CredentialFetcher( + pathsid + ); } + public static CredentialReader reader() { - return new CredentialReader(); + return new CredentialReader( + + ); } - public static CredentialUpdater updater(final String pathSid) { - return new CredentialUpdater(pathSid); + + public static CredentialUpdater updater(final String pathsid) { + return new CredentialUpdater( + pathsid + ); } + + public enum PushService { + GCM("gcm"), + APN("apn"), + FCM("fcm"); + + private final String value; + + private PushService(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static PushService forValue(final String value) { + return Promoter.enumFromString(value, PushService.values()); + } + } + + /** * Converts a JSON String into a Credential object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Credential object represented by the provided JSON */ - public static Credential fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Credential fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Credential.class); @@ -84,14 +119,11 @@ public static Credential fromJson( * Converts a JSON InputStream into a Credential object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Credential object represented by the provided JSON */ - public static Credential fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Credential fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Credential.class); @@ -102,68 +134,59 @@ public static Credential fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String friendlyName; - private final Credential.PushService type; - private final String sandbox; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; + @Getter + private final String friendlyName; + @Getter + private final String sandbox; + @Getter + private final String sid; + @Getter + private final Credential.PushService type; + @Getter private final URI url; @JsonCreator private Credential( - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("type") final Credential.PushService type, - @JsonProperty("sandbox") final String sandbox, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("url") final URI url + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("sandbox") final String sandbox, + @JsonProperty("sid") final String sid, + @JsonProperty("type") final Credential.PushService type, + @JsonProperty("url") final URI url ) { - this.sid = sid; this.accountSid = accountSid; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.friendlyName = friendlyName; - this.type = type; this.sandbox = sandbox; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); + this.sid = sid; + this.type = type; this.url = url; } - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final Credential.PushService getType() { - return this.type; - } - - public final String getSandbox() { - return this.sandbox; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final URI getUrl() { - return this.url; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -175,51 +198,32 @@ public boolean equals(final Object o) { } Credential other = (Credential) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(type, other.type) && - Objects.equals(sandbox, other.sandbox) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(url, other.url) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(sandbox, other.sandbox) && + Objects.equals(sid, other.sid) && + Objects.equals(type, other.type) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - sid, - accountSid, - friendlyName, - type, - sandbox, - dateCreated, - dateUpdated, - url + accountSid, + dateCreated, + dateUpdated, + friendlyName, + sandbox, + sid, + type, + url ); } - public enum PushService { - GCM("gcm"), - APN("apn"), - FCM("fcm"); - - private final String value; - - private PushService(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - @JsonCreator - public static PushService forValue(final String value) { - return Promoter.enumFromString(value, PushService.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/chat/v2/CredentialCreator.java b/src/main/java/com/twilio/rest/chat/v2/CredentialCreator.java index 849a78ed32..7a103c06a5 100644 --- a/src/main/java/com/twilio/rest/chat/v2/CredentialCreator.java +++ b/src/main/java/com/twilio/rest/chat/v2/CredentialCreator.java @@ -14,8 +14,11 @@ package com.twilio.rest.chat.v2; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -39,100 +42,117 @@ public CredentialCreator(final Credential.PushService type) { this.type = type; } + public CredentialCreator setType(final Credential.PushService type) { this.type = type; return this; } + public CredentialCreator setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + public CredentialCreator setCertificate(final String certificate) { this.certificate = certificate; return this; } + public CredentialCreator setPrivateKey(final String privateKey) { this.privateKey = privateKey; return this; } + public CredentialCreator setSandbox(final Boolean sandbox) { this.sandbox = sandbox; return this; } + public CredentialCreator setApiKey(final String apiKey) { this.apiKey = apiKey; return this; } + public CredentialCreator setSecret(final String secret) { this.secret = secret; return this; } + @Override public Credential create(final TwilioRestClient client) { + String path = "/v2/Credentials"; - path = path.replace("{" + "Type" + "}", this.type.toString()); Request request = new Request( - HttpMethod.POST, - Domains.CHAT.toString(), - path + HttpMethod.POST, + Domains.CHAT.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Credential creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("Credential creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Credential.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Credential.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (type != null) { - request.addPostParam("Type", type.toString()); + Serializer.toString(request, "Type", type, ParameterType.URLENCODED); } + + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + if (certificate != null) { - request.addPostParam("Certificate", certificate); + Serializer.toString(request, "Certificate", certificate, ParameterType.URLENCODED); } + + if (privateKey != null) { - request.addPostParam("PrivateKey", privateKey); + Serializer.toString(request, "PrivateKey", privateKey, ParameterType.URLENCODED); } + + if (sandbox != null) { - request.addPostParam("Sandbox", sandbox.toString()); + Serializer.toString(request, "Sandbox", sandbox, ParameterType.URLENCODED); } + + if (apiKey != null) { - request.addPostParam("ApiKey", apiKey); + Serializer.toString(request, "ApiKey", apiKey, ParameterType.URLENCODED); } + + if (secret != null) { - request.addPostParam("Secret", secret); + Serializer.toString(request, "Secret", secret, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/chat/v2/CredentialDeleter.java b/src/main/java/com/twilio/rest/chat/v2/CredentialDeleter.java index be06a4dbe9..6193a1c267 100644 --- a/src/main/java/com/twilio/rest/chat/v2/CredentialDeleter.java +++ b/src/main/java/com/twilio/rest/chat/v2/CredentialDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.chat.v2; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,40 +26,38 @@ public class CredentialDeleter extends Deleter { - private String pathSid; + private String pathsid; - public CredentialDeleter(final String pathSid) { - this.pathSid = pathSid; + public CredentialDeleter(final String pathsid) { + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/v2/Credentials/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.CHAT.toString(), - path + HttpMethod.DELETE, + Domains.CHAT.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Credential delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("Credential delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/chat/v2/CredentialFetcher.java b/src/main/java/com/twilio/rest/chat/v2/CredentialFetcher.java index d9a57d7acb..5254e87e7b 100644 --- a/src/main/java/com/twilio/rest/chat/v2/CredentialFetcher.java +++ b/src/main/java/com/twilio/rest/chat/v2/CredentialFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.chat.v2; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,47 +26,41 @@ public class CredentialFetcher extends Fetcher { - private String pathSid; + private String pathsid; - public CredentialFetcher(final String pathSid) { - this.pathSid = pathSid; + public CredentialFetcher(final String pathsid) { + this.pathsid = pathsid; } + @Override public Credential fetch(final TwilioRestClient client) { + String path = "/v2/Credentials/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.CHAT.toString(), - path + HttpMethod.GET, + Domains.CHAT.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Credential fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Credential fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return Credential.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Credential.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/chat/v2/CredentialReader.java b/src/main/java/com/twilio/rest/chat/v2/CredentialReader.java index dd14f66cfe..7821e560e1 100644 --- a/src/main/java/com/twilio/rest/chat/v2/CredentialReader.java +++ b/src/main/java/com/twilio/rest/chat/v2/CredentialReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -31,105 +32,83 @@ public class CredentialReader extends Reader { private Long pageSize; - public CredentialReader() {} + public CredentialReader() { + } + public CredentialReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v2/Credentials"; + Request request = new Request( - HttpMethod.GET, - Domains.CHAT.toString(), - path + HttpMethod.GET, + Domains.CHAT.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Credential read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Credential read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "credentials", - response.getContent(), - Credential.class, - client.getObjectMapper() - ); + "credentials", + response.getContent(), + Credential.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.CHAT.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.CHAT.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/chat/v2/CredentialUpdater.java b/src/main/java/com/twilio/rest/chat/v2/CredentialUpdater.java index 4a6e7069a5..5771833221 100644 --- a/src/main/java/com/twilio/rest/chat/v2/CredentialUpdater.java +++ b/src/main/java/com/twilio/rest/chat/v2/CredentialUpdater.java @@ -16,6 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -26,8 +28,7 @@ import com.twilio.rest.Domains; public class CredentialUpdater extends Updater { - - private String pathSid; + private String pathsid; private String friendlyName; private String certificate; private String privateKey; @@ -35,96 +36,112 @@ public class CredentialUpdater extends Updater { private String apiKey; private String secret; - public CredentialUpdater(final String pathSid) { - this.pathSid = pathSid; + public CredentialUpdater(final String pathsid) { + this.pathsid = pathsid; } + public CredentialUpdater setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + public CredentialUpdater setCertificate(final String certificate) { this.certificate = certificate; return this; } + public CredentialUpdater setPrivateKey(final String privateKey) { this.privateKey = privateKey; return this; } + public CredentialUpdater setSandbox(final Boolean sandbox) { this.sandbox = sandbox; return this; } + public CredentialUpdater setApiKey(final String apiKey) { this.apiKey = apiKey; return this; } + public CredentialUpdater setSecret(final String secret) { this.secret = secret; return this; } + @Override public Credential update(final TwilioRestClient client) { + String path = "/v2/Credentials/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.CHAT.toString(), - path + HttpMethod.POST, + Domains.CHAT.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Credential update failed: Unable to connect to server" - ); + throw new ApiConnectionException("Credential update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Credential.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Credential.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + if (certificate != null) { - request.addPostParam("Certificate", certificate); + Serializer.toString(request, "Certificate", certificate, ParameterType.URLENCODED); } + + if (privateKey != null) { - request.addPostParam("PrivateKey", privateKey); + Serializer.toString(request, "PrivateKey", privateKey, ParameterType.URLENCODED); } + + if (sandbox != null) { - request.addPostParam("Sandbox", sandbox.toString()); + Serializer.toString(request, "Sandbox", sandbox, ParameterType.URLENCODED); } + + if (apiKey != null) { - request.addPostParam("ApiKey", apiKey); + Serializer.toString(request, "ApiKey", apiKey, ParameterType.URLENCODED); } + + if (secret != null) { - request.addPostParam("Secret", secret); + Serializer.toString(request, "Secret", secret, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/chat/v2/Service.java b/src/main/java/com/twilio/rest/chat/v2/Service.java index f68a619f27..7c4dae00d9 100644 --- a/src/main/java/com/twilio/rest/chat/v2/Service.java +++ b/src/main/java/com/twilio/rest/chat/v2/Service.java @@ -18,60 +18,72 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.List; import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Service extends Resource { - private static final long serialVersionUID = 187047184630676L; public static ServiceCreator creator(final String friendlyName) { - return new ServiceCreator(friendlyName); + return new ServiceCreator( + friendlyName + ); } - public static ServiceDeleter deleter(final String pathSid) { - return new ServiceDeleter(pathSid); + + public static ServiceDeleter deleter(final String pathsid) { + return new ServiceDeleter( + pathsid + ); } - public static ServiceFetcher fetcher(final String pathSid) { - return new ServiceFetcher(pathSid); + + public static ServiceFetcher fetcher(final String pathsid) { + return new ServiceFetcher( + pathsid + ); } + public static ServiceReader reader() { - return new ServiceReader(); + return new ServiceReader( + + ); } - public static ServiceUpdater updater(final String pathSid) { - return new ServiceUpdater(pathSid); + + public static ServiceUpdater updater(final String pathsid) { + return new ServiceUpdater( + pathsid + ); } + /** * Converts a JSON String into a Service object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Service object represented by the provided JSON */ - public static Service fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Service fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Service.class); @@ -86,14 +98,11 @@ public static Service fromJson( * Converts a JSON InputStream into a Service object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Service object represented by the provided JSON */ - public static Service fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Service fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Service.class); @@ -104,185 +113,117 @@ public static Service fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String friendlyName; + @Getter + private final Integer consumptionReportInterval; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; - private final String defaultServiceRoleSid; - private final String defaultChannelRoleSid; + @Getter private final String defaultChannelCreatorRoleSid; - private final Boolean readStatusEnabled; - private final Boolean reachabilityEnabled; - private final Integer typingIndicatorTimeout; - private final Integer consumptionReportInterval; - private final Map limits; - private final String preWebhookUrl; + @Getter + private final String defaultChannelRoleSid; + @Getter + private final String defaultServiceRoleSid; + @Getter + private final String friendlyName; + @Getter + private final Object limits; + @Getter + private final Map links; + @Getter + private final Object media; + @Getter + private final Object notifications; + @Getter + private final Integer postWebhookRetryCount; + @Getter private final String postWebhookUrl; - private final String webhookMethod; - private final List webhookFilters; + @Getter private final Integer preWebhookRetryCount; - private final Integer postWebhookRetryCount; - private final Map notifications; - private final Map media; + @Getter + private final String preWebhookUrl; + @Getter + private final Boolean reachabilityEnabled; + @Getter + private final Boolean readStatusEnabled; + @Getter + private final String sid; + @Getter + private final Integer typingIndicatorTimeout; + @Getter private final URI url; - private final Map links; + @Getter + private final List webhookFilters; + @Getter + private final String webhookMethod; @JsonCreator private Service( - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty( - "default_service_role_sid" - ) final String defaultServiceRoleSid, - @JsonProperty( - "default_channel_role_sid" - ) final String defaultChannelRoleSid, - @JsonProperty( - "default_channel_creator_role_sid" - ) final String defaultChannelCreatorRoleSid, - @JsonProperty("read_status_enabled") final Boolean readStatusEnabled, - @JsonProperty("reachability_enabled") final Boolean reachabilityEnabled, - @JsonProperty( - "typing_indicator_timeout" - ) final Integer typingIndicatorTimeout, - @JsonProperty( - "consumption_report_interval" - ) final Integer consumptionReportInterval, - @JsonProperty("limits") final Map limits, - @JsonProperty("pre_webhook_url") final String preWebhookUrl, - @JsonProperty("post_webhook_url") final String postWebhookUrl, - @JsonProperty("webhook_method") final String webhookMethod, - @JsonProperty("webhook_filters") final List webhookFilters, - @JsonProperty( - "pre_webhook_retry_count" - ) final Integer preWebhookRetryCount, - @JsonProperty( - "post_webhook_retry_count" - ) final Integer postWebhookRetryCount, - @JsonProperty("notifications") final Map notifications, - @JsonProperty("media") final Map media, - @JsonProperty("url") final URI url, - @JsonProperty("links") final Map links + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("consumption_report_interval") final Integer consumptionReportInterval, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("default_channel_creator_role_sid") final String defaultChannelCreatorRoleSid, + @JsonProperty("default_channel_role_sid") final String defaultChannelRoleSid, + @JsonProperty("default_service_role_sid") final String defaultServiceRoleSid, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("limits") final Object limits, + @JsonProperty("links") final Map links, + @JsonProperty("media") final Object media, + @JsonProperty("notifications") final Object notifications, + @JsonProperty("post_webhook_retry_count") final Integer postWebhookRetryCount, + @JsonProperty("post_webhook_url") final String postWebhookUrl, + @JsonProperty("pre_webhook_retry_count") final Integer preWebhookRetryCount, + @JsonProperty("pre_webhook_url") final String preWebhookUrl, + @JsonProperty("reachability_enabled") final Boolean reachabilityEnabled, + @JsonProperty("read_status_enabled") final Boolean readStatusEnabled, + @JsonProperty("sid") final String sid, + @JsonProperty("typing_indicator_timeout") final Integer typingIndicatorTimeout, + @JsonProperty("url") final URI url, + @JsonProperty("webhook_filters") final List webhookFilters, + @JsonProperty("webhook_method") final String webhookMethod ) { - this.sid = sid; this.accountSid = accountSid; - this.friendlyName = friendlyName; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); - this.defaultServiceRoleSid = defaultServiceRoleSid; - this.defaultChannelRoleSid = defaultChannelRoleSid; - this.defaultChannelCreatorRoleSid = defaultChannelCreatorRoleSid; - this.readStatusEnabled = readStatusEnabled; - this.reachabilityEnabled = reachabilityEnabled; - this.typingIndicatorTimeout = typingIndicatorTimeout; this.consumptionReportInterval = consumptionReportInterval; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; + this.defaultChannelCreatorRoleSid = defaultChannelCreatorRoleSid; + this.defaultChannelRoleSid = defaultChannelRoleSid; + this.defaultServiceRoleSid = defaultServiceRoleSid; + this.friendlyName = friendlyName; this.limits = limits; - this.preWebhookUrl = preWebhookUrl; + this.links = links; + this.media = media; + this.notifications = notifications; + this.postWebhookRetryCount = postWebhookRetryCount; this.postWebhookUrl = postWebhookUrl; - this.webhookMethod = webhookMethod; - this.webhookFilters = webhookFilters; this.preWebhookRetryCount = preWebhookRetryCount; - this.postWebhookRetryCount = postWebhookRetryCount; - this.notifications = notifications; - this.media = media; + this.preWebhookUrl = preWebhookUrl; + this.reachabilityEnabled = reachabilityEnabled; + this.readStatusEnabled = readStatusEnabled; + this.sid = sid; + this.typingIndicatorTimeout = typingIndicatorTimeout; this.url = url; - this.links = links; - } - - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final String getDefaultServiceRoleSid() { - return this.defaultServiceRoleSid; - } - - public final String getDefaultChannelRoleSid() { - return this.defaultChannelRoleSid; - } - - public final String getDefaultChannelCreatorRoleSid() { - return this.defaultChannelCreatorRoleSid; - } - - public final Boolean getReadStatusEnabled() { - return this.readStatusEnabled; - } - - public final Boolean getReachabilityEnabled() { - return this.reachabilityEnabled; - } - - public final Integer getTypingIndicatorTimeout() { - return this.typingIndicatorTimeout; - } - - public final Integer getConsumptionReportInterval() { - return this.consumptionReportInterval; - } - - public final Map getLimits() { - return this.limits; - } - - public final String getPreWebhookUrl() { - return this.preWebhookUrl; - } - - public final String getPostWebhookUrl() { - return this.postWebhookUrl; - } - - public final String getWebhookMethod() { - return this.webhookMethod; - } - - public final List getWebhookFilters() { - return this.webhookFilters; - } - - public final Integer getPreWebhookRetryCount() { - return this.preWebhookRetryCount; - } - - public final Integer getPostWebhookRetryCount() { - return this.postWebhookRetryCount; - } - - public final Map getNotifications() { - return this.notifications; - } - - public final Map getMedia() { - return this.media; - } - - public final URI getUrl() { - return this.url; - } - - public final Map getLinks() { - return this.links; + this.webhookFilters = webhookFilters; + this.webhookMethod = webhookMethod; } @Override @@ -296,78 +237,62 @@ public boolean equals(final Object o) { } Service other = (Service) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals( - defaultServiceRoleSid, - other.defaultServiceRoleSid - ) && - Objects.equals( - defaultChannelRoleSid, - other.defaultChannelRoleSid - ) && - Objects.equals( - defaultChannelCreatorRoleSid, - other.defaultChannelCreatorRoleSid - ) && - Objects.equals(readStatusEnabled, other.readStatusEnabled) && - Objects.equals(reachabilityEnabled, other.reachabilityEnabled) && - Objects.equals( - typingIndicatorTimeout, - other.typingIndicatorTimeout - ) && - Objects.equals( - consumptionReportInterval, - other.consumptionReportInterval - ) && - Objects.equals(limits, other.limits) && - Objects.equals(preWebhookUrl, other.preWebhookUrl) && - Objects.equals(postWebhookUrl, other.postWebhookUrl) && - Objects.equals(webhookMethod, other.webhookMethod) && - Objects.equals(webhookFilters, other.webhookFilters) && - Objects.equals(preWebhookRetryCount, other.preWebhookRetryCount) && - Objects.equals( - postWebhookRetryCount, - other.postWebhookRetryCount - ) && - Objects.equals(notifications, other.notifications) && - Objects.equals(media, other.media) && - Objects.equals(url, other.url) && - Objects.equals(links, other.links) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(consumptionReportInterval, other.consumptionReportInterval) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(defaultChannelCreatorRoleSid, other.defaultChannelCreatorRoleSid) && + Objects.equals(defaultChannelRoleSid, other.defaultChannelRoleSid) && + Objects.equals(defaultServiceRoleSid, other.defaultServiceRoleSid) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(limits, other.limits) && + Objects.equals(links, other.links) && + Objects.equals(media, other.media) && + Objects.equals(notifications, other.notifications) && + Objects.equals(postWebhookRetryCount, other.postWebhookRetryCount) && + Objects.equals(postWebhookUrl, other.postWebhookUrl) && + Objects.equals(preWebhookRetryCount, other.preWebhookRetryCount) && + Objects.equals(preWebhookUrl, other.preWebhookUrl) && + Objects.equals(reachabilityEnabled, other.reachabilityEnabled) && + Objects.equals(readStatusEnabled, other.readStatusEnabled) && + Objects.equals(sid, other.sid) && + Objects.equals(typingIndicatorTimeout, other.typingIndicatorTimeout) && + Objects.equals(url, other.url) && + Objects.equals(webhookFilters, other.webhookFilters) && + Objects.equals(webhookMethod, other.webhookMethod) ); } @Override public int hashCode() { return Objects.hash( - sid, - accountSid, - friendlyName, - dateCreated, - dateUpdated, - defaultServiceRoleSid, - defaultChannelRoleSid, - defaultChannelCreatorRoleSid, - readStatusEnabled, - reachabilityEnabled, - typingIndicatorTimeout, - consumptionReportInterval, - limits, - preWebhookUrl, - postWebhookUrl, - webhookMethod, - webhookFilters, - preWebhookRetryCount, - postWebhookRetryCount, - notifications, - media, - url, - links + accountSid, + consumptionReportInterval, + dateCreated, + dateUpdated, + defaultChannelCreatorRoleSid, + defaultChannelRoleSid, + defaultServiceRoleSid, + friendlyName, + limits, + links, + media, + notifications, + postWebhookRetryCount, + postWebhookUrl, + preWebhookRetryCount, + preWebhookUrl, + reachabilityEnabled, + readStatusEnabled, + sid, + typingIndicatorTimeout, + url, + webhookFilters, + webhookMethod ); } + + } + diff --git a/src/main/java/com/twilio/rest/chat/v2/ServiceCreator.java b/src/main/java/com/twilio/rest/chat/v2/ServiceCreator.java index dd75927800..b330a41899 100644 --- a/src/main/java/com/twilio/rest/chat/v2/ServiceCreator.java +++ b/src/main/java/com/twilio/rest/chat/v2/ServiceCreator.java @@ -14,8 +14,11 @@ package com.twilio.rest.chat.v2; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -33,43 +36,38 @@ public ServiceCreator(final String friendlyName) { this.friendlyName = friendlyName; } + public ServiceCreator setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + @Override public Service create(final TwilioRestClient client) { + String path = "/v2/Services"; - path = - path.replace( - "{" + "FriendlyName" + "}", - this.friendlyName.toString() - ); Request request = new Request( - HttpMethod.POST, - Domains.CHAT.toString(), - path + HttpMethod.POST, + Domains.CHAT.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Service creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("Service creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -78,8 +76,11 @@ public Service create(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/chat/v2/ServiceDeleter.java b/src/main/java/com/twilio/rest/chat/v2/ServiceDeleter.java index 6112728346..04df255e33 100644 --- a/src/main/java/com/twilio/rest/chat/v2/ServiceDeleter.java +++ b/src/main/java/com/twilio/rest/chat/v2/ServiceDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.chat.v2; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,40 +26,38 @@ public class ServiceDeleter extends Deleter { - private String pathSid; + private String pathsid; - public ServiceDeleter(final String pathSid) { - this.pathSid = pathSid; + public ServiceDeleter(final String pathsid) { + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/v2/Services/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.CHAT.toString(), - path + HttpMethod.DELETE, + Domains.CHAT.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Service delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("Service delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/chat/v2/ServiceFetcher.java b/src/main/java/com/twilio/rest/chat/v2/ServiceFetcher.java index de0479c53f..85012a9f74 100644 --- a/src/main/java/com/twilio/rest/chat/v2/ServiceFetcher.java +++ b/src/main/java/com/twilio/rest/chat/v2/ServiceFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.chat.v2; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,44 +26,41 @@ public class ServiceFetcher extends Fetcher { - private String pathSid; + private String pathsid; - public ServiceFetcher(final String pathSid) { - this.pathSid = pathSid; + public ServiceFetcher(final String pathsid) { + this.pathsid = pathsid; } + @Override public Service fetch(final TwilioRestClient client) { + String path = "/v2/Services/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.CHAT.toString(), - path + HttpMethod.GET, + Domains.CHAT.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Service fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Service fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Service.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/chat/v2/ServiceReader.java b/src/main/java/com/twilio/rest/chat/v2/ServiceReader.java index bf84228ed5..c029499f41 100644 --- a/src/main/java/com/twilio/rest/chat/v2/ServiceReader.java +++ b/src/main/java/com/twilio/rest/chat/v2/ServiceReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -31,105 +32,83 @@ public class ServiceReader extends Reader { private Long pageSize; - public ServiceReader() {} + public ServiceReader() { + } + public ServiceReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v2/Services"; + Request request = new Request( - HttpMethod.GET, - Domains.CHAT.toString(), - path + HttpMethod.GET, + Domains.CHAT.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Service read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Service read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "services", - response.getContent(), - Service.class, - client.getObjectMapper() - ); + "services", + response.getContent(), + Service.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.CHAT.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.CHAT.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/chat/v2/ServiceUpdater.java b/src/main/java/com/twilio/rest/chat/v2/ServiceUpdater.java index 3cc69e2a41..48be3a00a8 100644 --- a/src/main/java/com/twilio/rest/chat/v2/ServiceUpdater.java +++ b/src/main/java/com/twilio/rest/chat/v2/ServiceUpdater.java @@ -16,7 +16,9 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; import com.twilio.converter.Promoter; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,12 +27,12 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.net.URI; import java.util.List; public class ServiceUpdater extends Updater { - - private String pathSid; + private String pathsid; private String friendlyName; private String defaultServiceRoleSid; private String defaultChannelRoleSid; @@ -63,188 +65,155 @@ public class ServiceUpdater extends Updater { private Integer postWebhookRetryCount; private Boolean notificationsLogEnabled; - public ServiceUpdater(final String pathSid) { - this.pathSid = pathSid; + public ServiceUpdater(final String pathsid) { + this.pathsid = pathsid; } + public ServiceUpdater setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } - public ServiceUpdater setDefaultServiceRoleSid( - final String defaultServiceRoleSid - ) { + + public ServiceUpdater setDefaultServiceRoleSid(final String defaultServiceRoleSid) { this.defaultServiceRoleSid = defaultServiceRoleSid; return this; } - public ServiceUpdater setDefaultChannelRoleSid( - final String defaultChannelRoleSid - ) { + + public ServiceUpdater setDefaultChannelRoleSid(final String defaultChannelRoleSid) { this.defaultChannelRoleSid = defaultChannelRoleSid; return this; } - public ServiceUpdater setDefaultChannelCreatorRoleSid( - final String defaultChannelCreatorRoleSid - ) { + + public ServiceUpdater setDefaultChannelCreatorRoleSid(final String defaultChannelCreatorRoleSid) { this.defaultChannelCreatorRoleSid = defaultChannelCreatorRoleSid; return this; } - public ServiceUpdater setReadStatusEnabled( - final Boolean readStatusEnabled - ) { + + public ServiceUpdater setReadStatusEnabled(final Boolean readStatusEnabled) { this.readStatusEnabled = readStatusEnabled; return this; } - public ServiceUpdater setReachabilityEnabled( - final Boolean reachabilityEnabled - ) { + + public ServiceUpdater setReachabilityEnabled(final Boolean reachabilityEnabled) { this.reachabilityEnabled = reachabilityEnabled; return this; } - public ServiceUpdater setTypingIndicatorTimeout( - final Integer typingIndicatorTimeout - ) { + + public ServiceUpdater setTypingIndicatorTimeout(final Integer typingIndicatorTimeout) { this.typingIndicatorTimeout = typingIndicatorTimeout; return this; } - public ServiceUpdater setConsumptionReportInterval( - final Integer consumptionReportInterval - ) { + + public ServiceUpdater setConsumptionReportInterval(final Integer consumptionReportInterval) { this.consumptionReportInterval = consumptionReportInterval; return this; } - public ServiceUpdater setNotificationsNewMessageEnabled( - final Boolean notificationsNewMessageEnabled - ) { + + public ServiceUpdater setNotificationsNewMessageEnabled(final Boolean notificationsNewMessageEnabled) { this.notificationsNewMessageEnabled = notificationsNewMessageEnabled; return this; } - public ServiceUpdater setNotificationsNewMessageTemplate( - final String notificationsNewMessageTemplate - ) { + + public ServiceUpdater setNotificationsNewMessageTemplate(final String notificationsNewMessageTemplate) { this.notificationsNewMessageTemplate = notificationsNewMessageTemplate; return this; } - public ServiceUpdater setNotificationsNewMessageSound( - final String notificationsNewMessageSound - ) { + + public ServiceUpdater setNotificationsNewMessageSound(final String notificationsNewMessageSound) { this.notificationsNewMessageSound = notificationsNewMessageSound; return this; } - public ServiceUpdater setNotificationsNewMessageBadgeCountEnabled( - final Boolean notificationsNewMessageBadgeCountEnabled - ) { - this.notificationsNewMessageBadgeCountEnabled = - notificationsNewMessageBadgeCountEnabled; + + public ServiceUpdater setNotificationsNewMessageBadgeCountEnabled(final Boolean notificationsNewMessageBadgeCountEnabled) { + this.notificationsNewMessageBadgeCountEnabled = notificationsNewMessageBadgeCountEnabled; return this; } - public ServiceUpdater setNotificationsAddedToChannelEnabled( - final Boolean notificationsAddedToChannelEnabled - ) { - this.notificationsAddedToChannelEnabled = - notificationsAddedToChannelEnabled; + + public ServiceUpdater setNotificationsAddedToChannelEnabled(final Boolean notificationsAddedToChannelEnabled) { + this.notificationsAddedToChannelEnabled = notificationsAddedToChannelEnabled; return this; } - public ServiceUpdater setNotificationsAddedToChannelTemplate( - final String notificationsAddedToChannelTemplate - ) { - this.notificationsAddedToChannelTemplate = - notificationsAddedToChannelTemplate; + + public ServiceUpdater setNotificationsAddedToChannelTemplate(final String notificationsAddedToChannelTemplate) { + this.notificationsAddedToChannelTemplate = notificationsAddedToChannelTemplate; return this; } - public ServiceUpdater setNotificationsAddedToChannelSound( - final String notificationsAddedToChannelSound - ) { - this.notificationsAddedToChannelSound = - notificationsAddedToChannelSound; + + public ServiceUpdater setNotificationsAddedToChannelSound(final String notificationsAddedToChannelSound) { + this.notificationsAddedToChannelSound = notificationsAddedToChannelSound; return this; } - public ServiceUpdater setNotificationsRemovedFromChannelEnabled( - final Boolean notificationsRemovedFromChannelEnabled - ) { - this.notificationsRemovedFromChannelEnabled = - notificationsRemovedFromChannelEnabled; + + public ServiceUpdater setNotificationsRemovedFromChannelEnabled(final Boolean notificationsRemovedFromChannelEnabled) { + this.notificationsRemovedFromChannelEnabled = notificationsRemovedFromChannelEnabled; return this; } - public ServiceUpdater setNotificationsRemovedFromChannelTemplate( - final String notificationsRemovedFromChannelTemplate - ) { - this.notificationsRemovedFromChannelTemplate = - notificationsRemovedFromChannelTemplate; + + public ServiceUpdater setNotificationsRemovedFromChannelTemplate(final String notificationsRemovedFromChannelTemplate) { + this.notificationsRemovedFromChannelTemplate = notificationsRemovedFromChannelTemplate; return this; } - public ServiceUpdater setNotificationsRemovedFromChannelSound( - final String notificationsRemovedFromChannelSound - ) { - this.notificationsRemovedFromChannelSound = - notificationsRemovedFromChannelSound; + + public ServiceUpdater setNotificationsRemovedFromChannelSound(final String notificationsRemovedFromChannelSound) { + this.notificationsRemovedFromChannelSound = notificationsRemovedFromChannelSound; return this; } - public ServiceUpdater setNotificationsInvitedToChannelEnabled( - final Boolean notificationsInvitedToChannelEnabled - ) { - this.notificationsInvitedToChannelEnabled = - notificationsInvitedToChannelEnabled; + + public ServiceUpdater setNotificationsInvitedToChannelEnabled(final Boolean notificationsInvitedToChannelEnabled) { + this.notificationsInvitedToChannelEnabled = notificationsInvitedToChannelEnabled; return this; } - public ServiceUpdater setNotificationsInvitedToChannelTemplate( - final String notificationsInvitedToChannelTemplate - ) { - this.notificationsInvitedToChannelTemplate = - notificationsInvitedToChannelTemplate; + + public ServiceUpdater setNotificationsInvitedToChannelTemplate(final String notificationsInvitedToChannelTemplate) { + this.notificationsInvitedToChannelTemplate = notificationsInvitedToChannelTemplate; return this; } - public ServiceUpdater setNotificationsInvitedToChannelSound( - final String notificationsInvitedToChannelSound - ) { - this.notificationsInvitedToChannelSound = - notificationsInvitedToChannelSound; + + public ServiceUpdater setNotificationsInvitedToChannelSound(final String notificationsInvitedToChannelSound) { + this.notificationsInvitedToChannelSound = notificationsInvitedToChannelSound; return this; } + public ServiceUpdater setPreWebhookUrl(final URI preWebhookUrl) { this.preWebhookUrl = preWebhookUrl; return this; } - public ServiceUpdater setPreWebhookUrl(final String preWebhookUrl) { - return setPreWebhookUrl(Promoter.uriFromString(preWebhookUrl)); - } public ServiceUpdater setPostWebhookUrl(final URI postWebhookUrl) { this.postWebhookUrl = postWebhookUrl; return this; } - public ServiceUpdater setPostWebhookUrl(final String postWebhookUrl) { - return setPostWebhookUrl(Promoter.uriFromString(postWebhookUrl)); - } public ServiceUpdater setWebhookMethod(final HttpMethod webhookMethod) { this.webhookMethod = webhookMethod; return this; } + public ServiceUpdater setWebhookFilters(final List webhookFilters) { this.webhookFilters = webhookFilters; return this; @@ -254,76 +223,69 @@ public ServiceUpdater setWebhookFilters(final String webhookFilters) { return setWebhookFilters(Promoter.listOfOne(webhookFilters)); } - public ServiceUpdater setLimitsChannelMembers( - final Integer limitsChannelMembers - ) { + public ServiceUpdater setLimitsChannelMembers(final Integer limitsChannelMembers) { this.limitsChannelMembers = limitsChannelMembers; return this; } - public ServiceUpdater setLimitsUserChannels( - final Integer limitsUserChannels - ) { + + public ServiceUpdater setLimitsUserChannels(final Integer limitsUserChannels) { this.limitsUserChannels = limitsUserChannels; return this; } - public ServiceUpdater setMediaCompatibilityMessage( - final String mediaCompatibilityMessage - ) { + + public ServiceUpdater setMediaCompatibilityMessage(final String mediaCompatibilityMessage) { this.mediaCompatibilityMessage = mediaCompatibilityMessage; return this; } - public ServiceUpdater setPreWebhookRetryCount( - final Integer preWebhookRetryCount - ) { + + public ServiceUpdater setPreWebhookRetryCount(final Integer preWebhookRetryCount) { this.preWebhookRetryCount = preWebhookRetryCount; return this; } - public ServiceUpdater setPostWebhookRetryCount( - final Integer postWebhookRetryCount - ) { + + public ServiceUpdater setPostWebhookRetryCount(final Integer postWebhookRetryCount) { this.postWebhookRetryCount = postWebhookRetryCount; return this; } - public ServiceUpdater setNotificationsLogEnabled( - final Boolean notificationsLogEnabled - ) { + + public ServiceUpdater setNotificationsLogEnabled(final Boolean notificationsLogEnabled) { this.notificationsLogEnabled = notificationsLogEnabled; return this; } + @Override public Service update(final TwilioRestClient client) { + String path = "/v2/Services/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.CHAT.toString(), - path + HttpMethod.POST, + Domains.CHAT.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Service update failed: Unable to connect to server" - ); + throw new ApiConnectionException("Service update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -332,178 +294,163 @@ public Service update(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + if (defaultServiceRoleSid != null) { - request.addPostParam( - "DefaultServiceRoleSid", - defaultServiceRoleSid - ); + Serializer.toString(request, "DefaultServiceRoleSid", defaultServiceRoleSid, ParameterType.URLENCODED); } + + if (defaultChannelRoleSid != null) { - request.addPostParam( - "DefaultChannelRoleSid", - defaultChannelRoleSid - ); + Serializer.toString(request, "DefaultChannelRoleSid", defaultChannelRoleSid, ParameterType.URLENCODED); } + + if (defaultChannelCreatorRoleSid != null) { - request.addPostParam( - "DefaultChannelCreatorRoleSid", - defaultChannelCreatorRoleSid - ); + Serializer.toString(request, "DefaultChannelCreatorRoleSid", defaultChannelCreatorRoleSid, ParameterType.URLENCODED); } + + if (readStatusEnabled != null) { - request.addPostParam( - "ReadStatusEnabled", - readStatusEnabled.toString() - ); + Serializer.toString(request, "ReadStatusEnabled", readStatusEnabled, ParameterType.URLENCODED); } + + if (reachabilityEnabled != null) { - request.addPostParam( - "ReachabilityEnabled", - reachabilityEnabled.toString() - ); + Serializer.toString(request, "ReachabilityEnabled", reachabilityEnabled, ParameterType.URLENCODED); } + + if (typingIndicatorTimeout != null) { - request.addPostParam( - "TypingIndicatorTimeout", - typingIndicatorTimeout.toString() - ); + Serializer.toString(request, "TypingIndicatorTimeout", typingIndicatorTimeout, ParameterType.URLENCODED); } + + if (consumptionReportInterval != null) { - request.addPostParam( - "ConsumptionReportInterval", - consumptionReportInterval.toString() - ); + Serializer.toString(request, "ConsumptionReportInterval", consumptionReportInterval, ParameterType.URLENCODED); } + + if (notificationsNewMessageEnabled != null) { - request.addPostParam( - "Notifications.NewMessage.Enabled", - notificationsNewMessageEnabled.toString() - ); + Serializer.toString(request, "Notifications.NewMessage.Enabled", notificationsNewMessageEnabled, ParameterType.URLENCODED); } + + if (notificationsNewMessageTemplate != null) { - request.addPostParam( - "Notifications.NewMessage.Template", - notificationsNewMessageTemplate - ); + Serializer.toString(request, "Notifications.NewMessage.Template", notificationsNewMessageTemplate, ParameterType.URLENCODED); } + + if (notificationsNewMessageSound != null) { - request.addPostParam( - "Notifications.NewMessage.Sound", - notificationsNewMessageSound - ); + Serializer.toString(request, "Notifications.NewMessage.Sound", notificationsNewMessageSound, ParameterType.URLENCODED); } + + if (notificationsNewMessageBadgeCountEnabled != null) { - request.addPostParam( - "Notifications.NewMessage.BadgeCountEnabled", - notificationsNewMessageBadgeCountEnabled.toString() - ); + Serializer.toString(request, "Notifications.NewMessage.BadgeCountEnabled", notificationsNewMessageBadgeCountEnabled, ParameterType.URLENCODED); } + + if (notificationsAddedToChannelEnabled != null) { - request.addPostParam( - "Notifications.AddedToChannel.Enabled", - notificationsAddedToChannelEnabled.toString() - ); + Serializer.toString(request, "Notifications.AddedToChannel.Enabled", notificationsAddedToChannelEnabled, ParameterType.URLENCODED); } + + if (notificationsAddedToChannelTemplate != null) { - request.addPostParam( - "Notifications.AddedToChannel.Template", - notificationsAddedToChannelTemplate - ); + Serializer.toString(request, "Notifications.AddedToChannel.Template", notificationsAddedToChannelTemplate, ParameterType.URLENCODED); } + + if (notificationsAddedToChannelSound != null) { - request.addPostParam( - "Notifications.AddedToChannel.Sound", - notificationsAddedToChannelSound - ); + Serializer.toString(request, "Notifications.AddedToChannel.Sound", notificationsAddedToChannelSound, ParameterType.URLENCODED); } + + if (notificationsRemovedFromChannelEnabled != null) { - request.addPostParam( - "Notifications.RemovedFromChannel.Enabled", - notificationsRemovedFromChannelEnabled.toString() - ); + Serializer.toString(request, "Notifications.RemovedFromChannel.Enabled", notificationsRemovedFromChannelEnabled, ParameterType.URLENCODED); } + + if (notificationsRemovedFromChannelTemplate != null) { - request.addPostParam( - "Notifications.RemovedFromChannel.Template", - notificationsRemovedFromChannelTemplate - ); + Serializer.toString(request, "Notifications.RemovedFromChannel.Template", notificationsRemovedFromChannelTemplate, ParameterType.URLENCODED); } + + if (notificationsRemovedFromChannelSound != null) { - request.addPostParam( - "Notifications.RemovedFromChannel.Sound", - notificationsRemovedFromChannelSound - ); + Serializer.toString(request, "Notifications.RemovedFromChannel.Sound", notificationsRemovedFromChannelSound, ParameterType.URLENCODED); } + + if (notificationsInvitedToChannelEnabled != null) { - request.addPostParam( - "Notifications.InvitedToChannel.Enabled", - notificationsInvitedToChannelEnabled.toString() - ); + Serializer.toString(request, "Notifications.InvitedToChannel.Enabled", notificationsInvitedToChannelEnabled, ParameterType.URLENCODED); } + + if (notificationsInvitedToChannelTemplate != null) { - request.addPostParam( - "Notifications.InvitedToChannel.Template", - notificationsInvitedToChannelTemplate - ); + Serializer.toString(request, "Notifications.InvitedToChannel.Template", notificationsInvitedToChannelTemplate, ParameterType.URLENCODED); } + + if (notificationsInvitedToChannelSound != null) { - request.addPostParam( - "Notifications.InvitedToChannel.Sound", - notificationsInvitedToChannelSound - ); + Serializer.toString(request, "Notifications.InvitedToChannel.Sound", notificationsInvitedToChannelSound, ParameterType.URLENCODED); } + + if (preWebhookUrl != null) { - request.addPostParam("PreWebhookUrl", preWebhookUrl.toString()); + Serializer.toString(request, "PreWebhookUrl", preWebhookUrl, ParameterType.URLENCODED); } + + if (postWebhookUrl != null) { - request.addPostParam("PostWebhookUrl", postWebhookUrl.toString()); + Serializer.toString(request, "PostWebhookUrl", postWebhookUrl, ParameterType.URLENCODED); } + + if (webhookMethod != null) { - request.addPostParam("WebhookMethod", webhookMethod.toString()); + Serializer.toString(request, "WebhookMethod", webhookMethod, ParameterType.URLENCODED); } + + if (webhookFilters != null) { - for (String prop : webhookFilters) { - request.addPostParam("WebhookFilters", prop); + for (String param : webhookFilters) { + Serializer.toString(request, "WebhookFilters", param, ParameterType.URLENCODED); } } + + if (limitsChannelMembers != null) { - request.addPostParam( - "Limits.ChannelMembers", - limitsChannelMembers.toString() - ); + Serializer.toString(request, "Limits.ChannelMembers", limitsChannelMembers, ParameterType.URLENCODED); } + + if (limitsUserChannels != null) { - request.addPostParam( - "Limits.UserChannels", - limitsUserChannels.toString() - ); + Serializer.toString(request, "Limits.UserChannels", limitsUserChannels, ParameterType.URLENCODED); } + + if (mediaCompatibilityMessage != null) { - request.addPostParam( - "Media.CompatibilityMessage", - mediaCompatibilityMessage - ); + Serializer.toString(request, "Media.CompatibilityMessage", mediaCompatibilityMessage, ParameterType.URLENCODED); } + + if (preWebhookRetryCount != null) { - request.addPostParam( - "PreWebhookRetryCount", - preWebhookRetryCount.toString() - ); + Serializer.toString(request, "PreWebhookRetryCount", preWebhookRetryCount, ParameterType.URLENCODED); } + + if (postWebhookRetryCount != null) { - request.addPostParam( - "PostWebhookRetryCount", - postWebhookRetryCount.toString() - ); + Serializer.toString(request, "PostWebhookRetryCount", postWebhookRetryCount, ParameterType.URLENCODED); } + + if (notificationsLogEnabled != null) { - request.addPostParam( - "Notifications.LogEnabled", - notificationsLogEnabled.toString() - ); + Serializer.toString(request, "Notifications.LogEnabled", notificationsLogEnabled, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/chat/v2/service/Binding.java b/src/main/java/com/twilio/rest/chat/v2/service/Binding.java index 3ace8bfd8d..63899bc465 100644 --- a/src/main/java/com/twilio/rest/chat/v2/service/Binding.java +++ b/src/main/java/com/twilio/rest/chat/v2/service/Binding.java @@ -18,59 +18,81 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.List; import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Binding extends Resource { - private static final long serialVersionUID = 223064407729885L; - public static BindingDeleter deleter( - final String pathServiceSid, - final String pathSid - ) { - return new BindingDeleter(pathServiceSid, pathSid); + public static BindingDeleter deleter(final String pathserviceSid, final String pathsid) { + return new BindingDeleter( + pathserviceSid, pathsid + ); } - public static BindingFetcher fetcher( - final String pathServiceSid, - final String pathSid - ) { - return new BindingFetcher(pathServiceSid, pathSid); + + public static BindingFetcher fetcher(final String pathserviceSid, final String pathsid) { + return new BindingFetcher( + pathserviceSid, pathsid + ); + } + + + public static BindingReader reader(final String pathserviceSid) { + return new BindingReader( + pathserviceSid + ); } - public static BindingReader reader(final String pathServiceSid) { - return new BindingReader(pathServiceSid); + + public enum BindingType { + GCM("gcm"), + APN("apn"), + FCM("fcm"); + + private final String value; + + private BindingType(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static BindingType forValue(final String value) { + return Promoter.enumFromString(value, BindingType.values()); + } } + /** * Converts a JSON String into a Binding object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Binding object represented by the provided JSON */ - public static Binding fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Binding fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Binding.class); @@ -85,14 +107,11 @@ public static Binding fromJson( * Converts a JSON InputStream into a Binding object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Binding object represented by the provided JSON */ - public static Binding fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Binding fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Binding.class); @@ -103,94 +122,73 @@ public static Binding fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String serviceSid; + @Getter + private final Binding.BindingType bindingType; + @Getter + private final String credentialSid; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; + @Getter private final String endpoint; + @Getter private final String identity; - private final String credentialSid; - private final Binding.BindingType bindingType; + @Getter + private final Map links; + @Getter private final List messageTypes; + @Getter + private final String serviceSid; + @Getter + private final String sid; + @Getter private final URI url; - private final Map links; @JsonCreator private Binding( - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("service_sid") final String serviceSid, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("endpoint") final String endpoint, - @JsonProperty("identity") final String identity, - @JsonProperty("credential_sid") final String credentialSid, - @JsonProperty("binding_type") final Binding.BindingType bindingType, - @JsonProperty("message_types") final List messageTypes, - @JsonProperty("url") final URI url, - @JsonProperty("links") final Map links + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("binding_type") final Binding.BindingType bindingType, + @JsonProperty("credential_sid") final String credentialSid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("endpoint") final String endpoint, + @JsonProperty("identity") final String identity, + @JsonProperty("links") final Map links, + @JsonProperty("message_types") final List messageTypes, + @JsonProperty("service_sid") final String serviceSid, + @JsonProperty("sid") final String sid, + @JsonProperty("url") final URI url ) { - this.sid = sid; this.accountSid = accountSid; - this.serviceSid = serviceSid; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); + this.bindingType = bindingType; + this.credentialSid = credentialSid; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.endpoint = endpoint; this.identity = identity; - this.credentialSid = credentialSid; - this.bindingType = bindingType; + this.links = links; this.messageTypes = messageTypes; + this.serviceSid = serviceSid; + this.sid = sid; this.url = url; - this.links = links; - } - - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getServiceSid() { - return this.serviceSid; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final String getEndpoint() { - return this.endpoint; - } - - public final String getIdentity() { - return this.identity; - } - - public final String getCredentialSid() { - return this.credentialSid; - } - - public final Binding.BindingType getBindingType() { - return this.bindingType; - } - - public final List getMessageTypes() { - return this.messageTypes; - } - - public final URI getUrl() { - return this.url; - } - - public final Map getLinks() { - return this.links; } @Override @@ -204,59 +202,40 @@ public boolean equals(final Object o) { } Binding other = (Binding) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(serviceSid, other.serviceSid) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(endpoint, other.endpoint) && - Objects.equals(identity, other.identity) && - Objects.equals(credentialSid, other.credentialSid) && - Objects.equals(bindingType, other.bindingType) && - Objects.equals(messageTypes, other.messageTypes) && - Objects.equals(url, other.url) && - Objects.equals(links, other.links) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(bindingType, other.bindingType) && + Objects.equals(credentialSid, other.credentialSid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(endpoint, other.endpoint) && + Objects.equals(identity, other.identity) && + Objects.equals(links, other.links) && + Objects.equals(messageTypes, other.messageTypes) && + Objects.equals(serviceSid, other.serviceSid) && + Objects.equals(sid, other.sid) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - sid, - accountSid, - serviceSid, - dateCreated, - dateUpdated, - endpoint, - identity, - credentialSid, - bindingType, - messageTypes, - url, - links + accountSid, + bindingType, + credentialSid, + dateCreated, + dateUpdated, + endpoint, + identity, + links, + messageTypes, + serviceSid, + sid, + url ); } - public enum BindingType { - GCM("gcm"), - APN("apn"), - FCM("fcm"); - private final String value; - - private BindingType(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static BindingType forValue(final String value) { - return Promoter.enumFromString(value, BindingType.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/chat/v2/service/BindingDeleter.java b/src/main/java/com/twilio/rest/chat/v2/service/BindingDeleter.java index 5ec8328c2e..c3bae56fee 100644 --- a/src/main/java/com/twilio/rest/chat/v2/service/BindingDeleter.java +++ b/src/main/java/com/twilio/rest/chat/v2/service/BindingDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.chat.v2.service; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,47 +26,41 @@ public class BindingDeleter extends Deleter { - private String pathServiceSid; - private String pathSid; + private String pathserviceSid; + private String pathsid; - public BindingDeleter(final String pathServiceSid, final String pathSid) { - this.pathServiceSid = pathServiceSid; - this.pathSid = pathSid; + public BindingDeleter(final String pathserviceSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/v2/Services/{ServiceSid}/Bindings/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.CHAT.toString(), - path + HttpMethod.DELETE, + Domains.CHAT.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Binding delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("Binding delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/chat/v2/service/BindingFetcher.java b/src/main/java/com/twilio/rest/chat/v2/service/BindingFetcher.java index 72a45708cd..83513b5645 100644 --- a/src/main/java/com/twilio/rest/chat/v2/service/BindingFetcher.java +++ b/src/main/java/com/twilio/rest/chat/v2/service/BindingFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.chat.v2.service; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,51 +26,44 @@ public class BindingFetcher extends Fetcher { - private String pathServiceSid; - private String pathSid; + private String pathserviceSid; + private String pathsid; - public BindingFetcher(final String pathServiceSid, final String pathSid) { - this.pathServiceSid = pathServiceSid; - this.pathSid = pathSid; + public BindingFetcher(final String pathserviceSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathsid = pathsid; } + @Override public Binding fetch(final TwilioRestClient client) { + String path = "/v2/Services/{ServiceSid}/Bindings/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.CHAT.toString(), - path + HttpMethod.GET, + Domains.CHAT.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Binding fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Binding fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Binding.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/chat/v2/service/BindingReader.java b/src/main/java/com/twilio/rest/chat/v2/service/BindingReader.java index 6bd594c579..5616e28718 100644 --- a/src/main/java/com/twilio/rest/chat/v2/service/BindingReader.java +++ b/src/main/java/com/twilio/rest/chat/v2/service/BindingReader.java @@ -17,8 +17,9 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; import com.twilio.converter.Promoter; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,22 +28,22 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.util.List; public class BindingReader extends Reader { - private String pathServiceSid; + private String pathserviceSid; private List bindingType; private List identity; private Long pageSize; - public BindingReader(final String pathServiceSid) { - this.pathServiceSid = pathServiceSid; + public BindingReader(final String pathserviceSid) { + this.pathserviceSid = pathserviceSid; } - public BindingReader setBindingType( - final List bindingType - ) { + + public BindingReader setBindingType(final List bindingType) { this.bindingType = bindingType; return this; } @@ -65,113 +66,89 @@ public BindingReader setPageSize(final Long pageSize) { return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v2/Services/{ServiceSid}/Bindings"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.CHAT.toString(), - path + HttpMethod.GET, + Domains.CHAT.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Binding read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Binding read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "bindings", - response.getContent(), - Binding.class, - client.getObjectMapper() - ); + "bindings", + response.getContent(), + Binding.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.CHAT.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.CHAT.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (bindingType != null) { - for (Binding.BindingType prop : bindingType) { - request.addQueryParam("BindingType", prop.toString()); + for (Binding.BindingType param : bindingType) { + Serializer.toString(request, "BindingType", param, ParameterType.QUERY); } } + + if (identity != null) { - for (String prop : identity) { - request.addQueryParam("Identity", prop); + for (String param : identity) { + Serializer.toString(request, "Identity", param, ParameterType.QUERY); } } + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/chat/v2/service/Channel.java b/src/main/java/com/twilio/rest/chat/v2/service/Channel.java index d950169893..a9f820a30b 100644 --- a/src/main/java/com/twilio/rest/chat/v2/service/Channel.java +++ b/src/main/java/com/twilio/rest/chat/v2/service/Channel.java @@ -18,69 +18,113 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Channel extends Resource { - private static final long serialVersionUID = 188288773259274L; - public static ChannelCreator creator(final String pathServiceSid) { - return new ChannelCreator(pathServiceSid); + public static ChannelCreator creator(final String pathserviceSid) { + return new ChannelCreator( + pathserviceSid + ); } - public static ChannelDeleter deleter( - final String pathServiceSid, - final String pathSid - ) { - return new ChannelDeleter(pathServiceSid, pathSid); + + public static ChannelDeleter deleter(final String pathserviceSid, final String pathsid) { + return new ChannelDeleter( + pathserviceSid, pathsid + ); } - public static ChannelFetcher fetcher( - final String pathServiceSid, - final String pathSid - ) { - return new ChannelFetcher(pathServiceSid, pathSid); + + public static ChannelFetcher fetcher(final String pathserviceSid, final String pathsid) { + return new ChannelFetcher( + pathserviceSid, pathsid + ); } - public static ChannelReader reader(final String pathServiceSid) { - return new ChannelReader(pathServiceSid); + + public static ChannelReader reader(final String pathserviceSid) { + return new ChannelReader( + pathserviceSid + ); } - public static ChannelUpdater updater( - final String pathServiceSid, - final String pathSid - ) { - return new ChannelUpdater(pathServiceSid, pathSid); + + public static ChannelUpdater updater(final String pathserviceSid, final String pathsid) { + return new ChannelUpdater( + pathserviceSid, pathsid + ); + } + + + public enum WebhookEnabledType { + TRUE("true"), + FALSE("false"); + + private final String value; + + private WebhookEnabledType(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static WebhookEnabledType forValue(final String value) { + return Promoter.enumFromString(value, WebhookEnabledType.values()); + } + } + + public enum ChannelType { + PUBLIC("public"), + PRIVATE("private"); + + private final String value; + + private ChannelType(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static ChannelType forValue(final String value) { + return Promoter.enumFromString(value, ChannelType.values()); + } } + /** * Converts a JSON String into a Channel object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Channel object represented by the provided JSON */ - public static Channel fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Channel fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Channel.class); @@ -95,14 +139,11 @@ public static Channel fromJson( * Converts a JSON InputStream into a Channel object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Channel object represented by the provided JSON */ - public static Channel fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Channel fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Channel.class); @@ -113,108 +154,81 @@ public static Channel fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String serviceSid; - private final String friendlyName; - private final String uniqueName; + @Getter private final String attributes; - private final Channel.ChannelType type; + @Getter + private final String createdBy; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; - private final String createdBy; + @Getter + private final String friendlyName; + @Getter + private final Map links; + @Getter private final Integer membersCount; + @Getter private final Integer messagesCount; + @Getter + private final String serviceSid; + @Getter + private final String sid; + @Getter + private final Channel.ChannelType type; + @Getter + private final String uniqueName; + @Getter private final URI url; - private final Map links; @JsonCreator private Channel( - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("service_sid") final String serviceSid, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("unique_name") final String uniqueName, - @JsonProperty("attributes") final String attributes, - @JsonProperty("type") final Channel.ChannelType type, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("created_by") final String createdBy, - @JsonProperty("members_count") final Integer membersCount, - @JsonProperty("messages_count") final Integer messagesCount, - @JsonProperty("url") final URI url, - @JsonProperty("links") final Map links + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("attributes") final String attributes, + @JsonProperty("created_by") final String createdBy, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("links") final Map links, + @JsonProperty("members_count") final Integer membersCount, + @JsonProperty("messages_count") final Integer messagesCount, + @JsonProperty("service_sid") final String serviceSid, + @JsonProperty("sid") final String sid, + @JsonProperty("type") final Channel.ChannelType type, + @JsonProperty("unique_name") final String uniqueName, + @JsonProperty("url") final URI url ) { - this.sid = sid; this.accountSid = accountSid; - this.serviceSid = serviceSid; - this.friendlyName = friendlyName; - this.uniqueName = uniqueName; this.attributes = attributes; - this.type = type; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); this.createdBy = createdBy; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; + this.friendlyName = friendlyName; + this.links = links; this.membersCount = membersCount; this.messagesCount = messagesCount; + this.serviceSid = serviceSid; + this.sid = sid; + this.type = type; + this.uniqueName = uniqueName; this.url = url; - this.links = links; - } - - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getServiceSid() { - return this.serviceSid; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final String getUniqueName() { - return this.uniqueName; - } - - public final String getAttributes() { - return this.attributes; - } - - public final Channel.ChannelType getType() { - return this.type; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final String getCreatedBy() { - return this.createdBy; - } - - public final Integer getMembersCount() { - return this.membersCount; - } - - public final Integer getMessagesCount() { - return this.messagesCount; - } - - public final URI getUrl() { - return this.url; - } - - public final Map getLinks() { - return this.links; } @Override @@ -228,82 +242,44 @@ public boolean equals(final Object o) { } Channel other = (Channel) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(serviceSid, other.serviceSid) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(uniqueName, other.uniqueName) && - Objects.equals(attributes, other.attributes) && - Objects.equals(type, other.type) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(createdBy, other.createdBy) && - Objects.equals(membersCount, other.membersCount) && - Objects.equals(messagesCount, other.messagesCount) && - Objects.equals(url, other.url) && - Objects.equals(links, other.links) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(attributes, other.attributes) && + Objects.equals(createdBy, other.createdBy) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(links, other.links) && + Objects.equals(membersCount, other.membersCount) && + Objects.equals(messagesCount, other.messagesCount) && + Objects.equals(serviceSid, other.serviceSid) && + Objects.equals(sid, other.sid) && + Objects.equals(type, other.type) && + Objects.equals(uniqueName, other.uniqueName) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - sid, - accountSid, - serviceSid, - friendlyName, - uniqueName, - attributes, - type, - dateCreated, - dateUpdated, - createdBy, - membersCount, - messagesCount, - url, - links + accountSid, + attributes, + createdBy, + dateCreated, + dateUpdated, + friendlyName, + links, + membersCount, + messagesCount, + serviceSid, + sid, + type, + uniqueName, + url ); } - public enum ChannelType { - PUBLIC("public"), - PRIVATE("private"); - - private final String value; - - private ChannelType(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static ChannelType forValue(final String value) { - return Promoter.enumFromString(value, ChannelType.values()); - } - } - public enum WebhookEnabledType { - TRUE("true"), - FALSE("false"); - - private final String value; - - private WebhookEnabledType(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static WebhookEnabledType forValue(final String value) { - return Promoter.enumFromString(value, WebhookEnabledType.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/chat/v2/service/ChannelCreator.java b/src/main/java/com/twilio/rest/chat/v2/service/ChannelCreator.java index 8b13c0f35e..8bcd5f8ac2 100644 --- a/src/main/java/com/twilio/rest/chat/v2/service/ChannelCreator.java +++ b/src/main/java/com/twilio/rest/chat/v2/service/ChannelCreator.java @@ -14,8 +14,11 @@ package com.twilio.rest.chat.v2.service; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -24,11 +27,12 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.time.ZonedDateTime; public class ChannelCreator extends Creator { - private String pathServiceSid; + private String pathserviceSid; private Channel.WebhookEnabledType xTwilioWebhookEnabled; private String friendlyName; private String uniqueName; @@ -38,85 +42,87 @@ public class ChannelCreator extends Creator { private ZonedDateTime dateUpdated; private String createdBy; - public ChannelCreator(final String pathServiceSid) { - this.pathServiceSid = pathServiceSid; + public ChannelCreator(final String pathserviceSid) { + this.pathserviceSid = pathserviceSid; } - public ChannelCreator setXTwilioWebhookEnabled( - final Channel.WebhookEnabledType xTwilioWebhookEnabled - ) { - this.xTwilioWebhookEnabled = xTwilioWebhookEnabled; - return this; - } public ChannelCreator setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + public ChannelCreator setUniqueName(final String uniqueName) { this.uniqueName = uniqueName; return this; } + public ChannelCreator setAttributes(final String attributes) { this.attributes = attributes; return this; } + public ChannelCreator setType(final Channel.ChannelType type) { this.type = type; return this; } + public ChannelCreator setDateCreated(final ZonedDateTime dateCreated) { this.dateCreated = dateCreated; return this; } + public ChannelCreator setDateUpdated(final ZonedDateTime dateUpdated) { this.dateUpdated = dateUpdated; return this; } + public ChannelCreator setCreatedBy(final String createdBy) { this.createdBy = createdBy; return this; } + + public ChannelCreator setXTwilioWebhookEnabled(final Channel.WebhookEnabledType xTwilioWebhookEnabled) { + this.xTwilioWebhookEnabled = xTwilioWebhookEnabled; + return this; + } + + @Override public Channel create(final TwilioRestClient client) { + String path = "/v2/Services/{ServiceSid}/Channels"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.CHAT.toString(), - path + HttpMethod.POST, + Domains.CHAT.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); - addPostParams(request); addHeaderParams(request); + addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Channel creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("Channel creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -125,41 +131,49 @@ public Channel create(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + if (uniqueName != null) { - request.addPostParam("UniqueName", uniqueName); + Serializer.toString(request, "UniqueName", uniqueName, ParameterType.URLENCODED); } + + if (attributes != null) { - request.addPostParam("Attributes", attributes); + Serializer.toString(request, "Attributes", attributes, ParameterType.URLENCODED); } + + if (type != null) { - request.addPostParam("Type", type.toString()); + Serializer.toString(request, "Type", type, ParameterType.URLENCODED); } + + if (dateCreated != null) { - request.addPostParam( - "DateCreated", - dateCreated.toInstant().toString() - ); + Serializer.toString(request, "DateCreated", dateCreated, ParameterType.URLENCODED); } + + if (dateUpdated != null) { - request.addPostParam( - "DateUpdated", - dateUpdated.toInstant().toString() - ); + Serializer.toString(request, "DateUpdated", dateUpdated, ParameterType.URLENCODED); } + + if (createdBy != null) { - request.addPostParam("CreatedBy", createdBy); + Serializer.toString(request, "CreatedBy", createdBy, ParameterType.URLENCODED); } + + } private void addHeaderParams(final Request request) { + if (xTwilioWebhookEnabled != null) { - request.addHeaderParam( - "X-Twilio-Webhook-Enabled", - xTwilioWebhookEnabled.toString() - ); + Serializer.toString(request, "X-Twilio-Webhook-Enabled", xTwilioWebhookEnabled, ParameterType.HEADER); } + } } diff --git a/src/main/java/com/twilio/rest/chat/v2/service/ChannelDeleter.java b/src/main/java/com/twilio/rest/chat/v2/service/ChannelDeleter.java index 73460f5e06..dcd886570a 100644 --- a/src/main/java/com/twilio/rest/chat/v2/service/ChannelDeleter.java +++ b/src/main/java/com/twilio/rest/chat/v2/service/ChannelDeleter.java @@ -15,7 +15,8 @@ package com.twilio.rest.chat.v2.service; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,56 +28,49 @@ public class ChannelDeleter extends Deleter { - private String pathServiceSid; - private String pathSid; + private String pathserviceSid; + private String pathsid; private Channel.WebhookEnabledType xTwilioWebhookEnabled; - public ChannelDeleter(final String pathServiceSid, final String pathSid) { - this.pathServiceSid = pathServiceSid; - this.pathSid = pathSid; + public ChannelDeleter(final String pathserviceSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathsid = pathsid; } - public ChannelDeleter setXTwilioWebhookEnabled( - final Channel.WebhookEnabledType xTwilioWebhookEnabled - ) { + + public ChannelDeleter setXTwilioWebhookEnabled(final Channel.WebhookEnabledType xTwilioWebhookEnabled) { this.xTwilioWebhookEnabled = xTwilioWebhookEnabled; return this; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/v2/Services/{ServiceSid}/Channels/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.CHAT.toString(), - path + HttpMethod.DELETE, + Domains.CHAT.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addHeaderParams(request); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Channel delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("Channel delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -84,11 +78,10 @@ public boolean delete(final TwilioRestClient client) { } private void addHeaderParams(final Request request) { + if (xTwilioWebhookEnabled != null) { - request.addHeaderParam( - "X-Twilio-Webhook-Enabled", - xTwilioWebhookEnabled.toString() - ); + Serializer.toString(request, "X-Twilio-Webhook-Enabled", xTwilioWebhookEnabled, ParameterType.HEADER); } + } } diff --git a/src/main/java/com/twilio/rest/chat/v2/service/ChannelFetcher.java b/src/main/java/com/twilio/rest/chat/v2/service/ChannelFetcher.java index 189bb23b32..10df671ea6 100644 --- a/src/main/java/com/twilio/rest/chat/v2/service/ChannelFetcher.java +++ b/src/main/java/com/twilio/rest/chat/v2/service/ChannelFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.chat.v2.service; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,51 +26,44 @@ public class ChannelFetcher extends Fetcher { - private String pathServiceSid; - private String pathSid; + private String pathserviceSid; + private String pathsid; - public ChannelFetcher(final String pathServiceSid, final String pathSid) { - this.pathServiceSid = pathServiceSid; - this.pathSid = pathSid; + public ChannelFetcher(final String pathserviceSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathsid = pathsid; } + @Override public Channel fetch(final TwilioRestClient client) { + String path = "/v2/Services/{ServiceSid}/Channels/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.CHAT.toString(), - path + HttpMethod.GET, + Domains.CHAT.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Channel fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Channel fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Channel.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/chat/v2/service/ChannelReader.java b/src/main/java/com/twilio/rest/chat/v2/service/ChannelReader.java index 4943072986..82dc044220 100644 --- a/src/main/java/com/twilio/rest/chat/v2/service/ChannelReader.java +++ b/src/main/java/com/twilio/rest/chat/v2/service/ChannelReader.java @@ -17,8 +17,9 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; import com.twilio.converter.Promoter; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,18 +28,20 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.util.List; public class ChannelReader extends Reader { - private String pathServiceSid; + private String pathserviceSid; private List type; private Long pageSize; - public ChannelReader(final String pathServiceSid) { - this.pathServiceSid = pathServiceSid; + public ChannelReader(final String pathserviceSid) { + this.pathserviceSid = pathserviceSid; } + public ChannelReader setType(final List type) { this.type = type; return this; @@ -53,108 +56,82 @@ public ChannelReader setPageSize(final Long pageSize) { return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v2/Services/{ServiceSid}/Channels"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.CHAT.toString(), - path + HttpMethod.GET, + Domains.CHAT.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Channel read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Channel read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "channels", - response.getContent(), - Channel.class, - client.getObjectMapper() - ); + "channels", + response.getContent(), + Channel.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.CHAT.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.CHAT.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (type != null) { - for (Channel.ChannelType prop : type) { - request.addQueryParam("Type", prop.toString()); + for (Channel.ChannelType param : type) { + Serializer.toString(request, "Type", param, ParameterType.QUERY); } } + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/chat/v2/service/ChannelUpdater.java b/src/main/java/com/twilio/rest/chat/v2/service/ChannelUpdater.java index 42fe6a5e6a..a304859bbd 100644 --- a/src/main/java/com/twilio/rest/chat/v2/service/ChannelUpdater.java +++ b/src/main/java/com/twilio/rest/chat/v2/service/ChannelUpdater.java @@ -16,6 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -24,12 +26,12 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.time.ZonedDateTime; public class ChannelUpdater extends Updater { - - private String pathServiceSid; - private String pathSid; + private String pathserviceSid; + private String pathsid; private Channel.WebhookEnabledType xTwilioWebhookEnabled; private String friendlyName; private String uniqueName; @@ -38,82 +40,83 @@ public class ChannelUpdater extends Updater { private ZonedDateTime dateUpdated; private String createdBy; - public ChannelUpdater(final String pathServiceSid, final String pathSid) { - this.pathServiceSid = pathServiceSid; - this.pathSid = pathSid; + public ChannelUpdater(final String pathserviceSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathsid = pathsid; } - public ChannelUpdater setXTwilioWebhookEnabled( - final Channel.WebhookEnabledType xTwilioWebhookEnabled - ) { - this.xTwilioWebhookEnabled = xTwilioWebhookEnabled; - return this; - } public ChannelUpdater setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + public ChannelUpdater setUniqueName(final String uniqueName) { this.uniqueName = uniqueName; return this; } + public ChannelUpdater setAttributes(final String attributes) { this.attributes = attributes; return this; } + public ChannelUpdater setDateCreated(final ZonedDateTime dateCreated) { this.dateCreated = dateCreated; return this; } + public ChannelUpdater setDateUpdated(final ZonedDateTime dateUpdated) { this.dateUpdated = dateUpdated; return this; } + public ChannelUpdater setCreatedBy(final String createdBy) { this.createdBy = createdBy; return this; } + + public ChannelUpdater setXTwilioWebhookEnabled(final Channel.WebhookEnabledType xTwilioWebhookEnabled) { + this.xTwilioWebhookEnabled = xTwilioWebhookEnabled; + return this; + } + + @Override public Channel update(final TwilioRestClient client) { + String path = "/v2/Services/{ServiceSid}/Channels/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.CHAT.toString(), - path + HttpMethod.POST, + Domains.CHAT.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); - addPostParams(request); addHeaderParams(request); + addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Channel update failed: Unable to connect to server" - ); + throw new ApiConnectionException("Channel update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -122,38 +125,44 @@ public Channel update(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + if (uniqueName != null) { - request.addPostParam("UniqueName", uniqueName); + Serializer.toString(request, "UniqueName", uniqueName, ParameterType.URLENCODED); } + + if (attributes != null) { - request.addPostParam("Attributes", attributes); + Serializer.toString(request, "Attributes", attributes, ParameterType.URLENCODED); } + + if (dateCreated != null) { - request.addPostParam( - "DateCreated", - dateCreated.toInstant().toString() - ); + Serializer.toString(request, "DateCreated", dateCreated, ParameterType.URLENCODED); } + + if (dateUpdated != null) { - request.addPostParam( - "DateUpdated", - dateUpdated.toInstant().toString() - ); + Serializer.toString(request, "DateUpdated", dateUpdated, ParameterType.URLENCODED); } + + if (createdBy != null) { - request.addPostParam("CreatedBy", createdBy); + Serializer.toString(request, "CreatedBy", createdBy, ParameterType.URLENCODED); } + + } private void addHeaderParams(final Request request) { + if (xTwilioWebhookEnabled != null) { - request.addHeaderParam( - "X-Twilio-Webhook-Enabled", - xTwilioWebhookEnabled.toString() - ); + Serializer.toString(request, "X-Twilio-Webhook-Enabled", xTwilioWebhookEnabled, ParameterType.HEADER); } + } } diff --git a/src/main/java/com/twilio/rest/chat/v2/service/Role.java b/src/main/java/com/twilio/rest/chat/v2/service/Role.java index 83550db69d..b72d8bc82b 100644 --- a/src/main/java/com/twilio/rest/chat/v2/service/Role.java +++ b/src/main/java/com/twilio/rest/chat/v2/service/Role.java @@ -18,74 +18,93 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.List; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Role extends Resource { - private static final long serialVersionUID = 252065084446046L; - public static RoleCreator creator( - final String pathServiceSid, - final String friendlyName, - final Role.RoleType type, - final List permission - ) { - return new RoleCreator(pathServiceSid, friendlyName, type, permission); + public static RoleCreator creator(final String pathserviceSid, final String friendlyName, final Role.RoleType type, final List permission) { + return new RoleCreator( + pathserviceSid, friendlyName, type, permission + ); } - public static RoleDeleter deleter( - final String pathServiceSid, - final String pathSid - ) { - return new RoleDeleter(pathServiceSid, pathSid); + + public static RoleDeleter deleter(final String pathserviceSid, final String pathsid) { + return new RoleDeleter( + pathserviceSid, pathsid + ); } - public static RoleFetcher fetcher( - final String pathServiceSid, - final String pathSid - ) { - return new RoleFetcher(pathServiceSid, pathSid); + + public static RoleFetcher fetcher(final String pathserviceSid, final String pathsid) { + return new RoleFetcher( + pathserviceSid, pathsid + ); + } + + + public static RoleReader reader(final String pathserviceSid) { + return new RoleReader( + pathserviceSid + ); } - public static RoleReader reader(final String pathServiceSid) { - return new RoleReader(pathServiceSid); + + public static RoleUpdater updater(final String pathserviceSid, final String pathsid, final List permission) { + return new RoleUpdater( + pathserviceSid, pathsid, permission + ); } - public static RoleUpdater updater( - final String pathServiceSid, - final String pathSid, - final List permission - ) { - return new RoleUpdater(pathServiceSid, pathSid, permission); + + public enum RoleType { + CHANNEL("channel"), + DEPLOYMENT("deployment"); + + private final String value; + + private RoleType(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static RoleType forValue(final String value) { + return Promoter.enumFromString(value, RoleType.values()); + } } + /** * Converts a JSON String into a Role object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Role object represented by the provided JSON */ - public static Role fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Role fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Role.class); @@ -100,14 +119,11 @@ public static Role fromJson( * Converts a JSON InputStream into a Role object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Role object represented by the provided JSON */ - public static Role fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Role fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Role.class); @@ -118,75 +134,63 @@ public static Role fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String serviceSid; - private final String friendlyName; - private final Role.RoleType type; - private final List permissions; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; + @Getter + private final String friendlyName; + @Getter + private final List permissions; + @Getter + private final String serviceSid; + @Getter + private final String sid; + @Getter + private final Role.RoleType type; + @Getter private final URI url; @JsonCreator private Role( - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("service_sid") final String serviceSid, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("type") final Role.RoleType type, - @JsonProperty("permissions") final List permissions, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("url") final URI url + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("permissions") final List permissions, + @JsonProperty("service_sid") final String serviceSid, + @JsonProperty("sid") final String sid, + @JsonProperty("type") final Role.RoleType type, + @JsonProperty("url") final URI url ) { - this.sid = sid; this.accountSid = accountSid; - this.serviceSid = serviceSid; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.friendlyName = friendlyName; - this.type = type; this.permissions = permissions; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); + this.serviceSid = serviceSid; + this.sid = sid; + this.type = type; this.url = url; } - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getServiceSid() { - return this.serviceSid; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final Role.RoleType getType() { - return this.type; - } - - public final List getPermissions() { - return this.permissions; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final URI getUrl() { - return this.url; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -198,52 +202,34 @@ public boolean equals(final Object o) { } Role other = (Role) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(serviceSid, other.serviceSid) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(type, other.type) && - Objects.equals(permissions, other.permissions) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(url, other.url) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(permissions, other.permissions) && + Objects.equals(serviceSid, other.serviceSid) && + Objects.equals(sid, other.sid) && + Objects.equals(type, other.type) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - sid, - accountSid, - serviceSid, - friendlyName, - type, - permissions, - dateCreated, - dateUpdated, - url + accountSid, + dateCreated, + dateUpdated, + friendlyName, + permissions, + serviceSid, + sid, + type, + url ); } - public enum RoleType { - CHANNEL("channel"), - DEPLOYMENT("deployment"); - - private final String value; - - private RoleType(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - @JsonCreator - public static RoleType forValue(final String value) { - return Promoter.enumFromString(value, RoleType.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/chat/v2/service/RoleCreator.java b/src/main/java/com/twilio/rest/chat/v2/service/RoleCreator.java index 740903745f..402bfde007 100644 --- a/src/main/java/com/twilio/rest/chat/v2/service/RoleCreator.java +++ b/src/main/java/com/twilio/rest/chat/v2/service/RoleCreator.java @@ -14,9 +14,12 @@ package com.twilio.rest.chat.v2.service; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; import com.twilio.converter.Promoter; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,38 +28,36 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -import java.util.List; + import java.util.List; public class RoleCreator extends Creator { - private String pathServiceSid; + private String pathserviceSid; private String friendlyName; private Role.RoleType type; private List permission; - public RoleCreator( - final String pathServiceSid, - final String friendlyName, - final Role.RoleType type, - final List permission - ) { - this.pathServiceSid = pathServiceSid; + public RoleCreator(final String pathserviceSid, final String friendlyName, final Role.RoleType type, final List permission) { + this.pathserviceSid = pathserviceSid; this.friendlyName = friendlyName; this.type = type; this.permission = permission; } + public RoleCreator setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + public RoleCreator setType(final Role.RoleType type) { this.type = type; return this; } + public RoleCreator setPermission(final List permission) { this.permission = permission; return this; @@ -68,44 +69,31 @@ public RoleCreator setPermission(final String permission) { @Override public Role create(final TwilioRestClient client) { + String path = "/v2/Services/{ServiceSid}/Roles"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = - path.replace( - "{" + "FriendlyName" + "}", - this.friendlyName.toString() - ); - path = path.replace("{" + "Type" + "}", this.type.toString()); - path = - path.replace("{" + "Permission" + "}", this.permission.toString()); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.CHAT.toString(), - path + HttpMethod.POST, + Domains.CHAT.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Role creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("Role creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -114,16 +102,22 @@ public Role create(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + if (type != null) { - request.addPostParam("Type", type.toString()); + Serializer.toString(request, "Type", type, ParameterType.URLENCODED); } + + if (permission != null) { - for (String prop : permission) { - request.addPostParam("Permission", prop); + for (String param : permission) { + Serializer.toString(request, "Permission", param, ParameterType.URLENCODED); } } + } } diff --git a/src/main/java/com/twilio/rest/chat/v2/service/RoleDeleter.java b/src/main/java/com/twilio/rest/chat/v2/service/RoleDeleter.java index babd36dfdf..f94b8c1671 100644 --- a/src/main/java/com/twilio/rest/chat/v2/service/RoleDeleter.java +++ b/src/main/java/com/twilio/rest/chat/v2/service/RoleDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.chat.v2.service; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,47 +26,41 @@ public class RoleDeleter extends Deleter { - private String pathServiceSid; - private String pathSid; + private String pathserviceSid; + private String pathsid; - public RoleDeleter(final String pathServiceSid, final String pathSid) { - this.pathServiceSid = pathServiceSid; - this.pathSid = pathSid; + public RoleDeleter(final String pathserviceSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/v2/Services/{ServiceSid}/Roles/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.CHAT.toString(), - path + HttpMethod.DELETE, + Domains.CHAT.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Role delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("Role delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/chat/v2/service/RoleFetcher.java b/src/main/java/com/twilio/rest/chat/v2/service/RoleFetcher.java index ef65c7c707..e9200e8dbe 100644 --- a/src/main/java/com/twilio/rest/chat/v2/service/RoleFetcher.java +++ b/src/main/java/com/twilio/rest/chat/v2/service/RoleFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.chat.v2.service; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,51 +26,44 @@ public class RoleFetcher extends Fetcher { - private String pathServiceSid; - private String pathSid; + private String pathserviceSid; + private String pathsid; - public RoleFetcher(final String pathServiceSid, final String pathSid) { - this.pathServiceSid = pathServiceSid; - this.pathSid = pathSid; + public RoleFetcher(final String pathserviceSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathsid = pathsid; } + @Override public Role fetch(final TwilioRestClient client) { + String path = "/v2/Services/{ServiceSid}/Roles/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.CHAT.toString(), - path + HttpMethod.GET, + Domains.CHAT.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Role fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Role fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Role.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/chat/v2/service/RoleReader.java b/src/main/java/com/twilio/rest/chat/v2/service/RoleReader.java index 37266e1683..7deae677f4 100644 --- a/src/main/java/com/twilio/rest/chat/v2/service/RoleReader.java +++ b/src/main/java/com/twilio/rest/chat/v2/service/RoleReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,115 +30,88 @@ public class RoleReader extends Reader { - private String pathServiceSid; + private String pathserviceSid; private Long pageSize; - public RoleReader(final String pathServiceSid) { - this.pathServiceSid = pathServiceSid; + public RoleReader(final String pathserviceSid) { + this.pathserviceSid = pathserviceSid; } + public RoleReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v2/Services/{ServiceSid}/Roles"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.CHAT.toString(), - path + HttpMethod.GET, + Domains.CHAT.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Role read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Role read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "roles", - response.getContent(), - Role.class, - client.getObjectMapper() - ); + "roles", + response.getContent(), + Role.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.CHAT.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.CHAT.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/chat/v2/service/RoleUpdater.java b/src/main/java/com/twilio/rest/chat/v2/service/RoleUpdater.java index 1237e2dd6b..47ce76d4d3 100644 --- a/src/main/java/com/twilio/rest/chat/v2/service/RoleUpdater.java +++ b/src/main/java/com/twilio/rest/chat/v2/service/RoleUpdater.java @@ -16,7 +16,9 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; import com.twilio.converter.Promoter; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,24 +27,21 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.util.List; public class RoleUpdater extends Updater { - - private String pathServiceSid; - private String pathSid; + private String pathserviceSid; + private String pathsid; private List permission; - public RoleUpdater( - final String pathServiceSid, - final String pathSid, - final List permission - ) { - this.pathServiceSid = pathServiceSid; - this.pathSid = pathSid; + public RoleUpdater(final String pathserviceSid, final String pathsid, final List permission) { + this.pathserviceSid = pathserviceSid; + this.pathsid = pathsid; this.permission = permission; } + public RoleUpdater setPermission(final List permission) { this.permission = permission; return this; @@ -54,39 +53,32 @@ public RoleUpdater setPermission(final String permission) { @Override public Role update(final TwilioRestClient client) { + String path = "/v2/Services/{ServiceSid}/Roles/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); - path = - path.replace("{" + "Permission" + "}", this.permission.toString()); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.CHAT.toString(), - path + HttpMethod.POST, + Domains.CHAT.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Role update failed: Unable to connect to server" - ); + throw new ApiConnectionException("Role update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -95,10 +87,13 @@ public Role update(final TwilioRestClient client) { } private void addPostParams(final Request request) { + + if (permission != null) { - for (String prop : permission) { - request.addPostParam("Permission", prop); + for (String param : permission) { + Serializer.toString(request, "Permission", param, ParameterType.URLENCODED); } } + } } diff --git a/src/main/java/com/twilio/rest/chat/v2/service/User.java b/src/main/java/com/twilio/rest/chat/v2/service/User.java index cb65b073ef..aab87a0804 100644 --- a/src/main/java/com/twilio/rest/chat/v2/service/User.java +++ b/src/main/java/com/twilio/rest/chat/v2/service/User.java @@ -18,72 +18,93 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class User extends Resource { - private static final long serialVersionUID = 136391609300437L; - public static UserCreator creator( - final String pathServiceSid, - final String identity - ) { - return new UserCreator(pathServiceSid, identity); + public static UserCreator creator(final String pathserviceSid, final String identity) { + return new UserCreator( + pathserviceSid, identity + ); } - public static UserDeleter deleter( - final String pathServiceSid, - final String pathSid - ) { - return new UserDeleter(pathServiceSid, pathSid); + + public static UserDeleter deleter(final String pathserviceSid, final String pathsid) { + return new UserDeleter( + pathserviceSid, pathsid + ); } - public static UserFetcher fetcher( - final String pathServiceSid, - final String pathSid - ) { - return new UserFetcher(pathServiceSid, pathSid); + + public static UserFetcher fetcher(final String pathserviceSid, final String pathsid) { + return new UserFetcher( + pathserviceSid, pathsid + ); + } + + + public static UserReader reader(final String pathserviceSid) { + return new UserReader( + pathserviceSid + ); } - public static UserReader reader(final String pathServiceSid) { - return new UserReader(pathServiceSid); + + public static UserUpdater updater(final String pathserviceSid, final String pathsid) { + return new UserUpdater( + pathserviceSid, pathsid + ); } - public static UserUpdater updater( - final String pathServiceSid, - final String pathSid - ) { - return new UserUpdater(pathServiceSid, pathSid); + + public enum WebhookEnabledType { + TRUE("true"), + FALSE("false"); + + private final String value; + + private WebhookEnabledType(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static WebhookEnabledType forValue(final String value) { + return Promoter.enumFromString(value, WebhookEnabledType.values()); + } } + /** * Converts a JSON String into a User object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return User object represented by the provided JSON */ - public static User fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static User fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, User.class); @@ -98,14 +119,11 @@ public static User fromJson( * Converts a JSON InputStream into a User object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return User object represented by the provided JSON */ - public static User fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static User fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, User.class); @@ -116,112 +134,83 @@ public static User fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String serviceSid; + @Getter private final String attributes; + @Getter + private final ZonedDateTime dateCreated; + @Getter + private final ZonedDateTime dateUpdated; + @Getter private final String friendlyName; - private final String roleSid; + @Getter private final String identity; - private final Boolean isOnline; + @Getter private final Boolean isNotifiable; - private final ZonedDateTime dateCreated; - private final ZonedDateTime dateUpdated; + @Getter + private final Boolean isOnline; + @Getter private final Integer joinedChannelsCount; + @Getter private final Map links; + @Getter + private final String roleSid; + @Getter + private final String serviceSid; + @Getter + private final String sid; + @Getter private final URI url; @JsonCreator private User( - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("service_sid") final String serviceSid, - @JsonProperty("attributes") final String attributes, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("role_sid") final String roleSid, - @JsonProperty("identity") final String identity, - @JsonProperty("is_online") final Boolean isOnline, - @JsonProperty("is_notifiable") final Boolean isNotifiable, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty( - "joined_channels_count" - ) final Integer joinedChannelsCount, - @JsonProperty("links") final Map links, - @JsonProperty("url") final URI url + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("attributes") final String attributes, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("identity") final String identity, + @JsonProperty("is_notifiable") final Boolean isNotifiable, + @JsonProperty("is_online") final Boolean isOnline, + @JsonProperty("joined_channels_count") final Integer joinedChannelsCount, + @JsonProperty("links") final Map links, + @JsonProperty("role_sid") final String roleSid, + @JsonProperty("service_sid") final String serviceSid, + @JsonProperty("sid") final String sid, + @JsonProperty("url") final URI url ) { - this.sid = sid; this.accountSid = accountSid; - this.serviceSid = serviceSid; this.attributes = attributes; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.friendlyName = friendlyName; - this.roleSid = roleSid; this.identity = identity; - this.isOnline = isOnline; this.isNotifiable = isNotifiable; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); + this.isOnline = isOnline; this.joinedChannelsCount = joinedChannelsCount; this.links = links; + this.roleSid = roleSid; + this.serviceSid = serviceSid; + this.sid = sid; this.url = url; } - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getServiceSid() { - return this.serviceSid; - } - - public final String getAttributes() { - return this.attributes; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final String getRoleSid() { - return this.roleSid; - } - - public final String getIdentity() { - return this.identity; - } - - public final Boolean getIsOnline() { - return this.isOnline; - } - - public final Boolean getIsNotifiable() { - return this.isNotifiable; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final Integer getJoinedChannelsCount() { - return this.joinedChannelsCount; - } - - public final Map getLinks() { - return this.links; - } - - public final URI getUrl() { - return this.url; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -233,62 +222,44 @@ public boolean equals(final Object o) { } User other = (User) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(serviceSid, other.serviceSid) && - Objects.equals(attributes, other.attributes) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(roleSid, other.roleSid) && - Objects.equals(identity, other.identity) && - Objects.equals(isOnline, other.isOnline) && - Objects.equals(isNotifiable, other.isNotifiable) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(joinedChannelsCount, other.joinedChannelsCount) && - Objects.equals(links, other.links) && - Objects.equals(url, other.url) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(attributes, other.attributes) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(identity, other.identity) && + Objects.equals(isNotifiable, other.isNotifiable) && + Objects.equals(isOnline, other.isOnline) && + Objects.equals(joinedChannelsCount, other.joinedChannelsCount) && + Objects.equals(links, other.links) && + Objects.equals(roleSid, other.roleSid) && + Objects.equals(serviceSid, other.serviceSid) && + Objects.equals(sid, other.sid) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - sid, - accountSid, - serviceSid, - attributes, - friendlyName, - roleSid, - identity, - isOnline, - isNotifiable, - dateCreated, - dateUpdated, - joinedChannelsCount, - links, - url + accountSid, + attributes, + dateCreated, + dateUpdated, + friendlyName, + identity, + isNotifiable, + isOnline, + joinedChannelsCount, + links, + roleSid, + serviceSid, + sid, + url ); } - public enum WebhookEnabledType { - TRUE("true"), - FALSE("false"); - - private final String value; - private WebhookEnabledType(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static WebhookEnabledType forValue(final String value) { - return Promoter.enumFromString(value, WebhookEnabledType.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/chat/v2/service/UserCreator.java b/src/main/java/com/twilio/rest/chat/v2/service/UserCreator.java index 722537b7dc..2cf0e8dfc2 100644 --- a/src/main/java/com/twilio/rest/chat/v2/service/UserCreator.java +++ b/src/main/java/com/twilio/rest/chat/v2/service/UserCreator.java @@ -14,8 +14,11 @@ package com.twilio.rest.chat.v2.service; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,79 +30,77 @@ public class UserCreator extends Creator { - private String pathServiceSid; - private String identity; + private String pathserviceSid; private User.WebhookEnabledType xTwilioWebhookEnabled; + private String identity; private String roleSid; private String attributes; private String friendlyName; - public UserCreator(final String pathServiceSid, final String identity) { - this.pathServiceSid = pathServiceSid; + public UserCreator(final String pathserviceSid, final String identity) { + this.pathserviceSid = pathserviceSid; this.identity = identity; } + public UserCreator setIdentity(final String identity) { this.identity = identity; return this; } - public UserCreator setXTwilioWebhookEnabled( - final User.WebhookEnabledType xTwilioWebhookEnabled - ) { - this.xTwilioWebhookEnabled = xTwilioWebhookEnabled; - return this; - } public UserCreator setRoleSid(final String roleSid) { this.roleSid = roleSid; return this; } + public UserCreator setAttributes(final String attributes) { this.attributes = attributes; return this; } + public UserCreator setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + + public UserCreator setXTwilioWebhookEnabled(final User.WebhookEnabledType xTwilioWebhookEnabled) { + this.xTwilioWebhookEnabled = xTwilioWebhookEnabled; + return this; + } + + @Override public User create(final TwilioRestClient client) { + String path = "/v2/Services/{ServiceSid}/Users"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = path.replace("{" + "Identity" + "}", this.identity.toString()); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.CHAT.toString(), - path + HttpMethod.POST, + Domains.CHAT.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); - addPostParams(request); addHeaderParams(request); + addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "User creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("User creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -108,26 +109,34 @@ public User create(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (identity != null) { - request.addPostParam("Identity", identity); + Serializer.toString(request, "Identity", identity, ParameterType.URLENCODED); } + + if (roleSid != null) { - request.addPostParam("RoleSid", roleSid); + Serializer.toString(request, "RoleSid", roleSid, ParameterType.URLENCODED); } + + if (attributes != null) { - request.addPostParam("Attributes", attributes); + Serializer.toString(request, "Attributes", attributes, ParameterType.URLENCODED); } + + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + } private void addHeaderParams(final Request request) { + if (xTwilioWebhookEnabled != null) { - request.addHeaderParam( - "X-Twilio-Webhook-Enabled", - xTwilioWebhookEnabled.toString() - ); + Serializer.toString(request, "X-Twilio-Webhook-Enabled", xTwilioWebhookEnabled, ParameterType.HEADER); } + } } diff --git a/src/main/java/com/twilio/rest/chat/v2/service/UserDeleter.java b/src/main/java/com/twilio/rest/chat/v2/service/UserDeleter.java index e34a10587e..6c9b45bbf4 100644 --- a/src/main/java/com/twilio/rest/chat/v2/service/UserDeleter.java +++ b/src/main/java/com/twilio/rest/chat/v2/service/UserDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.chat.v2.service; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,47 +26,41 @@ public class UserDeleter extends Deleter { - private String pathServiceSid; - private String pathSid; + private String pathserviceSid; + private String pathsid; - public UserDeleter(final String pathServiceSid, final String pathSid) { - this.pathServiceSid = pathServiceSid; - this.pathSid = pathSid; + public UserDeleter(final String pathserviceSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/v2/Services/{ServiceSid}/Users/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.CHAT.toString(), - path + HttpMethod.DELETE, + Domains.CHAT.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "User delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("User delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/chat/v2/service/UserFetcher.java b/src/main/java/com/twilio/rest/chat/v2/service/UserFetcher.java index 52522f9a65..abb14008be 100644 --- a/src/main/java/com/twilio/rest/chat/v2/service/UserFetcher.java +++ b/src/main/java/com/twilio/rest/chat/v2/service/UserFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.chat.v2.service; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,51 +26,44 @@ public class UserFetcher extends Fetcher { - private String pathServiceSid; - private String pathSid; + private String pathserviceSid; + private String pathsid; - public UserFetcher(final String pathServiceSid, final String pathSid) { - this.pathServiceSid = pathServiceSid; - this.pathSid = pathSid; + public UserFetcher(final String pathserviceSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathsid = pathsid; } + @Override public User fetch(final TwilioRestClient client) { + String path = "/v2/Services/{ServiceSid}/Users/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.CHAT.toString(), - path + HttpMethod.GET, + Domains.CHAT.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "User fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("User fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return User.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/chat/v2/service/UserReader.java b/src/main/java/com/twilio/rest/chat/v2/service/UserReader.java index a67fb7521c..4c3450bf0a 100644 --- a/src/main/java/com/twilio/rest/chat/v2/service/UserReader.java +++ b/src/main/java/com/twilio/rest/chat/v2/service/UserReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,115 +30,88 @@ public class UserReader extends Reader { - private String pathServiceSid; + private String pathserviceSid; private Long pageSize; - public UserReader(final String pathServiceSid) { - this.pathServiceSid = pathServiceSid; + public UserReader(final String pathserviceSid) { + this.pathserviceSid = pathserviceSid; } + public UserReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v2/Services/{ServiceSid}/Users"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.CHAT.toString(), - path + HttpMethod.GET, + Domains.CHAT.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "User read failed: Unable to connect to server" - ); + throw new ApiConnectionException("User read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "users", - response.getContent(), - User.class, - client.getObjectMapper() - ); + "users", + response.getContent(), + User.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.CHAT.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.CHAT.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/chat/v2/service/UserUpdater.java b/src/main/java/com/twilio/rest/chat/v2/service/UserUpdater.java index 9bd0a04418..1212165787 100644 --- a/src/main/java/com/twilio/rest/chat/v2/service/UserUpdater.java +++ b/src/main/java/com/twilio/rest/chat/v2/service/UserUpdater.java @@ -16,6 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -26,75 +28,72 @@ import com.twilio.rest.Domains; public class UserUpdater extends Updater { - - private String pathServiceSid; - private String pathSid; + private String pathserviceSid; + private String pathsid; private User.WebhookEnabledType xTwilioWebhookEnabled; private String roleSid; private String attributes; private String friendlyName; - public UserUpdater(final String pathServiceSid, final String pathSid) { - this.pathServiceSid = pathServiceSid; - this.pathSid = pathSid; + public UserUpdater(final String pathserviceSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathsid = pathsid; } - public UserUpdater setXTwilioWebhookEnabled( - final User.WebhookEnabledType xTwilioWebhookEnabled - ) { - this.xTwilioWebhookEnabled = xTwilioWebhookEnabled; - return this; - } public UserUpdater setRoleSid(final String roleSid) { this.roleSid = roleSid; return this; } + public UserUpdater setAttributes(final String attributes) { this.attributes = attributes; return this; } + public UserUpdater setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + + public UserUpdater setXTwilioWebhookEnabled(final User.WebhookEnabledType xTwilioWebhookEnabled) { + this.xTwilioWebhookEnabled = xTwilioWebhookEnabled; + return this; + } + + @Override public User update(final TwilioRestClient client) { + String path = "/v2/Services/{ServiceSid}/Users/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.CHAT.toString(), - path + HttpMethod.POST, + Domains.CHAT.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); - addPostParams(request); addHeaderParams(request); + addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "User update failed: Unable to connect to server" - ); + throw new ApiConnectionException("User update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -103,23 +102,29 @@ public User update(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (roleSid != null) { - request.addPostParam("RoleSid", roleSid); + Serializer.toString(request, "RoleSid", roleSid, ParameterType.URLENCODED); } + + if (attributes != null) { - request.addPostParam("Attributes", attributes); + Serializer.toString(request, "Attributes", attributes, ParameterType.URLENCODED); } + + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + } private void addHeaderParams(final Request request) { + if (xTwilioWebhookEnabled != null) { - request.addHeaderParam( - "X-Twilio-Webhook-Enabled", - xTwilioWebhookEnabled.toString() - ); + Serializer.toString(request, "X-Twilio-Webhook-Enabled", xTwilioWebhookEnabled, ParameterType.HEADER); } + } } diff --git a/src/main/java/com/twilio/rest/chat/v2/service/channel/Invite.java b/src/main/java/com/twilio/rest/chat/v2/service/channel/Invite.java index 4c079f24d8..470d9fac5c 100644 --- a/src/main/java/com/twilio/rest/chat/v2/service/channel/Invite.java +++ b/src/main/java/com/twilio/rest/chat/v2/service/channel/Invite.java @@ -18,68 +18,63 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Invite extends Resource { - private static final long serialVersionUID = 148273166902210L; - public static InviteCreator creator( - final String pathServiceSid, - final String pathChannelSid, - final String identity - ) { - return new InviteCreator(pathServiceSid, pathChannelSid, identity); + public static InviteCreator creator(final String pathserviceSid, final String pathchannelSid, final String identity) { + return new InviteCreator( + pathserviceSid, pathchannelSid, identity + ); } - public static InviteDeleter deleter( - final String pathServiceSid, - final String pathChannelSid, - final String pathSid - ) { - return new InviteDeleter(pathServiceSid, pathChannelSid, pathSid); + + public static InviteDeleter deleter(final String pathserviceSid, final String pathchannelSid, final String pathsid) { + return new InviteDeleter( + pathserviceSid, pathchannelSid, pathsid + ); } - public static InviteFetcher fetcher( - final String pathServiceSid, - final String pathChannelSid, - final String pathSid - ) { - return new InviteFetcher(pathServiceSid, pathChannelSid, pathSid); + + public static InviteFetcher fetcher(final String pathserviceSid, final String pathchannelSid, final String pathsid) { + return new InviteFetcher( + pathserviceSid, pathchannelSid, pathsid + ); } - public static InviteReader reader( - final String pathServiceSid, - final String pathChannelSid - ) { - return new InviteReader(pathServiceSid, pathChannelSid); + + public static InviteReader reader(final String pathserviceSid, final String pathchannelSid) { + return new InviteReader( + pathserviceSid, pathchannelSid + ); } + /** * Converts a JSON String into a Invite object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Invite object represented by the provided JSON */ - public static Invite fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Invite fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Invite.class); @@ -94,14 +89,11 @@ public static Invite fromJson( * Converts a JSON InputStream into a Invite object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Invite object represented by the provided JSON */ - public static Invite fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Invite fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Invite.class); @@ -112,82 +104,67 @@ public static Invite fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; + @Getter private final String channelSid; - private final String serviceSid; - private final String identity; + @Getter + private final String createdBy; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; + @Getter + private final String identity; + @Getter private final String roleSid; - private final String createdBy; + @Getter + private final String serviceSid; + @Getter + private final String sid; + @Getter private final URI url; @JsonCreator private Invite( - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("channel_sid") final String channelSid, - @JsonProperty("service_sid") final String serviceSid, - @JsonProperty("identity") final String identity, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("role_sid") final String roleSid, - @JsonProperty("created_by") final String createdBy, - @JsonProperty("url") final URI url + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("channel_sid") final String channelSid, + @JsonProperty("created_by") final String createdBy, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("identity") final String identity, + @JsonProperty("role_sid") final String roleSid, + @JsonProperty("service_sid") final String serviceSid, + @JsonProperty("sid") final String sid, + @JsonProperty("url") final URI url ) { - this.sid = sid; this.accountSid = accountSid; this.channelSid = channelSid; - this.serviceSid = serviceSid; + this.createdBy = createdBy; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.identity = identity; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); this.roleSid = roleSid; - this.createdBy = createdBy; + this.serviceSid = serviceSid; + this.sid = sid; this.url = url; } - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getChannelSid() { - return this.channelSid; - } - - public final String getServiceSid() { - return this.serviceSid; - } - - public final String getIdentity() { - return this.identity; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final String getRoleSid() { - return this.roleSid; - } - - public final String getCreatedBy() { - return this.createdBy; - } - - public final URI getUrl() { - return this.url; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -199,34 +176,36 @@ public boolean equals(final Object o) { } Invite other = (Invite) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(channelSid, other.channelSid) && - Objects.equals(serviceSid, other.serviceSid) && - Objects.equals(identity, other.identity) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(roleSid, other.roleSid) && - Objects.equals(createdBy, other.createdBy) && - Objects.equals(url, other.url) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(channelSid, other.channelSid) && + Objects.equals(createdBy, other.createdBy) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(identity, other.identity) && + Objects.equals(roleSid, other.roleSid) && + Objects.equals(serviceSid, other.serviceSid) && + Objects.equals(sid, other.sid) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - sid, - accountSid, - channelSid, - serviceSid, - identity, - dateCreated, - dateUpdated, - roleSid, - createdBy, - url + accountSid, + channelSid, + createdBy, + dateCreated, + dateUpdated, + identity, + roleSid, + serviceSid, + sid, + url ); } + + } + diff --git a/src/main/java/com/twilio/rest/chat/v2/service/channel/InviteCreator.java b/src/main/java/com/twilio/rest/chat/v2/service/channel/InviteCreator.java index 51917a0e89..6f951b50d8 100644 --- a/src/main/java/com/twilio/rest/chat/v2/service/channel/InviteCreator.java +++ b/src/main/java/com/twilio/rest/chat/v2/service/channel/InviteCreator.java @@ -14,8 +14,11 @@ package com.twilio.rest.chat.v2.service.channel; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,69 +30,58 @@ public class InviteCreator extends Creator { - private String pathServiceSid; - private String pathChannelSid; + private String pathserviceSid; + private String pathchannelSid; private String identity; private String roleSid; - public InviteCreator( - final String pathServiceSid, - final String pathChannelSid, - final String identity - ) { - this.pathServiceSid = pathServiceSid; - this.pathChannelSid = pathChannelSid; + public InviteCreator(final String pathserviceSid, final String pathchannelSid, final String identity) { + this.pathserviceSid = pathserviceSid; + this.pathchannelSid = pathchannelSid; this.identity = identity; } + public InviteCreator setIdentity(final String identity) { this.identity = identity; return this; } + public InviteCreator setRoleSid(final String roleSid) { this.roleSid = roleSid; return this; } + @Override public Invite create(final TwilioRestClient client) { + String path = "/v2/Services/{ServiceSid}/Channels/{ChannelSid}/Invites"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = - path.replace( - "{" + "ChannelSid" + "}", - this.pathChannelSid.toString() - ); - path = path.replace("{" + "Identity" + "}", this.identity.toString()); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "ChannelSid" + "}", this.pathchannelSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.CHAT.toString(), - path + HttpMethod.POST, + Domains.CHAT.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Invite creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("Invite creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -98,11 +90,16 @@ public Invite create(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (identity != null) { - request.addPostParam("Identity", identity); + Serializer.toString(request, "Identity", identity, ParameterType.URLENCODED); } + + if (roleSid != null) { - request.addPostParam("RoleSid", roleSid); + Serializer.toString(request, "RoleSid", roleSid, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/chat/v2/service/channel/InviteDeleter.java b/src/main/java/com/twilio/rest/chat/v2/service/channel/InviteDeleter.java index e0f120dc84..266b9940dc 100644 --- a/src/main/java/com/twilio/rest/chat/v2/service/channel/InviteDeleter.java +++ b/src/main/java/com/twilio/rest/chat/v2/service/channel/InviteDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.chat.v2.service.channel; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,59 +26,44 @@ public class InviteDeleter extends Deleter { - private String pathServiceSid; - private String pathChannelSid; - private String pathSid; + private String pathserviceSid; + private String pathchannelSid; + private String pathsid; - public InviteDeleter( - final String pathServiceSid, - final String pathChannelSid, - final String pathSid - ) { - this.pathServiceSid = pathServiceSid; - this.pathChannelSid = pathChannelSid; - this.pathSid = pathSid; + public InviteDeleter(final String pathserviceSid, final String pathchannelSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathchannelSid = pathchannelSid; + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { - String path = - "/v2/Services/{ServiceSid}/Channels/{ChannelSid}/Invites/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = - path.replace( - "{" + "ChannelSid" + "}", - this.pathChannelSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/v2/Services/{ServiceSid}/Channels/{ChannelSid}/Invites/{Sid}"; + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "ChannelSid" + "}", this.pathchannelSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.CHAT.toString(), - path + HttpMethod.DELETE, + Domains.CHAT.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Invite delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("Invite delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/chat/v2/service/channel/InviteFetcher.java b/src/main/java/com/twilio/rest/chat/v2/service/channel/InviteFetcher.java index 244d73312f..0039fe18f0 100644 --- a/src/main/java/com/twilio/rest/chat/v2/service/channel/InviteFetcher.java +++ b/src/main/java/com/twilio/rest/chat/v2/service/channel/InviteFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.chat.v2.service.channel; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,63 +26,47 @@ public class InviteFetcher extends Fetcher { - private String pathServiceSid; - private String pathChannelSid; - private String pathSid; + private String pathserviceSid; + private String pathchannelSid; + private String pathsid; - public InviteFetcher( - final String pathServiceSid, - final String pathChannelSid, - final String pathSid - ) { - this.pathServiceSid = pathServiceSid; - this.pathChannelSid = pathChannelSid; - this.pathSid = pathSid; + public InviteFetcher(final String pathserviceSid, final String pathchannelSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathchannelSid = pathchannelSid; + this.pathsid = pathsid; } + @Override public Invite fetch(final TwilioRestClient client) { - String path = - "/v2/Services/{ServiceSid}/Channels/{ChannelSid}/Invites/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = - path.replace( - "{" + "ChannelSid" + "}", - this.pathChannelSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/v2/Services/{ServiceSid}/Channels/{ChannelSid}/Invites/{Sid}"; + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "ChannelSid" + "}", this.pathchannelSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.CHAT.toString(), - path + HttpMethod.GET, + Domains.CHAT.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Invite fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Invite fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Invite.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/chat/v2/service/channel/InviteReader.java b/src/main/java/com/twilio/rest/chat/v2/service/channel/InviteReader.java index b218c9049c..a0b015777d 100644 --- a/src/main/java/com/twilio/rest/chat/v2/service/channel/InviteReader.java +++ b/src/main/java/com/twilio/rest/chat/v2/service/channel/InviteReader.java @@ -17,8 +17,9 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; import com.twilio.converter.Promoter; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,23 +28,22 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.util.List; public class InviteReader extends Reader { - private String pathServiceSid; - private String pathChannelSid; + private String pathserviceSid; + private String pathchannelSid; private List identity; private Long pageSize; - public InviteReader( - final String pathServiceSid, - final String pathChannelSid - ) { - this.pathServiceSid = pathServiceSid; - this.pathChannelSid = pathChannelSid; + public InviteReader(final String pathserviceSid, final String pathchannelSid) { + this.pathserviceSid = pathserviceSid; + this.pathchannelSid = pathchannelSid; } + public InviteReader setIdentity(final List identity) { this.identity = identity; return this; @@ -58,113 +58,83 @@ public InviteReader setPageSize(final Long pageSize) { return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v2/Services/{ServiceSid}/Channels/{ChannelSid}/Invites"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = - path.replace( - "{" + "ChannelSid" + "}", - this.pathChannelSid.toString() - ); + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "ChannelSid" + "}", this.pathchannelSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.CHAT.toString(), - path + HttpMethod.GET, + Domains.CHAT.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Invite read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Invite read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "invites", - response.getContent(), - Invite.class, - client.getObjectMapper() - ); + "invites", + response.getContent(), + Invite.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.CHAT.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.CHAT.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (identity != null) { - for (String prop : identity) { - request.addQueryParam("Identity", prop); + for (String param : identity) { + Serializer.toString(request, "Identity", param, ParameterType.QUERY); } } + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/chat/v2/service/channel/Member.java b/src/main/java/com/twilio/rest/chat/v2/service/channel/Member.java index 781bdad9d1..869be15b52 100644 --- a/src/main/java/com/twilio/rest/chat/v2/service/channel/Member.java +++ b/src/main/java/com/twilio/rest/chat/v2/service/channel/Member.java @@ -18,77 +18,92 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Member extends Resource { - private static final long serialVersionUID = 220317594144302L; - public static MemberCreator creator( - final String pathServiceSid, - final String pathChannelSid, - final String identity - ) { - return new MemberCreator(pathServiceSid, pathChannelSid, identity); + public static MemberCreator creator(final String pathserviceSid, final String pathchannelSid, final String identity) { + return new MemberCreator( + pathserviceSid, pathchannelSid, identity + ); } - public static MemberDeleter deleter( - final String pathServiceSid, - final String pathChannelSid, - final String pathSid - ) { - return new MemberDeleter(pathServiceSid, pathChannelSid, pathSid); + + public static MemberDeleter deleter(final String pathserviceSid, final String pathchannelSid, final String pathsid) { + return new MemberDeleter( + pathserviceSid, pathchannelSid, pathsid + ); } - public static MemberFetcher fetcher( - final String pathServiceSid, - final String pathChannelSid, - final String pathSid - ) { - return new MemberFetcher(pathServiceSid, pathChannelSid, pathSid); + + public static MemberFetcher fetcher(final String pathserviceSid, final String pathchannelSid, final String pathsid) { + return new MemberFetcher( + pathserviceSid, pathchannelSid, pathsid + ); } - public static MemberReader reader( - final String pathServiceSid, - final String pathChannelSid - ) { - return new MemberReader(pathServiceSid, pathChannelSid); + + public static MemberReader reader(final String pathserviceSid, final String pathchannelSid) { + return new MemberReader( + pathserviceSid, pathchannelSid + ); } - public static MemberUpdater updater( - final String pathServiceSid, - final String pathChannelSid, - final String pathSid - ) { - return new MemberUpdater(pathServiceSid, pathChannelSid, pathSid); + + public static MemberUpdater updater(final String pathserviceSid, final String pathchannelSid, final String pathsid) { + return new MemberUpdater( + pathserviceSid, pathchannelSid, pathsid + ); } + + public enum WebhookEnabledType { + TRUE("true"), + FALSE("false"); + + private final String value; + + private WebhookEnabledType(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static WebhookEnabledType forValue(final String value) { + return Promoter.enumFromString(value, WebhookEnabledType.values()); + } + } + + /** * Converts a JSON String into a Member object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Member object represented by the provided JSON */ - public static Member fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Member fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Member.class); @@ -103,14 +118,11 @@ public static Member fromJson( * Converts a JSON InputStream into a Member object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Member object represented by the provided JSON */ - public static Member fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Member fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Member.class); @@ -121,99 +133,74 @@ public static Member fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; + @Getter + private final String attributes; + @Getter private final String channelSid; - private final String serviceSid; - private final String identity; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; - private final String roleSid; + @Getter + private final String identity; + @Getter private final Integer lastConsumedMessageIndex; + @Getter private final ZonedDateTime lastConsumptionTimestamp; + @Getter + private final String roleSid; + @Getter + private final String serviceSid; + @Getter + private final String sid; + @Getter private final URI url; - private final String attributes; @JsonCreator private Member( - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("channel_sid") final String channelSid, - @JsonProperty("service_sid") final String serviceSid, - @JsonProperty("identity") final String identity, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("role_sid") final String roleSid, - @JsonProperty( - "last_consumed_message_index" - ) final Integer lastConsumedMessageIndex, - @JsonProperty( - "last_consumption_timestamp" - ) final String lastConsumptionTimestamp, - @JsonProperty("url") final URI url, - @JsonProperty("attributes") final String attributes + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("attributes") final String attributes, + @JsonProperty("channel_sid") final String channelSid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("identity") final String identity, + @JsonProperty("last_consumed_message_index") final Integer lastConsumedMessageIndex, + @JsonProperty("last_consumption_timestamp") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime lastConsumptionTimestamp, + @JsonProperty("role_sid") final String roleSid, + @JsonProperty("service_sid") final String serviceSid, + @JsonProperty("sid") final String sid, + @JsonProperty("url") final URI url ) { - this.sid = sid; this.accountSid = accountSid; + this.attributes = attributes; this.channelSid = channelSid; - this.serviceSid = serviceSid; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.identity = identity; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); - this.roleSid = roleSid; this.lastConsumedMessageIndex = lastConsumedMessageIndex; - this.lastConsumptionTimestamp = - DateConverter.iso8601DateTimeFromString(lastConsumptionTimestamp); + this.lastConsumptionTimestamp = lastConsumptionTimestamp; + this.roleSid = roleSid; + this.serviceSid = serviceSid; + this.sid = sid; this.url = url; - this.attributes = attributes; - } - - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getChannelSid() { - return this.channelSid; - } - - public final String getServiceSid() { - return this.serviceSid; - } - - public final String getIdentity() { - return this.identity; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final String getRoleSid() { - return this.roleSid; - } - - public final Integer getLastConsumedMessageIndex() { - return this.lastConsumedMessageIndex; - } - - public final ZonedDateTime getLastConsumptionTimestamp() { - return this.lastConsumptionTimestamp; - } - - public final URI getUrl() { - return this.url; - } - - public final String getAttributes() { - return this.attributes; } @Override @@ -227,64 +214,40 @@ public boolean equals(final Object o) { } Member other = (Member) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(channelSid, other.channelSid) && - Objects.equals(serviceSid, other.serviceSid) && - Objects.equals(identity, other.identity) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(roleSid, other.roleSid) && - Objects.equals( - lastConsumedMessageIndex, - other.lastConsumedMessageIndex - ) && - Objects.equals( - lastConsumptionTimestamp, - other.lastConsumptionTimestamp - ) && - Objects.equals(url, other.url) && - Objects.equals(attributes, other.attributes) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(attributes, other.attributes) && + Objects.equals(channelSid, other.channelSid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(identity, other.identity) && + Objects.equals(lastConsumedMessageIndex, other.lastConsumedMessageIndex) && + Objects.equals(lastConsumptionTimestamp, other.lastConsumptionTimestamp) && + Objects.equals(roleSid, other.roleSid) && + Objects.equals(serviceSid, other.serviceSid) && + Objects.equals(sid, other.sid) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - sid, - accountSid, - channelSid, - serviceSid, - identity, - dateCreated, - dateUpdated, - roleSid, - lastConsumedMessageIndex, - lastConsumptionTimestamp, - url, - attributes + accountSid, + attributes, + channelSid, + dateCreated, + dateUpdated, + identity, + lastConsumedMessageIndex, + lastConsumptionTimestamp, + roleSid, + serviceSid, + sid, + url ); } - public enum WebhookEnabledType { - TRUE("true"), - FALSE("false"); - - private final String value; - private WebhookEnabledType(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static WebhookEnabledType forValue(final String value) { - return Promoter.enumFromString(value, WebhookEnabledType.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/chat/v2/service/channel/MemberCreator.java b/src/main/java/com/twilio/rest/chat/v2/service/channel/MemberCreator.java index 3e86bcfe0b..f94d9c55bc 100644 --- a/src/main/java/com/twilio/rest/chat/v2/service/channel/MemberCreator.java +++ b/src/main/java/com/twilio/rest/chat/v2/service/channel/MemberCreator.java @@ -14,8 +14,11 @@ package com.twilio.rest.chat.v2.service.channel; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -24,14 +27,15 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.time.ZonedDateTime; public class MemberCreator extends Creator { - private String pathServiceSid; - private String pathChannelSid; - private String identity; + private String pathserviceSid; + private String pathchannelSid; private Member.WebhookEnabledType xTwilioWebhookEnabled; + private String identity; private String roleSid; private Integer lastConsumedMessageIndex; private ZonedDateTime lastConsumptionTimestamp; @@ -39,101 +43,90 @@ public class MemberCreator extends Creator { private ZonedDateTime dateUpdated; private String attributes; - public MemberCreator( - final String pathServiceSid, - final String pathChannelSid, - final String identity - ) { - this.pathServiceSid = pathServiceSid; - this.pathChannelSid = pathChannelSid; + public MemberCreator(final String pathserviceSid, final String pathchannelSid, final String identity) { + this.pathserviceSid = pathserviceSid; + this.pathchannelSid = pathchannelSid; this.identity = identity; } + public MemberCreator setIdentity(final String identity) { this.identity = identity; return this; } - public MemberCreator setXTwilioWebhookEnabled( - final Member.WebhookEnabledType xTwilioWebhookEnabled - ) { - this.xTwilioWebhookEnabled = xTwilioWebhookEnabled; - return this; - } public MemberCreator setRoleSid(final String roleSid) { this.roleSid = roleSid; return this; } - public MemberCreator setLastConsumedMessageIndex( - final Integer lastConsumedMessageIndex - ) { + + public MemberCreator setLastConsumedMessageIndex(final Integer lastConsumedMessageIndex) { this.lastConsumedMessageIndex = lastConsumedMessageIndex; return this; } - public MemberCreator setLastConsumptionTimestamp( - final ZonedDateTime lastConsumptionTimestamp - ) { + + public MemberCreator setLastConsumptionTimestamp(final ZonedDateTime lastConsumptionTimestamp) { this.lastConsumptionTimestamp = lastConsumptionTimestamp; return this; } + public MemberCreator setDateCreated(final ZonedDateTime dateCreated) { this.dateCreated = dateCreated; return this; } + public MemberCreator setDateUpdated(final ZonedDateTime dateUpdated) { this.dateUpdated = dateUpdated; return this; } + public MemberCreator setAttributes(final String attributes) { this.attributes = attributes; return this; } + + public MemberCreator setXTwilioWebhookEnabled(final Member.WebhookEnabledType xTwilioWebhookEnabled) { + this.xTwilioWebhookEnabled = xTwilioWebhookEnabled; + return this; + } + + @Override public Member create(final TwilioRestClient client) { + String path = "/v2/Services/{ServiceSid}/Channels/{ChannelSid}/Members"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = - path.replace( - "{" + "ChannelSid" + "}", - this.pathChannelSid.toString() - ); - path = path.replace("{" + "Identity" + "}", this.identity.toString()); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "ChannelSid" + "}", this.pathchannelSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.CHAT.toString(), - path + HttpMethod.POST, + Domains.CHAT.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); - addPostParams(request); addHeaderParams(request); + addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Member creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("Member creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -142,47 +135,49 @@ public Member create(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (identity != null) { - request.addPostParam("Identity", identity); + Serializer.toString(request, "Identity", identity, ParameterType.URLENCODED); } + + if (roleSid != null) { - request.addPostParam("RoleSid", roleSid); + Serializer.toString(request, "RoleSid", roleSid, ParameterType.URLENCODED); } + + if (lastConsumedMessageIndex != null) { - request.addPostParam( - "LastConsumedMessageIndex", - lastConsumedMessageIndex.toString() - ); + Serializer.toString(request, "LastConsumedMessageIndex", lastConsumedMessageIndex, ParameterType.URLENCODED); } + + if (lastConsumptionTimestamp != null) { - request.addPostParam( - "LastConsumptionTimestamp", - lastConsumptionTimestamp.toInstant().toString() - ); + Serializer.toString(request, "LastConsumptionTimestamp", lastConsumptionTimestamp, ParameterType.URLENCODED); } + + if (dateCreated != null) { - request.addPostParam( - "DateCreated", - dateCreated.toInstant().toString() - ); + Serializer.toString(request, "DateCreated", dateCreated, ParameterType.URLENCODED); } + + if (dateUpdated != null) { - request.addPostParam( - "DateUpdated", - dateUpdated.toInstant().toString() - ); + Serializer.toString(request, "DateUpdated", dateUpdated, ParameterType.URLENCODED); } + + if (attributes != null) { - request.addPostParam("Attributes", attributes); + Serializer.toString(request, "Attributes", attributes, ParameterType.URLENCODED); } + + } private void addHeaderParams(final Request request) { + if (xTwilioWebhookEnabled != null) { - request.addHeaderParam( - "X-Twilio-Webhook-Enabled", - xTwilioWebhookEnabled.toString() - ); + Serializer.toString(request, "X-Twilio-Webhook-Enabled", xTwilioWebhookEnabled, ParameterType.HEADER); } + } } diff --git a/src/main/java/com/twilio/rest/chat/v2/service/channel/MemberDeleter.java b/src/main/java/com/twilio/rest/chat/v2/service/channel/MemberDeleter.java index be8e783241..84463ea2b3 100644 --- a/src/main/java/com/twilio/rest/chat/v2/service/channel/MemberDeleter.java +++ b/src/main/java/com/twilio/rest/chat/v2/service/channel/MemberDeleter.java @@ -15,7 +15,8 @@ package com.twilio.rest.chat.v2.service.channel; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,68 +28,52 @@ public class MemberDeleter extends Deleter { - private String pathServiceSid; - private String pathChannelSid; - private String pathSid; + private String pathserviceSid; + private String pathchannelSid; + private String pathsid; private Member.WebhookEnabledType xTwilioWebhookEnabled; - public MemberDeleter( - final String pathServiceSid, - final String pathChannelSid, - final String pathSid - ) { - this.pathServiceSid = pathServiceSid; - this.pathChannelSid = pathChannelSid; - this.pathSid = pathSid; + public MemberDeleter(final String pathserviceSid, final String pathchannelSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathchannelSid = pathchannelSid; + this.pathsid = pathsid; } - public MemberDeleter setXTwilioWebhookEnabled( - final Member.WebhookEnabledType xTwilioWebhookEnabled - ) { + + public MemberDeleter setXTwilioWebhookEnabled(final Member.WebhookEnabledType xTwilioWebhookEnabled) { this.xTwilioWebhookEnabled = xTwilioWebhookEnabled; return this; } + @Override public boolean delete(final TwilioRestClient client) { - String path = - "/v2/Services/{ServiceSid}/Channels/{ChannelSid}/Members/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = - path.replace( - "{" + "ChannelSid" + "}", - this.pathChannelSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/v2/Services/{ServiceSid}/Channels/{ChannelSid}/Members/{Sid}"; + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "ChannelSid" + "}", this.pathchannelSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.CHAT.toString(), - path + HttpMethod.DELETE, + Domains.CHAT.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addHeaderParams(request); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Member delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("Member delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -96,11 +81,10 @@ public boolean delete(final TwilioRestClient client) { } private void addHeaderParams(final Request request) { + if (xTwilioWebhookEnabled != null) { - request.addHeaderParam( - "X-Twilio-Webhook-Enabled", - xTwilioWebhookEnabled.toString() - ); + Serializer.toString(request, "X-Twilio-Webhook-Enabled", xTwilioWebhookEnabled, ParameterType.HEADER); } + } } diff --git a/src/main/java/com/twilio/rest/chat/v2/service/channel/MemberFetcher.java b/src/main/java/com/twilio/rest/chat/v2/service/channel/MemberFetcher.java index 5d83edb5e5..0059df56b2 100644 --- a/src/main/java/com/twilio/rest/chat/v2/service/channel/MemberFetcher.java +++ b/src/main/java/com/twilio/rest/chat/v2/service/channel/MemberFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.chat.v2.service.channel; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,63 +26,47 @@ public class MemberFetcher extends Fetcher { - private String pathServiceSid; - private String pathChannelSid; - private String pathSid; + private String pathserviceSid; + private String pathchannelSid; + private String pathsid; - public MemberFetcher( - final String pathServiceSid, - final String pathChannelSid, - final String pathSid - ) { - this.pathServiceSid = pathServiceSid; - this.pathChannelSid = pathChannelSid; - this.pathSid = pathSid; + public MemberFetcher(final String pathserviceSid, final String pathchannelSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathchannelSid = pathchannelSid; + this.pathsid = pathsid; } + @Override public Member fetch(final TwilioRestClient client) { - String path = - "/v2/Services/{ServiceSid}/Channels/{ChannelSid}/Members/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = - path.replace( - "{" + "ChannelSid" + "}", - this.pathChannelSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/v2/Services/{ServiceSid}/Channels/{ChannelSid}/Members/{Sid}"; + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "ChannelSid" + "}", this.pathchannelSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.CHAT.toString(), - path + HttpMethod.GET, + Domains.CHAT.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Member fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Member fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Member.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/chat/v2/service/channel/MemberReader.java b/src/main/java/com/twilio/rest/chat/v2/service/channel/MemberReader.java index eb028a9266..85342e7a53 100644 --- a/src/main/java/com/twilio/rest/chat/v2/service/channel/MemberReader.java +++ b/src/main/java/com/twilio/rest/chat/v2/service/channel/MemberReader.java @@ -17,8 +17,9 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; import com.twilio.converter.Promoter; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,23 +28,22 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.util.List; public class MemberReader extends Reader { - private String pathServiceSid; - private String pathChannelSid; + private String pathserviceSid; + private String pathchannelSid; private List identity; private Long pageSize; - public MemberReader( - final String pathServiceSid, - final String pathChannelSid - ) { - this.pathServiceSid = pathServiceSid; - this.pathChannelSid = pathChannelSid; + public MemberReader(final String pathserviceSid, final String pathchannelSid) { + this.pathserviceSid = pathserviceSid; + this.pathchannelSid = pathchannelSid; } + public MemberReader setIdentity(final List identity) { this.identity = identity; return this; @@ -58,113 +58,83 @@ public MemberReader setPageSize(final Long pageSize) { return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v2/Services/{ServiceSid}/Channels/{ChannelSid}/Members"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = - path.replace( - "{" + "ChannelSid" + "}", - this.pathChannelSid.toString() - ); + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "ChannelSid" + "}", this.pathchannelSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.CHAT.toString(), - path + HttpMethod.GET, + Domains.CHAT.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Member read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Member read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "members", - response.getContent(), - Member.class, - client.getObjectMapper() - ); + "members", + response.getContent(), + Member.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.CHAT.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.CHAT.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (identity != null) { - for (String prop : identity) { - request.addQueryParam("Identity", prop); + for (String param : identity) { + Serializer.toString(request, "Identity", param, ParameterType.QUERY); } } + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/chat/v2/service/channel/MemberUpdater.java b/src/main/java/com/twilio/rest/chat/v2/service/channel/MemberUpdater.java index e7e68ded0d..d50d31c97c 100644 --- a/src/main/java/com/twilio/rest/chat/v2/service/channel/MemberUpdater.java +++ b/src/main/java/com/twilio/rest/chat/v2/service/channel/MemberUpdater.java @@ -16,6 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -24,13 +26,13 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.time.ZonedDateTime; public class MemberUpdater extends Updater { - - private String pathServiceSid; - private String pathChannelSid; - private String pathSid; + private String pathserviceSid; + private String pathchannelSid; + private String pathsid; private Member.WebhookEnabledType xTwilioWebhookEnabled; private String roleSid; private Integer lastConsumedMessageIndex; @@ -39,97 +41,85 @@ public class MemberUpdater extends Updater { private ZonedDateTime dateUpdated; private String attributes; - public MemberUpdater( - final String pathServiceSid, - final String pathChannelSid, - final String pathSid - ) { - this.pathServiceSid = pathServiceSid; - this.pathChannelSid = pathChannelSid; - this.pathSid = pathSid; + public MemberUpdater(final String pathserviceSid, final String pathchannelSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathchannelSid = pathchannelSid; + this.pathsid = pathsid; } - public MemberUpdater setXTwilioWebhookEnabled( - final Member.WebhookEnabledType xTwilioWebhookEnabled - ) { - this.xTwilioWebhookEnabled = xTwilioWebhookEnabled; - return this; - } public MemberUpdater setRoleSid(final String roleSid) { this.roleSid = roleSid; return this; } - public MemberUpdater setLastConsumedMessageIndex( - final Integer lastConsumedMessageIndex - ) { + + public MemberUpdater setLastConsumedMessageIndex(final Integer lastConsumedMessageIndex) { this.lastConsumedMessageIndex = lastConsumedMessageIndex; return this; } - public MemberUpdater setLastConsumptionTimestamp( - final ZonedDateTime lastConsumptionTimestamp - ) { + + public MemberUpdater setLastConsumptionTimestamp(final ZonedDateTime lastConsumptionTimestamp) { this.lastConsumptionTimestamp = lastConsumptionTimestamp; return this; } + public MemberUpdater setDateCreated(final ZonedDateTime dateCreated) { this.dateCreated = dateCreated; return this; } + public MemberUpdater setDateUpdated(final ZonedDateTime dateUpdated) { this.dateUpdated = dateUpdated; return this; } + public MemberUpdater setAttributes(final String attributes) { this.attributes = attributes; return this; } + + public MemberUpdater setXTwilioWebhookEnabled(final Member.WebhookEnabledType xTwilioWebhookEnabled) { + this.xTwilioWebhookEnabled = xTwilioWebhookEnabled; + return this; + } + + @Override public Member update(final TwilioRestClient client) { - String path = - "/v2/Services/{ServiceSid}/Channels/{ChannelSid}/Members/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = - path.replace( - "{" + "ChannelSid" + "}", - this.pathChannelSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/v2/Services/{ServiceSid}/Channels/{ChannelSid}/Members/{Sid}"; + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "ChannelSid" + "}", this.pathchannelSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.CHAT.toString(), - path + HttpMethod.POST, + Domains.CHAT.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); - addPostParams(request); addHeaderParams(request); + addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Member update failed: Unable to connect to server" - ); + throw new ApiConnectionException("Member update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -138,44 +128,44 @@ public Member update(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (roleSid != null) { - request.addPostParam("RoleSid", roleSid); + Serializer.toString(request, "RoleSid", roleSid, ParameterType.URLENCODED); } + + if (lastConsumedMessageIndex != null) { - request.addPostParam( - "LastConsumedMessageIndex", - lastConsumedMessageIndex.toString() - ); + Serializer.toString(request, "LastConsumedMessageIndex", lastConsumedMessageIndex, ParameterType.URLENCODED); } + + if (lastConsumptionTimestamp != null) { - request.addPostParam( - "LastConsumptionTimestamp", - lastConsumptionTimestamp.toInstant().toString() - ); + Serializer.toString(request, "LastConsumptionTimestamp", lastConsumptionTimestamp, ParameterType.URLENCODED); } + + if (dateCreated != null) { - request.addPostParam( - "DateCreated", - dateCreated.toInstant().toString() - ); + Serializer.toString(request, "DateCreated", dateCreated, ParameterType.URLENCODED); } + + if (dateUpdated != null) { - request.addPostParam( - "DateUpdated", - dateUpdated.toInstant().toString() - ); + Serializer.toString(request, "DateUpdated", dateUpdated, ParameterType.URLENCODED); } + + if (attributes != null) { - request.addPostParam("Attributes", attributes); + Serializer.toString(request, "Attributes", attributes, ParameterType.URLENCODED); } + + } private void addHeaderParams(final Request request) { + if (xTwilioWebhookEnabled != null) { - request.addHeaderParam( - "X-Twilio-Webhook-Enabled", - xTwilioWebhookEnabled.toString() - ); + Serializer.toString(request, "X-Twilio-Webhook-Enabled", xTwilioWebhookEnabled, ParameterType.HEADER); } + } } diff --git a/src/main/java/com/twilio/rest/chat/v2/service/channel/Message.java b/src/main/java/com/twilio/rest/chat/v2/service/channel/Message.java index e0dcdaae58..707e47f5f8 100644 --- a/src/main/java/com/twilio/rest/chat/v2/service/channel/Message.java +++ b/src/main/java/com/twilio/rest/chat/v2/service/channel/Message.java @@ -18,78 +18,112 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; -import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Message extends Resource { - private static final long serialVersionUID = 210901647084119L; - public static MessageCreator creator( - final String pathServiceSid, - final String pathChannelSid - ) { - return new MessageCreator(pathServiceSid, pathChannelSid); + public static MessageCreator creator(final String pathserviceSid, final String pathchannelSid) { + return new MessageCreator( + pathserviceSid, pathchannelSid + ); } - public static MessageDeleter deleter( - final String pathServiceSid, - final String pathChannelSid, - final String pathSid - ) { - return new MessageDeleter(pathServiceSid, pathChannelSid, pathSid); + + public static MessageDeleter deleter(final String pathserviceSid, final String pathchannelSid, final String pathsid) { + return new MessageDeleter( + pathserviceSid, pathchannelSid, pathsid + ); } - public static MessageFetcher fetcher( - final String pathServiceSid, - final String pathChannelSid, - final String pathSid - ) { - return new MessageFetcher(pathServiceSid, pathChannelSid, pathSid); + + public static MessageFetcher fetcher(final String pathserviceSid, final String pathchannelSid, final String pathsid) { + return new MessageFetcher( + pathserviceSid, pathchannelSid, pathsid + ); } - public static MessageReader reader( - final String pathServiceSid, - final String pathChannelSid - ) { - return new MessageReader(pathServiceSid, pathChannelSid); + + public static MessageReader reader(final String pathserviceSid, final String pathchannelSid) { + return new MessageReader( + pathserviceSid, pathchannelSid + ); } - public static MessageUpdater updater( - final String pathServiceSid, - final String pathChannelSid, - final String pathSid - ) { - return new MessageUpdater(pathServiceSid, pathChannelSid, pathSid); + + public static MessageUpdater updater(final String pathserviceSid, final String pathchannelSid, final String pathsid) { + return new MessageUpdater( + pathserviceSid, pathchannelSid, pathsid + ); } + + public enum WebhookEnabledType { + TRUE("true"), + FALSE("false"); + + private final String value; + + private WebhookEnabledType(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static WebhookEnabledType forValue(final String value) { + return Promoter.enumFromString(value, WebhookEnabledType.values()); + } + } + + public enum OrderType { + ASC("asc"), + DESC("desc"); + + private final String value; + + private OrderType(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static OrderType forValue(final String value) { + return Promoter.enumFromString(value, OrderType.values()); + } + } + + /** * Converts a JSON String into a Message object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Message object represented by the provided JSON */ - public static Message fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Message fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Message.class); @@ -104,14 +138,11 @@ public static Message fromJson( * Converts a JSON InputStream into a Message object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Message object represented by the provided JSON */ - public static Message fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Message fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Message.class); @@ -122,122 +153,89 @@ public static Message fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; + @Getter private final String attributes; - private final String serviceSid; - private final String to; + @Getter + private final String body; + @Getter private final String channelSid; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; - private final String lastUpdatedBy; - private final Boolean wasEdited; + @Getter private final String from; - private final String body; + @Getter private final Integer index; + @Getter + private final String lastUpdatedBy; + @Getter + private final Object media; + @Getter + private final String serviceSid; + @Getter + private final String sid; + @Getter + private final String to; + @Getter private final String type; - private final Map media; + @Getter private final URI url; + @Getter + private final Boolean wasEdited; @JsonCreator private Message( - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("attributes") final String attributes, - @JsonProperty("service_sid") final String serviceSid, - @JsonProperty("to") final String to, - @JsonProperty("channel_sid") final String channelSid, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("last_updated_by") final String lastUpdatedBy, - @JsonProperty("was_edited") final Boolean wasEdited, - @JsonProperty("from") final String from, - @JsonProperty("body") final String body, - @JsonProperty("index") final Integer index, - @JsonProperty("type") final String type, - @JsonProperty("media") final Map media, - @JsonProperty("url") final URI url + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("attributes") final String attributes, + @JsonProperty("body") final String body, + @JsonProperty("channel_sid") final String channelSid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("from") final String from, + @JsonProperty("index") final Integer index, + @JsonProperty("last_updated_by") final String lastUpdatedBy, + @JsonProperty("media") final Object media, + @JsonProperty("service_sid") final String serviceSid, + @JsonProperty("sid") final String sid, + @JsonProperty("to") final String to, + @JsonProperty("type") final String type, + @JsonProperty("url") final URI url, + @JsonProperty("was_edited") final Boolean wasEdited ) { - this.sid = sid; this.accountSid = accountSid; this.attributes = attributes; - this.serviceSid = serviceSid; - this.to = to; + this.body = body; this.channelSid = channelSid; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); - this.lastUpdatedBy = lastUpdatedBy; - this.wasEdited = wasEdited; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.from = from; - this.body = body; this.index = index; - this.type = type; + this.lastUpdatedBy = lastUpdatedBy; this.media = media; + this.serviceSid = serviceSid; + this.sid = sid; + this.to = to; + this.type = type; this.url = url; - } - - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getAttributes() { - return this.attributes; - } - - public final String getServiceSid() { - return this.serviceSid; - } - - public final String getTo() { - return this.to; - } - - public final String getChannelSid() { - return this.channelSid; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final String getLastUpdatedBy() { - return this.lastUpdatedBy; - } - - public final Boolean getWasEdited() { - return this.wasEdited; - } - - public final String getFrom() { - return this.from; - } - - public final String getBody() { - return this.body; - } - - public final Integer getIndex() { - return this.index; - } - - public final String getType() { - return this.type; - } - - public final Map getMedia() { - return this.media; - } - - public final URI getUrl() { - return this.url; + this.wasEdited = wasEdited; } @Override @@ -251,86 +249,48 @@ public boolean equals(final Object o) { } Message other = (Message) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(attributes, other.attributes) && - Objects.equals(serviceSid, other.serviceSid) && - Objects.equals(to, other.to) && - Objects.equals(channelSid, other.channelSid) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(lastUpdatedBy, other.lastUpdatedBy) && - Objects.equals(wasEdited, other.wasEdited) && - Objects.equals(from, other.from) && - Objects.equals(body, other.body) && - Objects.equals(index, other.index) && - Objects.equals(type, other.type) && - Objects.equals(media, other.media) && - Objects.equals(url, other.url) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(attributes, other.attributes) && + Objects.equals(body, other.body) && + Objects.equals(channelSid, other.channelSid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(from, other.from) && + Objects.equals(index, other.index) && + Objects.equals(lastUpdatedBy, other.lastUpdatedBy) && + Objects.equals(media, other.media) && + Objects.equals(serviceSid, other.serviceSid) && + Objects.equals(sid, other.sid) && + Objects.equals(to, other.to) && + Objects.equals(type, other.type) && + Objects.equals(url, other.url) && + Objects.equals(wasEdited, other.wasEdited) ); } @Override public int hashCode() { return Objects.hash( - sid, - accountSid, - attributes, - serviceSid, - to, - channelSid, - dateCreated, - dateUpdated, - lastUpdatedBy, - wasEdited, - from, - body, - index, - type, - media, - url + accountSid, + attributes, + body, + channelSid, + dateCreated, + dateUpdated, + from, + index, + lastUpdatedBy, + media, + serviceSid, + sid, + to, + type, + url, + wasEdited ); } - public enum WebhookEnabledType { - TRUE("true"), - FALSE("false"); - - private final String value; - - private WebhookEnabledType(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static WebhookEnabledType forValue(final String value) { - return Promoter.enumFromString(value, WebhookEnabledType.values()); - } - } - - public enum OrderType { - ASC("asc"), - DESC("desc"); - - private final String value; - - private OrderType(final String value) { - this.value = value; - } - public String toString() { - return value; - } - - @JsonCreator - public static OrderType forValue(final String value) { - return Promoter.enumFromString(value, OrderType.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/chat/v2/service/channel/MessageCreator.java b/src/main/java/com/twilio/rest/chat/v2/service/channel/MessageCreator.java index 577e6a6922..58981db99b 100644 --- a/src/main/java/com/twilio/rest/chat/v2/service/channel/MessageCreator.java +++ b/src/main/java/com/twilio/rest/chat/v2/service/channel/MessageCreator.java @@ -14,8 +14,11 @@ package com.twilio.rest.chat.v2.service.channel; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -24,12 +27,13 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.time.ZonedDateTime; public class MessageCreator extends Creator { - private String pathServiceSid; - private String pathChannelSid; + private String pathserviceSid; + private String pathchannelSid; private Message.WebhookEnabledType xTwilioWebhookEnabled; private String from; private String attributes; @@ -39,95 +43,89 @@ public class MessageCreator extends Creator { private String body; private String mediaSid; - public MessageCreator( - final String pathServiceSid, - final String pathChannelSid - ) { - this.pathServiceSid = pathServiceSid; - this.pathChannelSid = pathChannelSid; + public MessageCreator(final String pathserviceSid, final String pathchannelSid) { + this.pathserviceSid = pathserviceSid; + this.pathchannelSid = pathchannelSid; } - public MessageCreator setXTwilioWebhookEnabled( - final Message.WebhookEnabledType xTwilioWebhookEnabled - ) { - this.xTwilioWebhookEnabled = xTwilioWebhookEnabled; - return this; - } public MessageCreator setFrom(final String from) { this.from = from; return this; } + public MessageCreator setAttributes(final String attributes) { this.attributes = attributes; return this; } + public MessageCreator setDateCreated(final ZonedDateTime dateCreated) { this.dateCreated = dateCreated; return this; } + public MessageCreator setDateUpdated(final ZonedDateTime dateUpdated) { this.dateUpdated = dateUpdated; return this; } + public MessageCreator setLastUpdatedBy(final String lastUpdatedBy) { this.lastUpdatedBy = lastUpdatedBy; return this; } + public MessageCreator setBody(final String body) { this.body = body; return this; } + public MessageCreator setMediaSid(final String mediaSid) { this.mediaSid = mediaSid; return this; } + + public MessageCreator setXTwilioWebhookEnabled(final Message.WebhookEnabledType xTwilioWebhookEnabled) { + this.xTwilioWebhookEnabled = xTwilioWebhookEnabled; + return this; + } + + @Override public Message create(final TwilioRestClient client) { - String path = - "/v2/Services/{ServiceSid}/Channels/{ChannelSid}/Messages"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = - path.replace( - "{" + "ChannelSid" + "}", - this.pathChannelSid.toString() - ); + String path = "/v2/Services/{ServiceSid}/Channels/{ChannelSid}/Messages"; + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "ChannelSid" + "}", this.pathchannelSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.CHAT.toString(), - path + HttpMethod.POST, + Domains.CHAT.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); - addPostParams(request); addHeaderParams(request); + addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Message creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("Message creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -136,41 +134,49 @@ public Message create(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (from != null) { - request.addPostParam("From", from); + Serializer.toString(request, "From", from, ParameterType.URLENCODED); } + + if (attributes != null) { - request.addPostParam("Attributes", attributes); + Serializer.toString(request, "Attributes", attributes, ParameterType.URLENCODED); } + + if (dateCreated != null) { - request.addPostParam( - "DateCreated", - dateCreated.toInstant().toString() - ); + Serializer.toString(request, "DateCreated", dateCreated, ParameterType.URLENCODED); } + + if (dateUpdated != null) { - request.addPostParam( - "DateUpdated", - dateUpdated.toInstant().toString() - ); + Serializer.toString(request, "DateUpdated", dateUpdated, ParameterType.URLENCODED); } + + if (lastUpdatedBy != null) { - request.addPostParam("LastUpdatedBy", lastUpdatedBy); + Serializer.toString(request, "LastUpdatedBy", lastUpdatedBy, ParameterType.URLENCODED); } + + if (body != null) { - request.addPostParam("Body", body); + Serializer.toString(request, "Body", body, ParameterType.URLENCODED); } + + if (mediaSid != null) { - request.addPostParam("MediaSid", mediaSid); + Serializer.toString(request, "MediaSid", mediaSid, ParameterType.URLENCODED); } + + } private void addHeaderParams(final Request request) { + if (xTwilioWebhookEnabled != null) { - request.addHeaderParam( - "X-Twilio-Webhook-Enabled", - xTwilioWebhookEnabled.toString() - ); + Serializer.toString(request, "X-Twilio-Webhook-Enabled", xTwilioWebhookEnabled, ParameterType.HEADER); } + } } diff --git a/src/main/java/com/twilio/rest/chat/v2/service/channel/MessageDeleter.java b/src/main/java/com/twilio/rest/chat/v2/service/channel/MessageDeleter.java index 6fdfe0fab3..4ec25ced64 100644 --- a/src/main/java/com/twilio/rest/chat/v2/service/channel/MessageDeleter.java +++ b/src/main/java/com/twilio/rest/chat/v2/service/channel/MessageDeleter.java @@ -15,7 +15,8 @@ package com.twilio.rest.chat.v2.service.channel; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,68 +28,52 @@ public class MessageDeleter extends Deleter { - private String pathServiceSid; - private String pathChannelSid; - private String pathSid; + private String pathserviceSid; + private String pathchannelSid; + private String pathsid; private Message.WebhookEnabledType xTwilioWebhookEnabled; - public MessageDeleter( - final String pathServiceSid, - final String pathChannelSid, - final String pathSid - ) { - this.pathServiceSid = pathServiceSid; - this.pathChannelSid = pathChannelSid; - this.pathSid = pathSid; + public MessageDeleter(final String pathserviceSid, final String pathchannelSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathchannelSid = pathchannelSid; + this.pathsid = pathsid; } - public MessageDeleter setXTwilioWebhookEnabled( - final Message.WebhookEnabledType xTwilioWebhookEnabled - ) { + + public MessageDeleter setXTwilioWebhookEnabled(final Message.WebhookEnabledType xTwilioWebhookEnabled) { this.xTwilioWebhookEnabled = xTwilioWebhookEnabled; return this; } + @Override public boolean delete(final TwilioRestClient client) { - String path = - "/v2/Services/{ServiceSid}/Channels/{ChannelSid}/Messages/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = - path.replace( - "{" + "ChannelSid" + "}", - this.pathChannelSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/v2/Services/{ServiceSid}/Channels/{ChannelSid}/Messages/{Sid}"; + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "ChannelSid" + "}", this.pathchannelSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.CHAT.toString(), - path + HttpMethod.DELETE, + Domains.CHAT.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addHeaderParams(request); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Message delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("Message delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -96,11 +81,10 @@ public boolean delete(final TwilioRestClient client) { } private void addHeaderParams(final Request request) { + if (xTwilioWebhookEnabled != null) { - request.addHeaderParam( - "X-Twilio-Webhook-Enabled", - xTwilioWebhookEnabled.toString() - ); + Serializer.toString(request, "X-Twilio-Webhook-Enabled", xTwilioWebhookEnabled, ParameterType.HEADER); } + } } diff --git a/src/main/java/com/twilio/rest/chat/v2/service/channel/MessageFetcher.java b/src/main/java/com/twilio/rest/chat/v2/service/channel/MessageFetcher.java index 6b8ec66cc5..cf90cdfd12 100644 --- a/src/main/java/com/twilio/rest/chat/v2/service/channel/MessageFetcher.java +++ b/src/main/java/com/twilio/rest/chat/v2/service/channel/MessageFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.chat.v2.service.channel; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,63 +26,47 @@ public class MessageFetcher extends Fetcher { - private String pathServiceSid; - private String pathChannelSid; - private String pathSid; + private String pathserviceSid; + private String pathchannelSid; + private String pathsid; - public MessageFetcher( - final String pathServiceSid, - final String pathChannelSid, - final String pathSid - ) { - this.pathServiceSid = pathServiceSid; - this.pathChannelSid = pathChannelSid; - this.pathSid = pathSid; + public MessageFetcher(final String pathserviceSid, final String pathchannelSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathchannelSid = pathchannelSid; + this.pathsid = pathsid; } + @Override public Message fetch(final TwilioRestClient client) { - String path = - "/v2/Services/{ServiceSid}/Channels/{ChannelSid}/Messages/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = - path.replace( - "{" + "ChannelSid" + "}", - this.pathChannelSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/v2/Services/{ServiceSid}/Channels/{ChannelSid}/Messages/{Sid}"; + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "ChannelSid" + "}", this.pathchannelSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.CHAT.toString(), - path + HttpMethod.GET, + Domains.CHAT.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Message fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Message fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Message.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/chat/v2/service/channel/MessageReader.java b/src/main/java/com/twilio/rest/chat/v2/service/channel/MessageReader.java index f83caf56de..c242aa3041 100644 --- a/src/main/java/com/twilio/rest/chat/v2/service/channel/MessageReader.java +++ b/src/main/java/com/twilio/rest/chat/v2/service/channel/MessageReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,135 +30,103 @@ public class MessageReader extends Reader { - private String pathServiceSid; - private String pathChannelSid; + private String pathserviceSid; + private String pathchannelSid; private Message.OrderType order; private Long pageSize; - public MessageReader( - final String pathServiceSid, - final String pathChannelSid - ) { - this.pathServiceSid = pathServiceSid; - this.pathChannelSid = pathChannelSid; + public MessageReader(final String pathserviceSid, final String pathchannelSid) { + this.pathserviceSid = pathserviceSid; + this.pathchannelSid = pathchannelSid; } + public MessageReader setOrder(final Message.OrderType order) { this.order = order; return this; } + public MessageReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { - String path = - "/v2/Services/{ServiceSid}/Channels/{ChannelSid}/Messages"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = - path.replace( - "{" + "ChannelSid" + "}", - this.pathChannelSid.toString() - ); + + String path = "/v2/Services/{ServiceSid}/Channels/{ChannelSid}/Messages"; + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "ChannelSid" + "}", this.pathchannelSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.CHAT.toString(), - path + HttpMethod.GET, + Domains.CHAT.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Message read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Message read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "messages", - response.getContent(), - Message.class, - client.getObjectMapper() - ); + "messages", + response.getContent(), + Message.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.CHAT.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.CHAT.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (order != null) { - request.addQueryParam("Order", order.toString()); + Serializer.toString(request, "Order", order, ParameterType.QUERY); } + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/chat/v2/service/channel/MessageUpdater.java b/src/main/java/com/twilio/rest/chat/v2/service/channel/MessageUpdater.java index 2aec9dd36c..c27fc88dd3 100644 --- a/src/main/java/com/twilio/rest/chat/v2/service/channel/MessageUpdater.java +++ b/src/main/java/com/twilio/rest/chat/v2/service/channel/MessageUpdater.java @@ -16,6 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -24,13 +26,13 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.time.ZonedDateTime; public class MessageUpdater extends Updater { - - private String pathServiceSid; - private String pathChannelSid; - private String pathSid; + private String pathserviceSid; + private String pathchannelSid; + private String pathsid; private Message.WebhookEnabledType xTwilioWebhookEnabled; private String body; private String attributes; @@ -39,93 +41,85 @@ public class MessageUpdater extends Updater { private String lastUpdatedBy; private String from; - public MessageUpdater( - final String pathServiceSid, - final String pathChannelSid, - final String pathSid - ) { - this.pathServiceSid = pathServiceSid; - this.pathChannelSid = pathChannelSid; - this.pathSid = pathSid; + public MessageUpdater(final String pathserviceSid, final String pathchannelSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathchannelSid = pathchannelSid; + this.pathsid = pathsid; } - public MessageUpdater setXTwilioWebhookEnabled( - final Message.WebhookEnabledType xTwilioWebhookEnabled - ) { - this.xTwilioWebhookEnabled = xTwilioWebhookEnabled; - return this; - } public MessageUpdater setBody(final String body) { this.body = body; return this; } + public MessageUpdater setAttributes(final String attributes) { this.attributes = attributes; return this; } + public MessageUpdater setDateCreated(final ZonedDateTime dateCreated) { this.dateCreated = dateCreated; return this; } + public MessageUpdater setDateUpdated(final ZonedDateTime dateUpdated) { this.dateUpdated = dateUpdated; return this; } + public MessageUpdater setLastUpdatedBy(final String lastUpdatedBy) { this.lastUpdatedBy = lastUpdatedBy; return this; } + public MessageUpdater setFrom(final String from) { this.from = from; return this; } + + public MessageUpdater setXTwilioWebhookEnabled(final Message.WebhookEnabledType xTwilioWebhookEnabled) { + this.xTwilioWebhookEnabled = xTwilioWebhookEnabled; + return this; + } + + @Override public Message update(final TwilioRestClient client) { - String path = - "/v2/Services/{ServiceSid}/Channels/{ChannelSid}/Messages/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = - path.replace( - "{" + "ChannelSid" + "}", - this.pathChannelSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/v2/Services/{ServiceSid}/Channels/{ChannelSid}/Messages/{Sid}"; + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "ChannelSid" + "}", this.pathchannelSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.CHAT.toString(), - path + HttpMethod.POST, + Domains.CHAT.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); - addPostParams(request); addHeaderParams(request); + addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Message update failed: Unable to connect to server" - ); + throw new ApiConnectionException("Message update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -134,38 +128,44 @@ public Message update(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (body != null) { - request.addPostParam("Body", body); + Serializer.toString(request, "Body", body, ParameterType.URLENCODED); } + + if (attributes != null) { - request.addPostParam("Attributes", attributes); + Serializer.toString(request, "Attributes", attributes, ParameterType.URLENCODED); } + + if (dateCreated != null) { - request.addPostParam( - "DateCreated", - dateCreated.toInstant().toString() - ); + Serializer.toString(request, "DateCreated", dateCreated, ParameterType.URLENCODED); } + + if (dateUpdated != null) { - request.addPostParam( - "DateUpdated", - dateUpdated.toInstant().toString() - ); + Serializer.toString(request, "DateUpdated", dateUpdated, ParameterType.URLENCODED); } + + if (lastUpdatedBy != null) { - request.addPostParam("LastUpdatedBy", lastUpdatedBy); + Serializer.toString(request, "LastUpdatedBy", lastUpdatedBy, ParameterType.URLENCODED); } + + if (from != null) { - request.addPostParam("From", from); + Serializer.toString(request, "From", from, ParameterType.URLENCODED); } + + } private void addHeaderParams(final Request request) { + if (xTwilioWebhookEnabled != null) { - request.addHeaderParam( - "X-Twilio-Webhook-Enabled", - xTwilioWebhookEnabled.toString() - ); + Serializer.toString(request, "X-Twilio-Webhook-Enabled", xTwilioWebhookEnabled, ParameterType.HEADER); } + } } diff --git a/src/main/java/com/twilio/rest/chat/v2/service/channel/Webhook.java b/src/main/java/com/twilio/rest/chat/v2/service/channel/Webhook.java index 969a28cc11..e4b48061d1 100644 --- a/src/main/java/com/twilio/rest/chat/v2/service/channel/Webhook.java +++ b/src/main/java/com/twilio/rest/chat/v2/service/channel/Webhook.java @@ -18,79 +18,113 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; -import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Webhook extends Resource { - private static final long serialVersionUID = 201752828404640L; - public static WebhookCreator creator( - final String pathServiceSid, - final String pathChannelSid, - final Webhook.Type type - ) { - return new WebhookCreator(pathServiceSid, pathChannelSid, type); + public static WebhookCreator creator(final String pathserviceSid, final String pathchannelSid, final Webhook.Type type) { + return new WebhookCreator( + pathserviceSid, pathchannelSid, type + ); } - public static WebhookDeleter deleter( - final String pathServiceSid, - final String pathChannelSid, - final String pathSid - ) { - return new WebhookDeleter(pathServiceSid, pathChannelSid, pathSid); + + public static WebhookDeleter deleter(final String pathserviceSid, final String pathchannelSid, final String pathsid) { + return new WebhookDeleter( + pathserviceSid, pathchannelSid, pathsid + ); } - public static WebhookFetcher fetcher( - final String pathServiceSid, - final String pathChannelSid, - final String pathSid - ) { - return new WebhookFetcher(pathServiceSid, pathChannelSid, pathSid); + + public static WebhookFetcher fetcher(final String pathserviceSid, final String pathchannelSid, final String pathsid) { + return new WebhookFetcher( + pathserviceSid, pathchannelSid, pathsid + ); } - public static WebhookReader reader( - final String pathServiceSid, - final String pathChannelSid - ) { - return new WebhookReader(pathServiceSid, pathChannelSid); + + public static WebhookReader reader(final String pathserviceSid, final String pathchannelSid) { + return new WebhookReader( + pathserviceSid, pathchannelSid + ); } - public static WebhookUpdater updater( - final String pathServiceSid, - final String pathChannelSid, - final String pathSid - ) { - return new WebhookUpdater(pathServiceSid, pathChannelSid, pathSid); + + public static WebhookUpdater updater(final String pathserviceSid, final String pathchannelSid, final String pathsid) { + return new WebhookUpdater( + pathserviceSid, pathchannelSid, pathsid + ); } + + public enum Type { + WEBHOOK("webhook"), + TRIGGER("trigger"), + STUDIO("studio"); + + private final String value; + + private Type(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static Type forValue(final String value) { + return Promoter.enumFromString(value, Type.values()); + } + } + + public enum Method { + GET("GET"), + POST("POST"); + + private final String value; + + private Method(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static Method forValue(final String value) { + return Promoter.enumFromString(value, Method.values()); + } + } + + /** * Converts a JSON String into a Webhook object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Webhook object represented by the provided JSON */ - public static Webhook fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Webhook fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Webhook.class); @@ -105,14 +139,11 @@ public static Webhook fromJson( * Converts a JSON InputStream into a Webhook object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Webhook object represented by the provided JSON */ - public static Webhook fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Webhook fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Webhook.class); @@ -123,73 +154,61 @@ public static Webhook fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String serviceSid; + @Getter private final String channelSid; - private final String type; - private final URI url; - private final Map configuration; + @Getter + private final Object configuration; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; + @Getter + private final String serviceSid; + @Getter + private final String sid; + @Getter + private final String type; + @Getter + private final URI url; @JsonCreator private Webhook( - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("service_sid") final String serviceSid, - @JsonProperty("channel_sid") final String channelSid, - @JsonProperty("type") final String type, - @JsonProperty("url") final URI url, - @JsonProperty("configuration") final Map configuration, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("channel_sid") final String channelSid, + @JsonProperty("configuration") final Object configuration, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("service_sid") final String serviceSid, + @JsonProperty("sid") final String sid, + @JsonProperty("type") final String type, + @JsonProperty("url") final URI url ) { - this.sid = sid; this.accountSid = accountSid; - this.serviceSid = serviceSid; this.channelSid = channelSid; + this.configuration = configuration; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; + this.serviceSid = serviceSid; + this.sid = sid; this.type = type; this.url = url; - this.configuration = configuration; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); - } - - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getServiceSid() { - return this.serviceSid; - } - - public final String getChannelSid() { - return this.channelSid; - } - - public final String getType() { - return this.type; - } - - public final URI getUrl() { - return this.url; - } - - public final Map getConfiguration() { - return this.configuration; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; } @Override @@ -203,73 +222,34 @@ public boolean equals(final Object o) { } Webhook other = (Webhook) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(serviceSid, other.serviceSid) && - Objects.equals(channelSid, other.channelSid) && - Objects.equals(type, other.type) && - Objects.equals(url, other.url) && - Objects.equals(configuration, other.configuration) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(channelSid, other.channelSid) && + Objects.equals(configuration, other.configuration) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(serviceSid, other.serviceSid) && + Objects.equals(sid, other.sid) && + Objects.equals(type, other.type) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - sid, - accountSid, - serviceSid, - channelSid, - type, - url, - configuration, - dateCreated, - dateUpdated + accountSid, + channelSid, + configuration, + dateCreated, + dateUpdated, + serviceSid, + sid, + type, + url ); } - public enum Type { - WEBHOOK("webhook"), - TRIGGER("trigger"), - STUDIO("studio"); - - private final String value; - - private Type(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static Type forValue(final String value) { - return Promoter.enumFromString(value, Type.values()); - } - } - - public enum Method { - GET("GET"), - POST("POST"); - - private final String value; - - private Method(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - @JsonCreator - public static Method forValue(final String value) { - return Promoter.enumFromString(value, Method.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/chat/v2/service/channel/WebhookCreator.java b/src/main/java/com/twilio/rest/chat/v2/service/channel/WebhookCreator.java index 54e777f255..ea44f0c248 100644 --- a/src/main/java/com/twilio/rest/chat/v2/service/channel/WebhookCreator.java +++ b/src/main/java/com/twilio/rest/chat/v2/service/channel/WebhookCreator.java @@ -14,9 +14,12 @@ package com.twilio.rest.chat.v2.service.channel; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; import com.twilio.converter.Promoter; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,13 +28,13 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -import java.util.List; + import java.util.List; public class WebhookCreator extends Creator { - private String pathServiceSid; - private String pathChannelSid; + private String pathserviceSid; + private String pathchannelSid; private Webhook.Type type; private String configurationUrl; private Webhook.Method configurationMethod; @@ -40,116 +43,89 @@ public class WebhookCreator extends Creator { private String configurationFlowSid; private Integer configurationRetryCount; - public WebhookCreator( - final String pathServiceSid, - final String pathChannelSid, - final Webhook.Type type - ) { - this.pathServiceSid = pathServiceSid; - this.pathChannelSid = pathChannelSid; + public WebhookCreator(final String pathserviceSid, final String pathchannelSid, final Webhook.Type type) { + this.pathserviceSid = pathserviceSid; + this.pathchannelSid = pathchannelSid; this.type = type; } + public WebhookCreator setType(final Webhook.Type type) { this.type = type; return this; } + public WebhookCreator setConfigurationUrl(final String configurationUrl) { this.configurationUrl = configurationUrl; return this; } - public WebhookCreator setConfigurationMethod( - final Webhook.Method configurationMethod - ) { + + public WebhookCreator setConfigurationMethod(final Webhook.Method configurationMethod) { this.configurationMethod = configurationMethod; return this; } - public WebhookCreator setConfigurationFilters( - final List configurationFilters - ) { + + public WebhookCreator setConfigurationFilters(final List configurationFilters) { this.configurationFilters = configurationFilters; return this; } - public WebhookCreator setConfigurationFilters( - final String configurationFilters - ) { - return setConfigurationFilters( - Promoter.listOfOne(configurationFilters) - ); + public WebhookCreator setConfigurationFilters(final String configurationFilters) { + return setConfigurationFilters(Promoter.listOfOne(configurationFilters)); } - public WebhookCreator setConfigurationTriggers( - final List configurationTriggers - ) { + public WebhookCreator setConfigurationTriggers(final List configurationTriggers) { this.configurationTriggers = configurationTriggers; return this; } - public WebhookCreator setConfigurationTriggers( - final String configurationTriggers - ) { - return setConfigurationTriggers( - Promoter.listOfOne(configurationTriggers) - ); + public WebhookCreator setConfigurationTriggers(final String configurationTriggers) { + return setConfigurationTriggers(Promoter.listOfOne(configurationTriggers)); } - public WebhookCreator setConfigurationFlowSid( - final String configurationFlowSid - ) { + public WebhookCreator setConfigurationFlowSid(final String configurationFlowSid) { this.configurationFlowSid = configurationFlowSid; return this; } - public WebhookCreator setConfigurationRetryCount( - final Integer configurationRetryCount - ) { + + public WebhookCreator setConfigurationRetryCount(final Integer configurationRetryCount) { this.configurationRetryCount = configurationRetryCount; return this; } + @Override public Webhook create(final TwilioRestClient client) { - String path = - "/v2/Services/{ServiceSid}/Channels/{ChannelSid}/Webhooks"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = - path.replace( - "{" + "ChannelSid" + "}", - this.pathChannelSid.toString() - ); - path = path.replace("{" + "Type" + "}", this.type.toString()); + String path = "/v2/Services/{ServiceSid}/Channels/{ChannelSid}/Webhooks"; + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "ChannelSid" + "}", this.pathchannelSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.CHAT.toString(), - path + HttpMethod.POST, + Domains.CHAT.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Webhook creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("Webhook creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -158,36 +134,45 @@ public Webhook create(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (type != null) { - request.addPostParam("Type", type.toString()); + Serializer.toString(request, "Type", type, ParameterType.URLENCODED); } + + if (configurationUrl != null) { - request.addPostParam("Configuration.Url", configurationUrl); + Serializer.toString(request, "Configuration.Url", configurationUrl, ParameterType.URLENCODED); } + + if (configurationMethod != null) { - request.addPostParam( - "Configuration.Method", - configurationMethod.toString() - ); + Serializer.toString(request, "Configuration.Method", configurationMethod, ParameterType.URLENCODED); } + + if (configurationFilters != null) { - for (String prop : configurationFilters) { - request.addPostParam("Configuration.Filters", prop); + for (String param : configurationFilters) { + Serializer.toString(request, "Configuration.Filters", param, ParameterType.URLENCODED); } } + + if (configurationTriggers != null) { - for (String prop : configurationTriggers) { - request.addPostParam("Configuration.Triggers", prop); + for (String param : configurationTriggers) { + Serializer.toString(request, "Configuration.Triggers", param, ParameterType.URLENCODED); } } + + if (configurationFlowSid != null) { - request.addPostParam("Configuration.FlowSid", configurationFlowSid); + Serializer.toString(request, "Configuration.FlowSid", configurationFlowSid, ParameterType.URLENCODED); } + + if (configurationRetryCount != null) { - request.addPostParam( - "Configuration.RetryCount", - configurationRetryCount.toString() - ); + Serializer.toString(request, "Configuration.RetryCount", configurationRetryCount, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/chat/v2/service/channel/WebhookDeleter.java b/src/main/java/com/twilio/rest/chat/v2/service/channel/WebhookDeleter.java index c18c9a9582..72ee27596d 100644 --- a/src/main/java/com/twilio/rest/chat/v2/service/channel/WebhookDeleter.java +++ b/src/main/java/com/twilio/rest/chat/v2/service/channel/WebhookDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.chat.v2.service.channel; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,59 +26,44 @@ public class WebhookDeleter extends Deleter { - private String pathServiceSid; - private String pathChannelSid; - private String pathSid; + private String pathserviceSid; + private String pathchannelSid; + private String pathsid; - public WebhookDeleter( - final String pathServiceSid, - final String pathChannelSid, - final String pathSid - ) { - this.pathServiceSid = pathServiceSid; - this.pathChannelSid = pathChannelSid; - this.pathSid = pathSid; + public WebhookDeleter(final String pathserviceSid, final String pathchannelSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathchannelSid = pathchannelSid; + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { - String path = - "/v2/Services/{ServiceSid}/Channels/{ChannelSid}/Webhooks/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = - path.replace( - "{" + "ChannelSid" + "}", - this.pathChannelSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/v2/Services/{ServiceSid}/Channels/{ChannelSid}/Webhooks/{Sid}"; + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "ChannelSid" + "}", this.pathchannelSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.CHAT.toString(), - path + HttpMethod.DELETE, + Domains.CHAT.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Webhook delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("Webhook delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/chat/v2/service/channel/WebhookFetcher.java b/src/main/java/com/twilio/rest/chat/v2/service/channel/WebhookFetcher.java index 6f9c27637a..50ab60320d 100644 --- a/src/main/java/com/twilio/rest/chat/v2/service/channel/WebhookFetcher.java +++ b/src/main/java/com/twilio/rest/chat/v2/service/channel/WebhookFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.chat.v2.service.channel; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,63 +26,47 @@ public class WebhookFetcher extends Fetcher { - private String pathServiceSid; - private String pathChannelSid; - private String pathSid; + private String pathserviceSid; + private String pathchannelSid; + private String pathsid; - public WebhookFetcher( - final String pathServiceSid, - final String pathChannelSid, - final String pathSid - ) { - this.pathServiceSid = pathServiceSid; - this.pathChannelSid = pathChannelSid; - this.pathSid = pathSid; + public WebhookFetcher(final String pathserviceSid, final String pathchannelSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathchannelSid = pathchannelSid; + this.pathsid = pathsid; } + @Override public Webhook fetch(final TwilioRestClient client) { - String path = - "/v2/Services/{ServiceSid}/Channels/{ChannelSid}/Webhooks/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = - path.replace( - "{" + "ChannelSid" + "}", - this.pathChannelSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/v2/Services/{ServiceSid}/Channels/{ChannelSid}/Webhooks/{Sid}"; + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "ChannelSid" + "}", this.pathchannelSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.CHAT.toString(), - path + HttpMethod.GET, + Domains.CHAT.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Webhook fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Webhook fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Webhook.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/chat/v2/service/channel/WebhookReader.java b/src/main/java/com/twilio/rest/chat/v2/service/channel/WebhookReader.java index f8c93f1d3f..2f23650b5e 100644 --- a/src/main/java/com/twilio/rest/chat/v2/service/channel/WebhookReader.java +++ b/src/main/java/com/twilio/rest/chat/v2/service/channel/WebhookReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,126 +30,91 @@ public class WebhookReader extends Reader { - private String pathServiceSid; - private String pathChannelSid; + private String pathserviceSid; + private String pathchannelSid; private Long pageSize; - public WebhookReader( - final String pathServiceSid, - final String pathChannelSid - ) { - this.pathServiceSid = pathServiceSid; - this.pathChannelSid = pathChannelSid; + public WebhookReader(final String pathserviceSid, final String pathchannelSid) { + this.pathserviceSid = pathserviceSid; + this.pathchannelSid = pathchannelSid; } + public WebhookReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { - String path = - "/v2/Services/{ServiceSid}/Channels/{ChannelSid}/Webhooks"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = - path.replace( - "{" + "ChannelSid" + "}", - this.pathChannelSid.toString() - ); + + String path = "/v2/Services/{ServiceSid}/Channels/{ChannelSid}/Webhooks"; + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "ChannelSid" + "}", this.pathchannelSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.CHAT.toString(), - path + HttpMethod.GET, + Domains.CHAT.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Webhook read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Webhook read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "webhooks", - response.getContent(), - Webhook.class, - client.getObjectMapper() - ); + "webhooks", + response.getContent(), + Webhook.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.CHAT.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.CHAT.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/chat/v2/service/channel/WebhookUpdater.java b/src/main/java/com/twilio/rest/chat/v2/service/channel/WebhookUpdater.java index 357f924a24..85a3058af6 100644 --- a/src/main/java/com/twilio/rest/chat/v2/service/channel/WebhookUpdater.java +++ b/src/main/java/com/twilio/rest/chat/v2/service/channel/WebhookUpdater.java @@ -16,7 +16,9 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; import com.twilio.converter.Promoter; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,13 +27,13 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.util.List; public class WebhookUpdater extends Updater { - - private String pathServiceSid; - private String pathChannelSid; - private String pathSid; + private String pathserviceSid; + private String pathchannelSid; + private String pathsid; private String configurationUrl; private Webhook.Method configurationMethod; private List configurationFilters; @@ -39,111 +41,84 @@ public class WebhookUpdater extends Updater { private String configurationFlowSid; private Integer configurationRetryCount; - public WebhookUpdater( - final String pathServiceSid, - final String pathChannelSid, - final String pathSid - ) { - this.pathServiceSid = pathServiceSid; - this.pathChannelSid = pathChannelSid; - this.pathSid = pathSid; + public WebhookUpdater(final String pathserviceSid, final String pathchannelSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathchannelSid = pathchannelSid; + this.pathsid = pathsid; } + public WebhookUpdater setConfigurationUrl(final String configurationUrl) { this.configurationUrl = configurationUrl; return this; } - public WebhookUpdater setConfigurationMethod( - final Webhook.Method configurationMethod - ) { + + public WebhookUpdater setConfigurationMethod(final Webhook.Method configurationMethod) { this.configurationMethod = configurationMethod; return this; } - public WebhookUpdater setConfigurationFilters( - final List configurationFilters - ) { + + public WebhookUpdater setConfigurationFilters(final List configurationFilters) { this.configurationFilters = configurationFilters; return this; } - public WebhookUpdater setConfigurationFilters( - final String configurationFilters - ) { - return setConfigurationFilters( - Promoter.listOfOne(configurationFilters) - ); + public WebhookUpdater setConfigurationFilters(final String configurationFilters) { + return setConfigurationFilters(Promoter.listOfOne(configurationFilters)); } - public WebhookUpdater setConfigurationTriggers( - final List configurationTriggers - ) { + public WebhookUpdater setConfigurationTriggers(final List configurationTriggers) { this.configurationTriggers = configurationTriggers; return this; } - public WebhookUpdater setConfigurationTriggers( - final String configurationTriggers - ) { - return setConfigurationTriggers( - Promoter.listOfOne(configurationTriggers) - ); + public WebhookUpdater setConfigurationTriggers(final String configurationTriggers) { + return setConfigurationTriggers(Promoter.listOfOne(configurationTriggers)); } - public WebhookUpdater setConfigurationFlowSid( - final String configurationFlowSid - ) { + public WebhookUpdater setConfigurationFlowSid(final String configurationFlowSid) { this.configurationFlowSid = configurationFlowSid; return this; } - public WebhookUpdater setConfigurationRetryCount( - final Integer configurationRetryCount - ) { + + public WebhookUpdater setConfigurationRetryCount(final Integer configurationRetryCount) { this.configurationRetryCount = configurationRetryCount; return this; } + @Override public Webhook update(final TwilioRestClient client) { - String path = - "/v2/Services/{ServiceSid}/Channels/{ChannelSid}/Webhooks/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = - path.replace( - "{" + "ChannelSid" + "}", - this.pathChannelSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/v2/Services/{ServiceSid}/Channels/{ChannelSid}/Webhooks/{Sid}"; + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "ChannelSid" + "}", this.pathchannelSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.CHAT.toString(), - path + HttpMethod.POST, + Domains.CHAT.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Webhook update failed: Unable to connect to server" - ); + throw new ApiConnectionException("Webhook update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -152,33 +127,40 @@ public Webhook update(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (configurationUrl != null) { - request.addPostParam("Configuration.Url", configurationUrl); + Serializer.toString(request, "Configuration.Url", configurationUrl, ParameterType.URLENCODED); } + + if (configurationMethod != null) { - request.addPostParam( - "Configuration.Method", - configurationMethod.toString() - ); + Serializer.toString(request, "Configuration.Method", configurationMethod, ParameterType.URLENCODED); } + + if (configurationFilters != null) { - for (String prop : configurationFilters) { - request.addPostParam("Configuration.Filters", prop); + for (String param : configurationFilters) { + Serializer.toString(request, "Configuration.Filters", param, ParameterType.URLENCODED); } } + + if (configurationTriggers != null) { - for (String prop : configurationTriggers) { - request.addPostParam("Configuration.Triggers", prop); + for (String param : configurationTriggers) { + Serializer.toString(request, "Configuration.Triggers", param, ParameterType.URLENCODED); } } + + if (configurationFlowSid != null) { - request.addPostParam("Configuration.FlowSid", configurationFlowSid); + Serializer.toString(request, "Configuration.FlowSid", configurationFlowSid, ParameterType.URLENCODED); } + + if (configurationRetryCount != null) { - request.addPostParam( - "Configuration.RetryCount", - configurationRetryCount.toString() - ); + Serializer.toString(request, "Configuration.RetryCount", configurationRetryCount, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/chat/v2/service/user/UserBinding.java b/src/main/java/com/twilio/rest/chat/v2/service/user/UserBinding.java index f95fefa538..b1a3ec229b 100644 --- a/src/main/java/com/twilio/rest/chat/v2/service/user/UserBinding.java +++ b/src/main/java/com/twilio/rest/chat/v2/service/user/UserBinding.java @@ -18,62 +18,80 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.List; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class UserBinding extends Resource { - private static final long serialVersionUID = 252068300768529L; - public static UserBindingDeleter deleter( - final String pathServiceSid, - final String pathUserSid, - final String pathSid - ) { - return new UserBindingDeleter(pathServiceSid, pathUserSid, pathSid); + public static UserBindingDeleter deleter(final String pathserviceSid, final String pathuserSid, final String pathsid) { + return new UserBindingDeleter( + pathserviceSid, pathuserSid, pathsid + ); } - public static UserBindingFetcher fetcher( - final String pathServiceSid, - final String pathUserSid, - final String pathSid - ) { - return new UserBindingFetcher(pathServiceSid, pathUserSid, pathSid); + + public static UserBindingFetcher fetcher(final String pathserviceSid, final String pathuserSid, final String pathsid) { + return new UserBindingFetcher( + pathserviceSid, pathuserSid, pathsid + ); } - public static UserBindingReader reader( - final String pathServiceSid, - final String pathUserSid - ) { - return new UserBindingReader(pathServiceSid, pathUserSid); + + public static UserBindingReader reader(final String pathserviceSid, final String pathuserSid) { + return new UserBindingReader( + pathserviceSid, pathuserSid + ); + } + + + public enum BindingType { + GCM("gcm"), + APN("apn"), + FCM("fcm"); + + private final String value; + + private BindingType(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static BindingType forValue(final String value) { + return Promoter.enumFromString(value, BindingType.values()); + } } + /** * Converts a JSON String into a UserBinding object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return UserBinding object represented by the provided JSON */ - public static UserBinding fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static UserBinding fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, UserBinding.class); @@ -88,14 +106,11 @@ public static UserBinding fromJson( * Converts a JSON InputStream into a UserBinding object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return UserBinding object represented by the provided JSON */ - public static UserBinding fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static UserBinding fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, UserBinding.class); @@ -106,94 +121,73 @@ public static UserBinding fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String serviceSid; + @Getter + private final UserBinding.BindingType bindingType; + @Getter + private final String credentialSid; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; + @Getter private final String endpoint; + @Getter private final String identity; - private final String userSid; - private final String credentialSid; - private final UserBinding.BindingType bindingType; + @Getter private final List messageTypes; + @Getter + private final String serviceSid; + @Getter + private final String sid; + @Getter private final URI url; + @Getter + private final String userSid; @JsonCreator private UserBinding( - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("service_sid") final String serviceSid, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("endpoint") final String endpoint, - @JsonProperty("identity") final String identity, - @JsonProperty("user_sid") final String userSid, - @JsonProperty("credential_sid") final String credentialSid, - @JsonProperty("binding_type") final UserBinding.BindingType bindingType, - @JsonProperty("message_types") final List messageTypes, - @JsonProperty("url") final URI url + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("binding_type") final UserBinding.BindingType bindingType, + @JsonProperty("credential_sid") final String credentialSid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("endpoint") final String endpoint, + @JsonProperty("identity") final String identity, + @JsonProperty("message_types") final List messageTypes, + @JsonProperty("service_sid") final String serviceSid, + @JsonProperty("sid") final String sid, + @JsonProperty("url") final URI url, + @JsonProperty("user_sid") final String userSid ) { - this.sid = sid; this.accountSid = accountSid; - this.serviceSid = serviceSid; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); + this.bindingType = bindingType; + this.credentialSid = credentialSid; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.endpoint = endpoint; this.identity = identity; - this.userSid = userSid; - this.credentialSid = credentialSid; - this.bindingType = bindingType; this.messageTypes = messageTypes; + this.serviceSid = serviceSid; + this.sid = sid; this.url = url; - } - - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getServiceSid() { - return this.serviceSid; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final String getEndpoint() { - return this.endpoint; - } - - public final String getIdentity() { - return this.identity; - } - - public final String getUserSid() { - return this.userSid; - } - - public final String getCredentialSid() { - return this.credentialSid; - } - - public final UserBinding.BindingType getBindingType() { - return this.bindingType; - } - - public final List getMessageTypes() { - return this.messageTypes; - } - - public final URI getUrl() { - return this.url; + this.userSid = userSid; } @Override @@ -207,59 +201,40 @@ public boolean equals(final Object o) { } UserBinding other = (UserBinding) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(serviceSid, other.serviceSid) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(endpoint, other.endpoint) && - Objects.equals(identity, other.identity) && - Objects.equals(userSid, other.userSid) && - Objects.equals(credentialSid, other.credentialSid) && - Objects.equals(bindingType, other.bindingType) && - Objects.equals(messageTypes, other.messageTypes) && - Objects.equals(url, other.url) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(bindingType, other.bindingType) && + Objects.equals(credentialSid, other.credentialSid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(endpoint, other.endpoint) && + Objects.equals(identity, other.identity) && + Objects.equals(messageTypes, other.messageTypes) && + Objects.equals(serviceSid, other.serviceSid) && + Objects.equals(sid, other.sid) && + Objects.equals(url, other.url) && + Objects.equals(userSid, other.userSid) ); } @Override public int hashCode() { return Objects.hash( - sid, - accountSid, - serviceSid, - dateCreated, - dateUpdated, - endpoint, - identity, - userSid, - credentialSid, - bindingType, - messageTypes, - url + accountSid, + bindingType, + credentialSid, + dateCreated, + dateUpdated, + endpoint, + identity, + messageTypes, + serviceSid, + sid, + url, + userSid ); } - public enum BindingType { - GCM("gcm"), - APN("apn"), - FCM("fcm"); - private final String value; - - private BindingType(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static BindingType forValue(final String value) { - return Promoter.enumFromString(value, BindingType.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/chat/v2/service/user/UserBindingDeleter.java b/src/main/java/com/twilio/rest/chat/v2/service/user/UserBindingDeleter.java index b791caaaaf..c33434c8bc 100644 --- a/src/main/java/com/twilio/rest/chat/v2/service/user/UserBindingDeleter.java +++ b/src/main/java/com/twilio/rest/chat/v2/service/user/UserBindingDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.chat.v2.service.user; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,55 +26,44 @@ public class UserBindingDeleter extends Deleter { - private String pathServiceSid; - private String pathUserSid; - private String pathSid; + private String pathserviceSid; + private String pathuserSid; + private String pathsid; - public UserBindingDeleter( - final String pathServiceSid, - final String pathUserSid, - final String pathSid - ) { - this.pathServiceSid = pathServiceSid; - this.pathUserSid = pathUserSid; - this.pathSid = pathSid; + public UserBindingDeleter(final String pathserviceSid, final String pathuserSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathuserSid = pathuserSid; + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { - String path = - "/v2/Services/{ServiceSid}/Users/{UserSid}/Bindings/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = path.replace("{" + "UserSid" + "}", this.pathUserSid.toString()); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/v2/Services/{ServiceSid}/Users/{UserSid}/Bindings/{Sid}"; + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "UserSid" + "}", this.pathuserSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.CHAT.toString(), - path + HttpMethod.DELETE, + Domains.CHAT.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "UserBinding delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("UserBinding delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/chat/v2/service/user/UserBindingFetcher.java b/src/main/java/com/twilio/rest/chat/v2/service/user/UserBindingFetcher.java index 637085e782..f82b841057 100644 --- a/src/main/java/com/twilio/rest/chat/v2/service/user/UserBindingFetcher.java +++ b/src/main/java/com/twilio/rest/chat/v2/service/user/UserBindingFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.chat.v2.service.user; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,62 +26,47 @@ public class UserBindingFetcher extends Fetcher { - private String pathServiceSid; - private String pathUserSid; - private String pathSid; + private String pathserviceSid; + private String pathuserSid; + private String pathsid; - public UserBindingFetcher( - final String pathServiceSid, - final String pathUserSid, - final String pathSid - ) { - this.pathServiceSid = pathServiceSid; - this.pathUserSid = pathUserSid; - this.pathSid = pathSid; + public UserBindingFetcher(final String pathserviceSid, final String pathuserSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathuserSid = pathuserSid; + this.pathsid = pathsid; } + @Override public UserBinding fetch(final TwilioRestClient client) { - String path = - "/v2/Services/{ServiceSid}/Users/{UserSid}/Bindings/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = path.replace("{" + "UserSid" + "}", this.pathUserSid.toString()); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/v2/Services/{ServiceSid}/Users/{UserSid}/Bindings/{Sid}"; + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "UserSid" + "}", this.pathuserSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.CHAT.toString(), - path + HttpMethod.GET, + Domains.CHAT.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "UserBinding fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("UserBinding fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return UserBinding.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return UserBinding.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/chat/v2/service/user/UserBindingReader.java b/src/main/java/com/twilio/rest/chat/v2/service/user/UserBindingReader.java index 6dafaedfae..eb46689a5f 100644 --- a/src/main/java/com/twilio/rest/chat/v2/service/user/UserBindingReader.java +++ b/src/main/java/com/twilio/rest/chat/v2/service/user/UserBindingReader.java @@ -17,8 +17,9 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; import com.twilio.converter.Promoter; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,33 +28,28 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.util.List; public class UserBindingReader extends Reader { - private String pathServiceSid; - private String pathUserSid; + private String pathserviceSid; + private String pathuserSid; private List bindingType; private Long pageSize; - public UserBindingReader( - final String pathServiceSid, - final String pathUserSid - ) { - this.pathServiceSid = pathServiceSid; - this.pathUserSid = pathUserSid; + public UserBindingReader(final String pathserviceSid, final String pathuserSid) { + this.pathserviceSid = pathserviceSid; + this.pathuserSid = pathuserSid; } - public UserBindingReader setBindingType( - final List bindingType - ) { + + public UserBindingReader setBindingType(final List bindingType) { this.bindingType = bindingType; return this; } - public UserBindingReader setBindingType( - final UserBinding.BindingType bindingType - ) { + public UserBindingReader setBindingType(final UserBinding.BindingType bindingType) { return setBindingType(Promoter.listOfOne(bindingType)); } @@ -62,109 +58,83 @@ public UserBindingReader setPageSize(final Long pageSize) { return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v2/Services/{ServiceSid}/Users/{UserSid}/Bindings"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = path.replace("{" + "UserSid" + "}", this.pathUserSid.toString()); + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "UserSid" + "}", this.pathuserSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.CHAT.toString(), - path + HttpMethod.GET, + Domains.CHAT.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "UserBinding read failed: Unable to connect to server" - ); + throw new ApiConnectionException("UserBinding read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "bindings", - response.getContent(), - UserBinding.class, - client.getObjectMapper() - ); + "bindings", + response.getContent(), + UserBinding.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.CHAT.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.CHAT.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (bindingType != null) { - for (UserBinding.BindingType prop : bindingType) { - request.addQueryParam("BindingType", prop.toString()); + for (UserBinding.BindingType param : bindingType) { + Serializer.toString(request, "BindingType", param, ParameterType.QUERY); } } + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/chat/v2/service/user/UserChannel.java b/src/main/java/com/twilio/rest/chat/v2/service/user/UserChannel.java index ebe37d60ac..1f1d8e41e0 100644 --- a/src/main/java/com/twilio/rest/chat/v2/service/user/UserChannel.java +++ b/src/main/java/com/twilio/rest/chat/v2/service/user/UserChannel.java @@ -18,81 +18,125 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class UserChannel extends Resource { - private static final long serialVersionUID = 104594062960806L; - public static UserChannelDeleter deleter( - final String pathServiceSid, - final String pathUserSid, - final String pathChannelSid - ) { + public static UserChannelDeleter deleter(final String pathserviceSid, final String pathuserSid, final String pathchannelSid) { return new UserChannelDeleter( - pathServiceSid, - pathUserSid, - pathChannelSid + pathserviceSid, pathuserSid, pathchannelSid ); } - public static UserChannelFetcher fetcher( - final String pathServiceSid, - final String pathUserSid, - final String pathChannelSid - ) { + + public static UserChannelFetcher fetcher(final String pathserviceSid, final String pathuserSid, final String pathchannelSid) { return new UserChannelFetcher( - pathServiceSid, - pathUserSid, - pathChannelSid + pathserviceSid, pathuserSid, pathchannelSid ); } - public static UserChannelReader reader( - final String pathServiceSid, - final String pathUserSid - ) { - return new UserChannelReader(pathServiceSid, pathUserSid); + + public static UserChannelReader reader(final String pathserviceSid, final String pathuserSid) { + return new UserChannelReader( + pathserviceSid, pathuserSid + ); } - public static UserChannelUpdater updater( - final String pathServiceSid, - final String pathUserSid, - final String pathChannelSid - ) { + + public static UserChannelUpdater updater(final String pathserviceSid, final String pathuserSid, final String pathchannelSid) { return new UserChannelUpdater( - pathServiceSid, - pathUserSid, - pathChannelSid + pathserviceSid, pathuserSid, pathchannelSid ); } + + public enum WebhookEnabledType { + TRUE("true"), + FALSE("false"); + + private final String value; + + private WebhookEnabledType(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static WebhookEnabledType forValue(final String value) { + return Promoter.enumFromString(value, WebhookEnabledType.values()); + } + } + + public enum NotificationLevel { + DEFAULT("default"), + MUTED("muted"); + + private final String value; + + private NotificationLevel(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static NotificationLevel forValue(final String value) { + return Promoter.enumFromString(value, NotificationLevel.values()); + } + } + + public enum ChannelStatus { + JOINED("joined"), + INVITED("invited"), + NOT_PARTICIPATING("not_participating"); + + private final String value; + + private ChannelStatus(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static ChannelStatus forValue(final String value) { + return Promoter.enumFromString(value, ChannelStatus.values()); + } + } + + /** * Converts a JSON String into a UserChannel object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return UserChannel object represented by the provided JSON */ - public static UserChannel fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static UserChannel fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, UserChannel.class); @@ -107,14 +151,11 @@ public static UserChannel fromJson( * Converts a JSON InputStream into a UserChannel object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return UserChannel object represented by the provided JSON */ - public static UserChannel fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static UserChannel fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, UserChannel.class); @@ -125,93 +166,67 @@ public static UserChannel fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String serviceSid; + @Getter private final String channelSid; - private final String userSid; + @Getter + private final Integer lastConsumedMessageIndex; + @Getter + private final Map links; + @Getter private final String memberSid; + @Getter + private final UserChannel.NotificationLevel notificationLevel; + @Getter + private final String serviceSid; + @Getter private final UserChannel.ChannelStatus status; - private final Integer lastConsumedMessageIndex; + @Getter private final Integer unreadMessagesCount; - private final Map links; + @Getter private final URI url; - private final UserChannel.NotificationLevel notificationLevel; + @Getter + private final String userSid; @JsonCreator private UserChannel( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("service_sid") final String serviceSid, - @JsonProperty("channel_sid") final String channelSid, - @JsonProperty("user_sid") final String userSid, - @JsonProperty("member_sid") final String memberSid, - @JsonProperty("status") final UserChannel.ChannelStatus status, - @JsonProperty( - "last_consumed_message_index" - ) final Integer lastConsumedMessageIndex, - @JsonProperty( - "unread_messages_count" - ) final Integer unreadMessagesCount, - @JsonProperty("links") final Map links, - @JsonProperty("url") final URI url, - @JsonProperty( - "notification_level" - ) final UserChannel.NotificationLevel notificationLevel + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("channel_sid") final String channelSid, + @JsonProperty("last_consumed_message_index") final Integer lastConsumedMessageIndex, + @JsonProperty("links") final Map links, + @JsonProperty("member_sid") final String memberSid, + @JsonProperty("notification_level") final UserChannel.NotificationLevel notificationLevel, + @JsonProperty("service_sid") final String serviceSid, + @JsonProperty("status") final UserChannel.ChannelStatus status, + @JsonProperty("unread_messages_count") final Integer unreadMessagesCount, + @JsonProperty("url") final URI url, + @JsonProperty("user_sid") final String userSid ) { this.accountSid = accountSid; - this.serviceSid = serviceSid; this.channelSid = channelSid; - this.userSid = userSid; + this.lastConsumedMessageIndex = lastConsumedMessageIndex; + this.links = links; this.memberSid = memberSid; + this.notificationLevel = notificationLevel; + this.serviceSid = serviceSid; this.status = status; - this.lastConsumedMessageIndex = lastConsumedMessageIndex; this.unreadMessagesCount = unreadMessagesCount; - this.links = links; this.url = url; - this.notificationLevel = notificationLevel; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getServiceSid() { - return this.serviceSid; - } - - public final String getChannelSid() { - return this.channelSid; - } - - public final String getUserSid() { - return this.userSid; - } - - public final String getMemberSid() { - return this.memberSid; - } - - public final UserChannel.ChannelStatus getStatus() { - return this.status; - } - - public final Integer getLastConsumedMessageIndex() { - return this.lastConsumedMessageIndex; - } - - public final Integer getUnreadMessagesCount() { - return this.unreadMessagesCount; - } - - public final Map getLinks() { - return this.links; - } - - public final URI getUrl() { - return this.url; - } - - public final UserChannel.NotificationLevel getNotificationLevel() { - return this.notificationLevel; + this.userSid = userSid; } @Override @@ -225,100 +240,38 @@ public boolean equals(final Object o) { } UserChannel other = (UserChannel) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(serviceSid, other.serviceSid) && - Objects.equals(channelSid, other.channelSid) && - Objects.equals(userSid, other.userSid) && - Objects.equals(memberSid, other.memberSid) && - Objects.equals(status, other.status) && - Objects.equals( - lastConsumedMessageIndex, - other.lastConsumedMessageIndex - ) && - Objects.equals(unreadMessagesCount, other.unreadMessagesCount) && - Objects.equals(links, other.links) && - Objects.equals(url, other.url) && - Objects.equals(notificationLevel, other.notificationLevel) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(channelSid, other.channelSid) && + Objects.equals(lastConsumedMessageIndex, other.lastConsumedMessageIndex) && + Objects.equals(links, other.links) && + Objects.equals(memberSid, other.memberSid) && + Objects.equals(notificationLevel, other.notificationLevel) && + Objects.equals(serviceSid, other.serviceSid) && + Objects.equals(status, other.status) && + Objects.equals(unreadMessagesCount, other.unreadMessagesCount) && + Objects.equals(url, other.url) && + Objects.equals(userSid, other.userSid) ); } @Override public int hashCode() { return Objects.hash( - accountSid, - serviceSid, - channelSid, - userSid, - memberSid, - status, - lastConsumedMessageIndex, - unreadMessagesCount, - links, - url, - notificationLevel + accountSid, + channelSid, + lastConsumedMessageIndex, + links, + memberSid, + notificationLevel, + serviceSid, + status, + unreadMessagesCount, + url, + userSid ); } - public enum WebhookEnabledType { - TRUE("true"), - FALSE("false"); - - private final String value; - - private WebhookEnabledType(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static WebhookEnabledType forValue(final String value) { - return Promoter.enumFromString(value, WebhookEnabledType.values()); - } - } - - public enum ChannelStatus { - JOINED("joined"), - INVITED("invited"), - NOT_PARTICIPATING("not_participating"); - - private final String value; - - private ChannelStatus(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static ChannelStatus forValue(final String value) { - return Promoter.enumFromString(value, ChannelStatus.values()); - } - } - - public enum NotificationLevel { - DEFAULT("default"), - MUTED("muted"); - - private final String value; - - private NotificationLevel(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - @JsonCreator - public static NotificationLevel forValue(final String value) { - return Promoter.enumFromString(value, NotificationLevel.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/chat/v2/service/user/UserChannelDeleter.java b/src/main/java/com/twilio/rest/chat/v2/service/user/UserChannelDeleter.java index ece9a6ad75..70c72becd9 100644 --- a/src/main/java/com/twilio/rest/chat/v2/service/user/UserChannelDeleter.java +++ b/src/main/java/com/twilio/rest/chat/v2/service/user/UserChannelDeleter.java @@ -15,7 +15,8 @@ package com.twilio.rest.chat.v2.service.user; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,68 +28,52 @@ public class UserChannelDeleter extends Deleter { - private String pathServiceSid; - private String pathUserSid; - private String pathChannelSid; + private String pathserviceSid; + private String pathuserSid; + private String pathchannelSid; private UserChannel.WebhookEnabledType xTwilioWebhookEnabled; - public UserChannelDeleter( - final String pathServiceSid, - final String pathUserSid, - final String pathChannelSid - ) { - this.pathServiceSid = pathServiceSid; - this.pathUserSid = pathUserSid; - this.pathChannelSid = pathChannelSid; + public UserChannelDeleter(final String pathserviceSid, final String pathuserSid, final String pathchannelSid) { + this.pathserviceSid = pathserviceSid; + this.pathuserSid = pathuserSid; + this.pathchannelSid = pathchannelSid; } - public UserChannelDeleter setXTwilioWebhookEnabled( - final UserChannel.WebhookEnabledType xTwilioWebhookEnabled - ) { + + public UserChannelDeleter setXTwilioWebhookEnabled(final UserChannel.WebhookEnabledType xTwilioWebhookEnabled) { this.xTwilioWebhookEnabled = xTwilioWebhookEnabled; return this; } + @Override public boolean delete(final TwilioRestClient client) { - String path = - "/v2/Services/{ServiceSid}/Users/{UserSid}/Channels/{ChannelSid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = path.replace("{" + "UserSid" + "}", this.pathUserSid.toString()); - path = - path.replace( - "{" + "ChannelSid" + "}", - this.pathChannelSid.toString() - ); + String path = "/v2/Services/{ServiceSid}/Users/{UserSid}/Channels/{ChannelSid}"; + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "UserSid" + "}", this.pathuserSid.toString()); + path = path.replace("{" + "ChannelSid" + "}", this.pathchannelSid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.CHAT.toString(), - path + HttpMethod.DELETE, + Domains.CHAT.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addHeaderParams(request); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "UserChannel delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("UserChannel delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -96,11 +81,10 @@ public boolean delete(final TwilioRestClient client) { } private void addHeaderParams(final Request request) { + if (xTwilioWebhookEnabled != null) { - request.addHeaderParam( - "X-Twilio-Webhook-Enabled", - xTwilioWebhookEnabled.toString() - ); + Serializer.toString(request, "X-Twilio-Webhook-Enabled", xTwilioWebhookEnabled, ParameterType.HEADER); } + } } diff --git a/src/main/java/com/twilio/rest/chat/v2/service/user/UserChannelFetcher.java b/src/main/java/com/twilio/rest/chat/v2/service/user/UserChannelFetcher.java index 8b1dfa878b..16845e58e6 100644 --- a/src/main/java/com/twilio/rest/chat/v2/service/user/UserChannelFetcher.java +++ b/src/main/java/com/twilio/rest/chat/v2/service/user/UserChannelFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.chat.v2.service.user; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,66 +26,47 @@ public class UserChannelFetcher extends Fetcher { - private String pathServiceSid; - private String pathUserSid; - private String pathChannelSid; + private String pathserviceSid; + private String pathuserSid; + private String pathchannelSid; - public UserChannelFetcher( - final String pathServiceSid, - final String pathUserSid, - final String pathChannelSid - ) { - this.pathServiceSid = pathServiceSid; - this.pathUserSid = pathUserSid; - this.pathChannelSid = pathChannelSid; + public UserChannelFetcher(final String pathserviceSid, final String pathuserSid, final String pathchannelSid) { + this.pathserviceSid = pathserviceSid; + this.pathuserSid = pathuserSid; + this.pathchannelSid = pathchannelSid; } + @Override public UserChannel fetch(final TwilioRestClient client) { - String path = - "/v2/Services/{ServiceSid}/Users/{UserSid}/Channels/{ChannelSid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = path.replace("{" + "UserSid" + "}", this.pathUserSid.toString()); - path = - path.replace( - "{" + "ChannelSid" + "}", - this.pathChannelSid.toString() - ); + String path = "/v2/Services/{ServiceSid}/Users/{UserSid}/Channels/{ChannelSid}"; + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "UserSid" + "}", this.pathuserSid.toString()); + path = path.replace("{" + "ChannelSid" + "}", this.pathchannelSid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.CHAT.toString(), - path + HttpMethod.GET, + Domains.CHAT.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "UserChannel fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("UserChannel fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return UserChannel.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return UserChannel.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/chat/v2/service/user/UserChannelReader.java b/src/main/java/com/twilio/rest/chat/v2/service/user/UserChannelReader.java index eae21c02a1..b3650082c7 100644 --- a/src/main/java/com/twilio/rest/chat/v2/service/user/UserChannelReader.java +++ b/src/main/java/com/twilio/rest/chat/v2/service/user/UserChannelReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,121 +30,91 @@ public class UserChannelReader extends Reader { - private String pathServiceSid; - private String pathUserSid; + private String pathserviceSid; + private String pathuserSid; private Long pageSize; - public UserChannelReader( - final String pathServiceSid, - final String pathUserSid - ) { - this.pathServiceSid = pathServiceSid; - this.pathUserSid = pathUserSid; + public UserChannelReader(final String pathserviceSid, final String pathuserSid) { + this.pathserviceSid = pathserviceSid; + this.pathuserSid = pathuserSid; } + public UserChannelReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v2/Services/{ServiceSid}/Users/{UserSid}/Channels"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = path.replace("{" + "UserSid" + "}", this.pathUserSid.toString()); + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "UserSid" + "}", this.pathuserSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.CHAT.toString(), - path + HttpMethod.GET, + Domains.CHAT.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "UserChannel read failed: Unable to connect to server" - ); + throw new ApiConnectionException("UserChannel read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "channels", - response.getContent(), - UserChannel.class, - client.getObjectMapper() - ); + "channels", + response.getContent(), + UserChannel.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.CHAT.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.CHAT.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/chat/v2/service/user/UserChannelUpdater.java b/src/main/java/com/twilio/rest/chat/v2/service/user/UserChannelUpdater.java index 29ba47054e..aeaa2ff9f2 100644 --- a/src/main/java/com/twilio/rest/chat/v2/service/user/UserChannelUpdater.java +++ b/src/main/java/com/twilio/rest/chat/v2/service/user/UserChannelUpdater.java @@ -16,6 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -24,115 +26,94 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.time.ZonedDateTime; public class UserChannelUpdater extends Updater { - - private String pathServiceSid; - private String pathUserSid; - private String pathChannelSid; + private String pathserviceSid; + private String pathuserSid; + private String pathchannelSid; private UserChannel.NotificationLevel notificationLevel; private Integer lastConsumedMessageIndex; private ZonedDateTime lastConsumptionTimestamp; - public UserChannelUpdater( - final String pathServiceSid, - final String pathUserSid, - final String pathChannelSid - ) { - this.pathServiceSid = pathServiceSid; - this.pathUserSid = pathUserSid; - this.pathChannelSid = pathChannelSid; + public UserChannelUpdater(final String pathserviceSid, final String pathuserSid, final String pathchannelSid) { + this.pathserviceSid = pathserviceSid; + this.pathuserSid = pathuserSid; + this.pathchannelSid = pathchannelSid; } - public UserChannelUpdater setNotificationLevel( - final UserChannel.NotificationLevel notificationLevel - ) { + + public UserChannelUpdater setNotificationLevel(final UserChannel.NotificationLevel notificationLevel) { this.notificationLevel = notificationLevel; return this; } - public UserChannelUpdater setLastConsumedMessageIndex( - final Integer lastConsumedMessageIndex - ) { + + public UserChannelUpdater setLastConsumedMessageIndex(final Integer lastConsumedMessageIndex) { this.lastConsumedMessageIndex = lastConsumedMessageIndex; return this; } - public UserChannelUpdater setLastConsumptionTimestamp( - final ZonedDateTime lastConsumptionTimestamp - ) { + + public UserChannelUpdater setLastConsumptionTimestamp(final ZonedDateTime lastConsumptionTimestamp) { this.lastConsumptionTimestamp = lastConsumptionTimestamp; return this; } + @Override public UserChannel update(final TwilioRestClient client) { - String path = - "/v2/Services/{ServiceSid}/Users/{UserSid}/Channels/{ChannelSid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = path.replace("{" + "UserSid" + "}", this.pathUserSid.toString()); - path = - path.replace( - "{" + "ChannelSid" + "}", - this.pathChannelSid.toString() - ); + String path = "/v2/Services/{ServiceSid}/Users/{UserSid}/Channels/{ChannelSid}"; + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "UserSid" + "}", this.pathuserSid.toString()); + path = path.replace("{" + "ChannelSid" + "}", this.pathchannelSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.CHAT.toString(), - path + HttpMethod.POST, + Domains.CHAT.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "UserChannel update failed: Unable to connect to server" - ); + throw new ApiConnectionException("UserChannel update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return UserChannel.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return UserChannel.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (notificationLevel != null) { - request.addPostParam( - "NotificationLevel", - notificationLevel.toString() - ); + Serializer.toString(request, "NotificationLevel", notificationLevel, ParameterType.URLENCODED); } + + if (lastConsumedMessageIndex != null) { - request.addPostParam( - "LastConsumedMessageIndex", - lastConsumedMessageIndex.toString() - ); + Serializer.toString(request, "LastConsumedMessageIndex", lastConsumedMessageIndex, ParameterType.URLENCODED); } + + if (lastConsumptionTimestamp != null) { - request.addPostParam( - "LastConsumptionTimestamp", - lastConsumptionTimestamp.toInstant().toString() - ); + Serializer.toString(request, "LastConsumptionTimestamp", lastConsumptionTimestamp, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/chat/v3/Channel.java b/src/main/java/com/twilio/rest/chat/v3/Channel.java index a46f618735..5f0f896aae 100644 --- a/src/main/java/com/twilio/rest/chat/v3/Channel.java +++ b/src/main/java/com/twilio/rest/chat/v3/Channel.java @@ -18,45 +18,84 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Channel extends Resource { - private static final long serialVersionUID = 62753936180140L; - public static ChannelUpdater updater( - final String pathServiceSid, - final String pathSid - ) { - return new ChannelUpdater(pathServiceSid, pathSid); + public static ChannelUpdater updater(final String pathserviceSid, final String pathsid) { + return new ChannelUpdater( + pathserviceSid, pathsid + ); + } + + + public enum WebhookEnabledType { + TRUE("true"), + FALSE("false"); + + private final String value; + + private WebhookEnabledType(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static WebhookEnabledType forValue(final String value) { + return Promoter.enumFromString(value, WebhookEnabledType.values()); + } } + public enum ChannelType { + PUBLIC("public"), + PRIVATE("private"); + + private final String value; + + private ChannelType(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static ChannelType forValue(final String value) { + return Promoter.enumFromString(value, ChannelType.values()); + } + } + + /** * Converts a JSON String into a Channel object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Channel object represented by the provided JSON */ - public static Channel fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Channel fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Channel.class); @@ -71,14 +110,11 @@ public static Channel fromJson( * Converts a JSON InputStream into a Channel object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Channel object represented by the provided JSON */ - public static Channel fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Channel fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Channel.class); @@ -89,110 +125,83 @@ public static Channel fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String serviceSid; - private final String friendlyName; - private final String uniqueName; + @Getter private final String attributes; - private final Channel.ChannelType type; + @Getter + private final String createdBy; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; - private final String createdBy; + @Getter + private final String friendlyName; + @Getter private final Integer membersCount; + @Getter private final Integer messagesCount; + @Getter private final String messagingServiceSid; + @Getter + private final String serviceSid; + @Getter + private final String sid; + @Getter + private final Channel.ChannelType type; + @Getter + private final String uniqueName; + @Getter private final URI url; @JsonCreator private Channel( - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("service_sid") final String serviceSid, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("unique_name") final String uniqueName, - @JsonProperty("attributes") final String attributes, - @JsonProperty("type") final Channel.ChannelType type, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("created_by") final String createdBy, - @JsonProperty("members_count") final Integer membersCount, - @JsonProperty("messages_count") final Integer messagesCount, - @JsonProperty("messaging_service_sid") final String messagingServiceSid, - @JsonProperty("url") final URI url + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("attributes") final String attributes, + @JsonProperty("created_by") final String createdBy, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("members_count") final Integer membersCount, + @JsonProperty("messages_count") final Integer messagesCount, + @JsonProperty("messaging_service_sid") final String messagingServiceSid, + @JsonProperty("service_sid") final String serviceSid, + @JsonProperty("sid") final String sid, + @JsonProperty("type") final Channel.ChannelType type, + @JsonProperty("unique_name") final String uniqueName, + @JsonProperty("url") final URI url ) { - this.sid = sid; this.accountSid = accountSid; - this.serviceSid = serviceSid; - this.friendlyName = friendlyName; - this.uniqueName = uniqueName; this.attributes = attributes; - this.type = type; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); this.createdBy = createdBy; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; + this.friendlyName = friendlyName; this.membersCount = membersCount; this.messagesCount = messagesCount; this.messagingServiceSid = messagingServiceSid; + this.serviceSid = serviceSid; + this.sid = sid; + this.type = type; + this.uniqueName = uniqueName; this.url = url; } - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getServiceSid() { - return this.serviceSid; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final String getUniqueName() { - return this.uniqueName; - } - - public final String getAttributes() { - return this.attributes; - } - - public final Channel.ChannelType getType() { - return this.type; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final String getCreatedBy() { - return this.createdBy; - } - - public final Integer getMembersCount() { - return this.membersCount; - } - - public final Integer getMessagesCount() { - return this.messagesCount; - } - - public final String getMessagingServiceSid() { - return this.messagingServiceSid; - } - - public final URI getUrl() { - return this.url; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -204,82 +213,44 @@ public boolean equals(final Object o) { } Channel other = (Channel) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(serviceSid, other.serviceSid) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(uniqueName, other.uniqueName) && - Objects.equals(attributes, other.attributes) && - Objects.equals(type, other.type) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(createdBy, other.createdBy) && - Objects.equals(membersCount, other.membersCount) && - Objects.equals(messagesCount, other.messagesCount) && - Objects.equals(messagingServiceSid, other.messagingServiceSid) && - Objects.equals(url, other.url) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(attributes, other.attributes) && + Objects.equals(createdBy, other.createdBy) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(membersCount, other.membersCount) && + Objects.equals(messagesCount, other.messagesCount) && + Objects.equals(messagingServiceSid, other.messagingServiceSid) && + Objects.equals(serviceSid, other.serviceSid) && + Objects.equals(sid, other.sid) && + Objects.equals(type, other.type) && + Objects.equals(uniqueName, other.uniqueName) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - sid, - accountSid, - serviceSid, - friendlyName, - uniqueName, - attributes, - type, - dateCreated, - dateUpdated, - createdBy, - membersCount, - messagesCount, - messagingServiceSid, - url + accountSid, + attributes, + createdBy, + dateCreated, + dateUpdated, + friendlyName, + membersCount, + messagesCount, + messagingServiceSid, + serviceSid, + sid, + type, + uniqueName, + url ); } - public enum ChannelType { - PUBLIC("public"), - PRIVATE("private"); - - private final String value; - - private ChannelType(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static ChannelType forValue(final String value) { - return Promoter.enumFromString(value, ChannelType.values()); - } - } - - public enum WebhookEnabledType { - TRUE("true"), - FALSE("false"); - - private final String value; - - private WebhookEnabledType(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - @JsonCreator - public static WebhookEnabledType forValue(final String value) { - return Promoter.enumFromString(value, WebhookEnabledType.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/chat/v3/ChannelUpdater.java b/src/main/java/com/twilio/rest/chat/v3/ChannelUpdater.java index 59f3d5ec12..56bd6194e3 100644 --- a/src/main/java/com/twilio/rest/chat/v3/ChannelUpdater.java +++ b/src/main/java/com/twilio/rest/chat/v3/ChannelUpdater.java @@ -16,6 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -26,71 +28,65 @@ import com.twilio.rest.Domains; public class ChannelUpdater extends Updater { - - private String pathServiceSid; - private String pathSid; + private String pathserviceSid; + private String pathsid; private Channel.WebhookEnabledType xTwilioWebhookEnabled; private Channel.ChannelType type; private String messagingServiceSid; - public ChannelUpdater(final String pathServiceSid, final String pathSid) { - this.pathServiceSid = pathServiceSid; - this.pathSid = pathSid; + public ChannelUpdater(final String pathserviceSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathsid = pathsid; } - public ChannelUpdater setXTwilioWebhookEnabled( - final Channel.WebhookEnabledType xTwilioWebhookEnabled - ) { - this.xTwilioWebhookEnabled = xTwilioWebhookEnabled; - return this; - } public ChannelUpdater setType(final Channel.ChannelType type) { this.type = type; return this; } - public ChannelUpdater setMessagingServiceSid( - final String messagingServiceSid - ) { + + public ChannelUpdater setMessagingServiceSid(final String messagingServiceSid) { this.messagingServiceSid = messagingServiceSid; return this; } + + public ChannelUpdater setXTwilioWebhookEnabled(final Channel.WebhookEnabledType xTwilioWebhookEnabled) { + this.xTwilioWebhookEnabled = xTwilioWebhookEnabled; + return this; + } + + @Override public Channel update(final TwilioRestClient client) { + String path = "/v3/Services/{ServiceSid}/Channels/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.CHAT.toString(), - path + HttpMethod.POST, + Domains.CHAT.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); - addPostParams(request); addHeaderParams(request); + addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Channel update failed: Unable to connect to server" - ); + throw new ApiConnectionException("Channel update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -99,20 +95,24 @@ public Channel update(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (type != null) { - request.addPostParam("Type", type.toString()); + Serializer.toString(request, "Type", type, ParameterType.URLENCODED); } + + if (messagingServiceSid != null) { - request.addPostParam("MessagingServiceSid", messagingServiceSid); + Serializer.toString(request, "MessagingServiceSid", messagingServiceSid, ParameterType.URLENCODED); } + + } private void addHeaderParams(final Request request) { + if (xTwilioWebhookEnabled != null) { - request.addHeaderParam( - "X-Twilio-Webhook-Enabled", - xTwilioWebhookEnabled.toString() - ); + Serializer.toString(request, "X-Twilio-Webhook-Enabled", xTwilioWebhookEnabled, ParameterType.HEADER); } + } } diff --git a/src/main/java/com/twilio/rest/content/v1/Content.java b/src/main/java/com/twilio/rest/content/v1/Content.java index 1b21e6becb..e0066c1f64 100644 --- a/src/main/java/com/twilio/rest/content/v1/Content.java +++ b/src/main/java/com/twilio/rest/content/v1/Content.java @@ -22,11 +22,15 @@ import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.math.BigDecimal; @@ -35,161 +39,314 @@ import java.util.List; import java.util.Map; import java.util.Objects; -import lombok.Getter; -import lombok.Setter; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Content extends Resource { - private static final long serialVersionUID = 58899890984300L; + public static ContentCreator creator(final Content.ContentCreateRequest contentCreateRequest) { + return new ContentCreator( + contentCreateRequest + ); + } + + + public static ContentDeleter deleter(final String pathsid) { + return new ContentDeleter( + pathsid + ); + } + + + public static ContentFetcher fetcher(final String pathsid) { + return new ContentFetcher( + pathsid + ); + } + + + public static ContentReader reader() { + return new ContentReader( + + ); + } + + + public enum CarouselActionType { + URL("URL"), + PHONE_NUMBER("PHONE_NUMBER"), + QUICK_REPLY("QUICK_REPLY"); + + private final String value; + + private CarouselActionType(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static CarouselActionType forValue(final String value) { + return Promoter.enumFromString(value, CarouselActionType.values()); + } + } + + public enum AuthenticationActionType { + COPY_CODE("COPY_CODE"); + + private final String value; + + private AuthenticationActionType(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static AuthenticationActionType forValue(final String value) { + return Promoter.enumFromString(value, AuthenticationActionType.values()); + } + } + + public enum CardActionType { + URL("URL"), + PHONE_NUMBER("PHONE_NUMBER"), + QUICK_REPLY("QUICK_REPLY"), + COPY_CODE("COPY_CODE"), + VOICE_CALL("VOICE_CALL"); + + private final String value; + + private CardActionType(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static CardActionType forValue(final String value) { + return Promoter.enumFromString(value, CardActionType.values()); + } + } + + public enum QuickReplyActionType { + QUICK_REPLY("QUICK_REPLY"); + + private final String value; + + private QuickReplyActionType(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static QuickReplyActionType forValue(final String value) { + return Promoter.enumFromString(value, QuickReplyActionType.values()); + } + } + + public enum WebviewSizeType { + TALL("TALL"), + FULL("FULL"), + HALF("HALF"), + NONE("NONE"); + + private final String value; + + private WebviewSizeType(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static WebviewSizeType forValue(final String value) { + return Promoter.enumFromString(value, WebviewSizeType.values()); + } + } + + public enum CallToActionActionType { + URL("URL"), + PHONE_NUMBER("PHONE_NUMBER"), + COPY_CODE("COPY_CODE"), + VOICE_CALL("VOICE_CALL"), + VOICE_CALL_REQUEST("VOICE_CALL_REQUEST"); + + private final String value; + + private CallToActionActionType(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static CallToActionActionType forValue(final String value) { + return Promoter.enumFromString(value, CallToActionActionType.values()); + } + } + + + //@JsonDeserialize(builder = FlowsPage.Builder.class) + @JsonInclude(JsonInclude.Include.NON_EMPTY) @ToString - public static class TwilioText { + public static class FlowsPage { + public FlowsPage(final String id, final List layout) { + this.id = id; + this.layout = layout; + } @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("body") + @JsonProperty("id") @Getter @Setter - private String body; + private String id; - public static TwilioText fromJson( - String jsonString, - ObjectMapper mapper - ) throws IOException { - return mapper.readValue(jsonString, TwilioText.class); - } - } + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("next_page_id") + @Getter + @Setter + private String nextPageId; - @ToString - public static class TwilioMedia { + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("title") + @Getter + @Setter + private String title; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("body") + @JsonProperty("subtitle") @Getter @Setter - private String body; + private String subtitle; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("media") + @JsonProperty("layout") @Getter @Setter - private List media; + private List layout; - public static TwilioMedia fromJson( - String jsonString, - ObjectMapper mapper - ) throws IOException { - return mapper.readValue(jsonString, TwilioMedia.class); - } } + //@JsonDeserialize(builder = Types.Builder.class) + @JsonInclude(JsonInclude.Include.NON_EMPTY) @ToString - public static class TwilioLocation { + public static class Types { @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("latitude") + @JsonProperty("twilio/text") @Getter @Setter - private BigDecimal latitude; + private TwilioText twilioText; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("longitude") + @JsonProperty("twilio/media") @Getter @Setter - private BigDecimal longitude; + private TwilioMedia twilioMedia; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("label") + @JsonProperty("twilio/location") @Getter @Setter - private String label; + private TwilioLocation twilioLocation; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("id") + @JsonProperty("twilio/list-picker") @Getter @Setter - private String id; + private TwilioListPicker twilioListPicker; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("address") + @JsonProperty("twilio/call-to-action") @Getter @Setter - private String address; - - public static TwilioLocation fromJson( - String jsonString, - ObjectMapper mapper - ) throws IOException { - return mapper.readValue(jsonString, TwilioLocation.class); - } - } + private TwilioCallToAction twilioCallToAction; - @ToString - public static class ListItem { + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("twilio/quick-reply") + @Getter + @Setter + private TwilioQuickReply twilioQuickReply; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("id") + @JsonProperty("twilio/card") @Getter @Setter - private String id; + private TwilioCard twilioCard; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("item") + @JsonProperty("twilio/catalog") @Getter @Setter - private String item; + private TwilioCatalog twilioCatalog; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("description") + @JsonProperty("twilio/carousel") @Getter @Setter - private String description; + private TwilioCarousel twilioCarousel; - public static ListItem fromJson(String jsonString, ObjectMapper mapper) - throws IOException { - return mapper.readValue(jsonString, ListItem.class); - } - } + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("twilio/flows") + @Getter + @Setter + private TwilioFlows twilioFlows; - @ToString - public static class TwilioListPicker { + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("twilio/schedule") + @Getter + @Setter + private TwilioSchedule twilioSchedule; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("body") + @JsonProperty("whatsapp/card") @Getter @Setter - private String body; + private WhatsappCard whatsappCard; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("button") + @JsonProperty("whatsapp/authentication") @Getter @Setter - private String button; + private WhatsappAuthentication whatsappAuthentication; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("items") + @JsonProperty("whatsapp/flows") @Getter @Setter - private List items; + private WhatsappFlows whatsappFlows; - public static TwilioListPicker fromJson( - String jsonString, - ObjectMapper mapper - ) throws IOException { - return mapper.readValue(jsonString, TwilioListPicker.class); - } } + //@JsonDeserialize(builder = CallToActionAction.Builder.class) + @JsonInclude(JsonInclude.Include.NON_EMPTY) @ToString public static class CallToActionAction { + public CallToActionAction(final Content.CallToActionActionType type, final String title) { + this.type = type; + this.title = title; + } @JsonInclude(JsonInclude.Include.NON_EMPTY) @JsonProperty("type") @Getter @Setter - private CallToActionActionType type; + private Content.CallToActionActionType type; @JsonInclude(JsonInclude.Include.NON_EMPTY) @JsonProperty("title") @@ -221,51 +378,40 @@ public static class CallToActionAction { @Setter private String id; - public static CallToActionAction fromJson( - String jsonString, - ObjectMapper mapper - ) throws IOException { - return mapper.readValue(jsonString, CallToActionAction.class); - } } + //@JsonDeserialize(builder = CarouselAction.Builder.class) + @JsonInclude(JsonInclude.Include.NON_EMPTY) @ToString - public static class TwilioCallToAction { + public static class CarouselAction { + public CarouselAction(final Content.CarouselActionType type, final String title) { + this.type = type; + this.title = title; + } @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("body") + @JsonProperty("type") @Getter @Setter - private String body; + private Content.CarouselActionType type; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("actions") + @JsonProperty("title") @Getter @Setter - private List actions; - - public static TwilioCallToAction fromJson( - String jsonString, - ObjectMapper mapper - ) throws IOException { - return mapper.readValue(jsonString, TwilioCallToAction.class); - } - } - - @ToString - public static class QuickReplyAction { + private String title; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("type") + @JsonProperty("url") @Getter @Setter - private QuickReplyActionType type; + private String url; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("title") + @JsonProperty("phone") @Getter @Setter - private String title; + private String phone; @JsonInclude(JsonInclude.Include.NON_EMPTY) @JsonProperty("id") @@ -273,16 +419,15 @@ public static class QuickReplyAction { @Setter private String id; - public static QuickReplyAction fromJson( - String jsonString, - ObjectMapper mapper - ) throws IOException { - return mapper.readValue(jsonString, QuickReplyAction.class); - } } + //@JsonDeserialize(builder = WhatsappCard.Builder.class) + @JsonInclude(JsonInclude.Include.NON_EMPTY) @ToString - public static class TwilioQuickReply { + public static class WhatsappCard { + public WhatsappCard(final String body) { + this.body = body; + } @JsonInclude(JsonInclude.Include.NON_EMPTY) @JsonProperty("body") @@ -291,74 +436,95 @@ public static class TwilioQuickReply { private String body; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("actions") + @JsonProperty("footer") @Getter @Setter - private List actions; + private String footer; - public static TwilioQuickReply fromJson( - String jsonString, - ObjectMapper mapper - ) throws IOException { - return mapper.readValue(jsonString, TwilioQuickReply.class); - } - } + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("media") + @Getter + @Setter + private List media; - @ToString - public static class CardAction { + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("header_text") + @Getter + @Setter + private String headerText; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("type") + @JsonProperty("actions") @Getter @Setter - private CardActionType type; + private List actions; + + } + + //@JsonDeserialize(builder = WhatsappAuthentication.Builder.class) + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @ToString + public static class WhatsappAuthentication { + public WhatsappAuthentication(final List actions) { + this.actions = actions; + } @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("title") + @JsonProperty("add_security_recommendation") @Getter @Setter - private String title; + private Boolean addSecurityRecommendation; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("url") + @JsonProperty("code_expiration_minutes") @Getter @Setter - private String url; + private BigDecimal codeExpirationMinutes; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("phone") + @JsonProperty("actions") @Getter @Setter - private String phone; + private List actions; + + } + + //@JsonDeserialize(builder = QuickReplyAction.Builder.class) + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @ToString + public static class QuickReplyAction { + public QuickReplyAction(final Content.QuickReplyActionType type, final String title) { + this.type = type; + this.title = title; + } @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("id") + @JsonProperty("type") @Getter @Setter - private String id; + private Content.QuickReplyActionType type; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("code") + @JsonProperty("title") @Getter @Setter - private String code; + private String title; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("webview_size") + @JsonProperty("id") @Getter @Setter - private WebviewSizeType webviewSize; + private String id; - public static CardAction fromJson( - String jsonString, - ObjectMapper mapper - ) throws IOException { - return mapper.readValue(jsonString, CardAction.class); - } } + //@JsonDeserialize(builder = TwilioCard.Builder.class) + @JsonInclude(JsonInclude.Include.NON_EMPTY) @ToString public static class TwilioCard { + public TwilioCard(final String title) { + this.title = title; + } @JsonInclude(JsonInclude.Include.NON_EMPTY) @JsonProperty("title") @@ -384,209 +550,189 @@ public static class TwilioCard { @Setter private List actions; - public static TwilioCard fromJson( - String jsonString, - ObjectMapper mapper - ) throws IOException { - return mapper.readValue(jsonString, TwilioCard.class); - } } + //@JsonDeserialize(builder = AuthenticationAction.Builder.class) + @JsonInclude(JsonInclude.Include.NON_EMPTY) @ToString - public static class CatalogItem { - - @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("id") - @Getter - @Setter - private String id; - - @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("section_title") - @Getter - @Setter - private String sectionTitle; - - @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("name") - @Getter - @Setter - private String name; - - @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("media_url") - @Getter - @Setter - private String mediaUrl; + public static class AuthenticationAction { + public AuthenticationAction(final Content.AuthenticationActionType type, final String copyCodeText) { + this.type = type; + this.copyCodeText = copyCodeText; + } @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("price") + @JsonProperty("type") @Getter @Setter - private BigDecimal price; + private Content.AuthenticationActionType type; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("description") + @JsonProperty("copy_code_text") @Getter @Setter - private String description; + private String copyCodeText; - public static CatalogItem fromJson( - String jsonString, - ObjectMapper mapper - ) throws IOException { - return mapper.readValue(jsonString, CatalogItem.class); - } } + //@JsonDeserialize(builder = ContentCreateRequest.Builder.class) + @JsonInclude(JsonInclude.Include.NON_EMPTY) @ToString - public static class TwilioCatalog { + public static class ContentCreateRequest { + public ContentCreateRequest(final String language, final Types types) { + this.language = language; + this.types = types; + } @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("title") + @JsonProperty("friendly_name") @Getter @Setter - private String title; + private String friendlyName; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("body") + @JsonProperty("variables") @Getter @Setter - private String body; + private Map variables; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("subtitle") + @JsonProperty("language") @Getter @Setter - private String subtitle; + private String language; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("id") + @JsonProperty("types") @Getter @Setter - private String id; + private Types types; + + } + + //@JsonDeserialize(builder = TwilioCallToAction.Builder.class) + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @ToString + public static class TwilioCallToAction { @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("items") + @JsonProperty("body") @Getter @Setter - private List items; + private String body; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("dynamic_items") + @JsonProperty("actions") @Getter @Setter - private String dynamicItems; + private List actions; - public static TwilioCatalog fromJson( - String jsonString, - ObjectMapper mapper - ) throws IOException { - return mapper.readValue(jsonString, TwilioCatalog.class); - } } + //@JsonDeserialize(builder = TwilioQuickReply.Builder.class) + @JsonInclude(JsonInclude.Include.NON_EMPTY) @ToString - public static class CarouselAction { + public static class TwilioQuickReply { + public TwilioQuickReply(final String body, final List actions) { + this.body = body; + this.actions = actions; + } @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("type") + @JsonProperty("body") @Getter @Setter - private CarouselActionType type; + private String body; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("title") + @JsonProperty("actions") @Getter @Setter - private String title; + private List actions; - @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("url") - @Getter - @Setter - private String url; + } + + //@JsonDeserialize(builder = TwilioMedia.Builder.class) + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @ToString + public static class TwilioMedia { + public TwilioMedia(final List media) { + this.media = media; + } @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("phone") + @JsonProperty("body") @Getter @Setter - private String phone; + private String body; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("id") + @JsonProperty("media") @Getter @Setter - private String id; + private List media; - public static CarouselAction fromJson( - String jsonString, - ObjectMapper mapper - ) throws IOException { - return mapper.readValue(jsonString, CarouselAction.class); - } } + //@JsonDeserialize(builder = TwilioFlows.Builder.class) + @JsonInclude(JsonInclude.Include.NON_EMPTY) @ToString - public static class CarouselCard { + public static class TwilioFlows { + public TwilioFlows(final String body, final String buttonText, final String subtitle, final String mediaUrl, final List pages, final String type) { + this.body = body; + this.buttonText = buttonText; + this.subtitle = subtitle; + this.mediaUrl = mediaUrl; + this.pages = pages; + this.type = type; + } @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("title") + @JsonProperty("body") @Getter @Setter - private String title; + private String body; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("body") + @JsonProperty("button_text") @Getter @Setter - private String body; + private String buttonText; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("media") + @JsonProperty("subtitle") @Getter @Setter - private String media; + private String subtitle; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("actions") + @JsonProperty("media_url") @Getter @Setter - private List actions; - - public static CarouselCard fromJson( - String jsonString, - ObjectMapper mapper - ) throws IOException { - return mapper.readValue(jsonString, CarouselCard.class); - } - } - - @ToString - public static class TwilioCarousel { + private String mediaUrl; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("body") + @JsonProperty("pages") @Getter @Setter - private String body; + private List pages; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("cards") + @JsonProperty("type") @Getter @Setter - private List cards; + private String type; - public static TwilioCarousel fromJson( - String jsonString, - ObjectMapper mapper - ) throws IOException { - return mapper.readValue(jsonString, TwilioCarousel.class); - } } + //@JsonDeserialize(builder = FlowsPageComponent.Builder.class) + @JsonInclude(JsonInclude.Include.NON_EMPTY) @ToString public static class FlowsPageComponent { + public FlowsPageComponent(final String label, final String type) { + this.label = label; + this.type = type; + } @JsonInclude(JsonInclude.Include.NON_EMPTY) @JsonProperty("label") @@ -600,57 +746,77 @@ public static class FlowsPageComponent { @Setter private String type; - public static FlowsPageComponent fromJson( - String jsonString, - ObjectMapper mapper - ) throws IOException { - return mapper.readValue(jsonString, FlowsPageComponent.class); - } } + //@JsonDeserialize(builder = WhatsappFlows.Builder.class) + @JsonInclude(JsonInclude.Include.NON_EMPTY) @ToString - public static class FlowsPage { + public static class WhatsappFlows { + public WhatsappFlows(final String body, final String buttonText, final String flowId) { + this.body = body; + this.buttonText = buttonText; + this.flowId = flowId; + } @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("id") + @JsonProperty("body") @Getter @Setter - private String id; + private String body; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("next_page_id") + @JsonProperty("button_text") @Getter @Setter - private String nextPageId; + private String buttonText; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("title") + @JsonProperty("subtitle") @Getter @Setter - private String title; + private String subtitle; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("subtitle") + @JsonProperty("media_url") @Getter @Setter - private String subtitle; + private String mediaUrl; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("layout") + @JsonProperty("flow_id") @Getter @Setter - private List layout; + private String flowId; + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("flow_token") + @Getter + @Setter + private String flowToken; + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("flow_first_page_id") + @Getter + @Setter + private String flowFirstPageId; + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("is_flow_first_page_endpoint") + @Getter + @Setter + private Boolean isFlowFirstPageEndpoint; - public static FlowsPage fromJson( - String jsonString, - ObjectMapper mapper - ) throws IOException { - return mapper.readValue(jsonString, FlowsPage.class); - } } + //@JsonDeserialize(builder = TwilioListPicker.Builder.class) + @JsonInclude(JsonInclude.Include.NON_EMPTY) @ToString - public static class TwilioFlows { + public static class TwilioListPicker { + public TwilioListPicker(final String body, final String button, final List items) { + this.body = body; + this.button = button; + this.items = items; + } @JsonInclude(JsonInclude.Include.NON_EMPTY) @JsonProperty("body") @@ -659,45 +825,44 @@ public static class TwilioFlows { private String body; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("button_text") + @JsonProperty("button") @Getter @Setter - private String buttonText; + private String button; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("subtitle") + @JsonProperty("items") @Getter @Setter - private String subtitle; + private List items; + + } + + //@JsonDeserialize(builder = TwilioCatalog.Builder.class) + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @ToString + public static class TwilioCatalog { + public TwilioCatalog(final String body) { + this.body = body; + } @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("media_url") + @JsonProperty("title") @Getter @Setter - private String mediaUrl; + private String title; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("pages") + @JsonProperty("body") @Getter @Setter - private List pages; + private String body; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("type") + @JsonProperty("subtitle") @Getter @Setter - private String type; - - public static TwilioFlows fromJson( - String jsonString, - ObjectMapper mapper - ) throws IOException { - return mapper.readValue(jsonString, TwilioFlows.class); - } - } - - @ToString - public static class TwilioSchedule { + private String subtitle; @JsonInclude(JsonInclude.Include.NON_EMPTY) @JsonProperty("id") @@ -706,27 +871,26 @@ public static class TwilioSchedule { private String id; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("title") + @JsonProperty("items") @Getter @Setter - private String title; + private List items; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("timeSlots") + @JsonProperty("dynamic_items") @Getter @Setter - private String timeSlots; + private String dynamicItems; - public static TwilioSchedule fromJson( - String jsonString, - ObjectMapper mapper - ) throws IOException { - return mapper.readValue(jsonString, TwilioSchedule.class); - } } + //@JsonDeserialize(builder = TwilioText.Builder.class) + @JsonInclude(JsonInclude.Include.NON_EMPTY) @ToString - public static class WhatsappCard { + public static class TwilioText { + public TwilioText(final String body) { + this.body = body; + } @JsonInclude(JsonInclude.Include.NON_EMPTY) @JsonProperty("body") @@ -734,246 +898,266 @@ public static class WhatsappCard { @Setter private String body; + } + + //@JsonDeserialize(builder = CatalogItem.Builder.class) + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @ToString + public static class CatalogItem { + @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("footer") + @JsonProperty("id") @Getter @Setter - private String footer; + private String id; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("media") + @JsonProperty("section_title") @Getter @Setter - private List media; + private String sectionTitle; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("header_text") + @JsonProperty("name") @Getter @Setter - private String headerText; + private String name; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("actions") + @JsonProperty("media_url") @Getter @Setter - private List actions; - - public static WhatsappCard fromJson( - String jsonString, - ObjectMapper mapper - ) throws IOException { - return mapper.readValue(jsonString, WhatsappCard.class); - } - } - - @ToString - public static class AuthenticationAction { + private String mediaUrl; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("type") + @JsonProperty("price") @Getter @Setter - private AuthenticationActionType type; + private BigDecimal price; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("copy_code_text") + @JsonProperty("description") @Getter @Setter - private String copyCodeText; + private String description; - public static AuthenticationAction fromJson( - String jsonString, - ObjectMapper mapper - ) throws IOException { - return mapper.readValue(jsonString, AuthenticationAction.class); - } } + //@JsonDeserialize(builder = TwilioSchedule.Builder.class) + @JsonInclude(JsonInclude.Include.NON_EMPTY) @ToString - public static class WhatsappAuthentication { + public static class TwilioSchedule { + public TwilioSchedule(final String id, final String title, final String timeSlots) { + this.id = id; + this.title = title; + this.timeSlots = timeSlots; + } @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("add_security_recommendation") + @JsonProperty("id") @Getter @Setter - private Boolean addSecurityRecommendation; + private String id; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("code_expiration_minutes") + @JsonProperty("title") @Getter @Setter - private BigDecimal codeExpirationMinutes; + private String title; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("actions") + @JsonProperty("timeSlots") @Getter @Setter - private List actions; + private String timeSlots; - public static WhatsappAuthentication fromJson( - String jsonString, - ObjectMapper mapper - ) throws IOException { - return mapper.readValue(jsonString, WhatsappAuthentication.class); - } } + //@JsonDeserialize(builder = TwilioCarousel.Builder.class) + @JsonInclude(JsonInclude.Include.NON_EMPTY) @ToString - public static class Types { + public static class TwilioCarousel { + public TwilioCarousel(final String body, final List cards) { + this.body = body; + this.cards = cards; + } @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("twilio/text") + @JsonProperty("body") @Getter @Setter - private TwilioText twilioText; + private String body; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("twilio/media") + @JsonProperty("cards") @Getter @Setter - private TwilioMedia twilioMedia; + private List cards; + + } + + //@JsonDeserialize(builder = CardAction.Builder.class) + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @ToString + public static class CardAction { + public CardAction(final Content.CardActionType type, final String title) { + this.type = type; + this.title = title; + } @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("twilio/location") + @JsonProperty("type") @Getter @Setter - private TwilioLocation twilioLocation; + private Content.CardActionType type; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("twilio/list-picker") + @JsonProperty("title") @Getter @Setter - private TwilioListPicker twilioListPicker; + private String title; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("twilio/call-to-action") + @JsonProperty("url") @Getter @Setter - private TwilioCallToAction twilioCallToAction; + private String url; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("twilio/quick-reply") + @JsonProperty("phone") @Getter @Setter - private TwilioQuickReply twilioQuickReply; + private String phone; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("twilio/card") + @JsonProperty("id") @Getter @Setter - private TwilioCard twilioCard; + private String id; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("twilio/catalog") + @JsonProperty("code") @Getter @Setter - private TwilioCatalog twilioCatalog; + private String code; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("twilio/carousel") + @JsonProperty("webview_size") @Getter @Setter - private TwilioCarousel twilioCarousel; + private Content.WebviewSizeType webviewSize; + + } + + //@JsonDeserialize(builder = CarouselCard.Builder.class) + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @ToString + public static class CarouselCard { @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("twilio/flows") + @JsonProperty("title") @Getter @Setter - private TwilioFlows twilioFlows; + private String title; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("twilio/schedule") + @JsonProperty("body") @Getter @Setter - private TwilioSchedule twilioSchedule; + private String body; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("whatsapp/card") + @JsonProperty("media") @Getter @Setter - private WhatsappCard whatsappCard; + private String media; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("whatsapp/authentication") + @JsonProperty("actions") @Getter @Setter - private WhatsappAuthentication whatsappAuthentication; + private List actions; - public static Types fromJson(String jsonString, ObjectMapper mapper) - throws IOException { - return mapper.readValue(jsonString, Types.class); - } } + //@JsonDeserialize(builder = TwilioLocation.Builder.class) + @JsonInclude(JsonInclude.Include.NON_EMPTY) @ToString - public static class ContentCreateRequest { + public static class TwilioLocation { + public TwilioLocation(final BigDecimal latitude, final BigDecimal longitude) { + this.latitude = latitude; + this.longitude = longitude; + } @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("friendly_name") + @JsonProperty("latitude") @Getter @Setter - private String friendlyName; + private BigDecimal latitude; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("variables") + @JsonProperty("longitude") @Getter @Setter - private Map variables; + private BigDecimal longitude; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("language") + @JsonProperty("label") @Getter @Setter - private String language; + private String label; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("types") + @JsonProperty("id") @Getter @Setter - private Types types; + private String id; - public ContentCreateRequest(final String language, final Types types) { - this.language = language; - this.types = types; - } + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("address") + @Getter + @Setter + private String address; - public static ContentCreateRequest fromJson( - String jsonString, - ObjectMapper mapper - ) throws IOException { - return mapper.readValue(jsonString, ContentCreateRequest.class); - } } - public static ContentCreator creator( - final Content.ContentCreateRequest contentCreateRequest - ) { - return new ContentCreator(contentCreateRequest); - } + //@JsonDeserialize(builder = ListItem.Builder.class) + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @ToString + public static class ListItem { + public ListItem(final String id, final String item) { + this.id = id; + this.item = item; + } - public static ContentDeleter deleter(final String pathSid) { - return new ContentDeleter(pathSid); - } + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("id") + @Getter + @Setter + private String id; - public static ContentFetcher fetcher(final String pathSid) { - return new ContentFetcher(pathSid); - } + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("item") + @Getter + @Setter + private String item; + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("description") + @Getter + @Setter + private String description; - public static ContentReader reader() { - return new ContentReader(); } /** * Converts a JSON String into a Content object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Content object represented by the provided JSON */ - public static Content fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Content fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Content.class); @@ -988,14 +1172,11 @@ public static Content fromJson( * Converts a JSON InputStream into a Content object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Content object represented by the provided JSON */ - public static Content fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Content fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Content.class); @@ -1018,80 +1199,53 @@ public static String toJson(Object object, ObjectMapper mapper) { } } + + @Getter + private final String accountSid; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; - private final String sid; - private final String accountSid; + @Getter private final String friendlyName; + @Getter private final String language; - private final Map variables; - private final Map types; - private final URI url; + @Getter private final Map links; + @Getter + private final String sid; + @Getter + private final Object types; + @Getter + private final URI url; + @Getter + private final Object variables; @JsonCreator private Content( - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("language") final String language, - @JsonProperty("variables") final Map variables, - @JsonProperty("types") final Map types, - @JsonProperty("url") final URI url, - @JsonProperty("links") final Map links + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("language") final String language, + @JsonProperty("links") final Map links, + @JsonProperty("sid") final String sid, + @JsonProperty("types") final Object types, + @JsonProperty("url") final URI url, + @JsonProperty("variables") final Object variables ) { - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); - this.sid = sid; this.accountSid = accountSid; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.friendlyName = friendlyName; this.language = language; - this.variables = variables; + this.links = links; + this.sid = sid; this.types = types; this.url = url; - this.links = links; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final String getLanguage() { - return this.language; - } - - public final Map getVariables() { - return this.variables; - } - - public final Map getTypes() { - return this.types; - } - - public final URI getUrl() { - return this.url; - } - - public final Map getLinks() { - return this.links; + this.variables = variables; } @Override @@ -1105,170 +1259,36 @@ public boolean equals(final Object o) { } Content other = (Content) o; - return ( - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(language, other.language) && - Objects.equals(variables, other.variables) && - Objects.equals(types, other.types) && - Objects.equals(url, other.url) && - Objects.equals(links, other.links) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(language, other.language) && + Objects.equals(links, other.links) && + Objects.equals(sid, other.sid) && + Objects.equals(types, other.types) && + Objects.equals(url, other.url) && + Objects.equals(variables, other.variables) ); } @Override public int hashCode() { return Objects.hash( - dateCreated, - dateUpdated, - sid, - accountSid, - friendlyName, - language, - variables, - types, - url, - links + accountSid, + dateCreated, + dateUpdated, + friendlyName, + language, + links, + sid, + types, + url, + variables ); } - public enum QuickReplyActionType { - QUICK_REPLY("QUICK_REPLY"); - - private final String value; - - private QuickReplyActionType(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static QuickReplyActionType forValue(final String value) { - return Promoter.enumFromString( - value, - QuickReplyActionType.values() - ); - } - } - - public enum WebviewSizeType { - TALL("TALL"), - FULL("FULL"), - HALF("HALF"), - NONE("NONE"); - - private final String value; - - private WebviewSizeType(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static WebviewSizeType forValue(final String value) { - return Promoter.enumFromString(value, WebviewSizeType.values()); - } - } - - public enum CardActionType { - URL("URL"), - PHONE_NUMBER("PHONE_NUMBER"), - QUICK_REPLY("QUICK_REPLY"), - COPY_CODE("COPY_CODE"), - VOICE_CALL("VOICE_CALL"); - - private final String value; - - private CardActionType(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static CardActionType forValue(final String value) { - return Promoter.enumFromString(value, CardActionType.values()); - } - } - - public enum CarouselActionType { - URL("URL"), - PHONE_NUMBER("PHONE_NUMBER"), - QUICK_REPLY("QUICK_REPLY"); - - private final String value; - - private CarouselActionType(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static CarouselActionType forValue(final String value) { - return Promoter.enumFromString(value, CarouselActionType.values()); - } - } - - public enum CallToActionActionType { - URL("URL"), - PHONE_NUMBER("PHONE_NUMBER"), - COPY_CODE("COPY_CODE"), - VOICE_CALL("VOICE_CALL"), - VOICE_CALL_REQUEST("VOICE_CALL_REQUEST"); - - private final String value; - - private CallToActionActionType(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static CallToActionActionType forValue(final String value) { - return Promoter.enumFromString( - value, - CallToActionActionType.values() - ); - } - } - - public enum AuthenticationActionType { - COPY_CODE("COPY_CODE"); - - private final String value; - - private AuthenticationActionType(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - @JsonCreator - public static AuthenticationActionType forValue(final String value) { - return Promoter.enumFromString( - value, - AuthenticationActionType.values() - ); - } - } } + diff --git a/src/main/java/com/twilio/rest/content/v1/ContentAndApprovals.java b/src/main/java/com/twilio/rest/content/v1/ContentAndApprovals.java index 27cf2c06e3..0bbba61ecb 100644 --- a/src/main/java/com/twilio/rest/content/v1/ContentAndApprovals.java +++ b/src/main/java/com/twilio/rest/content/v1/ContentAndApprovals.java @@ -18,42 +18,41 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.time.ZonedDateTime; -import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class ContentAndApprovals extends Resource { - private static final long serialVersionUID = 67575038421166L; public static ContentAndApprovalsReader reader() { - return new ContentAndApprovalsReader(); + return new ContentAndApprovalsReader( + + ); } + /** * Converts a JSON String into a ContentAndApprovals object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return ContentAndApprovals object represented by the provided JSON */ - public static ContentAndApprovals fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static ContentAndApprovals fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, ContentAndApprovals.class); @@ -68,14 +67,11 @@ public static ContentAndApprovals fromJson( * Converts a JSON InputStream into a ContentAndApprovals object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return ContentAndApprovals object represented by the provided JSON */ - public static ContentAndApprovals fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static ContentAndApprovals fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, ContentAndApprovals.class); @@ -86,76 +82,61 @@ public static ContentAndApprovals fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter + private final String accountSid; + @Getter + private final Object approvalRequests; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; - private final String sid; - private final String accountSid; + @Getter private final String friendlyName; + @Getter private final String language; - private final Map variables; - private final Map types; - private final Map approvalRequests; + @Getter + private final String sid; + @Getter + private final Object types; + @Getter + private final Object variables; @JsonCreator private ContentAndApprovals( - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("language") final String language, - @JsonProperty("variables") final Map variables, - @JsonProperty("types") final Map types, - @JsonProperty("approval_requests") final Map< - String, - Object - > approvalRequests + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("approval_requests") final Object approvalRequests, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("language") final String language, + @JsonProperty("sid") final String sid, + @JsonProperty("types") final Object types, + @JsonProperty("variables") final Object variables ) { - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); - this.sid = sid; this.accountSid = accountSid; + this.approvalRequests = approvalRequests; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.friendlyName = friendlyName; this.language = language; - this.variables = variables; + this.sid = sid; this.types = types; - this.approvalRequests = approvalRequests; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final String getLanguage() { - return this.language; - } - - public final Map getVariables() { - return this.variables; - } - - public final Map getTypes() { - return this.types; - } - - public final Map getApprovalRequests() { - return this.approvalRequests; + this.variables = variables; } @Override @@ -169,32 +150,34 @@ public boolean equals(final Object o) { } ContentAndApprovals other = (ContentAndApprovals) o; - return ( - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(language, other.language) && - Objects.equals(variables, other.variables) && - Objects.equals(types, other.types) && - Objects.equals(approvalRequests, other.approvalRequests) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(approvalRequests, other.approvalRequests) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(language, other.language) && + Objects.equals(sid, other.sid) && + Objects.equals(types, other.types) && + Objects.equals(variables, other.variables) ); } @Override public int hashCode() { return Objects.hash( - dateCreated, - dateUpdated, - sid, - accountSid, - friendlyName, - language, - variables, - types, - approvalRequests + accountSid, + approvalRequests, + dateCreated, + dateUpdated, + friendlyName, + language, + sid, + types, + variables ); } + + } + diff --git a/src/main/java/com/twilio/rest/content/v1/ContentAndApprovalsReader.java b/src/main/java/com/twilio/rest/content/v1/ContentAndApprovalsReader.java index f537c90b66..148aa37e20 100644 --- a/src/main/java/com/twilio/rest/content/v1/ContentAndApprovalsReader.java +++ b/src/main/java/com/twilio/rest/content/v1/ContentAndApprovalsReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -31,107 +32,83 @@ public class ContentAndApprovalsReader extends Reader { private Integer pageSize; - public ContentAndApprovalsReader() {} + public ContentAndApprovalsReader() { + } + public ContentAndApprovalsReader setPageSize(final Integer pageSize) { this.pageSize = pageSize; return this; } + @Override - public ResourceSet read( - final TwilioRestClient client - ) { + public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/ContentAndApprovals"; + Request request = new Request( - HttpMethod.GET, - Domains.CONTENT.toString(), - path + HttpMethod.GET, + Domains.CONTENT.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "ContentAndApprovals read failed: Unable to connect to server" - ); + throw new ApiConnectionException("ContentAndApprovals read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "contents", - response.getContent(), - ContentAndApprovals.class, - client.getObjectMapper() - ); + "contents", + response.getContent(), + ContentAndApprovals.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.CONTENT.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.CONTENT.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/content/v1/ContentCreator.java b/src/main/java/com/twilio/rest/content/v1/ContentCreator.java index 47642b9924..428d5bcd85 100644 --- a/src/main/java/com/twilio/rest/content/v1/ContentCreator.java +++ b/src/main/java/com/twilio/rest/content/v1/ContentCreator.java @@ -30,51 +30,42 @@ public class ContentCreator extends Creator { private Content.ContentCreateRequest contentCreateRequest; - public ContentCreator( - final Content.ContentCreateRequest contentCreateRequest - ) { + public ContentCreator(final Content.ContentCreateRequest contentCreateRequest) { this.contentCreateRequest = contentCreateRequest; } - public ContentCreator setContentCreateRequest( - final Content.ContentCreateRequest contentCreateRequest - ) { + + public ContentCreator setContentCreateRequest(final Content.ContentCreateRequest contentCreateRequest) { this.contentCreateRequest = contentCreateRequest; return this; } + @Override public Content create(final TwilioRestClient client) { + String path = "/v1/Content"; - path = - path.replace( - "{" + "ContentCreateRequest" + "}", - this.contentCreateRequest.toString() - ); Request request = new Request( - HttpMethod.POST, - Domains.CONTENT.toString(), - path + HttpMethod.POST, + Domains.CONTENT.toString(), + path ); request.setContentType(EnumConstants.ContentType.JSON); addPostParams(request, client); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Content creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("Content creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/content/v1/ContentDeleter.java b/src/main/java/com/twilio/rest/content/v1/ContentDeleter.java index 630fcef39d..bfbba160f9 100644 --- a/src/main/java/com/twilio/rest/content/v1/ContentDeleter.java +++ b/src/main/java/com/twilio/rest/content/v1/ContentDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.content.v1; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,40 +26,38 @@ public class ContentDeleter extends Deleter { - private String pathSid; + private String pathsid; - public ContentDeleter(final String pathSid) { - this.pathSid = pathSid; + public ContentDeleter(final String pathsid) { + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/v1/Content/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.CONTENT.toString(), - path + HttpMethod.DELETE, + Domains.CONTENT.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Content delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("Content delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/content/v1/ContentFetcher.java b/src/main/java/com/twilio/rest/content/v1/ContentFetcher.java index fa2b3c623b..6bcf8ee4ab 100644 --- a/src/main/java/com/twilio/rest/content/v1/ContentFetcher.java +++ b/src/main/java/com/twilio/rest/content/v1/ContentFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.content.v1; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,44 +26,41 @@ public class ContentFetcher extends Fetcher { - private String pathSid; + private String pathsid; - public ContentFetcher(final String pathSid) { - this.pathSid = pathSid; + public ContentFetcher(final String pathsid) { + this.pathsid = pathsid; } + @Override public Content fetch(final TwilioRestClient client) { + String path = "/v1/Content/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.CONTENT.toString(), - path + HttpMethod.GET, + Domains.CONTENT.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Content fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Content fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Content.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/content/v1/ContentReader.java b/src/main/java/com/twilio/rest/content/v1/ContentReader.java index 40eb2a39bd..374dc95389 100644 --- a/src/main/java/com/twilio/rest/content/v1/ContentReader.java +++ b/src/main/java/com/twilio/rest/content/v1/ContentReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -31,105 +32,83 @@ public class ContentReader extends Reader { private Integer pageSize; - public ContentReader() {} + public ContentReader() { + } + public ContentReader setPageSize(final Integer pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/Content"; + Request request = new Request( - HttpMethod.GET, - Domains.CONTENT.toString(), - path + HttpMethod.GET, + Domains.CONTENT.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Content read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Content read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "contents", - response.getContent(), - Content.class, - client.getObjectMapper() - ); + "contents", + response.getContent(), + Content.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.CONTENT.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.CONTENT.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/content/v1/LegacyContent.java b/src/main/java/com/twilio/rest/content/v1/LegacyContent.java index 131390a1b8..5377c33e07 100644 --- a/src/main/java/com/twilio/rest/content/v1/LegacyContent.java +++ b/src/main/java/com/twilio/rest/content/v1/LegacyContent.java @@ -18,43 +18,42 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; -import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class LegacyContent extends Resource { - private static final long serialVersionUID = 57833124155343L; public static LegacyContentReader reader() { - return new LegacyContentReader(); + return new LegacyContentReader( + + ); } + /** * Converts a JSON String into a LegacyContent object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return LegacyContent object represented by the provided JSON */ - public static LegacyContent fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static LegacyContent fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, LegacyContent.class); @@ -69,14 +68,11 @@ public static LegacyContent fromJson( * Converts a JSON InputStream into a LegacyContent object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return LegacyContent object represented by the provided JSON */ - public static LegacyContent fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static LegacyContent fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, LegacyContent.class); @@ -87,87 +83,69 @@ public static LegacyContent fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter + private final String accountSid; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; - private final String sid; - private final String accountSid; + @Getter private final String friendlyName; + @Getter private final String language; - private final Map variables; - private final Map types; - private final String legacyTemplateName; + @Getter private final String legacyBody; + @Getter + private final String legacyTemplateName; + @Getter + private final String sid; + @Getter + private final Object types; + @Getter private final URI url; + @Getter + private final Object variables; @JsonCreator private LegacyContent( - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("language") final String language, - @JsonProperty("variables") final Map variables, - @JsonProperty("types") final Map types, - @JsonProperty("legacy_template_name") final String legacyTemplateName, - @JsonProperty("legacy_body") final String legacyBody, - @JsonProperty("url") final URI url + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("language") final String language, + @JsonProperty("legacy_body") final String legacyBody, + @JsonProperty("legacy_template_name") final String legacyTemplateName, + @JsonProperty("sid") final String sid, + @JsonProperty("types") final Object types, + @JsonProperty("url") final URI url, + @JsonProperty("variables") final Object variables ) { - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); - this.sid = sid; this.accountSid = accountSid; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.friendlyName = friendlyName; this.language = language; - this.variables = variables; - this.types = types; - this.legacyTemplateName = legacyTemplateName; this.legacyBody = legacyBody; + this.legacyTemplateName = legacyTemplateName; + this.sid = sid; + this.types = types; this.url = url; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final String getLanguage() { - return this.language; - } - - public final Map getVariables() { - return this.variables; - } - - public final Map getTypes() { - return this.types; - } - - public final String getLegacyTemplateName() { - return this.legacyTemplateName; - } - - public final String getLegacyBody() { - return this.legacyBody; - } - - public final URI getUrl() { - return this.url; + this.variables = variables; } @Override @@ -181,36 +159,38 @@ public boolean equals(final Object o) { } LegacyContent other = (LegacyContent) o; - return ( - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(language, other.language) && - Objects.equals(variables, other.variables) && - Objects.equals(types, other.types) && - Objects.equals(legacyTemplateName, other.legacyTemplateName) && - Objects.equals(legacyBody, other.legacyBody) && - Objects.equals(url, other.url) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(language, other.language) && + Objects.equals(legacyBody, other.legacyBody) && + Objects.equals(legacyTemplateName, other.legacyTemplateName) && + Objects.equals(sid, other.sid) && + Objects.equals(types, other.types) && + Objects.equals(url, other.url) && + Objects.equals(variables, other.variables) ); } @Override public int hashCode() { return Objects.hash( - dateCreated, - dateUpdated, - sid, - accountSid, - friendlyName, - language, - variables, - types, - legacyTemplateName, - legacyBody, - url + accountSid, + dateCreated, + dateUpdated, + friendlyName, + language, + legacyBody, + legacyTemplateName, + sid, + types, + url, + variables ); } + + } + diff --git a/src/main/java/com/twilio/rest/content/v1/LegacyContentReader.java b/src/main/java/com/twilio/rest/content/v1/LegacyContentReader.java index 6abe6f40c8..9ca7237594 100644 --- a/src/main/java/com/twilio/rest/content/v1/LegacyContentReader.java +++ b/src/main/java/com/twilio/rest/content/v1/LegacyContentReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -31,105 +32,83 @@ public class LegacyContentReader extends Reader { private Integer pageSize; - public LegacyContentReader() {} + public LegacyContentReader() { + } + public LegacyContentReader setPageSize(final Integer pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/LegacyContent"; + Request request = new Request( - HttpMethod.GET, - Domains.CONTENT.toString(), - path + HttpMethod.GET, + Domains.CONTENT.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "LegacyContent read failed: Unable to connect to server" - ); + throw new ApiConnectionException("LegacyContent read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "contents", - response.getContent(), - LegacyContent.class, - client.getObjectMapper() - ); + "contents", + response.getContent(), + LegacyContent.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.CONTENT.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.CONTENT.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/content/v1/content/ApprovalCreate.java b/src/main/java/com/twilio/rest/content/v1/content/ApprovalCreate.java index aff2efdaf5..ad6e636f60 100644 --- a/src/main/java/com/twilio/rest/content/v1/content/ApprovalCreate.java +++ b/src/main/java/com/twilio/rest/content/v1/content/ApprovalCreate.java @@ -25,22 +25,34 @@ import com.twilio.base.Resource; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; -import java.io.IOException; -import java.io.InputStream; -import java.util.Objects; import lombok.Getter; import lombok.Setter; import lombok.ToString; -import lombok.ToString; + +import java.io.IOException; +import java.io.InputStream; +import java.util.Objects; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class ApprovalCreate extends Resource { - private static final long serialVersionUID = 150858338844938L; + public static ApprovalCreateCreator creator(final String pathcontentSid, final ApprovalCreate.ContentApprovalRequest contentApprovalRequest) { + return new ApprovalCreateCreator( + pathcontentSid, contentApprovalRequest + ); + } + + + //@JsonDeserialize(builder = ContentApprovalRequest.Builder.class) + @JsonInclude(JsonInclude.Include.NON_EMPTY) @ToString public static class ContentApprovalRequest { + public ContentApprovalRequest(final String name, final String category) { + this.name = name; + this.category = category; + } @JsonInclude(JsonInclude.Include.NON_EMPTY) @JsonProperty("name") @@ -54,43 +66,16 @@ public static class ContentApprovalRequest { @Setter private String category; - public ContentApprovalRequest( - final String name, - final String category - ) { - this.name = name; - this.category = category; - } - - public static ContentApprovalRequest fromJson( - String jsonString, - ObjectMapper mapper - ) throws IOException { - return mapper.readValue(jsonString, ContentApprovalRequest.class); - } - } - - public static ApprovalCreateCreator creator( - final String pathContentSid, - final ApprovalCreate.ContentApprovalRequest contentApprovalRequest - ) { - return new ApprovalCreateCreator( - pathContentSid, - contentApprovalRequest - ); } /** * Converts a JSON String into a ApprovalCreate object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return ApprovalCreate object represented by the provided JSON */ - public static ApprovalCreate fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static ApprovalCreate fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, ApprovalCreate.class); @@ -105,14 +90,11 @@ public static ApprovalCreate fromJson( * Converts a JSON InputStream into a ApprovalCreate object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return ApprovalCreate object represented by the provided JSON */ - public static ApprovalCreate fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static ApprovalCreate fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, ApprovalCreate.class); @@ -135,52 +117,35 @@ public static String toJson(Object object, ObjectMapper mapper) { } } - private final String name; + + @Getter + private final Boolean allowCategoryChange; + @Getter private final String category; + @Getter private final String contentType; - private final String status; + @Getter + private final String name; + @Getter private final String rejectionReason; - private final Boolean allowCategoryChange; + @Getter + private final String status; @JsonCreator private ApprovalCreate( - @JsonProperty("name") final String name, - @JsonProperty("category") final String category, - @JsonProperty("content_type") final String contentType, - @JsonProperty("status") final String status, - @JsonProperty("rejection_reason") final String rejectionReason, - @JsonProperty("allow_category_change") final Boolean allowCategoryChange + @JsonProperty("allow_category_change") final Boolean allowCategoryChange, + @JsonProperty("category") final String category, + @JsonProperty("content_type") final String contentType, + @JsonProperty("name") final String name, + @JsonProperty("rejection_reason") final String rejectionReason, + @JsonProperty("status") final String status ) { - this.name = name; + this.allowCategoryChange = allowCategoryChange; this.category = category; this.contentType = contentType; - this.status = status; + this.name = name; this.rejectionReason = rejectionReason; - this.allowCategoryChange = allowCategoryChange; - } - - public final String getName() { - return this.name; - } - - public final String getCategory() { - return this.category; - } - - public final String getContentType() { - return this.contentType; - } - - public final String getStatus() { - return this.status; - } - - public final String getRejectionReason() { - return this.rejectionReason; - } - - public final Boolean getAllowCategoryChange() { - return this.allowCategoryChange; + this.status = status; } @Override @@ -194,26 +159,28 @@ public boolean equals(final Object o) { } ApprovalCreate other = (ApprovalCreate) o; - return ( - Objects.equals(name, other.name) && - Objects.equals(category, other.category) && - Objects.equals(contentType, other.contentType) && - Objects.equals(status, other.status) && - Objects.equals(rejectionReason, other.rejectionReason) && - Objects.equals(allowCategoryChange, other.allowCategoryChange) + Objects.equals(allowCategoryChange, other.allowCategoryChange) && + Objects.equals(category, other.category) && + Objects.equals(contentType, other.contentType) && + Objects.equals(name, other.name) && + Objects.equals(rejectionReason, other.rejectionReason) && + Objects.equals(status, other.status) ); } @Override public int hashCode() { return Objects.hash( - name, - category, - contentType, - status, - rejectionReason, - allowCategoryChange + allowCategoryChange, + category, + contentType, + name, + rejectionReason, + status ); } + + } + diff --git a/src/main/java/com/twilio/rest/content/v1/content/ApprovalCreateCreator.java b/src/main/java/com/twilio/rest/content/v1/content/ApprovalCreateCreator.java index b29c547ab4..4d9ac4846a 100644 --- a/src/main/java/com/twilio/rest/content/v1/content/ApprovalCreateCreator.java +++ b/src/main/java/com/twilio/rest/content/v1/content/ApprovalCreateCreator.java @@ -28,77 +28,59 @@ public class ApprovalCreateCreator extends Creator { - private String pathContentSid; + private String pathcontentSid; private ApprovalCreate.ContentApprovalRequest contentApprovalRequest; - public ApprovalCreateCreator( - final String pathContentSid, - final ApprovalCreate.ContentApprovalRequest contentApprovalRequest - ) { - this.pathContentSid = pathContentSid; + public ApprovalCreateCreator(final String pathcontentSid, final ApprovalCreate.ContentApprovalRequest contentApprovalRequest) { + this.pathcontentSid = pathcontentSid; this.contentApprovalRequest = contentApprovalRequest; } - public ApprovalCreateCreator setContentApprovalRequest( - final ApprovalCreate.ContentApprovalRequest contentApprovalRequest - ) { + + public ApprovalCreateCreator setContentApprovalRequest(final ApprovalCreate.ContentApprovalRequest contentApprovalRequest) { this.contentApprovalRequest = contentApprovalRequest; return this; } + @Override public ApprovalCreate create(final TwilioRestClient client) { + String path = "/v1/Content/{ContentSid}/ApprovalRequests/whatsapp"; - path = - path.replace( - "{" + "ContentSid" + "}", - this.pathContentSid.toString() - ); - path = - path.replace( - "{" + "ContentApprovalRequest" + "}", - this.contentApprovalRequest.toString() - ); + path = path.replace("{" + "ContentSid" + "}", this.pathcontentSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.CONTENT.toString(), - path + HttpMethod.POST, + Domains.CONTENT.toString(), + path ); request.setContentType(EnumConstants.ContentType.JSON); addPostParams(request, client); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "ApprovalCreate creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("ApprovalCreate creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return ApprovalCreate.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return ApprovalCreate.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request, TwilioRestClient client) { ObjectMapper objectMapper = client.getObjectMapper(); if (contentApprovalRequest != null) { - request.setBody( - ApprovalCreate.toJson(contentApprovalRequest, objectMapper) - ); + request.setBody(ApprovalCreate.toJson(contentApprovalRequest, objectMapper)); } } } diff --git a/src/main/java/com/twilio/rest/content/v1/content/ApprovalFetch.java b/src/main/java/com/twilio/rest/content/v1/content/ApprovalFetch.java index 6893d223b7..c69cb3fc3d 100644 --- a/src/main/java/com/twilio/rest/content/v1/content/ApprovalFetch.java +++ b/src/main/java/com/twilio/rest/content/v1/content/ApprovalFetch.java @@ -18,41 +18,40 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; -import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class ApprovalFetch extends Resource { - private static final long serialVersionUID = 266557741388539L; - public static ApprovalFetchFetcher fetcher(final String pathSid) { - return new ApprovalFetchFetcher(pathSid); + public static ApprovalFetchFetcher fetcher(final String pathsid) { + return new ApprovalFetchFetcher( + pathsid + ); } + /** * Converts a JSON String into a ApprovalFetch object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return ApprovalFetch object represented by the provided JSON */ - public static ApprovalFetch fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static ApprovalFetch fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, ApprovalFetch.class); @@ -67,14 +66,11 @@ public static ApprovalFetch fromJson( * Converts a JSON InputStream into a ApprovalFetch object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return ApprovalFetch object represented by the provided JSON */ - public static ApprovalFetch fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static ApprovalFetch fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, ApprovalFetch.class); @@ -85,38 +81,39 @@ public static ApprovalFetch fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final Map whatsapp; + @Getter + private final String sid; + @Getter private final URI url; + @Getter + private final Object whatsapp; @JsonCreator private ApprovalFetch( - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("whatsapp") final Map whatsapp, - @JsonProperty("url") final URI url + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("sid") final String sid, + @JsonProperty("url") final URI url, + @JsonProperty("whatsapp") final Object whatsapp ) { - this.sid = sid; this.accountSid = accountSid; - this.whatsapp = whatsapp; + this.sid = sid; this.url = url; - } - - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final Map getWhatsapp() { - return this.whatsapp; - } - - public final URI getUrl() { - return this.url; + this.whatsapp = whatsapp; } @Override @@ -130,17 +127,24 @@ public boolean equals(final Object o) { } ApprovalFetch other = (ApprovalFetch) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(whatsapp, other.whatsapp) && - Objects.equals(url, other.url) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(sid, other.sid) && + Objects.equals(url, other.url) && + Objects.equals(whatsapp, other.whatsapp) ); } @Override public int hashCode() { - return Objects.hash(sid, accountSid, whatsapp, url); + return Objects.hash( + accountSid, + sid, + url, + whatsapp + ); } + + } + diff --git a/src/main/java/com/twilio/rest/content/v1/content/ApprovalFetchFetcher.java b/src/main/java/com/twilio/rest/content/v1/content/ApprovalFetchFetcher.java index 656e2d6ee1..db8969a01d 100644 --- a/src/main/java/com/twilio/rest/content/v1/content/ApprovalFetchFetcher.java +++ b/src/main/java/com/twilio/rest/content/v1/content/ApprovalFetchFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.content.v1.content; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,47 +26,41 @@ public class ApprovalFetchFetcher extends Fetcher { - private String pathSid; + private String pathsid; - public ApprovalFetchFetcher(final String pathSid) { - this.pathSid = pathSid; + public ApprovalFetchFetcher(final String pathsid) { + this.pathsid = pathsid; } + @Override public ApprovalFetch fetch(final TwilioRestClient client) { + String path = "/v1/Content/{Sid}/ApprovalRequests"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.CONTENT.toString(), - path + HttpMethod.GET, + Domains.CONTENT.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "ApprovalFetch fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("ApprovalFetch fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return ApprovalFetch.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return ApprovalFetch.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/content/v2/Content.java b/src/main/java/com/twilio/rest/content/v2/Content.java index 68c338901d..ab8d7bfe43 100644 --- a/src/main/java/com/twilio/rest/content/v2/Content.java +++ b/src/main/java/com/twilio/rest/content/v2/Content.java @@ -18,43 +18,43 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Content extends Resource { - private static final long serialVersionUID = 58899890984300L; public static ContentReader reader() { - return new ContentReader(); + return new ContentReader( + + ); } + /** * Converts a JSON String into a Content object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Content object represented by the provided JSON */ - public static Content fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Content fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Content.class); @@ -69,14 +69,11 @@ public static Content fromJson( * Converts a JSON InputStream into a Content object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Content object represented by the provided JSON */ - public static Content fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Content fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Content.class); @@ -87,80 +84,65 @@ public static Content fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter + private final String accountSid; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; - private final String sid; - private final String accountSid; + @Getter private final String friendlyName; + @Getter private final String language; - private final Map variables; - private final Map types; - private final URI url; + @Getter private final Map links; + @Getter + private final String sid; + @Getter + private final Object types; + @Getter + private final URI url; + @Getter + private final Object variables; @JsonCreator private Content( - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("language") final String language, - @JsonProperty("variables") final Map variables, - @JsonProperty("types") final Map types, - @JsonProperty("url") final URI url, - @JsonProperty("links") final Map links + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("language") final String language, + @JsonProperty("links") final Map links, + @JsonProperty("sid") final String sid, + @JsonProperty("types") final Object types, + @JsonProperty("url") final URI url, + @JsonProperty("variables") final Object variables ) { - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); - this.sid = sid; this.accountSid = accountSid; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.friendlyName = friendlyName; this.language = language; - this.variables = variables; + this.links = links; + this.sid = sid; this.types = types; this.url = url; - this.links = links; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final String getLanguage() { - return this.language; - } - - public final Map getVariables() { - return this.variables; - } - - public final Map getTypes() { - return this.types; - } - - public final URI getUrl() { - return this.url; - } - - public final Map getLinks() { - return this.links; + this.variables = variables; } @Override @@ -174,34 +156,36 @@ public boolean equals(final Object o) { } Content other = (Content) o; - return ( - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(language, other.language) && - Objects.equals(variables, other.variables) && - Objects.equals(types, other.types) && - Objects.equals(url, other.url) && - Objects.equals(links, other.links) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(language, other.language) && + Objects.equals(links, other.links) && + Objects.equals(sid, other.sid) && + Objects.equals(types, other.types) && + Objects.equals(url, other.url) && + Objects.equals(variables, other.variables) ); } @Override public int hashCode() { return Objects.hash( - dateCreated, - dateUpdated, - sid, - accountSid, - friendlyName, - language, - variables, - types, - url, - links + accountSid, + dateCreated, + dateUpdated, + friendlyName, + language, + links, + sid, + types, + url, + variables ); } + + } + diff --git a/src/main/java/com/twilio/rest/content/v2/ContentAndApprovals.java b/src/main/java/com/twilio/rest/content/v2/ContentAndApprovals.java index 54953760ff..f6236f37a4 100644 --- a/src/main/java/com/twilio/rest/content/v2/ContentAndApprovals.java +++ b/src/main/java/com/twilio/rest/content/v2/ContentAndApprovals.java @@ -18,42 +18,41 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.time.ZonedDateTime; -import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class ContentAndApprovals extends Resource { - private static final long serialVersionUID = 67575038421166L; public static ContentAndApprovalsReader reader() { - return new ContentAndApprovalsReader(); + return new ContentAndApprovalsReader( + + ); } + /** * Converts a JSON String into a ContentAndApprovals object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return ContentAndApprovals object represented by the provided JSON */ - public static ContentAndApprovals fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static ContentAndApprovals fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, ContentAndApprovals.class); @@ -68,14 +67,11 @@ public static ContentAndApprovals fromJson( * Converts a JSON InputStream into a ContentAndApprovals object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return ContentAndApprovals object represented by the provided JSON */ - public static ContentAndApprovals fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static ContentAndApprovals fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, ContentAndApprovals.class); @@ -86,76 +82,61 @@ public static ContentAndApprovals fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter + private final String accountSid; + @Getter + private final Object approvalRequests; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; - private final String sid; - private final String accountSid; + @Getter private final String friendlyName; + @Getter private final String language; - private final Map variables; - private final Map types; - private final Map approvalRequests; + @Getter + private final String sid; + @Getter + private final Object types; + @Getter + private final Object variables; @JsonCreator private ContentAndApprovals( - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("language") final String language, - @JsonProperty("variables") final Map variables, - @JsonProperty("types") final Map types, - @JsonProperty("approval_requests") final Map< - String, - Object - > approvalRequests + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("approval_requests") final Object approvalRequests, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("language") final String language, + @JsonProperty("sid") final String sid, + @JsonProperty("types") final Object types, + @JsonProperty("variables") final Object variables ) { - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); - this.sid = sid; this.accountSid = accountSid; + this.approvalRequests = approvalRequests; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.friendlyName = friendlyName; this.language = language; - this.variables = variables; + this.sid = sid; this.types = types; - this.approvalRequests = approvalRequests; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final String getLanguage() { - return this.language; - } - - public final Map getVariables() { - return this.variables; - } - - public final Map getTypes() { - return this.types; - } - - public final Map getApprovalRequests() { - return this.approvalRequests; + this.variables = variables; } @Override @@ -169,32 +150,34 @@ public boolean equals(final Object o) { } ContentAndApprovals other = (ContentAndApprovals) o; - return ( - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(language, other.language) && - Objects.equals(variables, other.variables) && - Objects.equals(types, other.types) && - Objects.equals(approvalRequests, other.approvalRequests) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(approvalRequests, other.approvalRequests) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(language, other.language) && + Objects.equals(sid, other.sid) && + Objects.equals(types, other.types) && + Objects.equals(variables, other.variables) ); } @Override public int hashCode() { return Objects.hash( - dateCreated, - dateUpdated, - sid, - accountSid, - friendlyName, - language, - variables, - types, - approvalRequests + accountSid, + approvalRequests, + dateCreated, + dateUpdated, + friendlyName, + language, + sid, + types, + variables ); } + + } + diff --git a/src/main/java/com/twilio/rest/content/v2/ContentAndApprovalsReader.java b/src/main/java/com/twilio/rest/content/v2/ContentAndApprovalsReader.java index dfb93ee141..7bbaaad216 100644 --- a/src/main/java/com/twilio/rest/content/v2/ContentAndApprovalsReader.java +++ b/src/main/java/com/twilio/rest/content/v2/ContentAndApprovalsReader.java @@ -17,8 +17,9 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; import com.twilio.converter.Promoter; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,6 +28,7 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.time.ZonedDateTime; import java.util.List; @@ -43,49 +45,52 @@ public class ContentAndApprovalsReader extends Reader { private List contentType; private List channelEligibility; - public ContentAndApprovalsReader() {} + public ContentAndApprovalsReader() { + } + public ContentAndApprovalsReader setPageSize(final Integer pageSize) { this.pageSize = pageSize; return this; } + public ContentAndApprovalsReader setSortByDate(final String sortByDate) { this.sortByDate = sortByDate; return this; } - public ContentAndApprovalsReader setSortByContentName( - final String sortByContentName - ) { + + public ContentAndApprovalsReader setSortByContentName(final String sortByContentName) { this.sortByContentName = sortByContentName; return this; } - public ContentAndApprovalsReader setDateCreatedAfter( - final ZonedDateTime dateCreatedAfter - ) { + + public ContentAndApprovalsReader setDateCreatedAfter(final ZonedDateTime dateCreatedAfter) { this.dateCreatedAfter = dateCreatedAfter; return this; } - public ContentAndApprovalsReader setDateCreatedBefore( - final ZonedDateTime dateCreatedBefore - ) { + + public ContentAndApprovalsReader setDateCreatedBefore(final ZonedDateTime dateCreatedBefore) { this.dateCreatedBefore = dateCreatedBefore; return this; } + public ContentAndApprovalsReader setContentName(final String contentName) { this.contentName = contentName; return this; } + public ContentAndApprovalsReader setContent(final String content) { this.content = content; return this; } + public ContentAndApprovalsReader setLanguage(final List language) { this.language = language; return this; @@ -95,9 +100,7 @@ public ContentAndApprovalsReader setLanguage(final String language) { return setLanguage(Promoter.listOfOne(language)); } - public ContentAndApprovalsReader setContentType( - final List contentType - ) { + public ContentAndApprovalsReader setContentType(final List contentType) { this.contentType = contentType; return this; } @@ -106,154 +109,132 @@ public ContentAndApprovalsReader setContentType(final String contentType) { return setContentType(Promoter.listOfOne(contentType)); } - public ContentAndApprovalsReader setChannelEligibility( - final List channelEligibility - ) { + public ContentAndApprovalsReader setChannelEligibility(final List channelEligibility) { this.channelEligibility = channelEligibility; return this; } - public ContentAndApprovalsReader setChannelEligibility( - final String channelEligibility - ) { + public ContentAndApprovalsReader setChannelEligibility(final String channelEligibility) { return setChannelEligibility(Promoter.listOfOne(channelEligibility)); } @Override - public ResourceSet read( - final TwilioRestClient client - ) { + public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v2/ContentAndApprovals"; + Request request = new Request( - HttpMethod.GET, - Domains.CONTENT.toString(), - path + HttpMethod.GET, + Domains.CONTENT.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "ContentAndApprovals read failed: Unable to connect to server" - ); + throw new ApiConnectionException("ContentAndApprovals read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "contents", - response.getContent(), - ContentAndApprovals.class, - client.getObjectMapper() - ); + "contents", + response.getContent(), + ContentAndApprovals.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.CONTENT.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.CONTENT.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } + + if (sortByDate != null) { - request.addQueryParam("SortByDate", sortByDate); + Serializer.toString(request, "SortByDate", sortByDate, ParameterType.QUERY); } + + if (sortByContentName != null) { - request.addQueryParam("SortByContentName", sortByContentName); + Serializer.toString(request, "SortByContentName", sortByContentName, ParameterType.QUERY); } + + if (dateCreatedAfter != null) { - request.addQueryParam( - "DateCreatedAfter", - dateCreatedAfter.toInstant().toString() - ); + Serializer.toString(request, "DateCreatedAfter", dateCreatedAfter, ParameterType.QUERY); } + if (dateCreatedBefore != null) { - request.addQueryParam( - "DateCreatedBefore", - dateCreatedBefore.toInstant().toString() - ); + Serializer.toString(request, "DateCreatedBefore", dateCreatedBefore, ParameterType.QUERY); } + if (contentName != null) { - request.addQueryParam("ContentName", contentName); + Serializer.toString(request, "ContentName", contentName, ParameterType.QUERY); } + + if (content != null) { - request.addQueryParam("Content", content); + Serializer.toString(request, "Content", content, ParameterType.QUERY); } + + if (language != null) { - for (String prop : language) { - request.addQueryParam("Language", prop); + for (String param : language) { + Serializer.toString(request, "Language", param, ParameterType.QUERY); } } + + if (contentType != null) { - for (String prop : contentType) { - request.addQueryParam("ContentType", prop); + for (String param : contentType) { + Serializer.toString(request, "ContentType", param, ParameterType.QUERY); } } + + if (channelEligibility != null) { - for (String prop : channelEligibility) { - request.addQueryParam("ChannelEligibility", prop); + for (String param : channelEligibility) { + Serializer.toString(request, "ChannelEligibility", param, ParameterType.QUERY); } } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } } } diff --git a/src/main/java/com/twilio/rest/content/v2/ContentReader.java b/src/main/java/com/twilio/rest/content/v2/ContentReader.java index 202dc23db3..8679d8a513 100644 --- a/src/main/java/com/twilio/rest/content/v2/ContentReader.java +++ b/src/main/java/com/twilio/rest/content/v2/ContentReader.java @@ -17,8 +17,9 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; import com.twilio.converter.Promoter; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,6 +28,7 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.time.ZonedDateTime; import java.util.List; @@ -43,47 +45,52 @@ public class ContentReader extends Reader { private List contentType; private List channelEligibility; - public ContentReader() {} + public ContentReader() { + } + public ContentReader setPageSize(final Integer pageSize) { this.pageSize = pageSize; return this; } + public ContentReader setSortByDate(final String sortByDate) { this.sortByDate = sortByDate; return this; } + public ContentReader setSortByContentName(final String sortByContentName) { this.sortByContentName = sortByContentName; return this; } - public ContentReader setDateCreatedAfter( - final ZonedDateTime dateCreatedAfter - ) { + + public ContentReader setDateCreatedAfter(final ZonedDateTime dateCreatedAfter) { this.dateCreatedAfter = dateCreatedAfter; return this; } - public ContentReader setDateCreatedBefore( - final ZonedDateTime dateCreatedBefore - ) { + + public ContentReader setDateCreatedBefore(final ZonedDateTime dateCreatedBefore) { this.dateCreatedBefore = dateCreatedBefore; return this; } + public ContentReader setContentName(final String contentName) { this.contentName = contentName; return this; } + public ContentReader setContent(final String content) { this.content = content; return this; } + public ContentReader setLanguage(final List language) { this.language = language; return this; @@ -102,16 +109,12 @@ public ContentReader setContentType(final String contentType) { return setContentType(Promoter.listOfOne(contentType)); } - public ContentReader setChannelEligibility( - final List channelEligibility - ) { + public ContentReader setChannelEligibility(final List channelEligibility) { this.channelEligibility = channelEligibility; return this; } - public ContentReader setChannelEligibility( - final String channelEligibility - ) { + public ContentReader setChannelEligibility(final String channelEligibility) { return setChannelEligibility(Promoter.listOfOne(channelEligibility)); } @@ -121,133 +124,117 @@ public ResourceSet read(final TwilioRestClient client) { } public Page firstPage(final TwilioRestClient client) { + String path = "/v2/Content"; + Request request = new Request( - HttpMethod.GET, - Domains.CONTENT.toString(), - path + HttpMethod.GET, + Domains.CONTENT.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Content read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Content read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "contents", - response.getContent(), - Content.class, - client.getObjectMapper() - ); + "contents", + response.getContent(), + Content.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.CONTENT.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.CONTENT.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } + + if (sortByDate != null) { - request.addQueryParam("SortByDate", sortByDate); + Serializer.toString(request, "SortByDate", sortByDate, ParameterType.QUERY); } + + if (sortByContentName != null) { - request.addQueryParam("SortByContentName", sortByContentName); + Serializer.toString(request, "SortByContentName", sortByContentName, ParameterType.QUERY); } + + if (dateCreatedAfter != null) { - request.addQueryParam( - "DateCreatedAfter", - dateCreatedAfter.toInstant().toString() - ); + Serializer.toString(request, "DateCreatedAfter", dateCreatedAfter, ParameterType.QUERY); } + if (dateCreatedBefore != null) { - request.addQueryParam( - "DateCreatedBefore", - dateCreatedBefore.toInstant().toString() - ); + Serializer.toString(request, "DateCreatedBefore", dateCreatedBefore, ParameterType.QUERY); } + if (contentName != null) { - request.addQueryParam("ContentName", contentName); + Serializer.toString(request, "ContentName", contentName, ParameterType.QUERY); } + + if (content != null) { - request.addQueryParam("Content", content); + Serializer.toString(request, "Content", content, ParameterType.QUERY); } + + if (language != null) { - for (String prop : language) { - request.addQueryParam("Language", prop); + for (String param : language) { + Serializer.toString(request, "Language", param, ParameterType.QUERY); } } + + if (contentType != null) { - for (String prop : contentType) { - request.addQueryParam("ContentType", prop); + for (String param : contentType) { + Serializer.toString(request, "ContentType", param, ParameterType.QUERY); } } + + if (channelEligibility != null) { - for (String prop : channelEligibility) { - request.addQueryParam("ChannelEligibility", prop); + for (String param : channelEligibility) { + Serializer.toString(request, "ChannelEligibility", param, ParameterType.QUERY); } } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } } } diff --git a/src/main/java/com/twilio/rest/conversations/v1/AddressConfiguration.java b/src/main/java/com/twilio/rest/conversations/v1/AddressConfiguration.java index b0b200cf5f..37d9697809 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/AddressConfiguration.java +++ b/src/main/java/com/twilio/rest/conversations/v1/AddressConfiguration.java @@ -18,63 +18,139 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; -import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class AddressConfiguration extends Resource { - private static final long serialVersionUID = 162346024858734L; - public static AddressConfigurationCreator creator( - final AddressConfiguration.Type type, - final String address - ) { - return new AddressConfigurationCreator(type, address); + public static AddressConfigurationCreator creator(final AddressConfiguration.Type type, final String address) { + return new AddressConfigurationCreator( + type, address + ); } - public static AddressConfigurationDeleter deleter(final String pathSid) { - return new AddressConfigurationDeleter(pathSid); + + public static AddressConfigurationDeleter deleter(final String pathsid) { + return new AddressConfigurationDeleter( + pathsid + ); } - public static AddressConfigurationFetcher fetcher(final String pathSid) { - return new AddressConfigurationFetcher(pathSid); + + public static AddressConfigurationFetcher fetcher(final String pathsid) { + return new AddressConfigurationFetcher( + pathsid + ); } + public static AddressConfigurationReader reader() { - return new AddressConfigurationReader(); + return new AddressConfigurationReader( + + ); } - public static AddressConfigurationUpdater updater(final String pathSid) { - return new AddressConfigurationUpdater(pathSid); + + public static AddressConfigurationUpdater updater(final String pathsid) { + return new AddressConfigurationUpdater( + pathsid + ); + } + + + public enum Type { + SMS("sms"), + WHATSAPP("whatsapp"), + MESSENGER("messenger"), + GBM("gbm"), + EMAIL("email"), + RCS("rcs"), + APPLE("apple"), + CHAT("chat"); + + private final String value; + + private Type(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static Type forValue(final String value) { + return Promoter.enumFromString(value, Type.values()); + } } + public enum Method { + GET("get"), + POST("post"); + + private final String value; + + private Method(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static Method forValue(final String value) { + return Promoter.enumFromString(value, Method.values()); + } + } + + public enum AutoCreationType { + WEBHOOK("webhook"), + STUDIO("studio"), + DEFAULT("default"); + + private final String value; + + private AutoCreationType(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static AutoCreationType forValue(final String value) { + return Promoter.enumFromString(value, AutoCreationType.values()); + } + } + + /** * Converts a JSON String into a AddressConfiguration object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return AddressConfiguration object represented by the provided JSON */ - public static AddressConfiguration fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static AddressConfiguration fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, AddressConfiguration.class); @@ -89,14 +165,11 @@ public static AddressConfiguration fromJson( * Converts a JSON InputStream into a AddressConfiguration object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return AddressConfiguration object represented by the provided JSON */ - public static AddressConfiguration fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static AddressConfiguration fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, AddressConfiguration.class); @@ -107,80 +180,65 @@ public static AddressConfiguration fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String type; + @Getter private final String address; - private final String friendlyName; - private final Map autoCreation; + @Getter + private final String addressCountry; + @Getter + private final Object autoCreation; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; + @Getter + private final String friendlyName; + @Getter + private final String sid; + @Getter + private final String type; + @Getter private final URI url; - private final String addressCountry; @JsonCreator private AddressConfiguration( - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("type") final String type, - @JsonProperty("address") final String address, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("auto_creation") final Map autoCreation, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("url") final URI url, - @JsonProperty("address_country") final String addressCountry + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("address") final String address, + @JsonProperty("address_country") final String addressCountry, + @JsonProperty("auto_creation") final Object autoCreation, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("sid") final String sid, + @JsonProperty("type") final String type, + @JsonProperty("url") final URI url ) { - this.sid = sid; this.accountSid = accountSid; - this.type = type; this.address = address; - this.friendlyName = friendlyName; + this.addressCountry = addressCountry; this.autoCreation = autoCreation; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; + this.friendlyName = friendlyName; + this.sid = sid; + this.type = type; this.url = url; - this.addressCountry = addressCountry; - } - - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getType() { - return this.type; - } - - public final String getAddress() { - return this.address; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final Map getAutoCreation() { - return this.autoCreation; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final URI getUrl() { - return this.url; - } - - public final String getAddressCountry() { - return this.addressCountry; } @Override @@ -194,101 +252,36 @@ public boolean equals(final Object o) { } AddressConfiguration other = (AddressConfiguration) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(type, other.type) && - Objects.equals(address, other.address) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(autoCreation, other.autoCreation) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(url, other.url) && - Objects.equals(addressCountry, other.addressCountry) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(address, other.address) && + Objects.equals(addressCountry, other.addressCountry) && + Objects.equals(autoCreation, other.autoCreation) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(sid, other.sid) && + Objects.equals(type, other.type) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - sid, - accountSid, - type, - address, - friendlyName, - autoCreation, - dateCreated, - dateUpdated, - url, - addressCountry + accountSid, + address, + addressCountry, + autoCreation, + dateCreated, + dateUpdated, + friendlyName, + sid, + type, + url ); } - public enum AutoCreationType { - WEBHOOK("webhook"), - STUDIO("studio"), - DEFAULT("default"); - private final String value; - - private AutoCreationType(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static AutoCreationType forValue(final String value) { - return Promoter.enumFromString(value, AutoCreationType.values()); - } - } - - public enum Method { - GET("get"), - POST("post"); - - private final String value; - - private Method(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static Method forValue(final String value) { - return Promoter.enumFromString(value, Method.values()); - } - } - - public enum Type { - SMS("sms"), - WHATSAPP("whatsapp"), - MESSENGER("messenger"), - GBM("gbm"), - EMAIL("email"), - RCS("rcs"), - APPLE("apple"), - CHAT("chat"); - - private final String value; - - private Type(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static Type forValue(final String value) { - return Promoter.enumFromString(value, Type.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/conversations/v1/AddressConfigurationCreator.java b/src/main/java/com/twilio/rest/conversations/v1/AddressConfigurationCreator.java index ea9e197e9c..f760503d30 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/AddressConfigurationCreator.java +++ b/src/main/java/com/twilio/rest/conversations/v1/AddressConfigurationCreator.java @@ -14,9 +14,12 @@ package com.twilio.rest.conversations.v1; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; import com.twilio.converter.Promoter; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,7 +28,7 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -import java.util.List; + import java.util.List; public class AddressConfigurationCreator extends Creator { @@ -43,203 +46,182 @@ public class AddressConfigurationCreator extends Creator { private Integer autoCreationStudioRetryCount; private String addressCountry; - public AddressConfigurationCreator( - final AddressConfiguration.Type type, - final String address - ) { + public AddressConfigurationCreator(final AddressConfiguration.Type type, final String address) { this.type = type; this.address = address; } - public AddressConfigurationCreator setType( - final AddressConfiguration.Type type - ) { + + public AddressConfigurationCreator setType(final AddressConfiguration.Type type) { this.type = type; return this; } + public AddressConfigurationCreator setAddress(final String address) { this.address = address; return this; } - public AddressConfigurationCreator setFriendlyName( - final String friendlyName - ) { + + public AddressConfigurationCreator setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } - public AddressConfigurationCreator setAutoCreationEnabled( - final Boolean autoCreationEnabled - ) { + + public AddressConfigurationCreator setAutoCreationEnabled(final Boolean autoCreationEnabled) { this.autoCreationEnabled = autoCreationEnabled; return this; } - public AddressConfigurationCreator setAutoCreationType( - final AddressConfiguration.AutoCreationType autoCreationType - ) { + + public AddressConfigurationCreator setAutoCreationType(final AddressConfiguration.AutoCreationType autoCreationType) { this.autoCreationType = autoCreationType; return this; } - public AddressConfigurationCreator setAutoCreationConversationServiceSid( - final String autoCreationConversationServiceSid - ) { - this.autoCreationConversationServiceSid = - autoCreationConversationServiceSid; + + public AddressConfigurationCreator setAutoCreationConversationServiceSid(final String autoCreationConversationServiceSid) { + this.autoCreationConversationServiceSid = autoCreationConversationServiceSid; return this; } - public AddressConfigurationCreator setAutoCreationWebhookUrl( - final String autoCreationWebhookUrl - ) { + + public AddressConfigurationCreator setAutoCreationWebhookUrl(final String autoCreationWebhookUrl) { this.autoCreationWebhookUrl = autoCreationWebhookUrl; return this; } - public AddressConfigurationCreator setAutoCreationWebhookMethod( - final AddressConfiguration.Method autoCreationWebhookMethod - ) { + + public AddressConfigurationCreator setAutoCreationWebhookMethod(final AddressConfiguration.Method autoCreationWebhookMethod) { this.autoCreationWebhookMethod = autoCreationWebhookMethod; return this; } - public AddressConfigurationCreator setAutoCreationWebhookFilters( - final List autoCreationWebhookFilters - ) { + + public AddressConfigurationCreator setAutoCreationWebhookFilters(final List autoCreationWebhookFilters) { this.autoCreationWebhookFilters = autoCreationWebhookFilters; return this; } - public AddressConfigurationCreator setAutoCreationWebhookFilters( - final String autoCreationWebhookFilters - ) { - return setAutoCreationWebhookFilters( - Promoter.listOfOne(autoCreationWebhookFilters) - ); + public AddressConfigurationCreator setAutoCreationWebhookFilters(final String autoCreationWebhookFilters) { + return setAutoCreationWebhookFilters(Promoter.listOfOne(autoCreationWebhookFilters)); } - public AddressConfigurationCreator setAutoCreationStudioFlowSid( - final String autoCreationStudioFlowSid - ) { + public AddressConfigurationCreator setAutoCreationStudioFlowSid(final String autoCreationStudioFlowSid) { this.autoCreationStudioFlowSid = autoCreationStudioFlowSid; return this; } - public AddressConfigurationCreator setAutoCreationStudioRetryCount( - final Integer autoCreationStudioRetryCount - ) { + + public AddressConfigurationCreator setAutoCreationStudioRetryCount(final Integer autoCreationStudioRetryCount) { this.autoCreationStudioRetryCount = autoCreationStudioRetryCount; return this; } - public AddressConfigurationCreator setAddressCountry( - final String addressCountry - ) { + + public AddressConfigurationCreator setAddressCountry(final String addressCountry) { this.addressCountry = addressCountry; return this; } + @Override public AddressConfiguration create(final TwilioRestClient client) { + String path = "/v1/Configuration/Addresses"; - path = path.replace("{" + "Type" + "}", this.type.toString()); - path = path.replace("{" + "Address" + "}", this.address.toString()); Request request = new Request( - HttpMethod.POST, - Domains.CONVERSATIONS.toString(), - path + HttpMethod.POST, + Domains.CONVERSATIONS.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "AddressConfiguration creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("AddressConfiguration creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return AddressConfiguration.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return AddressConfiguration.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (type != null) { - request.addPostParam("Type", type.toString()); + Serializer.toString(request, "Type", type, ParameterType.URLENCODED); } + + if (address != null) { - request.addPostParam("Address", address); + Serializer.toString(request, "Address", address, ParameterType.URLENCODED); } + + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + if (autoCreationEnabled != null) { - request.addPostParam( - "AutoCreation.Enabled", - autoCreationEnabled.toString() - ); + Serializer.toString(request, "AutoCreation.Enabled", autoCreationEnabled, ParameterType.URLENCODED); } + + if (autoCreationType != null) { - request.addPostParam( - "AutoCreation.Type", - autoCreationType.toString() - ); + Serializer.toString(request, "AutoCreation.Type", autoCreationType, ParameterType.URLENCODED); } + + if (autoCreationConversationServiceSid != null) { - request.addPostParam( - "AutoCreation.ConversationServiceSid", - autoCreationConversationServiceSid - ); + Serializer.toString(request, "AutoCreation.ConversationServiceSid", autoCreationConversationServiceSid, ParameterType.URLENCODED); } + + if (autoCreationWebhookUrl != null) { - request.addPostParam( - "AutoCreation.WebhookUrl", - autoCreationWebhookUrl - ); + Serializer.toString(request, "AutoCreation.WebhookUrl", autoCreationWebhookUrl, ParameterType.URLENCODED); } + + if (autoCreationWebhookMethod != null) { - request.addPostParam( - "AutoCreation.WebhookMethod", - autoCreationWebhookMethod.toString() - ); + Serializer.toString(request, "AutoCreation.WebhookMethod", autoCreationWebhookMethod, ParameterType.URLENCODED); } + + if (autoCreationWebhookFilters != null) { - for (String prop : autoCreationWebhookFilters) { - request.addPostParam("AutoCreation.WebhookFilters", prop); + for (String param : autoCreationWebhookFilters) { + Serializer.toString(request, "AutoCreation.WebhookFilters", param, ParameterType.URLENCODED); } } + + if (autoCreationStudioFlowSid != null) { - request.addPostParam( - "AutoCreation.StudioFlowSid", - autoCreationStudioFlowSid - ); + Serializer.toString(request, "AutoCreation.StudioFlowSid", autoCreationStudioFlowSid, ParameterType.URLENCODED); } + + if (autoCreationStudioRetryCount != null) { - request.addPostParam( - "AutoCreation.StudioRetryCount", - autoCreationStudioRetryCount.toString() - ); + Serializer.toString(request, "AutoCreation.StudioRetryCount", autoCreationStudioRetryCount, ParameterType.URLENCODED); } + + if (addressCountry != null) { - request.addPostParam("AddressCountry", addressCountry); + Serializer.toString(request, "AddressCountry", addressCountry, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/conversations/v1/AddressConfigurationDeleter.java b/src/main/java/com/twilio/rest/conversations/v1/AddressConfigurationDeleter.java index 5a95e9f134..0f3df57a80 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/AddressConfigurationDeleter.java +++ b/src/main/java/com/twilio/rest/conversations/v1/AddressConfigurationDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.conversations.v1; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,40 +26,38 @@ public class AddressConfigurationDeleter extends Deleter { - private String pathSid; + private String pathsid; - public AddressConfigurationDeleter(final String pathSid) { - this.pathSid = pathSid; + public AddressConfigurationDeleter(final String pathsid) { + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/v1/Configuration/Addresses/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.CONVERSATIONS.toString(), - path + HttpMethod.DELETE, + Domains.CONVERSATIONS.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "AddressConfiguration delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("AddressConfiguration delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/conversations/v1/AddressConfigurationFetcher.java b/src/main/java/com/twilio/rest/conversations/v1/AddressConfigurationFetcher.java index efda5dbd1b..9a6aa0ad49 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/AddressConfigurationFetcher.java +++ b/src/main/java/com/twilio/rest/conversations/v1/AddressConfigurationFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.conversations.v1; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,47 +26,41 @@ public class AddressConfigurationFetcher extends Fetcher { - private String pathSid; + private String pathsid; - public AddressConfigurationFetcher(final String pathSid) { - this.pathSid = pathSid; + public AddressConfigurationFetcher(final String pathsid) { + this.pathsid = pathsid; } + @Override public AddressConfiguration fetch(final TwilioRestClient client) { + String path = "/v1/Configuration/Addresses/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.CONVERSATIONS.toString(), - path + HttpMethod.GET, + Domains.CONVERSATIONS.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "AddressConfiguration fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("AddressConfiguration fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return AddressConfiguration.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return AddressConfiguration.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/conversations/v1/AddressConfigurationReader.java b/src/main/java/com/twilio/rest/conversations/v1/AddressConfigurationReader.java index fd379da58a..90df0caa9e 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/AddressConfigurationReader.java +++ b/src/main/java/com/twilio/rest/conversations/v1/AddressConfigurationReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -32,115 +33,94 @@ public class AddressConfigurationReader extends Reader { private String type; private Long pageSize; - public AddressConfigurationReader() {} + public AddressConfigurationReader() { + } + public AddressConfigurationReader setType(final String type) { this.type = type; return this; } + public AddressConfigurationReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override - public ResourceSet read( - final TwilioRestClient client - ) { + public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/Configuration/Addresses"; + Request request = new Request( - HttpMethod.GET, - Domains.CONVERSATIONS.toString(), - path + HttpMethod.GET, + Domains.CONVERSATIONS.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "AddressConfiguration read failed: Unable to connect to server" - ); + throw new ApiConnectionException("AddressConfiguration read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "address_configurations", - response.getContent(), - AddressConfiguration.class, - client.getObjectMapper() - ); + "address_configurations", + response.getContent(), + AddressConfiguration.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.CONVERSATIONS.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.CONVERSATIONS.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (type != null) { - request.addQueryParam("Type", type); + Serializer.toString(request, "Type", type, ParameterType.QUERY); } + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/conversations/v1/AddressConfigurationUpdater.java b/src/main/java/com/twilio/rest/conversations/v1/AddressConfigurationUpdater.java index 74843cc1d3..0f74feaa7a 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/AddressConfigurationUpdater.java +++ b/src/main/java/com/twilio/rest/conversations/v1/AddressConfigurationUpdater.java @@ -16,7 +16,9 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; import com.twilio.converter.Promoter; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,11 +27,11 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.util.List; public class AddressConfigurationUpdater extends Updater { - - private String pathSid; + private String pathsid; private String friendlyName; private Boolean autoCreationEnabled; private AddressConfiguration.AutoCreationType autoCreationType; @@ -40,170 +42,150 @@ public class AddressConfigurationUpdater extends Updater { private String autoCreationStudioFlowSid; private Integer autoCreationStudioRetryCount; - public AddressConfigurationUpdater(final String pathSid) { - this.pathSid = pathSid; + public AddressConfigurationUpdater(final String pathsid) { + this.pathsid = pathsid; } - public AddressConfigurationUpdater setFriendlyName( - final String friendlyName - ) { + + public AddressConfigurationUpdater setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } - public AddressConfigurationUpdater setAutoCreationEnabled( - final Boolean autoCreationEnabled - ) { + + public AddressConfigurationUpdater setAutoCreationEnabled(final Boolean autoCreationEnabled) { this.autoCreationEnabled = autoCreationEnabled; return this; } - public AddressConfigurationUpdater setAutoCreationType( - final AddressConfiguration.AutoCreationType autoCreationType - ) { + + public AddressConfigurationUpdater setAutoCreationType(final AddressConfiguration.AutoCreationType autoCreationType) { this.autoCreationType = autoCreationType; return this; } - public AddressConfigurationUpdater setAutoCreationConversationServiceSid( - final String autoCreationConversationServiceSid - ) { - this.autoCreationConversationServiceSid = - autoCreationConversationServiceSid; + + public AddressConfigurationUpdater setAutoCreationConversationServiceSid(final String autoCreationConversationServiceSid) { + this.autoCreationConversationServiceSid = autoCreationConversationServiceSid; return this; } - public AddressConfigurationUpdater setAutoCreationWebhookUrl( - final String autoCreationWebhookUrl - ) { + + public AddressConfigurationUpdater setAutoCreationWebhookUrl(final String autoCreationWebhookUrl) { this.autoCreationWebhookUrl = autoCreationWebhookUrl; return this; } - public AddressConfigurationUpdater setAutoCreationWebhookMethod( - final AddressConfiguration.Method autoCreationWebhookMethod - ) { + + public AddressConfigurationUpdater setAutoCreationWebhookMethod(final AddressConfiguration.Method autoCreationWebhookMethod) { this.autoCreationWebhookMethod = autoCreationWebhookMethod; return this; } - public AddressConfigurationUpdater setAutoCreationWebhookFilters( - final List autoCreationWebhookFilters - ) { + + public AddressConfigurationUpdater setAutoCreationWebhookFilters(final List autoCreationWebhookFilters) { this.autoCreationWebhookFilters = autoCreationWebhookFilters; return this; } - public AddressConfigurationUpdater setAutoCreationWebhookFilters( - final String autoCreationWebhookFilters - ) { - return setAutoCreationWebhookFilters( - Promoter.listOfOne(autoCreationWebhookFilters) - ); + public AddressConfigurationUpdater setAutoCreationWebhookFilters(final String autoCreationWebhookFilters) { + return setAutoCreationWebhookFilters(Promoter.listOfOne(autoCreationWebhookFilters)); } - public AddressConfigurationUpdater setAutoCreationStudioFlowSid( - final String autoCreationStudioFlowSid - ) { + public AddressConfigurationUpdater setAutoCreationStudioFlowSid(final String autoCreationStudioFlowSid) { this.autoCreationStudioFlowSid = autoCreationStudioFlowSid; return this; } - public AddressConfigurationUpdater setAutoCreationStudioRetryCount( - final Integer autoCreationStudioRetryCount - ) { + + public AddressConfigurationUpdater setAutoCreationStudioRetryCount(final Integer autoCreationStudioRetryCount) { this.autoCreationStudioRetryCount = autoCreationStudioRetryCount; return this; } + @Override public AddressConfiguration update(final TwilioRestClient client) { + String path = "/v1/Configuration/Addresses/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.CONVERSATIONS.toString(), - path + HttpMethod.POST, + Domains.CONVERSATIONS.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "AddressConfiguration update failed: Unable to connect to server" - ); + throw new ApiConnectionException("AddressConfiguration update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return AddressConfiguration.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return AddressConfiguration.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + if (autoCreationEnabled != null) { - request.addPostParam( - "AutoCreation.Enabled", - autoCreationEnabled.toString() - ); + Serializer.toString(request, "AutoCreation.Enabled", autoCreationEnabled, ParameterType.URLENCODED); } + + if (autoCreationType != null) { - request.addPostParam( - "AutoCreation.Type", - autoCreationType.toString() - ); + Serializer.toString(request, "AutoCreation.Type", autoCreationType, ParameterType.URLENCODED); } + + if (autoCreationConversationServiceSid != null) { - request.addPostParam( - "AutoCreation.ConversationServiceSid", - autoCreationConversationServiceSid - ); + Serializer.toString(request, "AutoCreation.ConversationServiceSid", autoCreationConversationServiceSid, ParameterType.URLENCODED); } + + if (autoCreationWebhookUrl != null) { - request.addPostParam( - "AutoCreation.WebhookUrl", - autoCreationWebhookUrl - ); + Serializer.toString(request, "AutoCreation.WebhookUrl", autoCreationWebhookUrl, ParameterType.URLENCODED); } + + if (autoCreationWebhookMethod != null) { - request.addPostParam( - "AutoCreation.WebhookMethod", - autoCreationWebhookMethod.toString() - ); + Serializer.toString(request, "AutoCreation.WebhookMethod", autoCreationWebhookMethod, ParameterType.URLENCODED); } + + if (autoCreationWebhookFilters != null) { - for (String prop : autoCreationWebhookFilters) { - request.addPostParam("AutoCreation.WebhookFilters", prop); + for (String param : autoCreationWebhookFilters) { + Serializer.toString(request, "AutoCreation.WebhookFilters", param, ParameterType.URLENCODED); } } + + if (autoCreationStudioFlowSid != null) { - request.addPostParam( - "AutoCreation.StudioFlowSid", - autoCreationStudioFlowSid - ); + Serializer.toString(request, "AutoCreation.StudioFlowSid", autoCreationStudioFlowSid, ParameterType.URLENCODED); } + + if (autoCreationStudioRetryCount != null) { - request.addPostParam( - "AutoCreation.StudioRetryCount", - autoCreationStudioRetryCount.toString() - ); + Serializer.toString(request, "AutoCreation.StudioRetryCount", autoCreationStudioRetryCount, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/conversations/v1/Configuration.java b/src/main/java/com/twilio/rest/conversations/v1/Configuration.java index e426d2f468..831a486f1e 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/Configuration.java +++ b/src/main/java/com/twilio/rest/conversations/v1/Configuration.java @@ -18,45 +18,48 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Configuration extends Resource { - private static final long serialVersionUID = 31286932068884L; public static ConfigurationFetcher fetcher() { - return new ConfigurationFetcher(); + return new ConfigurationFetcher( + + ); } + public static ConfigurationUpdater updater() { - return new ConfigurationUpdater(); + return new ConfigurationUpdater( + + ); } + /** * Converts a JSON String into a Configuration object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Configuration object represented by the provided JSON */ - public static Configuration fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Configuration fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Configuration.class); @@ -71,14 +74,11 @@ public static Configuration fromJson( * Converts a JSON InputStream into a Configuration object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Configuration object represented by the provided JSON */ - public static Configuration fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Configuration fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Configuration.class); @@ -89,65 +89,51 @@ public static Configuration fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; + @Getter private final String defaultChatServiceSid; - private final String defaultMessagingServiceSid; - private final String defaultInactiveTimer; + @Getter private final String defaultClosedTimer; - private final URI url; + @Getter + private final String defaultInactiveTimer; + @Getter + private final String defaultMessagingServiceSid; + @Getter private final Map links; + @Getter + private final URI url; @JsonCreator private Configuration( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty( - "default_chat_service_sid" - ) final String defaultChatServiceSid, - @JsonProperty( - "default_messaging_service_sid" - ) final String defaultMessagingServiceSid, - @JsonProperty( - "default_inactive_timer" - ) final String defaultInactiveTimer, - @JsonProperty("default_closed_timer") final String defaultClosedTimer, - @JsonProperty("url") final URI url, - @JsonProperty("links") final Map links + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("default_chat_service_sid") final String defaultChatServiceSid, + @JsonProperty("default_closed_timer") final String defaultClosedTimer, + @JsonProperty("default_inactive_timer") final String defaultInactiveTimer, + @JsonProperty("default_messaging_service_sid") final String defaultMessagingServiceSid, + @JsonProperty("links") final Map links, + @JsonProperty("url") final URI url ) { this.accountSid = accountSid; this.defaultChatServiceSid = defaultChatServiceSid; - this.defaultMessagingServiceSid = defaultMessagingServiceSid; - this.defaultInactiveTimer = defaultInactiveTimer; this.defaultClosedTimer = defaultClosedTimer; - this.url = url; + this.defaultInactiveTimer = defaultInactiveTimer; + this.defaultMessagingServiceSid = defaultMessagingServiceSid; this.links = links; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getDefaultChatServiceSid() { - return this.defaultChatServiceSid; - } - - public final String getDefaultMessagingServiceSid() { - return this.defaultMessagingServiceSid; - } - - public final String getDefaultInactiveTimer() { - return this.defaultInactiveTimer; - } - - public final String getDefaultClosedTimer() { - return this.defaultClosedTimer; - } - - public final URI getUrl() { - return this.url; - } - - public final Map getLinks() { - return this.links; + this.url = url; } @Override @@ -161,34 +147,30 @@ public boolean equals(final Object o) { } Configuration other = (Configuration) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals( - defaultChatServiceSid, - other.defaultChatServiceSid - ) && - Objects.equals( - defaultMessagingServiceSid, - other.defaultMessagingServiceSid - ) && - Objects.equals(defaultInactiveTimer, other.defaultInactiveTimer) && - Objects.equals(defaultClosedTimer, other.defaultClosedTimer) && - Objects.equals(url, other.url) && - Objects.equals(links, other.links) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(defaultChatServiceSid, other.defaultChatServiceSid) && + Objects.equals(defaultClosedTimer, other.defaultClosedTimer) && + Objects.equals(defaultInactiveTimer, other.defaultInactiveTimer) && + Objects.equals(defaultMessagingServiceSid, other.defaultMessagingServiceSid) && + Objects.equals(links, other.links) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - accountSid, - defaultChatServiceSid, - defaultMessagingServiceSid, - defaultInactiveTimer, - defaultClosedTimer, - url, - links + accountSid, + defaultChatServiceSid, + defaultClosedTimer, + defaultInactiveTimer, + defaultMessagingServiceSid, + links, + url ); } + + } + diff --git a/src/main/java/com/twilio/rest/conversations/v1/ConfigurationFetcher.java b/src/main/java/com/twilio/rest/conversations/v1/ConfigurationFetcher.java index a9a17e3ed1..c0922e87bf 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/ConfigurationFetcher.java +++ b/src/main/java/com/twilio/rest/conversations/v1/ConfigurationFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.conversations.v1; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,41 +26,37 @@ public class ConfigurationFetcher extends Fetcher { - public ConfigurationFetcher() {} + + public ConfigurationFetcher() { + } + @Override public Configuration fetch(final TwilioRestClient client) { + String path = "/v1/Configuration"; + Request request = new Request( - HttpMethod.GET, - Domains.CONVERSATIONS.toString(), - path + HttpMethod.GET, + Domains.CONVERSATIONS.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Configuration fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Configuration fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return Configuration.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Configuration.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/conversations/v1/ConfigurationUpdater.java b/src/main/java/com/twilio/rest/conversations/v1/ConfigurationUpdater.java index 96d49e720c..83cc0e290b 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/ConfigurationUpdater.java +++ b/src/main/java/com/twilio/rest/conversations/v1/ConfigurationUpdater.java @@ -16,6 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -26,96 +28,92 @@ import com.twilio.rest.Domains; public class ConfigurationUpdater extends Updater { - private String defaultChatServiceSid; private String defaultMessagingServiceSid; private String defaultInactiveTimer; private String defaultClosedTimer; - public ConfigurationUpdater() {} + public ConfigurationUpdater() { + } + - public ConfigurationUpdater setDefaultChatServiceSid( - final String defaultChatServiceSid - ) { + public ConfigurationUpdater setDefaultChatServiceSid(final String defaultChatServiceSid) { this.defaultChatServiceSid = defaultChatServiceSid; return this; } - public ConfigurationUpdater setDefaultMessagingServiceSid( - final String defaultMessagingServiceSid - ) { + + public ConfigurationUpdater setDefaultMessagingServiceSid(final String defaultMessagingServiceSid) { this.defaultMessagingServiceSid = defaultMessagingServiceSid; return this; } - public ConfigurationUpdater setDefaultInactiveTimer( - final String defaultInactiveTimer - ) { + + public ConfigurationUpdater setDefaultInactiveTimer(final String defaultInactiveTimer) { this.defaultInactiveTimer = defaultInactiveTimer; return this; } - public ConfigurationUpdater setDefaultClosedTimer( - final String defaultClosedTimer - ) { + + public ConfigurationUpdater setDefaultClosedTimer(final String defaultClosedTimer) { this.defaultClosedTimer = defaultClosedTimer; return this; } + @Override public Configuration update(final TwilioRestClient client) { + String path = "/v1/Configuration"; + Request request = new Request( - HttpMethod.POST, - Domains.CONVERSATIONS.toString(), - path + HttpMethod.POST, + Domains.CONVERSATIONS.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Configuration update failed: Unable to connect to server" - ); + throw new ApiConnectionException("Configuration update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Configuration.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Configuration.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (defaultChatServiceSid != null) { - request.addPostParam( - "DefaultChatServiceSid", - defaultChatServiceSid - ); + Serializer.toString(request, "DefaultChatServiceSid", defaultChatServiceSid, ParameterType.URLENCODED); } + + if (defaultMessagingServiceSid != null) { - request.addPostParam( - "DefaultMessagingServiceSid", - defaultMessagingServiceSid - ); + Serializer.toString(request, "DefaultMessagingServiceSid", defaultMessagingServiceSid, ParameterType.URLENCODED); } + + if (defaultInactiveTimer != null) { - request.addPostParam("DefaultInactiveTimer", defaultInactiveTimer); + Serializer.toString(request, "DefaultInactiveTimer", defaultInactiveTimer, ParameterType.URLENCODED); } + + if (defaultClosedTimer != null) { - request.addPostParam("DefaultClosedTimer", defaultClosedTimer); + Serializer.toString(request, "DefaultClosedTimer", defaultClosedTimer, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/conversations/v1/Conversation.java b/src/main/java/com/twilio/rest/conversations/v1/Conversation.java index 6a849cb54e..64ef4d021b 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/Conversation.java +++ b/src/main/java/com/twilio/rest/conversations/v1/Conversation.java @@ -18,60 +18,115 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Conversation extends Resource { - private static final long serialVersionUID = 208929192266810L; public static ConversationCreator creator() { - return new ConversationCreator(); + return new ConversationCreator( + + ); } - public static ConversationDeleter deleter(final String pathSid) { - return new ConversationDeleter(pathSid); + + public static ConversationDeleter deleter(final String pathsid) { + return new ConversationDeleter( + pathsid + ); } - public static ConversationFetcher fetcher(final String pathSid) { - return new ConversationFetcher(pathSid); + + public static ConversationFetcher fetcher(final String pathsid) { + return new ConversationFetcher( + pathsid + ); } + public static ConversationReader reader() { - return new ConversationReader(); + return new ConversationReader( + + ); + } + + + public static ConversationUpdater updater(final String pathsid) { + return new ConversationUpdater( + pathsid + ); } - public static ConversationUpdater updater(final String pathSid) { - return new ConversationUpdater(pathSid); + + public enum WebhookEnabledType { + TRUE("true"), + FALSE("false"); + + private final String value; + + private WebhookEnabledType(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static WebhookEnabledType forValue(final String value) { + return Promoter.enumFromString(value, WebhookEnabledType.values()); + } + } + + public enum State { + INITIALIZING("initializing"), + INACTIVE("inactive"), + ACTIVE("active"), + CLOSED("closed"); + + private final String value; + + private State(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static State forValue(final String value) { + return Promoter.enumFromString(value, State.values()); + } } + /** * Converts a JSON String into a Conversation object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Conversation object represented by the provided JSON */ - public static Conversation fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Conversation fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Conversation.class); @@ -86,14 +141,11 @@ public static Conversation fromJson( * Converts a JSON InputStream into a Conversation object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Conversation object represented by the provided JSON */ - public static Conversation fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Conversation fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Conversation.class); @@ -104,108 +156,81 @@ public static Conversation fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; + @Getter + private final String attributes; + @Getter + private final Object bindings; + @Getter private final String chatServiceSid; + @Getter + private final ZonedDateTime dateCreated; + @Getter + private final ZonedDateTime dateUpdated; + @Getter + private final String friendlyName; + @Getter + private final Map links; + @Getter private final String messagingServiceSid; + @Getter private final String sid; - private final String friendlyName; - private final String uniqueName; - private final String attributes; + @Getter private final Conversation.State state; - private final ZonedDateTime dateCreated; - private final ZonedDateTime dateUpdated; - private final Map timers; + @Getter + private final Object timers; + @Getter + private final String uniqueName; + @Getter private final URI url; - private final Map links; - private final Map bindings; @JsonCreator private Conversation( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("chat_service_sid") final String chatServiceSid, - @JsonProperty("messaging_service_sid") final String messagingServiceSid, - @JsonProperty("sid") final String sid, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("unique_name") final String uniqueName, - @JsonProperty("attributes") final String attributes, - @JsonProperty("state") final Conversation.State state, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("timers") final Map timers, - @JsonProperty("url") final URI url, - @JsonProperty("links") final Map links, - @JsonProperty("bindings") final Map bindings + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("attributes") final String attributes, + @JsonProperty("bindings") final Object bindings, + @JsonProperty("chat_service_sid") final String chatServiceSid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("links") final Map links, + @JsonProperty("messaging_service_sid") final String messagingServiceSid, + @JsonProperty("sid") final String sid, + @JsonProperty("state") final Conversation.State state, + @JsonProperty("timers") final Object timers, + @JsonProperty("unique_name") final String uniqueName, + @JsonProperty("url") final URI url ) { this.accountSid = accountSid; + this.attributes = attributes; + this.bindings = bindings; this.chatServiceSid = chatServiceSid; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; + this.friendlyName = friendlyName; + this.links = links; this.messagingServiceSid = messagingServiceSid; this.sid = sid; - this.friendlyName = friendlyName; - this.uniqueName = uniqueName; - this.attributes = attributes; this.state = state; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); this.timers = timers; + this.uniqueName = uniqueName; this.url = url; - this.links = links; - this.bindings = bindings; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getChatServiceSid() { - return this.chatServiceSid; - } - - public final String getMessagingServiceSid() { - return this.messagingServiceSid; - } - - public final String getSid() { - return this.sid; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final String getUniqueName() { - return this.uniqueName; - } - - public final String getAttributes() { - return this.attributes; - } - - public final Conversation.State getState() { - return this.state; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final Map getTimers() { - return this.timers; - } - - public final URI getUrl() { - return this.url; - } - - public final Map getLinks() { - return this.links; - } - - public final Map getBindings() { - return this.bindings; } @Override @@ -219,84 +244,44 @@ public boolean equals(final Object o) { } Conversation other = (Conversation) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(chatServiceSid, other.chatServiceSid) && - Objects.equals(messagingServiceSid, other.messagingServiceSid) && - Objects.equals(sid, other.sid) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(uniqueName, other.uniqueName) && - Objects.equals(attributes, other.attributes) && - Objects.equals(state, other.state) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(timers, other.timers) && - Objects.equals(url, other.url) && - Objects.equals(links, other.links) && - Objects.equals(bindings, other.bindings) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(attributes, other.attributes) && + Objects.equals(bindings, other.bindings) && + Objects.equals(chatServiceSid, other.chatServiceSid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(links, other.links) && + Objects.equals(messagingServiceSid, other.messagingServiceSid) && + Objects.equals(sid, other.sid) && + Objects.equals(state, other.state) && + Objects.equals(timers, other.timers) && + Objects.equals(uniqueName, other.uniqueName) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - accountSid, - chatServiceSid, - messagingServiceSid, - sid, - friendlyName, - uniqueName, - attributes, - state, - dateCreated, - dateUpdated, - timers, - url, - links, - bindings + accountSid, + attributes, + bindings, + chatServiceSid, + dateCreated, + dateUpdated, + friendlyName, + links, + messagingServiceSid, + sid, + state, + timers, + uniqueName, + url ); } - public enum WebhookEnabledType { - TRUE("true"), - FALSE("false"); - - private final String value; - - private WebhookEnabledType(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static WebhookEnabledType forValue(final String value) { - return Promoter.enumFromString(value, WebhookEnabledType.values()); - } - } - - public enum State { - INITIALIZING("initializing"), - INACTIVE("inactive"), - ACTIVE("active"), - CLOSED("closed"); - - private final String value; - - private State(final String value) { - this.value = value; - } - public String toString() { - return value; - } - - @JsonCreator - public static State forValue(final String value) { - return Promoter.enumFromString(value, State.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/conversations/v1/ConversationCreator.java b/src/main/java/com/twilio/rest/conversations/v1/ConversationCreator.java index 5e66458ed8..4324f52fe1 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/ConversationCreator.java +++ b/src/main/java/com/twilio/rest/conversations/v1/ConversationCreator.java @@ -14,8 +14,11 @@ package com.twilio.rest.conversations.v1; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -24,6 +27,7 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.time.ZonedDateTime; public class ConversationCreator extends Creator { @@ -41,164 +45,179 @@ public class ConversationCreator extends Creator { private String bindingsEmailAddress; private String bindingsEmailName; - public ConversationCreator() {} - - public ConversationCreator setXTwilioWebhookEnabled( - final Conversation.WebhookEnabledType xTwilioWebhookEnabled - ) { - this.xTwilioWebhookEnabled = xTwilioWebhookEnabled; - return this; + public ConversationCreator() { } + public ConversationCreator setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + public ConversationCreator setUniqueName(final String uniqueName) { this.uniqueName = uniqueName; return this; } + public ConversationCreator setDateCreated(final ZonedDateTime dateCreated) { this.dateCreated = dateCreated; return this; } + public ConversationCreator setDateUpdated(final ZonedDateTime dateUpdated) { this.dateUpdated = dateUpdated; return this; } - public ConversationCreator setMessagingServiceSid( - final String messagingServiceSid - ) { + + public ConversationCreator setMessagingServiceSid(final String messagingServiceSid) { this.messagingServiceSid = messagingServiceSid; return this; } + public ConversationCreator setAttributes(final String attributes) { this.attributes = attributes; return this; } + public ConversationCreator setState(final Conversation.State state) { this.state = state; return this; } + public ConversationCreator setTimersInactive(final String timersInactive) { this.timersInactive = timersInactive; return this; } + public ConversationCreator setTimersClosed(final String timersClosed) { this.timersClosed = timersClosed; return this; } - public ConversationCreator setBindingsEmailAddress( - final String bindingsEmailAddress - ) { + + public ConversationCreator setBindingsEmailAddress(final String bindingsEmailAddress) { this.bindingsEmailAddress = bindingsEmailAddress; return this; } - public ConversationCreator setBindingsEmailName( - final String bindingsEmailName - ) { + + public ConversationCreator setBindingsEmailName(final String bindingsEmailName) { this.bindingsEmailName = bindingsEmailName; return this; } + + public ConversationCreator setXTwilioWebhookEnabled(final Conversation.WebhookEnabledType xTwilioWebhookEnabled) { + this.xTwilioWebhookEnabled = xTwilioWebhookEnabled; + return this; + } + + @Override public Conversation create(final TwilioRestClient client) { + String path = "/v1/Conversations"; + Request request = new Request( - HttpMethod.POST, - Domains.CONVERSATIONS.toString(), - path + HttpMethod.POST, + Domains.CONVERSATIONS.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); - addPostParams(request); addHeaderParams(request); + addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Conversation creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("Conversation creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Conversation.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Conversation.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + if (uniqueName != null) { - request.addPostParam("UniqueName", uniqueName); + Serializer.toString(request, "UniqueName", uniqueName, ParameterType.URLENCODED); } + + if (dateCreated != null) { - request.addPostParam( - "DateCreated", - dateCreated.toInstant().toString() - ); + Serializer.toString(request, "DateCreated", dateCreated, ParameterType.URLENCODED); } + + if (dateUpdated != null) { - request.addPostParam( - "DateUpdated", - dateUpdated.toInstant().toString() - ); + Serializer.toString(request, "DateUpdated", dateUpdated, ParameterType.URLENCODED); } + + if (messagingServiceSid != null) { - request.addPostParam("MessagingServiceSid", messagingServiceSid); + Serializer.toString(request, "MessagingServiceSid", messagingServiceSid, ParameterType.URLENCODED); } + + if (attributes != null) { - request.addPostParam("Attributes", attributes); + Serializer.toString(request, "Attributes", attributes, ParameterType.URLENCODED); } + + if (state != null) { - request.addPostParam("State", state.toString()); + Serializer.toString(request, "State", state, ParameterType.URLENCODED); } + + if (timersInactive != null) { - request.addPostParam("Timers.Inactive", timersInactive); + Serializer.toString(request, "Timers.Inactive", timersInactive, ParameterType.URLENCODED); } + + if (timersClosed != null) { - request.addPostParam("Timers.Closed", timersClosed); + Serializer.toString(request, "Timers.Closed", timersClosed, ParameterType.URLENCODED); } + + if (bindingsEmailAddress != null) { - request.addPostParam( - "Bindings.Email.Address", - bindingsEmailAddress - ); + Serializer.toString(request, "Bindings.Email.Address", bindingsEmailAddress, ParameterType.URLENCODED); } + + if (bindingsEmailName != null) { - request.addPostParam("Bindings.Email.Name", bindingsEmailName); + Serializer.toString(request, "Bindings.Email.Name", bindingsEmailName, ParameterType.URLENCODED); } + + } private void addHeaderParams(final Request request) { + if (xTwilioWebhookEnabled != null) { - request.addHeaderParam( - "X-Twilio-Webhook-Enabled", - xTwilioWebhookEnabled.toString() - ); + Serializer.toString(request, "X-Twilio-Webhook-Enabled", xTwilioWebhookEnabled, ParameterType.HEADER); } + } } diff --git a/src/main/java/com/twilio/rest/conversations/v1/ConversationDeleter.java b/src/main/java/com/twilio/rest/conversations/v1/ConversationDeleter.java index 0d726dd307..36404a60be 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/ConversationDeleter.java +++ b/src/main/java/com/twilio/rest/conversations/v1/ConversationDeleter.java @@ -15,7 +15,8 @@ package com.twilio.rest.conversations.v1; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,49 +28,46 @@ public class ConversationDeleter extends Deleter { - private String pathSid; + private String pathsid; private Conversation.WebhookEnabledType xTwilioWebhookEnabled; - public ConversationDeleter(final String pathSid) { - this.pathSid = pathSid; + public ConversationDeleter(final String pathsid) { + this.pathsid = pathsid; } - public ConversationDeleter setXTwilioWebhookEnabled( - final Conversation.WebhookEnabledType xTwilioWebhookEnabled - ) { + + public ConversationDeleter setXTwilioWebhookEnabled(final Conversation.WebhookEnabledType xTwilioWebhookEnabled) { this.xTwilioWebhookEnabled = xTwilioWebhookEnabled; return this; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/v1/Conversations/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.CONVERSATIONS.toString(), - path + HttpMethod.DELETE, + Domains.CONVERSATIONS.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addHeaderParams(request); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Conversation delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("Conversation delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -77,11 +75,10 @@ public boolean delete(final TwilioRestClient client) { } private void addHeaderParams(final Request request) { + if (xTwilioWebhookEnabled != null) { - request.addHeaderParam( - "X-Twilio-Webhook-Enabled", - xTwilioWebhookEnabled.toString() - ); + Serializer.toString(request, "X-Twilio-Webhook-Enabled", xTwilioWebhookEnabled, ParameterType.HEADER); } + } } diff --git a/src/main/java/com/twilio/rest/conversations/v1/ConversationFetcher.java b/src/main/java/com/twilio/rest/conversations/v1/ConversationFetcher.java index a2db599e69..69fdba8084 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/ConversationFetcher.java +++ b/src/main/java/com/twilio/rest/conversations/v1/ConversationFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.conversations.v1; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,47 +26,41 @@ public class ConversationFetcher extends Fetcher { - private String pathSid; + private String pathsid; - public ConversationFetcher(final String pathSid) { - this.pathSid = pathSid; + public ConversationFetcher(final String pathsid) { + this.pathsid = pathsid; } + @Override public Conversation fetch(final TwilioRestClient client) { + String path = "/v1/Conversations/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.CONVERSATIONS.toString(), - path + HttpMethod.GET, + Domains.CONVERSATIONS.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Conversation fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Conversation fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return Conversation.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Conversation.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/conversations/v1/ConversationReader.java b/src/main/java/com/twilio/rest/conversations/v1/ConversationReader.java index 94f07006e9..96c5a09a5f 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/ConversationReader.java +++ b/src/main/java/com/twilio/rest/conversations/v1/ConversationReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -34,129 +35,116 @@ public class ConversationReader extends Reader { private Conversation.State state; private Long pageSize; - public ConversationReader() {} + public ConversationReader() { + } + public ConversationReader setStartDate(final String startDate) { this.startDate = startDate; return this; } + public ConversationReader setEndDate(final String endDate) { this.endDate = endDate; return this; } + public ConversationReader setState(final Conversation.State state) { this.state = state; return this; } + public ConversationReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/Conversations"; + Request request = new Request( - HttpMethod.GET, - Domains.CONVERSATIONS.toString(), - path + HttpMethod.GET, + Domains.CONVERSATIONS.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Conversation read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Conversation read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "conversations", - response.getContent(), - Conversation.class, - client.getObjectMapper() - ); + "conversations", + response.getContent(), + Conversation.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.CONVERSATIONS.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.CONVERSATIONS.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (startDate != null) { - request.addQueryParam("StartDate", startDate); + Serializer.toString(request, "StartDate", startDate, ParameterType.QUERY); } + + if (endDate != null) { - request.addQueryParam("EndDate", endDate); + Serializer.toString(request, "EndDate", endDate, ParameterType.QUERY); } + + if (state != null) { - request.addQueryParam("State", state.toString()); + Serializer.toString(request, "State", state, ParameterType.QUERY); } + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/conversations/v1/ConversationUpdater.java b/src/main/java/com/twilio/rest/conversations/v1/ConversationUpdater.java index 8c4ea3d172..433316cd24 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/ConversationUpdater.java +++ b/src/main/java/com/twilio/rest/conversations/v1/ConversationUpdater.java @@ -16,6 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -24,11 +26,11 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.time.ZonedDateTime; public class ConversationUpdater extends Updater { - - private String pathSid; + private String pathsid; private Conversation.WebhookEnabledType xTwilioWebhookEnabled; private String friendlyName; private ZonedDateTime dateCreated; @@ -42,168 +44,182 @@ public class ConversationUpdater extends Updater { private String bindingsEmailAddress; private String bindingsEmailName; - public ConversationUpdater(final String pathSid) { - this.pathSid = pathSid; + public ConversationUpdater(final String pathsid) { + this.pathsid = pathsid; } - public ConversationUpdater setXTwilioWebhookEnabled( - final Conversation.WebhookEnabledType xTwilioWebhookEnabled - ) { - this.xTwilioWebhookEnabled = xTwilioWebhookEnabled; - return this; - } public ConversationUpdater setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + public ConversationUpdater setDateCreated(final ZonedDateTime dateCreated) { this.dateCreated = dateCreated; return this; } + public ConversationUpdater setDateUpdated(final ZonedDateTime dateUpdated) { this.dateUpdated = dateUpdated; return this; } + public ConversationUpdater setAttributes(final String attributes) { this.attributes = attributes; return this; } - public ConversationUpdater setMessagingServiceSid( - final String messagingServiceSid - ) { + + public ConversationUpdater setMessagingServiceSid(final String messagingServiceSid) { this.messagingServiceSid = messagingServiceSid; return this; } + public ConversationUpdater setState(final Conversation.State state) { this.state = state; return this; } + public ConversationUpdater setTimersInactive(final String timersInactive) { this.timersInactive = timersInactive; return this; } + public ConversationUpdater setTimersClosed(final String timersClosed) { this.timersClosed = timersClosed; return this; } + public ConversationUpdater setUniqueName(final String uniqueName) { this.uniqueName = uniqueName; return this; } - public ConversationUpdater setBindingsEmailAddress( - final String bindingsEmailAddress - ) { + + public ConversationUpdater setBindingsEmailAddress(final String bindingsEmailAddress) { this.bindingsEmailAddress = bindingsEmailAddress; return this; } - public ConversationUpdater setBindingsEmailName( - final String bindingsEmailName - ) { + + public ConversationUpdater setBindingsEmailName(final String bindingsEmailName) { this.bindingsEmailName = bindingsEmailName; return this; } + + public ConversationUpdater setXTwilioWebhookEnabled(final Conversation.WebhookEnabledType xTwilioWebhookEnabled) { + this.xTwilioWebhookEnabled = xTwilioWebhookEnabled; + return this; + } + + @Override public Conversation update(final TwilioRestClient client) { + String path = "/v1/Conversations/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.CONVERSATIONS.toString(), - path + HttpMethod.POST, + Domains.CONVERSATIONS.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); - addPostParams(request); addHeaderParams(request); + addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Conversation update failed: Unable to connect to server" - ); + throw new ApiConnectionException("Conversation update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Conversation.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Conversation.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + if (dateCreated != null) { - request.addPostParam( - "DateCreated", - dateCreated.toInstant().toString() - ); + Serializer.toString(request, "DateCreated", dateCreated, ParameterType.URLENCODED); } + + if (dateUpdated != null) { - request.addPostParam( - "DateUpdated", - dateUpdated.toInstant().toString() - ); + Serializer.toString(request, "DateUpdated", dateUpdated, ParameterType.URLENCODED); } + + if (attributes != null) { - request.addPostParam("Attributes", attributes); + Serializer.toString(request, "Attributes", attributes, ParameterType.URLENCODED); } + + if (messagingServiceSid != null) { - request.addPostParam("MessagingServiceSid", messagingServiceSid); + Serializer.toString(request, "MessagingServiceSid", messagingServiceSid, ParameterType.URLENCODED); } + + if (state != null) { - request.addPostParam("State", state.toString()); + Serializer.toString(request, "State", state, ParameterType.URLENCODED); } + + if (timersInactive != null) { - request.addPostParam("Timers.Inactive", timersInactive); + Serializer.toString(request, "Timers.Inactive", timersInactive, ParameterType.URLENCODED); } + + if (timersClosed != null) { - request.addPostParam("Timers.Closed", timersClosed); + Serializer.toString(request, "Timers.Closed", timersClosed, ParameterType.URLENCODED); } + + if (uniqueName != null) { - request.addPostParam("UniqueName", uniqueName); + Serializer.toString(request, "UniqueName", uniqueName, ParameterType.URLENCODED); } + + if (bindingsEmailAddress != null) { - request.addPostParam( - "Bindings.Email.Address", - bindingsEmailAddress - ); + Serializer.toString(request, "Bindings.Email.Address", bindingsEmailAddress, ParameterType.URLENCODED); } + + if (bindingsEmailName != null) { - request.addPostParam("Bindings.Email.Name", bindingsEmailName); + Serializer.toString(request, "Bindings.Email.Name", bindingsEmailName, ParameterType.URLENCODED); } + + } private void addHeaderParams(final Request request) { + if (xTwilioWebhookEnabled != null) { - request.addHeaderParam( - "X-Twilio-Webhook-Enabled", - xTwilioWebhookEnabled.toString() - ); + Serializer.toString(request, "X-Twilio-Webhook-Enabled", xTwilioWebhookEnabled, ParameterType.HEADER); } + } } diff --git a/src/main/java/com/twilio/rest/conversations/v1/ConversationWithParticipants.java b/src/main/java/com/twilio/rest/conversations/v1/ConversationWithParticipants.java index 5ae7e297d4..33a240a3fd 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/ConversationWithParticipants.java +++ b/src/main/java/com/twilio/rest/conversations/v1/ConversationWithParticipants.java @@ -18,50 +18,90 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class ConversationWithParticipants extends Resource { - private static final long serialVersionUID = 37532883203442L; public static ConversationWithParticipantsCreator creator() { - return new ConversationWithParticipantsCreator(); + return new ConversationWithParticipantsCreator( + + ); } + + public enum WebhookEnabledType { + TRUE("true"), + FALSE("false"); + + private final String value; + + private WebhookEnabledType(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static WebhookEnabledType forValue(final String value) { + return Promoter.enumFromString(value, WebhookEnabledType.values()); + } + } + + public enum State { + INITIALIZING("initializing"), + INACTIVE("inactive"), + ACTIVE("active"), + CLOSED("closed"); + + private final String value; + + private State(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static State forValue(final String value) { + return Promoter.enumFromString(value, State.values()); + } + } + + /** * Converts a JSON String into a ConversationWithParticipants object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return ConversationWithParticipants object represented by the provided JSON */ - public static ConversationWithParticipants fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static ConversationWithParticipants fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { - return objectMapper.readValue( - json, - ConversationWithParticipants.class - ); + return objectMapper.readValue(json, ConversationWithParticipants.class); } catch (final JsonMappingException | JsonParseException e) { throw new ApiException(e.getMessage(), e); } catch (final IOException e) { @@ -73,20 +113,14 @@ public static ConversationWithParticipants fromJson( * Converts a JSON InputStream into a ConversationWithParticipants object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return ConversationWithParticipants object represented by the provided JSON */ - public static ConversationWithParticipants fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static ConversationWithParticipants fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { - return objectMapper.readValue( - json, - ConversationWithParticipants.class - ); + return objectMapper.readValue(json, ConversationWithParticipants.class); } catch (final JsonMappingException | JsonParseException e) { throw new ApiException(e.getMessage(), e); } catch (final IOException e) { @@ -94,110 +128,83 @@ public static ConversationWithParticipants fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String chatServiceSid; - private final String messagingServiceSid; - private final String sid; - private final String friendlyName; - private final String uniqueName; + @Getter private final String attributes; - private final ConversationWithParticipants.State state; + @Getter + private final Object bindings; + @Getter + private final String chatServiceSid; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; - private final Map timers; + @Getter + private final String friendlyName; + @Getter private final Map links; - private final Map bindings; + @Getter + private final String messagingServiceSid; + @Getter + private final String sid; + @Getter + private final ConversationWithParticipants.State state; + @Getter + private final Object timers; + @Getter + private final String uniqueName; + @Getter private final URI url; @JsonCreator private ConversationWithParticipants( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("chat_service_sid") final String chatServiceSid, - @JsonProperty("messaging_service_sid") final String messagingServiceSid, - @JsonProperty("sid") final String sid, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("unique_name") final String uniqueName, - @JsonProperty("attributes") final String attributes, - @JsonProperty("state") final ConversationWithParticipants.State state, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("timers") final Map timers, - @JsonProperty("links") final Map links, - @JsonProperty("bindings") final Map bindings, - @JsonProperty("url") final URI url + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("attributes") final String attributes, + @JsonProperty("bindings") final Object bindings, + @JsonProperty("chat_service_sid") final String chatServiceSid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("links") final Map links, + @JsonProperty("messaging_service_sid") final String messagingServiceSid, + @JsonProperty("sid") final String sid, + @JsonProperty("state") final ConversationWithParticipants.State state, + @JsonProperty("timers") final Object timers, + @JsonProperty("unique_name") final String uniqueName, + @JsonProperty("url") final URI url ) { this.accountSid = accountSid; + this.attributes = attributes; + this.bindings = bindings; this.chatServiceSid = chatServiceSid; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; + this.friendlyName = friendlyName; + this.links = links; this.messagingServiceSid = messagingServiceSid; this.sid = sid; - this.friendlyName = friendlyName; - this.uniqueName = uniqueName; - this.attributes = attributes; this.state = state; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); this.timers = timers; - this.links = links; - this.bindings = bindings; + this.uniqueName = uniqueName; this.url = url; } - public final String getAccountSid() { - return this.accountSid; - } - - public final String getChatServiceSid() { - return this.chatServiceSid; - } - - public final String getMessagingServiceSid() { - return this.messagingServiceSid; - } - - public final String getSid() { - return this.sid; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final String getUniqueName() { - return this.uniqueName; - } - - public final String getAttributes() { - return this.attributes; - } - - public final ConversationWithParticipants.State getState() { - return this.state; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final Map getTimers() { - return this.timers; - } - - public final Map getLinks() { - return this.links; - } - - public final Map getBindings() { - return this.bindings; - } - - public final URI getUrl() { - return this.url; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -209,84 +216,44 @@ public boolean equals(final Object o) { } ConversationWithParticipants other = (ConversationWithParticipants) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(chatServiceSid, other.chatServiceSid) && - Objects.equals(messagingServiceSid, other.messagingServiceSid) && - Objects.equals(sid, other.sid) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(uniqueName, other.uniqueName) && - Objects.equals(attributes, other.attributes) && - Objects.equals(state, other.state) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(timers, other.timers) && - Objects.equals(links, other.links) && - Objects.equals(bindings, other.bindings) && - Objects.equals(url, other.url) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(attributes, other.attributes) && + Objects.equals(bindings, other.bindings) && + Objects.equals(chatServiceSid, other.chatServiceSid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(links, other.links) && + Objects.equals(messagingServiceSid, other.messagingServiceSid) && + Objects.equals(sid, other.sid) && + Objects.equals(state, other.state) && + Objects.equals(timers, other.timers) && + Objects.equals(uniqueName, other.uniqueName) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - accountSid, - chatServiceSid, - messagingServiceSid, - sid, - friendlyName, - uniqueName, - attributes, - state, - dateCreated, - dateUpdated, - timers, - links, - bindings, - url + accountSid, + attributes, + bindings, + chatServiceSid, + dateCreated, + dateUpdated, + friendlyName, + links, + messagingServiceSid, + sid, + state, + timers, + uniqueName, + url ); } - public enum State { - INITIALIZING("initializing"), - INACTIVE("inactive"), - ACTIVE("active"), - CLOSED("closed"); - - private final String value; - - private State(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static State forValue(final String value) { - return Promoter.enumFromString(value, State.values()); - } - } - - public enum WebhookEnabledType { - TRUE("true"), - FALSE("false"); - - private final String value; - private WebhookEnabledType(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static WebhookEnabledType forValue(final String value) { - return Promoter.enumFromString(value, WebhookEnabledType.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/conversations/v1/ConversationWithParticipantsCreator.java b/src/main/java/com/twilio/rest/conversations/v1/ConversationWithParticipantsCreator.java index 38daf45bb7..61bc93d305 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/ConversationWithParticipantsCreator.java +++ b/src/main/java/com/twilio/rest/conversations/v1/ConversationWithParticipantsCreator.java @@ -14,9 +14,12 @@ package com.twilio.rest.conversations.v1; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; import com.twilio.converter.Promoter; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,12 +28,11 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.time.ZonedDateTime; import java.util.List; -import java.util.List; -public class ConversationWithParticipantsCreator - extends Creator { +public class ConversationWithParticipantsCreator extends Creator { private ConversationWithParticipants.WebhookEnabledType xTwilioWebhookEnabled; private String friendlyName; @@ -46,198 +48,194 @@ public class ConversationWithParticipantsCreator private String bindingsEmailName; private List participant; - public ConversationWithParticipantsCreator() {} - - public ConversationWithParticipantsCreator setXTwilioWebhookEnabled( - final ConversationWithParticipants.WebhookEnabledType xTwilioWebhookEnabled - ) { - this.xTwilioWebhookEnabled = xTwilioWebhookEnabled; - return this; + public ConversationWithParticipantsCreator() { } - public ConversationWithParticipantsCreator setFriendlyName( - final String friendlyName - ) { + + public ConversationWithParticipantsCreator setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } - public ConversationWithParticipantsCreator setUniqueName( - final String uniqueName - ) { + + public ConversationWithParticipantsCreator setUniqueName(final String uniqueName) { this.uniqueName = uniqueName; return this; } - public ConversationWithParticipantsCreator setDateCreated( - final ZonedDateTime dateCreated - ) { + + public ConversationWithParticipantsCreator setDateCreated(final ZonedDateTime dateCreated) { this.dateCreated = dateCreated; return this; } - public ConversationWithParticipantsCreator setDateUpdated( - final ZonedDateTime dateUpdated - ) { + + public ConversationWithParticipantsCreator setDateUpdated(final ZonedDateTime dateUpdated) { this.dateUpdated = dateUpdated; return this; } - public ConversationWithParticipantsCreator setMessagingServiceSid( - final String messagingServiceSid - ) { + + public ConversationWithParticipantsCreator setMessagingServiceSid(final String messagingServiceSid) { this.messagingServiceSid = messagingServiceSid; return this; } - public ConversationWithParticipantsCreator setAttributes( - final String attributes - ) { + + public ConversationWithParticipantsCreator setAttributes(final String attributes) { this.attributes = attributes; return this; } - public ConversationWithParticipantsCreator setState( - final ConversationWithParticipants.State state - ) { + + public ConversationWithParticipantsCreator setState(final ConversationWithParticipants.State state) { this.state = state; return this; } - public ConversationWithParticipantsCreator setTimersInactive( - final String timersInactive - ) { + + public ConversationWithParticipantsCreator setTimersInactive(final String timersInactive) { this.timersInactive = timersInactive; return this; } - public ConversationWithParticipantsCreator setTimersClosed( - final String timersClosed - ) { + + public ConversationWithParticipantsCreator setTimersClosed(final String timersClosed) { this.timersClosed = timersClosed; return this; } - public ConversationWithParticipantsCreator setBindingsEmailAddress( - final String bindingsEmailAddress - ) { + + public ConversationWithParticipantsCreator setBindingsEmailAddress(final String bindingsEmailAddress) { this.bindingsEmailAddress = bindingsEmailAddress; return this; } - public ConversationWithParticipantsCreator setBindingsEmailName( - final String bindingsEmailName - ) { + + public ConversationWithParticipantsCreator setBindingsEmailName(final String bindingsEmailName) { this.bindingsEmailName = bindingsEmailName; return this; } - public ConversationWithParticipantsCreator setParticipant( - final List participant - ) { + + public ConversationWithParticipantsCreator setParticipant(final List participant) { this.participant = participant; return this; } - public ConversationWithParticipantsCreator setParticipant( - final String participant - ) { + public ConversationWithParticipantsCreator setParticipant(final String participant) { return setParticipant(Promoter.listOfOne(participant)); } + public ConversationWithParticipantsCreator setXTwilioWebhookEnabled(final ConversationWithParticipants.WebhookEnabledType xTwilioWebhookEnabled) { + this.xTwilioWebhookEnabled = xTwilioWebhookEnabled; + return this; + } + + @Override public ConversationWithParticipants create(final TwilioRestClient client) { + String path = "/v1/ConversationWithParticipants"; + Request request = new Request( - HttpMethod.POST, - Domains.CONVERSATIONS.toString(), - path + HttpMethod.POST, + Domains.CONVERSATIONS.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); - addPostParams(request); addHeaderParams(request); + addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "ConversationWithParticipants creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("ConversationWithParticipants creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return ConversationWithParticipants.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return ConversationWithParticipants.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + if (uniqueName != null) { - request.addPostParam("UniqueName", uniqueName); + Serializer.toString(request, "UniqueName", uniqueName, ParameterType.URLENCODED); } + + if (dateCreated != null) { - request.addPostParam( - "DateCreated", - dateCreated.toInstant().toString() - ); + Serializer.toString(request, "DateCreated", dateCreated, ParameterType.URLENCODED); } + + if (dateUpdated != null) { - request.addPostParam( - "DateUpdated", - dateUpdated.toInstant().toString() - ); + Serializer.toString(request, "DateUpdated", dateUpdated, ParameterType.URLENCODED); } + + if (messagingServiceSid != null) { - request.addPostParam("MessagingServiceSid", messagingServiceSid); + Serializer.toString(request, "MessagingServiceSid", messagingServiceSid, ParameterType.URLENCODED); } + + if (attributes != null) { - request.addPostParam("Attributes", attributes); + Serializer.toString(request, "Attributes", attributes, ParameterType.URLENCODED); } + + if (state != null) { - request.addPostParam("State", state.toString()); + Serializer.toString(request, "State", state, ParameterType.URLENCODED); } + + if (timersInactive != null) { - request.addPostParam("Timers.Inactive", timersInactive); + Serializer.toString(request, "Timers.Inactive", timersInactive, ParameterType.URLENCODED); } + + if (timersClosed != null) { - request.addPostParam("Timers.Closed", timersClosed); + Serializer.toString(request, "Timers.Closed", timersClosed, ParameterType.URLENCODED); } + + if (bindingsEmailAddress != null) { - request.addPostParam( - "Bindings.Email.Address", - bindingsEmailAddress - ); + Serializer.toString(request, "Bindings.Email.Address", bindingsEmailAddress, ParameterType.URLENCODED); } + + if (bindingsEmailName != null) { - request.addPostParam("Bindings.Email.Name", bindingsEmailName); + Serializer.toString(request, "Bindings.Email.Name", bindingsEmailName, ParameterType.URLENCODED); } + + if (participant != null) { - for (String prop : participant) { - request.addPostParam("Participant", prop); + for (String param : participant) { + Serializer.toString(request, "Participant", param, ParameterType.URLENCODED); } } + } private void addHeaderParams(final Request request) { + if (xTwilioWebhookEnabled != null) { - request.addHeaderParam( - "X-Twilio-Webhook-Enabled", - xTwilioWebhookEnabled.toString() - ); + Serializer.toString(request, "X-Twilio-Webhook-Enabled", xTwilioWebhookEnabled, ParameterType.HEADER); } + } } diff --git a/src/main/java/com/twilio/rest/conversations/v1/Credential.java b/src/main/java/com/twilio/rest/conversations/v1/Credential.java index 9b3cc9b62d..d4285cb043 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/Credential.java +++ b/src/main/java/com/twilio/rest/conversations/v1/Credential.java @@ -18,58 +18,93 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Credential extends Resource { - private static final long serialVersionUID = 265726674321801L; public static CredentialCreator creator(final Credential.PushType type) { - return new CredentialCreator(type); + return new CredentialCreator( + type + ); } - public static CredentialDeleter deleter(final String pathSid) { - return new CredentialDeleter(pathSid); + + public static CredentialDeleter deleter(final String pathsid) { + return new CredentialDeleter( + pathsid + ); } - public static CredentialFetcher fetcher(final String pathSid) { - return new CredentialFetcher(pathSid); + + public static CredentialFetcher fetcher(final String pathsid) { + return new CredentialFetcher( + pathsid + ); } + public static CredentialReader reader() { - return new CredentialReader(); + return new CredentialReader( + + ); } - public static CredentialUpdater updater(final String pathSid) { - return new CredentialUpdater(pathSid); + + public static CredentialUpdater updater(final String pathsid) { + return new CredentialUpdater( + pathsid + ); } + + public enum PushType { + APN("apn"), + GCM("gcm"), + FCM("fcm"); + + private final String value; + + private PushType(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static PushType forValue(final String value) { + return Promoter.enumFromString(value, PushType.values()); + } + } + + /** * Converts a JSON String into a Credential object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Credential object represented by the provided JSON */ - public static Credential fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Credential fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Credential.class); @@ -84,14 +119,11 @@ public static Credential fromJson( * Converts a JSON InputStream into a Credential object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Credential object represented by the provided JSON */ - public static Credential fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Credential fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Credential.class); @@ -102,68 +134,59 @@ public static Credential fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String friendlyName; - private final Credential.PushType type; - private final String sandbox; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; + @Getter + private final String friendlyName; + @Getter + private final String sandbox; + @Getter + private final String sid; + @Getter + private final Credential.PushType type; + @Getter private final URI url; @JsonCreator private Credential( - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("type") final Credential.PushType type, - @JsonProperty("sandbox") final String sandbox, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("url") final URI url + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("sandbox") final String sandbox, + @JsonProperty("sid") final String sid, + @JsonProperty("type") final Credential.PushType type, + @JsonProperty("url") final URI url ) { - this.sid = sid; this.accountSid = accountSid; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.friendlyName = friendlyName; - this.type = type; this.sandbox = sandbox; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); + this.sid = sid; + this.type = type; this.url = url; } - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final Credential.PushType getType() { - return this.type; - } - - public final String getSandbox() { - return this.sandbox; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final URI getUrl() { - return this.url; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -175,51 +198,32 @@ public boolean equals(final Object o) { } Credential other = (Credential) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(type, other.type) && - Objects.equals(sandbox, other.sandbox) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(url, other.url) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(sandbox, other.sandbox) && + Objects.equals(sid, other.sid) && + Objects.equals(type, other.type) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - sid, - accountSid, - friendlyName, - type, - sandbox, - dateCreated, - dateUpdated, - url + accountSid, + dateCreated, + dateUpdated, + friendlyName, + sandbox, + sid, + type, + url ); } - public enum PushType { - APN("apn"), - GCM("gcm"), - FCM("fcm"); - - private final String value; - - private PushType(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - @JsonCreator - public static PushType forValue(final String value) { - return Promoter.enumFromString(value, PushType.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/conversations/v1/CredentialCreator.java b/src/main/java/com/twilio/rest/conversations/v1/CredentialCreator.java index 3865fef931..1a52cc609f 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/CredentialCreator.java +++ b/src/main/java/com/twilio/rest/conversations/v1/CredentialCreator.java @@ -14,8 +14,11 @@ package com.twilio.rest.conversations.v1; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -39,100 +42,117 @@ public CredentialCreator(final Credential.PushType type) { this.type = type; } + public CredentialCreator setType(final Credential.PushType type) { this.type = type; return this; } + public CredentialCreator setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + public CredentialCreator setCertificate(final String certificate) { this.certificate = certificate; return this; } + public CredentialCreator setPrivateKey(final String privateKey) { this.privateKey = privateKey; return this; } + public CredentialCreator setSandbox(final Boolean sandbox) { this.sandbox = sandbox; return this; } + public CredentialCreator setApiKey(final String apiKey) { this.apiKey = apiKey; return this; } + public CredentialCreator setSecret(final String secret) { this.secret = secret; return this; } + @Override public Credential create(final TwilioRestClient client) { + String path = "/v1/Credentials"; - path = path.replace("{" + "Type" + "}", this.type.toString()); Request request = new Request( - HttpMethod.POST, - Domains.CONVERSATIONS.toString(), - path + HttpMethod.POST, + Domains.CONVERSATIONS.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Credential creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("Credential creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Credential.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Credential.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (type != null) { - request.addPostParam("Type", type.toString()); + Serializer.toString(request, "Type", type, ParameterType.URLENCODED); } + + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + if (certificate != null) { - request.addPostParam("Certificate", certificate); + Serializer.toString(request, "Certificate", certificate, ParameterType.URLENCODED); } + + if (privateKey != null) { - request.addPostParam("PrivateKey", privateKey); + Serializer.toString(request, "PrivateKey", privateKey, ParameterType.URLENCODED); } + + if (sandbox != null) { - request.addPostParam("Sandbox", sandbox.toString()); + Serializer.toString(request, "Sandbox", sandbox, ParameterType.URLENCODED); } + + if (apiKey != null) { - request.addPostParam("ApiKey", apiKey); + Serializer.toString(request, "ApiKey", apiKey, ParameterType.URLENCODED); } + + if (secret != null) { - request.addPostParam("Secret", secret); + Serializer.toString(request, "Secret", secret, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/conversations/v1/CredentialDeleter.java b/src/main/java/com/twilio/rest/conversations/v1/CredentialDeleter.java index 1e213249cd..29abe47c62 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/CredentialDeleter.java +++ b/src/main/java/com/twilio/rest/conversations/v1/CredentialDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.conversations.v1; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,40 +26,38 @@ public class CredentialDeleter extends Deleter { - private String pathSid; + private String pathsid; - public CredentialDeleter(final String pathSid) { - this.pathSid = pathSid; + public CredentialDeleter(final String pathsid) { + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/v1/Credentials/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.CONVERSATIONS.toString(), - path + HttpMethod.DELETE, + Domains.CONVERSATIONS.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Credential delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("Credential delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/conversations/v1/CredentialFetcher.java b/src/main/java/com/twilio/rest/conversations/v1/CredentialFetcher.java index 44007649aa..9fa7aca2d3 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/CredentialFetcher.java +++ b/src/main/java/com/twilio/rest/conversations/v1/CredentialFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.conversations.v1; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,47 +26,41 @@ public class CredentialFetcher extends Fetcher { - private String pathSid; + private String pathsid; - public CredentialFetcher(final String pathSid) { - this.pathSid = pathSid; + public CredentialFetcher(final String pathsid) { + this.pathsid = pathsid; } + @Override public Credential fetch(final TwilioRestClient client) { + String path = "/v1/Credentials/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.CONVERSATIONS.toString(), - path + HttpMethod.GET, + Domains.CONVERSATIONS.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Credential fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Credential fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return Credential.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Credential.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/conversations/v1/CredentialReader.java b/src/main/java/com/twilio/rest/conversations/v1/CredentialReader.java index 85eed77d09..05b0a14a8c 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/CredentialReader.java +++ b/src/main/java/com/twilio/rest/conversations/v1/CredentialReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -31,105 +32,83 @@ public class CredentialReader extends Reader { private Long pageSize; - public CredentialReader() {} + public CredentialReader() { + } + public CredentialReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/Credentials"; + Request request = new Request( - HttpMethod.GET, - Domains.CONVERSATIONS.toString(), - path + HttpMethod.GET, + Domains.CONVERSATIONS.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Credential read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Credential read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "credentials", - response.getContent(), - Credential.class, - client.getObjectMapper() - ); + "credentials", + response.getContent(), + Credential.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.CONVERSATIONS.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.CONVERSATIONS.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/conversations/v1/CredentialUpdater.java b/src/main/java/com/twilio/rest/conversations/v1/CredentialUpdater.java index 57dc20f595..87c868f512 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/CredentialUpdater.java +++ b/src/main/java/com/twilio/rest/conversations/v1/CredentialUpdater.java @@ -16,6 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -26,8 +28,7 @@ import com.twilio.rest.Domains; public class CredentialUpdater extends Updater { - - private String pathSid; + private String pathsid; private Credential.PushType type; private String friendlyName; private String certificate; @@ -36,104 +37,123 @@ public class CredentialUpdater extends Updater { private String apiKey; private String secret; - public CredentialUpdater(final String pathSid) { - this.pathSid = pathSid; + public CredentialUpdater(final String pathsid) { + this.pathsid = pathsid; } + public CredentialUpdater setType(final Credential.PushType type) { this.type = type; return this; } + public CredentialUpdater setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + public CredentialUpdater setCertificate(final String certificate) { this.certificate = certificate; return this; } + public CredentialUpdater setPrivateKey(final String privateKey) { this.privateKey = privateKey; return this; } + public CredentialUpdater setSandbox(final Boolean sandbox) { this.sandbox = sandbox; return this; } + public CredentialUpdater setApiKey(final String apiKey) { this.apiKey = apiKey; return this; } + public CredentialUpdater setSecret(final String secret) { this.secret = secret; return this; } + @Override public Credential update(final TwilioRestClient client) { + String path = "/v1/Credentials/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.CONVERSATIONS.toString(), - path + HttpMethod.POST, + Domains.CONVERSATIONS.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Credential update failed: Unable to connect to server" - ); + throw new ApiConnectionException("Credential update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Credential.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Credential.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (type != null) { - request.addPostParam("Type", type.toString()); + Serializer.toString(request, "Type", type, ParameterType.URLENCODED); } + + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + if (certificate != null) { - request.addPostParam("Certificate", certificate); + Serializer.toString(request, "Certificate", certificate, ParameterType.URLENCODED); } + + if (privateKey != null) { - request.addPostParam("PrivateKey", privateKey); + Serializer.toString(request, "PrivateKey", privateKey, ParameterType.URLENCODED); } + + if (sandbox != null) { - request.addPostParam("Sandbox", sandbox.toString()); + Serializer.toString(request, "Sandbox", sandbox, ParameterType.URLENCODED); } + + if (apiKey != null) { - request.addPostParam("ApiKey", apiKey); + Serializer.toString(request, "ApiKey", apiKey, ParameterType.URLENCODED); } + + if (secret != null) { - request.addPostParam("Secret", secret); + Serializer.toString(request, "Secret", secret, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/conversations/v1/ParticipantConversation.java b/src/main/java/com/twilio/rest/conversations/v1/ParticipantConversation.java index 49b97fb0c4..f2e6ff2278 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/ParticipantConversation.java +++ b/src/main/java/com/twilio/rest/conversations/v1/ParticipantConversation.java @@ -18,43 +18,65 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.time.ZonedDateTime; import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class ParticipantConversation extends Resource { - private static final long serialVersionUID = 210706261724884L; public static ParticipantConversationReader reader() { - return new ParticipantConversationReader(); + return new ParticipantConversationReader( + + ); + } + + + public enum State { + INACTIVE("inactive"), + ACTIVE("active"), + CLOSED("closed"); + + private final String value; + + private State(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static State forValue(final String value) { + return Promoter.enumFromString(value, State.values()); + } } + /** * Converts a JSON String into a ParticipantConversation object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return ParticipantConversation object represented by the provided JSON */ - public static ParticipantConversation fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static ParticipantConversation fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, ParticipantConversation.class); @@ -69,14 +91,11 @@ public static ParticipantConversation fromJson( * Converts a JSON InputStream into a ParticipantConversation object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return ParticipantConversation object represented by the provided JSON */ - public static ParticipantConversation fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static ParticipantConversation fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, ParticipantConversation.class); @@ -87,144 +106,89 @@ public static ParticipantConversation fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; + @Getter private final String chatServiceSid; - private final String participantSid; - private final String participantUserSid; - private final String participantIdentity; - private final Map participantMessagingBinding; - private final String conversationSid; - private final String conversationUniqueName; - private final String conversationFriendlyName; + @Getter private final String conversationAttributes; + @Getter + private final String conversationCreatedBy; + @Getter private final ZonedDateTime conversationDateCreated; + @Getter private final ZonedDateTime conversationDateUpdated; - private final String conversationCreatedBy; + @Getter + private final String conversationFriendlyName; + @Getter + private final String conversationSid; + @Getter private final ParticipantConversation.State conversationState; - private final Map conversationTimers; + @Getter + private final Object conversationTimers; + @Getter + private final String conversationUniqueName; + @Getter private final Map links; + @Getter + private final String participantIdentity; + @Getter + private final Object participantMessagingBinding; + @Getter + private final String participantSid; + @Getter + private final String participantUserSid; @JsonCreator private ParticipantConversation( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("chat_service_sid") final String chatServiceSid, - @JsonProperty("participant_sid") final String participantSid, - @JsonProperty("participant_user_sid") final String participantUserSid, - @JsonProperty("participant_identity") final String participantIdentity, - @JsonProperty("participant_messaging_binding") final Map< - String, - Object - > participantMessagingBinding, - @JsonProperty("conversation_sid") final String conversationSid, - @JsonProperty( - "conversation_unique_name" - ) final String conversationUniqueName, - @JsonProperty( - "conversation_friendly_name" - ) final String conversationFriendlyName, - @JsonProperty( - "conversation_attributes" - ) final String conversationAttributes, - @JsonProperty( - "conversation_date_created" - ) final String conversationDateCreated, - @JsonProperty( - "conversation_date_updated" - ) final String conversationDateUpdated, - @JsonProperty( - "conversation_created_by" - ) final String conversationCreatedBy, - @JsonProperty( - "conversation_state" - ) final ParticipantConversation.State conversationState, - @JsonProperty("conversation_timers") final Map< - String, - Object - > conversationTimers, - @JsonProperty("links") final Map links + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("chat_service_sid") final String chatServiceSid, + @JsonProperty("conversation_attributes") final String conversationAttributes, + @JsonProperty("conversation_created_by") final String conversationCreatedBy, + @JsonProperty("conversation_date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime conversationDateCreated, + @JsonProperty("conversation_date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime conversationDateUpdated, + @JsonProperty("conversation_friendly_name") final String conversationFriendlyName, + @JsonProperty("conversation_sid") final String conversationSid, + @JsonProperty("conversation_state") final ParticipantConversation.State conversationState, + @JsonProperty("conversation_timers") final Object conversationTimers, + @JsonProperty("conversation_unique_name") final String conversationUniqueName, + @JsonProperty("links") final Map links, + @JsonProperty("participant_identity") final String participantIdentity, + @JsonProperty("participant_messaging_binding") final Object participantMessagingBinding, + @JsonProperty("participant_sid") final String participantSid, + @JsonProperty("participant_user_sid") final String participantUserSid ) { this.accountSid = accountSid; this.chatServiceSid = chatServiceSid; - this.participantSid = participantSid; - this.participantUserSid = participantUserSid; - this.participantIdentity = participantIdentity; - this.participantMessagingBinding = participantMessagingBinding; - this.conversationSid = conversationSid; - this.conversationUniqueName = conversationUniqueName; - this.conversationFriendlyName = conversationFriendlyName; this.conversationAttributes = conversationAttributes; - this.conversationDateCreated = - DateConverter.iso8601DateTimeFromString(conversationDateCreated); - this.conversationDateUpdated = - DateConverter.iso8601DateTimeFromString(conversationDateUpdated); this.conversationCreatedBy = conversationCreatedBy; + this.conversationDateCreated = conversationDateCreated; + this.conversationDateUpdated = conversationDateUpdated; + this.conversationFriendlyName = conversationFriendlyName; + this.conversationSid = conversationSid; this.conversationState = conversationState; this.conversationTimers = conversationTimers; + this.conversationUniqueName = conversationUniqueName; this.links = links; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getChatServiceSid() { - return this.chatServiceSid; - } - - public final String getParticipantSid() { - return this.participantSid; - } - - public final String getParticipantUserSid() { - return this.participantUserSid; - } - - public final String getParticipantIdentity() { - return this.participantIdentity; - } - - public final Map getParticipantMessagingBinding() { - return this.participantMessagingBinding; - } - - public final String getConversationSid() { - return this.conversationSid; - } - - public final String getConversationUniqueName() { - return this.conversationUniqueName; - } - - public final String getConversationFriendlyName() { - return this.conversationFriendlyName; - } - - public final String getConversationAttributes() { - return this.conversationAttributes; - } - - public final ZonedDateTime getConversationDateCreated() { - return this.conversationDateCreated; - } - - public final ZonedDateTime getConversationDateUpdated() { - return this.conversationDateUpdated; - } - - public final String getConversationCreatedBy() { - return this.conversationCreatedBy; - } - - public final ParticipantConversation.State getConversationState() { - return this.conversationState; - } - - public final Map getConversationTimers() { - return this.conversationTimers; - } - - public final Map getLinks() { - return this.links; + this.participantIdentity = participantIdentity; + this.participantMessagingBinding = participantMessagingBinding; + this.participantSid = participantSid; + this.participantUserSid = participantUserSid; } @Override @@ -238,88 +202,48 @@ public boolean equals(final Object o) { } ParticipantConversation other = (ParticipantConversation) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(chatServiceSid, other.chatServiceSid) && - Objects.equals(participantSid, other.participantSid) && - Objects.equals(participantUserSid, other.participantUserSid) && - Objects.equals(participantIdentity, other.participantIdentity) && - Objects.equals( - participantMessagingBinding, - other.participantMessagingBinding - ) && - Objects.equals(conversationSid, other.conversationSid) && - Objects.equals( - conversationUniqueName, - other.conversationUniqueName - ) && - Objects.equals( - conversationFriendlyName, - other.conversationFriendlyName - ) && - Objects.equals( - conversationAttributes, - other.conversationAttributes - ) && - Objects.equals( - conversationDateCreated, - other.conversationDateCreated - ) && - Objects.equals( - conversationDateUpdated, - other.conversationDateUpdated - ) && - Objects.equals( - conversationCreatedBy, - other.conversationCreatedBy - ) && - Objects.equals(conversationState, other.conversationState) && - Objects.equals(conversationTimers, other.conversationTimers) && - Objects.equals(links, other.links) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(chatServiceSid, other.chatServiceSid) && + Objects.equals(conversationAttributes, other.conversationAttributes) && + Objects.equals(conversationCreatedBy, other.conversationCreatedBy) && + Objects.equals(conversationDateCreated, other.conversationDateCreated) && + Objects.equals(conversationDateUpdated, other.conversationDateUpdated) && + Objects.equals(conversationFriendlyName, other.conversationFriendlyName) && + Objects.equals(conversationSid, other.conversationSid) && + Objects.equals(conversationState, other.conversationState) && + Objects.equals(conversationTimers, other.conversationTimers) && + Objects.equals(conversationUniqueName, other.conversationUniqueName) && + Objects.equals(links, other.links) && + Objects.equals(participantIdentity, other.participantIdentity) && + Objects.equals(participantMessagingBinding, other.participantMessagingBinding) && + Objects.equals(participantSid, other.participantSid) && + Objects.equals(participantUserSid, other.participantUserSid) ); } @Override public int hashCode() { return Objects.hash( - accountSid, - chatServiceSid, - participantSid, - participantUserSid, - participantIdentity, - participantMessagingBinding, - conversationSid, - conversationUniqueName, - conversationFriendlyName, - conversationAttributes, - conversationDateCreated, - conversationDateUpdated, - conversationCreatedBy, - conversationState, - conversationTimers, - links + accountSid, + chatServiceSid, + conversationAttributes, + conversationCreatedBy, + conversationDateCreated, + conversationDateUpdated, + conversationFriendlyName, + conversationSid, + conversationState, + conversationTimers, + conversationUniqueName, + links, + participantIdentity, + participantMessagingBinding, + participantSid, + participantUserSid ); } - public enum State { - INACTIVE("inactive"), - ACTIVE("active"), - CLOSED("closed"); - - private final String value; - private State(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static State forValue(final String value) { - return Promoter.enumFromString(value, State.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/conversations/v1/ParticipantConversationReader.java b/src/main/java/com/twilio/rest/conversations/v1/ParticipantConversationReader.java index fa4bc1831d..34bdfc4a17 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/ParticipantConversationReader.java +++ b/src/main/java/com/twilio/rest/conversations/v1/ParticipantConversationReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,132 +28,111 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class ParticipantConversationReader - extends Reader { +public class ParticipantConversationReader extends Reader { private String identity; private String address; private Long pageSize; - public ParticipantConversationReader() {} + public ParticipantConversationReader() { + } + public ParticipantConversationReader setIdentity(final String identity) { this.identity = identity; return this; } + public ParticipantConversationReader setAddress(final String address) { this.address = address; return this; } + public ParticipantConversationReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override - public ResourceSet read( - final TwilioRestClient client - ) { + public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } - public Page firstPage( - final TwilioRestClient client - ) { + public Page firstPage(final TwilioRestClient client) { + String path = "/v1/ParticipantConversations"; + Request request = new Request( - HttpMethod.GET, - Domains.CONVERSATIONS.toString(), - path + HttpMethod.GET, + Domains.CONVERSATIONS.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "ParticipantConversation read failed: Unable to connect to server" - ); + throw new ApiConnectionException("ParticipantConversation read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "conversations", - response.getContent(), - ParticipantConversation.class, - client.getObjectMapper() - ); + "conversations", + response.getContent(), + ParticipantConversation.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.CONVERSATIONS.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.CONVERSATIONS.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (identity != null) { - request.addQueryParam("Identity", identity); + Serializer.toString(request, "Identity", identity, ParameterType.QUERY); } + + if (address != null) { - request.addQueryParam("Address", address); + Serializer.toString(request, "Address", address, ParameterType.QUERY); } + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/conversations/v1/Role.java b/src/main/java/com/twilio/rest/conversations/v1/Role.java index 96ca04b94e..3a40e7603e 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/Role.java +++ b/src/main/java/com/twilio/rest/conversations/v1/Role.java @@ -18,66 +18,93 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.List; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Role extends Resource { - private static final long serialVersionUID = 223283830784079L; - public static RoleCreator creator( - final String friendlyName, - final Role.RoleType type, - final List permission - ) { - return new RoleCreator(friendlyName, type, permission); + public static RoleCreator creator(final String friendlyName, final Role.RoleType type, final List permission) { + return new RoleCreator( + friendlyName, type, permission + ); } - public static RoleDeleter deleter(final String pathSid) { - return new RoleDeleter(pathSid); + + public static RoleDeleter deleter(final String pathsid) { + return new RoleDeleter( + pathsid + ); } - public static RoleFetcher fetcher(final String pathSid) { - return new RoleFetcher(pathSid); + + public static RoleFetcher fetcher(final String pathsid) { + return new RoleFetcher( + pathsid + ); } + public static RoleReader reader() { - return new RoleReader(); + return new RoleReader( + + ); } - public static RoleUpdater updater( - final String pathSid, - final List permission - ) { - return new RoleUpdater(pathSid, permission); + + public static RoleUpdater updater(final String pathsid, final List permission) { + return new RoleUpdater( + pathsid, permission + ); + } + + + public enum RoleType { + CONVERSATION("conversation"), + SERVICE("service"); + + private final String value; + + private RoleType(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static RoleType forValue(final String value) { + return Promoter.enumFromString(value, RoleType.values()); + } } + /** * Converts a JSON String into a Role object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Role object represented by the provided JSON */ - public static Role fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Role fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Role.class); @@ -92,14 +119,11 @@ public static Role fromJson( * Converts a JSON InputStream into a Role object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Role object represented by the provided JSON */ - public static Role fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Role fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Role.class); @@ -110,75 +134,63 @@ public static Role fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; + @Getter private final String chatServiceSid; - private final String friendlyName; - private final Role.RoleType type; - private final List permissions; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; + @Getter + private final String friendlyName; + @Getter + private final List permissions; + @Getter + private final String sid; + @Getter + private final Role.RoleType type; + @Getter private final URI url; @JsonCreator private Role( - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("chat_service_sid") final String chatServiceSid, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("type") final Role.RoleType type, - @JsonProperty("permissions") final List permissions, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("url") final URI url + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("chat_service_sid") final String chatServiceSid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("permissions") final List permissions, + @JsonProperty("sid") final String sid, + @JsonProperty("type") final Role.RoleType type, + @JsonProperty("url") final URI url ) { - this.sid = sid; this.accountSid = accountSid; this.chatServiceSid = chatServiceSid; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.friendlyName = friendlyName; - this.type = type; this.permissions = permissions; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); + this.sid = sid; + this.type = type; this.url = url; } - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getChatServiceSid() { - return this.chatServiceSid; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final Role.RoleType getType() { - return this.type; - } - - public final List getPermissions() { - return this.permissions; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final URI getUrl() { - return this.url; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -190,52 +202,34 @@ public boolean equals(final Object o) { } Role other = (Role) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(chatServiceSid, other.chatServiceSid) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(type, other.type) && - Objects.equals(permissions, other.permissions) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(url, other.url) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(chatServiceSid, other.chatServiceSid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(permissions, other.permissions) && + Objects.equals(sid, other.sid) && + Objects.equals(type, other.type) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - sid, - accountSid, - chatServiceSid, - friendlyName, - type, - permissions, - dateCreated, - dateUpdated, - url + accountSid, + chatServiceSid, + dateCreated, + dateUpdated, + friendlyName, + permissions, + sid, + type, + url ); } - public enum RoleType { - CONVERSATION("conversation"), - SERVICE("service"); - - private final String value; - - private RoleType(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - @JsonCreator - public static RoleType forValue(final String value) { - return Promoter.enumFromString(value, RoleType.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/conversations/v1/RoleCreator.java b/src/main/java/com/twilio/rest/conversations/v1/RoleCreator.java index 45a3b1ee44..a0fd3d32aa 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/RoleCreator.java +++ b/src/main/java/com/twilio/rest/conversations/v1/RoleCreator.java @@ -14,9 +14,12 @@ package com.twilio.rest.conversations.v1; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; import com.twilio.converter.Promoter; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,7 +28,7 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -import java.util.List; + import java.util.List; public class RoleCreator extends Creator { @@ -34,26 +37,25 @@ public class RoleCreator extends Creator { private Role.RoleType type; private List permission; - public RoleCreator( - final String friendlyName, - final Role.RoleType type, - final List permission - ) { + public RoleCreator(final String friendlyName, final Role.RoleType type, final List permission) { this.friendlyName = friendlyName; this.type = type; this.permission = permission; } + public RoleCreator setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + public RoleCreator setType(final Role.RoleType type) { this.type = type; return this; } + public RoleCreator setPermission(final List permission) { this.permission = permission; return this; @@ -65,39 +67,29 @@ public RoleCreator setPermission(final String permission) { @Override public Role create(final TwilioRestClient client) { + String path = "/v1/Roles"; - path = - path.replace( - "{" + "FriendlyName" + "}", - this.friendlyName.toString() - ); - path = path.replace("{" + "Type" + "}", this.type.toString()); - path = - path.replace("{" + "Permission" + "}", this.permission.toString()); Request request = new Request( - HttpMethod.POST, - Domains.CONVERSATIONS.toString(), - path + HttpMethod.POST, + Domains.CONVERSATIONS.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Role creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("Role creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -106,16 +98,22 @@ public Role create(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + if (type != null) { - request.addPostParam("Type", type.toString()); + Serializer.toString(request, "Type", type, ParameterType.URLENCODED); } + + if (permission != null) { - for (String prop : permission) { - request.addPostParam("Permission", prop); + for (String param : permission) { + Serializer.toString(request, "Permission", param, ParameterType.URLENCODED); } } + } } diff --git a/src/main/java/com/twilio/rest/conversations/v1/RoleDeleter.java b/src/main/java/com/twilio/rest/conversations/v1/RoleDeleter.java index c307a837b9..5d51ea963d 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/RoleDeleter.java +++ b/src/main/java/com/twilio/rest/conversations/v1/RoleDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.conversations.v1; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,40 +26,38 @@ public class RoleDeleter extends Deleter { - private String pathSid; + private String pathsid; - public RoleDeleter(final String pathSid) { - this.pathSid = pathSid; + public RoleDeleter(final String pathsid) { + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/v1/Roles/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.CONVERSATIONS.toString(), - path + HttpMethod.DELETE, + Domains.CONVERSATIONS.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Role delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("Role delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/conversations/v1/RoleFetcher.java b/src/main/java/com/twilio/rest/conversations/v1/RoleFetcher.java index baa5e8883d..41dd16b96a 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/RoleFetcher.java +++ b/src/main/java/com/twilio/rest/conversations/v1/RoleFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.conversations.v1; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,44 +26,41 @@ public class RoleFetcher extends Fetcher { - private String pathSid; + private String pathsid; - public RoleFetcher(final String pathSid) { - this.pathSid = pathSid; + public RoleFetcher(final String pathsid) { + this.pathsid = pathsid; } + @Override public Role fetch(final TwilioRestClient client) { + String path = "/v1/Roles/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.CONVERSATIONS.toString(), - path + HttpMethod.GET, + Domains.CONVERSATIONS.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Role fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Role fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Role.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/conversations/v1/RoleReader.java b/src/main/java/com/twilio/rest/conversations/v1/RoleReader.java index 999b584a66..9d3c042aa7 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/RoleReader.java +++ b/src/main/java/com/twilio/rest/conversations/v1/RoleReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -31,105 +32,83 @@ public class RoleReader extends Reader { private Long pageSize; - public RoleReader() {} + public RoleReader() { + } + public RoleReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/Roles"; + Request request = new Request( - HttpMethod.GET, - Domains.CONVERSATIONS.toString(), - path + HttpMethod.GET, + Domains.CONVERSATIONS.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Role read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Role read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "roles", - response.getContent(), - Role.class, - client.getObjectMapper() - ); + "roles", + response.getContent(), + Role.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.CONVERSATIONS.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.CONVERSATIONS.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/conversations/v1/RoleUpdater.java b/src/main/java/com/twilio/rest/conversations/v1/RoleUpdater.java index f9a74418e7..8cabde96d5 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/RoleUpdater.java +++ b/src/main/java/com/twilio/rest/conversations/v1/RoleUpdater.java @@ -16,7 +16,9 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; import com.twilio.converter.Promoter; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,18 +27,19 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.util.List; public class RoleUpdater extends Updater { - - private String pathSid; + private String pathsid; private List permission; - public RoleUpdater(final String pathSid, final List permission) { - this.pathSid = pathSid; + public RoleUpdater(final String pathsid, final List permission) { + this.pathsid = pathsid; this.permission = permission; } + public RoleUpdater setPermission(final List permission) { this.permission = permission; return this; @@ -48,34 +51,31 @@ public RoleUpdater setPermission(final String permission) { @Override public Role update(final TwilioRestClient client) { + String path = "/v1/Roles/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); - path = - path.replace("{" + "Permission" + "}", this.permission.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.CONVERSATIONS.toString(), - path + HttpMethod.POST, + Domains.CONVERSATIONS.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Role update failed: Unable to connect to server" - ); + throw new ApiConnectionException("Role update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -84,10 +84,13 @@ public Role update(final TwilioRestClient client) { } private void addPostParams(final Request request) { + + if (permission != null) { - for (String prop : permission) { - request.addPostParam("Permission", prop); + for (String param : permission) { + Serializer.toString(request, "Permission", param, ParameterType.URLENCODED); } } + } } diff --git a/src/main/java/com/twilio/rest/conversations/v1/Service.java b/src/main/java/com/twilio/rest/conversations/v1/Service.java index 2f21845b3a..cf9678f040 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/Service.java +++ b/src/main/java/com/twilio/rest/conversations/v1/Service.java @@ -18,55 +18,64 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Service extends Resource { - private static final long serialVersionUID = 264513185242441L; public static ServiceCreator creator(final String friendlyName) { - return new ServiceCreator(friendlyName); + return new ServiceCreator( + friendlyName + ); } - public static ServiceDeleter deleter(final String pathSid) { - return new ServiceDeleter(pathSid); + + public static ServiceDeleter deleter(final String pathsid) { + return new ServiceDeleter( + pathsid + ); } - public static ServiceFetcher fetcher(final String pathSid) { - return new ServiceFetcher(pathSid); + + public static ServiceFetcher fetcher(final String pathsid) { + return new ServiceFetcher( + pathsid + ); } + public static ServiceReader reader() { - return new ServiceReader(); + return new ServiceReader( + + ); } + /** * Converts a JSON String into a Service object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Service object represented by the provided JSON */ - public static Service fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Service fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Service.class); @@ -81,14 +90,11 @@ public static Service fromJson( * Converts a JSON InputStream into a Service object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Service object represented by the provided JSON */ - public static Service fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Service fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Service.class); @@ -99,59 +105,53 @@ public static Service fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String sid; - private final String friendlyName; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; - private final URI url; + @Getter + private final String friendlyName; + @Getter private final Map links; + @Getter + private final String sid; + @Getter + private final URI url; @JsonCreator private Service( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("sid") final String sid, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("url") final URI url, - @JsonProperty("links") final Map links + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("links") final Map links, + @JsonProperty("sid") final String sid, + @JsonProperty("url") final URI url ) { this.accountSid = accountSid; - this.sid = sid; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.friendlyName = friendlyName; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); - this.url = url; this.links = links; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getSid() { - return this.sid; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final URI getUrl() { - return this.url; - } - - public final Map getLinks() { - return this.links; + this.sid = sid; + this.url = url; } @Override @@ -165,28 +165,30 @@ public boolean equals(final Object o) { } Service other = (Service) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(sid, other.sid) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(url, other.url) && - Objects.equals(links, other.links) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(links, other.links) && + Objects.equals(sid, other.sid) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - accountSid, - sid, - friendlyName, - dateCreated, - dateUpdated, - url, - links + accountSid, + dateCreated, + dateUpdated, + friendlyName, + links, + sid, + url ); } + + } + diff --git a/src/main/java/com/twilio/rest/conversations/v1/ServiceCreator.java b/src/main/java/com/twilio/rest/conversations/v1/ServiceCreator.java index bd9564abd7..c0c3092227 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/ServiceCreator.java +++ b/src/main/java/com/twilio/rest/conversations/v1/ServiceCreator.java @@ -14,8 +14,11 @@ package com.twilio.rest.conversations.v1; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -33,43 +36,38 @@ public ServiceCreator(final String friendlyName) { this.friendlyName = friendlyName; } + public ServiceCreator setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + @Override public Service create(final TwilioRestClient client) { + String path = "/v1/Services"; - path = - path.replace( - "{" + "FriendlyName" + "}", - this.friendlyName.toString() - ); Request request = new Request( - HttpMethod.POST, - Domains.CONVERSATIONS.toString(), - path + HttpMethod.POST, + Domains.CONVERSATIONS.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Service creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("Service creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -78,8 +76,11 @@ public Service create(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/conversations/v1/ServiceDeleter.java b/src/main/java/com/twilio/rest/conversations/v1/ServiceDeleter.java index d5d9a80b0d..2f50616126 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/ServiceDeleter.java +++ b/src/main/java/com/twilio/rest/conversations/v1/ServiceDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.conversations.v1; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,40 +26,38 @@ public class ServiceDeleter extends Deleter { - private String pathSid; + private String pathsid; - public ServiceDeleter(final String pathSid) { - this.pathSid = pathSid; + public ServiceDeleter(final String pathsid) { + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/v1/Services/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.CONVERSATIONS.toString(), - path + HttpMethod.DELETE, + Domains.CONVERSATIONS.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Service delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("Service delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/conversations/v1/ServiceFetcher.java b/src/main/java/com/twilio/rest/conversations/v1/ServiceFetcher.java index 90be32c11f..04400750bc 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/ServiceFetcher.java +++ b/src/main/java/com/twilio/rest/conversations/v1/ServiceFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.conversations.v1; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,44 +26,41 @@ public class ServiceFetcher extends Fetcher { - private String pathSid; + private String pathsid; - public ServiceFetcher(final String pathSid) { - this.pathSid = pathSid; + public ServiceFetcher(final String pathsid) { + this.pathsid = pathsid; } + @Override public Service fetch(final TwilioRestClient client) { + String path = "/v1/Services/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.CONVERSATIONS.toString(), - path + HttpMethod.GET, + Domains.CONVERSATIONS.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Service fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Service fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Service.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/conversations/v1/ServiceReader.java b/src/main/java/com/twilio/rest/conversations/v1/ServiceReader.java index 5df482b5b9..320aef6379 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/ServiceReader.java +++ b/src/main/java/com/twilio/rest/conversations/v1/ServiceReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -31,105 +32,83 @@ public class ServiceReader extends Reader { private Long pageSize; - public ServiceReader() {} + public ServiceReader() { + } + public ServiceReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/Services"; + Request request = new Request( - HttpMethod.GET, - Domains.CONVERSATIONS.toString(), - path + HttpMethod.GET, + Domains.CONVERSATIONS.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Service read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Service read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "services", - response.getContent(), - Service.class, - client.getObjectMapper() - ); + "services", + response.getContent(), + Service.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.CONVERSATIONS.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.CONVERSATIONS.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/conversations/v1/User.java b/src/main/java/com/twilio/rest/conversations/v1/User.java index 22649c0991..a5013821cd 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/User.java +++ b/src/main/java/com/twilio/rest/conversations/v1/User.java @@ -18,60 +18,93 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class User extends Resource { - private static final long serialVersionUID = 270629422616663L; public static UserCreator creator(final String identity) { - return new UserCreator(identity); + return new UserCreator( + identity + ); } - public static UserDeleter deleter(final String pathSid) { - return new UserDeleter(pathSid); + + public static UserDeleter deleter(final String pathsid) { + return new UserDeleter( + pathsid + ); } - public static UserFetcher fetcher(final String pathSid) { - return new UserFetcher(pathSid); + + public static UserFetcher fetcher(final String pathsid) { + return new UserFetcher( + pathsid + ); } + public static UserReader reader() { - return new UserReader(); + return new UserReader( + + ); } - public static UserUpdater updater(final String pathSid) { - return new UserUpdater(pathSid); + + public static UserUpdater updater(final String pathsid) { + return new UserUpdater( + pathsid + ); } + + public enum WebhookEnabledType { + TRUE("true"), + FALSE("false"); + + private final String value; + + private WebhookEnabledType(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static WebhookEnabledType forValue(final String value) { + return Promoter.enumFromString(value, WebhookEnabledType.values()); + } + } + + /** * Converts a JSON String into a User object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return User object represented by the provided JSON */ - public static User fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static User fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, User.class); @@ -86,14 +119,11 @@ public static User fromJson( * Converts a JSON InputStream into a User object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return User object represented by the provided JSON */ - public static User fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static User fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, User.class); @@ -104,101 +134,77 @@ public static User fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String chatServiceSid; - private final String roleSid; - private final String identity; - private final String friendlyName; + @Getter private final String attributes; - private final Boolean isOnline; - private final Boolean isNotifiable; + @Getter + private final String chatServiceSid; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; - private final URI url; + @Getter + private final String friendlyName; + @Getter + private final String identity; + @Getter + private final Boolean isNotifiable; + @Getter + private final Boolean isOnline; + @Getter private final Map links; + @Getter + private final String roleSid; + @Getter + private final String sid; + @Getter + private final URI url; @JsonCreator private User( - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("chat_service_sid") final String chatServiceSid, - @JsonProperty("role_sid") final String roleSid, - @JsonProperty("identity") final String identity, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("attributes") final String attributes, - @JsonProperty("is_online") final Boolean isOnline, - @JsonProperty("is_notifiable") final Boolean isNotifiable, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("url") final URI url, - @JsonProperty("links") final Map links + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("attributes") final String attributes, + @JsonProperty("chat_service_sid") final String chatServiceSid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("identity") final String identity, + @JsonProperty("is_notifiable") final Boolean isNotifiable, + @JsonProperty("is_online") final Boolean isOnline, + @JsonProperty("links") final Map links, + @JsonProperty("role_sid") final String roleSid, + @JsonProperty("sid") final String sid, + @JsonProperty("url") final URI url ) { - this.sid = sid; this.accountSid = accountSid; + this.attributes = attributes; this.chatServiceSid = chatServiceSid; - this.roleSid = roleSid; - this.identity = identity; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.friendlyName = friendlyName; - this.attributes = attributes; - this.isOnline = isOnline; + this.identity = identity; this.isNotifiable = isNotifiable; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); - this.url = url; + this.isOnline = isOnline; this.links = links; - } - - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getChatServiceSid() { - return this.chatServiceSid; - } - - public final String getRoleSid() { - return this.roleSid; - } - - public final String getIdentity() { - return this.identity; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final String getAttributes() { - return this.attributes; - } - - public final Boolean getIsOnline() { - return this.isOnline; - } - - public final Boolean getIsNotifiable() { - return this.isNotifiable; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final URI getUrl() { - return this.url; - } - - public final Map getLinks() { - return this.links; + this.roleSid = roleSid; + this.sid = sid; + this.url = url; } @Override @@ -212,60 +218,42 @@ public boolean equals(final Object o) { } User other = (User) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(chatServiceSid, other.chatServiceSid) && - Objects.equals(roleSid, other.roleSid) && - Objects.equals(identity, other.identity) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(attributes, other.attributes) && - Objects.equals(isOnline, other.isOnline) && - Objects.equals(isNotifiable, other.isNotifiable) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(url, other.url) && - Objects.equals(links, other.links) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(attributes, other.attributes) && + Objects.equals(chatServiceSid, other.chatServiceSid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(identity, other.identity) && + Objects.equals(isNotifiable, other.isNotifiable) && + Objects.equals(isOnline, other.isOnline) && + Objects.equals(links, other.links) && + Objects.equals(roleSid, other.roleSid) && + Objects.equals(sid, other.sid) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - sid, - accountSid, - chatServiceSid, - roleSid, - identity, - friendlyName, - attributes, - isOnline, - isNotifiable, - dateCreated, - dateUpdated, - url, - links + accountSid, + attributes, + chatServiceSid, + dateCreated, + dateUpdated, + friendlyName, + identity, + isNotifiable, + isOnline, + links, + roleSid, + sid, + url ); } - public enum WebhookEnabledType { - TRUE("true"), - FALSE("false"); - - private final String value; - - private WebhookEnabledType(final String value) { - this.value = value; - } - public String toString() { - return value; - } - - @JsonCreator - public static WebhookEnabledType forValue(final String value) { - return Promoter.enumFromString(value, WebhookEnabledType.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/conversations/v1/UserCreator.java b/src/main/java/com/twilio/rest/conversations/v1/UserCreator.java index 0dcdf4b7e9..013a2b1875 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/UserCreator.java +++ b/src/main/java/com/twilio/rest/conversations/v1/UserCreator.java @@ -14,8 +14,11 @@ package com.twilio.rest.conversations.v1; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,8 +30,8 @@ public class UserCreator extends Creator { - private String identity; private User.WebhookEnabledType xTwilioWebhookEnabled; + private String identity; private String friendlyName; private String attributes; private String roleSid; @@ -37,62 +40,63 @@ public UserCreator(final String identity) { this.identity = identity; } + public UserCreator setIdentity(final String identity) { this.identity = identity; return this; } - public UserCreator setXTwilioWebhookEnabled( - final User.WebhookEnabledType xTwilioWebhookEnabled - ) { - this.xTwilioWebhookEnabled = xTwilioWebhookEnabled; - return this; - } public UserCreator setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + public UserCreator setAttributes(final String attributes) { this.attributes = attributes; return this; } + public UserCreator setRoleSid(final String roleSid) { this.roleSid = roleSid; return this; } + + public UserCreator setXTwilioWebhookEnabled(final User.WebhookEnabledType xTwilioWebhookEnabled) { + this.xTwilioWebhookEnabled = xTwilioWebhookEnabled; + return this; + } + + @Override public User create(final TwilioRestClient client) { + String path = "/v1/Users"; - path = path.replace("{" + "Identity" + "}", this.identity.toString()); Request request = new Request( - HttpMethod.POST, - Domains.CONVERSATIONS.toString(), - path + HttpMethod.POST, + Domains.CONVERSATIONS.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); - addPostParams(request); addHeaderParams(request); + addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "User creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("User creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -101,26 +105,34 @@ public User create(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (identity != null) { - request.addPostParam("Identity", identity); + Serializer.toString(request, "Identity", identity, ParameterType.URLENCODED); } + + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + if (attributes != null) { - request.addPostParam("Attributes", attributes); + Serializer.toString(request, "Attributes", attributes, ParameterType.URLENCODED); } + + if (roleSid != null) { - request.addPostParam("RoleSid", roleSid); + Serializer.toString(request, "RoleSid", roleSid, ParameterType.URLENCODED); } + + } private void addHeaderParams(final Request request) { + if (xTwilioWebhookEnabled != null) { - request.addHeaderParam( - "X-Twilio-Webhook-Enabled", - xTwilioWebhookEnabled.toString() - ); + Serializer.toString(request, "X-Twilio-Webhook-Enabled", xTwilioWebhookEnabled, ParameterType.HEADER); } + } } diff --git a/src/main/java/com/twilio/rest/conversations/v1/UserDeleter.java b/src/main/java/com/twilio/rest/conversations/v1/UserDeleter.java index 2742ace0d6..d3bc43137f 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/UserDeleter.java +++ b/src/main/java/com/twilio/rest/conversations/v1/UserDeleter.java @@ -15,7 +15,8 @@ package com.twilio.rest.conversations.v1; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,49 +28,46 @@ public class UserDeleter extends Deleter { - private String pathSid; + private String pathsid; private User.WebhookEnabledType xTwilioWebhookEnabled; - public UserDeleter(final String pathSid) { - this.pathSid = pathSid; + public UserDeleter(final String pathsid) { + this.pathsid = pathsid; } - public UserDeleter setXTwilioWebhookEnabled( - final User.WebhookEnabledType xTwilioWebhookEnabled - ) { + + public UserDeleter setXTwilioWebhookEnabled(final User.WebhookEnabledType xTwilioWebhookEnabled) { this.xTwilioWebhookEnabled = xTwilioWebhookEnabled; return this; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/v1/Users/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.CONVERSATIONS.toString(), - path + HttpMethod.DELETE, + Domains.CONVERSATIONS.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addHeaderParams(request); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "User delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("User delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -77,11 +75,10 @@ public boolean delete(final TwilioRestClient client) { } private void addHeaderParams(final Request request) { + if (xTwilioWebhookEnabled != null) { - request.addHeaderParam( - "X-Twilio-Webhook-Enabled", - xTwilioWebhookEnabled.toString() - ); + Serializer.toString(request, "X-Twilio-Webhook-Enabled", xTwilioWebhookEnabled, ParameterType.HEADER); } + } } diff --git a/src/main/java/com/twilio/rest/conversations/v1/UserFetcher.java b/src/main/java/com/twilio/rest/conversations/v1/UserFetcher.java index 107da3131e..29e88e8ab1 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/UserFetcher.java +++ b/src/main/java/com/twilio/rest/conversations/v1/UserFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.conversations.v1; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,44 +26,41 @@ public class UserFetcher extends Fetcher { - private String pathSid; + private String pathsid; - public UserFetcher(final String pathSid) { - this.pathSid = pathSid; + public UserFetcher(final String pathsid) { + this.pathsid = pathsid; } + @Override public User fetch(final TwilioRestClient client) { + String path = "/v1/Users/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.CONVERSATIONS.toString(), - path + HttpMethod.GET, + Domains.CONVERSATIONS.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "User fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("User fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return User.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/conversations/v1/UserReader.java b/src/main/java/com/twilio/rest/conversations/v1/UserReader.java index 573c2d7635..71a2ee9a8f 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/UserReader.java +++ b/src/main/java/com/twilio/rest/conversations/v1/UserReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -31,105 +32,83 @@ public class UserReader extends Reader { private Long pageSize; - public UserReader() {} + public UserReader() { + } + public UserReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/Users"; + Request request = new Request( - HttpMethod.GET, - Domains.CONVERSATIONS.toString(), - path + HttpMethod.GET, + Domains.CONVERSATIONS.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "User read failed: Unable to connect to server" - ); + throw new ApiConnectionException("User read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "users", - response.getContent(), - User.class, - client.getObjectMapper() - ); + "users", + response.getContent(), + User.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.CONVERSATIONS.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.CONVERSATIONS.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/conversations/v1/UserUpdater.java b/src/main/java/com/twilio/rest/conversations/v1/UserUpdater.java index 80b98f5a15..c0a0048c10 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/UserUpdater.java +++ b/src/main/java/com/twilio/rest/conversations/v1/UserUpdater.java @@ -16,6 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -26,68 +28,69 @@ import com.twilio.rest.Domains; public class UserUpdater extends Updater { - - private String pathSid; + private String pathsid; private User.WebhookEnabledType xTwilioWebhookEnabled; private String friendlyName; private String attributes; private String roleSid; - public UserUpdater(final String pathSid) { - this.pathSid = pathSid; + public UserUpdater(final String pathsid) { + this.pathsid = pathsid; } - public UserUpdater setXTwilioWebhookEnabled( - final User.WebhookEnabledType xTwilioWebhookEnabled - ) { - this.xTwilioWebhookEnabled = xTwilioWebhookEnabled; - return this; - } public UserUpdater setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + public UserUpdater setAttributes(final String attributes) { this.attributes = attributes; return this; } + public UserUpdater setRoleSid(final String roleSid) { this.roleSid = roleSid; return this; } + + public UserUpdater setXTwilioWebhookEnabled(final User.WebhookEnabledType xTwilioWebhookEnabled) { + this.xTwilioWebhookEnabled = xTwilioWebhookEnabled; + return this; + } + + @Override public User update(final TwilioRestClient client) { + String path = "/v1/Users/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.CONVERSATIONS.toString(), - path + HttpMethod.POST, + Domains.CONVERSATIONS.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); - addPostParams(request); addHeaderParams(request); + addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "User update failed: Unable to connect to server" - ); + throw new ApiConnectionException("User update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -96,23 +99,29 @@ public User update(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + if (attributes != null) { - request.addPostParam("Attributes", attributes); + Serializer.toString(request, "Attributes", attributes, ParameterType.URLENCODED); } + + if (roleSid != null) { - request.addPostParam("RoleSid", roleSid); + Serializer.toString(request, "RoleSid", roleSid, ParameterType.URLENCODED); } + + } private void addHeaderParams(final Request request) { + if (xTwilioWebhookEnabled != null) { - request.addHeaderParam( - "X-Twilio-Webhook-Enabled", - xTwilioWebhookEnabled.toString() - ); + Serializer.toString(request, "X-Twilio-Webhook-Enabled", xTwilioWebhookEnabled, ParameterType.HEADER); } + } } diff --git a/src/main/java/com/twilio/rest/conversations/v1/configuration/Webhook.java b/src/main/java/com/twilio/rest/conversations/v1/configuration/Webhook.java index 485c684771..0ed2fccde9 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/configuration/Webhook.java +++ b/src/main/java/com/twilio/rest/conversations/v1/configuration/Webhook.java @@ -18,45 +18,90 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.util.List; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Webhook extends Resource { - private static final long serialVersionUID = 64791700237770L; public static WebhookFetcher fetcher() { - return new WebhookFetcher(); + return new WebhookFetcher( + + ); } + public static WebhookUpdater updater() { - return new WebhookUpdater(); + return new WebhookUpdater( + + ); + } + + + public enum Target { + WEBHOOK("webhook"), + FLEX("flex"); + + private final String value; + + private Target(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static Target forValue(final String value) { + return Promoter.enumFromString(value, Target.values()); + } + } + + public enum Method { + GET("GET"), + POST("POST"); + + private final String value; + + private Method(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static Method forValue(final String value) { + return Promoter.enumFromString(value, Method.values()); + } } + /** * Converts a JSON String into a Webhook object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Webhook object represented by the provided JSON */ - public static Webhook fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Webhook fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Webhook.class); @@ -71,14 +116,11 @@ public static Webhook fromJson( * Converts a JSON InputStream into a Webhook object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Webhook object represented by the provided JSON */ - public static Webhook fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Webhook fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Webhook.class); @@ -89,61 +131,53 @@ public static Webhook fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final Webhook.Method method; + @Getter private final List filters; - private final String preWebhookUrl; + @Getter + private final Webhook.Method method; + @Getter private final String postWebhookUrl; + @Getter + private final String preWebhookUrl; + @Getter private final Webhook.Target target; + @Getter private final URI url; @JsonCreator private Webhook( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("method") final Webhook.Method method, - @JsonProperty("filters") final List filters, - @JsonProperty("pre_webhook_url") final String preWebhookUrl, - @JsonProperty("post_webhook_url") final String postWebhookUrl, - @JsonProperty("target") final Webhook.Target target, - @JsonProperty("url") final URI url + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("filters") final List filters, + @JsonProperty("method") final Webhook.Method method, + @JsonProperty("post_webhook_url") final String postWebhookUrl, + @JsonProperty("pre_webhook_url") final String preWebhookUrl, + @JsonProperty("target") final Webhook.Target target, + @JsonProperty("url") final URI url ) { this.accountSid = accountSid; - this.method = method; this.filters = filters; - this.preWebhookUrl = preWebhookUrl; + this.method = method; this.postWebhookUrl = postWebhookUrl; + this.preWebhookUrl = preWebhookUrl; this.target = target; this.url = url; } - public final String getAccountSid() { - return this.accountSid; - } - - public final Webhook.Method getMethod() { - return this.method; - } - - public final List getFilters() { - return this.filters; - } - - public final String getPreWebhookUrl() { - return this.preWebhookUrl; - } - - public final String getPostWebhookUrl() { - return this.postWebhookUrl; - } - - public final Webhook.Target getTarget() { - return this.target; - } - - public final URI getUrl() { - return this.url; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -155,68 +189,30 @@ public boolean equals(final Object o) { } Webhook other = (Webhook) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(method, other.method) && - Objects.equals(filters, other.filters) && - Objects.equals(preWebhookUrl, other.preWebhookUrl) && - Objects.equals(postWebhookUrl, other.postWebhookUrl) && - Objects.equals(target, other.target) && - Objects.equals(url, other.url) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(filters, other.filters) && + Objects.equals(method, other.method) && + Objects.equals(postWebhookUrl, other.postWebhookUrl) && + Objects.equals(preWebhookUrl, other.preWebhookUrl) && + Objects.equals(target, other.target) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - accountSid, - method, - filters, - preWebhookUrl, - postWebhookUrl, - target, - url + accountSid, + filters, + method, + postWebhookUrl, + preWebhookUrl, + target, + url ); } - public enum Target { - WEBHOOK("webhook"), - FLEX("flex"); - - private final String value; - - private Target(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static Target forValue(final String value) { - return Promoter.enumFromString(value, Target.values()); - } - } - - public enum Method { - GET("GET"), - POST("POST"); - private final String value; - - private Method(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static Method forValue(final String value) { - return Promoter.enumFromString(value, Method.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/conversations/v1/configuration/WebhookFetcher.java b/src/main/java/com/twilio/rest/conversations/v1/configuration/WebhookFetcher.java index ebb8f919fc..f26b564123 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/configuration/WebhookFetcher.java +++ b/src/main/java/com/twilio/rest/conversations/v1/configuration/WebhookFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.conversations.v1.configuration; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,38 +26,37 @@ public class WebhookFetcher extends Fetcher { - public WebhookFetcher() {} + + public WebhookFetcher() { + } + @Override public Webhook fetch(final TwilioRestClient client) { + String path = "/v1/Configuration/Webhooks"; + Request request = new Request( - HttpMethod.GET, - Domains.CONVERSATIONS.toString(), - path + HttpMethod.GET, + Domains.CONVERSATIONS.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Webhook fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Webhook fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Webhook.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/conversations/v1/configuration/WebhookUpdater.java b/src/main/java/com/twilio/rest/conversations/v1/configuration/WebhookUpdater.java index fe4cf97a16..575203b44a 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/configuration/WebhookUpdater.java +++ b/src/main/java/com/twilio/rest/conversations/v1/configuration/WebhookUpdater.java @@ -16,7 +16,9 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; import com.twilio.converter.Promoter; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,23 +27,26 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.util.List; public class WebhookUpdater extends Updater { - private String method; private List filters; private String preWebhookUrl; private String postWebhookUrl; private Webhook.Target target; - public WebhookUpdater() {} + public WebhookUpdater() { + } + public WebhookUpdater setMethod(final String method) { this.method = method; return this; } + public WebhookUpdater setFilters(final List filters) { this.filters = filters; return this; @@ -56,42 +61,44 @@ public WebhookUpdater setPreWebhookUrl(final String preWebhookUrl) { return this; } + public WebhookUpdater setPostWebhookUrl(final String postWebhookUrl) { this.postWebhookUrl = postWebhookUrl; return this; } + public WebhookUpdater setTarget(final Webhook.Target target) { this.target = target; return this; } + @Override public Webhook update(final TwilioRestClient client) { + String path = "/v1/Configuration/Webhooks"; + Request request = new Request( - HttpMethod.POST, - Domains.CONVERSATIONS.toString(), - path + HttpMethod.POST, + Domains.CONVERSATIONS.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Webhook update failed: Unable to connect to server" - ); + throw new ApiConnectionException("Webhook update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -100,22 +107,33 @@ public Webhook update(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (method != null) { - request.addPostParam("Method", method); + Serializer.toString(request, "Method", method, ParameterType.URLENCODED); } + + if (filters != null) { - for (String prop : filters) { - request.addPostParam("Filters", prop); + for (String param : filters) { + Serializer.toString(request, "Filters", param, ParameterType.URLENCODED); } } + + if (preWebhookUrl != null) { - request.addPostParam("PreWebhookUrl", preWebhookUrl); + Serializer.toString(request, "PreWebhookUrl", preWebhookUrl, ParameterType.URLENCODED); } + + if (postWebhookUrl != null) { - request.addPostParam("PostWebhookUrl", postWebhookUrl); + Serializer.toString(request, "PostWebhookUrl", postWebhookUrl, ParameterType.URLENCODED); } + + if (target != null) { - request.addPostParam("Target", target.toString()); + Serializer.toString(request, "Target", target, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/conversations/v1/conversation/Message.java b/src/main/java/com/twilio/rest/conversations/v1/conversation/Message.java index 1b09716740..07eb74b7dc 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/conversation/Message.java +++ b/src/main/java/com/twilio/rest/conversations/v1/conversation/Message.java @@ -18,70 +18,114 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.List; import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Message extends Resource { - private static final long serialVersionUID = 43250311135417L; - public static MessageCreator creator(final String pathConversationSid) { - return new MessageCreator(pathConversationSid); + public static MessageCreator creator(final String pathconversationSid) { + return new MessageCreator( + pathconversationSid + ); } - public static MessageDeleter deleter( - final String pathConversationSid, - final String pathSid - ) { - return new MessageDeleter(pathConversationSid, pathSid); + + public static MessageDeleter deleter(final String pathconversationSid, final String pathsid) { + return new MessageDeleter( + pathconversationSid, pathsid + ); } - public static MessageFetcher fetcher( - final String pathConversationSid, - final String pathSid - ) { - return new MessageFetcher(pathConversationSid, pathSid); + + public static MessageFetcher fetcher(final String pathconversationSid, final String pathsid) { + return new MessageFetcher( + pathconversationSid, pathsid + ); } - public static MessageReader reader(final String pathConversationSid) { - return new MessageReader(pathConversationSid); + + public static MessageReader reader(final String pathconversationSid) { + return new MessageReader( + pathconversationSid + ); } - public static MessageUpdater updater( - final String pathConversationSid, - final String pathSid - ) { - return new MessageUpdater(pathConversationSid, pathSid); + + public static MessageUpdater updater(final String pathconversationSid, final String pathsid) { + return new MessageUpdater( + pathconversationSid, pathsid + ); + } + + + public enum WebhookEnabledType { + TRUE("true"), + FALSE("false"); + + private final String value; + + private WebhookEnabledType(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static WebhookEnabledType forValue(final String value) { + return Promoter.enumFromString(value, WebhookEnabledType.values()); + } + } + + public enum OrderType { + ASC("asc"), + DESC("desc"); + + private final String value; + + private OrderType(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static OrderType forValue(final String value) { + return Promoter.enumFromString(value, OrderType.values()); + } } + /** * Converts a JSON String into a Message object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Message object represented by the provided JSON */ - public static Message fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Message fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Message.class); @@ -96,14 +140,11 @@ public static Message fromJson( * Converts a JSON InputStream into a Message object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Message object represented by the provided JSON */ - public static Message fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Message fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Message.class); @@ -114,115 +155,85 @@ public static Message fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String conversationSid; - private final String sid; - private final Integer index; + @Getter + private final String attributes; + @Getter private final String author; + @Getter private final String body; - private final List> media; - private final String attributes; - private final String participantSid; + @Getter + private final String contentSid; + @Getter + private final String conversationSid; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; - private final URI url; - private final Map delivery; + @Getter + private final Object delivery; + @Getter + private final Integer index; + @Getter private final Map links; - private final String contentSid; + @Getter + private final List media; + @Getter + private final String participantSid; + @Getter + private final String sid; + @Getter + private final URI url; @JsonCreator private Message( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("conversation_sid") final String conversationSid, - @JsonProperty("sid") final String sid, - @JsonProperty("index") final Integer index, - @JsonProperty("author") final String author, - @JsonProperty("body") final String body, - @JsonProperty("media") final List> media, - @JsonProperty("attributes") final String attributes, - @JsonProperty("participant_sid") final String participantSid, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("url") final URI url, - @JsonProperty("delivery") final Map delivery, - @JsonProperty("links") final Map links, - @JsonProperty("content_sid") final String contentSid + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("attributes") final String attributes, + @JsonProperty("author") final String author, + @JsonProperty("body") final String body, + @JsonProperty("content_sid") final String contentSid, + @JsonProperty("conversation_sid") final String conversationSid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("delivery") final Object delivery, + @JsonProperty("index") final Integer index, + @JsonProperty("links") final Map links, + @JsonProperty("media") final List media, + @JsonProperty("participant_sid") final String participantSid, + @JsonProperty("sid") final String sid, + @JsonProperty("url") final URI url ) { this.accountSid = accountSid; - this.conversationSid = conversationSid; - this.sid = sid; - this.index = index; + this.attributes = attributes; this.author = author; this.body = body; + this.contentSid = contentSid; + this.conversationSid = conversationSid; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; + this.delivery = delivery; + this.index = index; + this.links = links; this.media = media; - this.attributes = attributes; this.participantSid = participantSid; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); + this.sid = sid; this.url = url; - this.delivery = delivery; - this.links = links; - this.contentSid = contentSid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getConversationSid() { - return this.conversationSid; - } - - public final String getSid() { - return this.sid; - } - - public final Integer getIndex() { - return this.index; - } - - public final String getAuthor() { - return this.author; - } - - public final String getBody() { - return this.body; - } - - public final List> getMedia() { - return this.media; - } - - public final String getAttributes() { - return this.attributes; - } - - public final String getParticipantSid() { - return this.participantSid; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final URI getUrl() { - return this.url; - } - - public final Map getDelivery() { - return this.delivery; - } - - public final Map getLinks() { - return this.links; - } - - public final String getContentSid() { - return this.contentSid; } @Override @@ -236,84 +247,46 @@ public boolean equals(final Object o) { } Message other = (Message) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(conversationSid, other.conversationSid) && - Objects.equals(sid, other.sid) && - Objects.equals(index, other.index) && - Objects.equals(author, other.author) && - Objects.equals(body, other.body) && - Objects.equals(media, other.media) && - Objects.equals(attributes, other.attributes) && - Objects.equals(participantSid, other.participantSid) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(url, other.url) && - Objects.equals(delivery, other.delivery) && - Objects.equals(links, other.links) && - Objects.equals(contentSid, other.contentSid) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(attributes, other.attributes) && + Objects.equals(author, other.author) && + Objects.equals(body, other.body) && + Objects.equals(contentSid, other.contentSid) && + Objects.equals(conversationSid, other.conversationSid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(delivery, other.delivery) && + Objects.equals(index, other.index) && + Objects.equals(links, other.links) && + Objects.equals(media, other.media) && + Objects.equals(participantSid, other.participantSid) && + Objects.equals(sid, other.sid) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - accountSid, - conversationSid, - sid, - index, - author, - body, - media, - attributes, - participantSid, - dateCreated, - dateUpdated, - url, - delivery, - links, - contentSid + accountSid, + attributes, + author, + body, + contentSid, + conversationSid, + dateCreated, + dateUpdated, + delivery, + index, + links, + media, + participantSid, + sid, + url ); } - public enum OrderType { - ASC("asc"), - DESC("desc"); - - private final String value; - - private OrderType(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static OrderType forValue(final String value) { - return Promoter.enumFromString(value, OrderType.values()); - } - } - - public enum WebhookEnabledType { - TRUE("true"), - FALSE("false"); - - private final String value; - - private WebhookEnabledType(final String value) { - this.value = value; - } - public String toString() { - return value; - } - - @JsonCreator - public static WebhookEnabledType forValue(final String value) { - return Promoter.enumFromString(value, WebhookEnabledType.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/conversations/v1/conversation/MessageCreator.java b/src/main/java/com/twilio/rest/conversations/v1/conversation/MessageCreator.java index 9813048c94..31226a67fa 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/conversation/MessageCreator.java +++ b/src/main/java/com/twilio/rest/conversations/v1/conversation/MessageCreator.java @@ -14,8 +14,11 @@ package com.twilio.rest.conversations.v1.conversation; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -24,11 +27,12 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.time.ZonedDateTime; public class MessageCreator extends Creator { - private String pathConversationSid; + private String pathconversationSid; private Message.WebhookEnabledType xTwilioWebhookEnabled; private String author; private String body; @@ -40,95 +44,99 @@ public class MessageCreator extends Creator { private String contentVariables; private String subject; - public MessageCreator(final String pathConversationSid) { - this.pathConversationSid = pathConversationSid; + public MessageCreator(final String pathconversationSid) { + this.pathconversationSid = pathconversationSid; } - public MessageCreator setXTwilioWebhookEnabled( - final Message.WebhookEnabledType xTwilioWebhookEnabled - ) { - this.xTwilioWebhookEnabled = xTwilioWebhookEnabled; - return this; - } public MessageCreator setAuthor(final String author) { this.author = author; return this; } + public MessageCreator setBody(final String body) { this.body = body; return this; } + public MessageCreator setDateCreated(final ZonedDateTime dateCreated) { this.dateCreated = dateCreated; return this; } + public MessageCreator setDateUpdated(final ZonedDateTime dateUpdated) { this.dateUpdated = dateUpdated; return this; } + public MessageCreator setAttributes(final String attributes) { this.attributes = attributes; return this; } + public MessageCreator setMediaSid(final String mediaSid) { this.mediaSid = mediaSid; return this; } + public MessageCreator setContentSid(final String contentSid) { this.contentSid = contentSid; return this; } + public MessageCreator setContentVariables(final String contentVariables) { this.contentVariables = contentVariables; return this; } + public MessageCreator setSubject(final String subject) { this.subject = subject; return this; } + + public MessageCreator setXTwilioWebhookEnabled(final Message.WebhookEnabledType xTwilioWebhookEnabled) { + this.xTwilioWebhookEnabled = xTwilioWebhookEnabled; + return this; + } + + @Override public Message create(final TwilioRestClient client) { + String path = "/v1/Conversations/{ConversationSid}/Messages"; - path = - path.replace( - "{" + "ConversationSid" + "}", - this.pathConversationSid.toString() - ); + path = path.replace("{" + "ConversationSid" + "}", this.pathconversationSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.CONVERSATIONS.toString(), - path + HttpMethod.POST, + Domains.CONVERSATIONS.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); - addPostParams(request); addHeaderParams(request); + addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Message creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("Message creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -137,47 +145,59 @@ public Message create(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (author != null) { - request.addPostParam("Author", author); + Serializer.toString(request, "Author", author, ParameterType.URLENCODED); } + + if (body != null) { - request.addPostParam("Body", body); + Serializer.toString(request, "Body", body, ParameterType.URLENCODED); } + + if (dateCreated != null) { - request.addPostParam( - "DateCreated", - dateCreated.toInstant().toString() - ); + Serializer.toString(request, "DateCreated", dateCreated, ParameterType.URLENCODED); } + + if (dateUpdated != null) { - request.addPostParam( - "DateUpdated", - dateUpdated.toInstant().toString() - ); + Serializer.toString(request, "DateUpdated", dateUpdated, ParameterType.URLENCODED); } + + if (attributes != null) { - request.addPostParam("Attributes", attributes); + Serializer.toString(request, "Attributes", attributes, ParameterType.URLENCODED); } + + if (mediaSid != null) { - request.addPostParam("MediaSid", mediaSid); + Serializer.toString(request, "MediaSid", mediaSid, ParameterType.URLENCODED); } + + if (contentSid != null) { - request.addPostParam("ContentSid", contentSid); + Serializer.toString(request, "ContentSid", contentSid, ParameterType.URLENCODED); } + + if (contentVariables != null) { - request.addPostParam("ContentVariables", contentVariables); + Serializer.toString(request, "ContentVariables", contentVariables, ParameterType.URLENCODED); } + + if (subject != null) { - request.addPostParam("Subject", subject); + Serializer.toString(request, "Subject", subject, ParameterType.URLENCODED); } + + } private void addHeaderParams(final Request request) { + if (xTwilioWebhookEnabled != null) { - request.addHeaderParam( - "X-Twilio-Webhook-Enabled", - xTwilioWebhookEnabled.toString() - ); + Serializer.toString(request, "X-Twilio-Webhook-Enabled", xTwilioWebhookEnabled, ParameterType.HEADER); } + } } diff --git a/src/main/java/com/twilio/rest/conversations/v1/conversation/MessageDeleter.java b/src/main/java/com/twilio/rest/conversations/v1/conversation/MessageDeleter.java index fd52f6c0fd..e485594d75 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/conversation/MessageDeleter.java +++ b/src/main/java/com/twilio/rest/conversations/v1/conversation/MessageDeleter.java @@ -15,7 +15,8 @@ package com.twilio.rest.conversations.v1.conversation; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,59 +28,49 @@ public class MessageDeleter extends Deleter { - private String pathConversationSid; - private String pathSid; + private String pathconversationSid; + private String pathsid; private Message.WebhookEnabledType xTwilioWebhookEnabled; - public MessageDeleter( - final String pathConversationSid, - final String pathSid - ) { - this.pathConversationSid = pathConversationSid; - this.pathSid = pathSid; + public MessageDeleter(final String pathconversationSid, final String pathsid) { + this.pathconversationSid = pathconversationSid; + this.pathsid = pathsid; } - public MessageDeleter setXTwilioWebhookEnabled( - final Message.WebhookEnabledType xTwilioWebhookEnabled - ) { + + public MessageDeleter setXTwilioWebhookEnabled(final Message.WebhookEnabledType xTwilioWebhookEnabled) { this.xTwilioWebhookEnabled = xTwilioWebhookEnabled; return this; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/v1/Conversations/{ConversationSid}/Messages/{Sid}"; - path = - path.replace( - "{" + "ConversationSid" + "}", - this.pathConversationSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "ConversationSid" + "}", this.pathconversationSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.CONVERSATIONS.toString(), - path + HttpMethod.DELETE, + Domains.CONVERSATIONS.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addHeaderParams(request); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Message delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("Message delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -87,11 +78,10 @@ public boolean delete(final TwilioRestClient client) { } private void addHeaderParams(final Request request) { + if (xTwilioWebhookEnabled != null) { - request.addHeaderParam( - "X-Twilio-Webhook-Enabled", - xTwilioWebhookEnabled.toString() - ); + Serializer.toString(request, "X-Twilio-Webhook-Enabled", xTwilioWebhookEnabled, ParameterType.HEADER); } + } } diff --git a/src/main/java/com/twilio/rest/conversations/v1/conversation/MessageFetcher.java b/src/main/java/com/twilio/rest/conversations/v1/conversation/MessageFetcher.java index b6cad392ec..af9c7ae371 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/conversation/MessageFetcher.java +++ b/src/main/java/com/twilio/rest/conversations/v1/conversation/MessageFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.conversations.v1.conversation; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,54 +26,44 @@ public class MessageFetcher extends Fetcher { - private String pathConversationSid; - private String pathSid; + private String pathconversationSid; + private String pathsid; - public MessageFetcher( - final String pathConversationSid, - final String pathSid - ) { - this.pathConversationSid = pathConversationSid; - this.pathSid = pathSid; + public MessageFetcher(final String pathconversationSid, final String pathsid) { + this.pathconversationSid = pathconversationSid; + this.pathsid = pathsid; } + @Override public Message fetch(final TwilioRestClient client) { + String path = "/v1/Conversations/{ConversationSid}/Messages/{Sid}"; - path = - path.replace( - "{" + "ConversationSid" + "}", - this.pathConversationSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "ConversationSid" + "}", this.pathconversationSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.CONVERSATIONS.toString(), - path + HttpMethod.GET, + Domains.CONVERSATIONS.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Message fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Message fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Message.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/conversations/v1/conversation/MessageReader.java b/src/main/java/com/twilio/rest/conversations/v1/conversation/MessageReader.java index 784e11db8c..fdc00400b7 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/conversation/MessageReader.java +++ b/src/main/java/com/twilio/rest/conversations/v1/conversation/MessageReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,124 +30,100 @@ public class MessageReader extends Reader { - private String pathConversationSid; + private String pathconversationSid; private Message.OrderType order; private Long pageSize; - public MessageReader(final String pathConversationSid) { - this.pathConversationSid = pathConversationSid; + public MessageReader(final String pathconversationSid) { + this.pathconversationSid = pathconversationSid; } + public MessageReader setOrder(final Message.OrderType order) { this.order = order; return this; } + public MessageReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/Conversations/{ConversationSid}/Messages"; - path = - path.replace( - "{" + "ConversationSid" + "}", - this.pathConversationSid.toString() - ); + + path = path.replace("{" + "ConversationSid" + "}", this.pathconversationSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.CONVERSATIONS.toString(), - path + HttpMethod.GET, + Domains.CONVERSATIONS.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Message read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Message read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "messages", - response.getContent(), - Message.class, - client.getObjectMapper() - ); + "messages", + response.getContent(), + Message.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.CONVERSATIONS.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.CONVERSATIONS.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (order != null) { - request.addQueryParam("Order", order.toString()); + Serializer.toString(request, "Order", order, ParameterType.QUERY); } + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/conversations/v1/conversation/MessageUpdater.java b/src/main/java/com/twilio/rest/conversations/v1/conversation/MessageUpdater.java index 62fd4ed828..25b8282b2f 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/conversation/MessageUpdater.java +++ b/src/main/java/com/twilio/rest/conversations/v1/conversation/MessageUpdater.java @@ -16,6 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -24,12 +26,12 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.time.ZonedDateTime; public class MessageUpdater extends Updater { - - private String pathConversationSid; - private String pathSid; + private String pathconversationSid; + private String pathsid; private Message.WebhookEnabledType xTwilioWebhookEnabled; private String author; private String body; @@ -38,85 +40,83 @@ public class MessageUpdater extends Updater { private String attributes; private String subject; - public MessageUpdater( - final String pathConversationSid, - final String pathSid - ) { - this.pathConversationSid = pathConversationSid; - this.pathSid = pathSid; + public MessageUpdater(final String pathconversationSid, final String pathsid) { + this.pathconversationSid = pathconversationSid; + this.pathsid = pathsid; } - public MessageUpdater setXTwilioWebhookEnabled( - final Message.WebhookEnabledType xTwilioWebhookEnabled - ) { - this.xTwilioWebhookEnabled = xTwilioWebhookEnabled; - return this; - } public MessageUpdater setAuthor(final String author) { this.author = author; return this; } + public MessageUpdater setBody(final String body) { this.body = body; return this; } + public MessageUpdater setDateCreated(final ZonedDateTime dateCreated) { this.dateCreated = dateCreated; return this; } + public MessageUpdater setDateUpdated(final ZonedDateTime dateUpdated) { this.dateUpdated = dateUpdated; return this; } + public MessageUpdater setAttributes(final String attributes) { this.attributes = attributes; return this; } + public MessageUpdater setSubject(final String subject) { this.subject = subject; return this; } + + public MessageUpdater setXTwilioWebhookEnabled(final Message.WebhookEnabledType xTwilioWebhookEnabled) { + this.xTwilioWebhookEnabled = xTwilioWebhookEnabled; + return this; + } + + @Override public Message update(final TwilioRestClient client) { + String path = "/v1/Conversations/{ConversationSid}/Messages/{Sid}"; - path = - path.replace( - "{" + "ConversationSid" + "}", - this.pathConversationSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "ConversationSid" + "}", this.pathconversationSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.CONVERSATIONS.toString(), - path + HttpMethod.POST, + Domains.CONVERSATIONS.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); - addPostParams(request); addHeaderParams(request); + addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Message update failed: Unable to connect to server" - ); + throw new ApiConnectionException("Message update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -125,38 +125,44 @@ public Message update(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (author != null) { - request.addPostParam("Author", author); + Serializer.toString(request, "Author", author, ParameterType.URLENCODED); } + + if (body != null) { - request.addPostParam("Body", body); + Serializer.toString(request, "Body", body, ParameterType.URLENCODED); } + + if (dateCreated != null) { - request.addPostParam( - "DateCreated", - dateCreated.toInstant().toString() - ); + Serializer.toString(request, "DateCreated", dateCreated, ParameterType.URLENCODED); } + + if (dateUpdated != null) { - request.addPostParam( - "DateUpdated", - dateUpdated.toInstant().toString() - ); + Serializer.toString(request, "DateUpdated", dateUpdated, ParameterType.URLENCODED); } + + if (attributes != null) { - request.addPostParam("Attributes", attributes); + Serializer.toString(request, "Attributes", attributes, ParameterType.URLENCODED); } + + if (subject != null) { - request.addPostParam("Subject", subject); + Serializer.toString(request, "Subject", subject, ParameterType.URLENCODED); } + + } private void addHeaderParams(final Request request) { + if (xTwilioWebhookEnabled != null) { - request.addHeaderParam( - "X-Twilio-Webhook-Enabled", - xTwilioWebhookEnabled.toString() - ); + Serializer.toString(request, "X-Twilio-Webhook-Enabled", xTwilioWebhookEnabled, ParameterType.HEADER); } + } } diff --git a/src/main/java/com/twilio/rest/conversations/v1/conversation/Participant.java b/src/main/java/com/twilio/rest/conversations/v1/conversation/Participant.java index 270b7918af..c66371f282 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/conversation/Participant.java +++ b/src/main/java/com/twilio/rest/conversations/v1/conversation/Participant.java @@ -18,69 +18,92 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; -import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Participant extends Resource { - private static final long serialVersionUID = 164096252184722L; - public static ParticipantCreator creator(final String pathConversationSid) { - return new ParticipantCreator(pathConversationSid); + public static ParticipantCreator creator(final String pathconversationSid) { + return new ParticipantCreator( + pathconversationSid + ); } - public static ParticipantDeleter deleter( - final String pathConversationSid, - final String pathSid - ) { - return new ParticipantDeleter(pathConversationSid, pathSid); + + public static ParticipantDeleter deleter(final String pathconversationSid, final String pathsid) { + return new ParticipantDeleter( + pathconversationSid, pathsid + ); } - public static ParticipantFetcher fetcher( - final String pathConversationSid, - final String pathSid - ) { - return new ParticipantFetcher(pathConversationSid, pathSid); + + public static ParticipantFetcher fetcher(final String pathconversationSid, final String pathsid) { + return new ParticipantFetcher( + pathconversationSid, pathsid + ); } - public static ParticipantReader reader(final String pathConversationSid) { - return new ParticipantReader(pathConversationSid); + + public static ParticipantReader reader(final String pathconversationSid) { + return new ParticipantReader( + pathconversationSid + ); } - public static ParticipantUpdater updater( - final String pathConversationSid, - final String pathSid - ) { - return new ParticipantUpdater(pathConversationSid, pathSid); + + public static ParticipantUpdater updater(final String pathconversationSid, final String pathsid) { + return new ParticipantUpdater( + pathconversationSid, pathsid + ); + } + + + public enum WebhookEnabledType { + TRUE("true"), + FALSE("false"); + + private final String value; + + private WebhookEnabledType(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static WebhookEnabledType forValue(final String value) { + return Promoter.enumFromString(value, WebhookEnabledType.values()); + } } + /** * Converts a JSON String into a Participant object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Participant object represented by the provided JSON */ - public static Participant fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Participant fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Participant.class); @@ -95,14 +118,11 @@ public static Participant fromJson( * Converts a JSON InputStream into a Participant object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Participant object represented by the provided JSON */ - public static Participant fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Participant fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Participant.class); @@ -113,99 +133,73 @@ public static Participant fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String conversationSid; - private final String sid; - private final String identity; + @Getter private final String attributes; - private final Map messagingBinding; - private final String roleSid; + @Getter + private final String conversationSid; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; - private final URI url; + @Getter + private final String identity; + @Getter private final Integer lastReadMessageIndex; + @Getter private final String lastReadTimestamp; + @Getter + private final Object messagingBinding; + @Getter + private final String roleSid; + @Getter + private final String sid; + @Getter + private final URI url; @JsonCreator private Participant( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("conversation_sid") final String conversationSid, - @JsonProperty("sid") final String sid, - @JsonProperty("identity") final String identity, - @JsonProperty("attributes") final String attributes, - @JsonProperty("messaging_binding") final Map< - String, - Object - > messagingBinding, - @JsonProperty("role_sid") final String roleSid, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("url") final URI url, - @JsonProperty( - "last_read_message_index" - ) final Integer lastReadMessageIndex, - @JsonProperty("last_read_timestamp") final String lastReadTimestamp + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("attributes") final String attributes, + @JsonProperty("conversation_sid") final String conversationSid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("identity") final String identity, + @JsonProperty("last_read_message_index") final Integer lastReadMessageIndex, + @JsonProperty("last_read_timestamp") final String lastReadTimestamp, + @JsonProperty("messaging_binding") final Object messagingBinding, + @JsonProperty("role_sid") final String roleSid, + @JsonProperty("sid") final String sid, + @JsonProperty("url") final URI url ) { this.accountSid = accountSid; + this.attributes = attributes; this.conversationSid = conversationSid; - this.sid = sid; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.identity = identity; - this.attributes = attributes; + this.lastReadMessageIndex = lastReadMessageIndex; + this.lastReadTimestamp = lastReadTimestamp; this.messagingBinding = messagingBinding; this.roleSid = roleSid; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); + this.sid = sid; this.url = url; - this.lastReadMessageIndex = lastReadMessageIndex; - this.lastReadTimestamp = lastReadTimestamp; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getConversationSid() { - return this.conversationSid; - } - - public final String getSid() { - return this.sid; - } - - public final String getIdentity() { - return this.identity; - } - - public final String getAttributes() { - return this.attributes; - } - - public final Map getMessagingBinding() { - return this.messagingBinding; - } - - public final String getRoleSid() { - return this.roleSid; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final URI getUrl() { - return this.url; - } - - public final Integer getLastReadMessageIndex() { - return this.lastReadMessageIndex; - } - - public final String getLastReadTimestamp() { - return this.lastReadTimestamp; } @Override @@ -219,58 +213,40 @@ public boolean equals(final Object o) { } Participant other = (Participant) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(conversationSid, other.conversationSid) && - Objects.equals(sid, other.sid) && - Objects.equals(identity, other.identity) && - Objects.equals(attributes, other.attributes) && - Objects.equals(messagingBinding, other.messagingBinding) && - Objects.equals(roleSid, other.roleSid) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(url, other.url) && - Objects.equals(lastReadMessageIndex, other.lastReadMessageIndex) && - Objects.equals(lastReadTimestamp, other.lastReadTimestamp) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(attributes, other.attributes) && + Objects.equals(conversationSid, other.conversationSid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(identity, other.identity) && + Objects.equals(lastReadMessageIndex, other.lastReadMessageIndex) && + Objects.equals(lastReadTimestamp, other.lastReadTimestamp) && + Objects.equals(messagingBinding, other.messagingBinding) && + Objects.equals(roleSid, other.roleSid) && + Objects.equals(sid, other.sid) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - accountSid, - conversationSid, - sid, - identity, - attributes, - messagingBinding, - roleSid, - dateCreated, - dateUpdated, - url, - lastReadMessageIndex, - lastReadTimestamp + accountSid, + attributes, + conversationSid, + dateCreated, + dateUpdated, + identity, + lastReadMessageIndex, + lastReadTimestamp, + messagingBinding, + roleSid, + sid, + url ); } - public enum WebhookEnabledType { - TRUE("true"), - FALSE("false"); - private final String value; - - private WebhookEnabledType(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static WebhookEnabledType forValue(final String value) { - return Promoter.enumFromString(value, WebhookEnabledType.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/conversations/v1/conversation/ParticipantCreator.java b/src/main/java/com/twilio/rest/conversations/v1/conversation/ParticipantCreator.java index 26e5eb7ccd..47f365959a 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/conversation/ParticipantCreator.java +++ b/src/main/java/com/twilio/rest/conversations/v1/conversation/ParticipantCreator.java @@ -14,8 +14,11 @@ package com.twilio.rest.conversations.v1.conversation; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -24,11 +27,12 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.time.ZonedDateTime; public class ParticipantCreator extends Creator { - private String pathConversationSid; + private String pathconversationSid; private Participant.WebhookEnabledType xTwilioWebhookEnabled; private String identity; private String messagingBindingAddress; @@ -39,155 +43,149 @@ public class ParticipantCreator extends Creator { private String messagingBindingProjectedAddress; private String roleSid; - public ParticipantCreator(final String pathConversationSid) { - this.pathConversationSid = pathConversationSid; + public ParticipantCreator(final String pathconversationSid) { + this.pathconversationSid = pathconversationSid; } - public ParticipantCreator setXTwilioWebhookEnabled( - final Participant.WebhookEnabledType xTwilioWebhookEnabled - ) { - this.xTwilioWebhookEnabled = xTwilioWebhookEnabled; - return this; - } public ParticipantCreator setIdentity(final String identity) { this.identity = identity; return this; } - public ParticipantCreator setMessagingBindingAddress( - final String messagingBindingAddress - ) { + + public ParticipantCreator setMessagingBindingAddress(final String messagingBindingAddress) { this.messagingBindingAddress = messagingBindingAddress; return this; } - public ParticipantCreator setMessagingBindingProxyAddress( - final String messagingBindingProxyAddress - ) { + + public ParticipantCreator setMessagingBindingProxyAddress(final String messagingBindingProxyAddress) { this.messagingBindingProxyAddress = messagingBindingProxyAddress; return this; } + public ParticipantCreator setDateCreated(final ZonedDateTime dateCreated) { this.dateCreated = dateCreated; return this; } + public ParticipantCreator setDateUpdated(final ZonedDateTime dateUpdated) { this.dateUpdated = dateUpdated; return this; } + public ParticipantCreator setAttributes(final String attributes) { this.attributes = attributes; return this; } - public ParticipantCreator setMessagingBindingProjectedAddress( - final String messagingBindingProjectedAddress - ) { - this.messagingBindingProjectedAddress = - messagingBindingProjectedAddress; + + public ParticipantCreator setMessagingBindingProjectedAddress(final String messagingBindingProjectedAddress) { + this.messagingBindingProjectedAddress = messagingBindingProjectedAddress; return this; } + public ParticipantCreator setRoleSid(final String roleSid) { this.roleSid = roleSid; return this; } + + public ParticipantCreator setXTwilioWebhookEnabled(final Participant.WebhookEnabledType xTwilioWebhookEnabled) { + this.xTwilioWebhookEnabled = xTwilioWebhookEnabled; + return this; + } + + @Override public Participant create(final TwilioRestClient client) { + String path = "/v1/Conversations/{ConversationSid}/Participants"; - path = - path.replace( - "{" + "ConversationSid" + "}", - this.pathConversationSid.toString() - ); + path = path.replace("{" + "ConversationSid" + "}", this.pathconversationSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.CONVERSATIONS.toString(), - path + HttpMethod.POST, + Domains.CONVERSATIONS.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); - addPostParams(request); addHeaderParams(request); + addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Participant creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("Participant creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Participant.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Participant.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (identity != null) { - request.addPostParam("Identity", identity); + Serializer.toString(request, "Identity", identity, ParameterType.URLENCODED); } + + if (messagingBindingAddress != null) { - request.addPostParam( - "MessagingBinding.Address", - messagingBindingAddress - ); + Serializer.toString(request, "MessagingBinding.Address", messagingBindingAddress, ParameterType.URLENCODED); } + + if (messagingBindingProxyAddress != null) { - request.addPostParam( - "MessagingBinding.ProxyAddress", - messagingBindingProxyAddress - ); + Serializer.toString(request, "MessagingBinding.ProxyAddress", messagingBindingProxyAddress, ParameterType.URLENCODED); } + + if (dateCreated != null) { - request.addPostParam( - "DateCreated", - dateCreated.toInstant().toString() - ); + Serializer.toString(request, "DateCreated", dateCreated, ParameterType.URLENCODED); } + + if (dateUpdated != null) { - request.addPostParam( - "DateUpdated", - dateUpdated.toInstant().toString() - ); + Serializer.toString(request, "DateUpdated", dateUpdated, ParameterType.URLENCODED); } + + if (attributes != null) { - request.addPostParam("Attributes", attributes); + Serializer.toString(request, "Attributes", attributes, ParameterType.URLENCODED); } + + if (messagingBindingProjectedAddress != null) { - request.addPostParam( - "MessagingBinding.ProjectedAddress", - messagingBindingProjectedAddress - ); + Serializer.toString(request, "MessagingBinding.ProjectedAddress", messagingBindingProjectedAddress, ParameterType.URLENCODED); } + + if (roleSid != null) { - request.addPostParam("RoleSid", roleSid); + Serializer.toString(request, "RoleSid", roleSid, ParameterType.URLENCODED); } + + } private void addHeaderParams(final Request request) { + if (xTwilioWebhookEnabled != null) { - request.addHeaderParam( - "X-Twilio-Webhook-Enabled", - xTwilioWebhookEnabled.toString() - ); + Serializer.toString(request, "X-Twilio-Webhook-Enabled", xTwilioWebhookEnabled, ParameterType.HEADER); } + } } diff --git a/src/main/java/com/twilio/rest/conversations/v1/conversation/ParticipantDeleter.java b/src/main/java/com/twilio/rest/conversations/v1/conversation/ParticipantDeleter.java index 6530feb3b8..54ff382b04 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/conversation/ParticipantDeleter.java +++ b/src/main/java/com/twilio/rest/conversations/v1/conversation/ParticipantDeleter.java @@ -15,7 +15,8 @@ package com.twilio.rest.conversations.v1.conversation; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,59 +28,49 @@ public class ParticipantDeleter extends Deleter { - private String pathConversationSid; - private String pathSid; + private String pathconversationSid; + private String pathsid; private Participant.WebhookEnabledType xTwilioWebhookEnabled; - public ParticipantDeleter( - final String pathConversationSid, - final String pathSid - ) { - this.pathConversationSid = pathConversationSid; - this.pathSid = pathSid; + public ParticipantDeleter(final String pathconversationSid, final String pathsid) { + this.pathconversationSid = pathconversationSid; + this.pathsid = pathsid; } - public ParticipantDeleter setXTwilioWebhookEnabled( - final Participant.WebhookEnabledType xTwilioWebhookEnabled - ) { + + public ParticipantDeleter setXTwilioWebhookEnabled(final Participant.WebhookEnabledType xTwilioWebhookEnabled) { this.xTwilioWebhookEnabled = xTwilioWebhookEnabled; return this; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/v1/Conversations/{ConversationSid}/Participants/{Sid}"; - path = - path.replace( - "{" + "ConversationSid" + "}", - this.pathConversationSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "ConversationSid" + "}", this.pathconversationSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.CONVERSATIONS.toString(), - path + HttpMethod.DELETE, + Domains.CONVERSATIONS.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addHeaderParams(request); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Participant delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("Participant delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -87,11 +78,10 @@ public boolean delete(final TwilioRestClient client) { } private void addHeaderParams(final Request request) { + if (xTwilioWebhookEnabled != null) { - request.addHeaderParam( - "X-Twilio-Webhook-Enabled", - xTwilioWebhookEnabled.toString() - ); + Serializer.toString(request, "X-Twilio-Webhook-Enabled", xTwilioWebhookEnabled, ParameterType.HEADER); } + } } diff --git a/src/main/java/com/twilio/rest/conversations/v1/conversation/ParticipantFetcher.java b/src/main/java/com/twilio/rest/conversations/v1/conversation/ParticipantFetcher.java index 71347d8511..c4c46fbcf1 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/conversation/ParticipantFetcher.java +++ b/src/main/java/com/twilio/rest/conversations/v1/conversation/ParticipantFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.conversations.v1.conversation; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,57 +26,44 @@ public class ParticipantFetcher extends Fetcher { - private String pathConversationSid; - private String pathSid; + private String pathconversationSid; + private String pathsid; - public ParticipantFetcher( - final String pathConversationSid, - final String pathSid - ) { - this.pathConversationSid = pathConversationSid; - this.pathSid = pathSid; + public ParticipantFetcher(final String pathconversationSid, final String pathsid) { + this.pathconversationSid = pathconversationSid; + this.pathsid = pathsid; } + @Override public Participant fetch(final TwilioRestClient client) { + String path = "/v1/Conversations/{ConversationSid}/Participants/{Sid}"; - path = - path.replace( - "{" + "ConversationSid" + "}", - this.pathConversationSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "ConversationSid" + "}", this.pathconversationSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.CONVERSATIONS.toString(), - path + HttpMethod.GET, + Domains.CONVERSATIONS.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Participant fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Participant fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return Participant.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Participant.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/conversations/v1/conversation/ParticipantReader.java b/src/main/java/com/twilio/rest/conversations/v1/conversation/ParticipantReader.java index 49f7eaf018..9f7d73275b 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/conversation/ParticipantReader.java +++ b/src/main/java/com/twilio/rest/conversations/v1/conversation/ParticipantReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,115 +30,88 @@ public class ParticipantReader extends Reader { - private String pathConversationSid; + private String pathconversationSid; private Long pageSize; - public ParticipantReader(final String pathConversationSid) { - this.pathConversationSid = pathConversationSid; + public ParticipantReader(final String pathconversationSid) { + this.pathconversationSid = pathconversationSid; } + public ParticipantReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/Conversations/{ConversationSid}/Participants"; - path = - path.replace( - "{" + "ConversationSid" + "}", - this.pathConversationSid.toString() - ); + + path = path.replace("{" + "ConversationSid" + "}", this.pathconversationSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.CONVERSATIONS.toString(), - path + HttpMethod.GET, + Domains.CONVERSATIONS.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Participant read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Participant read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "participants", - response.getContent(), - Participant.class, - client.getObjectMapper() - ); + "participants", + response.getContent(), + Participant.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.CONVERSATIONS.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.CONVERSATIONS.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/conversations/v1/conversation/ParticipantUpdater.java b/src/main/java/com/twilio/rest/conversations/v1/conversation/ParticipantUpdater.java index 0ff9faefd5..b037f20dbf 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/conversation/ParticipantUpdater.java +++ b/src/main/java/com/twilio/rest/conversations/v1/conversation/ParticipantUpdater.java @@ -16,6 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -24,12 +26,12 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.time.ZonedDateTime; public class ParticipantUpdater extends Updater { - - private String pathConversationSid; - private String pathSid; + private String pathconversationSid; + private String pathsid; private Participant.WebhookEnabledType xTwilioWebhookEnabled; private ZonedDateTime dateCreated; private ZonedDateTime dateUpdated; @@ -41,170 +43,162 @@ public class ParticipantUpdater extends Updater { private Integer lastReadMessageIndex; private String lastReadTimestamp; - public ParticipantUpdater( - final String pathConversationSid, - final String pathSid - ) { - this.pathConversationSid = pathConversationSid; - this.pathSid = pathSid; + public ParticipantUpdater(final String pathconversationSid, final String pathsid) { + this.pathconversationSid = pathconversationSid; + this.pathsid = pathsid; } - public ParticipantUpdater setXTwilioWebhookEnabled( - final Participant.WebhookEnabledType xTwilioWebhookEnabled - ) { - this.xTwilioWebhookEnabled = xTwilioWebhookEnabled; - return this; - } public ParticipantUpdater setDateCreated(final ZonedDateTime dateCreated) { this.dateCreated = dateCreated; return this; } + public ParticipantUpdater setDateUpdated(final ZonedDateTime dateUpdated) { this.dateUpdated = dateUpdated; return this; } + public ParticipantUpdater setAttributes(final String attributes) { this.attributes = attributes; return this; } + public ParticipantUpdater setRoleSid(final String roleSid) { this.roleSid = roleSid; return this; } - public ParticipantUpdater setMessagingBindingProxyAddress( - final String messagingBindingProxyAddress - ) { + + public ParticipantUpdater setMessagingBindingProxyAddress(final String messagingBindingProxyAddress) { this.messagingBindingProxyAddress = messagingBindingProxyAddress; return this; } - public ParticipantUpdater setMessagingBindingProjectedAddress( - final String messagingBindingProjectedAddress - ) { - this.messagingBindingProjectedAddress = - messagingBindingProjectedAddress; + + public ParticipantUpdater setMessagingBindingProjectedAddress(final String messagingBindingProjectedAddress) { + this.messagingBindingProjectedAddress = messagingBindingProjectedAddress; return this; } + public ParticipantUpdater setIdentity(final String identity) { this.identity = identity; return this; } - public ParticipantUpdater setLastReadMessageIndex( - final Integer lastReadMessageIndex - ) { + + public ParticipantUpdater setLastReadMessageIndex(final Integer lastReadMessageIndex) { this.lastReadMessageIndex = lastReadMessageIndex; return this; } - public ParticipantUpdater setLastReadTimestamp( - final String lastReadTimestamp - ) { + + public ParticipantUpdater setLastReadTimestamp(final String lastReadTimestamp) { this.lastReadTimestamp = lastReadTimestamp; return this; } + + public ParticipantUpdater setXTwilioWebhookEnabled(final Participant.WebhookEnabledType xTwilioWebhookEnabled) { + this.xTwilioWebhookEnabled = xTwilioWebhookEnabled; + return this; + } + + @Override public Participant update(final TwilioRestClient client) { + String path = "/v1/Conversations/{ConversationSid}/Participants/{Sid}"; - path = - path.replace( - "{" + "ConversationSid" + "}", - this.pathConversationSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "ConversationSid" + "}", this.pathconversationSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.CONVERSATIONS.toString(), - path + HttpMethod.POST, + Domains.CONVERSATIONS.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); - addPostParams(request); addHeaderParams(request); + addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Participant update failed: Unable to connect to server" - ); + throw new ApiConnectionException("Participant update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Participant.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Participant.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (dateCreated != null) { - request.addPostParam( - "DateCreated", - dateCreated.toInstant().toString() - ); + Serializer.toString(request, "DateCreated", dateCreated, ParameterType.URLENCODED); } + + if (dateUpdated != null) { - request.addPostParam( - "DateUpdated", - dateUpdated.toInstant().toString() - ); + Serializer.toString(request, "DateUpdated", dateUpdated, ParameterType.URLENCODED); } + + if (attributes != null) { - request.addPostParam("Attributes", attributes); + Serializer.toString(request, "Attributes", attributes, ParameterType.URLENCODED); } + + if (roleSid != null) { - request.addPostParam("RoleSid", roleSid); + Serializer.toString(request, "RoleSid", roleSid, ParameterType.URLENCODED); } + + if (messagingBindingProxyAddress != null) { - request.addPostParam( - "MessagingBinding.ProxyAddress", - messagingBindingProxyAddress - ); + Serializer.toString(request, "MessagingBinding.ProxyAddress", messagingBindingProxyAddress, ParameterType.URLENCODED); } + + if (messagingBindingProjectedAddress != null) { - request.addPostParam( - "MessagingBinding.ProjectedAddress", - messagingBindingProjectedAddress - ); + Serializer.toString(request, "MessagingBinding.ProjectedAddress", messagingBindingProjectedAddress, ParameterType.URLENCODED); } + + if (identity != null) { - request.addPostParam("Identity", identity); + Serializer.toString(request, "Identity", identity, ParameterType.URLENCODED); } + + if (lastReadMessageIndex != null) { - request.addPostParam( - "LastReadMessageIndex", - lastReadMessageIndex.toString() - ); + Serializer.toString(request, "LastReadMessageIndex", lastReadMessageIndex, ParameterType.URLENCODED); } + + if (lastReadTimestamp != null) { - request.addPostParam("LastReadTimestamp", lastReadTimestamp); + Serializer.toString(request, "LastReadTimestamp", lastReadTimestamp, ParameterType.URLENCODED); } + + } private void addHeaderParams(final Request request) { + if (xTwilioWebhookEnabled != null) { - request.addHeaderParam( - "X-Twilio-Webhook-Enabled", - xTwilioWebhookEnabled.toString() - ); + Serializer.toString(request, "X-Twilio-Webhook-Enabled", xTwilioWebhookEnabled, ParameterType.HEADER); } + } } diff --git a/src/main/java/com/twilio/rest/conversations/v1/conversation/Webhook.java b/src/main/java/com/twilio/rest/conversations/v1/conversation/Webhook.java index 8bfea294d0..6f77d7af9e 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/conversation/Webhook.java +++ b/src/main/java/com/twilio/rest/conversations/v1/conversation/Webhook.java @@ -18,72 +18,113 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; -import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Webhook extends Resource { - private static final long serialVersionUID = 253771507397775L; - public static WebhookCreator creator( - final String pathConversationSid, - final Webhook.Target target - ) { - return new WebhookCreator(pathConversationSid, target); + public static WebhookCreator creator(final String pathconversationSid, final Webhook.Target target) { + return new WebhookCreator( + pathconversationSid, target + ); } - public static WebhookDeleter deleter( - final String pathConversationSid, - final String pathSid - ) { - return new WebhookDeleter(pathConversationSid, pathSid); + + public static WebhookDeleter deleter(final String pathconversationSid, final String pathsid) { + return new WebhookDeleter( + pathconversationSid, pathsid + ); } - public static WebhookFetcher fetcher( - final String pathConversationSid, - final String pathSid - ) { - return new WebhookFetcher(pathConversationSid, pathSid); + + public static WebhookFetcher fetcher(final String pathconversationSid, final String pathsid) { + return new WebhookFetcher( + pathconversationSid, pathsid + ); } - public static WebhookReader reader(final String pathConversationSid) { - return new WebhookReader(pathConversationSid); + + public static WebhookReader reader(final String pathconversationSid) { + return new WebhookReader( + pathconversationSid + ); } - public static WebhookUpdater updater( - final String pathConversationSid, - final String pathSid - ) { - return new WebhookUpdater(pathConversationSid, pathSid); + + public static WebhookUpdater updater(final String pathconversationSid, final String pathsid) { + return new WebhookUpdater( + pathconversationSid, pathsid + ); } + + public enum Target { + WEBHOOK("webhook"), + TRIGGER("trigger"), + STUDIO("studio"); + + private final String value; + + private Target(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static Target forValue(final String value) { + return Promoter.enumFromString(value, Target.values()); + } + } + + public enum Method { + GET("get"), + POST("post"); + + private final String value; + + private Method(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static Method forValue(final String value) { + return Promoter.enumFromString(value, Method.values()); + } + } + + /** * Converts a JSON String into a Webhook object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Webhook object represented by the provided JSON */ - public static Webhook fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Webhook fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Webhook.class); @@ -98,14 +139,11 @@ public static Webhook fromJson( * Converts a JSON InputStream into a Webhook object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Webhook object represented by the provided JSON */ - public static Webhook fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Webhook fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Webhook.class); @@ -116,66 +154,57 @@ public static Webhook fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; + @Getter + private final Object configuration; + @Getter private final String conversationSid; - private final String target; - private final URI url; - private final Map configuration; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; + @Getter + private final String sid; + @Getter + private final String target; + @Getter + private final URI url; @JsonCreator private Webhook( - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("conversation_sid") final String conversationSid, - @JsonProperty("target") final String target, - @JsonProperty("url") final URI url, - @JsonProperty("configuration") final Map configuration, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("configuration") final Object configuration, + @JsonProperty("conversation_sid") final String conversationSid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("sid") final String sid, + @JsonProperty("target") final String target, + @JsonProperty("url") final URI url ) { - this.sid = sid; this.accountSid = accountSid; + this.configuration = configuration; this.conversationSid = conversationSid; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; + this.sid = sid; this.target = target; this.url = url; - this.configuration = configuration; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); - } - - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getConversationSid() { - return this.conversationSid; - } - - public final String getTarget() { - return this.target; - } - - public final URI getUrl() { - return this.url; - } - - public final Map getConfiguration() { - return this.configuration; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; } @Override @@ -189,71 +218,32 @@ public boolean equals(final Object o) { } Webhook other = (Webhook) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(conversationSid, other.conversationSid) && - Objects.equals(target, other.target) && - Objects.equals(url, other.url) && - Objects.equals(configuration, other.configuration) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(configuration, other.configuration) && + Objects.equals(conversationSid, other.conversationSid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(sid, other.sid) && + Objects.equals(target, other.target) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - sid, - accountSid, - conversationSid, - target, - url, - configuration, - dateCreated, - dateUpdated + accountSid, + configuration, + conversationSid, + dateCreated, + dateUpdated, + sid, + target, + url ); } - public enum Target { - WEBHOOK("webhook"), - TRIGGER("trigger"), - STUDIO("studio"); - - private final String value; - private Target(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static Target forValue(final String value) { - return Promoter.enumFromString(value, Target.values()); - } - } - - public enum Method { - GET("get"), - POST("post"); - - private final String value; - - private Method(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static Method forValue(final String value) { - return Promoter.enumFromString(value, Method.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/conversations/v1/conversation/WebhookCreator.java b/src/main/java/com/twilio/rest/conversations/v1/conversation/WebhookCreator.java index 192ff3ce45..1f8cc0f6d5 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/conversation/WebhookCreator.java +++ b/src/main/java/com/twilio/rest/conversations/v1/conversation/WebhookCreator.java @@ -14,9 +14,12 @@ package com.twilio.rest.conversations.v1.conversation; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; import com.twilio.converter.Promoter; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,12 +28,12 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -import java.util.List; + import java.util.List; public class WebhookCreator extends Creator { - private String pathConversationSid; + private String pathconversationSid; private Webhook.Target target; private String configurationUrl; private Webhook.Method configurationMethod; @@ -39,108 +42,87 @@ public class WebhookCreator extends Creator { private String configurationFlowSid; private Integer configurationReplayAfter; - public WebhookCreator( - final String pathConversationSid, - final Webhook.Target target - ) { - this.pathConversationSid = pathConversationSid; + public WebhookCreator(final String pathconversationSid, final Webhook.Target target) { + this.pathconversationSid = pathconversationSid; this.target = target; } + public WebhookCreator setTarget(final Webhook.Target target) { this.target = target; return this; } + public WebhookCreator setConfigurationUrl(final String configurationUrl) { this.configurationUrl = configurationUrl; return this; } - public WebhookCreator setConfigurationMethod( - final Webhook.Method configurationMethod - ) { + + public WebhookCreator setConfigurationMethod(final Webhook.Method configurationMethod) { this.configurationMethod = configurationMethod; return this; } - public WebhookCreator setConfigurationFilters( - final List configurationFilters - ) { + + public WebhookCreator setConfigurationFilters(final List configurationFilters) { this.configurationFilters = configurationFilters; return this; } - public WebhookCreator setConfigurationFilters( - final String configurationFilters - ) { - return setConfigurationFilters( - Promoter.listOfOne(configurationFilters) - ); + public WebhookCreator setConfigurationFilters(final String configurationFilters) { + return setConfigurationFilters(Promoter.listOfOne(configurationFilters)); } - public WebhookCreator setConfigurationTriggers( - final List configurationTriggers - ) { + public WebhookCreator setConfigurationTriggers(final List configurationTriggers) { this.configurationTriggers = configurationTriggers; return this; } - public WebhookCreator setConfigurationTriggers( - final String configurationTriggers - ) { - return setConfigurationTriggers( - Promoter.listOfOne(configurationTriggers) - ); + public WebhookCreator setConfigurationTriggers(final String configurationTriggers) { + return setConfigurationTriggers(Promoter.listOfOne(configurationTriggers)); } - public WebhookCreator setConfigurationFlowSid( - final String configurationFlowSid - ) { + public WebhookCreator setConfigurationFlowSid(final String configurationFlowSid) { this.configurationFlowSid = configurationFlowSid; return this; } - public WebhookCreator setConfigurationReplayAfter( - final Integer configurationReplayAfter - ) { + + public WebhookCreator setConfigurationReplayAfter(final Integer configurationReplayAfter) { this.configurationReplayAfter = configurationReplayAfter; return this; } + @Override public Webhook create(final TwilioRestClient client) { + String path = "/v1/Conversations/{ConversationSid}/Webhooks"; - path = - path.replace( - "{" + "ConversationSid" + "}", - this.pathConversationSid.toString() - ); - path = path.replace("{" + "Target" + "}", this.target.toString()); + path = path.replace("{" + "ConversationSid" + "}", this.pathconversationSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.CONVERSATIONS.toString(), - path + HttpMethod.POST, + Domains.CONVERSATIONS.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Webhook creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("Webhook creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -149,36 +131,45 @@ public Webhook create(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (target != null) { - request.addPostParam("Target", target.toString()); + Serializer.toString(request, "Target", target, ParameterType.URLENCODED); } + + if (configurationUrl != null) { - request.addPostParam("Configuration.Url", configurationUrl); + Serializer.toString(request, "Configuration.Url", configurationUrl, ParameterType.URLENCODED); } + + if (configurationMethod != null) { - request.addPostParam( - "Configuration.Method", - configurationMethod.toString() - ); + Serializer.toString(request, "Configuration.Method", configurationMethod, ParameterType.URLENCODED); } + + if (configurationFilters != null) { - for (String prop : configurationFilters) { - request.addPostParam("Configuration.Filters", prop); + for (String param : configurationFilters) { + Serializer.toString(request, "Configuration.Filters", param, ParameterType.URLENCODED); } } + + if (configurationTriggers != null) { - for (String prop : configurationTriggers) { - request.addPostParam("Configuration.Triggers", prop); + for (String param : configurationTriggers) { + Serializer.toString(request, "Configuration.Triggers", param, ParameterType.URLENCODED); } } + + if (configurationFlowSid != null) { - request.addPostParam("Configuration.FlowSid", configurationFlowSid); + Serializer.toString(request, "Configuration.FlowSid", configurationFlowSid, ParameterType.URLENCODED); } + + if (configurationReplayAfter != null) { - request.addPostParam( - "Configuration.ReplayAfter", - configurationReplayAfter.toString() - ); + Serializer.toString(request, "Configuration.ReplayAfter", configurationReplayAfter, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/conversations/v1/conversation/WebhookDeleter.java b/src/main/java/com/twilio/rest/conversations/v1/conversation/WebhookDeleter.java index 1444664f8e..9f862428cd 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/conversation/WebhookDeleter.java +++ b/src/main/java/com/twilio/rest/conversations/v1/conversation/WebhookDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.conversations.v1.conversation; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,50 +26,41 @@ public class WebhookDeleter extends Deleter { - private String pathConversationSid; - private String pathSid; + private String pathconversationSid; + private String pathsid; - public WebhookDeleter( - final String pathConversationSid, - final String pathSid - ) { - this.pathConversationSid = pathConversationSid; - this.pathSid = pathSid; + public WebhookDeleter(final String pathconversationSid, final String pathsid) { + this.pathconversationSid = pathconversationSid; + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/v1/Conversations/{ConversationSid}/Webhooks/{Sid}"; - path = - path.replace( - "{" + "ConversationSid" + "}", - this.pathConversationSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "ConversationSid" + "}", this.pathconversationSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.CONVERSATIONS.toString(), - path + HttpMethod.DELETE, + Domains.CONVERSATIONS.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Webhook delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("Webhook delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/conversations/v1/conversation/WebhookFetcher.java b/src/main/java/com/twilio/rest/conversations/v1/conversation/WebhookFetcher.java index cabed9772f..0b14c9a59e 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/conversation/WebhookFetcher.java +++ b/src/main/java/com/twilio/rest/conversations/v1/conversation/WebhookFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.conversations.v1.conversation; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,54 +26,44 @@ public class WebhookFetcher extends Fetcher { - private String pathConversationSid; - private String pathSid; + private String pathconversationSid; + private String pathsid; - public WebhookFetcher( - final String pathConversationSid, - final String pathSid - ) { - this.pathConversationSid = pathConversationSid; - this.pathSid = pathSid; + public WebhookFetcher(final String pathconversationSid, final String pathsid) { + this.pathconversationSid = pathconversationSid; + this.pathsid = pathsid; } + @Override public Webhook fetch(final TwilioRestClient client) { + String path = "/v1/Conversations/{ConversationSid}/Webhooks/{Sid}"; - path = - path.replace( - "{" + "ConversationSid" + "}", - this.pathConversationSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "ConversationSid" + "}", this.pathconversationSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.CONVERSATIONS.toString(), - path + HttpMethod.GET, + Domains.CONVERSATIONS.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Webhook fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Webhook fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Webhook.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/conversations/v1/conversation/WebhookReader.java b/src/main/java/com/twilio/rest/conversations/v1/conversation/WebhookReader.java index bcc82472e5..be9c246039 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/conversation/WebhookReader.java +++ b/src/main/java/com/twilio/rest/conversations/v1/conversation/WebhookReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,115 +30,88 @@ public class WebhookReader extends Reader { - private String pathConversationSid; + private String pathconversationSid; private Long pageSize; - public WebhookReader(final String pathConversationSid) { - this.pathConversationSid = pathConversationSid; + public WebhookReader(final String pathconversationSid) { + this.pathconversationSid = pathconversationSid; } + public WebhookReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/Conversations/{ConversationSid}/Webhooks"; - path = - path.replace( - "{" + "ConversationSid" + "}", - this.pathConversationSid.toString() - ); + + path = path.replace("{" + "ConversationSid" + "}", this.pathconversationSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.CONVERSATIONS.toString(), - path + HttpMethod.GET, + Domains.CONVERSATIONS.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Webhook read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Webhook read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "webhooks", - response.getContent(), - Webhook.class, - client.getObjectMapper() - ); + "webhooks", + response.getContent(), + Webhook.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.CONVERSATIONS.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.CONVERSATIONS.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/conversations/v1/conversation/WebhookUpdater.java b/src/main/java/com/twilio/rest/conversations/v1/conversation/WebhookUpdater.java index aa90ff07ca..26fb712074 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/conversation/WebhookUpdater.java +++ b/src/main/java/com/twilio/rest/conversations/v1/conversation/WebhookUpdater.java @@ -16,7 +16,9 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; import com.twilio.converter.Promoter; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,108 +27,88 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.util.List; public class WebhookUpdater extends Updater { - - private String pathConversationSid; - private String pathSid; + private String pathconversationSid; + private String pathsid; private String configurationUrl; private Webhook.Method configurationMethod; private List configurationFilters; private List configurationTriggers; private String configurationFlowSid; - public WebhookUpdater( - final String pathConversationSid, - final String pathSid - ) { - this.pathConversationSid = pathConversationSid; - this.pathSid = pathSid; + public WebhookUpdater(final String pathconversationSid, final String pathsid) { + this.pathconversationSid = pathconversationSid; + this.pathsid = pathsid; } + public WebhookUpdater setConfigurationUrl(final String configurationUrl) { this.configurationUrl = configurationUrl; return this; } - public WebhookUpdater setConfigurationMethod( - final Webhook.Method configurationMethod - ) { + + public WebhookUpdater setConfigurationMethod(final Webhook.Method configurationMethod) { this.configurationMethod = configurationMethod; return this; } - public WebhookUpdater setConfigurationFilters( - final List configurationFilters - ) { + + public WebhookUpdater setConfigurationFilters(final List configurationFilters) { this.configurationFilters = configurationFilters; return this; } - public WebhookUpdater setConfigurationFilters( - final String configurationFilters - ) { - return setConfigurationFilters( - Promoter.listOfOne(configurationFilters) - ); + public WebhookUpdater setConfigurationFilters(final String configurationFilters) { + return setConfigurationFilters(Promoter.listOfOne(configurationFilters)); } - public WebhookUpdater setConfigurationTriggers( - final List configurationTriggers - ) { + public WebhookUpdater setConfigurationTriggers(final List configurationTriggers) { this.configurationTriggers = configurationTriggers; return this; } - public WebhookUpdater setConfigurationTriggers( - final String configurationTriggers - ) { - return setConfigurationTriggers( - Promoter.listOfOne(configurationTriggers) - ); + public WebhookUpdater setConfigurationTriggers(final String configurationTriggers) { + return setConfigurationTriggers(Promoter.listOfOne(configurationTriggers)); } - public WebhookUpdater setConfigurationFlowSid( - final String configurationFlowSid - ) { + public WebhookUpdater setConfigurationFlowSid(final String configurationFlowSid) { this.configurationFlowSid = configurationFlowSid; return this; } + @Override public Webhook update(final TwilioRestClient client) { + String path = "/v1/Conversations/{ConversationSid}/Webhooks/{Sid}"; - path = - path.replace( - "{" + "ConversationSid" + "}", - this.pathConversationSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "ConversationSid" + "}", this.pathconversationSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.CONVERSATIONS.toString(), - path + HttpMethod.POST, + Domains.CONVERSATIONS.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Webhook update failed: Unable to connect to server" - ); + throw new ApiConnectionException("Webhook update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -135,27 +117,35 @@ public Webhook update(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (configurationUrl != null) { - request.addPostParam("Configuration.Url", configurationUrl); + Serializer.toString(request, "Configuration.Url", configurationUrl, ParameterType.URLENCODED); } + + if (configurationMethod != null) { - request.addPostParam( - "Configuration.Method", - configurationMethod.toString() - ); + Serializer.toString(request, "Configuration.Method", configurationMethod, ParameterType.URLENCODED); } + + if (configurationFilters != null) { - for (String prop : configurationFilters) { - request.addPostParam("Configuration.Filters", prop); + for (String param : configurationFilters) { + Serializer.toString(request, "Configuration.Filters", param, ParameterType.URLENCODED); } } + + if (configurationTriggers != null) { - for (String prop : configurationTriggers) { - request.addPostParam("Configuration.Triggers", prop); + for (String param : configurationTriggers) { + Serializer.toString(request, "Configuration.Triggers", param, ParameterType.URLENCODED); } } + + if (configurationFlowSid != null) { - request.addPostParam("Configuration.FlowSid", configurationFlowSid); + Serializer.toString(request, "Configuration.FlowSid", configurationFlowSid, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/conversations/v1/conversation/message/DeliveryReceipt.java b/src/main/java/com/twilio/rest/conversations/v1/conversation/message/DeliveryReceipt.java index 5e5098d0a9..9bc23b80a3 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/conversation/message/DeliveryReceipt.java +++ b/src/main/java/com/twilio/rest/conversations/v1/conversation/message/DeliveryReceipt.java @@ -18,57 +18,74 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class DeliveryReceipt extends Resource { - private static final long serialVersionUID = 126608153820635L; - public static DeliveryReceiptFetcher fetcher( - final String pathConversationSid, - final String pathMessageSid, - final String pathSid - ) { + public static DeliveryReceiptFetcher fetcher(final String pathconversationSid, final String pathmessageSid, final String pathsid) { return new DeliveryReceiptFetcher( - pathConversationSid, - pathMessageSid, - pathSid + pathconversationSid, pathmessageSid, pathsid ); } - public static DeliveryReceiptReader reader( - final String pathConversationSid, - final String pathMessageSid - ) { - return new DeliveryReceiptReader(pathConversationSid, pathMessageSid); + + public static DeliveryReceiptReader reader(final String pathconversationSid, final String pathmessageSid) { + return new DeliveryReceiptReader( + pathconversationSid, pathmessageSid + ); } + + public enum DeliveryStatus { + READ("read"), + FAILED("failed"), + DELIVERED("delivered"), + UNDELIVERED("undelivered"), + SENT("sent"); + + private final String value; + + private DeliveryStatus(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static DeliveryStatus forValue(final String value) { + return Promoter.enumFromString(value, DeliveryStatus.values()); + } + } + + /** * Converts a JSON String into a DeliveryReceipt object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return DeliveryReceipt object represented by the provided JSON */ - public static DeliveryReceipt fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static DeliveryReceipt fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, DeliveryReceipt.class); @@ -83,14 +100,11 @@ public static DeliveryReceipt fromJson( * Converts a JSON InputStream into a DeliveryReceipt object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return DeliveryReceipt object represented by the provided JSON */ - public static DeliveryReceipt fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static DeliveryReceipt fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, DeliveryReceipt.class); @@ -101,89 +115,71 @@ public static DeliveryReceipt fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; + @Getter + private final String channelMessageSid; + @Getter private final String conversationSid; - private final String sid; + @Getter + private final ZonedDateTime dateCreated; + @Getter + private final ZonedDateTime dateUpdated; + @Getter + private final Integer errorCode; + @Getter private final String messageSid; - private final String channelMessageSid; + @Getter private final String participantSid; + @Getter + private final String sid; + @Getter private final DeliveryReceipt.DeliveryStatus status; - private final Integer errorCode; - private final ZonedDateTime dateCreated; - private final ZonedDateTime dateUpdated; + @Getter private final URI url; @JsonCreator private DeliveryReceipt( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("conversation_sid") final String conversationSid, - @JsonProperty("sid") final String sid, - @JsonProperty("message_sid") final String messageSid, - @JsonProperty("channel_message_sid") final String channelMessageSid, - @JsonProperty("participant_sid") final String participantSid, - @JsonProperty("status") final DeliveryReceipt.DeliveryStatus status, - @JsonProperty("error_code") final Integer errorCode, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("url") final URI url + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("channel_message_sid") final String channelMessageSid, + @JsonProperty("conversation_sid") final String conversationSid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("error_code") final Integer errorCode, + @JsonProperty("message_sid") final String messageSid, + @JsonProperty("participant_sid") final String participantSid, + @JsonProperty("sid") final String sid, + @JsonProperty("status") final DeliveryReceipt.DeliveryStatus status, + @JsonProperty("url") final URI url ) { this.accountSid = accountSid; + this.channelMessageSid = channelMessageSid; this.conversationSid = conversationSid; - this.sid = sid; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; + this.errorCode = errorCode; this.messageSid = messageSid; - this.channelMessageSid = channelMessageSid; this.participantSid = participantSid; + this.sid = sid; this.status = status; - this.errorCode = errorCode; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); this.url = url; } - public final String getAccountSid() { - return this.accountSid; - } - - public final String getConversationSid() { - return this.conversationSid; - } - - public final String getSid() { - return this.sid; - } - - public final String getMessageSid() { - return this.messageSid; - } - - public final String getChannelMessageSid() { - return this.channelMessageSid; - } - - public final String getParticipantSid() { - return this.participantSid; - } - - public final DeliveryReceipt.DeliveryStatus getStatus() { - return this.status; - } - - public final Integer getErrorCode() { - return this.errorCode; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final URI getUrl() { - return this.url; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -195,59 +191,38 @@ public boolean equals(final Object o) { } DeliveryReceipt other = (DeliveryReceipt) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(conversationSid, other.conversationSid) && - Objects.equals(sid, other.sid) && - Objects.equals(messageSid, other.messageSid) && - Objects.equals(channelMessageSid, other.channelMessageSid) && - Objects.equals(participantSid, other.participantSid) && - Objects.equals(status, other.status) && - Objects.equals(errorCode, other.errorCode) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(url, other.url) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(channelMessageSid, other.channelMessageSid) && + Objects.equals(conversationSid, other.conversationSid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(errorCode, other.errorCode) && + Objects.equals(messageSid, other.messageSid) && + Objects.equals(participantSid, other.participantSid) && + Objects.equals(sid, other.sid) && + Objects.equals(status, other.status) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - accountSid, - conversationSid, - sid, - messageSid, - channelMessageSid, - participantSid, - status, - errorCode, - dateCreated, - dateUpdated, - url + accountSid, + channelMessageSid, + conversationSid, + dateCreated, + dateUpdated, + errorCode, + messageSid, + participantSid, + sid, + status, + url ); } - public enum DeliveryStatus { - READ("read"), - FAILED("failed"), - DELIVERED("delivered"), - UNDELIVERED("undelivered"), - SENT("sent"); - - private final String value; - - private DeliveryStatus(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - @JsonCreator - public static DeliveryStatus forValue(final String value) { - return Promoter.enumFromString(value, DeliveryStatus.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/conversations/v1/conversation/message/DeliveryReceiptFetcher.java b/src/main/java/com/twilio/rest/conversations/v1/conversation/message/DeliveryReceiptFetcher.java index 2dc1bc968d..e993bf5042 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/conversation/message/DeliveryReceiptFetcher.java +++ b/src/main/java/com/twilio/rest/conversations/v1/conversation/message/DeliveryReceiptFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.conversations.v1.conversation.message; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,66 +26,47 @@ public class DeliveryReceiptFetcher extends Fetcher { - private String pathConversationSid; - private String pathMessageSid; - private String pathSid; + private String pathconversationSid; + private String pathmessageSid; + private String pathsid; - public DeliveryReceiptFetcher( - final String pathConversationSid, - final String pathMessageSid, - final String pathSid - ) { - this.pathConversationSid = pathConversationSid; - this.pathMessageSid = pathMessageSid; - this.pathSid = pathSid; + public DeliveryReceiptFetcher(final String pathconversationSid, final String pathmessageSid, final String pathsid) { + this.pathconversationSid = pathconversationSid; + this.pathmessageSid = pathmessageSid; + this.pathsid = pathsid; } + @Override public DeliveryReceipt fetch(final TwilioRestClient client) { - String path = - "/v1/Conversations/{ConversationSid}/Messages/{MessageSid}/Receipts/{Sid}"; - path = - path.replace( - "{" + "ConversationSid" + "}", - this.pathConversationSid.toString() - ); - path = - path.replace( - "{" + "MessageSid" + "}", - this.pathMessageSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/v1/Conversations/{ConversationSid}/Messages/{MessageSid}/Receipts/{Sid}"; + + path = path.replace("{" + "ConversationSid" + "}", this.pathconversationSid.toString()); + path = path.replace("{" + "MessageSid" + "}", this.pathmessageSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.CONVERSATIONS.toString(), - path + HttpMethod.GET, + Domains.CONVERSATIONS.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "DeliveryReceipt fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("DeliveryReceipt fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return DeliveryReceipt.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return DeliveryReceipt.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/conversations/v1/conversation/message/DeliveryReceiptReader.java b/src/main/java/com/twilio/rest/conversations/v1/conversation/message/DeliveryReceiptReader.java index 8fb48d1af6..34d2780407 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/conversation/message/DeliveryReceiptReader.java +++ b/src/main/java/com/twilio/rest/conversations/v1/conversation/message/DeliveryReceiptReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,126 +30,91 @@ public class DeliveryReceiptReader extends Reader { - private String pathConversationSid; - private String pathMessageSid; + private String pathconversationSid; + private String pathmessageSid; private Long pageSize; - public DeliveryReceiptReader( - final String pathConversationSid, - final String pathMessageSid - ) { - this.pathConversationSid = pathConversationSid; - this.pathMessageSid = pathMessageSid; + public DeliveryReceiptReader(final String pathconversationSid, final String pathmessageSid) { + this.pathconversationSid = pathconversationSid; + this.pathmessageSid = pathmessageSid; } + public DeliveryReceiptReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { - String path = - "/v1/Conversations/{ConversationSid}/Messages/{MessageSid}/Receipts"; - path = - path.replace( - "{" + "ConversationSid" + "}", - this.pathConversationSid.toString() - ); - path = - path.replace( - "{" + "MessageSid" + "}", - this.pathMessageSid.toString() - ); + + String path = "/v1/Conversations/{ConversationSid}/Messages/{MessageSid}/Receipts"; + + path = path.replace("{" + "ConversationSid" + "}", this.pathconversationSid.toString()); + path = path.replace("{" + "MessageSid" + "}", this.pathmessageSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.CONVERSATIONS.toString(), - path + HttpMethod.GET, + Domains.CONVERSATIONS.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "DeliveryReceipt read failed: Unable to connect to server" - ); + throw new ApiConnectionException("DeliveryReceipt read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "delivery_receipts", - response.getContent(), - DeliveryReceipt.class, - client.getObjectMapper() - ); + "delivery_receipts", + response.getContent(), + DeliveryReceipt.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.CONVERSATIONS.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.CONVERSATIONS.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/conversations/v1/service/Binding.java b/src/main/java/com/twilio/rest/conversations/v1/service/Binding.java index 0c10c7165f..2de5b83b62 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/service/Binding.java +++ b/src/main/java/com/twilio/rest/conversations/v1/service/Binding.java @@ -18,57 +18,80 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.List; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Binding extends Resource { - private static final long serialVersionUID = 124400281339927L; - public static BindingDeleter deleter( - final String pathChatServiceSid, - final String pathSid - ) { - return new BindingDeleter(pathChatServiceSid, pathSid); + public static BindingDeleter deleter(final String pathchatServiceSid, final String pathsid) { + return new BindingDeleter( + pathchatServiceSid, pathsid + ); } - public static BindingFetcher fetcher( - final String pathChatServiceSid, - final String pathSid - ) { - return new BindingFetcher(pathChatServiceSid, pathSid); + + public static BindingFetcher fetcher(final String pathchatServiceSid, final String pathsid) { + return new BindingFetcher( + pathchatServiceSid, pathsid + ); + } + + + public static BindingReader reader(final String pathchatServiceSid) { + return new BindingReader( + pathchatServiceSid + ); } - public static BindingReader reader(final String pathChatServiceSid) { - return new BindingReader(pathChatServiceSid); + + public enum BindingType { + APN("apn"), + GCM("gcm"), + FCM("fcm"); + + private final String value; + + private BindingType(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static BindingType forValue(final String value) { + return Promoter.enumFromString(value, BindingType.values()); + } } + /** * Converts a JSON String into a Binding object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Binding object represented by the provided JSON */ - public static Binding fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Binding fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Binding.class); @@ -83,14 +106,11 @@ public static Binding fromJson( * Converts a JSON InputStream into a Binding object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Binding object represented by the provided JSON */ - public static Binding fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Binding fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Binding.class); @@ -101,89 +121,71 @@ public static Binding fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; + @Getter + private final Binding.BindingType bindingType; + @Getter private final String chatServiceSid; + @Getter private final String credentialSid; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; + @Getter private final String endpoint; + @Getter private final String identity; - private final Binding.BindingType bindingType; + @Getter private final List messageTypes; + @Getter + private final String sid; + @Getter private final URI url; @JsonCreator private Binding( - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("chat_service_sid") final String chatServiceSid, - @JsonProperty("credential_sid") final String credentialSid, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("endpoint") final String endpoint, - @JsonProperty("identity") final String identity, - @JsonProperty("binding_type") final Binding.BindingType bindingType, - @JsonProperty("message_types") final List messageTypes, - @JsonProperty("url") final URI url + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("binding_type") final Binding.BindingType bindingType, + @JsonProperty("chat_service_sid") final String chatServiceSid, + @JsonProperty("credential_sid") final String credentialSid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("endpoint") final String endpoint, + @JsonProperty("identity") final String identity, + @JsonProperty("message_types") final List messageTypes, + @JsonProperty("sid") final String sid, + @JsonProperty("url") final URI url ) { - this.sid = sid; this.accountSid = accountSid; + this.bindingType = bindingType; this.chatServiceSid = chatServiceSid; this.credentialSid = credentialSid; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.endpoint = endpoint; this.identity = identity; - this.bindingType = bindingType; this.messageTypes = messageTypes; + this.sid = sid; this.url = url; } - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getChatServiceSid() { - return this.chatServiceSid; - } - - public final String getCredentialSid() { - return this.credentialSid; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final String getEndpoint() { - return this.endpoint; - } - - public final String getIdentity() { - return this.identity; - } - - public final Binding.BindingType getBindingType() { - return this.bindingType; - } - - public final List getMessageTypes() { - return this.messageTypes; - } - - public final URI getUrl() { - return this.url; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -195,57 +197,38 @@ public boolean equals(final Object o) { } Binding other = (Binding) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(chatServiceSid, other.chatServiceSid) && - Objects.equals(credentialSid, other.credentialSid) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(endpoint, other.endpoint) && - Objects.equals(identity, other.identity) && - Objects.equals(bindingType, other.bindingType) && - Objects.equals(messageTypes, other.messageTypes) && - Objects.equals(url, other.url) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(bindingType, other.bindingType) && + Objects.equals(chatServiceSid, other.chatServiceSid) && + Objects.equals(credentialSid, other.credentialSid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(endpoint, other.endpoint) && + Objects.equals(identity, other.identity) && + Objects.equals(messageTypes, other.messageTypes) && + Objects.equals(sid, other.sid) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - sid, - accountSid, - chatServiceSid, - credentialSid, - dateCreated, - dateUpdated, - endpoint, - identity, - bindingType, - messageTypes, - url + accountSid, + bindingType, + chatServiceSid, + credentialSid, + dateCreated, + dateUpdated, + endpoint, + identity, + messageTypes, + sid, + url ); } - public enum BindingType { - APN("apn"), - GCM("gcm"), - FCM("fcm"); - - private final String value; - - private BindingType(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - @JsonCreator - public static BindingType forValue(final String value) { - return Promoter.enumFromString(value, BindingType.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/conversations/v1/service/BindingDeleter.java b/src/main/java/com/twilio/rest/conversations/v1/service/BindingDeleter.java index 199d79e52b..6bd9cd5d74 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/service/BindingDeleter.java +++ b/src/main/java/com/twilio/rest/conversations/v1/service/BindingDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.conversations.v1.service; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,50 +26,41 @@ public class BindingDeleter extends Deleter { - private String pathChatServiceSid; - private String pathSid; + private String pathchatServiceSid; + private String pathsid; - public BindingDeleter( - final String pathChatServiceSid, - final String pathSid - ) { - this.pathChatServiceSid = pathChatServiceSid; - this.pathSid = pathSid; + public BindingDeleter(final String pathchatServiceSid, final String pathsid) { + this.pathchatServiceSid = pathchatServiceSid; + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/v1/Services/{ChatServiceSid}/Bindings/{Sid}"; - path = - path.replace( - "{" + "ChatServiceSid" + "}", - this.pathChatServiceSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "ChatServiceSid" + "}", this.pathchatServiceSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.CONVERSATIONS.toString(), - path + HttpMethod.DELETE, + Domains.CONVERSATIONS.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Binding delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("Binding delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/conversations/v1/service/BindingFetcher.java b/src/main/java/com/twilio/rest/conversations/v1/service/BindingFetcher.java index 813b058d4f..7397ff5413 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/service/BindingFetcher.java +++ b/src/main/java/com/twilio/rest/conversations/v1/service/BindingFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.conversations.v1.service; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,54 +26,44 @@ public class BindingFetcher extends Fetcher { - private String pathChatServiceSid; - private String pathSid; + private String pathchatServiceSid; + private String pathsid; - public BindingFetcher( - final String pathChatServiceSid, - final String pathSid - ) { - this.pathChatServiceSid = pathChatServiceSid; - this.pathSid = pathSid; + public BindingFetcher(final String pathchatServiceSid, final String pathsid) { + this.pathchatServiceSid = pathchatServiceSid; + this.pathsid = pathsid; } + @Override public Binding fetch(final TwilioRestClient client) { + String path = "/v1/Services/{ChatServiceSid}/Bindings/{Sid}"; - path = - path.replace( - "{" + "ChatServiceSid" + "}", - this.pathChatServiceSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "ChatServiceSid" + "}", this.pathchatServiceSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.CONVERSATIONS.toString(), - path + HttpMethod.GET, + Domains.CONVERSATIONS.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Binding fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Binding fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Binding.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/conversations/v1/service/BindingReader.java b/src/main/java/com/twilio/rest/conversations/v1/service/BindingReader.java index a815377a47..5fa47d1e53 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/service/BindingReader.java +++ b/src/main/java/com/twilio/rest/conversations/v1/service/BindingReader.java @@ -17,8 +17,9 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; import com.twilio.converter.Promoter; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,22 +28,22 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.util.List; public class BindingReader extends Reader { - private String pathChatServiceSid; + private String pathchatServiceSid; private List bindingType; private List identity; private Long pageSize; - public BindingReader(final String pathChatServiceSid) { - this.pathChatServiceSid = pathChatServiceSid; + public BindingReader(final String pathchatServiceSid) { + this.pathchatServiceSid = pathchatServiceSid; } - public BindingReader setBindingType( - final List bindingType - ) { + + public BindingReader setBindingType(final List bindingType) { this.bindingType = bindingType; return this; } @@ -65,113 +66,89 @@ public BindingReader setPageSize(final Long pageSize) { return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/Services/{ChatServiceSid}/Bindings"; - path = - path.replace( - "{" + "ChatServiceSid" + "}", - this.pathChatServiceSid.toString() - ); + + path = path.replace("{" + "ChatServiceSid" + "}", this.pathchatServiceSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.CONVERSATIONS.toString(), - path + HttpMethod.GET, + Domains.CONVERSATIONS.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Binding read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Binding read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "bindings", - response.getContent(), - Binding.class, - client.getObjectMapper() - ); + "bindings", + response.getContent(), + Binding.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.CONVERSATIONS.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.CONVERSATIONS.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (bindingType != null) { - for (Binding.BindingType prop : bindingType) { - request.addQueryParam("BindingType", prop.toString()); + for (Binding.BindingType param : bindingType) { + Serializer.toString(request, "BindingType", param, ParameterType.QUERY); } } + + if (identity != null) { - for (String prop : identity) { - request.addQueryParam("Identity", prop); + for (String param : identity) { + Serializer.toString(request, "Identity", param, ParameterType.QUERY); } } + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/conversations/v1/service/Configuration.java b/src/main/java/com/twilio/rest/conversations/v1/service/Configuration.java index 9e686dae32..90cc1db376 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/service/Configuration.java +++ b/src/main/java/com/twilio/rest/conversations/v1/service/Configuration.java @@ -18,49 +18,48 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Configuration extends Resource { - private static final long serialVersionUID = 35465460450497L; - public static ConfigurationFetcher fetcher( - final String pathChatServiceSid - ) { - return new ConfigurationFetcher(pathChatServiceSid); + public static ConfigurationFetcher fetcher(final String pathchatServiceSid) { + return new ConfigurationFetcher( + pathchatServiceSid + ); } - public static ConfigurationUpdater updater( - final String pathChatServiceSid - ) { - return new ConfigurationUpdater(pathChatServiceSid); + + public static ConfigurationUpdater updater(final String pathchatServiceSid) { + return new ConfigurationUpdater( + pathchatServiceSid + ); } + /** * Converts a JSON String into a Configuration object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Configuration object represented by the provided JSON */ - public static Configuration fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Configuration fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Configuration.class); @@ -75,14 +74,11 @@ public static Configuration fromJson( * Converts a JSON InputStream into a Configuration object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Configuration object represented by the provided JSON */ - public static Configuration fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Configuration fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Configuration.class); @@ -93,66 +89,51 @@ public static Configuration fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String chatServiceSid; + @Getter + private final String defaultChatServiceRoleSid; + @Getter private final String defaultConversationCreatorRoleSid; + @Getter private final String defaultConversationRoleSid; - private final String defaultChatServiceRoleSid; - private final URI url; + @Getter private final Map links; + @Getter private final Boolean reachabilityEnabled; + @Getter + private final URI url; @JsonCreator private Configuration( - @JsonProperty("chat_service_sid") final String chatServiceSid, - @JsonProperty( - "default_conversation_creator_role_sid" - ) final String defaultConversationCreatorRoleSid, - @JsonProperty( - "default_conversation_role_sid" - ) final String defaultConversationRoleSid, - @JsonProperty( - "default_chat_service_role_sid" - ) final String defaultChatServiceRoleSid, - @JsonProperty("url") final URI url, - @JsonProperty("links") final Map links, - @JsonProperty("reachability_enabled") final Boolean reachabilityEnabled + @JsonProperty("chat_service_sid") final String chatServiceSid, + @JsonProperty("default_chat_service_role_sid") final String defaultChatServiceRoleSid, + @JsonProperty("default_conversation_creator_role_sid") final String defaultConversationCreatorRoleSid, + @JsonProperty("default_conversation_role_sid") final String defaultConversationRoleSid, + @JsonProperty("links") final Map links, + @JsonProperty("reachability_enabled") final Boolean reachabilityEnabled, + @JsonProperty("url") final URI url ) { this.chatServiceSid = chatServiceSid; - this.defaultConversationCreatorRoleSid = - defaultConversationCreatorRoleSid; - this.defaultConversationRoleSid = defaultConversationRoleSid; this.defaultChatServiceRoleSid = defaultChatServiceRoleSid; - this.url = url; + this.defaultConversationCreatorRoleSid = defaultConversationCreatorRoleSid; + this.defaultConversationRoleSid = defaultConversationRoleSid; this.links = links; this.reachabilityEnabled = reachabilityEnabled; - } - - public final String getChatServiceSid() { - return this.chatServiceSid; - } - - public final String getDefaultConversationCreatorRoleSid() { - return this.defaultConversationCreatorRoleSid; - } - - public final String getDefaultConversationRoleSid() { - return this.defaultConversationRoleSid; - } - - public final String getDefaultChatServiceRoleSid() { - return this.defaultChatServiceRoleSid; - } - - public final URI getUrl() { - return this.url; - } - - public final Map getLinks() { - return this.links; - } - - public final Boolean getReachabilityEnabled() { - return this.reachabilityEnabled; + this.url = url; } @Override @@ -166,37 +147,30 @@ public boolean equals(final Object o) { } Configuration other = (Configuration) o; - return ( - Objects.equals(chatServiceSid, other.chatServiceSid) && - Objects.equals( - defaultConversationCreatorRoleSid, - other.defaultConversationCreatorRoleSid - ) && - Objects.equals( - defaultConversationRoleSid, - other.defaultConversationRoleSid - ) && - Objects.equals( - defaultChatServiceRoleSid, - other.defaultChatServiceRoleSid - ) && - Objects.equals(url, other.url) && - Objects.equals(links, other.links) && - Objects.equals(reachabilityEnabled, other.reachabilityEnabled) + Objects.equals(chatServiceSid, other.chatServiceSid) && + Objects.equals(defaultChatServiceRoleSid, other.defaultChatServiceRoleSid) && + Objects.equals(defaultConversationCreatorRoleSid, other.defaultConversationCreatorRoleSid) && + Objects.equals(defaultConversationRoleSid, other.defaultConversationRoleSid) && + Objects.equals(links, other.links) && + Objects.equals(reachabilityEnabled, other.reachabilityEnabled) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - chatServiceSid, - defaultConversationCreatorRoleSid, - defaultConversationRoleSid, - defaultChatServiceRoleSid, - url, - links, - reachabilityEnabled + chatServiceSid, + defaultChatServiceRoleSid, + defaultConversationCreatorRoleSid, + defaultConversationRoleSid, + links, + reachabilityEnabled, + url ); } + + } + diff --git a/src/main/java/com/twilio/rest/conversations/v1/service/ConfigurationFetcher.java b/src/main/java/com/twilio/rest/conversations/v1/service/ConfigurationFetcher.java index 78318cdcf7..0b166543cd 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/service/ConfigurationFetcher.java +++ b/src/main/java/com/twilio/rest/conversations/v1/service/ConfigurationFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.conversations.v1.service; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,51 +26,41 @@ public class ConfigurationFetcher extends Fetcher { - private String pathChatServiceSid; + private String pathchatServiceSid; - public ConfigurationFetcher(final String pathChatServiceSid) { - this.pathChatServiceSid = pathChatServiceSid; + public ConfigurationFetcher(final String pathchatServiceSid) { + this.pathchatServiceSid = pathchatServiceSid; } + @Override public Configuration fetch(final TwilioRestClient client) { + String path = "/v1/Services/{ChatServiceSid}/Configuration"; - path = - path.replace( - "{" + "ChatServiceSid" + "}", - this.pathChatServiceSid.toString() - ); + path = path.replace("{" + "ChatServiceSid" + "}", this.pathchatServiceSid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.CONVERSATIONS.toString(), - path + HttpMethod.GET, + Domains.CONVERSATIONS.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Configuration fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Configuration fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return Configuration.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Configuration.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/conversations/v1/service/ConfigurationUpdater.java b/src/main/java/com/twilio/rest/conversations/v1/service/ConfigurationUpdater.java index db0565c16b..90435af460 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/service/ConfigurationUpdater.java +++ b/src/main/java/com/twilio/rest/conversations/v1/service/ConfigurationUpdater.java @@ -16,6 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -26,112 +28,96 @@ import com.twilio.rest.Domains; public class ConfigurationUpdater extends Updater { - - private String pathChatServiceSid; + private String pathchatServiceSid; private String defaultConversationCreatorRoleSid; private String defaultConversationRoleSid; private String defaultChatServiceRoleSid; private Boolean reachabilityEnabled; - public ConfigurationUpdater(final String pathChatServiceSid) { - this.pathChatServiceSid = pathChatServiceSid; + public ConfigurationUpdater(final String pathchatServiceSid) { + this.pathchatServiceSid = pathchatServiceSid; } - public ConfigurationUpdater setDefaultConversationCreatorRoleSid( - final String defaultConversationCreatorRoleSid - ) { - this.defaultConversationCreatorRoleSid = - defaultConversationCreatorRoleSid; + + public ConfigurationUpdater setDefaultConversationCreatorRoleSid(final String defaultConversationCreatorRoleSid) { + this.defaultConversationCreatorRoleSid = defaultConversationCreatorRoleSid; return this; } - public ConfigurationUpdater setDefaultConversationRoleSid( - final String defaultConversationRoleSid - ) { + + public ConfigurationUpdater setDefaultConversationRoleSid(final String defaultConversationRoleSid) { this.defaultConversationRoleSid = defaultConversationRoleSid; return this; } - public ConfigurationUpdater setDefaultChatServiceRoleSid( - final String defaultChatServiceRoleSid - ) { + + public ConfigurationUpdater setDefaultChatServiceRoleSid(final String defaultChatServiceRoleSid) { this.defaultChatServiceRoleSid = defaultChatServiceRoleSid; return this; } - public ConfigurationUpdater setReachabilityEnabled( - final Boolean reachabilityEnabled - ) { + + public ConfigurationUpdater setReachabilityEnabled(final Boolean reachabilityEnabled) { this.reachabilityEnabled = reachabilityEnabled; return this; } + @Override public Configuration update(final TwilioRestClient client) { + String path = "/v1/Services/{ChatServiceSid}/Configuration"; - path = - path.replace( - "{" + "ChatServiceSid" + "}", - this.pathChatServiceSid.toString() - ); + path = path.replace("{" + "ChatServiceSid" + "}", this.pathchatServiceSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.CONVERSATIONS.toString(), - path + HttpMethod.POST, + Domains.CONVERSATIONS.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Configuration update failed: Unable to connect to server" - ); + throw new ApiConnectionException("Configuration update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Configuration.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Configuration.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (defaultConversationCreatorRoleSid != null) { - request.addPostParam( - "DefaultConversationCreatorRoleSid", - defaultConversationCreatorRoleSid - ); + Serializer.toString(request, "DefaultConversationCreatorRoleSid", defaultConversationCreatorRoleSid, ParameterType.URLENCODED); } + + if (defaultConversationRoleSid != null) { - request.addPostParam( - "DefaultConversationRoleSid", - defaultConversationRoleSid - ); + Serializer.toString(request, "DefaultConversationRoleSid", defaultConversationRoleSid, ParameterType.URLENCODED); } + + if (defaultChatServiceRoleSid != null) { - request.addPostParam( - "DefaultChatServiceRoleSid", - defaultChatServiceRoleSid - ); + Serializer.toString(request, "DefaultChatServiceRoleSid", defaultChatServiceRoleSid, ParameterType.URLENCODED); } + + if (reachabilityEnabled != null) { - request.addPostParam( - "ReachabilityEnabled", - reachabilityEnabled.toString() - ); + Serializer.toString(request, "ReachabilityEnabled", reachabilityEnabled, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/conversations/v1/service/Conversation.java b/src/main/java/com/twilio/rest/conversations/v1/service/Conversation.java index 181767e7e6..b8af7a7682 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/service/Conversation.java +++ b/src/main/java/com/twilio/rest/conversations/v1/service/Conversation.java @@ -18,69 +18,114 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Conversation extends Resource { - private static final long serialVersionUID = 208929192266810L; - public static ConversationCreator creator(final String pathChatServiceSid) { - return new ConversationCreator(pathChatServiceSid); + public static ConversationCreator creator(final String pathchatServiceSid) { + return new ConversationCreator( + pathchatServiceSid + ); } - public static ConversationDeleter deleter( - final String pathChatServiceSid, - final String pathSid - ) { - return new ConversationDeleter(pathChatServiceSid, pathSid); + + public static ConversationDeleter deleter(final String pathchatServiceSid, final String pathsid) { + return new ConversationDeleter( + pathchatServiceSid, pathsid + ); } - public static ConversationFetcher fetcher( - final String pathChatServiceSid, - final String pathSid - ) { - return new ConversationFetcher(pathChatServiceSid, pathSid); + + public static ConversationFetcher fetcher(final String pathchatServiceSid, final String pathsid) { + return new ConversationFetcher( + pathchatServiceSid, pathsid + ); } - public static ConversationReader reader(final String pathChatServiceSid) { - return new ConversationReader(pathChatServiceSid); + + public static ConversationReader reader(final String pathchatServiceSid) { + return new ConversationReader( + pathchatServiceSid + ); } - public static ConversationUpdater updater( - final String pathChatServiceSid, - final String pathSid - ) { - return new ConversationUpdater(pathChatServiceSid, pathSid); + + public static ConversationUpdater updater(final String pathchatServiceSid, final String pathsid) { + return new ConversationUpdater( + pathchatServiceSid, pathsid + ); } + + public enum WebhookEnabledType { + TRUE("true"), + FALSE("false"); + + private final String value; + + private WebhookEnabledType(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static WebhookEnabledType forValue(final String value) { + return Promoter.enumFromString(value, WebhookEnabledType.values()); + } + } + + public enum State { + INACTIVE("inactive"), + ACTIVE("active"), + CLOSED("closed"); + + private final String value; + + private State(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static State forValue(final String value) { + return Promoter.enumFromString(value, State.values()); + } + } + + /** * Converts a JSON String into a Conversation object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Conversation object represented by the provided JSON */ - public static Conversation fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Conversation fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Conversation.class); @@ -95,14 +140,11 @@ public static Conversation fromJson( * Converts a JSON InputStream into a Conversation object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Conversation object represented by the provided JSON */ - public static Conversation fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Conversation fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Conversation.class); @@ -113,108 +155,81 @@ public static Conversation fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; + @Getter + private final String attributes; + @Getter + private final Object bindings; + @Getter private final String chatServiceSid; + @Getter + private final ZonedDateTime dateCreated; + @Getter + private final ZonedDateTime dateUpdated; + @Getter + private final String friendlyName; + @Getter + private final Map links; + @Getter private final String messagingServiceSid; + @Getter private final String sid; - private final String friendlyName; - private final String uniqueName; - private final String attributes; + @Getter private final Conversation.State state; - private final ZonedDateTime dateCreated; - private final ZonedDateTime dateUpdated; - private final Map timers; + @Getter + private final Object timers; + @Getter + private final String uniqueName; + @Getter private final URI url; - private final Map links; - private final Map bindings; @JsonCreator private Conversation( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("chat_service_sid") final String chatServiceSid, - @JsonProperty("messaging_service_sid") final String messagingServiceSid, - @JsonProperty("sid") final String sid, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("unique_name") final String uniqueName, - @JsonProperty("attributes") final String attributes, - @JsonProperty("state") final Conversation.State state, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("timers") final Map timers, - @JsonProperty("url") final URI url, - @JsonProperty("links") final Map links, - @JsonProperty("bindings") final Map bindings + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("attributes") final String attributes, + @JsonProperty("bindings") final Object bindings, + @JsonProperty("chat_service_sid") final String chatServiceSid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("links") final Map links, + @JsonProperty("messaging_service_sid") final String messagingServiceSid, + @JsonProperty("sid") final String sid, + @JsonProperty("state") final Conversation.State state, + @JsonProperty("timers") final Object timers, + @JsonProperty("unique_name") final String uniqueName, + @JsonProperty("url") final URI url ) { this.accountSid = accountSid; + this.attributes = attributes; + this.bindings = bindings; this.chatServiceSid = chatServiceSid; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; + this.friendlyName = friendlyName; + this.links = links; this.messagingServiceSid = messagingServiceSid; this.sid = sid; - this.friendlyName = friendlyName; - this.uniqueName = uniqueName; - this.attributes = attributes; this.state = state; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); this.timers = timers; + this.uniqueName = uniqueName; this.url = url; - this.links = links; - this.bindings = bindings; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getChatServiceSid() { - return this.chatServiceSid; - } - - public final String getMessagingServiceSid() { - return this.messagingServiceSid; - } - - public final String getSid() { - return this.sid; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final String getUniqueName() { - return this.uniqueName; - } - - public final String getAttributes() { - return this.attributes; - } - - public final Conversation.State getState() { - return this.state; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final Map getTimers() { - return this.timers; - } - - public final URI getUrl() { - return this.url; - } - - public final Map getLinks() { - return this.links; - } - - public final Map getBindings() { - return this.bindings; } @Override @@ -228,83 +243,44 @@ public boolean equals(final Object o) { } Conversation other = (Conversation) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(chatServiceSid, other.chatServiceSid) && - Objects.equals(messagingServiceSid, other.messagingServiceSid) && - Objects.equals(sid, other.sid) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(uniqueName, other.uniqueName) && - Objects.equals(attributes, other.attributes) && - Objects.equals(state, other.state) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(timers, other.timers) && - Objects.equals(url, other.url) && - Objects.equals(links, other.links) && - Objects.equals(bindings, other.bindings) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(attributes, other.attributes) && + Objects.equals(bindings, other.bindings) && + Objects.equals(chatServiceSid, other.chatServiceSid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(links, other.links) && + Objects.equals(messagingServiceSid, other.messagingServiceSid) && + Objects.equals(sid, other.sid) && + Objects.equals(state, other.state) && + Objects.equals(timers, other.timers) && + Objects.equals(uniqueName, other.uniqueName) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - accountSid, - chatServiceSid, - messagingServiceSid, - sid, - friendlyName, - uniqueName, - attributes, - state, - dateCreated, - dateUpdated, - timers, - url, - links, - bindings + accountSid, + attributes, + bindings, + chatServiceSid, + dateCreated, + dateUpdated, + friendlyName, + links, + messagingServiceSid, + sid, + state, + timers, + uniqueName, + url ); } - public enum State { - INACTIVE("inactive"), - ACTIVE("active"), - CLOSED("closed"); - - private final String value; - - private State(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static State forValue(final String value) { - return Promoter.enumFromString(value, State.values()); - } - } - public enum WebhookEnabledType { - TRUE("true"), - FALSE("false"); - - private final String value; - - private WebhookEnabledType(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static WebhookEnabledType forValue(final String value) { - return Promoter.enumFromString(value, WebhookEnabledType.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/conversations/v1/service/ConversationCreator.java b/src/main/java/com/twilio/rest/conversations/v1/service/ConversationCreator.java index 83625cb32e..0d32d4d288 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/service/ConversationCreator.java +++ b/src/main/java/com/twilio/rest/conversations/v1/service/ConversationCreator.java @@ -14,8 +14,11 @@ package com.twilio.rest.conversations.v1.service; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -24,11 +27,12 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.time.ZonedDateTime; public class ConversationCreator extends Creator { - private String pathChatServiceSid; + private String pathchatServiceSid; private Conversation.WebhookEnabledType xTwilioWebhookEnabled; private String friendlyName; private String uniqueName; @@ -42,172 +46,182 @@ public class ConversationCreator extends Creator { private String bindingsEmailAddress; private String bindingsEmailName; - public ConversationCreator(final String pathChatServiceSid) { - this.pathChatServiceSid = pathChatServiceSid; + public ConversationCreator(final String pathchatServiceSid) { + this.pathchatServiceSid = pathchatServiceSid; } - public ConversationCreator setXTwilioWebhookEnabled( - final Conversation.WebhookEnabledType xTwilioWebhookEnabled - ) { - this.xTwilioWebhookEnabled = xTwilioWebhookEnabled; - return this; - } public ConversationCreator setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + public ConversationCreator setUniqueName(final String uniqueName) { this.uniqueName = uniqueName; return this; } + public ConversationCreator setAttributes(final String attributes) { this.attributes = attributes; return this; } - public ConversationCreator setMessagingServiceSid( - final String messagingServiceSid - ) { + + public ConversationCreator setMessagingServiceSid(final String messagingServiceSid) { this.messagingServiceSid = messagingServiceSid; return this; } + public ConversationCreator setDateCreated(final ZonedDateTime dateCreated) { this.dateCreated = dateCreated; return this; } + public ConversationCreator setDateUpdated(final ZonedDateTime dateUpdated) { this.dateUpdated = dateUpdated; return this; } + public ConversationCreator setState(final Conversation.State state) { this.state = state; return this; } + public ConversationCreator setTimersInactive(final String timersInactive) { this.timersInactive = timersInactive; return this; } + public ConversationCreator setTimersClosed(final String timersClosed) { this.timersClosed = timersClosed; return this; } - public ConversationCreator setBindingsEmailAddress( - final String bindingsEmailAddress - ) { + + public ConversationCreator setBindingsEmailAddress(final String bindingsEmailAddress) { this.bindingsEmailAddress = bindingsEmailAddress; return this; } - public ConversationCreator setBindingsEmailName( - final String bindingsEmailName - ) { + + public ConversationCreator setBindingsEmailName(final String bindingsEmailName) { this.bindingsEmailName = bindingsEmailName; return this; } + + public ConversationCreator setXTwilioWebhookEnabled(final Conversation.WebhookEnabledType xTwilioWebhookEnabled) { + this.xTwilioWebhookEnabled = xTwilioWebhookEnabled; + return this; + } + + @Override public Conversation create(final TwilioRestClient client) { + String path = "/v1/Services/{ChatServiceSid}/Conversations"; - path = - path.replace( - "{" + "ChatServiceSid" + "}", - this.pathChatServiceSid.toString() - ); + path = path.replace("{" + "ChatServiceSid" + "}", this.pathchatServiceSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.CONVERSATIONS.toString(), - path + HttpMethod.POST, + Domains.CONVERSATIONS.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); - addPostParams(request); addHeaderParams(request); + addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Conversation creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("Conversation creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Conversation.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Conversation.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + if (uniqueName != null) { - request.addPostParam("UniqueName", uniqueName); + Serializer.toString(request, "UniqueName", uniqueName, ParameterType.URLENCODED); } + + if (attributes != null) { - request.addPostParam("Attributes", attributes); + Serializer.toString(request, "Attributes", attributes, ParameterType.URLENCODED); } + + if (messagingServiceSid != null) { - request.addPostParam("MessagingServiceSid", messagingServiceSid); + Serializer.toString(request, "MessagingServiceSid", messagingServiceSid, ParameterType.URLENCODED); } + + if (dateCreated != null) { - request.addPostParam( - "DateCreated", - dateCreated.toInstant().toString() - ); + Serializer.toString(request, "DateCreated", dateCreated, ParameterType.URLENCODED); } + + if (dateUpdated != null) { - request.addPostParam( - "DateUpdated", - dateUpdated.toInstant().toString() - ); + Serializer.toString(request, "DateUpdated", dateUpdated, ParameterType.URLENCODED); } + + if (state != null) { - request.addPostParam("State", state.toString()); + Serializer.toString(request, "State", state, ParameterType.URLENCODED); } + + if (timersInactive != null) { - request.addPostParam("Timers.Inactive", timersInactive); + Serializer.toString(request, "Timers.Inactive", timersInactive, ParameterType.URLENCODED); } + + if (timersClosed != null) { - request.addPostParam("Timers.Closed", timersClosed); + Serializer.toString(request, "Timers.Closed", timersClosed, ParameterType.URLENCODED); } + + if (bindingsEmailAddress != null) { - request.addPostParam( - "Bindings.Email.Address", - bindingsEmailAddress - ); + Serializer.toString(request, "Bindings.Email.Address", bindingsEmailAddress, ParameterType.URLENCODED); } + + if (bindingsEmailName != null) { - request.addPostParam("Bindings.Email.Name", bindingsEmailName); + Serializer.toString(request, "Bindings.Email.Name", bindingsEmailName, ParameterType.URLENCODED); } + + } private void addHeaderParams(final Request request) { + if (xTwilioWebhookEnabled != null) { - request.addHeaderParam( - "X-Twilio-Webhook-Enabled", - xTwilioWebhookEnabled.toString() - ); + Serializer.toString(request, "X-Twilio-Webhook-Enabled", xTwilioWebhookEnabled, ParameterType.HEADER); } + } } diff --git a/src/main/java/com/twilio/rest/conversations/v1/service/ConversationDeleter.java b/src/main/java/com/twilio/rest/conversations/v1/service/ConversationDeleter.java index 47540bf7b3..92063b9413 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/service/ConversationDeleter.java +++ b/src/main/java/com/twilio/rest/conversations/v1/service/ConversationDeleter.java @@ -15,7 +15,8 @@ package com.twilio.rest.conversations.v1.service; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,59 +28,49 @@ public class ConversationDeleter extends Deleter { - private String pathChatServiceSid; - private String pathSid; + private String pathchatServiceSid; + private String pathsid; private Conversation.WebhookEnabledType xTwilioWebhookEnabled; - public ConversationDeleter( - final String pathChatServiceSid, - final String pathSid - ) { - this.pathChatServiceSid = pathChatServiceSid; - this.pathSid = pathSid; + public ConversationDeleter(final String pathchatServiceSid, final String pathsid) { + this.pathchatServiceSid = pathchatServiceSid; + this.pathsid = pathsid; } - public ConversationDeleter setXTwilioWebhookEnabled( - final Conversation.WebhookEnabledType xTwilioWebhookEnabled - ) { + + public ConversationDeleter setXTwilioWebhookEnabled(final Conversation.WebhookEnabledType xTwilioWebhookEnabled) { this.xTwilioWebhookEnabled = xTwilioWebhookEnabled; return this; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/v1/Services/{ChatServiceSid}/Conversations/{Sid}"; - path = - path.replace( - "{" + "ChatServiceSid" + "}", - this.pathChatServiceSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "ChatServiceSid" + "}", this.pathchatServiceSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.CONVERSATIONS.toString(), - path + HttpMethod.DELETE, + Domains.CONVERSATIONS.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addHeaderParams(request); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Conversation delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("Conversation delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -87,11 +78,10 @@ public boolean delete(final TwilioRestClient client) { } private void addHeaderParams(final Request request) { + if (xTwilioWebhookEnabled != null) { - request.addHeaderParam( - "X-Twilio-Webhook-Enabled", - xTwilioWebhookEnabled.toString() - ); + Serializer.toString(request, "X-Twilio-Webhook-Enabled", xTwilioWebhookEnabled, ParameterType.HEADER); } + } } diff --git a/src/main/java/com/twilio/rest/conversations/v1/service/ConversationFetcher.java b/src/main/java/com/twilio/rest/conversations/v1/service/ConversationFetcher.java index 7a3489a8a4..396681f5d4 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/service/ConversationFetcher.java +++ b/src/main/java/com/twilio/rest/conversations/v1/service/ConversationFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.conversations.v1.service; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,57 +26,44 @@ public class ConversationFetcher extends Fetcher { - private String pathChatServiceSid; - private String pathSid; + private String pathchatServiceSid; + private String pathsid; - public ConversationFetcher( - final String pathChatServiceSid, - final String pathSid - ) { - this.pathChatServiceSid = pathChatServiceSid; - this.pathSid = pathSid; + public ConversationFetcher(final String pathchatServiceSid, final String pathsid) { + this.pathchatServiceSid = pathchatServiceSid; + this.pathsid = pathsid; } + @Override public Conversation fetch(final TwilioRestClient client) { + String path = "/v1/Services/{ChatServiceSid}/Conversations/{Sid}"; - path = - path.replace( - "{" + "ChatServiceSid" + "}", - this.pathChatServiceSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "ChatServiceSid" + "}", this.pathchatServiceSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.CONVERSATIONS.toString(), - path + HttpMethod.GET, + Domains.CONVERSATIONS.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Conversation fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Conversation fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return Conversation.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Conversation.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/conversations/v1/service/ConversationReader.java b/src/main/java/com/twilio/rest/conversations/v1/service/ConversationReader.java index 069037bc9c..53da01b9cb 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/service/ConversationReader.java +++ b/src/main/java/com/twilio/rest/conversations/v1/service/ConversationReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,142 +30,124 @@ public class ConversationReader extends Reader { - private String pathChatServiceSid; + private String pathchatServiceSid; private String startDate; private String endDate; private Conversation.State state; private Long pageSize; - public ConversationReader(final String pathChatServiceSid) { - this.pathChatServiceSid = pathChatServiceSid; + public ConversationReader(final String pathchatServiceSid) { + this.pathchatServiceSid = pathchatServiceSid; } + public ConversationReader setStartDate(final String startDate) { this.startDate = startDate; return this; } + public ConversationReader setEndDate(final String endDate) { this.endDate = endDate; return this; } + public ConversationReader setState(final Conversation.State state) { this.state = state; return this; } + public ConversationReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/Services/{ChatServiceSid}/Conversations"; - path = - path.replace( - "{" + "ChatServiceSid" + "}", - this.pathChatServiceSid.toString() - ); + + path = path.replace("{" + "ChatServiceSid" + "}", this.pathchatServiceSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.CONVERSATIONS.toString(), - path + HttpMethod.GET, + Domains.CONVERSATIONS.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Conversation read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Conversation read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "conversations", - response.getContent(), - Conversation.class, - client.getObjectMapper() - ); + "conversations", + response.getContent(), + Conversation.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.CONVERSATIONS.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.CONVERSATIONS.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (startDate != null) { - request.addQueryParam("StartDate", startDate); + Serializer.toString(request, "StartDate", startDate, ParameterType.QUERY); } + + if (endDate != null) { - request.addQueryParam("EndDate", endDate); + Serializer.toString(request, "EndDate", endDate, ParameterType.QUERY); } + + if (state != null) { - request.addQueryParam("State", state.toString()); + Serializer.toString(request, "State", state, ParameterType.QUERY); } + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/conversations/v1/service/ConversationUpdater.java b/src/main/java/com/twilio/rest/conversations/v1/service/ConversationUpdater.java index a045c54c9f..43ec4ff226 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/service/ConversationUpdater.java +++ b/src/main/java/com/twilio/rest/conversations/v1/service/ConversationUpdater.java @@ -16,6 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -24,12 +26,12 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.time.ZonedDateTime; public class ConversationUpdater extends Updater { - - private String pathChatServiceSid; - private String pathSid; + private String pathchatServiceSid; + private String pathsid; private Conversation.WebhookEnabledType xTwilioWebhookEnabled; private String friendlyName; private ZonedDateTime dateCreated; @@ -43,177 +45,184 @@ public class ConversationUpdater extends Updater { private String bindingsEmailAddress; private String bindingsEmailName; - public ConversationUpdater( - final String pathChatServiceSid, - final String pathSid - ) { - this.pathChatServiceSid = pathChatServiceSid; - this.pathSid = pathSid; + public ConversationUpdater(final String pathchatServiceSid, final String pathsid) { + this.pathchatServiceSid = pathchatServiceSid; + this.pathsid = pathsid; } - public ConversationUpdater setXTwilioWebhookEnabled( - final Conversation.WebhookEnabledType xTwilioWebhookEnabled - ) { - this.xTwilioWebhookEnabled = xTwilioWebhookEnabled; - return this; - } public ConversationUpdater setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + public ConversationUpdater setDateCreated(final ZonedDateTime dateCreated) { this.dateCreated = dateCreated; return this; } + public ConversationUpdater setDateUpdated(final ZonedDateTime dateUpdated) { this.dateUpdated = dateUpdated; return this; } + public ConversationUpdater setAttributes(final String attributes) { this.attributes = attributes; return this; } - public ConversationUpdater setMessagingServiceSid( - final String messagingServiceSid - ) { + + public ConversationUpdater setMessagingServiceSid(final String messagingServiceSid) { this.messagingServiceSid = messagingServiceSid; return this; } + public ConversationUpdater setState(final Conversation.State state) { this.state = state; return this; } + public ConversationUpdater setTimersInactive(final String timersInactive) { this.timersInactive = timersInactive; return this; } + public ConversationUpdater setTimersClosed(final String timersClosed) { this.timersClosed = timersClosed; return this; } + public ConversationUpdater setUniqueName(final String uniqueName) { this.uniqueName = uniqueName; return this; } - public ConversationUpdater setBindingsEmailAddress( - final String bindingsEmailAddress - ) { + + public ConversationUpdater setBindingsEmailAddress(final String bindingsEmailAddress) { this.bindingsEmailAddress = bindingsEmailAddress; return this; } - public ConversationUpdater setBindingsEmailName( - final String bindingsEmailName - ) { + + public ConversationUpdater setBindingsEmailName(final String bindingsEmailName) { this.bindingsEmailName = bindingsEmailName; return this; } + + public ConversationUpdater setXTwilioWebhookEnabled(final Conversation.WebhookEnabledType xTwilioWebhookEnabled) { + this.xTwilioWebhookEnabled = xTwilioWebhookEnabled; + return this; + } + + @Override public Conversation update(final TwilioRestClient client) { + String path = "/v1/Services/{ChatServiceSid}/Conversations/{Sid}"; - path = - path.replace( - "{" + "ChatServiceSid" + "}", - this.pathChatServiceSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "ChatServiceSid" + "}", this.pathchatServiceSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.CONVERSATIONS.toString(), - path + HttpMethod.POST, + Domains.CONVERSATIONS.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); - addPostParams(request); addHeaderParams(request); + addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Conversation update failed: Unable to connect to server" - ); + throw new ApiConnectionException("Conversation update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Conversation.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Conversation.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + if (dateCreated != null) { - request.addPostParam( - "DateCreated", - dateCreated.toInstant().toString() - ); + Serializer.toString(request, "DateCreated", dateCreated, ParameterType.URLENCODED); } + + if (dateUpdated != null) { - request.addPostParam( - "DateUpdated", - dateUpdated.toInstant().toString() - ); + Serializer.toString(request, "DateUpdated", dateUpdated, ParameterType.URLENCODED); } + + if (attributes != null) { - request.addPostParam("Attributes", attributes); + Serializer.toString(request, "Attributes", attributes, ParameterType.URLENCODED); } + + if (messagingServiceSid != null) { - request.addPostParam("MessagingServiceSid", messagingServiceSid); + Serializer.toString(request, "MessagingServiceSid", messagingServiceSid, ParameterType.URLENCODED); } + + if (state != null) { - request.addPostParam("State", state.toString()); + Serializer.toString(request, "State", state, ParameterType.URLENCODED); } + + if (timersInactive != null) { - request.addPostParam("Timers.Inactive", timersInactive); + Serializer.toString(request, "Timers.Inactive", timersInactive, ParameterType.URLENCODED); } + + if (timersClosed != null) { - request.addPostParam("Timers.Closed", timersClosed); + Serializer.toString(request, "Timers.Closed", timersClosed, ParameterType.URLENCODED); } + + if (uniqueName != null) { - request.addPostParam("UniqueName", uniqueName); + Serializer.toString(request, "UniqueName", uniqueName, ParameterType.URLENCODED); } + + if (bindingsEmailAddress != null) { - request.addPostParam( - "Bindings.Email.Address", - bindingsEmailAddress - ); + Serializer.toString(request, "Bindings.Email.Address", bindingsEmailAddress, ParameterType.URLENCODED); } + + if (bindingsEmailName != null) { - request.addPostParam("Bindings.Email.Name", bindingsEmailName); + Serializer.toString(request, "Bindings.Email.Name", bindingsEmailName, ParameterType.URLENCODED); } + + } private void addHeaderParams(final Request request) { + if (xTwilioWebhookEnabled != null) { - request.addHeaderParam( - "X-Twilio-Webhook-Enabled", - xTwilioWebhookEnabled.toString() - ); + Serializer.toString(request, "X-Twilio-Webhook-Enabled", xTwilioWebhookEnabled, ParameterType.HEADER); } + } } diff --git a/src/main/java/com/twilio/rest/conversations/v1/service/ConversationWithParticipants.java b/src/main/java/com/twilio/rest/conversations/v1/service/ConversationWithParticipants.java index 6726d9630b..574434150e 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/service/ConversationWithParticipants.java +++ b/src/main/java/com/twilio/rest/conversations/v1/service/ConversationWithParticipants.java @@ -18,52 +18,90 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class ConversationWithParticipants extends Resource { - private static final long serialVersionUID = 37532883203442L; - public static ConversationWithParticipantsCreator creator( - final String pathChatServiceSid - ) { - return new ConversationWithParticipantsCreator(pathChatServiceSid); + public static ConversationWithParticipantsCreator creator(final String pathchatServiceSid) { + return new ConversationWithParticipantsCreator( + pathchatServiceSid + ); } + + public enum WebhookEnabledType { + TRUE("true"), + FALSE("false"); + + private final String value; + + private WebhookEnabledType(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static WebhookEnabledType forValue(final String value) { + return Promoter.enumFromString(value, WebhookEnabledType.values()); + } + } + + public enum State { + INITIALIZING("initializing"), + INACTIVE("inactive"), + ACTIVE("active"), + CLOSED("closed"); + + private final String value; + + private State(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static State forValue(final String value) { + return Promoter.enumFromString(value, State.values()); + } + } + + /** * Converts a JSON String into a ConversationWithParticipants object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return ConversationWithParticipants object represented by the provided JSON */ - public static ConversationWithParticipants fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static ConversationWithParticipants fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { - return objectMapper.readValue( - json, - ConversationWithParticipants.class - ); + return objectMapper.readValue(json, ConversationWithParticipants.class); } catch (final JsonMappingException | JsonParseException e) { throw new ApiException(e.getMessage(), e); } catch (final IOException e) { @@ -75,20 +113,14 @@ public static ConversationWithParticipants fromJson( * Converts a JSON InputStream into a ConversationWithParticipants object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return ConversationWithParticipants object represented by the provided JSON */ - public static ConversationWithParticipants fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static ConversationWithParticipants fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { - return objectMapper.readValue( - json, - ConversationWithParticipants.class - ); + return objectMapper.readValue(json, ConversationWithParticipants.class); } catch (final JsonMappingException | JsonParseException e) { throw new ApiException(e.getMessage(), e); } catch (final IOException e) { @@ -96,110 +128,83 @@ public static ConversationWithParticipants fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String chatServiceSid; - private final String messagingServiceSid; - private final String sid; - private final String friendlyName; - private final String uniqueName; + @Getter private final String attributes; - private final ConversationWithParticipants.State state; + @Getter + private final Object bindings; + @Getter + private final String chatServiceSid; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; - private final Map timers; + @Getter + private final String friendlyName; + @Getter private final Map links; - private final Map bindings; + @Getter + private final String messagingServiceSid; + @Getter + private final String sid; + @Getter + private final ConversationWithParticipants.State state; + @Getter + private final Object timers; + @Getter + private final String uniqueName; + @Getter private final URI url; @JsonCreator private ConversationWithParticipants( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("chat_service_sid") final String chatServiceSid, - @JsonProperty("messaging_service_sid") final String messagingServiceSid, - @JsonProperty("sid") final String sid, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("unique_name") final String uniqueName, - @JsonProperty("attributes") final String attributes, - @JsonProperty("state") final ConversationWithParticipants.State state, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("timers") final Map timers, - @JsonProperty("links") final Map links, - @JsonProperty("bindings") final Map bindings, - @JsonProperty("url") final URI url + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("attributes") final String attributes, + @JsonProperty("bindings") final Object bindings, + @JsonProperty("chat_service_sid") final String chatServiceSid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("links") final Map links, + @JsonProperty("messaging_service_sid") final String messagingServiceSid, + @JsonProperty("sid") final String sid, + @JsonProperty("state") final ConversationWithParticipants.State state, + @JsonProperty("timers") final Object timers, + @JsonProperty("unique_name") final String uniqueName, + @JsonProperty("url") final URI url ) { this.accountSid = accountSid; + this.attributes = attributes; + this.bindings = bindings; this.chatServiceSid = chatServiceSid; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; + this.friendlyName = friendlyName; + this.links = links; this.messagingServiceSid = messagingServiceSid; this.sid = sid; - this.friendlyName = friendlyName; - this.uniqueName = uniqueName; - this.attributes = attributes; this.state = state; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); this.timers = timers; - this.links = links; - this.bindings = bindings; + this.uniqueName = uniqueName; this.url = url; } - public final String getAccountSid() { - return this.accountSid; - } - - public final String getChatServiceSid() { - return this.chatServiceSid; - } - - public final String getMessagingServiceSid() { - return this.messagingServiceSid; - } - - public final String getSid() { - return this.sid; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final String getUniqueName() { - return this.uniqueName; - } - - public final String getAttributes() { - return this.attributes; - } - - public final ConversationWithParticipants.State getState() { - return this.state; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final Map getTimers() { - return this.timers; - } - - public final Map getLinks() { - return this.links; - } - - public final Map getBindings() { - return this.bindings; - } - - public final URI getUrl() { - return this.url; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -211,84 +216,44 @@ public boolean equals(final Object o) { } ConversationWithParticipants other = (ConversationWithParticipants) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(chatServiceSid, other.chatServiceSid) && - Objects.equals(messagingServiceSid, other.messagingServiceSid) && - Objects.equals(sid, other.sid) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(uniqueName, other.uniqueName) && - Objects.equals(attributes, other.attributes) && - Objects.equals(state, other.state) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(timers, other.timers) && - Objects.equals(links, other.links) && - Objects.equals(bindings, other.bindings) && - Objects.equals(url, other.url) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(attributes, other.attributes) && + Objects.equals(bindings, other.bindings) && + Objects.equals(chatServiceSid, other.chatServiceSid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(links, other.links) && + Objects.equals(messagingServiceSid, other.messagingServiceSid) && + Objects.equals(sid, other.sid) && + Objects.equals(state, other.state) && + Objects.equals(timers, other.timers) && + Objects.equals(uniqueName, other.uniqueName) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - accountSid, - chatServiceSid, - messagingServiceSid, - sid, - friendlyName, - uniqueName, - attributes, - state, - dateCreated, - dateUpdated, - timers, - links, - bindings, - url + accountSid, + attributes, + bindings, + chatServiceSid, + dateCreated, + dateUpdated, + friendlyName, + links, + messagingServiceSid, + sid, + state, + timers, + uniqueName, + url ); } - public enum State { - INITIALIZING("initializing"), - INACTIVE("inactive"), - ACTIVE("active"), - CLOSED("closed"); - - private final String value; - - private State(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static State forValue(final String value) { - return Promoter.enumFromString(value, State.values()); - } - } - - public enum WebhookEnabledType { - TRUE("true"), - FALSE("false"); - - private final String value; - private WebhookEnabledType(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static WebhookEnabledType forValue(final String value) { - return Promoter.enumFromString(value, WebhookEnabledType.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/conversations/v1/service/ConversationWithParticipantsCreator.java b/src/main/java/com/twilio/rest/conversations/v1/service/ConversationWithParticipantsCreator.java index 818f36f106..fe3234a369 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/service/ConversationWithParticipantsCreator.java +++ b/src/main/java/com/twilio/rest/conversations/v1/service/ConversationWithParticipantsCreator.java @@ -14,9 +14,12 @@ package com.twilio.rest.conversations.v1.service; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; import com.twilio.converter.Promoter; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,14 +28,13 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.time.ZonedDateTime; import java.util.List; -import java.util.List; -public class ConversationWithParticipantsCreator - extends Creator { +public class ConversationWithParticipantsCreator extends Creator { - private String pathChatServiceSid; + private String pathchatServiceSid; private ConversationWithParticipants.WebhookEnabledType xTwilioWebhookEnabled; private String friendlyName; private String uniqueName; @@ -47,209 +49,197 @@ public class ConversationWithParticipantsCreator private String bindingsEmailName; private List participant; - public ConversationWithParticipantsCreator( - final String pathChatServiceSid - ) { - this.pathChatServiceSid = pathChatServiceSid; + public ConversationWithParticipantsCreator(final String pathchatServiceSid) { + this.pathchatServiceSid = pathchatServiceSid; } - public ConversationWithParticipantsCreator setXTwilioWebhookEnabled( - final ConversationWithParticipants.WebhookEnabledType xTwilioWebhookEnabled - ) { - this.xTwilioWebhookEnabled = xTwilioWebhookEnabled; - return this; - } - public ConversationWithParticipantsCreator setFriendlyName( - final String friendlyName - ) { + public ConversationWithParticipantsCreator setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } - public ConversationWithParticipantsCreator setUniqueName( - final String uniqueName - ) { + + public ConversationWithParticipantsCreator setUniqueName(final String uniqueName) { this.uniqueName = uniqueName; return this; } - public ConversationWithParticipantsCreator setDateCreated( - final ZonedDateTime dateCreated - ) { + + public ConversationWithParticipantsCreator setDateCreated(final ZonedDateTime dateCreated) { this.dateCreated = dateCreated; return this; } - public ConversationWithParticipantsCreator setDateUpdated( - final ZonedDateTime dateUpdated - ) { + + public ConversationWithParticipantsCreator setDateUpdated(final ZonedDateTime dateUpdated) { this.dateUpdated = dateUpdated; return this; } - public ConversationWithParticipantsCreator setMessagingServiceSid( - final String messagingServiceSid - ) { + + public ConversationWithParticipantsCreator setMessagingServiceSid(final String messagingServiceSid) { this.messagingServiceSid = messagingServiceSid; return this; } - public ConversationWithParticipantsCreator setAttributes( - final String attributes - ) { + + public ConversationWithParticipantsCreator setAttributes(final String attributes) { this.attributes = attributes; return this; } - public ConversationWithParticipantsCreator setState( - final ConversationWithParticipants.State state - ) { + + public ConversationWithParticipantsCreator setState(final ConversationWithParticipants.State state) { this.state = state; return this; } - public ConversationWithParticipantsCreator setTimersInactive( - final String timersInactive - ) { + + public ConversationWithParticipantsCreator setTimersInactive(final String timersInactive) { this.timersInactive = timersInactive; return this; } - public ConversationWithParticipantsCreator setTimersClosed( - final String timersClosed - ) { + + public ConversationWithParticipantsCreator setTimersClosed(final String timersClosed) { this.timersClosed = timersClosed; return this; } - public ConversationWithParticipantsCreator setBindingsEmailAddress( - final String bindingsEmailAddress - ) { + + public ConversationWithParticipantsCreator setBindingsEmailAddress(final String bindingsEmailAddress) { this.bindingsEmailAddress = bindingsEmailAddress; return this; } - public ConversationWithParticipantsCreator setBindingsEmailName( - final String bindingsEmailName - ) { + + public ConversationWithParticipantsCreator setBindingsEmailName(final String bindingsEmailName) { this.bindingsEmailName = bindingsEmailName; return this; } - public ConversationWithParticipantsCreator setParticipant( - final List participant - ) { + + public ConversationWithParticipantsCreator setParticipant(final List participant) { this.participant = participant; return this; } - public ConversationWithParticipantsCreator setParticipant( - final String participant - ) { + public ConversationWithParticipantsCreator setParticipant(final String participant) { return setParticipant(Promoter.listOfOne(participant)); } + public ConversationWithParticipantsCreator setXTwilioWebhookEnabled(final ConversationWithParticipants.WebhookEnabledType xTwilioWebhookEnabled) { + this.xTwilioWebhookEnabled = xTwilioWebhookEnabled; + return this; + } + + @Override public ConversationWithParticipants create(final TwilioRestClient client) { - String path = - "/v1/Services/{ChatServiceSid}/ConversationWithParticipants"; - path = - path.replace( - "{" + "ChatServiceSid" + "}", - this.pathChatServiceSid.toString() - ); + String path = "/v1/Services/{ChatServiceSid}/ConversationWithParticipants"; + + path = path.replace("{" + "ChatServiceSid" + "}", this.pathchatServiceSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.CONVERSATIONS.toString(), - path + HttpMethod.POST, + Domains.CONVERSATIONS.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); - addPostParams(request); addHeaderParams(request); + addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "ConversationWithParticipants creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("ConversationWithParticipants creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return ConversationWithParticipants.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return ConversationWithParticipants.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + if (uniqueName != null) { - request.addPostParam("UniqueName", uniqueName); + Serializer.toString(request, "UniqueName", uniqueName, ParameterType.URLENCODED); } + + if (dateCreated != null) { - request.addPostParam( - "DateCreated", - dateCreated.toInstant().toString() - ); + Serializer.toString(request, "DateCreated", dateCreated, ParameterType.URLENCODED); } + + if (dateUpdated != null) { - request.addPostParam( - "DateUpdated", - dateUpdated.toInstant().toString() - ); + Serializer.toString(request, "DateUpdated", dateUpdated, ParameterType.URLENCODED); } + + if (messagingServiceSid != null) { - request.addPostParam("MessagingServiceSid", messagingServiceSid); + Serializer.toString(request, "MessagingServiceSid", messagingServiceSid, ParameterType.URLENCODED); } + + if (attributes != null) { - request.addPostParam("Attributes", attributes); + Serializer.toString(request, "Attributes", attributes, ParameterType.URLENCODED); } + + if (state != null) { - request.addPostParam("State", state.toString()); + Serializer.toString(request, "State", state, ParameterType.URLENCODED); } + + if (timersInactive != null) { - request.addPostParam("Timers.Inactive", timersInactive); + Serializer.toString(request, "Timers.Inactive", timersInactive, ParameterType.URLENCODED); } + + if (timersClosed != null) { - request.addPostParam("Timers.Closed", timersClosed); + Serializer.toString(request, "Timers.Closed", timersClosed, ParameterType.URLENCODED); } + + if (bindingsEmailAddress != null) { - request.addPostParam( - "Bindings.Email.Address", - bindingsEmailAddress - ); + Serializer.toString(request, "Bindings.Email.Address", bindingsEmailAddress, ParameterType.URLENCODED); } + + if (bindingsEmailName != null) { - request.addPostParam("Bindings.Email.Name", bindingsEmailName); + Serializer.toString(request, "Bindings.Email.Name", bindingsEmailName, ParameterType.URLENCODED); } + + if (participant != null) { - for (String prop : participant) { - request.addPostParam("Participant", prop); + for (String param : participant) { + Serializer.toString(request, "Participant", param, ParameterType.URLENCODED); } } + } private void addHeaderParams(final Request request) { + if (xTwilioWebhookEnabled != null) { - request.addHeaderParam( - "X-Twilio-Webhook-Enabled", - xTwilioWebhookEnabled.toString() - ); + Serializer.toString(request, "X-Twilio-Webhook-Enabled", xTwilioWebhookEnabled, ParameterType.HEADER); } + } } diff --git a/src/main/java/com/twilio/rest/conversations/v1/service/ParticipantConversation.java b/src/main/java/com/twilio/rest/conversations/v1/service/ParticipantConversation.java index 7ee5b2860d..5e8ba33ebf 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/service/ParticipantConversation.java +++ b/src/main/java/com/twilio/rest/conversations/v1/service/ParticipantConversation.java @@ -18,45 +18,65 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.time.ZonedDateTime; import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class ParticipantConversation extends Resource { - private static final long serialVersionUID = 210706261724884L; - public static ParticipantConversationReader reader( - final String pathChatServiceSid - ) { - return new ParticipantConversationReader(pathChatServiceSid); + public static ParticipantConversationReader reader(final String pathchatServiceSid) { + return new ParticipantConversationReader( + pathchatServiceSid + ); + } + + + public enum State { + INACTIVE("inactive"), + ACTIVE("active"), + CLOSED("closed"); + + private final String value; + + private State(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static State forValue(final String value) { + return Promoter.enumFromString(value, State.values()); + } } + /** * Converts a JSON String into a ParticipantConversation object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return ParticipantConversation object represented by the provided JSON */ - public static ParticipantConversation fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static ParticipantConversation fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, ParticipantConversation.class); @@ -71,14 +91,11 @@ public static ParticipantConversation fromJson( * Converts a JSON InputStream into a ParticipantConversation object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return ParticipantConversation object represented by the provided JSON */ - public static ParticipantConversation fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static ParticipantConversation fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, ParticipantConversation.class); @@ -89,144 +106,89 @@ public static ParticipantConversation fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; + @Getter private final String chatServiceSid; - private final String participantSid; - private final String participantUserSid; - private final String participantIdentity; - private final Map participantMessagingBinding; - private final String conversationSid; - private final String conversationUniqueName; - private final String conversationFriendlyName; + @Getter private final String conversationAttributes; + @Getter + private final String conversationCreatedBy; + @Getter private final ZonedDateTime conversationDateCreated; + @Getter private final ZonedDateTime conversationDateUpdated; - private final String conversationCreatedBy; + @Getter + private final String conversationFriendlyName; + @Getter + private final String conversationSid; + @Getter private final ParticipantConversation.State conversationState; - private final Map conversationTimers; + @Getter + private final Object conversationTimers; + @Getter + private final String conversationUniqueName; + @Getter private final Map links; + @Getter + private final String participantIdentity; + @Getter + private final Object participantMessagingBinding; + @Getter + private final String participantSid; + @Getter + private final String participantUserSid; @JsonCreator private ParticipantConversation( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("chat_service_sid") final String chatServiceSid, - @JsonProperty("participant_sid") final String participantSid, - @JsonProperty("participant_user_sid") final String participantUserSid, - @JsonProperty("participant_identity") final String participantIdentity, - @JsonProperty("participant_messaging_binding") final Map< - String, - Object - > participantMessagingBinding, - @JsonProperty("conversation_sid") final String conversationSid, - @JsonProperty( - "conversation_unique_name" - ) final String conversationUniqueName, - @JsonProperty( - "conversation_friendly_name" - ) final String conversationFriendlyName, - @JsonProperty( - "conversation_attributes" - ) final String conversationAttributes, - @JsonProperty( - "conversation_date_created" - ) final String conversationDateCreated, - @JsonProperty( - "conversation_date_updated" - ) final String conversationDateUpdated, - @JsonProperty( - "conversation_created_by" - ) final String conversationCreatedBy, - @JsonProperty( - "conversation_state" - ) final ParticipantConversation.State conversationState, - @JsonProperty("conversation_timers") final Map< - String, - Object - > conversationTimers, - @JsonProperty("links") final Map links + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("chat_service_sid") final String chatServiceSid, + @JsonProperty("conversation_attributes") final String conversationAttributes, + @JsonProperty("conversation_created_by") final String conversationCreatedBy, + @JsonProperty("conversation_date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime conversationDateCreated, + @JsonProperty("conversation_date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime conversationDateUpdated, + @JsonProperty("conversation_friendly_name") final String conversationFriendlyName, + @JsonProperty("conversation_sid") final String conversationSid, + @JsonProperty("conversation_state") final ParticipantConversation.State conversationState, + @JsonProperty("conversation_timers") final Object conversationTimers, + @JsonProperty("conversation_unique_name") final String conversationUniqueName, + @JsonProperty("links") final Map links, + @JsonProperty("participant_identity") final String participantIdentity, + @JsonProperty("participant_messaging_binding") final Object participantMessagingBinding, + @JsonProperty("participant_sid") final String participantSid, + @JsonProperty("participant_user_sid") final String participantUserSid ) { this.accountSid = accountSid; this.chatServiceSid = chatServiceSid; - this.participantSid = participantSid; - this.participantUserSid = participantUserSid; - this.participantIdentity = participantIdentity; - this.participantMessagingBinding = participantMessagingBinding; - this.conversationSid = conversationSid; - this.conversationUniqueName = conversationUniqueName; - this.conversationFriendlyName = conversationFriendlyName; this.conversationAttributes = conversationAttributes; - this.conversationDateCreated = - DateConverter.iso8601DateTimeFromString(conversationDateCreated); - this.conversationDateUpdated = - DateConverter.iso8601DateTimeFromString(conversationDateUpdated); this.conversationCreatedBy = conversationCreatedBy; + this.conversationDateCreated = conversationDateCreated; + this.conversationDateUpdated = conversationDateUpdated; + this.conversationFriendlyName = conversationFriendlyName; + this.conversationSid = conversationSid; this.conversationState = conversationState; this.conversationTimers = conversationTimers; + this.conversationUniqueName = conversationUniqueName; this.links = links; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getChatServiceSid() { - return this.chatServiceSid; - } - - public final String getParticipantSid() { - return this.participantSid; - } - - public final String getParticipantUserSid() { - return this.participantUserSid; - } - - public final String getParticipantIdentity() { - return this.participantIdentity; - } - - public final Map getParticipantMessagingBinding() { - return this.participantMessagingBinding; - } - - public final String getConversationSid() { - return this.conversationSid; - } - - public final String getConversationUniqueName() { - return this.conversationUniqueName; - } - - public final String getConversationFriendlyName() { - return this.conversationFriendlyName; - } - - public final String getConversationAttributes() { - return this.conversationAttributes; - } - - public final ZonedDateTime getConversationDateCreated() { - return this.conversationDateCreated; - } - - public final ZonedDateTime getConversationDateUpdated() { - return this.conversationDateUpdated; - } - - public final String getConversationCreatedBy() { - return this.conversationCreatedBy; - } - - public final ParticipantConversation.State getConversationState() { - return this.conversationState; - } - - public final Map getConversationTimers() { - return this.conversationTimers; - } - - public final Map getLinks() { - return this.links; + this.participantIdentity = participantIdentity; + this.participantMessagingBinding = participantMessagingBinding; + this.participantSid = participantSid; + this.participantUserSid = participantUserSid; } @Override @@ -240,88 +202,48 @@ public boolean equals(final Object o) { } ParticipantConversation other = (ParticipantConversation) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(chatServiceSid, other.chatServiceSid) && - Objects.equals(participantSid, other.participantSid) && - Objects.equals(participantUserSid, other.participantUserSid) && - Objects.equals(participantIdentity, other.participantIdentity) && - Objects.equals( - participantMessagingBinding, - other.participantMessagingBinding - ) && - Objects.equals(conversationSid, other.conversationSid) && - Objects.equals( - conversationUniqueName, - other.conversationUniqueName - ) && - Objects.equals( - conversationFriendlyName, - other.conversationFriendlyName - ) && - Objects.equals( - conversationAttributes, - other.conversationAttributes - ) && - Objects.equals( - conversationDateCreated, - other.conversationDateCreated - ) && - Objects.equals( - conversationDateUpdated, - other.conversationDateUpdated - ) && - Objects.equals( - conversationCreatedBy, - other.conversationCreatedBy - ) && - Objects.equals(conversationState, other.conversationState) && - Objects.equals(conversationTimers, other.conversationTimers) && - Objects.equals(links, other.links) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(chatServiceSid, other.chatServiceSid) && + Objects.equals(conversationAttributes, other.conversationAttributes) && + Objects.equals(conversationCreatedBy, other.conversationCreatedBy) && + Objects.equals(conversationDateCreated, other.conversationDateCreated) && + Objects.equals(conversationDateUpdated, other.conversationDateUpdated) && + Objects.equals(conversationFriendlyName, other.conversationFriendlyName) && + Objects.equals(conversationSid, other.conversationSid) && + Objects.equals(conversationState, other.conversationState) && + Objects.equals(conversationTimers, other.conversationTimers) && + Objects.equals(conversationUniqueName, other.conversationUniqueName) && + Objects.equals(links, other.links) && + Objects.equals(participantIdentity, other.participantIdentity) && + Objects.equals(participantMessagingBinding, other.participantMessagingBinding) && + Objects.equals(participantSid, other.participantSid) && + Objects.equals(participantUserSid, other.participantUserSid) ); } @Override public int hashCode() { return Objects.hash( - accountSid, - chatServiceSid, - participantSid, - participantUserSid, - participantIdentity, - participantMessagingBinding, - conversationSid, - conversationUniqueName, - conversationFriendlyName, - conversationAttributes, - conversationDateCreated, - conversationDateUpdated, - conversationCreatedBy, - conversationState, - conversationTimers, - links + accountSid, + chatServiceSid, + conversationAttributes, + conversationCreatedBy, + conversationDateCreated, + conversationDateUpdated, + conversationFriendlyName, + conversationSid, + conversationState, + conversationTimers, + conversationUniqueName, + links, + participantIdentity, + participantMessagingBinding, + participantSid, + participantUserSid ); } - public enum State { - INACTIVE("inactive"), - ACTIVE("active"), - CLOSED("closed"); - - private final String value; - private State(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static State forValue(final String value) { - return Promoter.enumFromString(value, State.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/conversations/v1/service/ParticipantConversationReader.java b/src/main/java/com/twilio/rest/conversations/v1/service/ParticipantConversationReader.java index 4b8c72f69c..982ba79f55 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/service/ParticipantConversationReader.java +++ b/src/main/java/com/twilio/rest/conversations/v1/service/ParticipantConversationReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,140 +28,114 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class ParticipantConversationReader - extends Reader { +public class ParticipantConversationReader extends Reader { - private String pathChatServiceSid; + private String pathchatServiceSid; private String identity; private String address; private Long pageSize; - public ParticipantConversationReader(final String pathChatServiceSid) { - this.pathChatServiceSid = pathChatServiceSid; + public ParticipantConversationReader(final String pathchatServiceSid) { + this.pathchatServiceSid = pathchatServiceSid; } + public ParticipantConversationReader setIdentity(final String identity) { this.identity = identity; return this; } + public ParticipantConversationReader setAddress(final String address) { this.address = address; return this; } + public ParticipantConversationReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override - public ResourceSet read( - final TwilioRestClient client - ) { + public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } - public Page firstPage( - final TwilioRestClient client - ) { + public Page firstPage(final TwilioRestClient client) { + String path = "/v1/Services/{ChatServiceSid}/ParticipantConversations"; - path = - path.replace( - "{" + "ChatServiceSid" + "}", - this.pathChatServiceSid.toString() - ); + + path = path.replace("{" + "ChatServiceSid" + "}", this.pathchatServiceSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.CONVERSATIONS.toString(), - path + HttpMethod.GET, + Domains.CONVERSATIONS.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "ParticipantConversation read failed: Unable to connect to server" - ); + throw new ApiConnectionException("ParticipantConversation read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "conversations", - response.getContent(), - ParticipantConversation.class, - client.getObjectMapper() - ); + "conversations", + response.getContent(), + ParticipantConversation.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.CONVERSATIONS.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.CONVERSATIONS.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (identity != null) { - request.addQueryParam("Identity", identity); + Serializer.toString(request, "Identity", identity, ParameterType.QUERY); } + + if (address != null) { - request.addQueryParam("Address", address); + Serializer.toString(request, "Address", address, ParameterType.QUERY); } + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/conversations/v1/service/Role.java b/src/main/java/com/twilio/rest/conversations/v1/service/Role.java index 43c80476c7..b811571426 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/service/Role.java +++ b/src/main/java/com/twilio/rest/conversations/v1/service/Role.java @@ -18,79 +18,93 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.List; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Role extends Resource { - private static final long serialVersionUID = 223283830784079L; - public static RoleCreator creator( - final String pathChatServiceSid, - final String friendlyName, - final Role.RoleType type, - final List permission - ) { + public static RoleCreator creator(final String pathchatServiceSid, final String friendlyName, final Role.RoleType type, final List permission) { return new RoleCreator( - pathChatServiceSid, - friendlyName, - type, - permission + pathchatServiceSid, friendlyName, type, permission ); } - public static RoleDeleter deleter( - final String pathChatServiceSid, - final String pathSid - ) { - return new RoleDeleter(pathChatServiceSid, pathSid); + + public static RoleDeleter deleter(final String pathchatServiceSid, final String pathsid) { + return new RoleDeleter( + pathchatServiceSid, pathsid + ); } - public static RoleFetcher fetcher( - final String pathChatServiceSid, - final String pathSid - ) { - return new RoleFetcher(pathChatServiceSid, pathSid); + + public static RoleFetcher fetcher(final String pathchatServiceSid, final String pathsid) { + return new RoleFetcher( + pathchatServiceSid, pathsid + ); } - public static RoleReader reader(final String pathChatServiceSid) { - return new RoleReader(pathChatServiceSid); + + public static RoleReader reader(final String pathchatServiceSid) { + return new RoleReader( + pathchatServiceSid + ); } - public static RoleUpdater updater( - final String pathChatServiceSid, - final String pathSid, - final List permission - ) { - return new RoleUpdater(pathChatServiceSid, pathSid, permission); + + public static RoleUpdater updater(final String pathchatServiceSid, final String pathsid, final List permission) { + return new RoleUpdater( + pathchatServiceSid, pathsid, permission + ); + } + + + public enum RoleType { + CONVERSATION("conversation"), + SERVICE("service"); + + private final String value; + + private RoleType(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static RoleType forValue(final String value) { + return Promoter.enumFromString(value, RoleType.values()); + } } + /** * Converts a JSON String into a Role object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Role object represented by the provided JSON */ - public static Role fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Role fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Role.class); @@ -105,14 +119,11 @@ public static Role fromJson( * Converts a JSON InputStream into a Role object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Role object represented by the provided JSON */ - public static Role fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Role fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Role.class); @@ -123,75 +134,63 @@ public static Role fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; + @Getter private final String chatServiceSid; - private final String friendlyName; - private final Role.RoleType type; - private final List permissions; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; + @Getter + private final String friendlyName; + @Getter + private final List permissions; + @Getter + private final String sid; + @Getter + private final Role.RoleType type; + @Getter private final URI url; @JsonCreator private Role( - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("chat_service_sid") final String chatServiceSid, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("type") final Role.RoleType type, - @JsonProperty("permissions") final List permissions, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("url") final URI url + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("chat_service_sid") final String chatServiceSid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("permissions") final List permissions, + @JsonProperty("sid") final String sid, + @JsonProperty("type") final Role.RoleType type, + @JsonProperty("url") final URI url ) { - this.sid = sid; this.accountSid = accountSid; this.chatServiceSid = chatServiceSid; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.friendlyName = friendlyName; - this.type = type; this.permissions = permissions; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); + this.sid = sid; + this.type = type; this.url = url; } - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getChatServiceSid() { - return this.chatServiceSid; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final Role.RoleType getType() { - return this.type; - } - - public final List getPermissions() { - return this.permissions; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final URI getUrl() { - return this.url; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -203,52 +202,34 @@ public boolean equals(final Object o) { } Role other = (Role) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(chatServiceSid, other.chatServiceSid) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(type, other.type) && - Objects.equals(permissions, other.permissions) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(url, other.url) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(chatServiceSid, other.chatServiceSid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(permissions, other.permissions) && + Objects.equals(sid, other.sid) && + Objects.equals(type, other.type) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - sid, - accountSid, - chatServiceSid, - friendlyName, - type, - permissions, - dateCreated, - dateUpdated, - url + accountSid, + chatServiceSid, + dateCreated, + dateUpdated, + friendlyName, + permissions, + sid, + type, + url ); } - public enum RoleType { - CONVERSATION("conversation"), - SERVICE("service"); - - private final String value; - - private RoleType(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - @JsonCreator - public static RoleType forValue(final String value) { - return Promoter.enumFromString(value, RoleType.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/conversations/v1/service/RoleCreator.java b/src/main/java/com/twilio/rest/conversations/v1/service/RoleCreator.java index ca11a6883d..8721fb462b 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/service/RoleCreator.java +++ b/src/main/java/com/twilio/rest/conversations/v1/service/RoleCreator.java @@ -14,9 +14,12 @@ package com.twilio.rest.conversations.v1.service; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; import com.twilio.converter.Promoter; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,38 +28,36 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -import java.util.List; + import java.util.List; public class RoleCreator extends Creator { - private String pathChatServiceSid; + private String pathchatServiceSid; private String friendlyName; private Role.RoleType type; private List permission; - public RoleCreator( - final String pathChatServiceSid, - final String friendlyName, - final Role.RoleType type, - final List permission - ) { - this.pathChatServiceSid = pathChatServiceSid; + public RoleCreator(final String pathchatServiceSid, final String friendlyName, final Role.RoleType type, final List permission) { + this.pathchatServiceSid = pathchatServiceSid; this.friendlyName = friendlyName; this.type = type; this.permission = permission; } + public RoleCreator setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + public RoleCreator setType(final Role.RoleType type) { this.type = type; return this; } + public RoleCreator setPermission(final List permission) { this.permission = permission; return this; @@ -68,44 +69,31 @@ public RoleCreator setPermission(final String permission) { @Override public Role create(final TwilioRestClient client) { + String path = "/v1/Services/{ChatServiceSid}/Roles"; - path = - path.replace( - "{" + "ChatServiceSid" + "}", - this.pathChatServiceSid.toString() - ); - path = - path.replace( - "{" + "FriendlyName" + "}", - this.friendlyName.toString() - ); - path = path.replace("{" + "Type" + "}", this.type.toString()); - path = - path.replace("{" + "Permission" + "}", this.permission.toString()); + path = path.replace("{" + "ChatServiceSid" + "}", this.pathchatServiceSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.CONVERSATIONS.toString(), - path + HttpMethod.POST, + Domains.CONVERSATIONS.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Role creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("Role creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -114,16 +102,22 @@ public Role create(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + if (type != null) { - request.addPostParam("Type", type.toString()); + Serializer.toString(request, "Type", type, ParameterType.URLENCODED); } + + if (permission != null) { - for (String prop : permission) { - request.addPostParam("Permission", prop); + for (String param : permission) { + Serializer.toString(request, "Permission", param, ParameterType.URLENCODED); } } + } } diff --git a/src/main/java/com/twilio/rest/conversations/v1/service/RoleDeleter.java b/src/main/java/com/twilio/rest/conversations/v1/service/RoleDeleter.java index 5d4ec880a4..c482a75104 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/service/RoleDeleter.java +++ b/src/main/java/com/twilio/rest/conversations/v1/service/RoleDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.conversations.v1.service; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,47 +26,41 @@ public class RoleDeleter extends Deleter { - private String pathChatServiceSid; - private String pathSid; + private String pathchatServiceSid; + private String pathsid; - public RoleDeleter(final String pathChatServiceSid, final String pathSid) { - this.pathChatServiceSid = pathChatServiceSid; - this.pathSid = pathSid; + public RoleDeleter(final String pathchatServiceSid, final String pathsid) { + this.pathchatServiceSid = pathchatServiceSid; + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/v1/Services/{ChatServiceSid}/Roles/{Sid}"; - path = - path.replace( - "{" + "ChatServiceSid" + "}", - this.pathChatServiceSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "ChatServiceSid" + "}", this.pathchatServiceSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.CONVERSATIONS.toString(), - path + HttpMethod.DELETE, + Domains.CONVERSATIONS.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Role delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("Role delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/conversations/v1/service/RoleFetcher.java b/src/main/java/com/twilio/rest/conversations/v1/service/RoleFetcher.java index 4ff06a894b..9a9aa3e44c 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/service/RoleFetcher.java +++ b/src/main/java/com/twilio/rest/conversations/v1/service/RoleFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.conversations.v1.service; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,51 +26,44 @@ public class RoleFetcher extends Fetcher { - private String pathChatServiceSid; - private String pathSid; + private String pathchatServiceSid; + private String pathsid; - public RoleFetcher(final String pathChatServiceSid, final String pathSid) { - this.pathChatServiceSid = pathChatServiceSid; - this.pathSid = pathSid; + public RoleFetcher(final String pathchatServiceSid, final String pathsid) { + this.pathchatServiceSid = pathchatServiceSid; + this.pathsid = pathsid; } + @Override public Role fetch(final TwilioRestClient client) { + String path = "/v1/Services/{ChatServiceSid}/Roles/{Sid}"; - path = - path.replace( - "{" + "ChatServiceSid" + "}", - this.pathChatServiceSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "ChatServiceSid" + "}", this.pathchatServiceSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.CONVERSATIONS.toString(), - path + HttpMethod.GET, + Domains.CONVERSATIONS.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Role fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Role fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Role.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/conversations/v1/service/RoleReader.java b/src/main/java/com/twilio/rest/conversations/v1/service/RoleReader.java index 46691bc9e0..e70630c77e 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/service/RoleReader.java +++ b/src/main/java/com/twilio/rest/conversations/v1/service/RoleReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,115 +30,88 @@ public class RoleReader extends Reader { - private String pathChatServiceSid; + private String pathchatServiceSid; private Long pageSize; - public RoleReader(final String pathChatServiceSid) { - this.pathChatServiceSid = pathChatServiceSid; + public RoleReader(final String pathchatServiceSid) { + this.pathchatServiceSid = pathchatServiceSid; } + public RoleReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/Services/{ChatServiceSid}/Roles"; - path = - path.replace( - "{" + "ChatServiceSid" + "}", - this.pathChatServiceSid.toString() - ); + + path = path.replace("{" + "ChatServiceSid" + "}", this.pathchatServiceSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.CONVERSATIONS.toString(), - path + HttpMethod.GET, + Domains.CONVERSATIONS.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Role read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Role read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "roles", - response.getContent(), - Role.class, - client.getObjectMapper() - ); + "roles", + response.getContent(), + Role.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.CONVERSATIONS.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.CONVERSATIONS.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/conversations/v1/service/RoleUpdater.java b/src/main/java/com/twilio/rest/conversations/v1/service/RoleUpdater.java index 0230637ab3..9eb6ede732 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/service/RoleUpdater.java +++ b/src/main/java/com/twilio/rest/conversations/v1/service/RoleUpdater.java @@ -16,7 +16,9 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; import com.twilio.converter.Promoter; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,24 +27,21 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.util.List; public class RoleUpdater extends Updater { - - private String pathChatServiceSid; - private String pathSid; + private String pathchatServiceSid; + private String pathsid; private List permission; - public RoleUpdater( - final String pathChatServiceSid, - final String pathSid, - final List permission - ) { - this.pathChatServiceSid = pathChatServiceSid; - this.pathSid = pathSid; + public RoleUpdater(final String pathchatServiceSid, final String pathsid, final List permission) { + this.pathchatServiceSid = pathchatServiceSid; + this.pathsid = pathsid; this.permission = permission; } + public RoleUpdater setPermission(final List permission) { this.permission = permission; return this; @@ -54,39 +53,32 @@ public RoleUpdater setPermission(final String permission) { @Override public Role update(final TwilioRestClient client) { + String path = "/v1/Services/{ChatServiceSid}/Roles/{Sid}"; - path = - path.replace( - "{" + "ChatServiceSid" + "}", - this.pathChatServiceSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); - path = - path.replace("{" + "Permission" + "}", this.permission.toString()); + path = path.replace("{" + "ChatServiceSid" + "}", this.pathchatServiceSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.CONVERSATIONS.toString(), - path + HttpMethod.POST, + Domains.CONVERSATIONS.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Role update failed: Unable to connect to server" - ); + throw new ApiConnectionException("Role update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -95,10 +87,13 @@ public Role update(final TwilioRestClient client) { } private void addPostParams(final Request request) { + + if (permission != null) { - for (String prop : permission) { - request.addPostParam("Permission", prop); + for (String param : permission) { + Serializer.toString(request, "Permission", param, ParameterType.URLENCODED); } } + } } diff --git a/src/main/java/com/twilio/rest/conversations/v1/service/User.java b/src/main/java/com/twilio/rest/conversations/v1/service/User.java index 3c0779e749..6ea600f074 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/service/User.java +++ b/src/main/java/com/twilio/rest/conversations/v1/service/User.java @@ -18,72 +18,93 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class User extends Resource { - private static final long serialVersionUID = 270629422616663L; - public static UserCreator creator( - final String pathChatServiceSid, - final String identity - ) { - return new UserCreator(pathChatServiceSid, identity); + public static UserCreator creator(final String pathchatServiceSid, final String identity) { + return new UserCreator( + pathchatServiceSid, identity + ); } - public static UserDeleter deleter( - final String pathChatServiceSid, - final String pathSid - ) { - return new UserDeleter(pathChatServiceSid, pathSid); + + public static UserDeleter deleter(final String pathchatServiceSid, final String pathsid) { + return new UserDeleter( + pathchatServiceSid, pathsid + ); } - public static UserFetcher fetcher( - final String pathChatServiceSid, - final String pathSid - ) { - return new UserFetcher(pathChatServiceSid, pathSid); + + public static UserFetcher fetcher(final String pathchatServiceSid, final String pathsid) { + return new UserFetcher( + pathchatServiceSid, pathsid + ); } - public static UserReader reader(final String pathChatServiceSid) { - return new UserReader(pathChatServiceSid); + + public static UserReader reader(final String pathchatServiceSid) { + return new UserReader( + pathchatServiceSid + ); } - public static UserUpdater updater( - final String pathChatServiceSid, - final String pathSid - ) { - return new UserUpdater(pathChatServiceSid, pathSid); + + public static UserUpdater updater(final String pathchatServiceSid, final String pathsid) { + return new UserUpdater( + pathchatServiceSid, pathsid + ); } + + public enum WebhookEnabledType { + TRUE("true"), + FALSE("false"); + + private final String value; + + private WebhookEnabledType(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static WebhookEnabledType forValue(final String value) { + return Promoter.enumFromString(value, WebhookEnabledType.values()); + } + } + + /** * Converts a JSON String into a User object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return User object represented by the provided JSON */ - public static User fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static User fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, User.class); @@ -98,14 +119,11 @@ public static User fromJson( * Converts a JSON InputStream into a User object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return User object represented by the provided JSON */ - public static User fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static User fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, User.class); @@ -116,101 +134,77 @@ public static User fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String chatServiceSid; - private final String roleSid; - private final String identity; - private final String friendlyName; + @Getter private final String attributes; - private final Boolean isOnline; - private final Boolean isNotifiable; + @Getter + private final String chatServiceSid; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; - private final URI url; + @Getter + private final String friendlyName; + @Getter + private final String identity; + @Getter + private final Boolean isNotifiable; + @Getter + private final Boolean isOnline; + @Getter private final Map links; + @Getter + private final String roleSid; + @Getter + private final String sid; + @Getter + private final URI url; @JsonCreator private User( - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("chat_service_sid") final String chatServiceSid, - @JsonProperty("role_sid") final String roleSid, - @JsonProperty("identity") final String identity, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("attributes") final String attributes, - @JsonProperty("is_online") final Boolean isOnline, - @JsonProperty("is_notifiable") final Boolean isNotifiable, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("url") final URI url, - @JsonProperty("links") final Map links + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("attributes") final String attributes, + @JsonProperty("chat_service_sid") final String chatServiceSid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("identity") final String identity, + @JsonProperty("is_notifiable") final Boolean isNotifiable, + @JsonProperty("is_online") final Boolean isOnline, + @JsonProperty("links") final Map links, + @JsonProperty("role_sid") final String roleSid, + @JsonProperty("sid") final String sid, + @JsonProperty("url") final URI url ) { - this.sid = sid; this.accountSid = accountSid; + this.attributes = attributes; this.chatServiceSid = chatServiceSid; - this.roleSid = roleSid; - this.identity = identity; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.friendlyName = friendlyName; - this.attributes = attributes; - this.isOnline = isOnline; + this.identity = identity; this.isNotifiable = isNotifiable; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); - this.url = url; + this.isOnline = isOnline; this.links = links; - } - - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getChatServiceSid() { - return this.chatServiceSid; - } - - public final String getRoleSid() { - return this.roleSid; - } - - public final String getIdentity() { - return this.identity; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final String getAttributes() { - return this.attributes; - } - - public final Boolean getIsOnline() { - return this.isOnline; - } - - public final Boolean getIsNotifiable() { - return this.isNotifiable; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final URI getUrl() { - return this.url; - } - - public final Map getLinks() { - return this.links; + this.roleSid = roleSid; + this.sid = sid; + this.url = url; } @Override @@ -224,60 +218,42 @@ public boolean equals(final Object o) { } User other = (User) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(chatServiceSid, other.chatServiceSid) && - Objects.equals(roleSid, other.roleSid) && - Objects.equals(identity, other.identity) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(attributes, other.attributes) && - Objects.equals(isOnline, other.isOnline) && - Objects.equals(isNotifiable, other.isNotifiable) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(url, other.url) && - Objects.equals(links, other.links) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(attributes, other.attributes) && + Objects.equals(chatServiceSid, other.chatServiceSid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(identity, other.identity) && + Objects.equals(isNotifiable, other.isNotifiable) && + Objects.equals(isOnline, other.isOnline) && + Objects.equals(links, other.links) && + Objects.equals(roleSid, other.roleSid) && + Objects.equals(sid, other.sid) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - sid, - accountSid, - chatServiceSid, - roleSid, - identity, - friendlyName, - attributes, - isOnline, - isNotifiable, - dateCreated, - dateUpdated, - url, - links + accountSid, + attributes, + chatServiceSid, + dateCreated, + dateUpdated, + friendlyName, + identity, + isNotifiable, + isOnline, + links, + roleSid, + sid, + url ); } - public enum WebhookEnabledType { - TRUE("true"), - FALSE("false"); - private final String value; - - private WebhookEnabledType(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static WebhookEnabledType forValue(final String value) { - return Promoter.enumFromString(value, WebhookEnabledType.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/conversations/v1/service/UserCreator.java b/src/main/java/com/twilio/rest/conversations/v1/service/UserCreator.java index 333215cfe7..c7509fea9f 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/service/UserCreator.java +++ b/src/main/java/com/twilio/rest/conversations/v1/service/UserCreator.java @@ -14,8 +14,11 @@ package com.twilio.rest.conversations.v1.service; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,79 +30,77 @@ public class UserCreator extends Creator { - private String pathChatServiceSid; - private String identity; + private String pathchatServiceSid; private User.WebhookEnabledType xTwilioWebhookEnabled; + private String identity; private String friendlyName; private String attributes; private String roleSid; - public UserCreator(final String pathChatServiceSid, final String identity) { - this.pathChatServiceSid = pathChatServiceSid; + public UserCreator(final String pathchatServiceSid, final String identity) { + this.pathchatServiceSid = pathchatServiceSid; this.identity = identity; } + public UserCreator setIdentity(final String identity) { this.identity = identity; return this; } - public UserCreator setXTwilioWebhookEnabled( - final User.WebhookEnabledType xTwilioWebhookEnabled - ) { - this.xTwilioWebhookEnabled = xTwilioWebhookEnabled; - return this; - } public UserCreator setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + public UserCreator setAttributes(final String attributes) { this.attributes = attributes; return this; } + public UserCreator setRoleSid(final String roleSid) { this.roleSid = roleSid; return this; } + + public UserCreator setXTwilioWebhookEnabled(final User.WebhookEnabledType xTwilioWebhookEnabled) { + this.xTwilioWebhookEnabled = xTwilioWebhookEnabled; + return this; + } + + @Override public User create(final TwilioRestClient client) { + String path = "/v1/Services/{ChatServiceSid}/Users"; - path = - path.replace( - "{" + "ChatServiceSid" + "}", - this.pathChatServiceSid.toString() - ); - path = path.replace("{" + "Identity" + "}", this.identity.toString()); + path = path.replace("{" + "ChatServiceSid" + "}", this.pathchatServiceSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.CONVERSATIONS.toString(), - path + HttpMethod.POST, + Domains.CONVERSATIONS.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); - addPostParams(request); addHeaderParams(request); + addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "User creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("User creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -108,26 +109,34 @@ public User create(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (identity != null) { - request.addPostParam("Identity", identity); + Serializer.toString(request, "Identity", identity, ParameterType.URLENCODED); } + + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + if (attributes != null) { - request.addPostParam("Attributes", attributes); + Serializer.toString(request, "Attributes", attributes, ParameterType.URLENCODED); } + + if (roleSid != null) { - request.addPostParam("RoleSid", roleSid); + Serializer.toString(request, "RoleSid", roleSid, ParameterType.URLENCODED); } + + } private void addHeaderParams(final Request request) { + if (xTwilioWebhookEnabled != null) { - request.addHeaderParam( - "X-Twilio-Webhook-Enabled", - xTwilioWebhookEnabled.toString() - ); + Serializer.toString(request, "X-Twilio-Webhook-Enabled", xTwilioWebhookEnabled, ParameterType.HEADER); } + } } diff --git a/src/main/java/com/twilio/rest/conversations/v1/service/UserDeleter.java b/src/main/java/com/twilio/rest/conversations/v1/service/UserDeleter.java index c74bece3e6..d4dada3405 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/service/UserDeleter.java +++ b/src/main/java/com/twilio/rest/conversations/v1/service/UserDeleter.java @@ -15,7 +15,8 @@ package com.twilio.rest.conversations.v1.service; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,56 +28,49 @@ public class UserDeleter extends Deleter { - private String pathChatServiceSid; - private String pathSid; + private String pathchatServiceSid; + private String pathsid; private User.WebhookEnabledType xTwilioWebhookEnabled; - public UserDeleter(final String pathChatServiceSid, final String pathSid) { - this.pathChatServiceSid = pathChatServiceSid; - this.pathSid = pathSid; + public UserDeleter(final String pathchatServiceSid, final String pathsid) { + this.pathchatServiceSid = pathchatServiceSid; + this.pathsid = pathsid; } - public UserDeleter setXTwilioWebhookEnabled( - final User.WebhookEnabledType xTwilioWebhookEnabled - ) { + + public UserDeleter setXTwilioWebhookEnabled(final User.WebhookEnabledType xTwilioWebhookEnabled) { this.xTwilioWebhookEnabled = xTwilioWebhookEnabled; return this; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/v1/Services/{ChatServiceSid}/Users/{Sid}"; - path = - path.replace( - "{" + "ChatServiceSid" + "}", - this.pathChatServiceSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "ChatServiceSid" + "}", this.pathchatServiceSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.CONVERSATIONS.toString(), - path + HttpMethod.DELETE, + Domains.CONVERSATIONS.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addHeaderParams(request); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "User delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("User delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -84,11 +78,10 @@ public boolean delete(final TwilioRestClient client) { } private void addHeaderParams(final Request request) { + if (xTwilioWebhookEnabled != null) { - request.addHeaderParam( - "X-Twilio-Webhook-Enabled", - xTwilioWebhookEnabled.toString() - ); + Serializer.toString(request, "X-Twilio-Webhook-Enabled", xTwilioWebhookEnabled, ParameterType.HEADER); } + } } diff --git a/src/main/java/com/twilio/rest/conversations/v1/service/UserFetcher.java b/src/main/java/com/twilio/rest/conversations/v1/service/UserFetcher.java index 17711aa0c8..f44678e2ea 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/service/UserFetcher.java +++ b/src/main/java/com/twilio/rest/conversations/v1/service/UserFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.conversations.v1.service; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,51 +26,44 @@ public class UserFetcher extends Fetcher { - private String pathChatServiceSid; - private String pathSid; + private String pathchatServiceSid; + private String pathsid; - public UserFetcher(final String pathChatServiceSid, final String pathSid) { - this.pathChatServiceSid = pathChatServiceSid; - this.pathSid = pathSid; + public UserFetcher(final String pathchatServiceSid, final String pathsid) { + this.pathchatServiceSid = pathchatServiceSid; + this.pathsid = pathsid; } + @Override public User fetch(final TwilioRestClient client) { + String path = "/v1/Services/{ChatServiceSid}/Users/{Sid}"; - path = - path.replace( - "{" + "ChatServiceSid" + "}", - this.pathChatServiceSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "ChatServiceSid" + "}", this.pathchatServiceSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.CONVERSATIONS.toString(), - path + HttpMethod.GET, + Domains.CONVERSATIONS.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "User fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("User fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return User.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/conversations/v1/service/UserReader.java b/src/main/java/com/twilio/rest/conversations/v1/service/UserReader.java index a29d393c77..e02bb24689 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/service/UserReader.java +++ b/src/main/java/com/twilio/rest/conversations/v1/service/UserReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,115 +30,88 @@ public class UserReader extends Reader { - private String pathChatServiceSid; + private String pathchatServiceSid; private Long pageSize; - public UserReader(final String pathChatServiceSid) { - this.pathChatServiceSid = pathChatServiceSid; + public UserReader(final String pathchatServiceSid) { + this.pathchatServiceSid = pathchatServiceSid; } + public UserReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/Services/{ChatServiceSid}/Users"; - path = - path.replace( - "{" + "ChatServiceSid" + "}", - this.pathChatServiceSid.toString() - ); + + path = path.replace("{" + "ChatServiceSid" + "}", this.pathchatServiceSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.CONVERSATIONS.toString(), - path + HttpMethod.GET, + Domains.CONVERSATIONS.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "User read failed: Unable to connect to server" - ); + throw new ApiConnectionException("User read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "users", - response.getContent(), - User.class, - client.getObjectMapper() - ); + "users", + response.getContent(), + User.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.CONVERSATIONS.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.CONVERSATIONS.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/conversations/v1/service/UserUpdater.java b/src/main/java/com/twilio/rest/conversations/v1/service/UserUpdater.java index 970274cbab..a253a260a0 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/service/UserUpdater.java +++ b/src/main/java/com/twilio/rest/conversations/v1/service/UserUpdater.java @@ -16,6 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -26,75 +28,72 @@ import com.twilio.rest.Domains; public class UserUpdater extends Updater { - - private String pathChatServiceSid; - private String pathSid; + private String pathchatServiceSid; + private String pathsid; private User.WebhookEnabledType xTwilioWebhookEnabled; private String friendlyName; private String attributes; private String roleSid; - public UserUpdater(final String pathChatServiceSid, final String pathSid) { - this.pathChatServiceSid = pathChatServiceSid; - this.pathSid = pathSid; + public UserUpdater(final String pathchatServiceSid, final String pathsid) { + this.pathchatServiceSid = pathchatServiceSid; + this.pathsid = pathsid; } - public UserUpdater setXTwilioWebhookEnabled( - final User.WebhookEnabledType xTwilioWebhookEnabled - ) { - this.xTwilioWebhookEnabled = xTwilioWebhookEnabled; - return this; - } public UserUpdater setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + public UserUpdater setAttributes(final String attributes) { this.attributes = attributes; return this; } + public UserUpdater setRoleSid(final String roleSid) { this.roleSid = roleSid; return this; } + + public UserUpdater setXTwilioWebhookEnabled(final User.WebhookEnabledType xTwilioWebhookEnabled) { + this.xTwilioWebhookEnabled = xTwilioWebhookEnabled; + return this; + } + + @Override public User update(final TwilioRestClient client) { + String path = "/v1/Services/{ChatServiceSid}/Users/{Sid}"; - path = - path.replace( - "{" + "ChatServiceSid" + "}", - this.pathChatServiceSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "ChatServiceSid" + "}", this.pathchatServiceSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.CONVERSATIONS.toString(), - path + HttpMethod.POST, + Domains.CONVERSATIONS.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); - addPostParams(request); addHeaderParams(request); + addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "User update failed: Unable to connect to server" - ); + throw new ApiConnectionException("User update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -103,23 +102,29 @@ public User update(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + if (attributes != null) { - request.addPostParam("Attributes", attributes); + Serializer.toString(request, "Attributes", attributes, ParameterType.URLENCODED); } + + if (roleSid != null) { - request.addPostParam("RoleSid", roleSid); + Serializer.toString(request, "RoleSid", roleSid, ParameterType.URLENCODED); } + + } private void addHeaderParams(final Request request) { + if (xTwilioWebhookEnabled != null) { - request.addHeaderParam( - "X-Twilio-Webhook-Enabled", - xTwilioWebhookEnabled.toString() - ); + Serializer.toString(request, "X-Twilio-Webhook-Enabled", xTwilioWebhookEnabled, ParameterType.HEADER); } + } } diff --git a/src/main/java/com/twilio/rest/conversations/v1/service/configuration/Notification.java b/src/main/java/com/twilio/rest/conversations/v1/service/configuration/Notification.java index 058411db83..29a040f6f7 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/service/configuration/Notification.java +++ b/src/main/java/com/twilio/rest/conversations/v1/service/configuration/Notification.java @@ -18,45 +18,47 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; -import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Notification extends Resource { - private static final long serialVersionUID = 46010876689651L; - public static NotificationFetcher fetcher(final String pathChatServiceSid) { - return new NotificationFetcher(pathChatServiceSid); + public static NotificationFetcher fetcher(final String pathchatServiceSid) { + return new NotificationFetcher( + pathchatServiceSid + ); } - public static NotificationUpdater updater(final String pathChatServiceSid) { - return new NotificationUpdater(pathChatServiceSid); + + public static NotificationUpdater updater(final String pathchatServiceSid) { + return new NotificationUpdater( + pathchatServiceSid + ); } + /** * Converts a JSON String into a Notification object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Notification object represented by the provided JSON */ - public static Notification fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Notification fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Notification.class); @@ -71,14 +73,11 @@ public static Notification fromJson( * Converts a JSON InputStream into a Notification object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Notification object represented by the provided JSON */ - public static Notification fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Notification fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Notification.class); @@ -89,67 +88,53 @@ public static Notification fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; + @Getter + private final Object addedToConversation; + @Getter private final String chatServiceSid; - private final Map newMessage; - private final Map addedToConversation; - private final Map removedFromConversation; + @Getter private final Boolean logEnabled; + @Getter + private final Object newMessage; + @Getter + private final Object removedFromConversation; + @Getter private final URI url; @JsonCreator private Notification( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("chat_service_sid") final String chatServiceSid, - @JsonProperty("new_message") final Map newMessage, - @JsonProperty("added_to_conversation") final Map< - String, - Object - > addedToConversation, - @JsonProperty("removed_from_conversation") final Map< - String, - Object - > removedFromConversation, - @JsonProperty("log_enabled") final Boolean logEnabled, - @JsonProperty("url") final URI url + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("added_to_conversation") final Object addedToConversation, + @JsonProperty("chat_service_sid") final String chatServiceSid, + @JsonProperty("log_enabled") final Boolean logEnabled, + @JsonProperty("new_message") final Object newMessage, + @JsonProperty("removed_from_conversation") final Object removedFromConversation, + @JsonProperty("url") final URI url ) { this.accountSid = accountSid; + this.addedToConversation = addedToConversation; this.chatServiceSid = chatServiceSid; + this.logEnabled = logEnabled; this.newMessage = newMessage; - this.addedToConversation = addedToConversation; this.removedFromConversation = removedFromConversation; - this.logEnabled = logEnabled; this.url = url; } - public final String getAccountSid() { - return this.accountSid; - } - - public final String getChatServiceSid() { - return this.chatServiceSid; - } - - public final Map getNewMessage() { - return this.newMessage; - } - - public final Map getAddedToConversation() { - return this.addedToConversation; - } - - public final Map getRemovedFromConversation() { - return this.removedFromConversation; - } - - public final Boolean getLogEnabled() { - return this.logEnabled; - } - - public final URI getUrl() { - return this.url; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -161,31 +146,30 @@ public boolean equals(final Object o) { } Notification other = (Notification) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(chatServiceSid, other.chatServiceSid) && - Objects.equals(newMessage, other.newMessage) && - Objects.equals(addedToConversation, other.addedToConversation) && - Objects.equals( - removedFromConversation, - other.removedFromConversation - ) && - Objects.equals(logEnabled, other.logEnabled) && - Objects.equals(url, other.url) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(addedToConversation, other.addedToConversation) && + Objects.equals(chatServiceSid, other.chatServiceSid) && + Objects.equals(logEnabled, other.logEnabled) && + Objects.equals(newMessage, other.newMessage) && + Objects.equals(removedFromConversation, other.removedFromConversation) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - accountSid, - chatServiceSid, - newMessage, - addedToConversation, - removedFromConversation, - logEnabled, - url + accountSid, + addedToConversation, + chatServiceSid, + logEnabled, + newMessage, + removedFromConversation, + url ); } + + } + diff --git a/src/main/java/com/twilio/rest/conversations/v1/service/configuration/NotificationFetcher.java b/src/main/java/com/twilio/rest/conversations/v1/service/configuration/NotificationFetcher.java index 14c2c7aa02..e4c6e04b71 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/service/configuration/NotificationFetcher.java +++ b/src/main/java/com/twilio/rest/conversations/v1/service/configuration/NotificationFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.conversations.v1.service.configuration; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,52 +26,41 @@ public class NotificationFetcher extends Fetcher { - private String pathChatServiceSid; + private String pathchatServiceSid; - public NotificationFetcher(final String pathChatServiceSid) { - this.pathChatServiceSid = pathChatServiceSid; + public NotificationFetcher(final String pathchatServiceSid) { + this.pathchatServiceSid = pathchatServiceSid; } + @Override public Notification fetch(final TwilioRestClient client) { - String path = - "/v1/Services/{ChatServiceSid}/Configuration/Notifications"; - path = - path.replace( - "{" + "ChatServiceSid" + "}", - this.pathChatServiceSid.toString() - ); + String path = "/v1/Services/{ChatServiceSid}/Configuration/Notifications"; + + path = path.replace("{" + "ChatServiceSid" + "}", this.pathchatServiceSid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.CONVERSATIONS.toString(), - path + HttpMethod.GET, + Domains.CONVERSATIONS.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Notification fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Notification fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return Notification.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Notification.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/conversations/v1/service/configuration/NotificationUpdater.java b/src/main/java/com/twilio/rest/conversations/v1/service/configuration/NotificationUpdater.java index 9ff7b85bce..db20fa2ed7 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/service/configuration/NotificationUpdater.java +++ b/src/main/java/com/twilio/rest/conversations/v1/service/configuration/NotificationUpdater.java @@ -16,6 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -26,8 +28,7 @@ import com.twilio.rest.Domains; public class NotificationUpdater extends Updater { - - private String pathChatServiceSid; + private String pathchatServiceSid; private Boolean logEnabled; private Boolean newMessageEnabled; private String newMessageTemplate; @@ -42,211 +43,189 @@ public class NotificationUpdater extends Updater { private Boolean newMessageWithMediaEnabled; private String newMessageWithMediaTemplate; - public NotificationUpdater(final String pathChatServiceSid) { - this.pathChatServiceSid = pathChatServiceSid; + public NotificationUpdater(final String pathchatServiceSid) { + this.pathchatServiceSid = pathchatServiceSid; } + public NotificationUpdater setLogEnabled(final Boolean logEnabled) { this.logEnabled = logEnabled; return this; } - public NotificationUpdater setNewMessageEnabled( - final Boolean newMessageEnabled - ) { + + public NotificationUpdater setNewMessageEnabled(final Boolean newMessageEnabled) { this.newMessageEnabled = newMessageEnabled; return this; } - public NotificationUpdater setNewMessageTemplate( - final String newMessageTemplate - ) { + + public NotificationUpdater setNewMessageTemplate(final String newMessageTemplate) { this.newMessageTemplate = newMessageTemplate; return this; } - public NotificationUpdater setNewMessageSound( - final String newMessageSound - ) { + + public NotificationUpdater setNewMessageSound(final String newMessageSound) { this.newMessageSound = newMessageSound; return this; } - public NotificationUpdater setNewMessageBadgeCountEnabled( - final Boolean newMessageBadgeCountEnabled - ) { + + public NotificationUpdater setNewMessageBadgeCountEnabled(final Boolean newMessageBadgeCountEnabled) { this.newMessageBadgeCountEnabled = newMessageBadgeCountEnabled; return this; } - public NotificationUpdater setAddedToConversationEnabled( - final Boolean addedToConversationEnabled - ) { + + public NotificationUpdater setAddedToConversationEnabled(final Boolean addedToConversationEnabled) { this.addedToConversationEnabled = addedToConversationEnabled; return this; } - public NotificationUpdater setAddedToConversationTemplate( - final String addedToConversationTemplate - ) { + + public NotificationUpdater setAddedToConversationTemplate(final String addedToConversationTemplate) { this.addedToConversationTemplate = addedToConversationTemplate; return this; } - public NotificationUpdater setAddedToConversationSound( - final String addedToConversationSound - ) { + + public NotificationUpdater setAddedToConversationSound(final String addedToConversationSound) { this.addedToConversationSound = addedToConversationSound; return this; } - public NotificationUpdater setRemovedFromConversationEnabled( - final Boolean removedFromConversationEnabled - ) { + + public NotificationUpdater setRemovedFromConversationEnabled(final Boolean removedFromConversationEnabled) { this.removedFromConversationEnabled = removedFromConversationEnabled; return this; } - public NotificationUpdater setRemovedFromConversationTemplate( - final String removedFromConversationTemplate - ) { + + public NotificationUpdater setRemovedFromConversationTemplate(final String removedFromConversationTemplate) { this.removedFromConversationTemplate = removedFromConversationTemplate; return this; } - public NotificationUpdater setRemovedFromConversationSound( - final String removedFromConversationSound - ) { + + public NotificationUpdater setRemovedFromConversationSound(final String removedFromConversationSound) { this.removedFromConversationSound = removedFromConversationSound; return this; } - public NotificationUpdater setNewMessageWithMediaEnabled( - final Boolean newMessageWithMediaEnabled - ) { + + public NotificationUpdater setNewMessageWithMediaEnabled(final Boolean newMessageWithMediaEnabled) { this.newMessageWithMediaEnabled = newMessageWithMediaEnabled; return this; } - public NotificationUpdater setNewMessageWithMediaTemplate( - final String newMessageWithMediaTemplate - ) { + + public NotificationUpdater setNewMessageWithMediaTemplate(final String newMessageWithMediaTemplate) { this.newMessageWithMediaTemplate = newMessageWithMediaTemplate; return this; } + @Override public Notification update(final TwilioRestClient client) { - String path = - "/v1/Services/{ChatServiceSid}/Configuration/Notifications"; - path = - path.replace( - "{" + "ChatServiceSid" + "}", - this.pathChatServiceSid.toString() - ); + String path = "/v1/Services/{ChatServiceSid}/Configuration/Notifications"; + + path = path.replace("{" + "ChatServiceSid" + "}", this.pathchatServiceSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.CONVERSATIONS.toString(), - path + HttpMethod.POST, + Domains.CONVERSATIONS.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Notification update failed: Unable to connect to server" - ); + throw new ApiConnectionException("Notification update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Notification.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Notification.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (logEnabled != null) { - request.addPostParam("LogEnabled", logEnabled.toString()); + Serializer.toString(request, "LogEnabled", logEnabled, ParameterType.URLENCODED); } + + if (newMessageEnabled != null) { - request.addPostParam( - "NewMessage.Enabled", - newMessageEnabled.toString() - ); + Serializer.toString(request, "NewMessage.Enabled", newMessageEnabled, ParameterType.URLENCODED); } + + if (newMessageTemplate != null) { - request.addPostParam("NewMessage.Template", newMessageTemplate); + Serializer.toString(request, "NewMessage.Template", newMessageTemplate, ParameterType.URLENCODED); } + + if (newMessageSound != null) { - request.addPostParam("NewMessage.Sound", newMessageSound); + Serializer.toString(request, "NewMessage.Sound", newMessageSound, ParameterType.URLENCODED); } + + if (newMessageBadgeCountEnabled != null) { - request.addPostParam( - "NewMessage.BadgeCountEnabled", - newMessageBadgeCountEnabled.toString() - ); + Serializer.toString(request, "NewMessage.BadgeCountEnabled", newMessageBadgeCountEnabled, ParameterType.URLENCODED); } + + if (addedToConversationEnabled != null) { - request.addPostParam( - "AddedToConversation.Enabled", - addedToConversationEnabled.toString() - ); + Serializer.toString(request, "AddedToConversation.Enabled", addedToConversationEnabled, ParameterType.URLENCODED); } + + if (addedToConversationTemplate != null) { - request.addPostParam( - "AddedToConversation.Template", - addedToConversationTemplate - ); + Serializer.toString(request, "AddedToConversation.Template", addedToConversationTemplate, ParameterType.URLENCODED); } + + if (addedToConversationSound != null) { - request.addPostParam( - "AddedToConversation.Sound", - addedToConversationSound - ); + Serializer.toString(request, "AddedToConversation.Sound", addedToConversationSound, ParameterType.URLENCODED); } + + if (removedFromConversationEnabled != null) { - request.addPostParam( - "RemovedFromConversation.Enabled", - removedFromConversationEnabled.toString() - ); + Serializer.toString(request, "RemovedFromConversation.Enabled", removedFromConversationEnabled, ParameterType.URLENCODED); } + + if (removedFromConversationTemplate != null) { - request.addPostParam( - "RemovedFromConversation.Template", - removedFromConversationTemplate - ); + Serializer.toString(request, "RemovedFromConversation.Template", removedFromConversationTemplate, ParameterType.URLENCODED); } + + if (removedFromConversationSound != null) { - request.addPostParam( - "RemovedFromConversation.Sound", - removedFromConversationSound - ); + Serializer.toString(request, "RemovedFromConversation.Sound", removedFromConversationSound, ParameterType.URLENCODED); } + + if (newMessageWithMediaEnabled != null) { - request.addPostParam( - "NewMessage.WithMedia.Enabled", - newMessageWithMediaEnabled.toString() - ); + Serializer.toString(request, "NewMessage.WithMedia.Enabled", newMessageWithMediaEnabled, ParameterType.URLENCODED); } + + if (newMessageWithMediaTemplate != null) { - request.addPostParam( - "NewMessage.WithMedia.Template", - newMessageWithMediaTemplate - ); + Serializer.toString(request, "NewMessage.WithMedia.Template", newMessageWithMediaTemplate, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/conversations/v1/service/configuration/Webhook.java b/src/main/java/com/twilio/rest/conversations/v1/service/configuration/Webhook.java index 9947722db0..cb7c5cc129 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/service/configuration/Webhook.java +++ b/src/main/java/com/twilio/rest/conversations/v1/service/configuration/Webhook.java @@ -18,45 +18,70 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.util.List; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Webhook extends Resource { - private static final long serialVersionUID = 148454673918473L; - public static WebhookFetcher fetcher(final String pathChatServiceSid) { - return new WebhookFetcher(pathChatServiceSid); + public static WebhookFetcher fetcher(final String pathchatServiceSid) { + return new WebhookFetcher( + pathchatServiceSid + ); } - public static WebhookUpdater updater(final String pathChatServiceSid) { - return new WebhookUpdater(pathChatServiceSid); + + public static WebhookUpdater updater(final String pathchatServiceSid) { + return new WebhookUpdater( + pathchatServiceSid + ); } + + public enum Method { + GET("GET"), + POST("POST"); + + private final String value; + + private Method(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static Method forValue(final String value) { + return Promoter.enumFromString(value, Method.values()); + } + } + + /** * Converts a JSON String into a Webhook object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Webhook object represented by the provided JSON */ - public static Webhook fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Webhook fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Webhook.class); @@ -71,14 +96,11 @@ public static Webhook fromJson( * Converts a JSON InputStream into a Webhook object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Webhook object represented by the provided JSON */ - public static Webhook fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Webhook fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Webhook.class); @@ -89,61 +111,53 @@ public static Webhook fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; + @Getter private final String chatServiceSid; - private final URI preWebhookUrl; - private final URI postWebhookUrl; + @Getter private final List filters; + @Getter private final Webhook.Method method; + @Getter + private final URI postWebhookUrl; + @Getter + private final URI preWebhookUrl; + @Getter private final URI url; @JsonCreator private Webhook( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("chat_service_sid") final String chatServiceSid, - @JsonProperty("pre_webhook_url") final URI preWebhookUrl, - @JsonProperty("post_webhook_url") final URI postWebhookUrl, - @JsonProperty("filters") final List filters, - @JsonProperty("method") final Webhook.Method method, - @JsonProperty("url") final URI url + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("chat_service_sid") final String chatServiceSid, + @JsonProperty("filters") final List filters, + @JsonProperty("method") final Webhook.Method method, + @JsonProperty("post_webhook_url") final URI postWebhookUrl, + @JsonProperty("pre_webhook_url") final URI preWebhookUrl, + @JsonProperty("url") final URI url ) { this.accountSid = accountSid; this.chatServiceSid = chatServiceSid; - this.preWebhookUrl = preWebhookUrl; - this.postWebhookUrl = postWebhookUrl; this.filters = filters; this.method = method; + this.postWebhookUrl = postWebhookUrl; + this.preWebhookUrl = preWebhookUrl; this.url = url; } - public final String getAccountSid() { - return this.accountSid; - } - - public final String getChatServiceSid() { - return this.chatServiceSid; - } - - public final URI getPreWebhookUrl() { - return this.preWebhookUrl; - } - - public final URI getPostWebhookUrl() { - return this.postWebhookUrl; - } - - public final List getFilters() { - return this.filters; - } - - public final Webhook.Method getMethod() { - return this.method; - } - - public final URI getUrl() { - return this.url; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -155,48 +169,30 @@ public boolean equals(final Object o) { } Webhook other = (Webhook) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(chatServiceSid, other.chatServiceSid) && - Objects.equals(preWebhookUrl, other.preWebhookUrl) && - Objects.equals(postWebhookUrl, other.postWebhookUrl) && - Objects.equals(filters, other.filters) && - Objects.equals(method, other.method) && - Objects.equals(url, other.url) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(chatServiceSid, other.chatServiceSid) && + Objects.equals(filters, other.filters) && + Objects.equals(method, other.method) && + Objects.equals(postWebhookUrl, other.postWebhookUrl) && + Objects.equals(preWebhookUrl, other.preWebhookUrl) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - accountSid, - chatServiceSid, - preWebhookUrl, - postWebhookUrl, - filters, - method, - url + accountSid, + chatServiceSid, + filters, + method, + postWebhookUrl, + preWebhookUrl, + url ); } - public enum Method { - GET("GET"), - POST("POST"); - - private final String value; - - private Method(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - @JsonCreator - public static Method forValue(final String value) { - return Promoter.enumFromString(value, Method.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/conversations/v1/service/configuration/WebhookFetcher.java b/src/main/java/com/twilio/rest/conversations/v1/service/configuration/WebhookFetcher.java index 0e0d412954..573dca3d32 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/service/configuration/WebhookFetcher.java +++ b/src/main/java/com/twilio/rest/conversations/v1/service/configuration/WebhookFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.conversations.v1.service.configuration; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,48 +26,41 @@ public class WebhookFetcher extends Fetcher { - private String pathChatServiceSid; + private String pathchatServiceSid; - public WebhookFetcher(final String pathChatServiceSid) { - this.pathChatServiceSid = pathChatServiceSid; + public WebhookFetcher(final String pathchatServiceSid) { + this.pathchatServiceSid = pathchatServiceSid; } + @Override public Webhook fetch(final TwilioRestClient client) { + String path = "/v1/Services/{ChatServiceSid}/Configuration/Webhooks"; - path = - path.replace( - "{" + "ChatServiceSid" + "}", - this.pathChatServiceSid.toString() - ); + path = path.replace("{" + "ChatServiceSid" + "}", this.pathchatServiceSid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.CONVERSATIONS.toString(), - path + HttpMethod.GET, + Domains.CONVERSATIONS.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Webhook fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Webhook fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Webhook.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/conversations/v1/service/configuration/WebhookUpdater.java b/src/main/java/com/twilio/rest/conversations/v1/service/configuration/WebhookUpdater.java index de53546b8c..dd12b1a00f 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/service/configuration/WebhookUpdater.java +++ b/src/main/java/com/twilio/rest/conversations/v1/service/configuration/WebhookUpdater.java @@ -16,7 +16,9 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; import com.twilio.converter.Promoter; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,38 +27,33 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.net.URI; import java.util.List; public class WebhookUpdater extends Updater { - - private String pathChatServiceSid; + private String pathchatServiceSid; private URI preWebhookUrl; private URI postWebhookUrl; private List filters; private String method; - public WebhookUpdater(final String pathChatServiceSid) { - this.pathChatServiceSid = pathChatServiceSid; + public WebhookUpdater(final String pathchatServiceSid) { + this.pathchatServiceSid = pathchatServiceSid; } + public WebhookUpdater setPreWebhookUrl(final URI preWebhookUrl) { this.preWebhookUrl = preWebhookUrl; return this; } - public WebhookUpdater setPreWebhookUrl(final String preWebhookUrl) { - return setPreWebhookUrl(Promoter.uriFromString(preWebhookUrl)); - } public WebhookUpdater setPostWebhookUrl(final URI postWebhookUrl) { this.postWebhookUrl = postWebhookUrl; return this; } - public WebhookUpdater setPostWebhookUrl(final String postWebhookUrl) { - return setPostWebhookUrl(Promoter.uriFromString(postWebhookUrl)); - } public WebhookUpdater setFilters(final List filters) { this.filters = filters; @@ -72,38 +69,34 @@ public WebhookUpdater setMethod(final String method) { return this; } + @Override public Webhook update(final TwilioRestClient client) { + String path = "/v1/Services/{ChatServiceSid}/Configuration/Webhooks"; - path = - path.replace( - "{" + "ChatServiceSid" + "}", - this.pathChatServiceSid.toString() - ); + path = path.replace("{" + "ChatServiceSid" + "}", this.pathchatServiceSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.CONVERSATIONS.toString(), - path + HttpMethod.POST, + Domains.CONVERSATIONS.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Webhook update failed: Unable to connect to server" - ); + throw new ApiConnectionException("Webhook update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -112,19 +105,28 @@ public Webhook update(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (preWebhookUrl != null) { - request.addPostParam("PreWebhookUrl", preWebhookUrl.toString()); + Serializer.toString(request, "PreWebhookUrl", preWebhookUrl, ParameterType.URLENCODED); } + + if (postWebhookUrl != null) { - request.addPostParam("PostWebhookUrl", postWebhookUrl.toString()); + Serializer.toString(request, "PostWebhookUrl", postWebhookUrl, ParameterType.URLENCODED); } + + if (filters != null) { - for (String prop : filters) { - request.addPostParam("Filters", prop); + for (String param : filters) { + Serializer.toString(request, "Filters", param, ParameterType.URLENCODED); } } + + if (method != null) { - request.addPostParam("Method", method); + Serializer.toString(request, "Method", method, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/conversations/v1/service/conversation/Message.java b/src/main/java/com/twilio/rest/conversations/v1/service/conversation/Message.java index f2cb2f7e5f..fe0d3abd6b 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/service/conversation/Message.java +++ b/src/main/java/com/twilio/rest/conversations/v1/service/conversation/Message.java @@ -18,91 +18,114 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.List; import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Message extends Resource { - private static final long serialVersionUID = 273348594526439L; - public static MessageCreator creator( - final String pathChatServiceSid, - final String pathConversationSid - ) { - return new MessageCreator(pathChatServiceSid, pathConversationSid); + public static MessageCreator creator(final String pathchatServiceSid, final String pathconversationSid) { + return new MessageCreator( + pathchatServiceSid, pathconversationSid + ); } - public static MessageDeleter deleter( - final String pathChatServiceSid, - final String pathConversationSid, - final String pathSid - ) { + + public static MessageDeleter deleter(final String pathchatServiceSid, final String pathconversationSid, final String pathsid) { return new MessageDeleter( - pathChatServiceSid, - pathConversationSid, - pathSid + pathchatServiceSid, pathconversationSid, pathsid ); } - public static MessageFetcher fetcher( - final String pathChatServiceSid, - final String pathConversationSid, - final String pathSid - ) { + + public static MessageFetcher fetcher(final String pathchatServiceSid, final String pathconversationSid, final String pathsid) { return new MessageFetcher( - pathChatServiceSid, - pathConversationSid, - pathSid + pathchatServiceSid, pathconversationSid, pathsid ); } - public static MessageReader reader( - final String pathChatServiceSid, - final String pathConversationSid - ) { - return new MessageReader(pathChatServiceSid, pathConversationSid); + + public static MessageReader reader(final String pathchatServiceSid, final String pathconversationSid) { + return new MessageReader( + pathchatServiceSid, pathconversationSid + ); } - public static MessageUpdater updater( - final String pathChatServiceSid, - final String pathConversationSid, - final String pathSid - ) { + + public static MessageUpdater updater(final String pathchatServiceSid, final String pathconversationSid, final String pathsid) { return new MessageUpdater( - pathChatServiceSid, - pathConversationSid, - pathSid + pathchatServiceSid, pathconversationSid, pathsid ); } + + public enum WebhookEnabledType { + TRUE("true"), + FALSE("false"); + + private final String value; + + private WebhookEnabledType(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static WebhookEnabledType forValue(final String value) { + return Promoter.enumFromString(value, WebhookEnabledType.values()); + } + } + + public enum OrderType { + ASC("asc"), + DESC("desc"); + + private final String value; + + private OrderType(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static OrderType forValue(final String value) { + return Promoter.enumFromString(value, OrderType.values()); + } + } + + /** * Converts a JSON String into a Message object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Message object represented by the provided JSON */ - public static Message fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Message fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Message.class); @@ -117,14 +140,11 @@ public static Message fromJson( * Converts a JSON InputStream into a Message object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Message object represented by the provided JSON */ - public static Message fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Message fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Message.class); @@ -135,122 +155,89 @@ public static Message fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String chatServiceSid; - private final String conversationSid; - private final String sid; - private final Integer index; + @Getter + private final String attributes; + @Getter private final String author; + @Getter private final String body; - private final List> media; - private final String attributes; - private final String participantSid; + @Getter + private final String chatServiceSid; + @Getter + private final String contentSid; + @Getter + private final String conversationSid; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; - private final Map delivery; - private final URI url; + @Getter + private final Object delivery; + @Getter + private final Integer index; + @Getter private final Map links; - private final String contentSid; + @Getter + private final List media; + @Getter + private final String participantSid; + @Getter + private final String sid; + @Getter + private final URI url; @JsonCreator private Message( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("chat_service_sid") final String chatServiceSid, - @JsonProperty("conversation_sid") final String conversationSid, - @JsonProperty("sid") final String sid, - @JsonProperty("index") final Integer index, - @JsonProperty("author") final String author, - @JsonProperty("body") final String body, - @JsonProperty("media") final List> media, - @JsonProperty("attributes") final String attributes, - @JsonProperty("participant_sid") final String participantSid, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("delivery") final Map delivery, - @JsonProperty("url") final URI url, - @JsonProperty("links") final Map links, - @JsonProperty("content_sid") final String contentSid + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("attributes") final String attributes, + @JsonProperty("author") final String author, + @JsonProperty("body") final String body, + @JsonProperty("chat_service_sid") final String chatServiceSid, + @JsonProperty("content_sid") final String contentSid, + @JsonProperty("conversation_sid") final String conversationSid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("delivery") final Object delivery, + @JsonProperty("index") final Integer index, + @JsonProperty("links") final Map links, + @JsonProperty("media") final List media, + @JsonProperty("participant_sid") final String participantSid, + @JsonProperty("sid") final String sid, + @JsonProperty("url") final URI url ) { this.accountSid = accountSid; + this.attributes = attributes; + this.author = author; + this.body = body; this.chatServiceSid = chatServiceSid; + this.contentSid = contentSid; this.conversationSid = conversationSid; - this.sid = sid; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; + this.delivery = delivery; this.index = index; - this.author = author; - this.body = body; + this.links = links; this.media = media; - this.attributes = attributes; this.participantSid = participantSid; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); - this.delivery = delivery; + this.sid = sid; this.url = url; - this.links = links; - this.contentSid = contentSid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getChatServiceSid() { - return this.chatServiceSid; - } - - public final String getConversationSid() { - return this.conversationSid; - } - - public final String getSid() { - return this.sid; - } - - public final Integer getIndex() { - return this.index; - } - - public final String getAuthor() { - return this.author; - } - - public final String getBody() { - return this.body; - } - - public final List> getMedia() { - return this.media; - } - - public final String getAttributes() { - return this.attributes; - } - - public final String getParticipantSid() { - return this.participantSid; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final Map getDelivery() { - return this.delivery; - } - - public final URI getUrl() { - return this.url; - } - - public final Map getLinks() { - return this.links; - } - - public final String getContentSid() { - return this.contentSid; } @Override @@ -264,86 +251,48 @@ public boolean equals(final Object o) { } Message other = (Message) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(chatServiceSid, other.chatServiceSid) && - Objects.equals(conversationSid, other.conversationSid) && - Objects.equals(sid, other.sid) && - Objects.equals(index, other.index) && - Objects.equals(author, other.author) && - Objects.equals(body, other.body) && - Objects.equals(media, other.media) && - Objects.equals(attributes, other.attributes) && - Objects.equals(participantSid, other.participantSid) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(delivery, other.delivery) && - Objects.equals(url, other.url) && - Objects.equals(links, other.links) && - Objects.equals(contentSid, other.contentSid) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(attributes, other.attributes) && + Objects.equals(author, other.author) && + Objects.equals(body, other.body) && + Objects.equals(chatServiceSid, other.chatServiceSid) && + Objects.equals(contentSid, other.contentSid) && + Objects.equals(conversationSid, other.conversationSid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(delivery, other.delivery) && + Objects.equals(index, other.index) && + Objects.equals(links, other.links) && + Objects.equals(media, other.media) && + Objects.equals(participantSid, other.participantSid) && + Objects.equals(sid, other.sid) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - accountSid, - chatServiceSid, - conversationSid, - sid, - index, - author, - body, - media, - attributes, - participantSid, - dateCreated, - dateUpdated, - delivery, - url, - links, - contentSid + accountSid, + attributes, + author, + body, + chatServiceSid, + contentSid, + conversationSid, + dateCreated, + dateUpdated, + delivery, + index, + links, + media, + participantSid, + sid, + url ); } - public enum OrderType { - ASC("asc"), - DESC("desc"); - - private final String value; - - private OrderType(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static OrderType forValue(final String value) { - return Promoter.enumFromString(value, OrderType.values()); - } - } - - public enum WebhookEnabledType { - TRUE("true"), - FALSE("false"); - - private final String value; - - private WebhookEnabledType(final String value) { - this.value = value; - } - public String toString() { - return value; - } - - @JsonCreator - public static WebhookEnabledType forValue(final String value) { - return Promoter.enumFromString(value, WebhookEnabledType.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/conversations/v1/service/conversation/MessageCreator.java b/src/main/java/com/twilio/rest/conversations/v1/service/conversation/MessageCreator.java index febbe4ed2a..1537e47010 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/service/conversation/MessageCreator.java +++ b/src/main/java/com/twilio/rest/conversations/v1/service/conversation/MessageCreator.java @@ -14,8 +14,11 @@ package com.twilio.rest.conversations.v1.service.conversation; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -24,12 +27,13 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.time.ZonedDateTime; public class MessageCreator extends Creator { - private String pathChatServiceSid; - private String pathConversationSid; + private String pathchatServiceSid; + private String pathconversationSid; private Message.WebhookEnabledType xTwilioWebhookEnabled; private String author; private String body; @@ -41,105 +45,101 @@ public class MessageCreator extends Creator { private String contentVariables; private String subject; - public MessageCreator( - final String pathChatServiceSid, - final String pathConversationSid - ) { - this.pathChatServiceSid = pathChatServiceSid; - this.pathConversationSid = pathConversationSid; + public MessageCreator(final String pathchatServiceSid, final String pathconversationSid) { + this.pathchatServiceSid = pathchatServiceSid; + this.pathconversationSid = pathconversationSid; } - public MessageCreator setXTwilioWebhookEnabled( - final Message.WebhookEnabledType xTwilioWebhookEnabled - ) { - this.xTwilioWebhookEnabled = xTwilioWebhookEnabled; - return this; - } public MessageCreator setAuthor(final String author) { this.author = author; return this; } + public MessageCreator setBody(final String body) { this.body = body; return this; } + public MessageCreator setDateCreated(final ZonedDateTime dateCreated) { this.dateCreated = dateCreated; return this; } + public MessageCreator setDateUpdated(final ZonedDateTime dateUpdated) { this.dateUpdated = dateUpdated; return this; } + public MessageCreator setAttributes(final String attributes) { this.attributes = attributes; return this; } + public MessageCreator setMediaSid(final String mediaSid) { this.mediaSid = mediaSid; return this; } + public MessageCreator setContentSid(final String contentSid) { this.contentSid = contentSid; return this; } + public MessageCreator setContentVariables(final String contentVariables) { this.contentVariables = contentVariables; return this; } + public MessageCreator setSubject(final String subject) { this.subject = subject; return this; } + + public MessageCreator setXTwilioWebhookEnabled(final Message.WebhookEnabledType xTwilioWebhookEnabled) { + this.xTwilioWebhookEnabled = xTwilioWebhookEnabled; + return this; + } + + @Override public Message create(final TwilioRestClient client) { - String path = - "/v1/Services/{ChatServiceSid}/Conversations/{ConversationSid}/Messages"; - path = - path.replace( - "{" + "ChatServiceSid" + "}", - this.pathChatServiceSid.toString() - ); - path = - path.replace( - "{" + "ConversationSid" + "}", - this.pathConversationSid.toString() - ); + String path = "/v1/Services/{ChatServiceSid}/Conversations/{ConversationSid}/Messages"; + + path = path.replace("{" + "ChatServiceSid" + "}", this.pathchatServiceSid.toString()); + path = path.replace("{" + "ConversationSid" + "}", this.pathconversationSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.CONVERSATIONS.toString(), - path + HttpMethod.POST, + Domains.CONVERSATIONS.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); - addPostParams(request); addHeaderParams(request); + addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Message creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("Message creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -148,47 +148,59 @@ public Message create(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (author != null) { - request.addPostParam("Author", author); + Serializer.toString(request, "Author", author, ParameterType.URLENCODED); } + + if (body != null) { - request.addPostParam("Body", body); + Serializer.toString(request, "Body", body, ParameterType.URLENCODED); } + + if (dateCreated != null) { - request.addPostParam( - "DateCreated", - dateCreated.toInstant().toString() - ); + Serializer.toString(request, "DateCreated", dateCreated, ParameterType.URLENCODED); } + + if (dateUpdated != null) { - request.addPostParam( - "DateUpdated", - dateUpdated.toInstant().toString() - ); + Serializer.toString(request, "DateUpdated", dateUpdated, ParameterType.URLENCODED); } + + if (attributes != null) { - request.addPostParam("Attributes", attributes); + Serializer.toString(request, "Attributes", attributes, ParameterType.URLENCODED); } + + if (mediaSid != null) { - request.addPostParam("MediaSid", mediaSid); + Serializer.toString(request, "MediaSid", mediaSid, ParameterType.URLENCODED); } + + if (contentSid != null) { - request.addPostParam("ContentSid", contentSid); + Serializer.toString(request, "ContentSid", contentSid, ParameterType.URLENCODED); } + + if (contentVariables != null) { - request.addPostParam("ContentVariables", contentVariables); + Serializer.toString(request, "ContentVariables", contentVariables, ParameterType.URLENCODED); } + + if (subject != null) { - request.addPostParam("Subject", subject); + Serializer.toString(request, "Subject", subject, ParameterType.URLENCODED); } + + } private void addHeaderParams(final Request request) { + if (xTwilioWebhookEnabled != null) { - request.addHeaderParam( - "X-Twilio-Webhook-Enabled", - xTwilioWebhookEnabled.toString() - ); + Serializer.toString(request, "X-Twilio-Webhook-Enabled", xTwilioWebhookEnabled, ParameterType.HEADER); } + } } diff --git a/src/main/java/com/twilio/rest/conversations/v1/service/conversation/MessageDeleter.java b/src/main/java/com/twilio/rest/conversations/v1/service/conversation/MessageDeleter.java index d0bf7257da..c5fe512ee7 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/service/conversation/MessageDeleter.java +++ b/src/main/java/com/twilio/rest/conversations/v1/service/conversation/MessageDeleter.java @@ -15,7 +15,8 @@ package com.twilio.rest.conversations.v1.service.conversation; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,68 +28,52 @@ public class MessageDeleter extends Deleter { - private String pathChatServiceSid; - private String pathConversationSid; - private String pathSid; + private String pathchatServiceSid; + private String pathconversationSid; + private String pathsid; private Message.WebhookEnabledType xTwilioWebhookEnabled; - public MessageDeleter( - final String pathChatServiceSid, - final String pathConversationSid, - final String pathSid - ) { - this.pathChatServiceSid = pathChatServiceSid; - this.pathConversationSid = pathConversationSid; - this.pathSid = pathSid; + public MessageDeleter(final String pathchatServiceSid, final String pathconversationSid, final String pathsid) { + this.pathchatServiceSid = pathchatServiceSid; + this.pathconversationSid = pathconversationSid; + this.pathsid = pathsid; } - public MessageDeleter setXTwilioWebhookEnabled( - final Message.WebhookEnabledType xTwilioWebhookEnabled - ) { + + public MessageDeleter setXTwilioWebhookEnabled(final Message.WebhookEnabledType xTwilioWebhookEnabled) { this.xTwilioWebhookEnabled = xTwilioWebhookEnabled; return this; } + @Override public boolean delete(final TwilioRestClient client) { - String path = - "/v1/Services/{ChatServiceSid}/Conversations/{ConversationSid}/Messages/{Sid}"; - path = - path.replace( - "{" + "ChatServiceSid" + "}", - this.pathChatServiceSid.toString() - ); - path = - path.replace( - "{" + "ConversationSid" + "}", - this.pathConversationSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/v1/Services/{ChatServiceSid}/Conversations/{ConversationSid}/Messages/{Sid}"; + + path = path.replace("{" + "ChatServiceSid" + "}", this.pathchatServiceSid.toString()); + path = path.replace("{" + "ConversationSid" + "}", this.pathconversationSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.CONVERSATIONS.toString(), - path + HttpMethod.DELETE, + Domains.CONVERSATIONS.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addHeaderParams(request); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Message delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("Message delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -96,11 +81,10 @@ public boolean delete(final TwilioRestClient client) { } private void addHeaderParams(final Request request) { + if (xTwilioWebhookEnabled != null) { - request.addHeaderParam( - "X-Twilio-Webhook-Enabled", - xTwilioWebhookEnabled.toString() - ); + Serializer.toString(request, "X-Twilio-Webhook-Enabled", xTwilioWebhookEnabled, ParameterType.HEADER); } + } } diff --git a/src/main/java/com/twilio/rest/conversations/v1/service/conversation/MessageFetcher.java b/src/main/java/com/twilio/rest/conversations/v1/service/conversation/MessageFetcher.java index 47486d2344..07a8fe6125 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/service/conversation/MessageFetcher.java +++ b/src/main/java/com/twilio/rest/conversations/v1/service/conversation/MessageFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.conversations.v1.service.conversation; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,63 +26,47 @@ public class MessageFetcher extends Fetcher { - private String pathChatServiceSid; - private String pathConversationSid; - private String pathSid; + private String pathchatServiceSid; + private String pathconversationSid; + private String pathsid; - public MessageFetcher( - final String pathChatServiceSid, - final String pathConversationSid, - final String pathSid - ) { - this.pathChatServiceSid = pathChatServiceSid; - this.pathConversationSid = pathConversationSid; - this.pathSid = pathSid; + public MessageFetcher(final String pathchatServiceSid, final String pathconversationSid, final String pathsid) { + this.pathchatServiceSid = pathchatServiceSid; + this.pathconversationSid = pathconversationSid; + this.pathsid = pathsid; } + @Override public Message fetch(final TwilioRestClient client) { - String path = - "/v1/Services/{ChatServiceSid}/Conversations/{ConversationSid}/Messages/{Sid}"; - path = - path.replace( - "{" + "ChatServiceSid" + "}", - this.pathChatServiceSid.toString() - ); - path = - path.replace( - "{" + "ConversationSid" + "}", - this.pathConversationSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/v1/Services/{ChatServiceSid}/Conversations/{ConversationSid}/Messages/{Sid}"; + + path = path.replace("{" + "ChatServiceSid" + "}", this.pathchatServiceSid.toString()); + path = path.replace("{" + "ConversationSid" + "}", this.pathconversationSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.CONVERSATIONS.toString(), - path + HttpMethod.GET, + Domains.CONVERSATIONS.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Message fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Message fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Message.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/conversations/v1/service/conversation/MessageReader.java b/src/main/java/com/twilio/rest/conversations/v1/service/conversation/MessageReader.java index 06f03328d3..5e15534d1c 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/service/conversation/MessageReader.java +++ b/src/main/java/com/twilio/rest/conversations/v1/service/conversation/MessageReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,135 +30,103 @@ public class MessageReader extends Reader { - private String pathChatServiceSid; - private String pathConversationSid; + private String pathchatServiceSid; + private String pathconversationSid; private Message.OrderType order; private Long pageSize; - public MessageReader( - final String pathChatServiceSid, - final String pathConversationSid - ) { - this.pathChatServiceSid = pathChatServiceSid; - this.pathConversationSid = pathConversationSid; + public MessageReader(final String pathchatServiceSid, final String pathconversationSid) { + this.pathchatServiceSid = pathchatServiceSid; + this.pathconversationSid = pathconversationSid; } + public MessageReader setOrder(final Message.OrderType order) { this.order = order; return this; } + public MessageReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { - String path = - "/v1/Services/{ChatServiceSid}/Conversations/{ConversationSid}/Messages"; - path = - path.replace( - "{" + "ChatServiceSid" + "}", - this.pathChatServiceSid.toString() - ); - path = - path.replace( - "{" + "ConversationSid" + "}", - this.pathConversationSid.toString() - ); + + String path = "/v1/Services/{ChatServiceSid}/Conversations/{ConversationSid}/Messages"; + + path = path.replace("{" + "ChatServiceSid" + "}", this.pathchatServiceSid.toString()); + path = path.replace("{" + "ConversationSid" + "}", this.pathconversationSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.CONVERSATIONS.toString(), - path + HttpMethod.GET, + Domains.CONVERSATIONS.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Message read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Message read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "messages", - response.getContent(), - Message.class, - client.getObjectMapper() - ); + "messages", + response.getContent(), + Message.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.CONVERSATIONS.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.CONVERSATIONS.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (order != null) { - request.addQueryParam("Order", order.toString()); + Serializer.toString(request, "Order", order, ParameterType.QUERY); } + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/conversations/v1/service/conversation/MessageUpdater.java b/src/main/java/com/twilio/rest/conversations/v1/service/conversation/MessageUpdater.java index ae92ffb275..cd8a3b6181 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/service/conversation/MessageUpdater.java +++ b/src/main/java/com/twilio/rest/conversations/v1/service/conversation/MessageUpdater.java @@ -16,6 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -24,13 +26,13 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.time.ZonedDateTime; public class MessageUpdater extends Updater { - - private String pathChatServiceSid; - private String pathConversationSid; - private String pathSid; + private String pathchatServiceSid; + private String pathconversationSid; + private String pathsid; private Message.WebhookEnabledType xTwilioWebhookEnabled; private String author; private String body; @@ -39,93 +41,85 @@ public class MessageUpdater extends Updater { private String attributes; private String subject; - public MessageUpdater( - final String pathChatServiceSid, - final String pathConversationSid, - final String pathSid - ) { - this.pathChatServiceSid = pathChatServiceSid; - this.pathConversationSid = pathConversationSid; - this.pathSid = pathSid; + public MessageUpdater(final String pathchatServiceSid, final String pathconversationSid, final String pathsid) { + this.pathchatServiceSid = pathchatServiceSid; + this.pathconversationSid = pathconversationSid; + this.pathsid = pathsid; } - public MessageUpdater setXTwilioWebhookEnabled( - final Message.WebhookEnabledType xTwilioWebhookEnabled - ) { - this.xTwilioWebhookEnabled = xTwilioWebhookEnabled; - return this; - } public MessageUpdater setAuthor(final String author) { this.author = author; return this; } + public MessageUpdater setBody(final String body) { this.body = body; return this; } + public MessageUpdater setDateCreated(final ZonedDateTime dateCreated) { this.dateCreated = dateCreated; return this; } + public MessageUpdater setDateUpdated(final ZonedDateTime dateUpdated) { this.dateUpdated = dateUpdated; return this; } + public MessageUpdater setAttributes(final String attributes) { this.attributes = attributes; return this; } + public MessageUpdater setSubject(final String subject) { this.subject = subject; return this; } + + public MessageUpdater setXTwilioWebhookEnabled(final Message.WebhookEnabledType xTwilioWebhookEnabled) { + this.xTwilioWebhookEnabled = xTwilioWebhookEnabled; + return this; + } + + @Override public Message update(final TwilioRestClient client) { - String path = - "/v1/Services/{ChatServiceSid}/Conversations/{ConversationSid}/Messages/{Sid}"; - path = - path.replace( - "{" + "ChatServiceSid" + "}", - this.pathChatServiceSid.toString() - ); - path = - path.replace( - "{" + "ConversationSid" + "}", - this.pathConversationSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/v1/Services/{ChatServiceSid}/Conversations/{ConversationSid}/Messages/{Sid}"; + + path = path.replace("{" + "ChatServiceSid" + "}", this.pathchatServiceSid.toString()); + path = path.replace("{" + "ConversationSid" + "}", this.pathconversationSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.CONVERSATIONS.toString(), - path + HttpMethod.POST, + Domains.CONVERSATIONS.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); - addPostParams(request); addHeaderParams(request); + addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Message update failed: Unable to connect to server" - ); + throw new ApiConnectionException("Message update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -134,38 +128,44 @@ public Message update(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (author != null) { - request.addPostParam("Author", author); + Serializer.toString(request, "Author", author, ParameterType.URLENCODED); } + + if (body != null) { - request.addPostParam("Body", body); + Serializer.toString(request, "Body", body, ParameterType.URLENCODED); } + + if (dateCreated != null) { - request.addPostParam( - "DateCreated", - dateCreated.toInstant().toString() - ); + Serializer.toString(request, "DateCreated", dateCreated, ParameterType.URLENCODED); } + + if (dateUpdated != null) { - request.addPostParam( - "DateUpdated", - dateUpdated.toInstant().toString() - ); + Serializer.toString(request, "DateUpdated", dateUpdated, ParameterType.URLENCODED); } + + if (attributes != null) { - request.addPostParam("Attributes", attributes); + Serializer.toString(request, "Attributes", attributes, ParameterType.URLENCODED); } + + if (subject != null) { - request.addPostParam("Subject", subject); + Serializer.toString(request, "Subject", subject, ParameterType.URLENCODED); } + + } private void addHeaderParams(final Request request) { + if (xTwilioWebhookEnabled != null) { - request.addHeaderParam( - "X-Twilio-Webhook-Enabled", - xTwilioWebhookEnabled.toString() - ); + Serializer.toString(request, "X-Twilio-Webhook-Enabled", xTwilioWebhookEnabled, ParameterType.HEADER); } + } } diff --git a/src/main/java/com/twilio/rest/conversations/v1/service/conversation/Participant.java b/src/main/java/com/twilio/rest/conversations/v1/service/conversation/Participant.java index 57bff1f68a..eb357dde99 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/service/conversation/Participant.java +++ b/src/main/java/com/twilio/rest/conversations/v1/service/conversation/Participant.java @@ -18,90 +18,92 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; -import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Participant extends Resource { - private static final long serialVersionUID = 110295013528965L; - public static ParticipantCreator creator( - final String pathChatServiceSid, - final String pathConversationSid - ) { - return new ParticipantCreator(pathChatServiceSid, pathConversationSid); + public static ParticipantCreator creator(final String pathchatServiceSid, final String pathconversationSid) { + return new ParticipantCreator( + pathchatServiceSid, pathconversationSid + ); } - public static ParticipantDeleter deleter( - final String pathChatServiceSid, - final String pathConversationSid, - final String pathSid - ) { + + public static ParticipantDeleter deleter(final String pathchatServiceSid, final String pathconversationSid, final String pathsid) { return new ParticipantDeleter( - pathChatServiceSid, - pathConversationSid, - pathSid + pathchatServiceSid, pathconversationSid, pathsid ); } - public static ParticipantFetcher fetcher( - final String pathChatServiceSid, - final String pathConversationSid, - final String pathSid - ) { + + public static ParticipantFetcher fetcher(final String pathchatServiceSid, final String pathconversationSid, final String pathsid) { return new ParticipantFetcher( - pathChatServiceSid, - pathConversationSid, - pathSid + pathchatServiceSid, pathconversationSid, pathsid ); } - public static ParticipantReader reader( - final String pathChatServiceSid, - final String pathConversationSid - ) { - return new ParticipantReader(pathChatServiceSid, pathConversationSid); + + public static ParticipantReader reader(final String pathchatServiceSid, final String pathconversationSid) { + return new ParticipantReader( + pathchatServiceSid, pathconversationSid + ); } - public static ParticipantUpdater updater( - final String pathChatServiceSid, - final String pathConversationSid, - final String pathSid - ) { + + public static ParticipantUpdater updater(final String pathchatServiceSid, final String pathconversationSid, final String pathsid) { return new ParticipantUpdater( - pathChatServiceSid, - pathConversationSid, - pathSid + pathchatServiceSid, pathconversationSid, pathsid ); } + + public enum WebhookEnabledType { + TRUE("true"), + FALSE("false"); + + private final String value; + + private WebhookEnabledType(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static WebhookEnabledType forValue(final String value) { + return Promoter.enumFromString(value, WebhookEnabledType.values()); + } + } + + /** * Converts a JSON String into a Participant object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Participant object represented by the provided JSON */ - public static Participant fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Participant fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Participant.class); @@ -116,14 +118,11 @@ public static Participant fromJson( * Converts a JSON InputStream into a Participant object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Participant object represented by the provided JSON */ - public static Participant fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Participant fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Participant.class); @@ -134,106 +133,77 @@ public static Participant fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; + @Getter + private final String attributes; + @Getter private final String chatServiceSid; + @Getter private final String conversationSid; - private final String sid; - private final String identity; - private final String attributes; - private final Map messagingBinding; - private final String roleSid; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; - private final URI url; + @Getter + private final String identity; + @Getter private final Integer lastReadMessageIndex; + @Getter private final String lastReadTimestamp; + @Getter + private final Object messagingBinding; + @Getter + private final String roleSid; + @Getter + private final String sid; + @Getter + private final URI url; @JsonCreator private Participant( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("chat_service_sid") final String chatServiceSid, - @JsonProperty("conversation_sid") final String conversationSid, - @JsonProperty("sid") final String sid, - @JsonProperty("identity") final String identity, - @JsonProperty("attributes") final String attributes, - @JsonProperty("messaging_binding") final Map< - String, - Object - > messagingBinding, - @JsonProperty("role_sid") final String roleSid, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("url") final URI url, - @JsonProperty( - "last_read_message_index" - ) final Integer lastReadMessageIndex, - @JsonProperty("last_read_timestamp") final String lastReadTimestamp + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("attributes") final String attributes, + @JsonProperty("chat_service_sid") final String chatServiceSid, + @JsonProperty("conversation_sid") final String conversationSid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("identity") final String identity, + @JsonProperty("last_read_message_index") final Integer lastReadMessageIndex, + @JsonProperty("last_read_timestamp") final String lastReadTimestamp, + @JsonProperty("messaging_binding") final Object messagingBinding, + @JsonProperty("role_sid") final String roleSid, + @JsonProperty("sid") final String sid, + @JsonProperty("url") final URI url ) { this.accountSid = accountSid; + this.attributes = attributes; this.chatServiceSid = chatServiceSid; this.conversationSid = conversationSid; - this.sid = sid; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.identity = identity; - this.attributes = attributes; + this.lastReadMessageIndex = lastReadMessageIndex; + this.lastReadTimestamp = lastReadTimestamp; this.messagingBinding = messagingBinding; this.roleSid = roleSid; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); + this.sid = sid; this.url = url; - this.lastReadMessageIndex = lastReadMessageIndex; - this.lastReadTimestamp = lastReadTimestamp; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getChatServiceSid() { - return this.chatServiceSid; - } - - public final String getConversationSid() { - return this.conversationSid; - } - - public final String getSid() { - return this.sid; - } - - public final String getIdentity() { - return this.identity; - } - - public final String getAttributes() { - return this.attributes; - } - - public final Map getMessagingBinding() { - return this.messagingBinding; - } - - public final String getRoleSid() { - return this.roleSid; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final URI getUrl() { - return this.url; - } - - public final Integer getLastReadMessageIndex() { - return this.lastReadMessageIndex; - } - - public final String getLastReadTimestamp() { - return this.lastReadTimestamp; } @Override @@ -247,60 +217,42 @@ public boolean equals(final Object o) { } Participant other = (Participant) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(chatServiceSid, other.chatServiceSid) && - Objects.equals(conversationSid, other.conversationSid) && - Objects.equals(sid, other.sid) && - Objects.equals(identity, other.identity) && - Objects.equals(attributes, other.attributes) && - Objects.equals(messagingBinding, other.messagingBinding) && - Objects.equals(roleSid, other.roleSid) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(url, other.url) && - Objects.equals(lastReadMessageIndex, other.lastReadMessageIndex) && - Objects.equals(lastReadTimestamp, other.lastReadTimestamp) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(attributes, other.attributes) && + Objects.equals(chatServiceSid, other.chatServiceSid) && + Objects.equals(conversationSid, other.conversationSid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(identity, other.identity) && + Objects.equals(lastReadMessageIndex, other.lastReadMessageIndex) && + Objects.equals(lastReadTimestamp, other.lastReadTimestamp) && + Objects.equals(messagingBinding, other.messagingBinding) && + Objects.equals(roleSid, other.roleSid) && + Objects.equals(sid, other.sid) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - accountSid, - chatServiceSid, - conversationSid, - sid, - identity, - attributes, - messagingBinding, - roleSid, - dateCreated, - dateUpdated, - url, - lastReadMessageIndex, - lastReadTimestamp + accountSid, + attributes, + chatServiceSid, + conversationSid, + dateCreated, + dateUpdated, + identity, + lastReadMessageIndex, + lastReadTimestamp, + messagingBinding, + roleSid, + sid, + url ); } - public enum WebhookEnabledType { - TRUE("true"), - FALSE("false"); - - private final String value; - - private WebhookEnabledType(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - @JsonCreator - public static WebhookEnabledType forValue(final String value) { - return Promoter.enumFromString(value, WebhookEnabledType.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/conversations/v1/service/conversation/ParticipantCreator.java b/src/main/java/com/twilio/rest/conversations/v1/service/conversation/ParticipantCreator.java index a2e4c531b6..4e03a438ba 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/service/conversation/ParticipantCreator.java +++ b/src/main/java/com/twilio/rest/conversations/v1/service/conversation/ParticipantCreator.java @@ -14,8 +14,11 @@ package com.twilio.rest.conversations.v1.service.conversation; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -24,12 +27,13 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.time.ZonedDateTime; public class ParticipantCreator extends Creator { - private String pathChatServiceSid; - private String pathConversationSid; + private String pathchatServiceSid; + private String pathconversationSid; private Participant.WebhookEnabledType xTwilioWebhookEnabled; private String identity; private String messagingBindingAddress; @@ -40,165 +44,151 @@ public class ParticipantCreator extends Creator { private String messagingBindingProjectedAddress; private String roleSid; - public ParticipantCreator( - final String pathChatServiceSid, - final String pathConversationSid - ) { - this.pathChatServiceSid = pathChatServiceSid; - this.pathConversationSid = pathConversationSid; + public ParticipantCreator(final String pathchatServiceSid, final String pathconversationSid) { + this.pathchatServiceSid = pathchatServiceSid; + this.pathconversationSid = pathconversationSid; } - public ParticipantCreator setXTwilioWebhookEnabled( - final Participant.WebhookEnabledType xTwilioWebhookEnabled - ) { - this.xTwilioWebhookEnabled = xTwilioWebhookEnabled; - return this; - } public ParticipantCreator setIdentity(final String identity) { this.identity = identity; return this; } - public ParticipantCreator setMessagingBindingAddress( - final String messagingBindingAddress - ) { + + public ParticipantCreator setMessagingBindingAddress(final String messagingBindingAddress) { this.messagingBindingAddress = messagingBindingAddress; return this; } - public ParticipantCreator setMessagingBindingProxyAddress( - final String messagingBindingProxyAddress - ) { + + public ParticipantCreator setMessagingBindingProxyAddress(final String messagingBindingProxyAddress) { this.messagingBindingProxyAddress = messagingBindingProxyAddress; return this; } + public ParticipantCreator setDateCreated(final ZonedDateTime dateCreated) { this.dateCreated = dateCreated; return this; } + public ParticipantCreator setDateUpdated(final ZonedDateTime dateUpdated) { this.dateUpdated = dateUpdated; return this; } + public ParticipantCreator setAttributes(final String attributes) { this.attributes = attributes; return this; } - public ParticipantCreator setMessagingBindingProjectedAddress( - final String messagingBindingProjectedAddress - ) { - this.messagingBindingProjectedAddress = - messagingBindingProjectedAddress; + + public ParticipantCreator setMessagingBindingProjectedAddress(final String messagingBindingProjectedAddress) { + this.messagingBindingProjectedAddress = messagingBindingProjectedAddress; return this; } + public ParticipantCreator setRoleSid(final String roleSid) { this.roleSid = roleSid; return this; } + + public ParticipantCreator setXTwilioWebhookEnabled(final Participant.WebhookEnabledType xTwilioWebhookEnabled) { + this.xTwilioWebhookEnabled = xTwilioWebhookEnabled; + return this; + } + + @Override public Participant create(final TwilioRestClient client) { - String path = - "/v1/Services/{ChatServiceSid}/Conversations/{ConversationSid}/Participants"; - path = - path.replace( - "{" + "ChatServiceSid" + "}", - this.pathChatServiceSid.toString() - ); - path = - path.replace( - "{" + "ConversationSid" + "}", - this.pathConversationSid.toString() - ); + String path = "/v1/Services/{ChatServiceSid}/Conversations/{ConversationSid}/Participants"; + + path = path.replace("{" + "ChatServiceSid" + "}", this.pathchatServiceSid.toString()); + path = path.replace("{" + "ConversationSid" + "}", this.pathconversationSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.CONVERSATIONS.toString(), - path + HttpMethod.POST, + Domains.CONVERSATIONS.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); - addPostParams(request); addHeaderParams(request); + addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Participant creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("Participant creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Participant.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Participant.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (identity != null) { - request.addPostParam("Identity", identity); + Serializer.toString(request, "Identity", identity, ParameterType.URLENCODED); } + + if (messagingBindingAddress != null) { - request.addPostParam( - "MessagingBinding.Address", - messagingBindingAddress - ); + Serializer.toString(request, "MessagingBinding.Address", messagingBindingAddress, ParameterType.URLENCODED); } + + if (messagingBindingProxyAddress != null) { - request.addPostParam( - "MessagingBinding.ProxyAddress", - messagingBindingProxyAddress - ); + Serializer.toString(request, "MessagingBinding.ProxyAddress", messagingBindingProxyAddress, ParameterType.URLENCODED); } + + if (dateCreated != null) { - request.addPostParam( - "DateCreated", - dateCreated.toInstant().toString() - ); + Serializer.toString(request, "DateCreated", dateCreated, ParameterType.URLENCODED); } + + if (dateUpdated != null) { - request.addPostParam( - "DateUpdated", - dateUpdated.toInstant().toString() - ); + Serializer.toString(request, "DateUpdated", dateUpdated, ParameterType.URLENCODED); } + + if (attributes != null) { - request.addPostParam("Attributes", attributes); + Serializer.toString(request, "Attributes", attributes, ParameterType.URLENCODED); } + + if (messagingBindingProjectedAddress != null) { - request.addPostParam( - "MessagingBinding.ProjectedAddress", - messagingBindingProjectedAddress - ); + Serializer.toString(request, "MessagingBinding.ProjectedAddress", messagingBindingProjectedAddress, ParameterType.URLENCODED); } + + if (roleSid != null) { - request.addPostParam("RoleSid", roleSid); + Serializer.toString(request, "RoleSid", roleSid, ParameterType.URLENCODED); } + + } private void addHeaderParams(final Request request) { + if (xTwilioWebhookEnabled != null) { - request.addHeaderParam( - "X-Twilio-Webhook-Enabled", - xTwilioWebhookEnabled.toString() - ); + Serializer.toString(request, "X-Twilio-Webhook-Enabled", xTwilioWebhookEnabled, ParameterType.HEADER); } + } } diff --git a/src/main/java/com/twilio/rest/conversations/v1/service/conversation/ParticipantDeleter.java b/src/main/java/com/twilio/rest/conversations/v1/service/conversation/ParticipantDeleter.java index c9b19e4122..f3f293260d 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/service/conversation/ParticipantDeleter.java +++ b/src/main/java/com/twilio/rest/conversations/v1/service/conversation/ParticipantDeleter.java @@ -15,7 +15,8 @@ package com.twilio.rest.conversations.v1.service.conversation; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,68 +28,52 @@ public class ParticipantDeleter extends Deleter { - private String pathChatServiceSid; - private String pathConversationSid; - private String pathSid; + private String pathchatServiceSid; + private String pathconversationSid; + private String pathsid; private Participant.WebhookEnabledType xTwilioWebhookEnabled; - public ParticipantDeleter( - final String pathChatServiceSid, - final String pathConversationSid, - final String pathSid - ) { - this.pathChatServiceSid = pathChatServiceSid; - this.pathConversationSid = pathConversationSid; - this.pathSid = pathSid; + public ParticipantDeleter(final String pathchatServiceSid, final String pathconversationSid, final String pathsid) { + this.pathchatServiceSid = pathchatServiceSid; + this.pathconversationSid = pathconversationSid; + this.pathsid = pathsid; } - public ParticipantDeleter setXTwilioWebhookEnabled( - final Participant.WebhookEnabledType xTwilioWebhookEnabled - ) { + + public ParticipantDeleter setXTwilioWebhookEnabled(final Participant.WebhookEnabledType xTwilioWebhookEnabled) { this.xTwilioWebhookEnabled = xTwilioWebhookEnabled; return this; } + @Override public boolean delete(final TwilioRestClient client) { - String path = - "/v1/Services/{ChatServiceSid}/Conversations/{ConversationSid}/Participants/{Sid}"; - path = - path.replace( - "{" + "ChatServiceSid" + "}", - this.pathChatServiceSid.toString() - ); - path = - path.replace( - "{" + "ConversationSid" + "}", - this.pathConversationSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/v1/Services/{ChatServiceSid}/Conversations/{ConversationSid}/Participants/{Sid}"; + + path = path.replace("{" + "ChatServiceSid" + "}", this.pathchatServiceSid.toString()); + path = path.replace("{" + "ConversationSid" + "}", this.pathconversationSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.CONVERSATIONS.toString(), - path + HttpMethod.DELETE, + Domains.CONVERSATIONS.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addHeaderParams(request); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Participant delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("Participant delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -96,11 +81,10 @@ public boolean delete(final TwilioRestClient client) { } private void addHeaderParams(final Request request) { + if (xTwilioWebhookEnabled != null) { - request.addHeaderParam( - "X-Twilio-Webhook-Enabled", - xTwilioWebhookEnabled.toString() - ); + Serializer.toString(request, "X-Twilio-Webhook-Enabled", xTwilioWebhookEnabled, ParameterType.HEADER); } + } } diff --git a/src/main/java/com/twilio/rest/conversations/v1/service/conversation/ParticipantFetcher.java b/src/main/java/com/twilio/rest/conversations/v1/service/conversation/ParticipantFetcher.java index 9855bee519..85f3bb8f5d 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/service/conversation/ParticipantFetcher.java +++ b/src/main/java/com/twilio/rest/conversations/v1/service/conversation/ParticipantFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.conversations.v1.service.conversation; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,66 +26,47 @@ public class ParticipantFetcher extends Fetcher { - private String pathChatServiceSid; - private String pathConversationSid; - private String pathSid; + private String pathchatServiceSid; + private String pathconversationSid; + private String pathsid; - public ParticipantFetcher( - final String pathChatServiceSid, - final String pathConversationSid, - final String pathSid - ) { - this.pathChatServiceSid = pathChatServiceSid; - this.pathConversationSid = pathConversationSid; - this.pathSid = pathSid; + public ParticipantFetcher(final String pathchatServiceSid, final String pathconversationSid, final String pathsid) { + this.pathchatServiceSid = pathchatServiceSid; + this.pathconversationSid = pathconversationSid; + this.pathsid = pathsid; } + @Override public Participant fetch(final TwilioRestClient client) { - String path = - "/v1/Services/{ChatServiceSid}/Conversations/{ConversationSid}/Participants/{Sid}"; - path = - path.replace( - "{" + "ChatServiceSid" + "}", - this.pathChatServiceSid.toString() - ); - path = - path.replace( - "{" + "ConversationSid" + "}", - this.pathConversationSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/v1/Services/{ChatServiceSid}/Conversations/{ConversationSid}/Participants/{Sid}"; + + path = path.replace("{" + "ChatServiceSid" + "}", this.pathchatServiceSid.toString()); + path = path.replace("{" + "ConversationSid" + "}", this.pathconversationSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.CONVERSATIONS.toString(), - path + HttpMethod.GET, + Domains.CONVERSATIONS.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Participant fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Participant fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return Participant.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Participant.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/conversations/v1/service/conversation/ParticipantReader.java b/src/main/java/com/twilio/rest/conversations/v1/service/conversation/ParticipantReader.java index bfc32ba4af..29682fa2ed 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/service/conversation/ParticipantReader.java +++ b/src/main/java/com/twilio/rest/conversations/v1/service/conversation/ParticipantReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,126 +30,91 @@ public class ParticipantReader extends Reader { - private String pathChatServiceSid; - private String pathConversationSid; + private String pathchatServiceSid; + private String pathconversationSid; private Long pageSize; - public ParticipantReader( - final String pathChatServiceSid, - final String pathConversationSid - ) { - this.pathChatServiceSid = pathChatServiceSid; - this.pathConversationSid = pathConversationSid; + public ParticipantReader(final String pathchatServiceSid, final String pathconversationSid) { + this.pathchatServiceSid = pathchatServiceSid; + this.pathconversationSid = pathconversationSid; } + public ParticipantReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { - String path = - "/v1/Services/{ChatServiceSid}/Conversations/{ConversationSid}/Participants"; - path = - path.replace( - "{" + "ChatServiceSid" + "}", - this.pathChatServiceSid.toString() - ); - path = - path.replace( - "{" + "ConversationSid" + "}", - this.pathConversationSid.toString() - ); + + String path = "/v1/Services/{ChatServiceSid}/Conversations/{ConversationSid}/Participants"; + + path = path.replace("{" + "ChatServiceSid" + "}", this.pathchatServiceSid.toString()); + path = path.replace("{" + "ConversationSid" + "}", this.pathconversationSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.CONVERSATIONS.toString(), - path + HttpMethod.GET, + Domains.CONVERSATIONS.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Participant read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Participant read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "participants", - response.getContent(), - Participant.class, - client.getObjectMapper() - ); + "participants", + response.getContent(), + Participant.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.CONVERSATIONS.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.CONVERSATIONS.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/conversations/v1/service/conversation/ParticipantUpdater.java b/src/main/java/com/twilio/rest/conversations/v1/service/conversation/ParticipantUpdater.java index 725fa9263c..821720d00b 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/service/conversation/ParticipantUpdater.java +++ b/src/main/java/com/twilio/rest/conversations/v1/service/conversation/ParticipantUpdater.java @@ -16,6 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -24,13 +26,13 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.time.ZonedDateTime; public class ParticipantUpdater extends Updater { - - private String pathChatServiceSid; - private String pathConversationSid; - private String pathSid; + private String pathchatServiceSid; + private String pathconversationSid; + private String pathsid; private Participant.WebhookEnabledType xTwilioWebhookEnabled; private ZonedDateTime dateCreated; private ZonedDateTime dateUpdated; @@ -42,178 +44,164 @@ public class ParticipantUpdater extends Updater { private Integer lastReadMessageIndex; private String lastReadTimestamp; - public ParticipantUpdater( - final String pathChatServiceSid, - final String pathConversationSid, - final String pathSid - ) { - this.pathChatServiceSid = pathChatServiceSid; - this.pathConversationSid = pathConversationSid; - this.pathSid = pathSid; + public ParticipantUpdater(final String pathchatServiceSid, final String pathconversationSid, final String pathsid) { + this.pathchatServiceSid = pathchatServiceSid; + this.pathconversationSid = pathconversationSid; + this.pathsid = pathsid; } - public ParticipantUpdater setXTwilioWebhookEnabled( - final Participant.WebhookEnabledType xTwilioWebhookEnabled - ) { - this.xTwilioWebhookEnabled = xTwilioWebhookEnabled; - return this; - } public ParticipantUpdater setDateCreated(final ZonedDateTime dateCreated) { this.dateCreated = dateCreated; return this; } + public ParticipantUpdater setDateUpdated(final ZonedDateTime dateUpdated) { this.dateUpdated = dateUpdated; return this; } + public ParticipantUpdater setIdentity(final String identity) { this.identity = identity; return this; } + public ParticipantUpdater setAttributes(final String attributes) { this.attributes = attributes; return this; } + public ParticipantUpdater setRoleSid(final String roleSid) { this.roleSid = roleSid; return this; } - public ParticipantUpdater setMessagingBindingProxyAddress( - final String messagingBindingProxyAddress - ) { + + public ParticipantUpdater setMessagingBindingProxyAddress(final String messagingBindingProxyAddress) { this.messagingBindingProxyAddress = messagingBindingProxyAddress; return this; } - public ParticipantUpdater setMessagingBindingProjectedAddress( - final String messagingBindingProjectedAddress - ) { - this.messagingBindingProjectedAddress = - messagingBindingProjectedAddress; + + public ParticipantUpdater setMessagingBindingProjectedAddress(final String messagingBindingProjectedAddress) { + this.messagingBindingProjectedAddress = messagingBindingProjectedAddress; return this; } - public ParticipantUpdater setLastReadMessageIndex( - final Integer lastReadMessageIndex - ) { + + public ParticipantUpdater setLastReadMessageIndex(final Integer lastReadMessageIndex) { this.lastReadMessageIndex = lastReadMessageIndex; return this; } - public ParticipantUpdater setLastReadTimestamp( - final String lastReadTimestamp - ) { + + public ParticipantUpdater setLastReadTimestamp(final String lastReadTimestamp) { this.lastReadTimestamp = lastReadTimestamp; return this; } + + public ParticipantUpdater setXTwilioWebhookEnabled(final Participant.WebhookEnabledType xTwilioWebhookEnabled) { + this.xTwilioWebhookEnabled = xTwilioWebhookEnabled; + return this; + } + + @Override public Participant update(final TwilioRestClient client) { - String path = - "/v1/Services/{ChatServiceSid}/Conversations/{ConversationSid}/Participants/{Sid}"; - path = - path.replace( - "{" + "ChatServiceSid" + "}", - this.pathChatServiceSid.toString() - ); - path = - path.replace( - "{" + "ConversationSid" + "}", - this.pathConversationSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/v1/Services/{ChatServiceSid}/Conversations/{ConversationSid}/Participants/{Sid}"; + + path = path.replace("{" + "ChatServiceSid" + "}", this.pathchatServiceSid.toString()); + path = path.replace("{" + "ConversationSid" + "}", this.pathconversationSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.CONVERSATIONS.toString(), - path + HttpMethod.POST, + Domains.CONVERSATIONS.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); - addPostParams(request); addHeaderParams(request); + addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Participant update failed: Unable to connect to server" - ); + throw new ApiConnectionException("Participant update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Participant.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Participant.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (dateCreated != null) { - request.addPostParam( - "DateCreated", - dateCreated.toInstant().toString() - ); + Serializer.toString(request, "DateCreated", dateCreated, ParameterType.URLENCODED); } + + if (dateUpdated != null) { - request.addPostParam( - "DateUpdated", - dateUpdated.toInstant().toString() - ); + Serializer.toString(request, "DateUpdated", dateUpdated, ParameterType.URLENCODED); } + + if (identity != null) { - request.addPostParam("Identity", identity); + Serializer.toString(request, "Identity", identity, ParameterType.URLENCODED); } + + if (attributes != null) { - request.addPostParam("Attributes", attributes); + Serializer.toString(request, "Attributes", attributes, ParameterType.URLENCODED); } + + if (roleSid != null) { - request.addPostParam("RoleSid", roleSid); + Serializer.toString(request, "RoleSid", roleSid, ParameterType.URLENCODED); } + + if (messagingBindingProxyAddress != null) { - request.addPostParam( - "MessagingBinding.ProxyAddress", - messagingBindingProxyAddress - ); + Serializer.toString(request, "MessagingBinding.ProxyAddress", messagingBindingProxyAddress, ParameterType.URLENCODED); } + + if (messagingBindingProjectedAddress != null) { - request.addPostParam( - "MessagingBinding.ProjectedAddress", - messagingBindingProjectedAddress - ); + Serializer.toString(request, "MessagingBinding.ProjectedAddress", messagingBindingProjectedAddress, ParameterType.URLENCODED); } + + if (lastReadMessageIndex != null) { - request.addPostParam( - "LastReadMessageIndex", - lastReadMessageIndex.toString() - ); + Serializer.toString(request, "LastReadMessageIndex", lastReadMessageIndex, ParameterType.URLENCODED); } + + if (lastReadTimestamp != null) { - request.addPostParam("LastReadTimestamp", lastReadTimestamp); + Serializer.toString(request, "LastReadTimestamp", lastReadTimestamp, ParameterType.URLENCODED); } + + } private void addHeaderParams(final Request request) { + if (xTwilioWebhookEnabled != null) { - request.addHeaderParam( - "X-Twilio-Webhook-Enabled", - xTwilioWebhookEnabled.toString() - ); + Serializer.toString(request, "X-Twilio-Webhook-Enabled", xTwilioWebhookEnabled, ParameterType.HEADER); } + } } diff --git a/src/main/java/com/twilio/rest/conversations/v1/service/conversation/Webhook.java b/src/main/java/com/twilio/rest/conversations/v1/service/conversation/Webhook.java index 3df7568adc..8898c8f246 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/service/conversation/Webhook.java +++ b/src/main/java/com/twilio/rest/conversations/v1/service/conversation/Webhook.java @@ -18,95 +18,113 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; -import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Webhook extends Resource { - private static final long serialVersionUID = 228548505277204L; - public static WebhookCreator creator( - final String pathChatServiceSid, - final String pathConversationSid, - final Webhook.Target target - ) { + public static WebhookCreator creator(final String pathchatServiceSid, final String pathconversationSid, final Webhook.Target target) { return new WebhookCreator( - pathChatServiceSid, - pathConversationSid, - target + pathchatServiceSid, pathconversationSid, target ); } - public static WebhookDeleter deleter( - final String pathChatServiceSid, - final String pathConversationSid, - final String pathSid - ) { + + public static WebhookDeleter deleter(final String pathchatServiceSid, final String pathconversationSid, final String pathsid) { return new WebhookDeleter( - pathChatServiceSid, - pathConversationSid, - pathSid + pathchatServiceSid, pathconversationSid, pathsid ); } - public static WebhookFetcher fetcher( - final String pathChatServiceSid, - final String pathConversationSid, - final String pathSid - ) { + + public static WebhookFetcher fetcher(final String pathchatServiceSid, final String pathconversationSid, final String pathsid) { return new WebhookFetcher( - pathChatServiceSid, - pathConversationSid, - pathSid + pathchatServiceSid, pathconversationSid, pathsid ); } - public static WebhookReader reader( - final String pathChatServiceSid, - final String pathConversationSid - ) { - return new WebhookReader(pathChatServiceSid, pathConversationSid); + + public static WebhookReader reader(final String pathchatServiceSid, final String pathconversationSid) { + return new WebhookReader( + pathchatServiceSid, pathconversationSid + ); } - public static WebhookUpdater updater( - final String pathChatServiceSid, - final String pathConversationSid, - final String pathSid - ) { + + public static WebhookUpdater updater(final String pathchatServiceSid, final String pathconversationSid, final String pathsid) { return new WebhookUpdater( - pathChatServiceSid, - pathConversationSid, - pathSid + pathchatServiceSid, pathconversationSid, pathsid ); } + + public enum Target { + WEBHOOK("webhook"), + TRIGGER("trigger"), + STUDIO("studio"); + + private final String value; + + private Target(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static Target forValue(final String value) { + return Promoter.enumFromString(value, Target.values()); + } + } + + public enum Method { + GET("get"), + POST("post"); + + private final String value; + + private Method(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static Method forValue(final String value) { + return Promoter.enumFromString(value, Method.values()); + } + } + + /** * Converts a JSON String into a Webhook object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Webhook object represented by the provided JSON */ - public static Webhook fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Webhook fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Webhook.class); @@ -121,14 +139,11 @@ public static Webhook fromJson( * Converts a JSON InputStream into a Webhook object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Webhook object represented by the provided JSON */ - public static Webhook fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Webhook fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Webhook.class); @@ -139,73 +154,61 @@ public static Webhook fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; + @Getter private final String chatServiceSid; + @Getter + private final Object configuration; + @Getter private final String conversationSid; - private final String target; - private final URI url; - private final Map configuration; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; + @Getter + private final String sid; + @Getter + private final String target; + @Getter + private final URI url; @JsonCreator private Webhook( - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("chat_service_sid") final String chatServiceSid, - @JsonProperty("conversation_sid") final String conversationSid, - @JsonProperty("target") final String target, - @JsonProperty("url") final URI url, - @JsonProperty("configuration") final Map configuration, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("chat_service_sid") final String chatServiceSid, + @JsonProperty("configuration") final Object configuration, + @JsonProperty("conversation_sid") final String conversationSid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("sid") final String sid, + @JsonProperty("target") final String target, + @JsonProperty("url") final URI url ) { - this.sid = sid; this.accountSid = accountSid; this.chatServiceSid = chatServiceSid; + this.configuration = configuration; this.conversationSid = conversationSid; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; + this.sid = sid; this.target = target; this.url = url; - this.configuration = configuration; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); - } - - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getChatServiceSid() { - return this.chatServiceSid; - } - - public final String getConversationSid() { - return this.conversationSid; - } - - public final String getTarget() { - return this.target; - } - - public final URI getUrl() { - return this.url; - } - - public final Map getConfiguration() { - return this.configuration; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; } @Override @@ -219,73 +222,34 @@ public boolean equals(final Object o) { } Webhook other = (Webhook) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(chatServiceSid, other.chatServiceSid) && - Objects.equals(conversationSid, other.conversationSid) && - Objects.equals(target, other.target) && - Objects.equals(url, other.url) && - Objects.equals(configuration, other.configuration) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(chatServiceSid, other.chatServiceSid) && + Objects.equals(configuration, other.configuration) && + Objects.equals(conversationSid, other.conversationSid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(sid, other.sid) && + Objects.equals(target, other.target) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - sid, - accountSid, - chatServiceSid, - conversationSid, - target, - url, - configuration, - dateCreated, - dateUpdated + accountSid, + chatServiceSid, + configuration, + conversationSid, + dateCreated, + dateUpdated, + sid, + target, + url ); } - public enum Target { - WEBHOOK("webhook"), - TRIGGER("trigger"), - STUDIO("studio"); - - private final String value; - - private Target(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static Target forValue(final String value) { - return Promoter.enumFromString(value, Target.values()); - } - } - - public enum Method { - GET("get"), - POST("post"); - - private final String value; - private Method(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static Method forValue(final String value) { - return Promoter.enumFromString(value, Method.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/conversations/v1/service/conversation/WebhookCreator.java b/src/main/java/com/twilio/rest/conversations/v1/service/conversation/WebhookCreator.java index 264be1bc1f..39c0b55a29 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/service/conversation/WebhookCreator.java +++ b/src/main/java/com/twilio/rest/conversations/v1/service/conversation/WebhookCreator.java @@ -14,9 +14,12 @@ package com.twilio.rest.conversations.v1.service.conversation; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; import com.twilio.converter.Promoter; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,13 +28,13 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -import java.util.List; + import java.util.List; public class WebhookCreator extends Creator { - private String pathChatServiceSid; - private String pathConversationSid; + private String pathchatServiceSid; + private String pathconversationSid; private Webhook.Target target; private String configurationUrl; private Webhook.Method configurationMethod; @@ -40,116 +43,89 @@ public class WebhookCreator extends Creator { private String configurationFlowSid; private Integer configurationReplayAfter; - public WebhookCreator( - final String pathChatServiceSid, - final String pathConversationSid, - final Webhook.Target target - ) { - this.pathChatServiceSid = pathChatServiceSid; - this.pathConversationSid = pathConversationSid; + public WebhookCreator(final String pathchatServiceSid, final String pathconversationSid, final Webhook.Target target) { + this.pathchatServiceSid = pathchatServiceSid; + this.pathconversationSid = pathconversationSid; this.target = target; } + public WebhookCreator setTarget(final Webhook.Target target) { this.target = target; return this; } + public WebhookCreator setConfigurationUrl(final String configurationUrl) { this.configurationUrl = configurationUrl; return this; } - public WebhookCreator setConfigurationMethod( - final Webhook.Method configurationMethod - ) { + + public WebhookCreator setConfigurationMethod(final Webhook.Method configurationMethod) { this.configurationMethod = configurationMethod; return this; } - public WebhookCreator setConfigurationFilters( - final List configurationFilters - ) { + + public WebhookCreator setConfigurationFilters(final List configurationFilters) { this.configurationFilters = configurationFilters; return this; } - public WebhookCreator setConfigurationFilters( - final String configurationFilters - ) { - return setConfigurationFilters( - Promoter.listOfOne(configurationFilters) - ); + public WebhookCreator setConfigurationFilters(final String configurationFilters) { + return setConfigurationFilters(Promoter.listOfOne(configurationFilters)); } - public WebhookCreator setConfigurationTriggers( - final List configurationTriggers - ) { + public WebhookCreator setConfigurationTriggers(final List configurationTriggers) { this.configurationTriggers = configurationTriggers; return this; } - public WebhookCreator setConfigurationTriggers( - final String configurationTriggers - ) { - return setConfigurationTriggers( - Promoter.listOfOne(configurationTriggers) - ); + public WebhookCreator setConfigurationTriggers(final String configurationTriggers) { + return setConfigurationTriggers(Promoter.listOfOne(configurationTriggers)); } - public WebhookCreator setConfigurationFlowSid( - final String configurationFlowSid - ) { + public WebhookCreator setConfigurationFlowSid(final String configurationFlowSid) { this.configurationFlowSid = configurationFlowSid; return this; } - public WebhookCreator setConfigurationReplayAfter( - final Integer configurationReplayAfter - ) { + + public WebhookCreator setConfigurationReplayAfter(final Integer configurationReplayAfter) { this.configurationReplayAfter = configurationReplayAfter; return this; } + @Override public Webhook create(final TwilioRestClient client) { - String path = - "/v1/Services/{ChatServiceSid}/Conversations/{ConversationSid}/Webhooks"; - path = - path.replace( - "{" + "ChatServiceSid" + "}", - this.pathChatServiceSid.toString() - ); - path = - path.replace( - "{" + "ConversationSid" + "}", - this.pathConversationSid.toString() - ); - path = path.replace("{" + "Target" + "}", this.target.toString()); + String path = "/v1/Services/{ChatServiceSid}/Conversations/{ConversationSid}/Webhooks"; + + path = path.replace("{" + "ChatServiceSid" + "}", this.pathchatServiceSid.toString()); + path = path.replace("{" + "ConversationSid" + "}", this.pathconversationSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.CONVERSATIONS.toString(), - path + HttpMethod.POST, + Domains.CONVERSATIONS.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Webhook creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("Webhook creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -158,36 +134,45 @@ public Webhook create(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (target != null) { - request.addPostParam("Target", target.toString()); + Serializer.toString(request, "Target", target, ParameterType.URLENCODED); } + + if (configurationUrl != null) { - request.addPostParam("Configuration.Url", configurationUrl); + Serializer.toString(request, "Configuration.Url", configurationUrl, ParameterType.URLENCODED); } + + if (configurationMethod != null) { - request.addPostParam( - "Configuration.Method", - configurationMethod.toString() - ); + Serializer.toString(request, "Configuration.Method", configurationMethod, ParameterType.URLENCODED); } + + if (configurationFilters != null) { - for (String prop : configurationFilters) { - request.addPostParam("Configuration.Filters", prop); + for (String param : configurationFilters) { + Serializer.toString(request, "Configuration.Filters", param, ParameterType.URLENCODED); } } + + if (configurationTriggers != null) { - for (String prop : configurationTriggers) { - request.addPostParam("Configuration.Triggers", prop); + for (String param : configurationTriggers) { + Serializer.toString(request, "Configuration.Triggers", param, ParameterType.URLENCODED); } } + + if (configurationFlowSid != null) { - request.addPostParam("Configuration.FlowSid", configurationFlowSid); + Serializer.toString(request, "Configuration.FlowSid", configurationFlowSid, ParameterType.URLENCODED); } + + if (configurationReplayAfter != null) { - request.addPostParam( - "Configuration.ReplayAfter", - configurationReplayAfter.toString() - ); + Serializer.toString(request, "Configuration.ReplayAfter", configurationReplayAfter, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/conversations/v1/service/conversation/WebhookDeleter.java b/src/main/java/com/twilio/rest/conversations/v1/service/conversation/WebhookDeleter.java index 794aab8b69..37ef82f052 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/service/conversation/WebhookDeleter.java +++ b/src/main/java/com/twilio/rest/conversations/v1/service/conversation/WebhookDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.conversations.v1.service.conversation; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,59 +26,44 @@ public class WebhookDeleter extends Deleter { - private String pathChatServiceSid; - private String pathConversationSid; - private String pathSid; + private String pathchatServiceSid; + private String pathconversationSid; + private String pathsid; - public WebhookDeleter( - final String pathChatServiceSid, - final String pathConversationSid, - final String pathSid - ) { - this.pathChatServiceSid = pathChatServiceSid; - this.pathConversationSid = pathConversationSid; - this.pathSid = pathSid; + public WebhookDeleter(final String pathchatServiceSid, final String pathconversationSid, final String pathsid) { + this.pathchatServiceSid = pathchatServiceSid; + this.pathconversationSid = pathconversationSid; + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { - String path = - "/v1/Services/{ChatServiceSid}/Conversations/{ConversationSid}/Webhooks/{Sid}"; - path = - path.replace( - "{" + "ChatServiceSid" + "}", - this.pathChatServiceSid.toString() - ); - path = - path.replace( - "{" + "ConversationSid" + "}", - this.pathConversationSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/v1/Services/{ChatServiceSid}/Conversations/{ConversationSid}/Webhooks/{Sid}"; + + path = path.replace("{" + "ChatServiceSid" + "}", this.pathchatServiceSid.toString()); + path = path.replace("{" + "ConversationSid" + "}", this.pathconversationSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.CONVERSATIONS.toString(), - path + HttpMethod.DELETE, + Domains.CONVERSATIONS.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Webhook delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("Webhook delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/conversations/v1/service/conversation/WebhookFetcher.java b/src/main/java/com/twilio/rest/conversations/v1/service/conversation/WebhookFetcher.java index 72803aeaa7..516f68ea67 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/service/conversation/WebhookFetcher.java +++ b/src/main/java/com/twilio/rest/conversations/v1/service/conversation/WebhookFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.conversations.v1.service.conversation; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,63 +26,47 @@ public class WebhookFetcher extends Fetcher { - private String pathChatServiceSid; - private String pathConversationSid; - private String pathSid; + private String pathchatServiceSid; + private String pathconversationSid; + private String pathsid; - public WebhookFetcher( - final String pathChatServiceSid, - final String pathConversationSid, - final String pathSid - ) { - this.pathChatServiceSid = pathChatServiceSid; - this.pathConversationSid = pathConversationSid; - this.pathSid = pathSid; + public WebhookFetcher(final String pathchatServiceSid, final String pathconversationSid, final String pathsid) { + this.pathchatServiceSid = pathchatServiceSid; + this.pathconversationSid = pathconversationSid; + this.pathsid = pathsid; } + @Override public Webhook fetch(final TwilioRestClient client) { - String path = - "/v1/Services/{ChatServiceSid}/Conversations/{ConversationSid}/Webhooks/{Sid}"; - path = - path.replace( - "{" + "ChatServiceSid" + "}", - this.pathChatServiceSid.toString() - ); - path = - path.replace( - "{" + "ConversationSid" + "}", - this.pathConversationSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/v1/Services/{ChatServiceSid}/Conversations/{ConversationSid}/Webhooks/{Sid}"; + + path = path.replace("{" + "ChatServiceSid" + "}", this.pathchatServiceSid.toString()); + path = path.replace("{" + "ConversationSid" + "}", this.pathconversationSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.CONVERSATIONS.toString(), - path + HttpMethod.GET, + Domains.CONVERSATIONS.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Webhook fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Webhook fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Webhook.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/conversations/v1/service/conversation/WebhookReader.java b/src/main/java/com/twilio/rest/conversations/v1/service/conversation/WebhookReader.java index 29ac6a285d..c9bdf14d22 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/service/conversation/WebhookReader.java +++ b/src/main/java/com/twilio/rest/conversations/v1/service/conversation/WebhookReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,126 +30,91 @@ public class WebhookReader extends Reader { - private String pathChatServiceSid; - private String pathConversationSid; + private String pathchatServiceSid; + private String pathconversationSid; private Long pageSize; - public WebhookReader( - final String pathChatServiceSid, - final String pathConversationSid - ) { - this.pathChatServiceSid = pathChatServiceSid; - this.pathConversationSid = pathConversationSid; + public WebhookReader(final String pathchatServiceSid, final String pathconversationSid) { + this.pathchatServiceSid = pathchatServiceSid; + this.pathconversationSid = pathconversationSid; } + public WebhookReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { - String path = - "/v1/Services/{ChatServiceSid}/Conversations/{ConversationSid}/Webhooks"; - path = - path.replace( - "{" + "ChatServiceSid" + "}", - this.pathChatServiceSid.toString() - ); - path = - path.replace( - "{" + "ConversationSid" + "}", - this.pathConversationSid.toString() - ); + + String path = "/v1/Services/{ChatServiceSid}/Conversations/{ConversationSid}/Webhooks"; + + path = path.replace("{" + "ChatServiceSid" + "}", this.pathchatServiceSid.toString()); + path = path.replace("{" + "ConversationSid" + "}", this.pathconversationSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.CONVERSATIONS.toString(), - path + HttpMethod.GET, + Domains.CONVERSATIONS.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Webhook read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Webhook read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "webhooks", - response.getContent(), - Webhook.class, - client.getObjectMapper() - ); + "webhooks", + response.getContent(), + Webhook.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.CONVERSATIONS.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.CONVERSATIONS.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/conversations/v1/service/conversation/WebhookUpdater.java b/src/main/java/com/twilio/rest/conversations/v1/service/conversation/WebhookUpdater.java index d45c01e46c..1658be5f84 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/service/conversation/WebhookUpdater.java +++ b/src/main/java/com/twilio/rest/conversations/v1/service/conversation/WebhookUpdater.java @@ -16,7 +16,9 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; import com.twilio.converter.Promoter; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,117 +27,91 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.util.List; public class WebhookUpdater extends Updater { - - private String pathChatServiceSid; - private String pathConversationSid; - private String pathSid; + private String pathchatServiceSid; + private String pathconversationSid; + private String pathsid; private String configurationUrl; private Webhook.Method configurationMethod; private List configurationFilters; private List configurationTriggers; private String configurationFlowSid; - public WebhookUpdater( - final String pathChatServiceSid, - final String pathConversationSid, - final String pathSid - ) { - this.pathChatServiceSid = pathChatServiceSid; - this.pathConversationSid = pathConversationSid; - this.pathSid = pathSid; + public WebhookUpdater(final String pathchatServiceSid, final String pathconversationSid, final String pathsid) { + this.pathchatServiceSid = pathchatServiceSid; + this.pathconversationSid = pathconversationSid; + this.pathsid = pathsid; } + public WebhookUpdater setConfigurationUrl(final String configurationUrl) { this.configurationUrl = configurationUrl; return this; } - public WebhookUpdater setConfigurationMethod( - final Webhook.Method configurationMethod - ) { + + public WebhookUpdater setConfigurationMethod(final Webhook.Method configurationMethod) { this.configurationMethod = configurationMethod; return this; } - public WebhookUpdater setConfigurationFilters( - final List configurationFilters - ) { + + public WebhookUpdater setConfigurationFilters(final List configurationFilters) { this.configurationFilters = configurationFilters; return this; } - public WebhookUpdater setConfigurationFilters( - final String configurationFilters - ) { - return setConfigurationFilters( - Promoter.listOfOne(configurationFilters) - ); + public WebhookUpdater setConfigurationFilters(final String configurationFilters) { + return setConfigurationFilters(Promoter.listOfOne(configurationFilters)); } - public WebhookUpdater setConfigurationTriggers( - final List configurationTriggers - ) { + public WebhookUpdater setConfigurationTriggers(final List configurationTriggers) { this.configurationTriggers = configurationTriggers; return this; } - public WebhookUpdater setConfigurationTriggers( - final String configurationTriggers - ) { - return setConfigurationTriggers( - Promoter.listOfOne(configurationTriggers) - ); + public WebhookUpdater setConfigurationTriggers(final String configurationTriggers) { + return setConfigurationTriggers(Promoter.listOfOne(configurationTriggers)); } - public WebhookUpdater setConfigurationFlowSid( - final String configurationFlowSid - ) { + public WebhookUpdater setConfigurationFlowSid(final String configurationFlowSid) { this.configurationFlowSid = configurationFlowSid; return this; } + @Override public Webhook update(final TwilioRestClient client) { - String path = - "/v1/Services/{ChatServiceSid}/Conversations/{ConversationSid}/Webhooks/{Sid}"; - path = - path.replace( - "{" + "ChatServiceSid" + "}", - this.pathChatServiceSid.toString() - ); - path = - path.replace( - "{" + "ConversationSid" + "}", - this.pathConversationSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/v1/Services/{ChatServiceSid}/Conversations/{ConversationSid}/Webhooks/{Sid}"; + + path = path.replace("{" + "ChatServiceSid" + "}", this.pathchatServiceSid.toString()); + path = path.replace("{" + "ConversationSid" + "}", this.pathconversationSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.CONVERSATIONS.toString(), - path + HttpMethod.POST, + Domains.CONVERSATIONS.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Webhook update failed: Unable to connect to server" - ); + throw new ApiConnectionException("Webhook update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -144,27 +120,35 @@ public Webhook update(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (configurationUrl != null) { - request.addPostParam("Configuration.Url", configurationUrl); + Serializer.toString(request, "Configuration.Url", configurationUrl, ParameterType.URLENCODED); } + + if (configurationMethod != null) { - request.addPostParam( - "Configuration.Method", - configurationMethod.toString() - ); + Serializer.toString(request, "Configuration.Method", configurationMethod, ParameterType.URLENCODED); } + + if (configurationFilters != null) { - for (String prop : configurationFilters) { - request.addPostParam("Configuration.Filters", prop); + for (String param : configurationFilters) { + Serializer.toString(request, "Configuration.Filters", param, ParameterType.URLENCODED); } } + + if (configurationTriggers != null) { - for (String prop : configurationTriggers) { - request.addPostParam("Configuration.Triggers", prop); + for (String param : configurationTriggers) { + Serializer.toString(request, "Configuration.Triggers", param, ParameterType.URLENCODED); } } + + if (configurationFlowSid != null) { - request.addPostParam("Configuration.FlowSid", configurationFlowSid); + Serializer.toString(request, "Configuration.FlowSid", configurationFlowSid, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/conversations/v1/service/conversation/message/DeliveryReceipt.java b/src/main/java/com/twilio/rest/conversations/v1/service/conversation/message/DeliveryReceipt.java index f3a9dd829d..32f85fea18 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/service/conversation/message/DeliveryReceipt.java +++ b/src/main/java/com/twilio/rest/conversations/v1/service/conversation/message/DeliveryReceipt.java @@ -18,64 +18,74 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class DeliveryReceipt extends Resource { - private static final long serialVersionUID = 201260516970011L; - public static DeliveryReceiptFetcher fetcher( - final String pathChatServiceSid, - final String pathConversationSid, - final String pathMessageSid, - final String pathSid - ) { + public static DeliveryReceiptFetcher fetcher(final String pathchatServiceSid, final String pathconversationSid, final String pathmessageSid, final String pathsid) { return new DeliveryReceiptFetcher( - pathChatServiceSid, - pathConversationSid, - pathMessageSid, - pathSid + pathchatServiceSid, pathconversationSid, pathmessageSid, pathsid ); } - public static DeliveryReceiptReader reader( - final String pathChatServiceSid, - final String pathConversationSid, - final String pathMessageSid - ) { + + public static DeliveryReceiptReader reader(final String pathchatServiceSid, final String pathconversationSid, final String pathmessageSid) { return new DeliveryReceiptReader( - pathChatServiceSid, - pathConversationSid, - pathMessageSid + pathchatServiceSid, pathconversationSid, pathmessageSid ); } + + public enum DeliveryStatus { + READ("read"), + FAILED("failed"), + DELIVERED("delivered"), + UNDELIVERED("undelivered"), + SENT("sent"); + + private final String value; + + private DeliveryStatus(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static DeliveryStatus forValue(final String value) { + return Promoter.enumFromString(value, DeliveryStatus.values()); + } + } + + /** * Converts a JSON String into a DeliveryReceipt object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return DeliveryReceipt object represented by the provided JSON */ - public static DeliveryReceipt fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static DeliveryReceipt fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, DeliveryReceipt.class); @@ -90,14 +100,11 @@ public static DeliveryReceipt fromJson( * Converts a JSON InputStream into a DeliveryReceipt object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return DeliveryReceipt object represented by the provided JSON */ - public static DeliveryReceipt fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static DeliveryReceipt fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, DeliveryReceipt.class); @@ -108,96 +115,75 @@ public static DeliveryReceipt fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; + @Getter + private final String channelMessageSid; + @Getter private final String chatServiceSid; + @Getter private final String conversationSid; + @Getter + private final ZonedDateTime dateCreated; + @Getter + private final ZonedDateTime dateUpdated; + @Getter + private final Integer errorCode; + @Getter private final String messageSid; - private final String sid; - private final String channelMessageSid; + @Getter private final String participantSid; + @Getter + private final String sid; + @Getter private final DeliveryReceipt.DeliveryStatus status; - private final Integer errorCode; - private final ZonedDateTime dateCreated; - private final ZonedDateTime dateUpdated; + @Getter private final URI url; @JsonCreator private DeliveryReceipt( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("chat_service_sid") final String chatServiceSid, - @JsonProperty("conversation_sid") final String conversationSid, - @JsonProperty("message_sid") final String messageSid, - @JsonProperty("sid") final String sid, - @JsonProperty("channel_message_sid") final String channelMessageSid, - @JsonProperty("participant_sid") final String participantSid, - @JsonProperty("status") final DeliveryReceipt.DeliveryStatus status, - @JsonProperty("error_code") final Integer errorCode, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("url") final URI url + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("channel_message_sid") final String channelMessageSid, + @JsonProperty("chat_service_sid") final String chatServiceSid, + @JsonProperty("conversation_sid") final String conversationSid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("error_code") final Integer errorCode, + @JsonProperty("message_sid") final String messageSid, + @JsonProperty("participant_sid") final String participantSid, + @JsonProperty("sid") final String sid, + @JsonProperty("status") final DeliveryReceipt.DeliveryStatus status, + @JsonProperty("url") final URI url ) { this.accountSid = accountSid; + this.channelMessageSid = channelMessageSid; this.chatServiceSid = chatServiceSid; this.conversationSid = conversationSid; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; + this.errorCode = errorCode; this.messageSid = messageSid; - this.sid = sid; - this.channelMessageSid = channelMessageSid; this.participantSid = participantSid; + this.sid = sid; this.status = status; - this.errorCode = errorCode; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); this.url = url; } - public final String getAccountSid() { - return this.accountSid; - } - - public final String getChatServiceSid() { - return this.chatServiceSid; - } - - public final String getConversationSid() { - return this.conversationSid; - } - - public final String getMessageSid() { - return this.messageSid; - } - - public final String getSid() { - return this.sid; - } - - public final String getChannelMessageSid() { - return this.channelMessageSid; - } - - public final String getParticipantSid() { - return this.participantSid; - } - - public final DeliveryReceipt.DeliveryStatus getStatus() { - return this.status; - } - - public final Integer getErrorCode() { - return this.errorCode; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final URI getUrl() { - return this.url; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -209,61 +195,40 @@ public boolean equals(final Object o) { } DeliveryReceipt other = (DeliveryReceipt) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(chatServiceSid, other.chatServiceSid) && - Objects.equals(conversationSid, other.conversationSid) && - Objects.equals(messageSid, other.messageSid) && - Objects.equals(sid, other.sid) && - Objects.equals(channelMessageSid, other.channelMessageSid) && - Objects.equals(participantSid, other.participantSid) && - Objects.equals(status, other.status) && - Objects.equals(errorCode, other.errorCode) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(url, other.url) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(channelMessageSid, other.channelMessageSid) && + Objects.equals(chatServiceSid, other.chatServiceSid) && + Objects.equals(conversationSid, other.conversationSid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(errorCode, other.errorCode) && + Objects.equals(messageSid, other.messageSid) && + Objects.equals(participantSid, other.participantSid) && + Objects.equals(sid, other.sid) && + Objects.equals(status, other.status) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - accountSid, - chatServiceSid, - conversationSid, - messageSid, - sid, - channelMessageSid, - participantSid, - status, - errorCode, - dateCreated, - dateUpdated, - url + accountSid, + channelMessageSid, + chatServiceSid, + conversationSid, + dateCreated, + dateUpdated, + errorCode, + messageSid, + participantSid, + sid, + status, + url ); } - public enum DeliveryStatus { - READ("read"), - FAILED("failed"), - DELIVERED("delivered"), - UNDELIVERED("undelivered"), - SENT("sent"); - - private final String value; - - private DeliveryStatus(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - @JsonCreator - public static DeliveryStatus forValue(final String value) { - return Promoter.enumFromString(value, DeliveryStatus.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/conversations/v1/service/conversation/message/DeliveryReceiptFetcher.java b/src/main/java/com/twilio/rest/conversations/v1/service/conversation/message/DeliveryReceiptFetcher.java index f427603dd8..947ed78488 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/service/conversation/message/DeliveryReceiptFetcher.java +++ b/src/main/java/com/twilio/rest/conversations/v1/service/conversation/message/DeliveryReceiptFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.conversations.v1.service.conversation.message; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,74 +26,50 @@ public class DeliveryReceiptFetcher extends Fetcher { - private String pathChatServiceSid; - private String pathConversationSid; - private String pathMessageSid; - private String pathSid; + private String pathchatServiceSid; + private String pathconversationSid; + private String pathmessageSid; + private String pathsid; - public DeliveryReceiptFetcher( - final String pathChatServiceSid, - final String pathConversationSid, - final String pathMessageSid, - final String pathSid - ) { - this.pathChatServiceSid = pathChatServiceSid; - this.pathConversationSid = pathConversationSid; - this.pathMessageSid = pathMessageSid; - this.pathSid = pathSid; + public DeliveryReceiptFetcher(final String pathchatServiceSid, final String pathconversationSid, final String pathmessageSid, final String pathsid) { + this.pathchatServiceSid = pathchatServiceSid; + this.pathconversationSid = pathconversationSid; + this.pathmessageSid = pathmessageSid; + this.pathsid = pathsid; } + @Override public DeliveryReceipt fetch(final TwilioRestClient client) { - String path = - "/v1/Services/{ChatServiceSid}/Conversations/{ConversationSid}/Messages/{MessageSid}/Receipts/{Sid}"; - path = - path.replace( - "{" + "ChatServiceSid" + "}", - this.pathChatServiceSid.toString() - ); - path = - path.replace( - "{" + "ConversationSid" + "}", - this.pathConversationSid.toString() - ); - path = - path.replace( - "{" + "MessageSid" + "}", - this.pathMessageSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/v1/Services/{ChatServiceSid}/Conversations/{ConversationSid}/Messages/{MessageSid}/Receipts/{Sid}"; + + path = path.replace("{" + "ChatServiceSid" + "}", this.pathchatServiceSid.toString()); + path = path.replace("{" + "ConversationSid" + "}", this.pathconversationSid.toString()); + path = path.replace("{" + "MessageSid" + "}", this.pathmessageSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.CONVERSATIONS.toString(), - path + HttpMethod.GET, + Domains.CONVERSATIONS.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "DeliveryReceipt fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("DeliveryReceipt fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return DeliveryReceipt.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return DeliveryReceipt.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/conversations/v1/service/conversation/message/DeliveryReceiptReader.java b/src/main/java/com/twilio/rest/conversations/v1/service/conversation/message/DeliveryReceiptReader.java index 045c92763a..2f558ad6e0 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/service/conversation/message/DeliveryReceiptReader.java +++ b/src/main/java/com/twilio/rest/conversations/v1/service/conversation/message/DeliveryReceiptReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,134 +30,94 @@ public class DeliveryReceiptReader extends Reader { - private String pathChatServiceSid; - private String pathConversationSid; - private String pathMessageSid; + private String pathchatServiceSid; + private String pathconversationSid; + private String pathmessageSid; private Long pageSize; - public DeliveryReceiptReader( - final String pathChatServiceSid, - final String pathConversationSid, - final String pathMessageSid - ) { - this.pathChatServiceSid = pathChatServiceSid; - this.pathConversationSid = pathConversationSid; - this.pathMessageSid = pathMessageSid; + public DeliveryReceiptReader(final String pathchatServiceSid, final String pathconversationSid, final String pathmessageSid) { + this.pathchatServiceSid = pathchatServiceSid; + this.pathconversationSid = pathconversationSid; + this.pathmessageSid = pathmessageSid; } + public DeliveryReceiptReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { - String path = - "/v1/Services/{ChatServiceSid}/Conversations/{ConversationSid}/Messages/{MessageSid}/Receipts"; - path = - path.replace( - "{" + "ChatServiceSid" + "}", - this.pathChatServiceSid.toString() - ); - path = - path.replace( - "{" + "ConversationSid" + "}", - this.pathConversationSid.toString() - ); - path = - path.replace( - "{" + "MessageSid" + "}", - this.pathMessageSid.toString() - ); + + String path = "/v1/Services/{ChatServiceSid}/Conversations/{ConversationSid}/Messages/{MessageSid}/Receipts"; + + path = path.replace("{" + "ChatServiceSid" + "}", this.pathchatServiceSid.toString()); + path = path.replace("{" + "ConversationSid" + "}", this.pathconversationSid.toString()); + path = path.replace("{" + "MessageSid" + "}", this.pathmessageSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.CONVERSATIONS.toString(), - path + HttpMethod.GET, + Domains.CONVERSATIONS.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "DeliveryReceipt read failed: Unable to connect to server" - ); + throw new ApiConnectionException("DeliveryReceipt read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "delivery_receipts", - response.getContent(), - DeliveryReceipt.class, - client.getObjectMapper() - ); + "delivery_receipts", + response.getContent(), + DeliveryReceipt.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.CONVERSATIONS.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.CONVERSATIONS.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/conversations/v1/service/user/UserConversation.java b/src/main/java/com/twilio/rest/conversations/v1/service/user/UserConversation.java index 555ae5a2c6..2b483f5b0c 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/service/user/UserConversation.java +++ b/src/main/java/com/twilio/rest/conversations/v1/service/user/UserConversation.java @@ -18,83 +18,107 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class UserConversation extends Resource { - private static final long serialVersionUID = 269317644556189L; - public static UserConversationDeleter deleter( - final String pathChatServiceSid, - final String pathUserSid, - final String pathConversationSid - ) { + public static UserConversationDeleter deleter(final String pathchatServiceSid, final String pathuserSid, final String pathconversationSid) { return new UserConversationDeleter( - pathChatServiceSid, - pathUserSid, - pathConversationSid + pathchatServiceSid, pathuserSid, pathconversationSid ); } - public static UserConversationFetcher fetcher( - final String pathChatServiceSid, - final String pathUserSid, - final String pathConversationSid - ) { + + public static UserConversationFetcher fetcher(final String pathchatServiceSid, final String pathuserSid, final String pathconversationSid) { return new UserConversationFetcher( - pathChatServiceSid, - pathUserSid, - pathConversationSid + pathchatServiceSid, pathuserSid, pathconversationSid ); } - public static UserConversationReader reader( - final String pathChatServiceSid, - final String pathUserSid - ) { - return new UserConversationReader(pathChatServiceSid, pathUserSid); + + public static UserConversationReader reader(final String pathchatServiceSid, final String pathuserSid) { + return new UserConversationReader( + pathchatServiceSid, pathuserSid + ); } - public static UserConversationUpdater updater( - final String pathChatServiceSid, - final String pathUserSid, - final String pathConversationSid - ) { + + public static UserConversationUpdater updater(final String pathchatServiceSid, final String pathuserSid, final String pathconversationSid) { return new UserConversationUpdater( - pathChatServiceSid, - pathUserSid, - pathConversationSid + pathchatServiceSid, pathuserSid, pathconversationSid ); } + + public enum State { + INACTIVE("inactive"), + ACTIVE("active"), + CLOSED("closed"); + + private final String value; + + private State(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static State forValue(final String value) { + return Promoter.enumFromString(value, State.values()); + } + } + + public enum NotificationLevel { + DEFAULT("default"), + MUTED("muted"); + + private final String value; + + private NotificationLevel(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static NotificationLevel forValue(final String value) { + return Promoter.enumFromString(value, NotificationLevel.values()); + } + } + + /** * Converts a JSON String into a UserConversation object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return UserConversation object represented by the provided JSON */ - public static UserConversation fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static UserConversation fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, UserConversation.class); @@ -109,14 +133,11 @@ public static UserConversation fromJson( * Converts a JSON InputStream into a UserConversation object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return UserConversation object represented by the provided JSON */ - public static UserConversation fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static UserConversation fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, UserConversation.class); @@ -127,144 +148,97 @@ public static UserConversation fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; + @Getter + private final String attributes; + @Getter private final String chatServiceSid; + @Getter private final String conversationSid; - private final Integer unreadMessagesCount; - private final Integer lastReadMessageIndex; - private final String participantSid; - private final String userSid; - private final String friendlyName; + @Getter private final UserConversation.State conversationState; - private final Map timers; - private final String attributes; + @Getter + private final String createdBy; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; - private final String createdBy; + @Getter + private final String friendlyName; + @Getter + private final Integer lastReadMessageIndex; + @Getter + private final Map links; + @Getter private final UserConversation.NotificationLevel notificationLevel; + @Getter + private final String participantSid; + @Getter + private final Object timers; + @Getter private final String uniqueName; + @Getter + private final Integer unreadMessagesCount; + @Getter private final URI url; - private final Map links; + @Getter + private final String userSid; @JsonCreator private UserConversation( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("chat_service_sid") final String chatServiceSid, - @JsonProperty("conversation_sid") final String conversationSid, - @JsonProperty( - "unread_messages_count" - ) final Integer unreadMessagesCount, - @JsonProperty( - "last_read_message_index" - ) final Integer lastReadMessageIndex, - @JsonProperty("participant_sid") final String participantSid, - @JsonProperty("user_sid") final String userSid, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty( - "conversation_state" - ) final UserConversation.State conversationState, - @JsonProperty("timers") final Map timers, - @JsonProperty("attributes") final String attributes, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("created_by") final String createdBy, - @JsonProperty( - "notification_level" - ) final UserConversation.NotificationLevel notificationLevel, - @JsonProperty("unique_name") final String uniqueName, - @JsonProperty("url") final URI url, - @JsonProperty("links") final Map links + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("attributes") final String attributes, + @JsonProperty("chat_service_sid") final String chatServiceSid, + @JsonProperty("conversation_sid") final String conversationSid, + @JsonProperty("conversation_state") final UserConversation.State conversationState, + @JsonProperty("created_by") final String createdBy, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("last_read_message_index") final Integer lastReadMessageIndex, + @JsonProperty("links") final Map links, + @JsonProperty("notification_level") final UserConversation.NotificationLevel notificationLevel, + @JsonProperty("participant_sid") final String participantSid, + @JsonProperty("timers") final Object timers, + @JsonProperty("unique_name") final String uniqueName, + @JsonProperty("unread_messages_count") final Integer unreadMessagesCount, + @JsonProperty("url") final URI url, + @JsonProperty("user_sid") final String userSid ) { this.accountSid = accountSid; + this.attributes = attributes; this.chatServiceSid = chatServiceSid; this.conversationSid = conversationSid; - this.unreadMessagesCount = unreadMessagesCount; - this.lastReadMessageIndex = lastReadMessageIndex; - this.participantSid = participantSid; - this.userSid = userSid; - this.friendlyName = friendlyName; this.conversationState = conversationState; - this.timers = timers; - this.attributes = attributes; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); this.createdBy = createdBy; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; + this.friendlyName = friendlyName; + this.lastReadMessageIndex = lastReadMessageIndex; + this.links = links; this.notificationLevel = notificationLevel; + this.participantSid = participantSid; + this.timers = timers; this.uniqueName = uniqueName; + this.unreadMessagesCount = unreadMessagesCount; this.url = url; - this.links = links; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getChatServiceSid() { - return this.chatServiceSid; - } - - public final String getConversationSid() { - return this.conversationSid; - } - - public final Integer getUnreadMessagesCount() { - return this.unreadMessagesCount; - } - - public final Integer getLastReadMessageIndex() { - return this.lastReadMessageIndex; - } - - public final String getParticipantSid() { - return this.participantSid; - } - - public final String getUserSid() { - return this.userSid; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final UserConversation.State getConversationState() { - return this.conversationState; - } - - public final Map getTimers() { - return this.timers; - } - - public final String getAttributes() { - return this.attributes; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final String getCreatedBy() { - return this.createdBy; - } - - public final UserConversation.NotificationLevel getNotificationLevel() { - return this.notificationLevel; - } - - public final String getUniqueName() { - return this.uniqueName; - } - - public final URI getUrl() { - return this.url; - } - - public final Map getLinks() { - return this.links; + this.userSid = userSid; } @Override @@ -278,91 +252,52 @@ public boolean equals(final Object o) { } UserConversation other = (UserConversation) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(chatServiceSid, other.chatServiceSid) && - Objects.equals(conversationSid, other.conversationSid) && - Objects.equals(unreadMessagesCount, other.unreadMessagesCount) && - Objects.equals(lastReadMessageIndex, other.lastReadMessageIndex) && - Objects.equals(participantSid, other.participantSid) && - Objects.equals(userSid, other.userSid) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(conversationState, other.conversationState) && - Objects.equals(timers, other.timers) && - Objects.equals(attributes, other.attributes) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(createdBy, other.createdBy) && - Objects.equals(notificationLevel, other.notificationLevel) && - Objects.equals(uniqueName, other.uniqueName) && - Objects.equals(url, other.url) && - Objects.equals(links, other.links) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(attributes, other.attributes) && + Objects.equals(chatServiceSid, other.chatServiceSid) && + Objects.equals(conversationSid, other.conversationSid) && + Objects.equals(conversationState, other.conversationState) && + Objects.equals(createdBy, other.createdBy) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(lastReadMessageIndex, other.lastReadMessageIndex) && + Objects.equals(links, other.links) && + Objects.equals(notificationLevel, other.notificationLevel) && + Objects.equals(participantSid, other.participantSid) && + Objects.equals(timers, other.timers) && + Objects.equals(uniqueName, other.uniqueName) && + Objects.equals(unreadMessagesCount, other.unreadMessagesCount) && + Objects.equals(url, other.url) && + Objects.equals(userSid, other.userSid) ); } @Override public int hashCode() { return Objects.hash( - accountSid, - chatServiceSid, - conversationSid, - unreadMessagesCount, - lastReadMessageIndex, - participantSid, - userSid, - friendlyName, - conversationState, - timers, - attributes, - dateCreated, - dateUpdated, - createdBy, - notificationLevel, - uniqueName, - url, - links + accountSid, + attributes, + chatServiceSid, + conversationSid, + conversationState, + createdBy, + dateCreated, + dateUpdated, + friendlyName, + lastReadMessageIndex, + links, + notificationLevel, + participantSid, + timers, + uniqueName, + unreadMessagesCount, + url, + userSid ); } - public enum NotificationLevel { - DEFAULT("default"), - MUTED("muted"); - - private final String value; - - private NotificationLevel(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static NotificationLevel forValue(final String value) { - return Promoter.enumFromString(value, NotificationLevel.values()); - } - } - - public enum State { - INACTIVE("inactive"), - ACTIVE("active"), - CLOSED("closed"); - - private final String value; - - private State(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - @JsonCreator - public static State forValue(final String value) { - return Promoter.enumFromString(value, State.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/conversations/v1/service/user/UserConversationDeleter.java b/src/main/java/com/twilio/rest/conversations/v1/service/user/UserConversationDeleter.java index 0a752534dd..f8a2d6cef8 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/service/user/UserConversationDeleter.java +++ b/src/main/java/com/twilio/rest/conversations/v1/service/user/UserConversationDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.conversations.v1.service.user; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,59 +26,44 @@ public class UserConversationDeleter extends Deleter { - private String pathChatServiceSid; - private String pathUserSid; - private String pathConversationSid; + private String pathchatServiceSid; + private String pathuserSid; + private String pathconversationSid; - public UserConversationDeleter( - final String pathChatServiceSid, - final String pathUserSid, - final String pathConversationSid - ) { - this.pathChatServiceSid = pathChatServiceSid; - this.pathUserSid = pathUserSid; - this.pathConversationSid = pathConversationSid; + public UserConversationDeleter(final String pathchatServiceSid, final String pathuserSid, final String pathconversationSid) { + this.pathchatServiceSid = pathchatServiceSid; + this.pathuserSid = pathuserSid; + this.pathconversationSid = pathconversationSid; } + @Override public boolean delete(final TwilioRestClient client) { - String path = - "/v1/Services/{ChatServiceSid}/Users/{UserSid}/Conversations/{ConversationSid}"; - path = - path.replace( - "{" + "ChatServiceSid" + "}", - this.pathChatServiceSid.toString() - ); - path = path.replace("{" + "UserSid" + "}", this.pathUserSid.toString()); - path = - path.replace( - "{" + "ConversationSid" + "}", - this.pathConversationSid.toString() - ); + String path = "/v1/Services/{ChatServiceSid}/Users/{UserSid}/Conversations/{ConversationSid}"; + + path = path.replace("{" + "ChatServiceSid" + "}", this.pathchatServiceSid.toString()); + path = path.replace("{" + "UserSid" + "}", this.pathuserSid.toString()); + path = path.replace("{" + "ConversationSid" + "}", this.pathconversationSid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.CONVERSATIONS.toString(), - path + HttpMethod.DELETE, + Domains.CONVERSATIONS.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "UserConversation delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("UserConversation delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/conversations/v1/service/user/UserConversationFetcher.java b/src/main/java/com/twilio/rest/conversations/v1/service/user/UserConversationFetcher.java index 02c937fca3..6496f5822e 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/service/user/UserConversationFetcher.java +++ b/src/main/java/com/twilio/rest/conversations/v1/service/user/UserConversationFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.conversations.v1.service.user; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,66 +26,47 @@ public class UserConversationFetcher extends Fetcher { - private String pathChatServiceSid; - private String pathUserSid; - private String pathConversationSid; + private String pathchatServiceSid; + private String pathuserSid; + private String pathconversationSid; - public UserConversationFetcher( - final String pathChatServiceSid, - final String pathUserSid, - final String pathConversationSid - ) { - this.pathChatServiceSid = pathChatServiceSid; - this.pathUserSid = pathUserSid; - this.pathConversationSid = pathConversationSid; + public UserConversationFetcher(final String pathchatServiceSid, final String pathuserSid, final String pathconversationSid) { + this.pathchatServiceSid = pathchatServiceSid; + this.pathuserSid = pathuserSid; + this.pathconversationSid = pathconversationSid; } + @Override public UserConversation fetch(final TwilioRestClient client) { - String path = - "/v1/Services/{ChatServiceSid}/Users/{UserSid}/Conversations/{ConversationSid}"; - path = - path.replace( - "{" + "ChatServiceSid" + "}", - this.pathChatServiceSid.toString() - ); - path = path.replace("{" + "UserSid" + "}", this.pathUserSid.toString()); - path = - path.replace( - "{" + "ConversationSid" + "}", - this.pathConversationSid.toString() - ); + String path = "/v1/Services/{ChatServiceSid}/Users/{UserSid}/Conversations/{ConversationSid}"; + + path = path.replace("{" + "ChatServiceSid" + "}", this.pathchatServiceSid.toString()); + path = path.replace("{" + "UserSid" + "}", this.pathuserSid.toString()); + path = path.replace("{" + "ConversationSid" + "}", this.pathconversationSid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.CONVERSATIONS.toString(), - path + HttpMethod.GET, + Domains.CONVERSATIONS.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "UserConversation fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("UserConversation fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return UserConversation.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return UserConversation.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/conversations/v1/service/user/UserConversationReader.java b/src/main/java/com/twilio/rest/conversations/v1/service/user/UserConversationReader.java index 0b4da0a25d..51aa91bd39 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/service/user/UserConversationReader.java +++ b/src/main/java/com/twilio/rest/conversations/v1/service/user/UserConversationReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,122 +30,91 @@ public class UserConversationReader extends Reader { - private String pathChatServiceSid; - private String pathUserSid; + private String pathchatServiceSid; + private String pathuserSid; private Long pageSize; - public UserConversationReader( - final String pathChatServiceSid, - final String pathUserSid - ) { - this.pathChatServiceSid = pathChatServiceSid; - this.pathUserSid = pathUserSid; + public UserConversationReader(final String pathchatServiceSid, final String pathuserSid) { + this.pathchatServiceSid = pathchatServiceSid; + this.pathuserSid = pathuserSid; } + public UserConversationReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { - String path = - "/v1/Services/{ChatServiceSid}/Users/{UserSid}/Conversations"; - path = - path.replace( - "{" + "ChatServiceSid" + "}", - this.pathChatServiceSid.toString() - ); - path = path.replace("{" + "UserSid" + "}", this.pathUserSid.toString()); + + String path = "/v1/Services/{ChatServiceSid}/Users/{UserSid}/Conversations"; + + path = path.replace("{" + "ChatServiceSid" + "}", this.pathchatServiceSid.toString()); + path = path.replace("{" + "UserSid" + "}", this.pathuserSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.CONVERSATIONS.toString(), - path + HttpMethod.GET, + Domains.CONVERSATIONS.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "UserConversation read failed: Unable to connect to server" - ); + throw new ApiConnectionException("UserConversation read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "conversations", - response.getContent(), - UserConversation.class, - client.getObjectMapper() - ); + "conversations", + response.getContent(), + UserConversation.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.CONVERSATIONS.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.CONVERSATIONS.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/conversations/v1/service/user/UserConversationUpdater.java b/src/main/java/com/twilio/rest/conversations/v1/service/user/UserConversationUpdater.java index abcf05d056..569e336f8a 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/service/user/UserConversationUpdater.java +++ b/src/main/java/com/twilio/rest/conversations/v1/service/user/UserConversationUpdater.java @@ -16,6 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -24,115 +26,94 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.time.ZonedDateTime; public class UserConversationUpdater extends Updater { - - private String pathChatServiceSid; - private String pathUserSid; - private String pathConversationSid; + private String pathchatServiceSid; + private String pathuserSid; + private String pathconversationSid; private UserConversation.NotificationLevel notificationLevel; private ZonedDateTime lastReadTimestamp; private Integer lastReadMessageIndex; - public UserConversationUpdater( - final String pathChatServiceSid, - final String pathUserSid, - final String pathConversationSid - ) { - this.pathChatServiceSid = pathChatServiceSid; - this.pathUserSid = pathUserSid; - this.pathConversationSid = pathConversationSid; + public UserConversationUpdater(final String pathchatServiceSid, final String pathuserSid, final String pathconversationSid) { + this.pathchatServiceSid = pathchatServiceSid; + this.pathuserSid = pathuserSid; + this.pathconversationSid = pathconversationSid; } - public UserConversationUpdater setNotificationLevel( - final UserConversation.NotificationLevel notificationLevel - ) { + + public UserConversationUpdater setNotificationLevel(final UserConversation.NotificationLevel notificationLevel) { this.notificationLevel = notificationLevel; return this; } - public UserConversationUpdater setLastReadTimestamp( - final ZonedDateTime lastReadTimestamp - ) { + + public UserConversationUpdater setLastReadTimestamp(final ZonedDateTime lastReadTimestamp) { this.lastReadTimestamp = lastReadTimestamp; return this; } - public UserConversationUpdater setLastReadMessageIndex( - final Integer lastReadMessageIndex - ) { + + public UserConversationUpdater setLastReadMessageIndex(final Integer lastReadMessageIndex) { this.lastReadMessageIndex = lastReadMessageIndex; return this; } + @Override public UserConversation update(final TwilioRestClient client) { - String path = - "/v1/Services/{ChatServiceSid}/Users/{UserSid}/Conversations/{ConversationSid}"; - path = - path.replace( - "{" + "ChatServiceSid" + "}", - this.pathChatServiceSid.toString() - ); - path = path.replace("{" + "UserSid" + "}", this.pathUserSid.toString()); - path = - path.replace( - "{" + "ConversationSid" + "}", - this.pathConversationSid.toString() - ); + String path = "/v1/Services/{ChatServiceSid}/Users/{UserSid}/Conversations/{ConversationSid}"; + + path = path.replace("{" + "ChatServiceSid" + "}", this.pathchatServiceSid.toString()); + path = path.replace("{" + "UserSid" + "}", this.pathuserSid.toString()); + path = path.replace("{" + "ConversationSid" + "}", this.pathconversationSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.CONVERSATIONS.toString(), - path + HttpMethod.POST, + Domains.CONVERSATIONS.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "UserConversation update failed: Unable to connect to server" - ); + throw new ApiConnectionException("UserConversation update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return UserConversation.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return UserConversation.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (notificationLevel != null) { - request.addPostParam( - "NotificationLevel", - notificationLevel.toString() - ); + Serializer.toString(request, "NotificationLevel", notificationLevel, ParameterType.URLENCODED); } + + if (lastReadTimestamp != null) { - request.addPostParam( - "LastReadTimestamp", - lastReadTimestamp.toInstant().toString() - ); + Serializer.toString(request, "LastReadTimestamp", lastReadTimestamp, ParameterType.URLENCODED); } + + if (lastReadMessageIndex != null) { - request.addPostParam( - "LastReadMessageIndex", - lastReadMessageIndex.toString() - ); + Serializer.toString(request, "LastReadMessageIndex", lastReadMessageIndex, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/conversations/v1/user/UserConversation.java b/src/main/java/com/twilio/rest/conversations/v1/user/UserConversation.java index 2b21907430..25db96c1aa 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/user/UserConversation.java +++ b/src/main/java/com/twilio/rest/conversations/v1/user/UserConversation.java @@ -18,65 +18,107 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class UserConversation extends Resource { - private static final long serialVersionUID = 269317644556189L; - public static UserConversationDeleter deleter( - final String pathUserSid, - final String pathConversationSid - ) { - return new UserConversationDeleter(pathUserSid, pathConversationSid); + public static UserConversationDeleter deleter(final String pathuserSid, final String pathconversationSid) { + return new UserConversationDeleter( + pathuserSid, pathconversationSid + ); } - public static UserConversationFetcher fetcher( - final String pathUserSid, - final String pathConversationSid - ) { - return new UserConversationFetcher(pathUserSid, pathConversationSid); + + public static UserConversationFetcher fetcher(final String pathuserSid, final String pathconversationSid) { + return new UserConversationFetcher( + pathuserSid, pathconversationSid + ); } - public static UserConversationReader reader(final String pathUserSid) { - return new UserConversationReader(pathUserSid); + + public static UserConversationReader reader(final String pathuserSid) { + return new UserConversationReader( + pathuserSid + ); } - public static UserConversationUpdater updater( - final String pathUserSid, - final String pathConversationSid - ) { - return new UserConversationUpdater(pathUserSid, pathConversationSid); + + public static UserConversationUpdater updater(final String pathuserSid, final String pathconversationSid) { + return new UserConversationUpdater( + pathuserSid, pathconversationSid + ); } + + public enum State { + INACTIVE("inactive"), + ACTIVE("active"), + CLOSED("closed"); + + private final String value; + + private State(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static State forValue(final String value) { + return Promoter.enumFromString(value, State.values()); + } + } + + public enum NotificationLevel { + DEFAULT("default"), + MUTED("muted"); + + private final String value; + + private NotificationLevel(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static NotificationLevel forValue(final String value) { + return Promoter.enumFromString(value, NotificationLevel.values()); + } + } + + /** * Converts a JSON String into a UserConversation object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return UserConversation object represented by the provided JSON */ - public static UserConversation fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static UserConversation fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, UserConversation.class); @@ -91,14 +133,11 @@ public static UserConversation fromJson( * Converts a JSON InputStream into a UserConversation object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return UserConversation object represented by the provided JSON */ - public static UserConversation fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static UserConversation fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, UserConversation.class); @@ -109,144 +148,97 @@ public static UserConversation fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; + @Getter + private final String attributes; + @Getter private final String chatServiceSid; + @Getter private final String conversationSid; - private final Integer unreadMessagesCount; - private final Integer lastReadMessageIndex; - private final String participantSid; - private final String userSid; - private final String friendlyName; + @Getter private final UserConversation.State conversationState; - private final Map timers; - private final String attributes; + @Getter + private final String createdBy; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; - private final String createdBy; + @Getter + private final String friendlyName; + @Getter + private final Integer lastReadMessageIndex; + @Getter + private final Map links; + @Getter private final UserConversation.NotificationLevel notificationLevel; + @Getter + private final String participantSid; + @Getter + private final Object timers; + @Getter private final String uniqueName; + @Getter + private final Integer unreadMessagesCount; + @Getter private final URI url; - private final Map links; + @Getter + private final String userSid; @JsonCreator private UserConversation( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("chat_service_sid") final String chatServiceSid, - @JsonProperty("conversation_sid") final String conversationSid, - @JsonProperty( - "unread_messages_count" - ) final Integer unreadMessagesCount, - @JsonProperty( - "last_read_message_index" - ) final Integer lastReadMessageIndex, - @JsonProperty("participant_sid") final String participantSid, - @JsonProperty("user_sid") final String userSid, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty( - "conversation_state" - ) final UserConversation.State conversationState, - @JsonProperty("timers") final Map timers, - @JsonProperty("attributes") final String attributes, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("created_by") final String createdBy, - @JsonProperty( - "notification_level" - ) final UserConversation.NotificationLevel notificationLevel, - @JsonProperty("unique_name") final String uniqueName, - @JsonProperty("url") final URI url, - @JsonProperty("links") final Map links + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("attributes") final String attributes, + @JsonProperty("chat_service_sid") final String chatServiceSid, + @JsonProperty("conversation_sid") final String conversationSid, + @JsonProperty("conversation_state") final UserConversation.State conversationState, + @JsonProperty("created_by") final String createdBy, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("last_read_message_index") final Integer lastReadMessageIndex, + @JsonProperty("links") final Map links, + @JsonProperty("notification_level") final UserConversation.NotificationLevel notificationLevel, + @JsonProperty("participant_sid") final String participantSid, + @JsonProperty("timers") final Object timers, + @JsonProperty("unique_name") final String uniqueName, + @JsonProperty("unread_messages_count") final Integer unreadMessagesCount, + @JsonProperty("url") final URI url, + @JsonProperty("user_sid") final String userSid ) { this.accountSid = accountSid; + this.attributes = attributes; this.chatServiceSid = chatServiceSid; this.conversationSid = conversationSid; - this.unreadMessagesCount = unreadMessagesCount; - this.lastReadMessageIndex = lastReadMessageIndex; - this.participantSid = participantSid; - this.userSid = userSid; - this.friendlyName = friendlyName; this.conversationState = conversationState; - this.timers = timers; - this.attributes = attributes; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); this.createdBy = createdBy; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; + this.friendlyName = friendlyName; + this.lastReadMessageIndex = lastReadMessageIndex; + this.links = links; this.notificationLevel = notificationLevel; + this.participantSid = participantSid; + this.timers = timers; this.uniqueName = uniqueName; + this.unreadMessagesCount = unreadMessagesCount; this.url = url; - this.links = links; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getChatServiceSid() { - return this.chatServiceSid; - } - - public final String getConversationSid() { - return this.conversationSid; - } - - public final Integer getUnreadMessagesCount() { - return this.unreadMessagesCount; - } - - public final Integer getLastReadMessageIndex() { - return this.lastReadMessageIndex; - } - - public final String getParticipantSid() { - return this.participantSid; - } - - public final String getUserSid() { - return this.userSid; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final UserConversation.State getConversationState() { - return this.conversationState; - } - - public final Map getTimers() { - return this.timers; - } - - public final String getAttributes() { - return this.attributes; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final String getCreatedBy() { - return this.createdBy; - } - - public final UserConversation.NotificationLevel getNotificationLevel() { - return this.notificationLevel; - } - - public final String getUniqueName() { - return this.uniqueName; - } - - public final URI getUrl() { - return this.url; - } - - public final Map getLinks() { - return this.links; + this.userSid = userSid; } @Override @@ -260,91 +252,52 @@ public boolean equals(final Object o) { } UserConversation other = (UserConversation) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(chatServiceSid, other.chatServiceSid) && - Objects.equals(conversationSid, other.conversationSid) && - Objects.equals(unreadMessagesCount, other.unreadMessagesCount) && - Objects.equals(lastReadMessageIndex, other.lastReadMessageIndex) && - Objects.equals(participantSid, other.participantSid) && - Objects.equals(userSid, other.userSid) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(conversationState, other.conversationState) && - Objects.equals(timers, other.timers) && - Objects.equals(attributes, other.attributes) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(createdBy, other.createdBy) && - Objects.equals(notificationLevel, other.notificationLevel) && - Objects.equals(uniqueName, other.uniqueName) && - Objects.equals(url, other.url) && - Objects.equals(links, other.links) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(attributes, other.attributes) && + Objects.equals(chatServiceSid, other.chatServiceSid) && + Objects.equals(conversationSid, other.conversationSid) && + Objects.equals(conversationState, other.conversationState) && + Objects.equals(createdBy, other.createdBy) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(lastReadMessageIndex, other.lastReadMessageIndex) && + Objects.equals(links, other.links) && + Objects.equals(notificationLevel, other.notificationLevel) && + Objects.equals(participantSid, other.participantSid) && + Objects.equals(timers, other.timers) && + Objects.equals(uniqueName, other.uniqueName) && + Objects.equals(unreadMessagesCount, other.unreadMessagesCount) && + Objects.equals(url, other.url) && + Objects.equals(userSid, other.userSid) ); } @Override public int hashCode() { return Objects.hash( - accountSid, - chatServiceSid, - conversationSid, - unreadMessagesCount, - lastReadMessageIndex, - participantSid, - userSid, - friendlyName, - conversationState, - timers, - attributes, - dateCreated, - dateUpdated, - createdBy, - notificationLevel, - uniqueName, - url, - links + accountSid, + attributes, + chatServiceSid, + conversationSid, + conversationState, + createdBy, + dateCreated, + dateUpdated, + friendlyName, + lastReadMessageIndex, + links, + notificationLevel, + participantSid, + timers, + uniqueName, + unreadMessagesCount, + url, + userSid ); } - public enum State { - INACTIVE("inactive"), - ACTIVE("active"), - CLOSED("closed"); - - private final String value; - - private State(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static State forValue(final String value) { - return Promoter.enumFromString(value, State.values()); - } - } - - public enum NotificationLevel { - DEFAULT("default"), - MUTED("muted"); - - private final String value; - - private NotificationLevel(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - @JsonCreator - public static NotificationLevel forValue(final String value) { - return Promoter.enumFromString(value, NotificationLevel.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/conversations/v1/user/UserConversationDeleter.java b/src/main/java/com/twilio/rest/conversations/v1/user/UserConversationDeleter.java index e50c7bdd57..24745e981b 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/user/UserConversationDeleter.java +++ b/src/main/java/com/twilio/rest/conversations/v1/user/UserConversationDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.conversations.v1.user; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,50 +26,41 @@ public class UserConversationDeleter extends Deleter { - private String pathUserSid; - private String pathConversationSid; + private String pathuserSid; + private String pathconversationSid; - public UserConversationDeleter( - final String pathUserSid, - final String pathConversationSid - ) { - this.pathUserSid = pathUserSid; - this.pathConversationSid = pathConversationSid; + public UserConversationDeleter(final String pathuserSid, final String pathconversationSid) { + this.pathuserSid = pathuserSid; + this.pathconversationSid = pathconversationSid; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/v1/Users/{UserSid}/Conversations/{ConversationSid}"; - path = path.replace("{" + "UserSid" + "}", this.pathUserSid.toString()); - path = - path.replace( - "{" + "ConversationSid" + "}", - this.pathConversationSid.toString() - ); + path = path.replace("{" + "UserSid" + "}", this.pathuserSid.toString()); + path = path.replace("{" + "ConversationSid" + "}", this.pathconversationSid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.CONVERSATIONS.toString(), - path + HttpMethod.DELETE, + Domains.CONVERSATIONS.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "UserConversation delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("UserConversation delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/conversations/v1/user/UserConversationFetcher.java b/src/main/java/com/twilio/rest/conversations/v1/user/UserConversationFetcher.java index e1def3a8dc..edcf98afe7 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/user/UserConversationFetcher.java +++ b/src/main/java/com/twilio/rest/conversations/v1/user/UserConversationFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.conversations.v1.user; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,57 +26,44 @@ public class UserConversationFetcher extends Fetcher { - private String pathUserSid; - private String pathConversationSid; + private String pathuserSid; + private String pathconversationSid; - public UserConversationFetcher( - final String pathUserSid, - final String pathConversationSid - ) { - this.pathUserSid = pathUserSid; - this.pathConversationSid = pathConversationSid; + public UserConversationFetcher(final String pathuserSid, final String pathconversationSid) { + this.pathuserSid = pathuserSid; + this.pathconversationSid = pathconversationSid; } + @Override public UserConversation fetch(final TwilioRestClient client) { + String path = "/v1/Users/{UserSid}/Conversations/{ConversationSid}"; - path = path.replace("{" + "UserSid" + "}", this.pathUserSid.toString()); - path = - path.replace( - "{" + "ConversationSid" + "}", - this.pathConversationSid.toString() - ); + path = path.replace("{" + "UserSid" + "}", this.pathuserSid.toString()); + path = path.replace("{" + "ConversationSid" + "}", this.pathconversationSid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.CONVERSATIONS.toString(), - path + HttpMethod.GET, + Domains.CONVERSATIONS.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "UserConversation fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("UserConversation fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return UserConversation.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return UserConversation.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/conversations/v1/user/UserConversationReader.java b/src/main/java/com/twilio/rest/conversations/v1/user/UserConversationReader.java index bf1391536d..60a5180a18 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/user/UserConversationReader.java +++ b/src/main/java/com/twilio/rest/conversations/v1/user/UserConversationReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,111 +30,88 @@ public class UserConversationReader extends Reader { - private String pathUserSid; + private String pathuserSid; private Long pageSize; - public UserConversationReader(final String pathUserSid) { - this.pathUserSid = pathUserSid; + public UserConversationReader(final String pathuserSid) { + this.pathuserSid = pathuserSid; } + public UserConversationReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/Users/{UserSid}/Conversations"; - path = path.replace("{" + "UserSid" + "}", this.pathUserSid.toString()); + + path = path.replace("{" + "UserSid" + "}", this.pathuserSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.CONVERSATIONS.toString(), - path + HttpMethod.GET, + Domains.CONVERSATIONS.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "UserConversation read failed: Unable to connect to server" - ); + throw new ApiConnectionException("UserConversation read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "conversations", - response.getContent(), - UserConversation.class, - client.getObjectMapper() - ); + "conversations", + response.getContent(), + UserConversation.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.CONVERSATIONS.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.CONVERSATIONS.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/conversations/v1/user/UserConversationUpdater.java b/src/main/java/com/twilio/rest/conversations/v1/user/UserConversationUpdater.java index 328caa73d8..55c817ad90 100644 --- a/src/main/java/com/twilio/rest/conversations/v1/user/UserConversationUpdater.java +++ b/src/main/java/com/twilio/rest/conversations/v1/user/UserConversationUpdater.java @@ -16,6 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -24,106 +26,91 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.time.ZonedDateTime; public class UserConversationUpdater extends Updater { - - private String pathUserSid; - private String pathConversationSid; + private String pathuserSid; + private String pathconversationSid; private UserConversation.NotificationLevel notificationLevel; private ZonedDateTime lastReadTimestamp; private Integer lastReadMessageIndex; - public UserConversationUpdater( - final String pathUserSid, - final String pathConversationSid - ) { - this.pathUserSid = pathUserSid; - this.pathConversationSid = pathConversationSid; + public UserConversationUpdater(final String pathuserSid, final String pathconversationSid) { + this.pathuserSid = pathuserSid; + this.pathconversationSid = pathconversationSid; } - public UserConversationUpdater setNotificationLevel( - final UserConversation.NotificationLevel notificationLevel - ) { + + public UserConversationUpdater setNotificationLevel(final UserConversation.NotificationLevel notificationLevel) { this.notificationLevel = notificationLevel; return this; } - public UserConversationUpdater setLastReadTimestamp( - final ZonedDateTime lastReadTimestamp - ) { + + public UserConversationUpdater setLastReadTimestamp(final ZonedDateTime lastReadTimestamp) { this.lastReadTimestamp = lastReadTimestamp; return this; } - public UserConversationUpdater setLastReadMessageIndex( - final Integer lastReadMessageIndex - ) { + + public UserConversationUpdater setLastReadMessageIndex(final Integer lastReadMessageIndex) { this.lastReadMessageIndex = lastReadMessageIndex; return this; } + @Override public UserConversation update(final TwilioRestClient client) { + String path = "/v1/Users/{UserSid}/Conversations/{ConversationSid}"; - path = path.replace("{" + "UserSid" + "}", this.pathUserSid.toString()); - path = - path.replace( - "{" + "ConversationSid" + "}", - this.pathConversationSid.toString() - ); + path = path.replace("{" + "UserSid" + "}", this.pathuserSid.toString()); + path = path.replace("{" + "ConversationSid" + "}", this.pathconversationSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.CONVERSATIONS.toString(), - path + HttpMethod.POST, + Domains.CONVERSATIONS.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "UserConversation update failed: Unable to connect to server" - ); + throw new ApiConnectionException("UserConversation update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return UserConversation.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return UserConversation.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (notificationLevel != null) { - request.addPostParam( - "NotificationLevel", - notificationLevel.toString() - ); + Serializer.toString(request, "NotificationLevel", notificationLevel, ParameterType.URLENCODED); } + + if (lastReadTimestamp != null) { - request.addPostParam( - "LastReadTimestamp", - lastReadTimestamp.toInstant().toString() - ); + Serializer.toString(request, "LastReadTimestamp", lastReadTimestamp, ParameterType.URLENCODED); } + + if (lastReadMessageIndex != null) { - request.addPostParam( - "LastReadMessageIndex", - lastReadMessageIndex.toString() - ); + Serializer.toString(request, "LastReadMessageIndex", lastReadMessageIndex, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/events/v1/EventType.java b/src/main/java/com/twilio/rest/events/v1/EventType.java index 46d98ad012..a95433a5ea 100644 --- a/src/main/java/com/twilio/rest/events/v1/EventType.java +++ b/src/main/java/com/twilio/rest/events/v1/EventType.java @@ -18,47 +18,50 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class EventType extends Resource { - private static final long serialVersionUID = 10451435371801L; - public static EventTypeFetcher fetcher(final String pathType) { - return new EventTypeFetcher(pathType); + public static EventTypeFetcher fetcher(final String pathtype) { + return new EventTypeFetcher( + pathtype + ); } + public static EventTypeReader reader() { - return new EventTypeReader(); + return new EventTypeReader( + + ); } + /** * Converts a JSON String into a EventType object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return EventType object represented by the provided JSON */ - public static EventType fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static EventType fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, EventType.class); @@ -73,14 +76,11 @@ public static EventType fromJson( * Converts a JSON InputStream into a EventType object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return EventType object represented by the provided JSON */ - public static EventType fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static EventType fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, EventType.class); @@ -91,73 +91,61 @@ public static EventType fromJson( } } - private final String type; - private final String schemaId; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; + @Getter private final String description; - private final String status; + @Getter private final String documentationUrl; - private final URI url; + @Getter private final Map links; + @Getter + private final String schemaId; + @Getter + private final String status; + @Getter + private final String type; + @Getter + private final URI url; @JsonCreator private EventType( - @JsonProperty("type") final String type, - @JsonProperty("schema_id") final String schemaId, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("description") final String description, - @JsonProperty("status") final String status, - @JsonProperty("documentation_url") final String documentationUrl, - @JsonProperty("url") final URI url, - @JsonProperty("links") final Map links + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("description") final String description, + @JsonProperty("documentation_url") final String documentationUrl, + @JsonProperty("links") final Map links, + @JsonProperty("schema_id") final String schemaId, + @JsonProperty("status") final String status, + @JsonProperty("type") final String type, + @JsonProperty("url") final URI url ) { - this.type = type; - this.schemaId = schemaId; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.description = description; - this.status = status; this.documentationUrl = documentationUrl; - this.url = url; this.links = links; - } - - public final String getType() { - return this.type; - } - - public final String getSchemaId() { - return this.schemaId; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final String getDescription() { - return this.description; - } - - public final String getStatus() { - return this.status; - } - - public final String getDocumentationUrl() { - return this.documentationUrl; - } - - public final URI getUrl() { - return this.url; - } - - public final Map getLinks() { - return this.links; + this.schemaId = schemaId; + this.status = status; + this.type = type; + this.url = url; } @Override @@ -171,32 +159,34 @@ public boolean equals(final Object o) { } EventType other = (EventType) o; - return ( - Objects.equals(type, other.type) && - Objects.equals(schemaId, other.schemaId) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(description, other.description) && - Objects.equals(status, other.status) && - Objects.equals(documentationUrl, other.documentationUrl) && - Objects.equals(url, other.url) && - Objects.equals(links, other.links) + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(description, other.description) && + Objects.equals(documentationUrl, other.documentationUrl) && + Objects.equals(links, other.links) && + Objects.equals(schemaId, other.schemaId) && + Objects.equals(status, other.status) && + Objects.equals(type, other.type) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - type, - schemaId, - dateCreated, - dateUpdated, - description, - status, - documentationUrl, - url, - links + dateCreated, + dateUpdated, + description, + documentationUrl, + links, + schemaId, + status, + type, + url ); } + + } + diff --git a/src/main/java/com/twilio/rest/events/v1/EventTypeFetcher.java b/src/main/java/com/twilio/rest/events/v1/EventTypeFetcher.java index 0a1d9d6002..702064cc8d 100644 --- a/src/main/java/com/twilio/rest/events/v1/EventTypeFetcher.java +++ b/src/main/java/com/twilio/rest/events/v1/EventTypeFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.events.v1; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,47 +26,41 @@ public class EventTypeFetcher extends Fetcher { - private String pathType; + private String pathtype; - public EventTypeFetcher(final String pathType) { - this.pathType = pathType; + public EventTypeFetcher(final String pathtype) { + this.pathtype = pathtype; } + @Override public EventType fetch(final TwilioRestClient client) { + String path = "/v1/Types/{Type}"; - path = path.replace("{" + "Type" + "}", this.pathType.toString()); + path = path.replace("{" + "Type" + "}", this.pathtype.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.EVENTS.toString(), - path + HttpMethod.GET, + Domains.EVENTS.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "EventType fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("EventType fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return EventType.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return EventType.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/events/v1/EventTypeReader.java b/src/main/java/com/twilio/rest/events/v1/EventTypeReader.java index 674890cc5e..6438d3041b 100644 --- a/src/main/java/com/twilio/rest/events/v1/EventTypeReader.java +++ b/src/main/java/com/twilio/rest/events/v1/EventTypeReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -32,113 +33,94 @@ public class EventTypeReader extends Reader { private String schemaId; private Long pageSize; - public EventTypeReader() {} + public EventTypeReader() { + } + public EventTypeReader setSchemaId(final String schemaId) { this.schemaId = schemaId; return this; } + public EventTypeReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/Types"; + Request request = new Request( - HttpMethod.GET, - Domains.EVENTS.toString(), - path + HttpMethod.GET, + Domains.EVENTS.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "EventType read failed: Unable to connect to server" - ); + throw new ApiConnectionException("EventType read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "types", - response.getContent(), - EventType.class, - client.getObjectMapper() - ); + "types", + response.getContent(), + EventType.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.EVENTS.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.EVENTS.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (schemaId != null) { - request.addQueryParam("SchemaId", schemaId); + Serializer.toString(request, "SchemaId", schemaId, ParameterType.QUERY); } + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/events/v1/Schema.java b/src/main/java/com/twilio/rest/events/v1/Schema.java index 09155b0f8c..d5a68b040d 100644 --- a/src/main/java/com/twilio/rest/events/v1/Schema.java +++ b/src/main/java/com/twilio/rest/events/v1/Schema.java @@ -18,43 +18,43 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Schema extends Resource { - private static final long serialVersionUID = 100183907119303L; - public static SchemaFetcher fetcher(final String pathId) { - return new SchemaFetcher(pathId); + public static SchemaFetcher fetcher(final String pathid) { + return new SchemaFetcher( + pathid + ); } + /** * Converts a JSON String into a Schema object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Schema object represented by the provided JSON */ - public static Schema fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Schema fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Schema.class); @@ -69,14 +69,11 @@ public static Schema fromJson( * Converts a JSON InputStream into a Schema object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Schema object represented by the provided JSON */ - public static Schema fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Schema fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Schema.class); @@ -87,48 +84,44 @@ public static Schema fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String id; - private final URI url; - private final Map links; - private final ZonedDateTime latestVersionDateCreated; + @Getter private final Integer latestVersion; + @Getter + private final ZonedDateTime latestVersionDateCreated; + @Getter + private final Map links; + @Getter + private final URI url; @JsonCreator private Schema( - @JsonProperty("id") final String id, - @JsonProperty("url") final URI url, - @JsonProperty("links") final Map links, - @JsonProperty( - "latest_version_date_created" - ) final String latestVersionDateCreated, - @JsonProperty("latest_version") final Integer latestVersion + @JsonProperty("id") final String id, + @JsonProperty("latest_version") final Integer latestVersion, + @JsonProperty("latest_version_date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime latestVersionDateCreated, + @JsonProperty("links") final Map links, + @JsonProperty("url") final URI url ) { this.id = id; - this.url = url; - this.links = links; - this.latestVersionDateCreated = - DateConverter.iso8601DateTimeFromString(latestVersionDateCreated); this.latestVersion = latestVersion; - } - - public final String getId() { - return this.id; - } - - public final URI getUrl() { - return this.url; - } - - public final Map getLinks() { - return this.links; - } - - public final ZonedDateTime getLatestVersionDateCreated() { - return this.latestVersionDateCreated; - } - - public final Integer getLatestVersion() { - return this.latestVersion; + this.latestVersionDateCreated = latestVersionDateCreated; + this.links = links; + this.url = url; } @Override @@ -142,27 +135,26 @@ public boolean equals(final Object o) { } Schema other = (Schema) o; - return ( - Objects.equals(id, other.id) && - Objects.equals(url, other.url) && - Objects.equals(links, other.links) && - Objects.equals( - latestVersionDateCreated, - other.latestVersionDateCreated - ) && - Objects.equals(latestVersion, other.latestVersion) + Objects.equals(id, other.id) && + Objects.equals(latestVersion, other.latestVersion) && + Objects.equals(latestVersionDateCreated, other.latestVersionDateCreated) && + Objects.equals(links, other.links) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - id, - url, - links, - latestVersionDateCreated, - latestVersion + id, + latestVersion, + latestVersionDateCreated, + links, + url ); } + + } + diff --git a/src/main/java/com/twilio/rest/events/v1/SchemaFetcher.java b/src/main/java/com/twilio/rest/events/v1/SchemaFetcher.java index bdf471f72f..6e77b8b6af 100644 --- a/src/main/java/com/twilio/rest/events/v1/SchemaFetcher.java +++ b/src/main/java/com/twilio/rest/events/v1/SchemaFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.events.v1; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,44 +26,41 @@ public class SchemaFetcher extends Fetcher { - private String pathId; + private String pathid; - public SchemaFetcher(final String pathId) { - this.pathId = pathId; + public SchemaFetcher(final String pathid) { + this.pathid = pathid; } + @Override public Schema fetch(final TwilioRestClient client) { + String path = "/v1/Schemas/{Id}"; - path = path.replace("{" + "Id" + "}", this.pathId.toString()); + path = path.replace("{" + "Id" + "}", this.pathid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.EVENTS.toString(), - path + HttpMethod.GET, + Domains.EVENTS.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Schema fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Schema fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Schema.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/events/v1/Sink.java b/src/main/java/com/twilio/rest/events/v1/Sink.java index 8a5ea31e9c..db268f5b5b 100644 --- a/src/main/java/com/twilio/rest/events/v1/Sink.java +++ b/src/main/java/com/twilio/rest/events/v1/Sink.java @@ -18,67 +18,117 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Sink extends Resource { - private static final long serialVersionUID = 81524362005938L; - public static SinkCreator creator( - final String description, - final Object sinkConfiguration, - final Sink.SinkType sinkType - ) { - return new SinkCreator(description, sinkConfiguration, sinkType); + public static SinkCreator creator(final String description, final Object sinkConfiguration, final Sink.SinkType sinkType) { + return new SinkCreator( + description, sinkConfiguration, sinkType + ); } - public static SinkDeleter deleter(final String pathSid) { - return new SinkDeleter(pathSid); + + public static SinkDeleter deleter(final String pathsid) { + return new SinkDeleter( + pathsid + ); } - public static SinkFetcher fetcher(final String pathSid) { - return new SinkFetcher(pathSid); + + public static SinkFetcher fetcher(final String pathsid) { + return new SinkFetcher( + pathsid + ); } + public static SinkReader reader() { - return new SinkReader(); + return new SinkReader( + + ); } - public static SinkUpdater updater( - final String pathSid, - final String description - ) { - return new SinkUpdater(pathSid, description); + + public static SinkUpdater updater(final String pathsid, final String description) { + return new SinkUpdater( + pathsid, description + ); + } + + + public enum Status { + INITIALIZED("initialized"), + VALIDATING("validating"), + ACTIVE("active"), + FAILED("failed"); + + private final String value; + + private Status(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static Status forValue(final String value) { + return Promoter.enumFromString(value, Status.values()); + } } + public enum SinkType { + KINESIS("kinesis"), + WEBHOOK("webhook"), + SEGMENT("segment"), + EMAIL("email"); + + private final String value; + + private SinkType(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static SinkType forValue(final String value) { + return Promoter.enumFromString(value, SinkType.values()); + } + } + + /** * Converts a JSON String into a Sink object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Sink object represented by the provided JSON */ - public static Sink fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Sink fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Sink.class); @@ -93,14 +143,11 @@ public static Sink fromJson( * Converts a JSON InputStream into a Sink object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Sink object represented by the provided JSON */ - public static Sink fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Sink fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Sink.class); @@ -111,76 +158,61 @@ public static Sink fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; + @Getter private final String description; + @Getter + private final Map links; + @Getter private final String sid; - private final Map sinkConfiguration; + @Getter + private final Object sinkConfiguration; + @Getter private final Sink.SinkType sinkType; + @Getter private final Sink.Status status; + @Getter private final URI url; - private final Map links; @JsonCreator private Sink( - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("description") final String description, - @JsonProperty("sid") final String sid, - @JsonProperty("sink_configuration") final Map< - String, - Object - > sinkConfiguration, - @JsonProperty("sink_type") final Sink.SinkType sinkType, - @JsonProperty("status") final Sink.Status status, - @JsonProperty("url") final URI url, - @JsonProperty("links") final Map links + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("description") final String description, + @JsonProperty("links") final Map links, + @JsonProperty("sid") final String sid, + @JsonProperty("sink_configuration") final Object sinkConfiguration, + @JsonProperty("sink_type") final Sink.SinkType sinkType, + @JsonProperty("status") final Sink.Status status, + @JsonProperty("url") final URI url ) { - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.description = description; + this.links = links; this.sid = sid; this.sinkConfiguration = sinkConfiguration; this.sinkType = sinkType; this.status = status; this.url = url; - this.links = links; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final String getDescription() { - return this.description; - } - - public final String getSid() { - return this.sid; - } - - public final Map getSinkConfiguration() { - return this.sinkConfiguration; - } - - public final Sink.SinkType getSinkType() { - return this.sinkType; - } - - public final Sink.Status getStatus() { - return this.status; - } - - public final URI getUrl() { - return this.url; - } - - public final Map getLinks() { - return this.links; } @Override @@ -194,76 +226,34 @@ public boolean equals(final Object o) { } Sink other = (Sink) o; - return ( - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(description, other.description) && - Objects.equals(sid, other.sid) && - Objects.equals(sinkConfiguration, other.sinkConfiguration) && - Objects.equals(sinkType, other.sinkType) && - Objects.equals(status, other.status) && - Objects.equals(url, other.url) && - Objects.equals(links, other.links) + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(description, other.description) && + Objects.equals(links, other.links) && + Objects.equals(sid, other.sid) && + Objects.equals(sinkConfiguration, other.sinkConfiguration) && + Objects.equals(sinkType, other.sinkType) && + Objects.equals(status, other.status) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - dateCreated, - dateUpdated, - description, - sid, - sinkConfiguration, - sinkType, - status, - url, - links + dateCreated, + dateUpdated, + description, + links, + sid, + sinkConfiguration, + sinkType, + status, + url ); } - public enum Status { - INITIALIZED("initialized"), - VALIDATING("validating"), - ACTIVE("active"), - FAILED("failed"); - - private final String value; - - private Status(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static Status forValue(final String value) { - return Promoter.enumFromString(value, Status.values()); - } - } - - public enum SinkType { - KINESIS("kinesis"), - WEBHOOK("webhook"), - SEGMENT("segment"), - EMAIL("email"); - - private final String value; - private SinkType(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static SinkType forValue(final String value) { - return Promoter.enumFromString(value, SinkType.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/events/v1/SinkCreator.java b/src/main/java/com/twilio/rest/events/v1/SinkCreator.java index 632c1d9aec..e922b7d95f 100644 --- a/src/main/java/com/twilio/rest/events/v1/SinkCreator.java +++ b/src/main/java/com/twilio/rest/events/v1/SinkCreator.java @@ -14,10 +14,11 @@ package com.twilio.rest.events.v1; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; -import com.twilio.converter.Converter; -import com.twilio.converter.Converter; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -33,69 +34,56 @@ public class SinkCreator extends Creator { private Object sinkConfiguration; private Sink.SinkType sinkType; - public SinkCreator( - final String description, - final Object sinkConfiguration, - final Sink.SinkType sinkType - ) { + public SinkCreator(final String description, final Object sinkConfiguration, final Sink.SinkType sinkType) { this.description = description; this.sinkConfiguration = sinkConfiguration; this.sinkType = sinkType; } + public SinkCreator setDescription(final String description) { this.description = description; return this; } + public SinkCreator setSinkConfiguration(final Object sinkConfiguration) { this.sinkConfiguration = sinkConfiguration; return this; } + public SinkCreator setSinkType(final Sink.SinkType sinkType) { this.sinkType = sinkType; return this; } + @Override public Sink create(final TwilioRestClient client) { + String path = "/v1/Sinks"; - path = - path.replace( - "{" + "Description" + "}", - this.description.toString() - ); - path = - path.replace( - "{" + "SinkConfiguration" + "}", - this.sinkConfiguration.toString() - ); - path = path.replace("{" + "SinkType" + "}", this.sinkType.toString()); Request request = new Request( - HttpMethod.POST, - Domains.EVENTS.toString(), - path + HttpMethod.POST, + Domains.EVENTS.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Sink creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("Sink creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -104,17 +92,21 @@ public Sink create(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (description != null) { - request.addPostParam("Description", description); + Serializer.toString(request, "Description", description, ParameterType.URLENCODED); } + + if (sinkConfiguration != null) { - request.addPostParam( - "SinkConfiguration", - Converter.objectToJson(sinkConfiguration) - ); + Serializer.toString(request, "SinkConfiguration", sinkConfiguration, ParameterType.URLENCODED); } + + if (sinkType != null) { - request.addPostParam("SinkType", sinkType.toString()); + Serializer.toString(request, "SinkType", sinkType, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/events/v1/SinkDeleter.java b/src/main/java/com/twilio/rest/events/v1/SinkDeleter.java index bd7c7e7b4c..6b06584a74 100644 --- a/src/main/java/com/twilio/rest/events/v1/SinkDeleter.java +++ b/src/main/java/com/twilio/rest/events/v1/SinkDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.events.v1; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,40 +26,38 @@ public class SinkDeleter extends Deleter { - private String pathSid; + private String pathsid; - public SinkDeleter(final String pathSid) { - this.pathSid = pathSid; + public SinkDeleter(final String pathsid) { + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/v1/Sinks/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.EVENTS.toString(), - path + HttpMethod.DELETE, + Domains.EVENTS.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Sink delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("Sink delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/events/v1/SinkFetcher.java b/src/main/java/com/twilio/rest/events/v1/SinkFetcher.java index d547e14ef5..0eba9532c7 100644 --- a/src/main/java/com/twilio/rest/events/v1/SinkFetcher.java +++ b/src/main/java/com/twilio/rest/events/v1/SinkFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.events.v1; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,44 +26,41 @@ public class SinkFetcher extends Fetcher { - private String pathSid; + private String pathsid; - public SinkFetcher(final String pathSid) { - this.pathSid = pathSid; + public SinkFetcher(final String pathsid) { + this.pathsid = pathsid; } + @Override public Sink fetch(final TwilioRestClient client) { + String path = "/v1/Sinks/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.EVENTS.toString(), - path + HttpMethod.GET, + Domains.EVENTS.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Sink fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Sink fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Sink.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/events/v1/SinkReader.java b/src/main/java/com/twilio/rest/events/v1/SinkReader.java index 422fa57cb6..41618a7484 100644 --- a/src/main/java/com/twilio/rest/events/v1/SinkReader.java +++ b/src/main/java/com/twilio/rest/events/v1/SinkReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -33,121 +34,105 @@ public class SinkReader extends Reader { private String status; private Long pageSize; - public SinkReader() {} + public SinkReader() { + } + public SinkReader setInUse(final Boolean inUse) { this.inUse = inUse; return this; } + public SinkReader setStatus(final String status) { this.status = status; return this; } + public SinkReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/Sinks"; + Request request = new Request( - HttpMethod.GET, - Domains.EVENTS.toString(), - path + HttpMethod.GET, + Domains.EVENTS.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Sink read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Sink read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "sinks", - response.getContent(), - Sink.class, - client.getObjectMapper() - ); + "sinks", + response.getContent(), + Sink.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.EVENTS.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.EVENTS.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (inUse != null) { - request.addQueryParam("InUse", inUse.toString()); + Serializer.toString(request, "InUse", inUse, ParameterType.QUERY); } + + if (status != null) { - request.addQueryParam("Status", status); + Serializer.toString(request, "Status", status, ParameterType.QUERY); } + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/events/v1/SinkUpdater.java b/src/main/java/com/twilio/rest/events/v1/SinkUpdater.java index b6a01f8f6f..f73a843325 100644 --- a/src/main/java/com/twilio/rest/events/v1/SinkUpdater.java +++ b/src/main/java/com/twilio/rest/events/v1/SinkUpdater.java @@ -16,6 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -26,53 +28,48 @@ import com.twilio.rest.Domains; public class SinkUpdater extends Updater { - - private String pathSid; + private String pathsid; private String description; - public SinkUpdater(final String pathSid, final String description) { - this.pathSid = pathSid; + public SinkUpdater(final String pathsid, final String description) { + this.pathsid = pathsid; this.description = description; } + public SinkUpdater setDescription(final String description) { this.description = description; return this; } + @Override public Sink update(final TwilioRestClient client) { + String path = "/v1/Sinks/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); - path = - path.replace( - "{" + "Description" + "}", - this.description.toString() - ); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.EVENTS.toString(), - path + HttpMethod.POST, + Domains.EVENTS.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Sink update failed: Unable to connect to server" - ); + throw new ApiConnectionException("Sink update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -81,8 +78,11 @@ public Sink update(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (description != null) { - request.addPostParam("Description", description); + Serializer.toString(request, "Description", description, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/events/v1/Subscription.java b/src/main/java/com/twilio/rest/events/v1/Subscription.java index 123ccdbbfc..b231b1b1c9 100644 --- a/src/main/java/com/twilio/rest/events/v1/Subscription.java +++ b/src/main/java/com/twilio/rest/events/v1/Subscription.java @@ -18,64 +18,72 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.List; import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Subscription extends Resource { - private static final long serialVersionUID = 198248500185102L; - public static SubscriptionCreator creator( - final String description, - final String sinkSid, - final List types - ) { - return new SubscriptionCreator(description, sinkSid, types); + public static SubscriptionCreator creator(final String description, final String sinkSid, final List types) { + return new SubscriptionCreator( + description, sinkSid, types + ); } - public static SubscriptionDeleter deleter(final String pathSid) { - return new SubscriptionDeleter(pathSid); + + public static SubscriptionDeleter deleter(final String pathsid) { + return new SubscriptionDeleter( + pathsid + ); } - public static SubscriptionFetcher fetcher(final String pathSid) { - return new SubscriptionFetcher(pathSid); + + public static SubscriptionFetcher fetcher(final String pathsid) { + return new SubscriptionFetcher( + pathsid + ); } + public static SubscriptionReader reader() { - return new SubscriptionReader(); + return new SubscriptionReader( + + ); } - public static SubscriptionUpdater updater(final String pathSid) { - return new SubscriptionUpdater(pathSid); + + public static SubscriptionUpdater updater(final String pathsid) { + return new SubscriptionUpdater( + pathsid + ); } + /** * Converts a JSON String into a Subscription object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Subscription object represented by the provided JSON */ - public static Subscription fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Subscription fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Subscription.class); @@ -90,14 +98,11 @@ public static Subscription fromJson( * Converts a JSON InputStream into a Subscription object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Subscription object represented by the provided JSON */ - public static Subscription fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Subscription fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Subscription.class); @@ -108,66 +113,57 @@ public static Subscription fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String sid; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; + @Getter private final String description; + @Getter + private final Map links; + @Getter + private final String sid; + @Getter private final String sinkSid; + @Getter private final URI url; - private final Map links; @JsonCreator private Subscription( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("sid") final String sid, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("description") final String description, - @JsonProperty("sink_sid") final String sinkSid, - @JsonProperty("url") final URI url, - @JsonProperty("links") final Map links + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("description") final String description, + @JsonProperty("links") final Map links, + @JsonProperty("sid") final String sid, + @JsonProperty("sink_sid") final String sinkSid, + @JsonProperty("url") final URI url ) { this.accountSid = accountSid; - this.sid = sid; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.description = description; + this.links = links; + this.sid = sid; this.sinkSid = sinkSid; this.url = url; - this.links = links; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getSid() { - return this.sid; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final String getDescription() { - return this.description; - } - - public final String getSinkSid() { - return this.sinkSid; - } - - public final URI getUrl() { - return this.url; - } - - public final Map getLinks() { - return this.links; } @Override @@ -181,30 +177,32 @@ public boolean equals(final Object o) { } Subscription other = (Subscription) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(sid, other.sid) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(description, other.description) && - Objects.equals(sinkSid, other.sinkSid) && - Objects.equals(url, other.url) && - Objects.equals(links, other.links) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(description, other.description) && + Objects.equals(links, other.links) && + Objects.equals(sid, other.sid) && + Objects.equals(sinkSid, other.sinkSid) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - accountSid, - sid, - dateCreated, - dateUpdated, - description, - sinkSid, - url, - links + accountSid, + dateCreated, + dateUpdated, + description, + links, + sid, + sinkSid, + url ); } + + } + diff --git a/src/main/java/com/twilio/rest/events/v1/SubscriptionCreator.java b/src/main/java/com/twilio/rest/events/v1/SubscriptionCreator.java index 32e9a37342..0fbb7ac697 100644 --- a/src/main/java/com/twilio/rest/events/v1/SubscriptionCreator.java +++ b/src/main/java/com/twilio/rest/events/v1/SubscriptionCreator.java @@ -14,11 +14,12 @@ package com.twilio.rest.events.v1; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; -import com.twilio.converter.Converter; -import com.twilio.converter.Converter; +import com.twilio.constant.EnumConstants.ParameterType; import com.twilio.converter.Promoter; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,7 +28,7 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -import java.util.List; + import java.util.List; public class SubscriptionCreator extends Creator { @@ -36,26 +37,25 @@ public class SubscriptionCreator extends Creator { private String sinkSid; private List types; - public SubscriptionCreator( - final String description, - final String sinkSid, - final List types - ) { + public SubscriptionCreator(final String description, final String sinkSid, final List types) { this.description = description; this.sinkSid = sinkSid; this.types = types; } + public SubscriptionCreator setDescription(final String description) { this.description = description; return this; } + public SubscriptionCreator setSinkSid(final String sinkSid) { this.sinkSid = sinkSid; return this; } + public SubscriptionCreator setTypes(final List types) { this.types = types; return this; @@ -67,59 +67,53 @@ public SubscriptionCreator setTypes(final Object types) { @Override public Subscription create(final TwilioRestClient client) { + String path = "/v1/Subscriptions"; - path = - path.replace( - "{" + "Description" + "}", - this.description.toString() - ); - path = path.replace("{" + "SinkSid" + "}", this.sinkSid.toString()); - path = path.replace("{" + "Types" + "}", this.types.toString()); Request request = new Request( - HttpMethod.POST, - Domains.EVENTS.toString(), - path + HttpMethod.POST, + Domains.EVENTS.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Subscription creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("Subscription creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Subscription.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Subscription.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (description != null) { - request.addPostParam("Description", description); + Serializer.toString(request, "Description", description, ParameterType.URLENCODED); } + + if (sinkSid != null) { - request.addPostParam("SinkSid", sinkSid); + Serializer.toString(request, "SinkSid", sinkSid, ParameterType.URLENCODED); } + + if (types != null) { - for (Object prop : types) { - request.addPostParam("Types", Converter.objectToJson(prop)); + for (Object param : types) { + Serializer.toString(request, "Types", param, ParameterType.URLENCODED); } } + } } diff --git a/src/main/java/com/twilio/rest/events/v1/SubscriptionDeleter.java b/src/main/java/com/twilio/rest/events/v1/SubscriptionDeleter.java index bab03981ac..d0f02c00bd 100644 --- a/src/main/java/com/twilio/rest/events/v1/SubscriptionDeleter.java +++ b/src/main/java/com/twilio/rest/events/v1/SubscriptionDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.events.v1; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,40 +26,38 @@ public class SubscriptionDeleter extends Deleter { - private String pathSid; + private String pathsid; - public SubscriptionDeleter(final String pathSid) { - this.pathSid = pathSid; + public SubscriptionDeleter(final String pathsid) { + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/v1/Subscriptions/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.EVENTS.toString(), - path + HttpMethod.DELETE, + Domains.EVENTS.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Subscription delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("Subscription delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/events/v1/SubscriptionFetcher.java b/src/main/java/com/twilio/rest/events/v1/SubscriptionFetcher.java index 97ac4d935c..d43b8acf72 100644 --- a/src/main/java/com/twilio/rest/events/v1/SubscriptionFetcher.java +++ b/src/main/java/com/twilio/rest/events/v1/SubscriptionFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.events.v1; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,47 +26,41 @@ public class SubscriptionFetcher extends Fetcher { - private String pathSid; + private String pathsid; - public SubscriptionFetcher(final String pathSid) { - this.pathSid = pathSid; + public SubscriptionFetcher(final String pathsid) { + this.pathsid = pathsid; } + @Override public Subscription fetch(final TwilioRestClient client) { + String path = "/v1/Subscriptions/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.EVENTS.toString(), - path + HttpMethod.GET, + Domains.EVENTS.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Subscription fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Subscription fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return Subscription.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Subscription.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/events/v1/SubscriptionReader.java b/src/main/java/com/twilio/rest/events/v1/SubscriptionReader.java index 54a7688931..034f77317a 100644 --- a/src/main/java/com/twilio/rest/events/v1/SubscriptionReader.java +++ b/src/main/java/com/twilio/rest/events/v1/SubscriptionReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -32,113 +33,94 @@ public class SubscriptionReader extends Reader { private String sinkSid; private Long pageSize; - public SubscriptionReader() {} + public SubscriptionReader() { + } + public SubscriptionReader setSinkSid(final String sinkSid) { this.sinkSid = sinkSid; return this; } + public SubscriptionReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/Subscriptions"; + Request request = new Request( - HttpMethod.GET, - Domains.EVENTS.toString(), - path + HttpMethod.GET, + Domains.EVENTS.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Subscription read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Subscription read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "subscriptions", - response.getContent(), - Subscription.class, - client.getObjectMapper() - ); + "subscriptions", + response.getContent(), + Subscription.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.EVENTS.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.EVENTS.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (sinkSid != null) { - request.addQueryParam("SinkSid", sinkSid); + Serializer.toString(request, "SinkSid", sinkSid, ParameterType.QUERY); } + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/events/v1/SubscriptionUpdater.java b/src/main/java/com/twilio/rest/events/v1/SubscriptionUpdater.java index a6907cb6e5..e8cbc91935 100644 --- a/src/main/java/com/twilio/rest/events/v1/SubscriptionUpdater.java +++ b/src/main/java/com/twilio/rest/events/v1/SubscriptionUpdater.java @@ -16,6 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -26,60 +28,60 @@ import com.twilio.rest.Domains; public class SubscriptionUpdater extends Updater { - - private String pathSid; + private String pathsid; private String description; - public SubscriptionUpdater(final String pathSid) { - this.pathSid = pathSid; + public SubscriptionUpdater(final String pathsid) { + this.pathsid = pathsid; } + public SubscriptionUpdater setDescription(final String description) { this.description = description; return this; } + @Override public Subscription update(final TwilioRestClient client) { + String path = "/v1/Subscriptions/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.EVENTS.toString(), - path + HttpMethod.POST, + Domains.EVENTS.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Subscription update failed: Unable to connect to server" - ); + throw new ApiConnectionException("Subscription update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Subscription.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Subscription.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (description != null) { - request.addPostParam("Description", description); + Serializer.toString(request, "Description", description, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/events/v1/schema/SchemaVersion.java b/src/main/java/com/twilio/rest/events/v1/schema/SchemaVersion.java index 1e30a12e12..8112f4d75d 100644 --- a/src/main/java/com/twilio/rest/events/v1/schema/SchemaVersion.java +++ b/src/main/java/com/twilio/rest/events/v1/schema/SchemaVersion.java @@ -18,48 +18,49 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class SchemaVersion extends Resource { - private static final long serialVersionUID = 232564429627083L; - public static SchemaVersionFetcher fetcher( - final String pathId, - final Integer pathSchemaVersion - ) { - return new SchemaVersionFetcher(pathId, pathSchemaVersion); + public static SchemaVersionFetcher fetcher(final String pathid, final Integer pathschemaVersion) { + return new SchemaVersionFetcher( + pathid, pathschemaVersion + ); } - public static SchemaVersionReader reader(final String pathId) { - return new SchemaVersionReader(pathId); + + public static SchemaVersionReader reader(final String pathid) { + return new SchemaVersionReader( + pathid + ); } + /** * Converts a JSON String into a SchemaVersion object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return SchemaVersion object represented by the provided JSON */ - public static SchemaVersion fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static SchemaVersion fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, SchemaVersion.class); @@ -74,14 +75,11 @@ public static SchemaVersion fromJson( * Converts a JSON InputStream into a SchemaVersion object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return SchemaVersion object represented by the provided JSON */ - public static SchemaVersion fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static SchemaVersion fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, SchemaVersion.class); @@ -92,45 +90,44 @@ public static SchemaVersion fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter + private final ZonedDateTime dateCreated; + @Getter private final String id; + @Getter + private final URI raw; + @Getter private final Integer schemaVersion; - private final ZonedDateTime dateCreated; + @Getter private final URI url; - private final URI raw; @JsonCreator private SchemaVersion( - @JsonProperty("id") final String id, - @JsonProperty("schema_version") final Integer schemaVersion, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("url") final URI url, - @JsonProperty("raw") final URI raw + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("id") final String id, + @JsonProperty("raw") final URI raw, + @JsonProperty("schema_version") final Integer schemaVersion, + @JsonProperty("url") final URI url ) { + this.dateCreated = dateCreated; this.id = id; + this.raw = raw; this.schemaVersion = schemaVersion; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); this.url = url; - this.raw = raw; - } - - public final String getId() { - return this.id; - } - - public final Integer getSchemaVersion() { - return this.schemaVersion; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final URI getUrl() { - return this.url; - } - - public final URI getRaw() { - return this.raw; } @Override @@ -144,18 +141,26 @@ public boolean equals(final Object o) { } SchemaVersion other = (SchemaVersion) o; - return ( - Objects.equals(id, other.id) && - Objects.equals(schemaVersion, other.schemaVersion) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(url, other.url) && - Objects.equals(raw, other.raw) + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(id, other.id) && + Objects.equals(raw, other.raw) && + Objects.equals(schemaVersion, other.schemaVersion) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { - return Objects.hash(id, schemaVersion, dateCreated, url, raw); + return Objects.hash( + dateCreated, + id, + raw, + schemaVersion, + url + ); } + + } + diff --git a/src/main/java/com/twilio/rest/events/v1/schema/SchemaVersionFetcher.java b/src/main/java/com/twilio/rest/events/v1/schema/SchemaVersionFetcher.java index 1b64527ebd..3b596c332b 100644 --- a/src/main/java/com/twilio/rest/events/v1/schema/SchemaVersionFetcher.java +++ b/src/main/java/com/twilio/rest/events/v1/schema/SchemaVersionFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.events.v1.schema; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,57 +26,44 @@ public class SchemaVersionFetcher extends Fetcher { - private String pathId; - private Integer pathSchemaVersion; + private String pathid; + private Integer pathschemaVersion; - public SchemaVersionFetcher( - final String pathId, - final Integer pathSchemaVersion - ) { - this.pathId = pathId; - this.pathSchemaVersion = pathSchemaVersion; + public SchemaVersionFetcher(final String pathid, final Integer pathschemaVersion) { + this.pathid = pathid; + this.pathschemaVersion = pathschemaVersion; } + @Override public SchemaVersion fetch(final TwilioRestClient client) { + String path = "/v1/Schemas/{Id}/Versions/{SchemaVersion}"; - path = path.replace("{" + "Id" + "}", this.pathId.toString()); - path = - path.replace( - "{" + "SchemaVersion" + "}", - this.pathSchemaVersion.toString() - ); + path = path.replace("{" + "Id" + "}", this.pathid.toString()); + path = path.replace("{" + "SchemaVersion" + "}", this.pathschemaVersion.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.EVENTS.toString(), - path + HttpMethod.GET, + Domains.EVENTS.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "SchemaVersion fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("SchemaVersion fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return SchemaVersion.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return SchemaVersion.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/events/v1/schema/SchemaVersionReader.java b/src/main/java/com/twilio/rest/events/v1/schema/SchemaVersionReader.java index 1feb88565f..d1dcb619a3 100644 --- a/src/main/java/com/twilio/rest/events/v1/schema/SchemaVersionReader.java +++ b/src/main/java/com/twilio/rest/events/v1/schema/SchemaVersionReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,111 +30,88 @@ public class SchemaVersionReader extends Reader { - private String pathId; + private String pathid; private Long pageSize; - public SchemaVersionReader(final String pathId) { - this.pathId = pathId; + public SchemaVersionReader(final String pathid) { + this.pathid = pathid; } + public SchemaVersionReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/Schemas/{Id}/Versions"; - path = path.replace("{" + "Id" + "}", this.pathId.toString()); + + path = path.replace("{" + "Id" + "}", this.pathid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.EVENTS.toString(), - path + HttpMethod.GET, + Domains.EVENTS.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "SchemaVersion read failed: Unable to connect to server" - ); + throw new ApiConnectionException("SchemaVersion read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "schema_versions", - response.getContent(), - SchemaVersion.class, - client.getObjectMapper() - ); + "schema_versions", + response.getContent(), + SchemaVersion.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.EVENTS.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.EVENTS.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/events/v1/sink/SinkTest.java b/src/main/java/com/twilio/rest/events/v1/sink/SinkTest.java index c3bd4ae6a7..90993df14d 100644 --- a/src/main/java/com/twilio/rest/events/v1/sink/SinkTest.java +++ b/src/main/java/com/twilio/rest/events/v1/sink/SinkTest.java @@ -18,38 +18,39 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class SinkTest extends Resource { - private static final long serialVersionUID = 233814002700195L; - public static SinkTestCreator creator(final String pathSid) { - return new SinkTestCreator(pathSid); + public static SinkTestCreator creator(final String pathsid) { + return new SinkTestCreator( + pathsid + ); } + /** * Converts a JSON String into a SinkTest object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return SinkTest object represented by the provided JSON */ - public static SinkTest fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static SinkTest fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, SinkTest.class); @@ -64,14 +65,11 @@ public static SinkTest fromJson( * Converts a JSON InputStream into a SinkTest object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return SinkTest object represented by the provided JSON */ - public static SinkTest fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static SinkTest fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, SinkTest.class); @@ -82,17 +80,29 @@ public static SinkTest fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String result; @JsonCreator - private SinkTest(@JsonProperty("result") final String result) { + private SinkTest( + @JsonProperty("result") final String result + ) { this.result = result; } - public final String getResult() { - return this.result; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -104,12 +114,18 @@ public boolean equals(final Object o) { } SinkTest other = (SinkTest) o; - - return Objects.equals(result, other.result); + return ( + Objects.equals(result, other.result) + ); } @Override public int hashCode() { - return Objects.hash(result); + return Objects.hash( + result + ); } + + } + diff --git a/src/main/java/com/twilio/rest/events/v1/sink/SinkTestCreator.java b/src/main/java/com/twilio/rest/events/v1/sink/SinkTestCreator.java index 7c3728336c..0626f018a2 100644 --- a/src/main/java/com/twilio/rest/events/v1/sink/SinkTestCreator.java +++ b/src/main/java/com/twilio/rest/events/v1/sink/SinkTestCreator.java @@ -14,8 +14,8 @@ package com.twilio.rest.events.v1.sink; + import com.twilio.base.Creator; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,46 +27,42 @@ public class SinkTestCreator extends Creator { - private String pathSid; + private String pathsid; - public SinkTestCreator(final String pathSid) { - this.pathSid = pathSid; + public SinkTestCreator(final String pathsid) { + this.pathsid = pathsid; } + @Override public SinkTest create(final TwilioRestClient client) { + String path = "/v1/Sinks/{Sid}/Test"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.EVENTS.toString(), - path + HttpMethod.POST, + Domains.EVENTS.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "SinkTest creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("SinkTest creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return SinkTest.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return SinkTest.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/events/v1/sink/SinkValidate.java b/src/main/java/com/twilio/rest/events/v1/sink/SinkValidate.java index ebca5d979c..27352a9bf7 100644 --- a/src/main/java/com/twilio/rest/events/v1/sink/SinkValidate.java +++ b/src/main/java/com/twilio/rest/events/v1/sink/SinkValidate.java @@ -18,41 +18,39 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class SinkValidate extends Resource { - private static final long serialVersionUID = 233814002700195L; - public static SinkValidateCreator creator( - final String pathSid, - final String testId - ) { - return new SinkValidateCreator(pathSid, testId); + public static SinkValidateCreator creator(final String pathsid, final String testId) { + return new SinkValidateCreator( + pathsid, testId + ); } + /** * Converts a JSON String into a SinkValidate object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return SinkValidate object represented by the provided JSON */ - public static SinkValidate fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static SinkValidate fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, SinkValidate.class); @@ -67,14 +65,11 @@ public static SinkValidate fromJson( * Converts a JSON InputStream into a SinkValidate object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return SinkValidate object represented by the provided JSON */ - public static SinkValidate fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static SinkValidate fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, SinkValidate.class); @@ -85,17 +80,29 @@ public static SinkValidate fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String result; @JsonCreator - private SinkValidate(@JsonProperty("result") final String result) { + private SinkValidate( + @JsonProperty("result") final String result + ) { this.result = result; } - public final String getResult() { - return this.result; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -107,12 +114,18 @@ public boolean equals(final Object o) { } SinkValidate other = (SinkValidate) o; - - return Objects.equals(result, other.result); + return ( + Objects.equals(result, other.result) + ); } @Override public int hashCode() { - return Objects.hash(result); + return Objects.hash( + result + ); } + + } + diff --git a/src/main/java/com/twilio/rest/events/v1/sink/SinkValidateCreator.java b/src/main/java/com/twilio/rest/events/v1/sink/SinkValidateCreator.java index e1356f8074..5c36d4aeff 100644 --- a/src/main/java/com/twilio/rest/events/v1/sink/SinkValidateCreator.java +++ b/src/main/java/com/twilio/rest/events/v1/sink/SinkValidateCreator.java @@ -14,8 +14,11 @@ package com.twilio.rest.events.v1.sink; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,61 +30,61 @@ public class SinkValidateCreator extends Creator { - private String pathSid; + private String pathsid; private String testId; - public SinkValidateCreator(final String pathSid, final String testId) { - this.pathSid = pathSid; + public SinkValidateCreator(final String pathsid, final String testId) { + this.pathsid = pathsid; this.testId = testId; } + public SinkValidateCreator setTestId(final String testId) { this.testId = testId; return this; } + @Override public SinkValidate create(final TwilioRestClient client) { + String path = "/v1/Sinks/{Sid}/Validate"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); - path = path.replace("{" + "TestId" + "}", this.testId.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.EVENTS.toString(), - path + HttpMethod.POST, + Domains.EVENTS.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "SinkValidate creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("SinkValidate creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return SinkValidate.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return SinkValidate.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (testId != null) { - request.addPostParam("TestId", testId); + Serializer.toString(request, "TestId", testId, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/events/v1/subscription/SubscribedEvent.java b/src/main/java/com/twilio/rest/events/v1/subscription/SubscribedEvent.java index 4affd70649..4fceb2b6ee 100644 --- a/src/main/java/com/twilio/rest/events/v1/subscription/SubscribedEvent.java +++ b/src/main/java/com/twilio/rest/events/v1/subscription/SubscribedEvent.java @@ -18,69 +18,68 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class SubscribedEvent extends Resource { - private static final long serialVersionUID = 216550539675838L; - public static SubscribedEventCreator creator( - final String pathSubscriptionSid, - final String type - ) { - return new SubscribedEventCreator(pathSubscriptionSid, type); + public static SubscribedEventCreator creator(final String pathsubscriptionSid, final String type) { + return new SubscribedEventCreator( + pathsubscriptionSid, type + ); } - public static SubscribedEventDeleter deleter( - final String pathSubscriptionSid, - final String pathType - ) { - return new SubscribedEventDeleter(pathSubscriptionSid, pathType); + + public static SubscribedEventDeleter deleter(final String pathsubscriptionSid, final String pathtype) { + return new SubscribedEventDeleter( + pathsubscriptionSid, pathtype + ); } - public static SubscribedEventFetcher fetcher( - final String pathSubscriptionSid, - final String pathType - ) { - return new SubscribedEventFetcher(pathSubscriptionSid, pathType); + + public static SubscribedEventFetcher fetcher(final String pathsubscriptionSid, final String pathtype) { + return new SubscribedEventFetcher( + pathsubscriptionSid, pathtype + ); } - public static SubscribedEventReader reader( - final String pathSubscriptionSid - ) { - return new SubscribedEventReader(pathSubscriptionSid); + + public static SubscribedEventReader reader(final String pathsubscriptionSid) { + return new SubscribedEventReader( + pathsubscriptionSid + ); } - public static SubscribedEventUpdater updater( - final String pathSubscriptionSid, - final String pathType - ) { - return new SubscribedEventUpdater(pathSubscriptionSid, pathType); + + public static SubscribedEventUpdater updater(final String pathsubscriptionSid, final String pathtype) { + return new SubscribedEventUpdater( + pathsubscriptionSid, pathtype + ); } + /** * Converts a JSON String into a SubscribedEvent object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return SubscribedEvent object represented by the provided JSON */ - public static SubscribedEvent fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static SubscribedEvent fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, SubscribedEvent.class); @@ -95,14 +94,11 @@ public static SubscribedEvent fromJson( * Converts a JSON InputStream into a SubscribedEvent object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return SubscribedEvent object represented by the provided JSON */ - public static SubscribedEvent fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static SubscribedEvent fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, SubscribedEvent.class); @@ -113,47 +109,45 @@ public static SubscribedEvent fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String type; + @Getter private final Integer schemaVersion; + @Getter private final String subscriptionSid; + @Getter + private final String type; + @Getter private final URI url; @JsonCreator private SubscribedEvent( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("type") final String type, - @JsonProperty("schema_version") final Integer schemaVersion, - @JsonProperty("subscription_sid") final String subscriptionSid, - @JsonProperty("url") final URI url + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("schema_version") final Integer schemaVersion, + @JsonProperty("subscription_sid") final String subscriptionSid, + @JsonProperty("type") final String type, + @JsonProperty("url") final URI url ) { this.accountSid = accountSid; - this.type = type; this.schemaVersion = schemaVersion; this.subscriptionSid = subscriptionSid; + this.type = type; this.url = url; } - public final String getAccountSid() { - return this.accountSid; - } - - public final String getType() { - return this.type; - } - - public final Integer getSchemaVersion() { - return this.schemaVersion; - } - - public final String getSubscriptionSid() { - return this.subscriptionSid; - } - - public final URI getUrl() { - return this.url; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -165,24 +159,26 @@ public boolean equals(final Object o) { } SubscribedEvent other = (SubscribedEvent) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(type, other.type) && - Objects.equals(schemaVersion, other.schemaVersion) && - Objects.equals(subscriptionSid, other.subscriptionSid) && - Objects.equals(url, other.url) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(schemaVersion, other.schemaVersion) && + Objects.equals(subscriptionSid, other.subscriptionSid) && + Objects.equals(type, other.type) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - accountSid, - type, - schemaVersion, - subscriptionSid, - url + accountSid, + schemaVersion, + subscriptionSid, + type, + url ); } + + } + diff --git a/src/main/java/com/twilio/rest/events/v1/subscription/SubscribedEventCreator.java b/src/main/java/com/twilio/rest/events/v1/subscription/SubscribedEventCreator.java index 1a9db41372..10aa285b7f 100644 --- a/src/main/java/com/twilio/rest/events/v1/subscription/SubscribedEventCreator.java +++ b/src/main/java/com/twilio/rest/events/v1/subscription/SubscribedEventCreator.java @@ -14,8 +14,11 @@ package com.twilio.rest.events.v1.subscription; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,79 +30,73 @@ public class SubscribedEventCreator extends Creator { - private String pathSubscriptionSid; + private String pathsubscriptionSid; private String type; private Integer schemaVersion; - public SubscribedEventCreator( - final String pathSubscriptionSid, - final String type - ) { - this.pathSubscriptionSid = pathSubscriptionSid; + public SubscribedEventCreator(final String pathsubscriptionSid, final String type) { + this.pathsubscriptionSid = pathsubscriptionSid; this.type = type; } + public SubscribedEventCreator setType(final String type) { this.type = type; return this; } - public SubscribedEventCreator setSchemaVersion( - final Integer schemaVersion - ) { + + public SubscribedEventCreator setSchemaVersion(final Integer schemaVersion) { this.schemaVersion = schemaVersion; return this; } + @Override public SubscribedEvent create(final TwilioRestClient client) { + String path = "/v1/Subscriptions/{SubscriptionSid}/SubscribedEvents"; - path = - path.replace( - "{" + "SubscriptionSid" + "}", - this.pathSubscriptionSid.toString() - ); - path = path.replace("{" + "Type" + "}", this.type.toString()); + path = path.replace("{" + "SubscriptionSid" + "}", this.pathsubscriptionSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.EVENTS.toString(), - path + HttpMethod.POST, + Domains.EVENTS.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "SubscribedEvent creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("SubscribedEvent creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return SubscribedEvent.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return SubscribedEvent.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (type != null) { - request.addPostParam("Type", type); + Serializer.toString(request, "Type", type, ParameterType.URLENCODED); } + + if (schemaVersion != null) { - request.addPostParam("SchemaVersion", schemaVersion.toString()); + Serializer.toString(request, "SchemaVersion", schemaVersion, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/events/v1/subscription/SubscribedEventDeleter.java b/src/main/java/com/twilio/rest/events/v1/subscription/SubscribedEventDeleter.java index e900bba50a..8b0583a6af 100644 --- a/src/main/java/com/twilio/rest/events/v1/subscription/SubscribedEventDeleter.java +++ b/src/main/java/com/twilio/rest/events/v1/subscription/SubscribedEventDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.events.v1.subscription; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,51 +26,41 @@ public class SubscribedEventDeleter extends Deleter { - private String pathSubscriptionSid; - private String pathType; + private String pathsubscriptionSid; + private String pathtype; - public SubscribedEventDeleter( - final String pathSubscriptionSid, - final String pathType - ) { - this.pathSubscriptionSid = pathSubscriptionSid; - this.pathType = pathType; + public SubscribedEventDeleter(final String pathsubscriptionSid, final String pathtype) { + this.pathsubscriptionSid = pathsubscriptionSid; + this.pathtype = pathtype; } + @Override public boolean delete(final TwilioRestClient client) { - String path = - "/v1/Subscriptions/{SubscriptionSid}/SubscribedEvents/{Type}"; - path = - path.replace( - "{" + "SubscriptionSid" + "}", - this.pathSubscriptionSid.toString() - ); - path = path.replace("{" + "Type" + "}", this.pathType.toString()); + String path = "/v1/Subscriptions/{SubscriptionSid}/SubscribedEvents/{Type}"; + + path = path.replace("{" + "SubscriptionSid" + "}", this.pathsubscriptionSid.toString()); + path = path.replace("{" + "Type" + "}", this.pathtype.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.EVENTS.toString(), - path + HttpMethod.DELETE, + Domains.EVENTS.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "SubscribedEvent delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("SubscribedEvent delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/events/v1/subscription/SubscribedEventFetcher.java b/src/main/java/com/twilio/rest/events/v1/subscription/SubscribedEventFetcher.java index 82fa59ddea..9ba247d017 100644 --- a/src/main/java/com/twilio/rest/events/v1/subscription/SubscribedEventFetcher.java +++ b/src/main/java/com/twilio/rest/events/v1/subscription/SubscribedEventFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.events.v1.subscription; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,58 +26,44 @@ public class SubscribedEventFetcher extends Fetcher { - private String pathSubscriptionSid; - private String pathType; + private String pathsubscriptionSid; + private String pathtype; - public SubscribedEventFetcher( - final String pathSubscriptionSid, - final String pathType - ) { - this.pathSubscriptionSid = pathSubscriptionSid; - this.pathType = pathType; + public SubscribedEventFetcher(final String pathsubscriptionSid, final String pathtype) { + this.pathsubscriptionSid = pathsubscriptionSid; + this.pathtype = pathtype; } + @Override public SubscribedEvent fetch(final TwilioRestClient client) { - String path = - "/v1/Subscriptions/{SubscriptionSid}/SubscribedEvents/{Type}"; - path = - path.replace( - "{" + "SubscriptionSid" + "}", - this.pathSubscriptionSid.toString() - ); - path = path.replace("{" + "Type" + "}", this.pathType.toString()); + String path = "/v1/Subscriptions/{SubscriptionSid}/SubscribedEvents/{Type}"; + + path = path.replace("{" + "SubscriptionSid" + "}", this.pathsubscriptionSid.toString()); + path = path.replace("{" + "Type" + "}", this.pathtype.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.EVENTS.toString(), - path + HttpMethod.GET, + Domains.EVENTS.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "SubscribedEvent fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("SubscribedEvent fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return SubscribedEvent.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return SubscribedEvent.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/events/v1/subscription/SubscribedEventReader.java b/src/main/java/com/twilio/rest/events/v1/subscription/SubscribedEventReader.java index 3d9a6a70b4..bba088594f 100644 --- a/src/main/java/com/twilio/rest/events/v1/subscription/SubscribedEventReader.java +++ b/src/main/java/com/twilio/rest/events/v1/subscription/SubscribedEventReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,115 +30,88 @@ public class SubscribedEventReader extends Reader { - private String pathSubscriptionSid; + private String pathsubscriptionSid; private Long pageSize; - public SubscribedEventReader(final String pathSubscriptionSid) { - this.pathSubscriptionSid = pathSubscriptionSid; + public SubscribedEventReader(final String pathsubscriptionSid) { + this.pathsubscriptionSid = pathsubscriptionSid; } + public SubscribedEventReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/Subscriptions/{SubscriptionSid}/SubscribedEvents"; - path = - path.replace( - "{" + "SubscriptionSid" + "}", - this.pathSubscriptionSid.toString() - ); + + path = path.replace("{" + "SubscriptionSid" + "}", this.pathsubscriptionSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.EVENTS.toString(), - path + HttpMethod.GET, + Domains.EVENTS.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "SubscribedEvent read failed: Unable to connect to server" - ); + throw new ApiConnectionException("SubscribedEvent read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "types", - response.getContent(), - SubscribedEvent.class, - client.getObjectMapper() - ); + "types", + response.getContent(), + SubscribedEvent.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.EVENTS.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.EVENTS.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/events/v1/subscription/SubscribedEventUpdater.java b/src/main/java/com/twilio/rest/events/v1/subscription/SubscribedEventUpdater.java index 47331fbced..57a90edfb8 100644 --- a/src/main/java/com/twilio/rest/events/v1/subscription/SubscribedEventUpdater.java +++ b/src/main/java/com/twilio/rest/events/v1/subscription/SubscribedEventUpdater.java @@ -16,6 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -26,73 +28,63 @@ import com.twilio.rest.Domains; public class SubscribedEventUpdater extends Updater { - - private String pathSubscriptionSid; - private String pathType; + private String pathsubscriptionSid; + private String pathtype; private Integer schemaVersion; - public SubscribedEventUpdater( - final String pathSubscriptionSid, - final String pathType - ) { - this.pathSubscriptionSid = pathSubscriptionSid; - this.pathType = pathType; + public SubscribedEventUpdater(final String pathsubscriptionSid, final String pathtype) { + this.pathsubscriptionSid = pathsubscriptionSid; + this.pathtype = pathtype; } - public SubscribedEventUpdater setSchemaVersion( - final Integer schemaVersion - ) { + + public SubscribedEventUpdater setSchemaVersion(final Integer schemaVersion) { this.schemaVersion = schemaVersion; return this; } + @Override public SubscribedEvent update(final TwilioRestClient client) { - String path = - "/v1/Subscriptions/{SubscriptionSid}/SubscribedEvents/{Type}"; - path = - path.replace( - "{" + "SubscriptionSid" + "}", - this.pathSubscriptionSid.toString() - ); - path = path.replace("{" + "Type" + "}", this.pathType.toString()); + String path = "/v1/Subscriptions/{SubscriptionSid}/SubscribedEvents/{Type}"; + + path = path.replace("{" + "SubscriptionSid" + "}", this.pathsubscriptionSid.toString()); + path = path.replace("{" + "Type" + "}", this.pathtype.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.EVENTS.toString(), - path + HttpMethod.POST, + Domains.EVENTS.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "SubscribedEvent update failed: Unable to connect to server" - ); + throw new ApiConnectionException("SubscribedEvent update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return SubscribedEvent.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return SubscribedEvent.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (schemaVersion != null) { - request.addPostParam("SchemaVersion", schemaVersion.toString()); + Serializer.toString(request, "SchemaVersion", schemaVersion, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/flexapi/v1/Assessments.java b/src/main/java/com/twilio/rest/flexapi/v1/Assessments.java index 21563c4279..3f6c355137 100644 --- a/src/main/java/com/twilio/rest/flexapi/v1/Assessments.java +++ b/src/main/java/com/twilio/rest/flexapi/v1/Assessments.java @@ -18,82 +18,55 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.math.BigDecimal; import java.net.URI; -import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Assessments extends Resource { - private static final long serialVersionUID = 2474918794072L; - public static AssessmentsCreator creator( - final String categorySid, - final String categoryName, - final String segmentId, - final String agentId, - final BigDecimal offset, - final String metricId, - final String metricName, - final String answerText, - final String answerId, - final String questionnaireSid - ) { + public static AssessmentsCreator creator(final String categorySid, final String categoryName, final String segmentId, final String agentId, final BigDecimal offset, final String metricId, final String metricName, final String answerText, final String answerId, final String questionnaireSid) { return new AssessmentsCreator( - categorySid, - categoryName, - segmentId, - agentId, - offset, - metricId, - metricName, - answerText, - answerId, - questionnaireSid + categorySid, categoryName, segmentId, agentId, offset, metricId, metricName, answerText, answerId, questionnaireSid ); } + public static AssessmentsReader reader() { - return new AssessmentsReader(); + return new AssessmentsReader( + + ); } - public static AssessmentsUpdater updater( - final String pathAssessmentSid, - final BigDecimal offset, - final String answerText, - final String answerId - ) { + + public static AssessmentsUpdater updater(final String pathassessmentSid, final BigDecimal offset, final String answerText, final String answerId) { return new AssessmentsUpdater( - pathAssessmentSid, - offset, - answerText, - answerId + pathassessmentSid, offset, answerText, answerId ); } + /** * Converts a JSON String into a Assessments object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Assessments object represented by the provided JSON */ - public static Assessments fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Assessments fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Assessments.class); @@ -108,14 +81,11 @@ public static Assessments fromJson( * Converts a JSON InputStream into a Assessments object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Assessments object represented by the provided JSON */ - public static Assessments fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Assessments fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Assessments.class); @@ -126,108 +96,79 @@ public static Assessments fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; + @Getter + private final String agentId; + @Getter + private final String answerId; + @Getter + private final String answerText; + @Getter + private final Object assessment; + @Getter private final String assessmentSid; + @Getter private final String offset; + @Getter private final Boolean report; - private final String weight; - private final String agentId; + @Getter private final String segmentId; - private final String userName; - private final String userEmail; - private final String answerText; - private final String answerId; - private final Map assessment; + @Getter private final String timestamp; + @Getter private final URI url; + @Getter + private final String userEmail; + @Getter + private final String userName; + @Getter + private final String weight; @JsonCreator private Assessments( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("assessment_sid") final String assessmentSid, - @JsonProperty("offset") final String offset, - @JsonProperty("report") final Boolean report, - @JsonProperty("weight") final String weight, - @JsonProperty("agent_id") final String agentId, - @JsonProperty("segment_id") final String segmentId, - @JsonProperty("user_name") final String userName, - @JsonProperty("user_email") final String userEmail, - @JsonProperty("answer_text") final String answerText, - @JsonProperty("answer_id") final String answerId, - @JsonProperty("assessment") final Map assessment, - @JsonProperty("timestamp") final String timestamp, - @JsonProperty("url") final URI url + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("agent_id") final String agentId, + @JsonProperty("answer_id") final String answerId, + @JsonProperty("answer_text") final String answerText, + @JsonProperty("assessment") final Object assessment, + @JsonProperty("assessment_sid") final String assessmentSid, + @JsonProperty("offset") final String offset, + @JsonProperty("report") final Boolean report, + @JsonProperty("segment_id") final String segmentId, + @JsonProperty("timestamp") final String timestamp, + @JsonProperty("url") final URI url, + @JsonProperty("user_email") final String userEmail, + @JsonProperty("user_name") final String userName, + @JsonProperty("weight") final String weight ) { this.accountSid = accountSid; + this.agentId = agentId; + this.answerId = answerId; + this.answerText = answerText; + this.assessment = assessment; this.assessmentSid = assessmentSid; this.offset = offset; this.report = report; - this.weight = weight; - this.agentId = agentId; this.segmentId = segmentId; - this.userName = userName; - this.userEmail = userEmail; - this.answerText = answerText; - this.answerId = answerId; - this.assessment = assessment; this.timestamp = timestamp; this.url = url; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getAssessmentSid() { - return this.assessmentSid; - } - - public final String getOffset() { - return this.offset; - } - - public final Boolean getReport() { - return this.report; - } - - public final String getWeight() { - return this.weight; - } - - public final String getAgentId() { - return this.agentId; - } - - public final String getSegmentId() { - return this.segmentId; - } - - public final String getUserName() { - return this.userName; - } - - public final String getUserEmail() { - return this.userEmail; - } - - public final String getAnswerText() { - return this.answerText; - } - - public final String getAnswerId() { - return this.answerId; - } - - public final Map getAssessment() { - return this.assessment; - } - - public final String getTimestamp() { - return this.timestamp; - } - - public final URI getUrl() { - return this.url; + this.userEmail = userEmail; + this.userName = userName; + this.weight = weight; } @Override @@ -241,42 +182,44 @@ public boolean equals(final Object o) { } Assessments other = (Assessments) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(assessmentSid, other.assessmentSid) && - Objects.equals(offset, other.offset) && - Objects.equals(report, other.report) && - Objects.equals(weight, other.weight) && - Objects.equals(agentId, other.agentId) && - Objects.equals(segmentId, other.segmentId) && - Objects.equals(userName, other.userName) && - Objects.equals(userEmail, other.userEmail) && - Objects.equals(answerText, other.answerText) && - Objects.equals(answerId, other.answerId) && - Objects.equals(assessment, other.assessment) && - Objects.equals(timestamp, other.timestamp) && - Objects.equals(url, other.url) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(agentId, other.agentId) && + Objects.equals(answerId, other.answerId) && + Objects.equals(answerText, other.answerText) && + Objects.equals(assessment, other.assessment) && + Objects.equals(assessmentSid, other.assessmentSid) && + Objects.equals(offset, other.offset) && + Objects.equals(report, other.report) && + Objects.equals(segmentId, other.segmentId) && + Objects.equals(timestamp, other.timestamp) && + Objects.equals(url, other.url) && + Objects.equals(userEmail, other.userEmail) && + Objects.equals(userName, other.userName) && + Objects.equals(weight, other.weight) ); } @Override public int hashCode() { return Objects.hash( - accountSid, - assessmentSid, - offset, - report, - weight, - agentId, - segmentId, - userName, - userEmail, - answerText, - answerId, - assessment, - timestamp, - url + accountSid, + agentId, + answerId, + answerText, + assessment, + assessmentSid, + offset, + report, + segmentId, + timestamp, + url, + userEmail, + userName, + weight ); } + + } + diff --git a/src/main/java/com/twilio/rest/flexapi/v1/AssessmentsCreator.java b/src/main/java/com/twilio/rest/flexapi/v1/AssessmentsCreator.java index 4ccdfce866..03eb988741 100644 --- a/src/main/java/com/twilio/rest/flexapi/v1/AssessmentsCreator.java +++ b/src/main/java/com/twilio/rest/flexapi/v1/AssessmentsCreator.java @@ -14,8 +14,11 @@ package com.twilio.rest.flexapi.v1; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -24,11 +27,12 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -import java.math.BigDecimal; + import java.math.BigDecimal; public class AssessmentsCreator extends Creator { + private String authorization; private String categorySid; private String categoryName; private String segmentId; @@ -39,20 +43,8 @@ public class AssessmentsCreator extends Creator { private String answerText; private String answerId; private String questionnaireSid; - private String authorization; - public AssessmentsCreator( - final String categorySid, - final String categoryName, - final String segmentId, - final String agentId, - final BigDecimal offset, - final String metricId, - final String metricName, - final String answerText, - final String answerId, - final String questionnaireSid - ) { + public AssessmentsCreator(final String categorySid, final String categoryName, final String segmentId, final String agentId, final BigDecimal offset, final String metricId, final String metricName, final String answerText, final String answerId, final String questionnaireSid) { this.categorySid = categorySid; this.categoryName = categoryName; this.segmentId = segmentId; @@ -65,161 +57,165 @@ public AssessmentsCreator( this.questionnaireSid = questionnaireSid; } + public AssessmentsCreator setCategorySid(final String categorySid) { this.categorySid = categorySid; return this; } + public AssessmentsCreator setCategoryName(final String categoryName) { this.categoryName = categoryName; return this; } + public AssessmentsCreator setSegmentId(final String segmentId) { this.segmentId = segmentId; return this; } + public AssessmentsCreator setAgentId(final String agentId) { this.agentId = agentId; return this; } + public AssessmentsCreator setOffset(final BigDecimal offset) { this.offset = offset; return this; } + public AssessmentsCreator setMetricId(final String metricId) { this.metricId = metricId; return this; } + public AssessmentsCreator setMetricName(final String metricName) { this.metricName = metricName; return this; } + public AssessmentsCreator setAnswerText(final String answerText) { this.answerText = answerText; return this; } + public AssessmentsCreator setAnswerId(final String answerId) { this.answerId = answerId; return this; } - public AssessmentsCreator setQuestionnaireSid( - final String questionnaireSid - ) { + + public AssessmentsCreator setQuestionnaireSid(final String questionnaireSid) { this.questionnaireSid = questionnaireSid; return this; } + public AssessmentsCreator setAuthorization(final String authorization) { this.authorization = authorization; return this; } + @Override public Assessments create(final TwilioRestClient client) { + String path = "/v1/Insights/QualityManagement/Assessments"; - path = - path.replace( - "{" + "CategorySid" + "}", - this.categorySid.toString() - ); - path = - path.replace( - "{" + "CategoryName" + "}", - this.categoryName.toString() - ); - path = path.replace("{" + "SegmentId" + "}", this.segmentId.toString()); - path = path.replace("{" + "AgentId" + "}", this.agentId.toString()); - path = path.replace("{" + "Offset" + "}", this.offset.toString()); - path = path.replace("{" + "MetricId" + "}", this.metricId.toString()); - path = - path.replace("{" + "MetricName" + "}", this.metricName.toString()); - path = - path.replace("{" + "AnswerText" + "}", this.answerText.toString()); - path = path.replace("{" + "AnswerId" + "}", this.answerId.toString()); - path = - path.replace( - "{" + "QuestionnaireSid" + "}", - this.questionnaireSid.toString() - ); Request request = new Request( - HttpMethod.POST, - Domains.FLEXAPI.toString(), - path + HttpMethod.POST, + Domains.FLEXAPI.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); - addPostParams(request); addHeaderParams(request); + addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Assessments creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("Assessments creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Assessments.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Assessments.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (categorySid != null) { - request.addPostParam("CategorySid", categorySid); + Serializer.toString(request, "CategorySid", categorySid, ParameterType.URLENCODED); } + + if (categoryName != null) { - request.addPostParam("CategoryName", categoryName); + Serializer.toString(request, "CategoryName", categoryName, ParameterType.URLENCODED); } + + if (segmentId != null) { - request.addPostParam("SegmentId", segmentId); + Serializer.toString(request, "SegmentId", segmentId, ParameterType.URLENCODED); } + + if (agentId != null) { - request.addPostParam("AgentId", agentId); + Serializer.toString(request, "AgentId", agentId, ParameterType.URLENCODED); } + + if (offset != null) { - request.addPostParam("Offset", offset.toString()); + Serializer.toString(request, "Offset", offset, ParameterType.URLENCODED); } + + if (metricId != null) { - request.addPostParam("MetricId", metricId); + Serializer.toString(request, "MetricId", metricId, ParameterType.URLENCODED); } + + if (metricName != null) { - request.addPostParam("MetricName", metricName); + Serializer.toString(request, "MetricName", metricName, ParameterType.URLENCODED); } + + if (answerText != null) { - request.addPostParam("AnswerText", answerText); + Serializer.toString(request, "AnswerText", answerText, ParameterType.URLENCODED); } + + if (answerId != null) { - request.addPostParam("AnswerId", answerId); + Serializer.toString(request, "AnswerId", answerId, ParameterType.URLENCODED); } + + if (questionnaireSid != null) { - request.addPostParam("QuestionnaireSid", questionnaireSid); + Serializer.toString(request, "QuestionnaireSid", questionnaireSid, ParameterType.URLENCODED); } + + } private void addHeaderParams(final Request request) { + if (authorization != null) { - request.addHeaderParam("Authorization", authorization); + Serializer.toString(request, "Authorization", authorization, ParameterType.HEADER); } + } } diff --git a/src/main/java/com/twilio/rest/flexapi/v1/AssessmentsReader.java b/src/main/java/com/twilio/rest/flexapi/v1/AssessmentsReader.java index 83f4ece41a..b76e7a9a55 100644 --- a/src/main/java/com/twilio/rest/flexapi/v1/AssessmentsReader.java +++ b/src/main/java/com/twilio/rest/flexapi/v1/AssessmentsReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,129 +30,113 @@ public class AssessmentsReader extends Reader { - private String authorization; private String segmentId; private Long pageSize; + private String authorization; - public AssessmentsReader() {} - - public AssessmentsReader setAuthorization(final String authorization) { - this.authorization = authorization; - return this; + public AssessmentsReader() { } + public AssessmentsReader setSegmentId(final String segmentId) { this.segmentId = segmentId; return this; } + public AssessmentsReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + + public AssessmentsReader setAuthorization(final String authorization) { + this.authorization = authorization; + return this; + } + + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/Insights/QualityManagement/Assessments"; + Request request = new Request( - HttpMethod.GET, - Domains.FLEXAPI.toString(), - path + HttpMethod.GET, + Domains.FLEXAPI.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addHeaderParams(request); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Assessments read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Assessments read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "assessments", - response.getContent(), - Assessments.class, - client.getObjectMapper() - ); + "assessments", + response.getContent(), + Assessments.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.FLEXAPI.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.FLEXAPI.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } - private void addHeaderParams(final Request request) { - if (authorization != null) { - request.addHeaderParam("Authorization", authorization); - } - } - private void addQueryParams(final Request request) { + + if (segmentId != null) { - request.addQueryParam("SegmentId", segmentId); + Serializer.toString(request, "SegmentId", segmentId, ParameterType.QUERY); } + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); + + } + + private void addHeaderParams(final Request request) { + + if (authorization != null) { + Serializer.toString(request, "Authorization", authorization, ParameterType.HEADER); } + } } diff --git a/src/main/java/com/twilio/rest/flexapi/v1/AssessmentsUpdater.java b/src/main/java/com/twilio/rest/flexapi/v1/AssessmentsUpdater.java index c9e41cb253..aeb1f8cf8e 100644 --- a/src/main/java/com/twilio/rest/flexapi/v1/AssessmentsUpdater.java +++ b/src/main/java/com/twilio/rest/flexapi/v1/AssessmentsUpdater.java @@ -16,6 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -24,111 +26,107 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.math.BigDecimal; public class AssessmentsUpdater extends Updater { - - private String pathAssessmentSid; + private String pathassessmentSid; + private String authorization; private BigDecimal offset; private String answerText; private String answerId; - private String authorization; - public AssessmentsUpdater( - final String pathAssessmentSid, - final BigDecimal offset, - final String answerText, - final String answerId - ) { - this.pathAssessmentSid = pathAssessmentSid; + public AssessmentsUpdater(final String pathassessmentSid, final BigDecimal offset, final String answerText, final String answerId) { + this.pathassessmentSid = pathassessmentSid; this.offset = offset; this.answerText = answerText; this.answerId = answerId; } + public AssessmentsUpdater setOffset(final BigDecimal offset) { this.offset = offset; return this; } + public AssessmentsUpdater setAnswerText(final String answerText) { this.answerText = answerText; return this; } + public AssessmentsUpdater setAnswerId(final String answerId) { this.answerId = answerId; return this; } + public AssessmentsUpdater setAuthorization(final String authorization) { this.authorization = authorization; return this; } + @Override public Assessments update(final TwilioRestClient client) { - String path = - "/v1/Insights/QualityManagement/Assessments/{AssessmentSid}"; - path = - path.replace( - "{" + "AssessmentSid" + "}", - this.pathAssessmentSid.toString() - ); - path = path.replace("{" + "Offset" + "}", this.offset.toString()); - path = - path.replace("{" + "AnswerText" + "}", this.answerText.toString()); - path = path.replace("{" + "AnswerId" + "}", this.answerId.toString()); + String path = "/v1/Insights/QualityManagement/Assessments/{AssessmentSid}"; + + path = path.replace("{" + "AssessmentSid" + "}", this.pathassessmentSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.FLEXAPI.toString(), - path + HttpMethod.POST, + Domains.FLEXAPI.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); - addPostParams(request); addHeaderParams(request); + addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Assessments update failed: Unable to connect to server" - ); + throw new ApiConnectionException("Assessments update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Assessments.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Assessments.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (offset != null) { - request.addPostParam("Offset", offset.toString()); + Serializer.toString(request, "Offset", offset, ParameterType.URLENCODED); } + + if (answerText != null) { - request.addPostParam("AnswerText", answerText); + Serializer.toString(request, "AnswerText", answerText, ParameterType.URLENCODED); } + + if (answerId != null) { - request.addPostParam("AnswerId", answerId); + Serializer.toString(request, "AnswerId", answerId, ParameterType.URLENCODED); } + + } private void addHeaderParams(final Request request) { + if (authorization != null) { - request.addHeaderParam("Authorization", authorization); + Serializer.toString(request, "Authorization", authorization, ParameterType.HEADER); } + } } diff --git a/src/main/java/com/twilio/rest/flexapi/v1/Channel.java b/src/main/java/com/twilio/rest/flexapi/v1/Channel.java index bde09c99f7..bd882a0b1f 100644 --- a/src/main/java/com/twilio/rest/flexapi/v1/Channel.java +++ b/src/main/java/com/twilio/rest/flexapi/v1/Channel.java @@ -18,63 +18,63 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Channel extends Resource { - private static final long serialVersionUID = 86822994047371L; - public static ChannelCreator creator( - final String flexFlowSid, - final String identity, - final String chatUserFriendlyName, - final String chatFriendlyName - ) { + public static ChannelCreator creator(final String flexFlowSid, final String identity, final String chatUserFriendlyName, final String chatFriendlyName) { return new ChannelCreator( - flexFlowSid, - identity, - chatUserFriendlyName, - chatFriendlyName + flexFlowSid, identity, chatUserFriendlyName, chatFriendlyName ); } - public static ChannelDeleter deleter(final String pathSid) { - return new ChannelDeleter(pathSid); + + public static ChannelDeleter deleter(final String pathsid) { + return new ChannelDeleter( + pathsid + ); } - public static ChannelFetcher fetcher(final String pathSid) { - return new ChannelFetcher(pathSid); + + public static ChannelFetcher fetcher(final String pathsid) { + return new ChannelFetcher( + pathsid + ); } + public static ChannelReader reader() { - return new ChannelReader(); + return new ChannelReader( + + ); } + /** * Converts a JSON String into a Channel object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Channel object represented by the provided JSON */ - public static Channel fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Channel fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Channel.class); @@ -89,14 +89,11 @@ public static Channel fromJson( * Converts a JSON InputStream into a Channel object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Channel object represented by the provided JSON */ - public static Channel fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Channel fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Channel.class); @@ -107,66 +104,57 @@ public static Channel fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; + @Getter + private final ZonedDateTime dateCreated; + @Getter + private final ZonedDateTime dateUpdated; + @Getter private final String flexFlowSid; + @Getter private final String sid; - private final String userSid; + @Getter private final String taskSid; + @Getter private final URI url; - private final ZonedDateTime dateCreated; - private final ZonedDateTime dateUpdated; + @Getter + private final String userSid; @JsonCreator private Channel( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("flex_flow_sid") final String flexFlowSid, - @JsonProperty("sid") final String sid, - @JsonProperty("user_sid") final String userSid, - @JsonProperty("task_sid") final String taskSid, - @JsonProperty("url") final URI url, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("flex_flow_sid") final String flexFlowSid, + @JsonProperty("sid") final String sid, + @JsonProperty("task_sid") final String taskSid, + @JsonProperty("url") final URI url, + @JsonProperty("user_sid") final String userSid ) { this.accountSid = accountSid; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.flexFlowSid = flexFlowSid; this.sid = sid; - this.userSid = userSid; this.taskSid = taskSid; this.url = url; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getFlexFlowSid() { - return this.flexFlowSid; - } - - public final String getSid() { - return this.sid; - } - - public final String getUserSid() { - return this.userSid; - } - - public final String getTaskSid() { - return this.taskSid; - } - - public final URI getUrl() { - return this.url; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; + this.userSid = userSid; } @Override @@ -180,30 +168,32 @@ public boolean equals(final Object o) { } Channel other = (Channel) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(flexFlowSid, other.flexFlowSid) && - Objects.equals(sid, other.sid) && - Objects.equals(userSid, other.userSid) && - Objects.equals(taskSid, other.taskSid) && - Objects.equals(url, other.url) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(flexFlowSid, other.flexFlowSid) && + Objects.equals(sid, other.sid) && + Objects.equals(taskSid, other.taskSid) && + Objects.equals(url, other.url) && + Objects.equals(userSid, other.userSid) ); } @Override public int hashCode() { return Objects.hash( - accountSid, - flexFlowSid, - sid, - userSid, - taskSid, - url, - dateCreated, - dateUpdated + accountSid, + dateCreated, + dateUpdated, + flexFlowSid, + sid, + taskSid, + url, + userSid ); } + + } + diff --git a/src/main/java/com/twilio/rest/flexapi/v1/ChannelCreator.java b/src/main/java/com/twilio/rest/flexapi/v1/ChannelCreator.java index 373a9bb506..8443b7b0cc 100644 --- a/src/main/java/com/twilio/rest/flexapi/v1/ChannelCreator.java +++ b/src/main/java/com/twilio/rest/flexapi/v1/ChannelCreator.java @@ -14,8 +14,11 @@ package com.twilio.rest.flexapi.v1; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -38,113 +41,99 @@ public class ChannelCreator extends Creator { private String taskAttributes; private Boolean longLived; - public ChannelCreator( - final String flexFlowSid, - final String identity, - final String chatUserFriendlyName, - final String chatFriendlyName - ) { + public ChannelCreator(final String flexFlowSid, final String identity, final String chatUserFriendlyName, final String chatFriendlyName) { this.flexFlowSid = flexFlowSid; this.identity = identity; this.chatUserFriendlyName = chatUserFriendlyName; this.chatFriendlyName = chatFriendlyName; } + public ChannelCreator setFlexFlowSid(final String flexFlowSid) { this.flexFlowSid = flexFlowSid; return this; } + public ChannelCreator setIdentity(final String identity) { this.identity = identity; return this; } - public ChannelCreator setChatUserFriendlyName( - final String chatUserFriendlyName - ) { + + public ChannelCreator setChatUserFriendlyName(final String chatUserFriendlyName) { this.chatUserFriendlyName = chatUserFriendlyName; return this; } + public ChannelCreator setChatFriendlyName(final String chatFriendlyName) { this.chatFriendlyName = chatFriendlyName; return this; } + public ChannelCreator setTarget(final String target) { this.target = target; return this; } + public ChannelCreator setChatUniqueName(final String chatUniqueName) { this.chatUniqueName = chatUniqueName; return this; } + public ChannelCreator setPreEngagementData(final String preEngagementData) { this.preEngagementData = preEngagementData; return this; } + public ChannelCreator setTaskSid(final String taskSid) { this.taskSid = taskSid; return this; } + public ChannelCreator setTaskAttributes(final String taskAttributes) { this.taskAttributes = taskAttributes; return this; } + public ChannelCreator setLongLived(final Boolean longLived) { this.longLived = longLived; return this; } + @Override public Channel create(final TwilioRestClient client) { + String path = "/v1/Channels"; - path = - path.replace( - "{" + "FlexFlowSid" + "}", - this.flexFlowSid.toString() - ); - path = path.replace("{" + "Identity" + "}", this.identity.toString()); - path = - path.replace( - "{" + "ChatUserFriendlyName" + "}", - this.chatUserFriendlyName.toString() - ); - path = - path.replace( - "{" + "ChatFriendlyName" + "}", - this.chatFriendlyName.toString() - ); Request request = new Request( - HttpMethod.POST, - Domains.FLEXAPI.toString(), - path + HttpMethod.POST, + Domains.FLEXAPI.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Channel creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("Channel creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -153,35 +142,56 @@ public Channel create(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (flexFlowSid != null) { - request.addPostParam("FlexFlowSid", flexFlowSid); + Serializer.toString(request, "FlexFlowSid", flexFlowSid, ParameterType.URLENCODED); } + + if (identity != null) { - request.addPostParam("Identity", identity); + Serializer.toString(request, "Identity", identity, ParameterType.URLENCODED); } + + if (chatUserFriendlyName != null) { - request.addPostParam("ChatUserFriendlyName", chatUserFriendlyName); + Serializer.toString(request, "ChatUserFriendlyName", chatUserFriendlyName, ParameterType.URLENCODED); } + + if (chatFriendlyName != null) { - request.addPostParam("ChatFriendlyName", chatFriendlyName); + Serializer.toString(request, "ChatFriendlyName", chatFriendlyName, ParameterType.URLENCODED); } + + if (target != null) { - request.addPostParam("Target", target); + Serializer.toString(request, "Target", target, ParameterType.URLENCODED); } + + if (chatUniqueName != null) { - request.addPostParam("ChatUniqueName", chatUniqueName); + Serializer.toString(request, "ChatUniqueName", chatUniqueName, ParameterType.URLENCODED); } + + if (preEngagementData != null) { - request.addPostParam("PreEngagementData", preEngagementData); + Serializer.toString(request, "PreEngagementData", preEngagementData, ParameterType.URLENCODED); } + + if (taskSid != null) { - request.addPostParam("TaskSid", taskSid); + Serializer.toString(request, "TaskSid", taskSid, ParameterType.URLENCODED); } + + if (taskAttributes != null) { - request.addPostParam("TaskAttributes", taskAttributes); + Serializer.toString(request, "TaskAttributes", taskAttributes, ParameterType.URLENCODED); } + + if (longLived != null) { - request.addPostParam("LongLived", longLived.toString()); + Serializer.toString(request, "LongLived", longLived, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/flexapi/v1/ChannelDeleter.java b/src/main/java/com/twilio/rest/flexapi/v1/ChannelDeleter.java index 230b5cda77..13fe697b2d 100644 --- a/src/main/java/com/twilio/rest/flexapi/v1/ChannelDeleter.java +++ b/src/main/java/com/twilio/rest/flexapi/v1/ChannelDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.flexapi.v1; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,40 +26,38 @@ public class ChannelDeleter extends Deleter { - private String pathSid; + private String pathsid; - public ChannelDeleter(final String pathSid) { - this.pathSid = pathSid; + public ChannelDeleter(final String pathsid) { + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/v1/Channels/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.FLEXAPI.toString(), - path + HttpMethod.DELETE, + Domains.FLEXAPI.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Channel delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("Channel delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/flexapi/v1/ChannelFetcher.java b/src/main/java/com/twilio/rest/flexapi/v1/ChannelFetcher.java index da20b419a8..f971780ac8 100644 --- a/src/main/java/com/twilio/rest/flexapi/v1/ChannelFetcher.java +++ b/src/main/java/com/twilio/rest/flexapi/v1/ChannelFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.flexapi.v1; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,44 +26,41 @@ public class ChannelFetcher extends Fetcher { - private String pathSid; + private String pathsid; - public ChannelFetcher(final String pathSid) { - this.pathSid = pathSid; + public ChannelFetcher(final String pathsid) { + this.pathsid = pathsid; } + @Override public Channel fetch(final TwilioRestClient client) { + String path = "/v1/Channels/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.FLEXAPI.toString(), - path + HttpMethod.GET, + Domains.FLEXAPI.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Channel fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Channel fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Channel.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/flexapi/v1/ChannelReader.java b/src/main/java/com/twilio/rest/flexapi/v1/ChannelReader.java index a37287d050..334b75d5e3 100644 --- a/src/main/java/com/twilio/rest/flexapi/v1/ChannelReader.java +++ b/src/main/java/com/twilio/rest/flexapi/v1/ChannelReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -31,105 +32,83 @@ public class ChannelReader extends Reader { private Long pageSize; - public ChannelReader() {} + public ChannelReader() { + } + public ChannelReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/Channels"; + Request request = new Request( - HttpMethod.GET, - Domains.FLEXAPI.toString(), - path + HttpMethod.GET, + Domains.FLEXAPI.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Channel read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Channel read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "flex_chat_channels", - response.getContent(), - Channel.class, - client.getObjectMapper() - ); + "flex_chat_channels", + response.getContent(), + Channel.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.FLEXAPI.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.FLEXAPI.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/flexapi/v1/Configuration.java b/src/main/java/com/twilio/rest/flexapi/v1/Configuration.java index 79e780fa58..fb80548b52 100644 --- a/src/main/java/com/twilio/rest/flexapi/v1/Configuration.java +++ b/src/main/java/com/twilio/rest/flexapi/v1/Configuration.java @@ -21,47 +21,70 @@ import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.List; -import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Configuration extends Resource { - private static final long serialVersionUID = 254841674782325L; public static ConfigurationFetcher fetcher() { - return new ConfigurationFetcher(); + return new ConfigurationFetcher( + + ); } + public static ConfigurationUpdater updater() { - return new ConfigurationUpdater(); + return new ConfigurationUpdater( + + ); } + + public enum Status { + OK("ok"), + INPROGRESS("inprogress"), + NOTSTARTED("notstarted"); + + private final String value; + + private Status(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static Status forValue(final String value) { + return Promoter.enumFromString(value, Status.values()); + } + } + + /** * Converts a JSON String into a Configuration object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Configuration object represented by the provided JSON */ - public static Configuration fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Configuration fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Configuration.class); @@ -76,14 +99,11 @@ public static Configuration fromJson( * Converts a JSON InputStream into a Configuration object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Configuration object represented by the provided JSON */ - public static Configuration fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Configuration fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Configuration.class); @@ -106,421 +126,209 @@ public static String toJson(Object object, ObjectMapper mapper) { } } + + @Getter private final String accountSid; - private final ZonedDateTime dateCreated; - private final ZonedDateTime dateUpdated; - private final Map attributes; - private final Configuration.Status status; - private final String taskrouterWorkspaceSid; - private final String taskrouterTargetWorkflowSid; - private final String taskrouterTargetTaskqueueSid; - private final List> taskrouterTaskqueues; - private final List> taskrouterSkills; - private final Map taskrouterWorkerChannels; - private final Map taskrouterWorkerAttributes; - private final String taskrouterOfflineActivitySid; - private final String runtimeDomain; - private final String messagingServiceInstanceSid; - private final String chatServiceInstanceSid; - private final String flexServiceInstanceSid; - private final String flexInstanceSid; - private final String uiLanguage; - private final Map uiAttributes; - private final Map uiDependencies; - private final String uiVersion; - private final String serviceVersion; + @Getter + private final Object agentConvEndMethods; + @Getter + private final Object attributes; + @Getter private final Boolean callRecordingEnabled; + @Getter private final String callRecordingWebhookUrl; - private final Boolean crmEnabled; - private final String crmType; + @Getter + private final List channelConfigs; + @Getter + private final String chatServiceInstanceSid; + @Getter + private final Object citrixVoiceVdi; + @Getter + private final Object crmAttributes; + @Getter private final String crmCallbackUrl; + @Getter + private final Boolean crmEnabled; + @Getter private final String crmFallbackUrl; - private final Map crmAttributes; - private final Map publicAttributes; + @Getter + private final String crmType; + @Getter + private final ZonedDateTime dateCreated; + @Getter + private final ZonedDateTime dateUpdated; + @Getter + private final Object debuggerIntegration; + @Getter + private final Boolean flexInsightsDrilldown; + @Getter + private final Object flexInsightsHr; + @Getter + private final String flexInstanceSid; + @Getter + private final String flexServiceInstanceSid; + @Getter + private final Object flexUiStatusReport; + @Getter + private final String flexUrl; + @Getter + private final List integrations; + @Getter + private final Object markdown; + @Getter + private final String messagingServiceInstanceSid; + @Getter + private final Object notifications; + @Getter + private final Object offlineConfig; + @Getter + private final Object outboundCallFlows; + @Getter + private final Object pluginServiceAttributes; + @Getter private final Boolean pluginServiceEnabled; - private final Map pluginServiceAttributes; - private final List> integrations; - private final Map outboundCallFlows; + @Getter + private final Object publicAttributes; + @Getter + private final Object queueStatsConfiguration; + @Getter + private final String runtimeDomain; + @Getter private final List serverlessServiceSids; - private final Map queueStatsConfiguration; - private final Map notifications; - private final Map markdown; + @Getter + private final String serviceVersion; + @Getter + private final Configuration.Status status; + @Getter + private final String taskrouterOfflineActivitySid; + @Getter + private final List taskrouterSkills; + @Getter + private final String taskrouterTargetTaskqueueSid; + @Getter + private final String taskrouterTargetWorkflowSid; + @Getter + private final List taskrouterTaskqueues; + @Getter + private final Object taskrouterWorkerAttributes; + @Getter + private final Object taskrouterWorkerChannels; + @Getter + private final String taskrouterWorkspaceSid; + @Getter + private final Object uiAttributes; + @Getter + private final Object uiDependencies; + @Getter + private final String uiLanguage; + @Getter + private final String uiVersion; + @Getter private final URI url; - private final Map flexInsightsHr; - private final Boolean flexInsightsDrilldown; - private final String flexUrl; - private final List> channelConfigs; - private final Map debuggerIntegration; - private final Map flexUiStatusReport; - private final Map agentConvEndMethods; - private final Map citrixVoiceVdi; - private final Map offlineConfig; @JsonCreator private Configuration( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("attributes") final Map attributes, - @JsonProperty("status") final Configuration.Status status, - @JsonProperty( - "taskrouter_workspace_sid" - ) final String taskrouterWorkspaceSid, - @JsonProperty( - "taskrouter_target_workflow_sid" - ) final String taskrouterTargetWorkflowSid, - @JsonProperty( - "taskrouter_target_taskqueue_sid" - ) final String taskrouterTargetTaskqueueSid, - @JsonProperty("taskrouter_taskqueues") final List< - Map - > taskrouterTaskqueues, - @JsonProperty("taskrouter_skills") final List< - Map - > taskrouterSkills, - @JsonProperty("taskrouter_worker_channels") final Map< - String, - Object - > taskrouterWorkerChannels, - @JsonProperty("taskrouter_worker_attributes") final Map< - String, - Object - > taskrouterWorkerAttributes, - @JsonProperty( - "taskrouter_offline_activity_sid" - ) final String taskrouterOfflineActivitySid, - @JsonProperty("runtime_domain") final String runtimeDomain, - @JsonProperty( - "messaging_service_instance_sid" - ) final String messagingServiceInstanceSid, - @JsonProperty( - "chat_service_instance_sid" - ) final String chatServiceInstanceSid, - @JsonProperty( - "flex_service_instance_sid" - ) final String flexServiceInstanceSid, - @JsonProperty("flex_instance_sid") final String flexInstanceSid, - @JsonProperty("ui_language") final String uiLanguage, - @JsonProperty("ui_attributes") final Map uiAttributes, - @JsonProperty("ui_dependencies") final Map< - String, - Object - > uiDependencies, - @JsonProperty("ui_version") final String uiVersion, - @JsonProperty("service_version") final String serviceVersion, - @JsonProperty( - "call_recording_enabled" - ) final Boolean callRecordingEnabled, - @JsonProperty( - "call_recording_webhook_url" - ) final String callRecordingWebhookUrl, - @JsonProperty("crm_enabled") final Boolean crmEnabled, - @JsonProperty("crm_type") final String crmType, - @JsonProperty("crm_callback_url") final String crmCallbackUrl, - @JsonProperty("crm_fallback_url") final String crmFallbackUrl, - @JsonProperty("crm_attributes") final Map crmAttributes, - @JsonProperty("public_attributes") final Map< - String, - Object - > publicAttributes, - @JsonProperty( - "plugin_service_enabled" - ) final Boolean pluginServiceEnabled, - @JsonProperty("plugin_service_attributes") final Map< - String, - Object - > pluginServiceAttributes, - @JsonProperty("integrations") final List< - Map - > integrations, - @JsonProperty("outbound_call_flows") final Map< - String, - Object - > outboundCallFlows, - @JsonProperty("serverless_service_sids") final List< - String - > serverlessServiceSids, - @JsonProperty("queue_stats_configuration") final Map< - String, - Object - > queueStatsConfiguration, - @JsonProperty("notifications") final Map notifications, - @JsonProperty("markdown") final Map markdown, - @JsonProperty("url") final URI url, - @JsonProperty("flex_insights_hr") final Map< - String, - Object - > flexInsightsHr, - @JsonProperty( - "flex_insights_drilldown" - ) final Boolean flexInsightsDrilldown, - @JsonProperty("flex_url") final String flexUrl, - @JsonProperty("channel_configs") final List< - Map - > channelConfigs, - @JsonProperty("debugger_integration") final Map< - String, - Object - > debuggerIntegration, - @JsonProperty("flex_ui_status_report") final Map< - String, - Object - > flexUiStatusReport, - @JsonProperty("agent_conv_end_methods") final Map< - String, - Object - > agentConvEndMethods, - @JsonProperty("citrix_voice_vdi") final Map< - String, - Object - > citrixVoiceVdi, - @JsonProperty("offline_config") final Map offlineConfig + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("agent_conv_end_methods") final Object agentConvEndMethods, + @JsonProperty("attributes") final Object attributes, + @JsonProperty("call_recording_enabled") final Boolean callRecordingEnabled, + @JsonProperty("call_recording_webhook_url") final String callRecordingWebhookUrl, + @JsonProperty("channel_configs") final List channelConfigs, + @JsonProperty("chat_service_instance_sid") final String chatServiceInstanceSid, + @JsonProperty("citrix_voice_vdi") final Object citrixVoiceVdi, + @JsonProperty("crm_attributes") final Object crmAttributes, + @JsonProperty("crm_callback_url") final String crmCallbackUrl, + @JsonProperty("crm_enabled") final Boolean crmEnabled, + @JsonProperty("crm_fallback_url") final String crmFallbackUrl, + @JsonProperty("crm_type") final String crmType, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("debugger_integration") final Object debuggerIntegration, + @JsonProperty("flex_insights_drilldown") final Boolean flexInsightsDrilldown, + @JsonProperty("flex_insights_hr") final Object flexInsightsHr, + @JsonProperty("flex_instance_sid") final String flexInstanceSid, + @JsonProperty("flex_service_instance_sid") final String flexServiceInstanceSid, + @JsonProperty("flex_ui_status_report") final Object flexUiStatusReport, + @JsonProperty("flex_url") final String flexUrl, + @JsonProperty("integrations") final List integrations, + @JsonProperty("markdown") final Object markdown, + @JsonProperty("messaging_service_instance_sid") final String messagingServiceInstanceSid, + @JsonProperty("notifications") final Object notifications, + @JsonProperty("offline_config") final Object offlineConfig, + @JsonProperty("outbound_call_flows") final Object outboundCallFlows, + @JsonProperty("plugin_service_attributes") final Object pluginServiceAttributes, + @JsonProperty("plugin_service_enabled") final Boolean pluginServiceEnabled, + @JsonProperty("public_attributes") final Object publicAttributes, + @JsonProperty("queue_stats_configuration") final Object queueStatsConfiguration, + @JsonProperty("runtime_domain") final String runtimeDomain, + @JsonProperty("serverless_service_sids") final List serverlessServiceSids, + @JsonProperty("service_version") final String serviceVersion, + @JsonProperty("status") final Configuration.Status status, + @JsonProperty("taskrouter_offline_activity_sid") final String taskrouterOfflineActivitySid, + @JsonProperty("taskrouter_skills") final List taskrouterSkills, + @JsonProperty("taskrouter_target_taskqueue_sid") final String taskrouterTargetTaskqueueSid, + @JsonProperty("taskrouter_target_workflow_sid") final String taskrouterTargetWorkflowSid, + @JsonProperty("taskrouter_taskqueues") final List taskrouterTaskqueues, + @JsonProperty("taskrouter_worker_attributes") final Object taskrouterWorkerAttributes, + @JsonProperty("taskrouter_worker_channels") final Object taskrouterWorkerChannels, + @JsonProperty("taskrouter_workspace_sid") final String taskrouterWorkspaceSid, + @JsonProperty("ui_attributes") final Object uiAttributes, + @JsonProperty("ui_dependencies") final Object uiDependencies, + @JsonProperty("ui_language") final String uiLanguage, + @JsonProperty("ui_version") final String uiVersion, + @JsonProperty("url") final URI url ) { this.accountSid = accountSid; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); + this.agentConvEndMethods = agentConvEndMethods; this.attributes = attributes; - this.status = status; - this.taskrouterWorkspaceSid = taskrouterWorkspaceSid; - this.taskrouterTargetWorkflowSid = taskrouterTargetWorkflowSid; - this.taskrouterTargetTaskqueueSid = taskrouterTargetTaskqueueSid; - this.taskrouterTaskqueues = taskrouterTaskqueues; - this.taskrouterSkills = taskrouterSkills; - this.taskrouterWorkerChannels = taskrouterWorkerChannels; - this.taskrouterWorkerAttributes = taskrouterWorkerAttributes; - this.taskrouterOfflineActivitySid = taskrouterOfflineActivitySid; - this.runtimeDomain = runtimeDomain; - this.messagingServiceInstanceSid = messagingServiceInstanceSid; - this.chatServiceInstanceSid = chatServiceInstanceSid; - this.flexServiceInstanceSid = flexServiceInstanceSid; - this.flexInstanceSid = flexInstanceSid; - this.uiLanguage = uiLanguage; - this.uiAttributes = uiAttributes; - this.uiDependencies = uiDependencies; - this.uiVersion = uiVersion; - this.serviceVersion = serviceVersion; this.callRecordingEnabled = callRecordingEnabled; this.callRecordingWebhookUrl = callRecordingWebhookUrl; - this.crmEnabled = crmEnabled; - this.crmType = crmType; + this.channelConfigs = channelConfigs; + this.chatServiceInstanceSid = chatServiceInstanceSid; + this.citrixVoiceVdi = citrixVoiceVdi; + this.crmAttributes = crmAttributes; this.crmCallbackUrl = crmCallbackUrl; + this.crmEnabled = crmEnabled; this.crmFallbackUrl = crmFallbackUrl; - this.crmAttributes = crmAttributes; - this.publicAttributes = publicAttributes; - this.pluginServiceEnabled = pluginServiceEnabled; - this.pluginServiceAttributes = pluginServiceAttributes; + this.crmType = crmType; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; + this.debuggerIntegration = debuggerIntegration; + this.flexInsightsDrilldown = flexInsightsDrilldown; + this.flexInsightsHr = flexInsightsHr; + this.flexInstanceSid = flexInstanceSid; + this.flexServiceInstanceSid = flexServiceInstanceSid; + this.flexUiStatusReport = flexUiStatusReport; + this.flexUrl = flexUrl; this.integrations = integrations; + this.markdown = markdown; + this.messagingServiceInstanceSid = messagingServiceInstanceSid; + this.notifications = notifications; + this.offlineConfig = offlineConfig; this.outboundCallFlows = outboundCallFlows; - this.serverlessServiceSids = serverlessServiceSids; + this.pluginServiceAttributes = pluginServiceAttributes; + this.pluginServiceEnabled = pluginServiceEnabled; + this.publicAttributes = publicAttributes; this.queueStatsConfiguration = queueStatsConfiguration; - this.notifications = notifications; - this.markdown = markdown; + this.runtimeDomain = runtimeDomain; + this.serverlessServiceSids = serverlessServiceSids; + this.serviceVersion = serviceVersion; + this.status = status; + this.taskrouterOfflineActivitySid = taskrouterOfflineActivitySid; + this.taskrouterSkills = taskrouterSkills; + this.taskrouterTargetTaskqueueSid = taskrouterTargetTaskqueueSid; + this.taskrouterTargetWorkflowSid = taskrouterTargetWorkflowSid; + this.taskrouterTaskqueues = taskrouterTaskqueues; + this.taskrouterWorkerAttributes = taskrouterWorkerAttributes; + this.taskrouterWorkerChannels = taskrouterWorkerChannels; + this.taskrouterWorkspaceSid = taskrouterWorkspaceSid; + this.uiAttributes = uiAttributes; + this.uiDependencies = uiDependencies; + this.uiLanguage = uiLanguage; + this.uiVersion = uiVersion; this.url = url; - this.flexInsightsHr = flexInsightsHr; - this.flexInsightsDrilldown = flexInsightsDrilldown; - this.flexUrl = flexUrl; - this.channelConfigs = channelConfigs; - this.debuggerIntegration = debuggerIntegration; - this.flexUiStatusReport = flexUiStatusReport; - this.agentConvEndMethods = agentConvEndMethods; - this.citrixVoiceVdi = citrixVoiceVdi; - this.offlineConfig = offlineConfig; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final Map getAttributes() { - return this.attributes; - } - - public final Configuration.Status getStatus() { - return this.status; - } - - public final String getTaskrouterWorkspaceSid() { - return this.taskrouterWorkspaceSid; - } - - public final String getTaskrouterTargetWorkflowSid() { - return this.taskrouterTargetWorkflowSid; - } - - public final String getTaskrouterTargetTaskqueueSid() { - return this.taskrouterTargetTaskqueueSid; - } - - public final List> getTaskrouterTaskqueues() { - return this.taskrouterTaskqueues; - } - - public final List> getTaskrouterSkills() { - return this.taskrouterSkills; - } - - public final Map getTaskrouterWorkerChannels() { - return this.taskrouterWorkerChannels; - } - - public final Map getTaskrouterWorkerAttributes() { - return this.taskrouterWorkerAttributes; - } - - public final String getTaskrouterOfflineActivitySid() { - return this.taskrouterOfflineActivitySid; - } - - public final String getRuntimeDomain() { - return this.runtimeDomain; - } - - public final String getMessagingServiceInstanceSid() { - return this.messagingServiceInstanceSid; - } - - public final String getChatServiceInstanceSid() { - return this.chatServiceInstanceSid; - } - - public final String getFlexServiceInstanceSid() { - return this.flexServiceInstanceSid; - } - - public final String getFlexInstanceSid() { - return this.flexInstanceSid; - } - - public final String getUiLanguage() { - return this.uiLanguage; - } - - public final Map getUiAttributes() { - return this.uiAttributes; - } - - public final Map getUiDependencies() { - return this.uiDependencies; - } - - public final String getUiVersion() { - return this.uiVersion; - } - - public final String getServiceVersion() { - return this.serviceVersion; - } - - public final Boolean getCallRecordingEnabled() { - return this.callRecordingEnabled; - } - - public final String getCallRecordingWebhookUrl() { - return this.callRecordingWebhookUrl; - } - - public final Boolean getCrmEnabled() { - return this.crmEnabled; - } - - public final String getCrmType() { - return this.crmType; - } - - public final String getCrmCallbackUrl() { - return this.crmCallbackUrl; - } - - public final String getCrmFallbackUrl() { - return this.crmFallbackUrl; - } - - public final Map getCrmAttributes() { - return this.crmAttributes; - } - - public final Map getPublicAttributes() { - return this.publicAttributes; - } - - public final Boolean getPluginServiceEnabled() { - return this.pluginServiceEnabled; - } - - public final Map getPluginServiceAttributes() { - return this.pluginServiceAttributes; - } - - public final List> getIntegrations() { - return this.integrations; - } - - public final Map getOutboundCallFlows() { - return this.outboundCallFlows; - } - - public final List getServerlessServiceSids() { - return this.serverlessServiceSids; - } - - public final Map getQueueStatsConfiguration() { - return this.queueStatsConfiguration; - } - - public final Map getNotifications() { - return this.notifications; - } - - public final Map getMarkdown() { - return this.markdown; - } - - public final URI getUrl() { - return this.url; - } - - public final Map getFlexInsightsHr() { - return this.flexInsightsHr; - } - - public final Boolean getFlexInsightsDrilldown() { - return this.flexInsightsDrilldown; - } - - public final String getFlexUrl() { - return this.flexUrl; - } - - public final List> getChannelConfigs() { - return this.channelConfigs; - } - - public final Map getDebuggerIntegration() { - return this.debuggerIntegration; - } - - public final Map getFlexUiStatusReport() { - return this.flexUiStatusReport; - } - - public final Map getAgentConvEndMethods() { - return this.agentConvEndMethods; - } - - public final Map getCitrixVoiceVdi() { - return this.citrixVoiceVdi; - } - - public final Map getOfflineConfig() { - return this.offlineConfig; } @Override @@ -534,175 +342,114 @@ public boolean equals(final Object o) { } Configuration other = (Configuration) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(attributes, other.attributes) && - Objects.equals(status, other.status) && - Objects.equals( - taskrouterWorkspaceSid, - other.taskrouterWorkspaceSid - ) && - Objects.equals( - taskrouterTargetWorkflowSid, - other.taskrouterTargetWorkflowSid - ) && - Objects.equals( - taskrouterTargetTaskqueueSid, - other.taskrouterTargetTaskqueueSid - ) && - Objects.equals(taskrouterTaskqueues, other.taskrouterTaskqueues) && - Objects.equals(taskrouterSkills, other.taskrouterSkills) && - Objects.equals( - taskrouterWorkerChannels, - other.taskrouterWorkerChannels - ) && - Objects.equals( - taskrouterWorkerAttributes, - other.taskrouterWorkerAttributes - ) && - Objects.equals( - taskrouterOfflineActivitySid, - other.taskrouterOfflineActivitySid - ) && - Objects.equals(runtimeDomain, other.runtimeDomain) && - Objects.equals( - messagingServiceInstanceSid, - other.messagingServiceInstanceSid - ) && - Objects.equals( - chatServiceInstanceSid, - other.chatServiceInstanceSid - ) && - Objects.equals( - flexServiceInstanceSid, - other.flexServiceInstanceSid - ) && - Objects.equals(flexInstanceSid, other.flexInstanceSid) && - Objects.equals(uiLanguage, other.uiLanguage) && - Objects.equals(uiAttributes, other.uiAttributes) && - Objects.equals(uiDependencies, other.uiDependencies) && - Objects.equals(uiVersion, other.uiVersion) && - Objects.equals(serviceVersion, other.serviceVersion) && - Objects.equals(callRecordingEnabled, other.callRecordingEnabled) && - Objects.equals( - callRecordingWebhookUrl, - other.callRecordingWebhookUrl - ) && - Objects.equals(crmEnabled, other.crmEnabled) && - Objects.equals(crmType, other.crmType) && - Objects.equals(crmCallbackUrl, other.crmCallbackUrl) && - Objects.equals(crmFallbackUrl, other.crmFallbackUrl) && - Objects.equals(crmAttributes, other.crmAttributes) && - Objects.equals(publicAttributes, other.publicAttributes) && - Objects.equals(pluginServiceEnabled, other.pluginServiceEnabled) && - Objects.equals( - pluginServiceAttributes, - other.pluginServiceAttributes - ) && - Objects.equals(integrations, other.integrations) && - Objects.equals(outboundCallFlows, other.outboundCallFlows) && - Objects.equals( - serverlessServiceSids, - other.serverlessServiceSids - ) && - Objects.equals( - queueStatsConfiguration, - other.queueStatsConfiguration - ) && - Objects.equals(notifications, other.notifications) && - Objects.equals(markdown, other.markdown) && - Objects.equals(url, other.url) && - Objects.equals(flexInsightsHr, other.flexInsightsHr) && - Objects.equals( - flexInsightsDrilldown, - other.flexInsightsDrilldown - ) && - Objects.equals(flexUrl, other.flexUrl) && - Objects.equals(channelConfigs, other.channelConfigs) && - Objects.equals(debuggerIntegration, other.debuggerIntegration) && - Objects.equals(flexUiStatusReport, other.flexUiStatusReport) && - Objects.equals(agentConvEndMethods, other.agentConvEndMethods) && - Objects.equals(citrixVoiceVdi, other.citrixVoiceVdi) && - Objects.equals(offlineConfig, other.offlineConfig) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(agentConvEndMethods, other.agentConvEndMethods) && + Objects.equals(attributes, other.attributes) && + Objects.equals(callRecordingEnabled, other.callRecordingEnabled) && + Objects.equals(callRecordingWebhookUrl, other.callRecordingWebhookUrl) && + Objects.equals(channelConfigs, other.channelConfigs) && + Objects.equals(chatServiceInstanceSid, other.chatServiceInstanceSid) && + Objects.equals(citrixVoiceVdi, other.citrixVoiceVdi) && + Objects.equals(crmAttributes, other.crmAttributes) && + Objects.equals(crmCallbackUrl, other.crmCallbackUrl) && + Objects.equals(crmEnabled, other.crmEnabled) && + Objects.equals(crmFallbackUrl, other.crmFallbackUrl) && + Objects.equals(crmType, other.crmType) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(debuggerIntegration, other.debuggerIntegration) && + Objects.equals(flexInsightsDrilldown, other.flexInsightsDrilldown) && + Objects.equals(flexInsightsHr, other.flexInsightsHr) && + Objects.equals(flexInstanceSid, other.flexInstanceSid) && + Objects.equals(flexServiceInstanceSid, other.flexServiceInstanceSid) && + Objects.equals(flexUiStatusReport, other.flexUiStatusReport) && + Objects.equals(flexUrl, other.flexUrl) && + Objects.equals(integrations, other.integrations) && + Objects.equals(markdown, other.markdown) && + Objects.equals(messagingServiceInstanceSid, other.messagingServiceInstanceSid) && + Objects.equals(notifications, other.notifications) && + Objects.equals(offlineConfig, other.offlineConfig) && + Objects.equals(outboundCallFlows, other.outboundCallFlows) && + Objects.equals(pluginServiceAttributes, other.pluginServiceAttributes) && + Objects.equals(pluginServiceEnabled, other.pluginServiceEnabled) && + Objects.equals(publicAttributes, other.publicAttributes) && + Objects.equals(queueStatsConfiguration, other.queueStatsConfiguration) && + Objects.equals(runtimeDomain, other.runtimeDomain) && + Objects.equals(serverlessServiceSids, other.serverlessServiceSids) && + Objects.equals(serviceVersion, other.serviceVersion) && + Objects.equals(status, other.status) && + Objects.equals(taskrouterOfflineActivitySid, other.taskrouterOfflineActivitySid) && + Objects.equals(taskrouterSkills, other.taskrouterSkills) && + Objects.equals(taskrouterTargetTaskqueueSid, other.taskrouterTargetTaskqueueSid) && + Objects.equals(taskrouterTargetWorkflowSid, other.taskrouterTargetWorkflowSid) && + Objects.equals(taskrouterTaskqueues, other.taskrouterTaskqueues) && + Objects.equals(taskrouterWorkerAttributes, other.taskrouterWorkerAttributes) && + Objects.equals(taskrouterWorkerChannels, other.taskrouterWorkerChannels) && + Objects.equals(taskrouterWorkspaceSid, other.taskrouterWorkspaceSid) && + Objects.equals(uiAttributes, other.uiAttributes) && + Objects.equals(uiDependencies, other.uiDependencies) && + Objects.equals(uiLanguage, other.uiLanguage) && + Objects.equals(uiVersion, other.uiVersion) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - accountSid, - dateCreated, - dateUpdated, - attributes, - status, - taskrouterWorkspaceSid, - taskrouterTargetWorkflowSid, - taskrouterTargetTaskqueueSid, - taskrouterTaskqueues, - taskrouterSkills, - taskrouterWorkerChannels, - taskrouterWorkerAttributes, - taskrouterOfflineActivitySid, - runtimeDomain, - messagingServiceInstanceSid, - chatServiceInstanceSid, - flexServiceInstanceSid, - flexInstanceSid, - uiLanguage, - uiAttributes, - uiDependencies, - uiVersion, - serviceVersion, - callRecordingEnabled, - callRecordingWebhookUrl, - crmEnabled, - crmType, - crmCallbackUrl, - crmFallbackUrl, - crmAttributes, - publicAttributes, - pluginServiceEnabled, - pluginServiceAttributes, - integrations, - outboundCallFlows, - serverlessServiceSids, - queueStatsConfiguration, - notifications, - markdown, - url, - flexInsightsHr, - flexInsightsDrilldown, - flexUrl, - channelConfigs, - debuggerIntegration, - flexUiStatusReport, - agentConvEndMethods, - citrixVoiceVdi, - offlineConfig + accountSid, + agentConvEndMethods, + attributes, + callRecordingEnabled, + callRecordingWebhookUrl, + channelConfigs, + chatServiceInstanceSid, + citrixVoiceVdi, + crmAttributes, + crmCallbackUrl, + crmEnabled, + crmFallbackUrl, + crmType, + dateCreated, + dateUpdated, + debuggerIntegration, + flexInsightsDrilldown, + flexInsightsHr, + flexInstanceSid, + flexServiceInstanceSid, + flexUiStatusReport, + flexUrl, + integrations, + markdown, + messagingServiceInstanceSid, + notifications, + offlineConfig, + outboundCallFlows, + pluginServiceAttributes, + pluginServiceEnabled, + publicAttributes, + queueStatsConfiguration, + runtimeDomain, + serverlessServiceSids, + serviceVersion, + status, + taskrouterOfflineActivitySid, + taskrouterSkills, + taskrouterTargetTaskqueueSid, + taskrouterTargetWorkflowSid, + taskrouterTaskqueues, + taskrouterWorkerAttributes, + taskrouterWorkerChannels, + taskrouterWorkspaceSid, + uiAttributes, + uiDependencies, + uiLanguage, + uiVersion, + url ); } - public enum Status { - OK("ok"), - INPROGRESS("inprogress"), - NOTSTARTED("notstarted"); - - private final String value; - - private Status(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - @JsonCreator - public static Status forValue(final String value) { - return Promoter.enumFromString(value, Status.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/flexapi/v1/ConfigurationFetcher.java b/src/main/java/com/twilio/rest/flexapi/v1/ConfigurationFetcher.java index 1dadb0e060..737c6ea488 100644 --- a/src/main/java/com/twilio/rest/flexapi/v1/ConfigurationFetcher.java +++ b/src/main/java/com/twilio/rest/flexapi/v1/ConfigurationFetcher.java @@ -15,7 +15,8 @@ package com.twilio.rest.flexapi.v1; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,53 +30,53 @@ public class ConfigurationFetcher extends Fetcher { private String uiVersion; - public ConfigurationFetcher() {} + public ConfigurationFetcher() { + } + public ConfigurationFetcher setUiVersion(final String uiVersion) { this.uiVersion = uiVersion; return this; } + @Override public Configuration fetch(final TwilioRestClient client) { + String path = "/v1/Configuration"; + Request request = new Request( - HttpMethod.GET, - Domains.FLEXAPI.toString(), - path + HttpMethod.GET, + Domains.FLEXAPI.toString(), + path ); addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Configuration fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Configuration fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return Configuration.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Configuration.fromJson(response.getStream(), client.getObjectMapper()); } private void addQueryParams(final Request request) { + + if (uiVersion != null) { - request.addQueryParam("UiVersion", uiVersion); + Serializer.toString(request, "UiVersion", uiVersion, ParameterType.QUERY); } + + } } diff --git a/src/main/java/com/twilio/rest/flexapi/v1/ConfigurationUpdater.java b/src/main/java/com/twilio/rest/flexapi/v1/ConfigurationUpdater.java index 713f78f99d..7aaa2c6622 100644 --- a/src/main/java/com/twilio/rest/flexapi/v1/ConfigurationUpdater.java +++ b/src/main/java/com/twilio/rest/flexapi/v1/ConfigurationUpdater.java @@ -27,50 +27,48 @@ import com.twilio.rest.Domains; public class ConfigurationUpdater extends Updater { - private Object body; - public ConfigurationUpdater() {} + public ConfigurationUpdater() { + } + public ConfigurationUpdater setBody(final Object body) { this.body = body; return this; } + @Override public Configuration update(final TwilioRestClient client) { + String path = "/v1/Configuration"; + Request request = new Request( - HttpMethod.POST, - Domains.FLEXAPI.toString(), - path + HttpMethod.POST, + Domains.FLEXAPI.toString(), + path ); request.setContentType(EnumConstants.ContentType.JSON); addPostParams(request, client); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Configuration update failed: Unable to connect to server" - ); + throw new ApiConnectionException("Configuration update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Configuration.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Configuration.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request, TwilioRestClient client) { diff --git a/src/main/java/com/twilio/rest/flexapi/v1/FlexFlow.java b/src/main/java/com/twilio/rest/flexapi/v1/FlexFlow.java index ecfe3be905..9ce309375c 100644 --- a/src/main/java/com/twilio/rest/flexapi/v1/FlexFlow.java +++ b/src/main/java/com/twilio/rest/flexapi/v1/FlexFlow.java @@ -18,64 +18,117 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; -import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class FlexFlow extends Resource { - private static final long serialVersionUID = 232454907869065L; - public static FlexFlowCreator creator( - final String friendlyName, - final String chatServiceSid, - final FlexFlow.ChannelType channelType - ) { - return new FlexFlowCreator(friendlyName, chatServiceSid, channelType); + public static FlexFlowCreator creator(final String friendlyName, final String chatServiceSid, final FlexFlow.ChannelType channelType) { + return new FlexFlowCreator( + friendlyName, chatServiceSid, channelType + ); } - public static FlexFlowDeleter deleter(final String pathSid) { - return new FlexFlowDeleter(pathSid); + + public static FlexFlowDeleter deleter(final String pathsid) { + return new FlexFlowDeleter( + pathsid + ); } - public static FlexFlowFetcher fetcher(final String pathSid) { - return new FlexFlowFetcher(pathSid); + + public static FlexFlowFetcher fetcher(final String pathsid) { + return new FlexFlowFetcher( + pathsid + ); } + public static FlexFlowReader reader() { - return new FlexFlowReader(); + return new FlexFlowReader( + + ); + } + + + public static FlexFlowUpdater updater(final String pathsid) { + return new FlexFlowUpdater( + pathsid + ); + } + + + public enum ChannelType { + WEB("web"), + SMS("sms"), + FACEBOOK("facebook"), + WHATSAPP("whatsapp"), + LINE("line"), + CUSTOM("custom"); + + private final String value; + + private ChannelType(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static ChannelType forValue(final String value) { + return Promoter.enumFromString(value, ChannelType.values()); + } } - public static FlexFlowUpdater updater(final String pathSid) { - return new FlexFlowUpdater(pathSid); + public enum IntegrationType { + STUDIO("studio"), + EXTERNAL("external"), + TASK("task"); + + private final String value; + + private IntegrationType(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static IntegrationType forValue(final String value) { + return Promoter.enumFromString(value, IntegrationType.values()); + } } + /** * Converts a JSON String into a FlexFlow object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return FlexFlow object represented by the provided JSON */ - public static FlexFlow fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static FlexFlow fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, FlexFlow.class); @@ -90,14 +143,11 @@ public static FlexFlow fromJson( * Converts a JSON InputStream into a FlexFlow object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return FlexFlow object represented by the provided JSON */ - public static FlexFlow fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static FlexFlow fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, FlexFlow.class); @@ -108,112 +158,83 @@ public static FlexFlow fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final ZonedDateTime dateCreated; - private final ZonedDateTime dateUpdated; - private final String sid; - private final String friendlyName; - private final String chatServiceSid; + @Getter private final FlexFlow.ChannelType channelType; + @Getter + private final String chatServiceSid; + @Getter private final String contactIdentity; + @Getter + private final ZonedDateTime dateCreated; + @Getter + private final ZonedDateTime dateUpdated; + @Getter private final Boolean enabled; + @Getter + private final String friendlyName; + @Getter + private final Object integration; + @Getter private final FlexFlow.IntegrationType integrationType; - private final Map integration; - private final Boolean longLived; + @Getter private final Boolean janitorEnabled; + @Getter + private final Boolean longLived; + @Getter + private final String sid; + @Getter private final URI url; @JsonCreator private FlexFlow( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("sid") final String sid, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("chat_service_sid") final String chatServiceSid, - @JsonProperty("channel_type") final FlexFlow.ChannelType channelType, - @JsonProperty("contact_identity") final String contactIdentity, - @JsonProperty("enabled") final Boolean enabled, - @JsonProperty( - "integration_type" - ) final FlexFlow.IntegrationType integrationType, - @JsonProperty("integration") final Map integration, - @JsonProperty("long_lived") final Boolean longLived, - @JsonProperty("janitor_enabled") final Boolean janitorEnabled, - @JsonProperty("url") final URI url + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("channel_type") final FlexFlow.ChannelType channelType, + @JsonProperty("chat_service_sid") final String chatServiceSid, + @JsonProperty("contact_identity") final String contactIdentity, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("enabled") final Boolean enabled, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("integration") final Object integration, + @JsonProperty("integration_type") final FlexFlow.IntegrationType integrationType, + @JsonProperty("janitor_enabled") final Boolean janitorEnabled, + @JsonProperty("long_lived") final Boolean longLived, + @JsonProperty("sid") final String sid, + @JsonProperty("url") final URI url ) { this.accountSid = accountSid; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); - this.sid = sid; - this.friendlyName = friendlyName; - this.chatServiceSid = chatServiceSid; this.channelType = channelType; + this.chatServiceSid = chatServiceSid; this.contactIdentity = contactIdentity; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.enabled = enabled; - this.integrationType = integrationType; + this.friendlyName = friendlyName; this.integration = integration; - this.longLived = longLived; + this.integrationType = integrationType; this.janitorEnabled = janitorEnabled; + this.longLived = longLived; + this.sid = sid; this.url = url; } - public final String getAccountSid() { - return this.accountSid; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final String getSid() { - return this.sid; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final String getChatServiceSid() { - return this.chatServiceSid; - } - - public final FlexFlow.ChannelType getChannelType() { - return this.channelType; - } - - public final String getContactIdentity() { - return this.contactIdentity; - } - - public final Boolean getEnabled() { - return this.enabled; - } - - public final FlexFlow.IntegrationType getIntegrationType() { - return this.integrationType; - } - - public final Map getIntegration() { - return this.integration; - } - - public final Boolean getLongLived() { - return this.longLived; - } - - public final Boolean getJanitorEnabled() { - return this.janitorEnabled; - } - - public final URI getUrl() { - return this.url; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -225,87 +246,44 @@ public boolean equals(final Object o) { } FlexFlow other = (FlexFlow) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(sid, other.sid) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(chatServiceSid, other.chatServiceSid) && - Objects.equals(channelType, other.channelType) && - Objects.equals(contactIdentity, other.contactIdentity) && - Objects.equals(enabled, other.enabled) && - Objects.equals(integrationType, other.integrationType) && - Objects.equals(integration, other.integration) && - Objects.equals(longLived, other.longLived) && - Objects.equals(janitorEnabled, other.janitorEnabled) && - Objects.equals(url, other.url) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(channelType, other.channelType) && + Objects.equals(chatServiceSid, other.chatServiceSid) && + Objects.equals(contactIdentity, other.contactIdentity) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(enabled, other.enabled) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(integration, other.integration) && + Objects.equals(integrationType, other.integrationType) && + Objects.equals(janitorEnabled, other.janitorEnabled) && + Objects.equals(longLived, other.longLived) && + Objects.equals(sid, other.sid) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - accountSid, - dateCreated, - dateUpdated, - sid, - friendlyName, - chatServiceSid, - channelType, - contactIdentity, - enabled, - integrationType, - integration, - longLived, - janitorEnabled, - url + accountSid, + channelType, + chatServiceSid, + contactIdentity, + dateCreated, + dateUpdated, + enabled, + friendlyName, + integration, + integrationType, + janitorEnabled, + longLived, + sid, + url ); } - public enum IntegrationType { - STUDIO("studio"), - EXTERNAL("external"), - TASK("task"); - - private final String value; - - private IntegrationType(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static IntegrationType forValue(final String value) { - return Promoter.enumFromString(value, IntegrationType.values()); - } - } - - public enum ChannelType { - WEB("web"), - SMS("sms"), - FACEBOOK("facebook"), - WHATSAPP("whatsapp"), - LINE("line"), - CUSTOM("custom"); - - private final String value; - - private ChannelType(final String value) { - this.value = value; - } - public String toString() { - return value; - } - - @JsonCreator - public static ChannelType forValue(final String value) { - return Promoter.enumFromString(value, ChannelType.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/flexapi/v1/FlexFlowCreator.java b/src/main/java/com/twilio/rest/flexapi/v1/FlexFlowCreator.java index 4e4e913cf3..a0667ad71f 100644 --- a/src/main/java/com/twilio/rest/flexapi/v1/FlexFlowCreator.java +++ b/src/main/java/com/twilio/rest/flexapi/v1/FlexFlowCreator.java @@ -14,9 +14,11 @@ package com.twilio.rest.flexapi.v1; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; -import com.twilio.converter.Promoter; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,7 +27,7 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -import java.net.URI; + import java.net.URI; public class FlexFlowCreator extends Creator { @@ -48,246 +50,233 @@ public class FlexFlowCreator extends Creator { private Boolean janitorEnabled; private Integer integrationRetryCount; - public FlexFlowCreator( - final String friendlyName, - final String chatServiceSid, - final FlexFlow.ChannelType channelType - ) { + public FlexFlowCreator(final String friendlyName, final String chatServiceSid, final FlexFlow.ChannelType channelType) { this.friendlyName = friendlyName; this.chatServiceSid = chatServiceSid; this.channelType = channelType; } + public FlexFlowCreator setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + public FlexFlowCreator setChatServiceSid(final String chatServiceSid) { this.chatServiceSid = chatServiceSid; return this; } - public FlexFlowCreator setChannelType( - final FlexFlow.ChannelType channelType - ) { + + public FlexFlowCreator setChannelType(final FlexFlow.ChannelType channelType) { this.channelType = channelType; return this; } + public FlexFlowCreator setContactIdentity(final String contactIdentity) { this.contactIdentity = contactIdentity; return this; } + public FlexFlowCreator setEnabled(final Boolean enabled) { this.enabled = enabled; return this; } - public FlexFlowCreator setIntegrationType( - final FlexFlow.IntegrationType integrationType - ) { + + public FlexFlowCreator setIntegrationType(final FlexFlow.IntegrationType integrationType) { this.integrationType = integrationType; return this; } - public FlexFlowCreator setIntegrationFlowSid( - final String integrationFlowSid - ) { + + public FlexFlowCreator setIntegrationFlowSid(final String integrationFlowSid) { this.integrationFlowSid = integrationFlowSid; return this; } + public FlexFlowCreator setIntegrationUrl(final URI integrationUrl) { this.integrationUrl = integrationUrl; return this; } - public FlexFlowCreator setIntegrationUrl(final String integrationUrl) { - return setIntegrationUrl(Promoter.uriFromString(integrationUrl)); - } - public FlexFlowCreator setIntegrationWorkspaceSid( - final String integrationWorkspaceSid - ) { + public FlexFlowCreator setIntegrationWorkspaceSid(final String integrationWorkspaceSid) { this.integrationWorkspaceSid = integrationWorkspaceSid; return this; } - public FlexFlowCreator setIntegrationWorkflowSid( - final String integrationWorkflowSid - ) { + + public FlexFlowCreator setIntegrationWorkflowSid(final String integrationWorkflowSid) { this.integrationWorkflowSid = integrationWorkflowSid; return this; } - public FlexFlowCreator setIntegrationChannel( - final String integrationChannel - ) { + + public FlexFlowCreator setIntegrationChannel(final String integrationChannel) { this.integrationChannel = integrationChannel; return this; } - public FlexFlowCreator setIntegrationTimeout( - final Integer integrationTimeout - ) { + + public FlexFlowCreator setIntegrationTimeout(final Integer integrationTimeout) { this.integrationTimeout = integrationTimeout; return this; } - public FlexFlowCreator setIntegrationPriority( - final Integer integrationPriority - ) { + + public FlexFlowCreator setIntegrationPriority(final Integer integrationPriority) { this.integrationPriority = integrationPriority; return this; } - public FlexFlowCreator setIntegrationCreationOnMessage( - final Boolean integrationCreationOnMessage - ) { + + public FlexFlowCreator setIntegrationCreationOnMessage(final Boolean integrationCreationOnMessage) { this.integrationCreationOnMessage = integrationCreationOnMessage; return this; } + public FlexFlowCreator setLongLived(final Boolean longLived) { this.longLived = longLived; return this; } + public FlexFlowCreator setJanitorEnabled(final Boolean janitorEnabled) { this.janitorEnabled = janitorEnabled; return this; } - public FlexFlowCreator setIntegrationRetryCount( - final Integer integrationRetryCount - ) { + + public FlexFlowCreator setIntegrationRetryCount(final Integer integrationRetryCount) { this.integrationRetryCount = integrationRetryCount; return this; } + @Override public FlexFlow create(final TwilioRestClient client) { + String path = "/v1/FlexFlows"; - path = - path.replace( - "{" + "FriendlyName" + "}", - this.friendlyName.toString() - ); - path = - path.replace( - "{" + "ChatServiceSid" + "}", - this.chatServiceSid.toString() - ); - path = - path.replace( - "{" + "ChannelType" + "}", - this.channelType.toString() - ); Request request = new Request( - HttpMethod.POST, - Domains.FLEXAPI.toString(), - path + HttpMethod.POST, + Domains.FLEXAPI.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "FlexFlow creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("FlexFlow creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return FlexFlow.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return FlexFlow.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + if (chatServiceSid != null) { - request.addPostParam("ChatServiceSid", chatServiceSid); + Serializer.toString(request, "ChatServiceSid", chatServiceSid, ParameterType.URLENCODED); } + + if (channelType != null) { - request.addPostParam("ChannelType", channelType.toString()); + Serializer.toString(request, "ChannelType", channelType, ParameterType.URLENCODED); } + + if (contactIdentity != null) { - request.addPostParam("ContactIdentity", contactIdentity); + Serializer.toString(request, "ContactIdentity", contactIdentity, ParameterType.URLENCODED); } + + if (enabled != null) { - request.addPostParam("Enabled", enabled.toString()); + Serializer.toString(request, "Enabled", enabled, ParameterType.URLENCODED); } + + if (integrationType != null) { - request.addPostParam("IntegrationType", integrationType.toString()); + Serializer.toString(request, "IntegrationType", integrationType, ParameterType.URLENCODED); } + + if (integrationFlowSid != null) { - request.addPostParam("Integration.FlowSid", integrationFlowSid); + Serializer.toString(request, "Integration.FlowSid", integrationFlowSid, ParameterType.URLENCODED); } + + if (integrationUrl != null) { - request.addPostParam("Integration.Url", integrationUrl.toString()); + Serializer.toString(request, "Integration.Url", integrationUrl, ParameterType.URLENCODED); } + + if (integrationWorkspaceSid != null) { - request.addPostParam( - "Integration.WorkspaceSid", - integrationWorkspaceSid - ); + Serializer.toString(request, "Integration.WorkspaceSid", integrationWorkspaceSid, ParameterType.URLENCODED); } + + if (integrationWorkflowSid != null) { - request.addPostParam( - "Integration.WorkflowSid", - integrationWorkflowSid - ); + Serializer.toString(request, "Integration.WorkflowSid", integrationWorkflowSid, ParameterType.URLENCODED); } + + if (integrationChannel != null) { - request.addPostParam("Integration.Channel", integrationChannel); + Serializer.toString(request, "Integration.Channel", integrationChannel, ParameterType.URLENCODED); } + + if (integrationTimeout != null) { - request.addPostParam( - "Integration.Timeout", - integrationTimeout.toString() - ); + Serializer.toString(request, "Integration.Timeout", integrationTimeout, ParameterType.URLENCODED); } + + if (integrationPriority != null) { - request.addPostParam( - "Integration.Priority", - integrationPriority.toString() - ); + Serializer.toString(request, "Integration.Priority", integrationPriority, ParameterType.URLENCODED); } + + if (integrationCreationOnMessage != null) { - request.addPostParam( - "Integration.CreationOnMessage", - integrationCreationOnMessage.toString() - ); + Serializer.toString(request, "Integration.CreationOnMessage", integrationCreationOnMessage, ParameterType.URLENCODED); } + + if (longLived != null) { - request.addPostParam("LongLived", longLived.toString()); + Serializer.toString(request, "LongLived", longLived, ParameterType.URLENCODED); } + + if (janitorEnabled != null) { - request.addPostParam("JanitorEnabled", janitorEnabled.toString()); + Serializer.toString(request, "JanitorEnabled", janitorEnabled, ParameterType.URLENCODED); } + + if (integrationRetryCount != null) { - request.addPostParam( - "Integration.RetryCount", - integrationRetryCount.toString() - ); + Serializer.toString(request, "Integration.RetryCount", integrationRetryCount, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/flexapi/v1/FlexFlowDeleter.java b/src/main/java/com/twilio/rest/flexapi/v1/FlexFlowDeleter.java index 25a4d95217..d62badc6ed 100644 --- a/src/main/java/com/twilio/rest/flexapi/v1/FlexFlowDeleter.java +++ b/src/main/java/com/twilio/rest/flexapi/v1/FlexFlowDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.flexapi.v1; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,40 +26,38 @@ public class FlexFlowDeleter extends Deleter { - private String pathSid; + private String pathsid; - public FlexFlowDeleter(final String pathSid) { - this.pathSid = pathSid; + public FlexFlowDeleter(final String pathsid) { + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/v1/FlexFlows/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.FLEXAPI.toString(), - path + HttpMethod.DELETE, + Domains.FLEXAPI.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "FlexFlow delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("FlexFlow delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/flexapi/v1/FlexFlowFetcher.java b/src/main/java/com/twilio/rest/flexapi/v1/FlexFlowFetcher.java index e4d3a9246e..e8d8e59365 100644 --- a/src/main/java/com/twilio/rest/flexapi/v1/FlexFlowFetcher.java +++ b/src/main/java/com/twilio/rest/flexapi/v1/FlexFlowFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.flexapi.v1; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,47 +26,41 @@ public class FlexFlowFetcher extends Fetcher { - private String pathSid; + private String pathsid; - public FlexFlowFetcher(final String pathSid) { - this.pathSid = pathSid; + public FlexFlowFetcher(final String pathsid) { + this.pathsid = pathsid; } + @Override public FlexFlow fetch(final TwilioRestClient client) { + String path = "/v1/FlexFlows/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.FLEXAPI.toString(), - path + HttpMethod.GET, + Domains.FLEXAPI.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "FlexFlow fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("FlexFlow fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return FlexFlow.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return FlexFlow.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/flexapi/v1/FlexFlowReader.java b/src/main/java/com/twilio/rest/flexapi/v1/FlexFlowReader.java index 3eac0f5293..2860bf4842 100644 --- a/src/main/java/com/twilio/rest/flexapi/v1/FlexFlowReader.java +++ b/src/main/java/com/twilio/rest/flexapi/v1/FlexFlowReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -32,113 +33,94 @@ public class FlexFlowReader extends Reader { private String friendlyName; private Long pageSize; - public FlexFlowReader() {} + public FlexFlowReader() { + } + public FlexFlowReader setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + public FlexFlowReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/FlexFlows"; + Request request = new Request( - HttpMethod.GET, - Domains.FLEXAPI.toString(), - path + HttpMethod.GET, + Domains.FLEXAPI.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "FlexFlow read failed: Unable to connect to server" - ); + throw new ApiConnectionException("FlexFlow read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "flex_flows", - response.getContent(), - FlexFlow.class, - client.getObjectMapper() - ); + "flex_flows", + response.getContent(), + FlexFlow.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.FLEXAPI.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.FLEXAPI.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (friendlyName != null) { - request.addQueryParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.QUERY); } + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/flexapi/v1/FlexFlowUpdater.java b/src/main/java/com/twilio/rest/flexapi/v1/FlexFlowUpdater.java index 41ebcd2e52..3c760ccefe 100644 --- a/src/main/java/com/twilio/rest/flexapi/v1/FlexFlowUpdater.java +++ b/src/main/java/com/twilio/rest/flexapi/v1/FlexFlowUpdater.java @@ -16,7 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; -import com.twilio.converter.Promoter; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,11 +26,11 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.net.URI; public class FlexFlowUpdater extends Updater { - - private String pathSid; + private String pathsid; private String friendlyName; private String chatServiceSid; private FlexFlow.ChannelType channelType; @@ -48,226 +49,233 @@ public class FlexFlowUpdater extends Updater { private Boolean janitorEnabled; private Integer integrationRetryCount; - public FlexFlowUpdater(final String pathSid) { - this.pathSid = pathSid; + public FlexFlowUpdater(final String pathsid) { + this.pathsid = pathsid; } + public FlexFlowUpdater setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + public FlexFlowUpdater setChatServiceSid(final String chatServiceSid) { this.chatServiceSid = chatServiceSid; return this; } - public FlexFlowUpdater setChannelType( - final FlexFlow.ChannelType channelType - ) { + + public FlexFlowUpdater setChannelType(final FlexFlow.ChannelType channelType) { this.channelType = channelType; return this; } + public FlexFlowUpdater setContactIdentity(final String contactIdentity) { this.contactIdentity = contactIdentity; return this; } + public FlexFlowUpdater setEnabled(final Boolean enabled) { this.enabled = enabled; return this; } - public FlexFlowUpdater setIntegrationType( - final FlexFlow.IntegrationType integrationType - ) { + + public FlexFlowUpdater setIntegrationType(final FlexFlow.IntegrationType integrationType) { this.integrationType = integrationType; return this; } - public FlexFlowUpdater setIntegrationFlowSid( - final String integrationFlowSid - ) { + + public FlexFlowUpdater setIntegrationFlowSid(final String integrationFlowSid) { this.integrationFlowSid = integrationFlowSid; return this; } + public FlexFlowUpdater setIntegrationUrl(final URI integrationUrl) { this.integrationUrl = integrationUrl; return this; } - public FlexFlowUpdater setIntegrationUrl(final String integrationUrl) { - return setIntegrationUrl(Promoter.uriFromString(integrationUrl)); - } - public FlexFlowUpdater setIntegrationWorkspaceSid( - final String integrationWorkspaceSid - ) { + public FlexFlowUpdater setIntegrationWorkspaceSid(final String integrationWorkspaceSid) { this.integrationWorkspaceSid = integrationWorkspaceSid; return this; } - public FlexFlowUpdater setIntegrationWorkflowSid( - final String integrationWorkflowSid - ) { + + public FlexFlowUpdater setIntegrationWorkflowSid(final String integrationWorkflowSid) { this.integrationWorkflowSid = integrationWorkflowSid; return this; } - public FlexFlowUpdater setIntegrationChannel( - final String integrationChannel - ) { + + public FlexFlowUpdater setIntegrationChannel(final String integrationChannel) { this.integrationChannel = integrationChannel; return this; } - public FlexFlowUpdater setIntegrationTimeout( - final Integer integrationTimeout - ) { + + public FlexFlowUpdater setIntegrationTimeout(final Integer integrationTimeout) { this.integrationTimeout = integrationTimeout; return this; } - public FlexFlowUpdater setIntegrationPriority( - final Integer integrationPriority - ) { + + public FlexFlowUpdater setIntegrationPriority(final Integer integrationPriority) { this.integrationPriority = integrationPriority; return this; } - public FlexFlowUpdater setIntegrationCreationOnMessage( - final Boolean integrationCreationOnMessage - ) { + + public FlexFlowUpdater setIntegrationCreationOnMessage(final Boolean integrationCreationOnMessage) { this.integrationCreationOnMessage = integrationCreationOnMessage; return this; } + public FlexFlowUpdater setLongLived(final Boolean longLived) { this.longLived = longLived; return this; } + public FlexFlowUpdater setJanitorEnabled(final Boolean janitorEnabled) { this.janitorEnabled = janitorEnabled; return this; } - public FlexFlowUpdater setIntegrationRetryCount( - final Integer integrationRetryCount - ) { + + public FlexFlowUpdater setIntegrationRetryCount(final Integer integrationRetryCount) { this.integrationRetryCount = integrationRetryCount; return this; } + @Override public FlexFlow update(final TwilioRestClient client) { + String path = "/v1/FlexFlows/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.FLEXAPI.toString(), - path + HttpMethod.POST, + Domains.FLEXAPI.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "FlexFlow update failed: Unable to connect to server" - ); + throw new ApiConnectionException("FlexFlow update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return FlexFlow.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return FlexFlow.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + if (chatServiceSid != null) { - request.addPostParam("ChatServiceSid", chatServiceSid); + Serializer.toString(request, "ChatServiceSid", chatServiceSid, ParameterType.URLENCODED); } + + if (channelType != null) { - request.addPostParam("ChannelType", channelType.toString()); + Serializer.toString(request, "ChannelType", channelType, ParameterType.URLENCODED); } + + if (contactIdentity != null) { - request.addPostParam("ContactIdentity", contactIdentity); + Serializer.toString(request, "ContactIdentity", contactIdentity, ParameterType.URLENCODED); } + + if (enabled != null) { - request.addPostParam("Enabled", enabled.toString()); + Serializer.toString(request, "Enabled", enabled, ParameterType.URLENCODED); } + + if (integrationType != null) { - request.addPostParam("IntegrationType", integrationType.toString()); + Serializer.toString(request, "IntegrationType", integrationType, ParameterType.URLENCODED); } + + if (integrationFlowSid != null) { - request.addPostParam("Integration.FlowSid", integrationFlowSid); + Serializer.toString(request, "Integration.FlowSid", integrationFlowSid, ParameterType.URLENCODED); } + + if (integrationUrl != null) { - request.addPostParam("Integration.Url", integrationUrl.toString()); + Serializer.toString(request, "Integration.Url", integrationUrl, ParameterType.URLENCODED); } + + if (integrationWorkspaceSid != null) { - request.addPostParam( - "Integration.WorkspaceSid", - integrationWorkspaceSid - ); + Serializer.toString(request, "Integration.WorkspaceSid", integrationWorkspaceSid, ParameterType.URLENCODED); } + + if (integrationWorkflowSid != null) { - request.addPostParam( - "Integration.WorkflowSid", - integrationWorkflowSid - ); + Serializer.toString(request, "Integration.WorkflowSid", integrationWorkflowSid, ParameterType.URLENCODED); } + + if (integrationChannel != null) { - request.addPostParam("Integration.Channel", integrationChannel); + Serializer.toString(request, "Integration.Channel", integrationChannel, ParameterType.URLENCODED); } + + if (integrationTimeout != null) { - request.addPostParam( - "Integration.Timeout", - integrationTimeout.toString() - ); + Serializer.toString(request, "Integration.Timeout", integrationTimeout, ParameterType.URLENCODED); } + + if (integrationPriority != null) { - request.addPostParam( - "Integration.Priority", - integrationPriority.toString() - ); + Serializer.toString(request, "Integration.Priority", integrationPriority, ParameterType.URLENCODED); } + + if (integrationCreationOnMessage != null) { - request.addPostParam( - "Integration.CreationOnMessage", - integrationCreationOnMessage.toString() - ); + Serializer.toString(request, "Integration.CreationOnMessage", integrationCreationOnMessage, ParameterType.URLENCODED); } + + if (longLived != null) { - request.addPostParam("LongLived", longLived.toString()); + Serializer.toString(request, "LongLived", longLived, ParameterType.URLENCODED); } + + if (janitorEnabled != null) { - request.addPostParam("JanitorEnabled", janitorEnabled.toString()); + Serializer.toString(request, "JanitorEnabled", janitorEnabled, ParameterType.URLENCODED); } + + if (integrationRetryCount != null) { - request.addPostParam( - "Integration.RetryCount", - integrationRetryCount.toString() - ); + Serializer.toString(request, "Integration.RetryCount", integrationRetryCount, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/flexapi/v1/InsightsAssessmentsComment.java b/src/main/java/com/twilio/rest/flexapi/v1/InsightsAssessmentsComment.java index d895b3d0e4..1ccc696d04 100644 --- a/src/main/java/com/twilio/rest/flexapi/v1/InsightsAssessmentsComment.java +++ b/src/main/java/com/twilio/rest/flexapi/v1/InsightsAssessmentsComment.java @@ -18,66 +18,51 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.math.BigDecimal; import java.net.URI; -import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class InsightsAssessmentsComment extends Resource { - private static final long serialVersionUID = 119423741777853L; - public static InsightsAssessmentsCommentCreator creator( - final String categoryId, - final String categoryName, - final String comment, - final String segmentId, - final String agentId, - final BigDecimal offset - ) { + public static InsightsAssessmentsCommentCreator creator(final String categoryId, final String categoryName, final String comment, final String segmentId, final String agentId, final BigDecimal offset) { return new InsightsAssessmentsCommentCreator( - categoryId, - categoryName, - comment, - segmentId, - agentId, - offset + categoryId, categoryName, comment, segmentId, agentId, offset ); } + public static InsightsAssessmentsCommentReader reader() { - return new InsightsAssessmentsCommentReader(); + return new InsightsAssessmentsCommentReader( + + ); } + /** * Converts a JSON String into a InsightsAssessmentsComment object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return InsightsAssessmentsComment object represented by the provided JSON */ - public static InsightsAssessmentsComment fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static InsightsAssessmentsComment fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { - return objectMapper.readValue( - json, - InsightsAssessmentsComment.class - ); + return objectMapper.readValue(json, InsightsAssessmentsComment.class); } catch (final JsonMappingException | JsonParseException e) { throw new ApiException(e.getMessage(), e); } catch (final IOException e) { @@ -89,20 +74,14 @@ public static InsightsAssessmentsComment fromJson( * Converts a JSON InputStream into a InsightsAssessmentsComment object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return InsightsAssessmentsComment object represented by the provided JSON */ - public static InsightsAssessmentsComment fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static InsightsAssessmentsComment fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { - return objectMapper.readValue( - json, - InsightsAssessmentsComment.class - ); + return objectMapper.readValue(json, InsightsAssessmentsComment.class); } catch (final JsonMappingException | JsonParseException e) { throw new ApiException(e.getMessage(), e); } catch (final IOException e) { @@ -110,94 +89,71 @@ public static InsightsAssessmentsComment fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; + @Getter + private final String agentId; + @Getter private final String assessmentSid; - private final Map comment; + @Getter + private final Object comment; + @Getter private final String offset; + @Getter private final Boolean report; - private final String weight; - private final String agentId; + @Getter private final String segmentId; - private final String userName; - private final String userEmail; + @Getter private final String timestamp; + @Getter private final URI url; + @Getter + private final String userEmail; + @Getter + private final String userName; + @Getter + private final String weight; @JsonCreator private InsightsAssessmentsComment( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("assessment_sid") final String assessmentSid, - @JsonProperty("comment") final Map comment, - @JsonProperty("offset") final String offset, - @JsonProperty("report") final Boolean report, - @JsonProperty("weight") final String weight, - @JsonProperty("agent_id") final String agentId, - @JsonProperty("segment_id") final String segmentId, - @JsonProperty("user_name") final String userName, - @JsonProperty("user_email") final String userEmail, - @JsonProperty("timestamp") final String timestamp, - @JsonProperty("url") final URI url + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("agent_id") final String agentId, + @JsonProperty("assessment_sid") final String assessmentSid, + @JsonProperty("comment") final Object comment, + @JsonProperty("offset") final String offset, + @JsonProperty("report") final Boolean report, + @JsonProperty("segment_id") final String segmentId, + @JsonProperty("timestamp") final String timestamp, + @JsonProperty("url") final URI url, + @JsonProperty("user_email") final String userEmail, + @JsonProperty("user_name") final String userName, + @JsonProperty("weight") final String weight ) { this.accountSid = accountSid; + this.agentId = agentId; this.assessmentSid = assessmentSid; this.comment = comment; this.offset = offset; this.report = report; - this.weight = weight; - this.agentId = agentId; this.segmentId = segmentId; - this.userName = userName; - this.userEmail = userEmail; this.timestamp = timestamp; this.url = url; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getAssessmentSid() { - return this.assessmentSid; - } - - public final Map getComment() { - return this.comment; - } - - public final String getOffset() { - return this.offset; - } - - public final Boolean getReport() { - return this.report; - } - - public final String getWeight() { - return this.weight; - } - - public final String getAgentId() { - return this.agentId; - } - - public final String getSegmentId() { - return this.segmentId; - } - - public final String getUserName() { - return this.userName; - } - - public final String getUserEmail() { - return this.userEmail; - } - - public final String getTimestamp() { - return this.timestamp; - } - - public final URI getUrl() { - return this.url; + this.userEmail = userEmail; + this.userName = userName; + this.weight = weight; } @Override @@ -211,38 +167,40 @@ public boolean equals(final Object o) { } InsightsAssessmentsComment other = (InsightsAssessmentsComment) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(assessmentSid, other.assessmentSid) && - Objects.equals(comment, other.comment) && - Objects.equals(offset, other.offset) && - Objects.equals(report, other.report) && - Objects.equals(weight, other.weight) && - Objects.equals(agentId, other.agentId) && - Objects.equals(segmentId, other.segmentId) && - Objects.equals(userName, other.userName) && - Objects.equals(userEmail, other.userEmail) && - Objects.equals(timestamp, other.timestamp) && - Objects.equals(url, other.url) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(agentId, other.agentId) && + Objects.equals(assessmentSid, other.assessmentSid) && + Objects.equals(comment, other.comment) && + Objects.equals(offset, other.offset) && + Objects.equals(report, other.report) && + Objects.equals(segmentId, other.segmentId) && + Objects.equals(timestamp, other.timestamp) && + Objects.equals(url, other.url) && + Objects.equals(userEmail, other.userEmail) && + Objects.equals(userName, other.userName) && + Objects.equals(weight, other.weight) ); } @Override public int hashCode() { return Objects.hash( - accountSid, - assessmentSid, - comment, - offset, - report, - weight, - agentId, - segmentId, - userName, - userEmail, - timestamp, - url + accountSid, + agentId, + assessmentSid, + comment, + offset, + report, + segmentId, + timestamp, + url, + userEmail, + userName, + weight ); } + + } + diff --git a/src/main/java/com/twilio/rest/flexapi/v1/InsightsAssessmentsCommentCreator.java b/src/main/java/com/twilio/rest/flexapi/v1/InsightsAssessmentsCommentCreator.java index cd5c765d18..129d8834d4 100644 --- a/src/main/java/com/twilio/rest/flexapi/v1/InsightsAssessmentsCommentCreator.java +++ b/src/main/java/com/twilio/rest/flexapi/v1/InsightsAssessmentsCommentCreator.java @@ -14,8 +14,11 @@ package com.twilio.rest.flexapi.v1; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -24,28 +27,20 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -import java.math.BigDecimal; + import java.math.BigDecimal; -public class InsightsAssessmentsCommentCreator - extends Creator { +public class InsightsAssessmentsCommentCreator extends Creator { + private String authorization; private String categoryId; private String categoryName; private String comment; private String segmentId; private String agentId; private BigDecimal offset; - private String authorization; - public InsightsAssessmentsCommentCreator( - final String categoryId, - final String categoryName, - final String comment, - final String segmentId, - final String agentId, - final BigDecimal offset - ) { + public InsightsAssessmentsCommentCreator(final String categoryId, final String categoryName, final String comment, final String segmentId, final String agentId, final BigDecimal offset) { this.categoryId = categoryId; this.categoryName = categoryName; this.comment = comment; @@ -54,124 +49,121 @@ public InsightsAssessmentsCommentCreator( this.offset = offset; } - public InsightsAssessmentsCommentCreator setCategoryId( - final String categoryId - ) { + + public InsightsAssessmentsCommentCreator setCategoryId(final String categoryId) { this.categoryId = categoryId; return this; } - public InsightsAssessmentsCommentCreator setCategoryName( - final String categoryName - ) { + + public InsightsAssessmentsCommentCreator setCategoryName(final String categoryName) { this.categoryName = categoryName; return this; } + public InsightsAssessmentsCommentCreator setComment(final String comment) { this.comment = comment; return this; } - public InsightsAssessmentsCommentCreator setSegmentId( - final String segmentId - ) { + + public InsightsAssessmentsCommentCreator setSegmentId(final String segmentId) { this.segmentId = segmentId; return this; } + public InsightsAssessmentsCommentCreator setAgentId(final String agentId) { this.agentId = agentId; return this; } - public InsightsAssessmentsCommentCreator setOffset( - final BigDecimal offset - ) { + + public InsightsAssessmentsCommentCreator setOffset(final BigDecimal offset) { this.offset = offset; return this; } - public InsightsAssessmentsCommentCreator setAuthorization( - final String authorization - ) { + + public InsightsAssessmentsCommentCreator setAuthorization(final String authorization) { this.authorization = authorization; return this; } + @Override public InsightsAssessmentsComment create(final TwilioRestClient client) { + String path = "/v1/Insights/QualityManagement/Assessments/Comments"; - path = - path.replace("{" + "CategoryId" + "}", this.categoryId.toString()); - path = - path.replace( - "{" + "CategoryName" + "}", - this.categoryName.toString() - ); - path = path.replace("{" + "Comment" + "}", this.comment.toString()); - path = path.replace("{" + "SegmentId" + "}", this.segmentId.toString()); - path = path.replace("{" + "AgentId" + "}", this.agentId.toString()); - path = path.replace("{" + "Offset" + "}", this.offset.toString()); Request request = new Request( - HttpMethod.POST, - Domains.FLEXAPI.toString(), - path + HttpMethod.POST, + Domains.FLEXAPI.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); - addPostParams(request); addHeaderParams(request); + addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "InsightsAssessmentsComment creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("InsightsAssessmentsComment creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return InsightsAssessmentsComment.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return InsightsAssessmentsComment.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (categoryId != null) { - request.addPostParam("CategoryId", categoryId); + Serializer.toString(request, "CategoryId", categoryId, ParameterType.URLENCODED); } + + if (categoryName != null) { - request.addPostParam("CategoryName", categoryName); + Serializer.toString(request, "CategoryName", categoryName, ParameterType.URLENCODED); } + + if (comment != null) { - request.addPostParam("Comment", comment); + Serializer.toString(request, "Comment", comment, ParameterType.URLENCODED); } + + if (segmentId != null) { - request.addPostParam("SegmentId", segmentId); + Serializer.toString(request, "SegmentId", segmentId, ParameterType.URLENCODED); } + + if (agentId != null) { - request.addPostParam("AgentId", agentId); + Serializer.toString(request, "AgentId", agentId, ParameterType.URLENCODED); } + + if (offset != null) { - request.addPostParam("Offset", offset.toString()); + Serializer.toString(request, "Offset", offset, ParameterType.URLENCODED); } + + } private void addHeaderParams(final Request request) { + if (authorization != null) { - request.addHeaderParam("Authorization", authorization); + Serializer.toString(request, "Authorization", authorization, ParameterType.HEADER); } + } } diff --git a/src/main/java/com/twilio/rest/flexapi/v1/InsightsAssessmentsCommentReader.java b/src/main/java/com/twilio/rest/flexapi/v1/InsightsAssessmentsCommentReader.java index 8768aed813..07ece87a8e 100644 --- a/src/main/java/com/twilio/rest/flexapi/v1/InsightsAssessmentsCommentReader.java +++ b/src/main/java/com/twilio/rest/flexapi/v1/InsightsAssessmentsCommentReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,149 +28,127 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class InsightsAssessmentsCommentReader - extends Reader { +public class InsightsAssessmentsCommentReader extends Reader { - private String authorization; private String segmentId; private String agentId; private Long pageSize; + private String authorization; - public InsightsAssessmentsCommentReader() {} - - public InsightsAssessmentsCommentReader setAuthorization( - final String authorization - ) { - this.authorization = authorization; - return this; + public InsightsAssessmentsCommentReader() { } - public InsightsAssessmentsCommentReader setSegmentId( - final String segmentId - ) { + + public InsightsAssessmentsCommentReader setSegmentId(final String segmentId) { this.segmentId = segmentId; return this; } + public InsightsAssessmentsCommentReader setAgentId(final String agentId) { this.agentId = agentId; return this; } + public InsightsAssessmentsCommentReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + + public InsightsAssessmentsCommentReader setAuthorization(final String authorization) { + this.authorization = authorization; + return this; + } + + @Override - public ResourceSet read( - final TwilioRestClient client - ) { + public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } - public Page firstPage( - final TwilioRestClient client - ) { + public Page firstPage(final TwilioRestClient client) { + String path = "/v1/Insights/QualityManagement/Assessments/Comments"; + Request request = new Request( - HttpMethod.GET, - Domains.FLEXAPI.toString(), - path + HttpMethod.GET, + Domains.FLEXAPI.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addHeaderParams(request); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "InsightsAssessmentsComment read failed: Unable to connect to server" - ); + throw new ApiConnectionException("InsightsAssessmentsComment read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "comments", - response.getContent(), - InsightsAssessmentsComment.class, - client.getObjectMapper() - ); + "comments", + response.getContent(), + InsightsAssessmentsComment.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.FLEXAPI.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.FLEXAPI.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } - private void addHeaderParams(final Request request) { - if (authorization != null) { - request.addHeaderParam("Authorization", authorization); - } - } - private void addQueryParams(final Request request) { + + if (segmentId != null) { - request.addQueryParam("SegmentId", segmentId); + Serializer.toString(request, "SegmentId", segmentId, ParameterType.QUERY); } + + if (agentId != null) { - request.addQueryParam("AgentId", agentId); + Serializer.toString(request, "AgentId", agentId, ParameterType.QUERY); } + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); + + } + + private void addHeaderParams(final Request request) { + + if (authorization != null) { + Serializer.toString(request, "Authorization", authorization, ParameterType.HEADER); } + } } diff --git a/src/main/java/com/twilio/rest/flexapi/v1/InsightsConversations.java b/src/main/java/com/twilio/rest/flexapi/v1/InsightsConversations.java index e458cfafe9..ed0b532cc3 100644 --- a/src/main/java/com/twilio/rest/flexapi/v1/InsightsConversations.java +++ b/src/main/java/com/twilio/rest/flexapi/v1/InsightsConversations.java @@ -18,41 +18,40 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.util.List; -import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class InsightsConversations extends Resource { - private static final long serialVersionUID = 172863414006149L; public static InsightsConversationsReader reader() { - return new InsightsConversationsReader(); + return new InsightsConversationsReader( + + ); } + /** * Converts a JSON String into a InsightsConversations object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return InsightsConversations object represented by the provided JSON */ - public static InsightsConversations fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static InsightsConversations fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, InsightsConversations.class); @@ -67,14 +66,11 @@ public static InsightsConversations fromJson( * Converts a JSON InputStream into a InsightsConversations object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return InsightsConversations object represented by the provided JSON */ - public static InsightsConversations fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static InsightsConversations fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, InsightsConversations.class); @@ -85,17 +81,34 @@ public static InsightsConversations fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountId; + @Getter private final String conversationId; + @Getter private final Integer segmentCount; - private final List> segments; + @Getter + private final List segments; @JsonCreator private InsightsConversations( - @JsonProperty("account_id") final String accountId, - @JsonProperty("conversation_id") final String conversationId, - @JsonProperty("segment_count") final Integer segmentCount, - @JsonProperty("segments") final List> segments + @JsonProperty("account_id") final String accountId, + @JsonProperty("conversation_id") final String conversationId, + @JsonProperty("segment_count") final Integer segmentCount, + @JsonProperty("segments") final List segments ) { this.accountId = accountId; this.conversationId = conversationId; @@ -103,22 +116,6 @@ private InsightsConversations( this.segments = segments; } - public final String getAccountId() { - return this.accountId; - } - - public final String getConversationId() { - return this.conversationId; - } - - public final Integer getSegmentCount() { - return this.segmentCount; - } - - public final List> getSegments() { - return this.segments; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -130,17 +127,24 @@ public boolean equals(final Object o) { } InsightsConversations other = (InsightsConversations) o; - return ( - Objects.equals(accountId, other.accountId) && - Objects.equals(conversationId, other.conversationId) && - Objects.equals(segmentCount, other.segmentCount) && - Objects.equals(segments, other.segments) + Objects.equals(accountId, other.accountId) && + Objects.equals(conversationId, other.conversationId) && + Objects.equals(segmentCount, other.segmentCount) && + Objects.equals(segments, other.segments) ); } @Override public int hashCode() { - return Objects.hash(accountId, conversationId, segmentCount, segments); + return Objects.hash( + accountId, + conversationId, + segmentCount, + segments + ); } + + } + diff --git a/src/main/java/com/twilio/rest/flexapi/v1/InsightsConversationsReader.java b/src/main/java/com/twilio/rest/flexapi/v1/InsightsConversationsReader.java index 2828680dcf..4c10511c8e 100644 --- a/src/main/java/com/twilio/rest/flexapi/v1/InsightsConversationsReader.java +++ b/src/main/java/com/twilio/rest/flexapi/v1/InsightsConversationsReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,135 +30,113 @@ public class InsightsConversationsReader extends Reader { - private String authorization; private String segmentId; private Long pageSize; + private String authorization; - public InsightsConversationsReader() {} - - public InsightsConversationsReader setAuthorization( - final String authorization - ) { - this.authorization = authorization; - return this; + public InsightsConversationsReader() { } + public InsightsConversationsReader setSegmentId(final String segmentId) { this.segmentId = segmentId; return this; } + public InsightsConversationsReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + + public InsightsConversationsReader setAuthorization(final String authorization) { + this.authorization = authorization; + return this; + } + + @Override - public ResourceSet read( - final TwilioRestClient client - ) { + public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } - public Page firstPage( - final TwilioRestClient client - ) { + public Page firstPage(final TwilioRestClient client) { + String path = "/v1/Insights/Conversations"; + Request request = new Request( - HttpMethod.GET, - Domains.FLEXAPI.toString(), - path + HttpMethod.GET, + Domains.FLEXAPI.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addHeaderParams(request); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "InsightsConversations read failed: Unable to connect to server" - ); + throw new ApiConnectionException("InsightsConversations read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "conversations", - response.getContent(), - InsightsConversations.class, - client.getObjectMapper() - ); + "conversations", + response.getContent(), + InsightsConversations.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.FLEXAPI.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.FLEXAPI.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } - private void addHeaderParams(final Request request) { - if (authorization != null) { - request.addHeaderParam("Authorization", authorization); - } - } - private void addQueryParams(final Request request) { + + if (segmentId != null) { - request.addQueryParam("SegmentId", segmentId); + Serializer.toString(request, "SegmentId", segmentId, ParameterType.QUERY); } + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); + + } + + private void addHeaderParams(final Request request) { + + if (authorization != null) { + Serializer.toString(request, "Authorization", authorization, ParameterType.HEADER); } + } } diff --git a/src/main/java/com/twilio/rest/flexapi/v1/InsightsQuestionnaires.java b/src/main/java/com/twilio/rest/flexapi/v1/InsightsQuestionnaires.java index 72266a5492..80239af480 100644 --- a/src/main/java/com/twilio/rest/flexapi/v1/InsightsQuestionnaires.java +++ b/src/main/java/com/twilio/rest/flexapi/v1/InsightsQuestionnaires.java @@ -18,65 +18,69 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.util.List; -import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class InsightsQuestionnaires extends Resource { - private static final long serialVersionUID = 101221063563372L; public static InsightsQuestionnairesCreator creator(final String name) { - return new InsightsQuestionnairesCreator(name); + return new InsightsQuestionnairesCreator( + name + ); } - public static InsightsQuestionnairesDeleter deleter( - final String pathQuestionnaireSid - ) { - return new InsightsQuestionnairesDeleter(pathQuestionnaireSid); + + public static InsightsQuestionnairesDeleter deleter(final String pathquestionnaireSid) { + return new InsightsQuestionnairesDeleter( + pathquestionnaireSid + ); } - public static InsightsQuestionnairesFetcher fetcher( - final String pathQuestionnaireSid - ) { - return new InsightsQuestionnairesFetcher(pathQuestionnaireSid); + + public static InsightsQuestionnairesFetcher fetcher(final String pathquestionnaireSid) { + return new InsightsQuestionnairesFetcher( + pathquestionnaireSid + ); } + public static InsightsQuestionnairesReader reader() { - return new InsightsQuestionnairesReader(); + return new InsightsQuestionnairesReader( + + ); } - public static InsightsQuestionnairesUpdater updater( - final String pathQuestionnaireSid, - final Boolean active - ) { - return new InsightsQuestionnairesUpdater(pathQuestionnaireSid, active); + + public static InsightsQuestionnairesUpdater updater(final String pathquestionnaireSid, final Boolean active) { + return new InsightsQuestionnairesUpdater( + pathquestionnaireSid, active + ); } + /** * Converts a JSON String into a InsightsQuestionnaires object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return InsightsQuestionnaires object represented by the provided JSON */ - public static InsightsQuestionnaires fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static InsightsQuestionnaires fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, InsightsQuestionnaires.class); @@ -91,14 +95,11 @@ public static InsightsQuestionnaires fromJson( * Converts a JSON InputStream into a InsightsQuestionnaires object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return InsightsQuestionnaires object represented by the provided JSON */ - public static InsightsQuestionnaires fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static InsightsQuestionnaires fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, InsightsQuestionnaires.class); @@ -109,61 +110,53 @@ public static InsightsQuestionnaires fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String questionnaireSid; - private final String name; - private final String description; + @Getter private final Boolean active; - private final List> questions; + @Getter + private final String description; + @Getter + private final String name; + @Getter + private final String questionnaireSid; + @Getter + private final List questions; + @Getter private final URI url; @JsonCreator private InsightsQuestionnaires( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("questionnaire_sid") final String questionnaireSid, - @JsonProperty("name") final String name, - @JsonProperty("description") final String description, - @JsonProperty("active") final Boolean active, - @JsonProperty("questions") final List> questions, - @JsonProperty("url") final URI url + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("active") final Boolean active, + @JsonProperty("description") final String description, + @JsonProperty("name") final String name, + @JsonProperty("questionnaire_sid") final String questionnaireSid, + @JsonProperty("questions") final List questions, + @JsonProperty("url") final URI url ) { this.accountSid = accountSid; - this.questionnaireSid = questionnaireSid; - this.name = name; - this.description = description; this.active = active; + this.description = description; + this.name = name; + this.questionnaireSid = questionnaireSid; this.questions = questions; this.url = url; } - public final String getAccountSid() { - return this.accountSid; - } - - public final String getQuestionnaireSid() { - return this.questionnaireSid; - } - - public final String getName() { - return this.name; - } - - public final String getDescription() { - return this.description; - } - - public final Boolean getActive() { - return this.active; - } - - public final List> getQuestions() { - return this.questions; - } - - public final URI getUrl() { - return this.url; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -175,28 +168,30 @@ public boolean equals(final Object o) { } InsightsQuestionnaires other = (InsightsQuestionnaires) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(questionnaireSid, other.questionnaireSid) && - Objects.equals(name, other.name) && - Objects.equals(description, other.description) && - Objects.equals(active, other.active) && - Objects.equals(questions, other.questions) && - Objects.equals(url, other.url) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(active, other.active) && + Objects.equals(description, other.description) && + Objects.equals(name, other.name) && + Objects.equals(questionnaireSid, other.questionnaireSid) && + Objects.equals(questions, other.questions) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - accountSid, - questionnaireSid, - name, - description, - active, - questions, - url + accountSid, + active, + description, + name, + questionnaireSid, + questions, + url ); } + + } + diff --git a/src/main/java/com/twilio/rest/flexapi/v1/InsightsQuestionnairesCategory.java b/src/main/java/com/twilio/rest/flexapi/v1/InsightsQuestionnairesCategory.java index 3682d38fcc..115003e936 100644 --- a/src/main/java/com/twilio/rest/flexapi/v1/InsightsQuestionnairesCategory.java +++ b/src/main/java/com/twilio/rest/flexapi/v1/InsightsQuestionnairesCategory.java @@ -18,64 +18,64 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class InsightsQuestionnairesCategory extends Resource { - private static final long serialVersionUID = 80122837059940L; - public static InsightsQuestionnairesCategoryCreator creator( - final String name - ) { - return new InsightsQuestionnairesCategoryCreator(name); + public static InsightsQuestionnairesCategoryCreator creator(final String name) { + return new InsightsQuestionnairesCategoryCreator( + name + ); } - public static InsightsQuestionnairesCategoryDeleter deleter( - final String pathCategorySid - ) { - return new InsightsQuestionnairesCategoryDeleter(pathCategorySid); + + public static InsightsQuestionnairesCategoryDeleter deleter(final String pathcategorySid) { + return new InsightsQuestionnairesCategoryDeleter( + pathcategorySid + ); } + public static InsightsQuestionnairesCategoryReader reader() { - return new InsightsQuestionnairesCategoryReader(); + return new InsightsQuestionnairesCategoryReader( + + ); } - public static InsightsQuestionnairesCategoryUpdater updater( - final String pathCategorySid, - final String name - ) { - return new InsightsQuestionnairesCategoryUpdater(pathCategorySid, name); + + public static InsightsQuestionnairesCategoryUpdater updater(final String pathcategorySid, final String name) { + return new InsightsQuestionnairesCategoryUpdater( + pathcategorySid, name + ); } + /** * Converts a JSON String into a InsightsQuestionnairesCategory object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return InsightsQuestionnairesCategory object represented by the provided JSON */ - public static InsightsQuestionnairesCategory fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static InsightsQuestionnairesCategory fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { - return objectMapper.readValue( - json, - InsightsQuestionnairesCategory.class - ); + return objectMapper.readValue(json, InsightsQuestionnairesCategory.class); } catch (final JsonMappingException | JsonParseException e) { throw new ApiException(e.getMessage(), e); } catch (final IOException e) { @@ -87,20 +87,14 @@ public static InsightsQuestionnairesCategory fromJson( * Converts a JSON InputStream into a InsightsQuestionnairesCategory object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return InsightsQuestionnairesCategory object represented by the provided JSON */ - public static InsightsQuestionnairesCategory fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static InsightsQuestionnairesCategory fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { - return objectMapper.readValue( - json, - InsightsQuestionnairesCategory.class - ); + return objectMapper.readValue(json, InsightsQuestionnairesCategory.class); } catch (final JsonMappingException | JsonParseException e) { throw new ApiException(e.getMessage(), e); } catch (final IOException e) { @@ -108,17 +102,34 @@ public static InsightsQuestionnairesCategory fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; + @Getter private final String categorySid; + @Getter private final String name; + @Getter private final URI url; @JsonCreator private InsightsQuestionnairesCategory( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("category_sid") final String categorySid, - @JsonProperty("name") final String name, - @JsonProperty("url") final URI url + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("category_sid") final String categorySid, + @JsonProperty("name") final String name, + @JsonProperty("url") final URI url ) { this.accountSid = accountSid; this.categorySid = categorySid; @@ -126,22 +137,6 @@ private InsightsQuestionnairesCategory( this.url = url; } - public final String getAccountSid() { - return this.accountSid; - } - - public final String getCategorySid() { - return this.categorySid; - } - - public final String getName() { - return this.name; - } - - public final URI getUrl() { - return this.url; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -152,19 +147,25 @@ public boolean equals(final Object o) { return false; } - InsightsQuestionnairesCategory other = - (InsightsQuestionnairesCategory) o; - + InsightsQuestionnairesCategory other = (InsightsQuestionnairesCategory) o; return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(categorySid, other.categorySid) && - Objects.equals(name, other.name) && - Objects.equals(url, other.url) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(categorySid, other.categorySid) && + Objects.equals(name, other.name) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { - return Objects.hash(accountSid, categorySid, name, url); + return Objects.hash( + accountSid, + categorySid, + name, + url + ); } + + } + diff --git a/src/main/java/com/twilio/rest/flexapi/v1/InsightsQuestionnairesCategoryCreator.java b/src/main/java/com/twilio/rest/flexapi/v1/InsightsQuestionnairesCategoryCreator.java index 623d0cc273..db3c6bcae9 100644 --- a/src/main/java/com/twilio/rest/flexapi/v1/InsightsQuestionnairesCategoryCreator.java +++ b/src/main/java/com/twilio/rest/flexapi/v1/InsightsQuestionnairesCategoryCreator.java @@ -14,8 +14,11 @@ package com.twilio.rest.flexapi.v1; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,78 +28,75 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class InsightsQuestionnairesCategoryCreator - extends Creator { +public class InsightsQuestionnairesCategoryCreator extends Creator { - private String name; private String authorization; + private String name; public InsightsQuestionnairesCategoryCreator(final String name) { this.name = name; } + public InsightsQuestionnairesCategoryCreator setName(final String name) { this.name = name; return this; } - public InsightsQuestionnairesCategoryCreator setAuthorization( - final String authorization - ) { + + public InsightsQuestionnairesCategoryCreator setAuthorization(final String authorization) { this.authorization = authorization; return this; } + @Override - public InsightsQuestionnairesCategory create( - final TwilioRestClient client - ) { + public InsightsQuestionnairesCategory create(final TwilioRestClient client) { + String path = "/v1/Insights/QualityManagement/Categories"; - path = path.replace("{" + "Name" + "}", this.name.toString()); Request request = new Request( - HttpMethod.POST, - Domains.FLEXAPI.toString(), - path + HttpMethod.POST, + Domains.FLEXAPI.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); - addPostParams(request); addHeaderParams(request); + addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "InsightsQuestionnairesCategory creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("InsightsQuestionnairesCategory creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return InsightsQuestionnairesCategory.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return InsightsQuestionnairesCategory.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (name != null) { - request.addPostParam("Name", name); + Serializer.toString(request, "Name", name, ParameterType.URLENCODED); } + + } private void addHeaderParams(final Request request) { + if (authorization != null) { - request.addHeaderParam("Authorization", authorization); + Serializer.toString(request, "Authorization", authorization, ParameterType.HEADER); } + } } diff --git a/src/main/java/com/twilio/rest/flexapi/v1/InsightsQuestionnairesCategoryDeleter.java b/src/main/java/com/twilio/rest/flexapi/v1/InsightsQuestionnairesCategoryDeleter.java index a8de8c0e0a..a708f26396 100644 --- a/src/main/java/com/twilio/rest/flexapi/v1/InsightsQuestionnairesCategoryDeleter.java +++ b/src/main/java/com/twilio/rest/flexapi/v1/InsightsQuestionnairesCategoryDeleter.java @@ -15,7 +15,8 @@ package com.twilio.rest.flexapi.v1; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,56 +26,48 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class InsightsQuestionnairesCategoryDeleter - extends Deleter { +public class InsightsQuestionnairesCategoryDeleter extends Deleter { - private String pathCategorySid; + private String pathcategorySid; private String authorization; - public InsightsQuestionnairesCategoryDeleter(final String pathCategorySid) { - this.pathCategorySid = pathCategorySid; + public InsightsQuestionnairesCategoryDeleter(final String pathcategorySid) { + this.pathcategorySid = pathcategorySid; } - public InsightsQuestionnairesCategoryDeleter setAuthorization( - final String authorization - ) { + + public InsightsQuestionnairesCategoryDeleter setAuthorization(final String authorization) { this.authorization = authorization; return this; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/v1/Insights/QualityManagement/Categories/{CategorySid}"; - path = - path.replace( - "{" + "CategorySid" + "}", - this.pathCategorySid.toString() - ); + path = path.replace("{" + "CategorySid" + "}", this.pathcategorySid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.FLEXAPI.toString(), - path + HttpMethod.DELETE, + Domains.FLEXAPI.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addHeaderParams(request); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "InsightsQuestionnairesCategory delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("InsightsQuestionnairesCategory delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -82,8 +75,10 @@ public boolean delete(final TwilioRestClient client) { } private void addHeaderParams(final Request request) { + if (authorization != null) { - request.addHeaderParam("Authorization", authorization); + Serializer.toString(request, "Authorization", authorization, ParameterType.HEADER); } + } } diff --git a/src/main/java/com/twilio/rest/flexapi/v1/InsightsQuestionnairesCategoryReader.java b/src/main/java/com/twilio/rest/flexapi/v1/InsightsQuestionnairesCategoryReader.java index a671866e14..60db4a2338 100644 --- a/src/main/java/com/twilio/rest/flexapi/v1/InsightsQuestionnairesCategoryReader.java +++ b/src/main/java/com/twilio/rest/flexapi/v1/InsightsQuestionnairesCategoryReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,131 +28,103 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class InsightsQuestionnairesCategoryReader - extends Reader { +public class InsightsQuestionnairesCategoryReader extends Reader { - private String authorization; private Long pageSize; + private String authorization; - public InsightsQuestionnairesCategoryReader() {} + public InsightsQuestionnairesCategoryReader() { + } - public InsightsQuestionnairesCategoryReader setAuthorization( - final String authorization - ) { - this.authorization = authorization; + + public InsightsQuestionnairesCategoryReader setPageSize(final Long pageSize) { + this.pageSize = pageSize; return this; } - public InsightsQuestionnairesCategoryReader setPageSize( - final Long pageSize - ) { - this.pageSize = pageSize; + + public InsightsQuestionnairesCategoryReader setAuthorization(final String authorization) { + this.authorization = authorization; return this; } + @Override - public ResourceSet read( - final TwilioRestClient client - ) { + public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } - public Page firstPage( - final TwilioRestClient client - ) { + public Page firstPage(final TwilioRestClient client) { + String path = "/v1/Insights/QualityManagement/Categories"; + Request request = new Request( - HttpMethod.GET, - Domains.FLEXAPI.toString(), - path + HttpMethod.GET, + Domains.FLEXAPI.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addHeaderParams(request); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "InsightsQuestionnairesCategory read failed: Unable to connect to server" - ); + throw new ApiConnectionException("InsightsQuestionnairesCategory read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "categories", - response.getContent(), - InsightsQuestionnairesCategory.class, - client.getObjectMapper() - ); + "categories", + response.getContent(), + InsightsQuestionnairesCategory.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.FLEXAPI.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.FLEXAPI.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } - private void addHeaderParams(final Request request) { - if (authorization != null) { - request.addHeaderParam("Authorization", authorization); - } - } - private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); + + } + + private void addHeaderParams(final Request request) { + + if (authorization != null) { + Serializer.toString(request, "Authorization", authorization, ParameterType.HEADER); } + } } diff --git a/src/main/java/com/twilio/rest/flexapi/v1/InsightsQuestionnairesCategoryUpdater.java b/src/main/java/com/twilio/rest/flexapi/v1/InsightsQuestionnairesCategoryUpdater.java index abdee9c303..f1eed7b1ff 100644 --- a/src/main/java/com/twilio/rest/flexapi/v1/InsightsQuestionnairesCategoryUpdater.java +++ b/src/main/java/com/twilio/rest/flexapi/v1/InsightsQuestionnairesCategoryUpdater.java @@ -16,6 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,88 +27,78 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class InsightsQuestionnairesCategoryUpdater - extends Updater { - - private String pathCategorySid; - private String name; +public class InsightsQuestionnairesCategoryUpdater extends Updater { + private String pathcategorySid; private String authorization; + private String name; - public InsightsQuestionnairesCategoryUpdater( - final String pathCategorySid, - final String name - ) { - this.pathCategorySid = pathCategorySid; + public InsightsQuestionnairesCategoryUpdater(final String pathcategorySid, final String name) { + this.pathcategorySid = pathcategorySid; this.name = name; } + public InsightsQuestionnairesCategoryUpdater setName(final String name) { this.name = name; return this; } - public InsightsQuestionnairesCategoryUpdater setAuthorization( - final String authorization - ) { + + public InsightsQuestionnairesCategoryUpdater setAuthorization(final String authorization) { this.authorization = authorization; return this; } + @Override - public InsightsQuestionnairesCategory update( - final TwilioRestClient client - ) { + public InsightsQuestionnairesCategory update(final TwilioRestClient client) { + String path = "/v1/Insights/QualityManagement/Categories/{CategorySid}"; - path = - path.replace( - "{" + "CategorySid" + "}", - this.pathCategorySid.toString() - ); - path = path.replace("{" + "Name" + "}", this.name.toString()); + path = path.replace("{" + "CategorySid" + "}", this.pathcategorySid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.FLEXAPI.toString(), - path + HttpMethod.POST, + Domains.FLEXAPI.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); - addPostParams(request); addHeaderParams(request); + addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "InsightsQuestionnairesCategory update failed: Unable to connect to server" - ); + throw new ApiConnectionException("InsightsQuestionnairesCategory update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return InsightsQuestionnairesCategory.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return InsightsQuestionnairesCategory.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (name != null) { - request.addPostParam("Name", name); + Serializer.toString(request, "Name", name, ParameterType.URLENCODED); } + + } private void addHeaderParams(final Request request) { + if (authorization != null) { - request.addHeaderParam("Authorization", authorization); + Serializer.toString(request, "Authorization", authorization, ParameterType.HEADER); } + } } diff --git a/src/main/java/com/twilio/rest/flexapi/v1/InsightsQuestionnairesCreator.java b/src/main/java/com/twilio/rest/flexapi/v1/InsightsQuestionnairesCreator.java index fc7cc48279..d28b83f98b 100644 --- a/src/main/java/com/twilio/rest/flexapi/v1/InsightsQuestionnairesCreator.java +++ b/src/main/java/com/twilio/rest/flexapi/v1/InsightsQuestionnairesCreator.java @@ -14,9 +14,12 @@ package com.twilio.rest.flexapi.v1; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; import com.twilio.converter.Promoter; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,14 +28,13 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -import java.util.List; + import java.util.List; -public class InsightsQuestionnairesCreator - extends Creator { +public class InsightsQuestionnairesCreator extends Creator { - private String name; private String authorization; + private String name; private String description; private Boolean active; private List questionSids; @@ -41,102 +43,103 @@ public InsightsQuestionnairesCreator(final String name) { this.name = name; } + public InsightsQuestionnairesCreator setName(final String name) { this.name = name; return this; } - public InsightsQuestionnairesCreator setAuthorization( - final String authorization - ) { - this.authorization = authorization; - return this; - } - public InsightsQuestionnairesCreator setDescription( - final String description - ) { + public InsightsQuestionnairesCreator setDescription(final String description) { this.description = description; return this; } + public InsightsQuestionnairesCreator setActive(final Boolean active) { this.active = active; return this; } - public InsightsQuestionnairesCreator setQuestionSids( - final List questionSids - ) { + + public InsightsQuestionnairesCreator setQuestionSids(final List questionSids) { this.questionSids = questionSids; return this; } - public InsightsQuestionnairesCreator setQuestionSids( - final String questionSids - ) { + public InsightsQuestionnairesCreator setQuestionSids(final String questionSids) { return setQuestionSids(Promoter.listOfOne(questionSids)); } + public InsightsQuestionnairesCreator setAuthorization(final String authorization) { + this.authorization = authorization; + return this; + } + + @Override public InsightsQuestionnaires create(final TwilioRestClient client) { + String path = "/v1/Insights/QualityManagement/Questionnaires"; - path = path.replace("{" + "Name" + "}", this.name.toString()); Request request = new Request( - HttpMethod.POST, - Domains.FLEXAPI.toString(), - path + HttpMethod.POST, + Domains.FLEXAPI.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); - addPostParams(request); addHeaderParams(request); + addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "InsightsQuestionnaires creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("InsightsQuestionnaires creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return InsightsQuestionnaires.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return InsightsQuestionnaires.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (name != null) { - request.addPostParam("Name", name); + Serializer.toString(request, "Name", name, ParameterType.URLENCODED); } + + if (description != null) { - request.addPostParam("Description", description); + Serializer.toString(request, "Description", description, ParameterType.URLENCODED); } + + if (active != null) { - request.addPostParam("Active", active.toString()); + Serializer.toString(request, "Active", active, ParameterType.URLENCODED); } + + if (questionSids != null) { - for (String prop : questionSids) { - request.addPostParam("QuestionSids", prop); + for (String param : questionSids) { + Serializer.toString(request, "QuestionSids", param, ParameterType.URLENCODED); } } + } private void addHeaderParams(final Request request) { + if (authorization != null) { - request.addHeaderParam("Authorization", authorization); + Serializer.toString(request, "Authorization", authorization, ParameterType.HEADER); } + } } diff --git a/src/main/java/com/twilio/rest/flexapi/v1/InsightsQuestionnairesDeleter.java b/src/main/java/com/twilio/rest/flexapi/v1/InsightsQuestionnairesDeleter.java index 61cb98e86f..5c415bed52 100644 --- a/src/main/java/com/twilio/rest/flexapi/v1/InsightsQuestionnairesDeleter.java +++ b/src/main/java/com/twilio/rest/flexapi/v1/InsightsQuestionnairesDeleter.java @@ -15,7 +15,8 @@ package com.twilio.rest.flexapi.v1; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,57 +26,48 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class InsightsQuestionnairesDeleter - extends Deleter { +public class InsightsQuestionnairesDeleter extends Deleter { - private String pathQuestionnaireSid; + private String pathquestionnaireSid; private String authorization; - public InsightsQuestionnairesDeleter(final String pathQuestionnaireSid) { - this.pathQuestionnaireSid = pathQuestionnaireSid; + public InsightsQuestionnairesDeleter(final String pathquestionnaireSid) { + this.pathquestionnaireSid = pathquestionnaireSid; } - public InsightsQuestionnairesDeleter setAuthorization( - final String authorization - ) { + + public InsightsQuestionnairesDeleter setAuthorization(final String authorization) { this.authorization = authorization; return this; } + @Override public boolean delete(final TwilioRestClient client) { - String path = - "/v1/Insights/QualityManagement/Questionnaires/{QuestionnaireSid}"; - path = - path.replace( - "{" + "QuestionnaireSid" + "}", - this.pathQuestionnaireSid.toString() - ); + String path = "/v1/Insights/QualityManagement/Questionnaires/{QuestionnaireSid}"; + + path = path.replace("{" + "QuestionnaireSid" + "}", this.pathquestionnaireSid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.FLEXAPI.toString(), - path + HttpMethod.DELETE, + Domains.FLEXAPI.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addHeaderParams(request); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "InsightsQuestionnaires delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("InsightsQuestionnaires delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -83,8 +75,10 @@ public boolean delete(final TwilioRestClient client) { } private void addHeaderParams(final Request request) { + if (authorization != null) { - request.addHeaderParam("Authorization", authorization); + Serializer.toString(request, "Authorization", authorization, ParameterType.HEADER); } + } } diff --git a/src/main/java/com/twilio/rest/flexapi/v1/InsightsQuestionnairesFetcher.java b/src/main/java/com/twilio/rest/flexapi/v1/InsightsQuestionnairesFetcher.java index 110cf863e7..53f4d3955c 100644 --- a/src/main/java/com/twilio/rest/flexapi/v1/InsightsQuestionnairesFetcher.java +++ b/src/main/java/com/twilio/rest/flexapi/v1/InsightsQuestionnairesFetcher.java @@ -15,7 +15,8 @@ package com.twilio.rest.flexapi.v1; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,70 +26,59 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class InsightsQuestionnairesFetcher - extends Fetcher { +public class InsightsQuestionnairesFetcher extends Fetcher { - private String pathQuestionnaireSid; + private String pathquestionnaireSid; private String authorization; - public InsightsQuestionnairesFetcher(final String pathQuestionnaireSid) { - this.pathQuestionnaireSid = pathQuestionnaireSid; + public InsightsQuestionnairesFetcher(final String pathquestionnaireSid) { + this.pathquestionnaireSid = pathquestionnaireSid; } - public InsightsQuestionnairesFetcher setAuthorization( - final String authorization - ) { + + public InsightsQuestionnairesFetcher setAuthorization(final String authorization) { this.authorization = authorization; return this; } + @Override public InsightsQuestionnaires fetch(final TwilioRestClient client) { - String path = - "/v1/Insights/QualityManagement/Questionnaires/{QuestionnaireSid}"; - path = - path.replace( - "{" + "QuestionnaireSid" + "}", - this.pathQuestionnaireSid.toString() - ); + String path = "/v1/Insights/QualityManagement/Questionnaires/{QuestionnaireSid}"; + + path = path.replace("{" + "QuestionnaireSid" + "}", this.pathquestionnaireSid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.FLEXAPI.toString(), - path + HttpMethod.GET, + Domains.FLEXAPI.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addHeaderParams(request); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "InsightsQuestionnaires fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("InsightsQuestionnaires fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return InsightsQuestionnaires.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return InsightsQuestionnaires.fromJson(response.getStream(), client.getObjectMapper()); } private void addHeaderParams(final Request request) { + if (authorization != null) { - request.addHeaderParam("Authorization", authorization); + Serializer.toString(request, "Authorization", authorization, ParameterType.HEADER); } + } } diff --git a/src/main/java/com/twilio/rest/flexapi/v1/InsightsQuestionnairesQuestion.java b/src/main/java/com/twilio/rest/flexapi/v1/InsightsQuestionnairesQuestion.java index b3f35448fa..b500018f2f 100644 --- a/src/main/java/com/twilio/rest/flexapi/v1/InsightsQuestionnairesQuestion.java +++ b/src/main/java/com/twilio/rest/flexapi/v1/InsightsQuestionnairesQuestion.java @@ -18,77 +18,64 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; -import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class InsightsQuestionnairesQuestion extends Resource { - private static final long serialVersionUID = 10229949486791L; - public static InsightsQuestionnairesQuestionCreator creator( - final String categorySid, - final String question, - final String answerSetId, - final Boolean allowNa - ) { + public static InsightsQuestionnairesQuestionCreator creator(final String categorySid, final String question, final String answerSetId, final Boolean allowNa) { return new InsightsQuestionnairesQuestionCreator( - categorySid, - question, - answerSetId, - allowNa + categorySid, question, answerSetId, allowNa ); } - public static InsightsQuestionnairesQuestionDeleter deleter( - final String pathQuestionSid - ) { - return new InsightsQuestionnairesQuestionDeleter(pathQuestionSid); + + public static InsightsQuestionnairesQuestionDeleter deleter(final String pathquestionSid) { + return new InsightsQuestionnairesQuestionDeleter( + pathquestionSid + ); } + public static InsightsQuestionnairesQuestionReader reader() { - return new InsightsQuestionnairesQuestionReader(); + return new InsightsQuestionnairesQuestionReader( + + ); } - public static InsightsQuestionnairesQuestionUpdater updater( - final String pathQuestionSid, - final Boolean allowNa - ) { + + public static InsightsQuestionnairesQuestionUpdater updater(final String pathquestionSid, final Boolean allowNa) { return new InsightsQuestionnairesQuestionUpdater( - pathQuestionSid, - allowNa + pathquestionSid, allowNa ); } + /** * Converts a JSON String into a InsightsQuestionnairesQuestion object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return InsightsQuestionnairesQuestion object represented by the provided JSON */ - public static InsightsQuestionnairesQuestion fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static InsightsQuestionnairesQuestion fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { - return objectMapper.readValue( - json, - InsightsQuestionnairesQuestion.class - ); + return objectMapper.readValue(json, InsightsQuestionnairesQuestion.class); } catch (final JsonMappingException | JsonParseException e) { throw new ApiException(e.getMessage(), e); } catch (final IOException e) { @@ -100,20 +87,14 @@ public static InsightsQuestionnairesQuestion fromJson( * Converts a JSON InputStream into a InsightsQuestionnairesQuestion object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return InsightsQuestionnairesQuestion object represented by the provided JSON */ - public static InsightsQuestionnairesQuestion fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static InsightsQuestionnairesQuestion fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { - return objectMapper.readValue( - json, - InsightsQuestionnairesQuestion.class - ); + return objectMapper.readValue(json, InsightsQuestionnairesQuestion.class); } catch (final JsonMappingException | JsonParseException e) { throw new ApiException(e.getMessage(), e); } catch (final IOException e) { @@ -121,80 +102,63 @@ public static InsightsQuestionnairesQuestion fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String questionSid; - private final String question; - private final String description; - private final Map category; - private final String answerSetId; + @Getter private final Boolean allowNa; - private final Integer usage; - private final Map answerSet; + @Getter + private final Object answerSet; + @Getter + private final String answerSetId; + @Getter + private final Object category; + @Getter + private final String description; + @Getter + private final String question; + @Getter + private final String questionSid; + @Getter private final URI url; + @Getter + private final Integer usage; @JsonCreator private InsightsQuestionnairesQuestion( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("question_sid") final String questionSid, - @JsonProperty("question") final String question, - @JsonProperty("description") final String description, - @JsonProperty("category") final Map category, - @JsonProperty("answer_set_id") final String answerSetId, - @JsonProperty("allow_na") final Boolean allowNa, - @JsonProperty("usage") final Integer usage, - @JsonProperty("answer_set") final Map answerSet, - @JsonProperty("url") final URI url + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("allow_na") final Boolean allowNa, + @JsonProperty("answer_set") final Object answerSet, + @JsonProperty("answer_set_id") final String answerSetId, + @JsonProperty("category") final Object category, + @JsonProperty("description") final String description, + @JsonProperty("question") final String question, + @JsonProperty("question_sid") final String questionSid, + @JsonProperty("url") final URI url, + @JsonProperty("usage") final Integer usage ) { this.accountSid = accountSid; - this.questionSid = questionSid; - this.question = question; - this.description = description; - this.category = category; - this.answerSetId = answerSetId; this.allowNa = allowNa; - this.usage = usage; this.answerSet = answerSet; + this.answerSetId = answerSetId; + this.category = category; + this.description = description; + this.question = question; + this.questionSid = questionSid; this.url = url; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getQuestionSid() { - return this.questionSid; - } - - public final String getQuestion() { - return this.question; - } - - public final String getDescription() { - return this.description; - } - - public final Map getCategory() { - return this.category; - } - - public final String getAnswerSetId() { - return this.answerSetId; - } - - public final Boolean getAllowNa() { - return this.allowNa; - } - - public final Integer getUsage() { - return this.usage; - } - - public final Map getAnswerSet() { - return this.answerSet; - } - - public final URI getUrl() { - return this.url; + this.usage = usage; } @Override @@ -207,36 +171,37 @@ public boolean equals(final Object o) { return false; } - InsightsQuestionnairesQuestion other = - (InsightsQuestionnairesQuestion) o; - + InsightsQuestionnairesQuestion other = (InsightsQuestionnairesQuestion) o; return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(questionSid, other.questionSid) && - Objects.equals(question, other.question) && - Objects.equals(description, other.description) && - Objects.equals(category, other.category) && - Objects.equals(answerSetId, other.answerSetId) && - Objects.equals(allowNa, other.allowNa) && - Objects.equals(usage, other.usage) && - Objects.equals(answerSet, other.answerSet) && - Objects.equals(url, other.url) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(allowNa, other.allowNa) && + Objects.equals(answerSet, other.answerSet) && + Objects.equals(answerSetId, other.answerSetId) && + Objects.equals(category, other.category) && + Objects.equals(description, other.description) && + Objects.equals(question, other.question) && + Objects.equals(questionSid, other.questionSid) && + Objects.equals(url, other.url) && + Objects.equals(usage, other.usage) ); } @Override public int hashCode() { return Objects.hash( - accountSid, - questionSid, - question, - description, - category, - answerSetId, - allowNa, - usage, - answerSet, - url + accountSid, + allowNa, + answerSet, + answerSetId, + category, + description, + question, + questionSid, + url, + usage ); } + + } + diff --git a/src/main/java/com/twilio/rest/flexapi/v1/InsightsQuestionnairesQuestionCreator.java b/src/main/java/com/twilio/rest/flexapi/v1/InsightsQuestionnairesQuestionCreator.java index 6b4d3c96a0..451754cb1d 100644 --- a/src/main/java/com/twilio/rest/flexapi/v1/InsightsQuestionnairesQuestionCreator.java +++ b/src/main/java/com/twilio/rest/flexapi/v1/InsightsQuestionnairesQuestionCreator.java @@ -14,8 +14,11 @@ package com.twilio.rest.flexapi.v1; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,143 +28,126 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class InsightsQuestionnairesQuestionCreator - extends Creator { +public class InsightsQuestionnairesQuestionCreator extends Creator { + private String authorization; private String categorySid; private String question; private String answerSetId; private Boolean allowNa; - private String authorization; private String description; - public InsightsQuestionnairesQuestionCreator( - final String categorySid, - final String question, - final String answerSetId, - final Boolean allowNa - ) { + public InsightsQuestionnairesQuestionCreator(final String categorySid, final String question, final String answerSetId, final Boolean allowNa) { this.categorySid = categorySid; this.question = question; this.answerSetId = answerSetId; this.allowNa = allowNa; } - public InsightsQuestionnairesQuestionCreator setCategorySid( - final String categorySid - ) { + + public InsightsQuestionnairesQuestionCreator setCategorySid(final String categorySid) { this.categorySid = categorySid; return this; } - public InsightsQuestionnairesQuestionCreator setQuestion( - final String question - ) { + + public InsightsQuestionnairesQuestionCreator setQuestion(final String question) { this.question = question; return this; } - public InsightsQuestionnairesQuestionCreator setAnswerSetId( - final String answerSetId - ) { + + public InsightsQuestionnairesQuestionCreator setAnswerSetId(final String answerSetId) { this.answerSetId = answerSetId; return this; } - public InsightsQuestionnairesQuestionCreator setAllowNa( - final Boolean allowNa - ) { + + public InsightsQuestionnairesQuestionCreator setAllowNa(final Boolean allowNa) { this.allowNa = allowNa; return this; } - public InsightsQuestionnairesQuestionCreator setAuthorization( - final String authorization - ) { - this.authorization = authorization; + + public InsightsQuestionnairesQuestionCreator setDescription(final String description) { + this.description = description; return this; } - public InsightsQuestionnairesQuestionCreator setDescription( - final String description - ) { - this.description = description; + + public InsightsQuestionnairesQuestionCreator setAuthorization(final String authorization) { + this.authorization = authorization; return this; } + @Override - public InsightsQuestionnairesQuestion create( - final TwilioRestClient client - ) { + public InsightsQuestionnairesQuestion create(final TwilioRestClient client) { + String path = "/v1/Insights/QualityManagement/Questions"; - path = - path.replace( - "{" + "CategorySid" + "}", - this.categorySid.toString() - ); - path = path.replace("{" + "Question" + "}", this.question.toString()); - path = - path.replace( - "{" + "AnswerSetId" + "}", - this.answerSetId.toString() - ); - path = path.replace("{" + "AllowNa" + "}", this.allowNa.toString()); Request request = new Request( - HttpMethod.POST, - Domains.FLEXAPI.toString(), - path + HttpMethod.POST, + Domains.FLEXAPI.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); - addPostParams(request); addHeaderParams(request); + addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "InsightsQuestionnairesQuestion creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("InsightsQuestionnairesQuestion creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return InsightsQuestionnairesQuestion.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return InsightsQuestionnairesQuestion.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (categorySid != null) { - request.addPostParam("CategorySid", categorySid); + Serializer.toString(request, "CategorySid", categorySid, ParameterType.URLENCODED); } + + if (question != null) { - request.addPostParam("Question", question); + Serializer.toString(request, "Question", question, ParameterType.URLENCODED); } + + if (answerSetId != null) { - request.addPostParam("AnswerSetId", answerSetId); + Serializer.toString(request, "AnswerSetId", answerSetId, ParameterType.URLENCODED); } + + if (allowNa != null) { - request.addPostParam("AllowNa", allowNa.toString()); + Serializer.toString(request, "AllowNa", allowNa, ParameterType.URLENCODED); } + + if (description != null) { - request.addPostParam("Description", description); + Serializer.toString(request, "Description", description, ParameterType.URLENCODED); } + + } private void addHeaderParams(final Request request) { + if (authorization != null) { - request.addHeaderParam("Authorization", authorization); + Serializer.toString(request, "Authorization", authorization, ParameterType.HEADER); } + } } diff --git a/src/main/java/com/twilio/rest/flexapi/v1/InsightsQuestionnairesQuestionDeleter.java b/src/main/java/com/twilio/rest/flexapi/v1/InsightsQuestionnairesQuestionDeleter.java index 30dbc96c4c..e57edafd61 100644 --- a/src/main/java/com/twilio/rest/flexapi/v1/InsightsQuestionnairesQuestionDeleter.java +++ b/src/main/java/com/twilio/rest/flexapi/v1/InsightsQuestionnairesQuestionDeleter.java @@ -15,7 +15,8 @@ package com.twilio.rest.flexapi.v1; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,56 +26,48 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class InsightsQuestionnairesQuestionDeleter - extends Deleter { +public class InsightsQuestionnairesQuestionDeleter extends Deleter { - private String pathQuestionSid; + private String pathquestionSid; private String authorization; - public InsightsQuestionnairesQuestionDeleter(final String pathQuestionSid) { - this.pathQuestionSid = pathQuestionSid; + public InsightsQuestionnairesQuestionDeleter(final String pathquestionSid) { + this.pathquestionSid = pathquestionSid; } - public InsightsQuestionnairesQuestionDeleter setAuthorization( - final String authorization - ) { + + public InsightsQuestionnairesQuestionDeleter setAuthorization(final String authorization) { this.authorization = authorization; return this; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/v1/Insights/QualityManagement/Questions/{QuestionSid}"; - path = - path.replace( - "{" + "QuestionSid" + "}", - this.pathQuestionSid.toString() - ); + path = path.replace("{" + "QuestionSid" + "}", this.pathquestionSid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.FLEXAPI.toString(), - path + HttpMethod.DELETE, + Domains.FLEXAPI.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addHeaderParams(request); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "InsightsQuestionnairesQuestion delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("InsightsQuestionnairesQuestion delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -82,8 +75,10 @@ public boolean delete(final TwilioRestClient client) { } private void addHeaderParams(final Request request) { + if (authorization != null) { - request.addHeaderParam("Authorization", authorization); + Serializer.toString(request, "Authorization", authorization, ParameterType.HEADER); } + } } diff --git a/src/main/java/com/twilio/rest/flexapi/v1/InsightsQuestionnairesQuestionReader.java b/src/main/java/com/twilio/rest/flexapi/v1/InsightsQuestionnairesQuestionReader.java index 6b28244125..845bef882e 100644 --- a/src/main/java/com/twilio/rest/flexapi/v1/InsightsQuestionnairesQuestionReader.java +++ b/src/main/java/com/twilio/rest/flexapi/v1/InsightsQuestionnairesQuestionReader.java @@ -17,8 +17,9 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; import com.twilio.converter.Promoter; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,152 +28,123 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.util.List; -public class InsightsQuestionnairesQuestionReader - extends Reader { +public class InsightsQuestionnairesQuestionReader extends Reader { - private String authorization; private List categorySid; private Long pageSize; + private String authorization; - public InsightsQuestionnairesQuestionReader() {} - - public InsightsQuestionnairesQuestionReader setAuthorization( - final String authorization - ) { - this.authorization = authorization; - return this; + public InsightsQuestionnairesQuestionReader() { } - public InsightsQuestionnairesQuestionReader setCategorySid( - final List categorySid - ) { + + public InsightsQuestionnairesQuestionReader setCategorySid(final List categorySid) { this.categorySid = categorySid; return this; } - public InsightsQuestionnairesQuestionReader setCategorySid( - final String categorySid - ) { + public InsightsQuestionnairesQuestionReader setCategorySid(final String categorySid) { return setCategorySid(Promoter.listOfOne(categorySid)); } - public InsightsQuestionnairesQuestionReader setPageSize( - final Long pageSize - ) { + public InsightsQuestionnairesQuestionReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + + public InsightsQuestionnairesQuestionReader setAuthorization(final String authorization) { + this.authorization = authorization; + return this; + } + + @Override - public ResourceSet read( - final TwilioRestClient client - ) { + public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } - public Page firstPage( - final TwilioRestClient client - ) { + public Page firstPage(final TwilioRestClient client) { + String path = "/v1/Insights/QualityManagement/Questions"; + Request request = new Request( - HttpMethod.GET, - Domains.FLEXAPI.toString(), - path + HttpMethod.GET, + Domains.FLEXAPI.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addHeaderParams(request); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "InsightsQuestionnairesQuestion read failed: Unable to connect to server" - ); + throw new ApiConnectionException("InsightsQuestionnairesQuestion read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "questions", - response.getContent(), - InsightsQuestionnairesQuestion.class, - client.getObjectMapper() - ); + "questions", + response.getContent(), + InsightsQuestionnairesQuestion.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.FLEXAPI.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.FLEXAPI.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } - private void addHeaderParams(final Request request) { - if (authorization != null) { - request.addHeaderParam("Authorization", authorization); - } - } - private void addQueryParams(final Request request) { + + if (categorySid != null) { - for (String prop : categorySid) { - request.addQueryParam("CategorySid", prop); + for (String param : categorySid) { + Serializer.toString(request, "CategorySid", param, ParameterType.QUERY); } } + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); + + } + + private void addHeaderParams(final Request request) { + + if (authorization != null) { + Serializer.toString(request, "Authorization", authorization, ParameterType.HEADER); } + } } diff --git a/src/main/java/com/twilio/rest/flexapi/v1/InsightsQuestionnairesQuestionUpdater.java b/src/main/java/com/twilio/rest/flexapi/v1/InsightsQuestionnairesQuestionUpdater.java index 1c2bc6be19..4f680501c0 100644 --- a/src/main/java/com/twilio/rest/flexapi/v1/InsightsQuestionnairesQuestionUpdater.java +++ b/src/main/java/com/twilio/rest/flexapi/v1/InsightsQuestionnairesQuestionUpdater.java @@ -16,6 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,134 +27,126 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class InsightsQuestionnairesQuestionUpdater - extends Updater { - - private String pathQuestionSid; - private Boolean allowNa; +public class InsightsQuestionnairesQuestionUpdater extends Updater { + private String pathquestionSid; private String authorization; + private Boolean allowNa; private String categorySid; private String question; private String description; private String answerSetId; - public InsightsQuestionnairesQuestionUpdater( - final String pathQuestionSid, - final Boolean allowNa - ) { - this.pathQuestionSid = pathQuestionSid; + public InsightsQuestionnairesQuestionUpdater(final String pathquestionSid, final Boolean allowNa) { + this.pathquestionSid = pathquestionSid; this.allowNa = allowNa; } - public InsightsQuestionnairesQuestionUpdater setAllowNa( - final Boolean allowNa - ) { + + public InsightsQuestionnairesQuestionUpdater setAllowNa(final Boolean allowNa) { this.allowNa = allowNa; return this; } - public InsightsQuestionnairesQuestionUpdater setAuthorization( - final String authorization - ) { - this.authorization = authorization; - return this; - } - public InsightsQuestionnairesQuestionUpdater setCategorySid( - final String categorySid - ) { + public InsightsQuestionnairesQuestionUpdater setCategorySid(final String categorySid) { this.categorySid = categorySid; return this; } - public InsightsQuestionnairesQuestionUpdater setQuestion( - final String question - ) { + + public InsightsQuestionnairesQuestionUpdater setQuestion(final String question) { this.question = question; return this; } - public InsightsQuestionnairesQuestionUpdater setDescription( - final String description - ) { + + public InsightsQuestionnairesQuestionUpdater setDescription(final String description) { this.description = description; return this; } - public InsightsQuestionnairesQuestionUpdater setAnswerSetId( - final String answerSetId - ) { + + public InsightsQuestionnairesQuestionUpdater setAnswerSetId(final String answerSetId) { this.answerSetId = answerSetId; return this; } + + public InsightsQuestionnairesQuestionUpdater setAuthorization(final String authorization) { + this.authorization = authorization; + return this; + } + + @Override - public InsightsQuestionnairesQuestion update( - final TwilioRestClient client - ) { + public InsightsQuestionnairesQuestion update(final TwilioRestClient client) { + String path = "/v1/Insights/QualityManagement/Questions/{QuestionSid}"; - path = - path.replace( - "{" + "QuestionSid" + "}", - this.pathQuestionSid.toString() - ); - path = path.replace("{" + "AllowNa" + "}", this.allowNa.toString()); + path = path.replace("{" + "QuestionSid" + "}", this.pathquestionSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.FLEXAPI.toString(), - path + HttpMethod.POST, + Domains.FLEXAPI.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); - addPostParams(request); addHeaderParams(request); + addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "InsightsQuestionnairesQuestion update failed: Unable to connect to server" - ); + throw new ApiConnectionException("InsightsQuestionnairesQuestion update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return InsightsQuestionnairesQuestion.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return InsightsQuestionnairesQuestion.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (allowNa != null) { - request.addPostParam("AllowNa", allowNa.toString()); + Serializer.toString(request, "AllowNa", allowNa, ParameterType.URLENCODED); } + + if (categorySid != null) { - request.addPostParam("CategorySid", categorySid); + Serializer.toString(request, "CategorySid", categorySid, ParameterType.URLENCODED); } + + if (question != null) { - request.addPostParam("Question", question); + Serializer.toString(request, "Question", question, ParameterType.URLENCODED); } + + if (description != null) { - request.addPostParam("Description", description); + Serializer.toString(request, "Description", description, ParameterType.URLENCODED); } + + if (answerSetId != null) { - request.addPostParam("AnswerSetId", answerSetId); + Serializer.toString(request, "AnswerSetId", answerSetId, ParameterType.URLENCODED); } + + } private void addHeaderParams(final Request request) { + if (authorization != null) { - request.addHeaderParam("Authorization", authorization); + Serializer.toString(request, "Authorization", authorization, ParameterType.HEADER); } + } } diff --git a/src/main/java/com/twilio/rest/flexapi/v1/InsightsQuestionnairesReader.java b/src/main/java/com/twilio/rest/flexapi/v1/InsightsQuestionnairesReader.java index 880350c64d..de73a10e63 100644 --- a/src/main/java/com/twilio/rest/flexapi/v1/InsightsQuestionnairesReader.java +++ b/src/main/java/com/twilio/rest/flexapi/v1/InsightsQuestionnairesReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,143 +28,115 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class InsightsQuestionnairesReader - extends Reader { +public class InsightsQuestionnairesReader extends Reader { - private String authorization; private Boolean includeInactive; private Long pageSize; + private String authorization; - public InsightsQuestionnairesReader() {} - - public InsightsQuestionnairesReader setAuthorization( - final String authorization - ) { - this.authorization = authorization; - return this; + public InsightsQuestionnairesReader() { } - public InsightsQuestionnairesReader setIncludeInactive( - final Boolean includeInactive - ) { + + public InsightsQuestionnairesReader setIncludeInactive(final Boolean includeInactive) { this.includeInactive = includeInactive; return this; } + public InsightsQuestionnairesReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + + public InsightsQuestionnairesReader setAuthorization(final String authorization) { + this.authorization = authorization; + return this; + } + + @Override - public ResourceSet read( - final TwilioRestClient client - ) { + public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } - public Page firstPage( - final TwilioRestClient client - ) { + public Page firstPage(final TwilioRestClient client) { + String path = "/v1/Insights/QualityManagement/Questionnaires"; + Request request = new Request( - HttpMethod.GET, - Domains.FLEXAPI.toString(), - path + HttpMethod.GET, + Domains.FLEXAPI.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addHeaderParams(request); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "InsightsQuestionnaires read failed: Unable to connect to server" - ); + throw new ApiConnectionException("InsightsQuestionnaires read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "questionnaires", - response.getContent(), - InsightsQuestionnaires.class, - client.getObjectMapper() - ); + "questionnaires", + response.getContent(), + InsightsQuestionnaires.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.FLEXAPI.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.FLEXAPI.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } - private void addHeaderParams(final Request request) { - if (authorization != null) { - request.addHeaderParam("Authorization", authorization); - } - } - private void addQueryParams(final Request request) { + + if (includeInactive != null) { - request.addQueryParam( - "IncludeInactive", - includeInactive.toString() - ); + Serializer.toString(request, "IncludeInactive", includeInactive, ParameterType.QUERY); } + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); + + } + + private void addHeaderParams(final Request request) { + + if (authorization != null) { + Serializer.toString(request, "Authorization", authorization, ParameterType.HEADER); } + } } diff --git a/src/main/java/com/twilio/rest/flexapi/v1/InsightsQuestionnairesUpdater.java b/src/main/java/com/twilio/rest/flexapi/v1/InsightsQuestionnairesUpdater.java index 2e283e3458..f41baf4002 100644 --- a/src/main/java/com/twilio/rest/flexapi/v1/InsightsQuestionnairesUpdater.java +++ b/src/main/java/com/twilio/rest/flexapi/v1/InsightsQuestionnairesUpdater.java @@ -16,7 +16,9 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; import com.twilio.converter.Promoter; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,128 +27,121 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -import java.util.List; -public class InsightsQuestionnairesUpdater - extends Updater { +import java.util.List; - private String pathQuestionnaireSid; - private Boolean active; +public class InsightsQuestionnairesUpdater extends Updater { + private String pathquestionnaireSid; private String authorization; + private Boolean active; private String name; private String description; private List questionSids; - public InsightsQuestionnairesUpdater( - final String pathQuestionnaireSid, - final Boolean active - ) { - this.pathQuestionnaireSid = pathQuestionnaireSid; + public InsightsQuestionnairesUpdater(final String pathquestionnaireSid, final Boolean active) { + this.pathquestionnaireSid = pathquestionnaireSid; this.active = active; } + public InsightsQuestionnairesUpdater setActive(final Boolean active) { this.active = active; return this; } - public InsightsQuestionnairesUpdater setAuthorization( - final String authorization - ) { - this.authorization = authorization; - return this; - } public InsightsQuestionnairesUpdater setName(final String name) { this.name = name; return this; } - public InsightsQuestionnairesUpdater setDescription( - final String description - ) { + + public InsightsQuestionnairesUpdater setDescription(final String description) { this.description = description; return this; } - public InsightsQuestionnairesUpdater setQuestionSids( - final List questionSids - ) { + + public InsightsQuestionnairesUpdater setQuestionSids(final List questionSids) { this.questionSids = questionSids; return this; } - public InsightsQuestionnairesUpdater setQuestionSids( - final String questionSids - ) { + public InsightsQuestionnairesUpdater setQuestionSids(final String questionSids) { return setQuestionSids(Promoter.listOfOne(questionSids)); } + public InsightsQuestionnairesUpdater setAuthorization(final String authorization) { + this.authorization = authorization; + return this; + } + + @Override public InsightsQuestionnaires update(final TwilioRestClient client) { - String path = - "/v1/Insights/QualityManagement/Questionnaires/{QuestionnaireSid}"; - path = - path.replace( - "{" + "QuestionnaireSid" + "}", - this.pathQuestionnaireSid.toString() - ); - path = path.replace("{" + "Active" + "}", this.active.toString()); + String path = "/v1/Insights/QualityManagement/Questionnaires/{QuestionnaireSid}"; + + path = path.replace("{" + "QuestionnaireSid" + "}", this.pathquestionnaireSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.FLEXAPI.toString(), - path + HttpMethod.POST, + Domains.FLEXAPI.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); - addPostParams(request); addHeaderParams(request); + addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "InsightsQuestionnaires update failed: Unable to connect to server" - ); + throw new ApiConnectionException("InsightsQuestionnaires update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return InsightsQuestionnaires.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return InsightsQuestionnaires.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (active != null) { - request.addPostParam("Active", active.toString()); + Serializer.toString(request, "Active", active, ParameterType.URLENCODED); } + + if (name != null) { - request.addPostParam("Name", name); + Serializer.toString(request, "Name", name, ParameterType.URLENCODED); } + + if (description != null) { - request.addPostParam("Description", description); + Serializer.toString(request, "Description", description, ParameterType.URLENCODED); } + + if (questionSids != null) { - for (String prop : questionSids) { - request.addPostParam("QuestionSids", prop); + for (String param : questionSids) { + Serializer.toString(request, "QuestionSids", param, ParameterType.URLENCODED); } } + } private void addHeaderParams(final Request request) { + if (authorization != null) { - request.addHeaderParam("Authorization", authorization); + Serializer.toString(request, "Authorization", authorization, ParameterType.HEADER); } + } } diff --git a/src/main/java/com/twilio/rest/flexapi/v1/InsightsSegments.java b/src/main/java/com/twilio/rest/flexapi/v1/InsightsSegments.java index b350c401cb..0fb484866e 100644 --- a/src/main/java/com/twilio/rest/flexapi/v1/InsightsSegments.java +++ b/src/main/java/com/twilio/rest/flexapi/v1/InsightsSegments.java @@ -18,41 +18,40 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; -import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class InsightsSegments extends Resource { - private static final long serialVersionUID = 85034429282364L; public static InsightsSegmentsReader reader() { - return new InsightsSegmentsReader(); + return new InsightsSegmentsReader( + + ); } + /** * Converts a JSON String into a InsightsSegments object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return InsightsSegments object represented by the provided JSON */ - public static InsightsSegments fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static InsightsSegments fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, InsightsSegments.class); @@ -67,14 +66,11 @@ public static InsightsSegments fromJson( * Converts a JSON InputStream into a InsightsSegments object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return InsightsSegments object represented by the provided JSON */ - public static InsightsSegments fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static InsightsSegments fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, InsightsSegments.class); @@ -85,178 +81,113 @@ public static InsightsSegments fromJson( } } - private final String segmentId; - private final String externalId; - private final String queue; - private final String externalContact; - private final String externalSegmentLinkId; - private final String date; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountId; - private final String externalSegmentLink; + @Getter private final String agentId; - private final String agentPhone; + @Getter + private final String agentLink; + @Getter private final String agentName; + @Getter + private final String agentPhone; + @Getter private final String agentTeamName; + @Getter private final String agentTeamNameInHierarchy; - private final String agentLink; - private final String customerPhone; - private final String customerName; + @Getter + private final Object assessmentPercentage; + @Getter + private final Object assessmentType; + @Getter private final String customerLink; + @Getter + private final String customerName; + @Getter + private final String customerPhone; + @Getter + private final String date; + @Getter + private final String externalContact; + @Getter + private final String externalId; + @Getter + private final String externalSegmentLink; + @Getter + private final String externalSegmentLinkId; + @Getter + private final Object media; + @Getter + private final String queue; + @Getter + private final String segmentId; + @Getter private final String segmentRecordingOffset; - private final Map media; - private final Map assessmentType; - private final Map assessmentPercentage; + @Getter private final URI url; @JsonCreator private InsightsSegments( - @JsonProperty("segment_id") final String segmentId, - @JsonProperty("external_id") final String externalId, - @JsonProperty("queue") final String queue, - @JsonProperty("external_contact") final String externalContact, - @JsonProperty( - "external_segment_link_id" - ) final String externalSegmentLinkId, - @JsonProperty("date") final String date, - @JsonProperty("account_id") final String accountId, - @JsonProperty("external_segment_link") final String externalSegmentLink, - @JsonProperty("agent_id") final String agentId, - @JsonProperty("agent_phone") final String agentPhone, - @JsonProperty("agent_name") final String agentName, - @JsonProperty("agent_team_name") final String agentTeamName, - @JsonProperty( - "agent_team_name_in_hierarchy" - ) final String agentTeamNameInHierarchy, - @JsonProperty("agent_link") final String agentLink, - @JsonProperty("customer_phone") final String customerPhone, - @JsonProperty("customer_name") final String customerName, - @JsonProperty("customer_link") final String customerLink, - @JsonProperty( - "segment_recording_offset" - ) final String segmentRecordingOffset, - @JsonProperty("media") final Map media, - @JsonProperty("assessment_type") final Map< - String, - Object - > assessmentType, - @JsonProperty("assessment_percentage") final Map< - String, - Object - > assessmentPercentage, - @JsonProperty("url") final URI url + @JsonProperty("account_id") final String accountId, + @JsonProperty("agent_id") final String agentId, + @JsonProperty("agent_link") final String agentLink, + @JsonProperty("agent_name") final String agentName, + @JsonProperty("agent_phone") final String agentPhone, + @JsonProperty("agent_team_name") final String agentTeamName, + @JsonProperty("agent_team_name_in_hierarchy") final String agentTeamNameInHierarchy, + @JsonProperty("assessment_percentage") final Object assessmentPercentage, + @JsonProperty("assessment_type") final Object assessmentType, + @JsonProperty("customer_link") final String customerLink, + @JsonProperty("customer_name") final String customerName, + @JsonProperty("customer_phone") final String customerPhone, + @JsonProperty("date") final String date, + @JsonProperty("external_contact") final String externalContact, + @JsonProperty("external_id") final String externalId, + @JsonProperty("external_segment_link") final String externalSegmentLink, + @JsonProperty("external_segment_link_id") final String externalSegmentLinkId, + @JsonProperty("media") final Object media, + @JsonProperty("queue") final String queue, + @JsonProperty("segment_id") final String segmentId, + @JsonProperty("segment_recording_offset") final String segmentRecordingOffset, + @JsonProperty("url") final URI url ) { - this.segmentId = segmentId; - this.externalId = externalId; - this.queue = queue; - this.externalContact = externalContact; - this.externalSegmentLinkId = externalSegmentLinkId; - this.date = date; this.accountId = accountId; - this.externalSegmentLink = externalSegmentLink; this.agentId = agentId; - this.agentPhone = agentPhone; + this.agentLink = agentLink; this.agentName = agentName; + this.agentPhone = agentPhone; this.agentTeamName = agentTeamName; this.agentTeamNameInHierarchy = agentTeamNameInHierarchy; - this.agentLink = agentLink; - this.customerPhone = customerPhone; - this.customerName = customerName; + this.assessmentPercentage = assessmentPercentage; + this.assessmentType = assessmentType; this.customerLink = customerLink; - this.segmentRecordingOffset = segmentRecordingOffset; + this.customerName = customerName; + this.customerPhone = customerPhone; + this.date = date; + this.externalContact = externalContact; + this.externalId = externalId; + this.externalSegmentLink = externalSegmentLink; + this.externalSegmentLinkId = externalSegmentLinkId; this.media = media; - this.assessmentType = assessmentType; - this.assessmentPercentage = assessmentPercentage; + this.queue = queue; + this.segmentId = segmentId; + this.segmentRecordingOffset = segmentRecordingOffset; this.url = url; } - public final String getSegmentId() { - return this.segmentId; - } - - public final String getExternalId() { - return this.externalId; - } - - public final String getQueue() { - return this.queue; - } - - public final String getExternalContact() { - return this.externalContact; - } - - public final String getExternalSegmentLinkId() { - return this.externalSegmentLinkId; - } - - public final String getDate() { - return this.date; - } - - public final String getAccountId() { - return this.accountId; - } - - public final String getExternalSegmentLink() { - return this.externalSegmentLink; - } - - public final String getAgentId() { - return this.agentId; - } - - public final String getAgentPhone() { - return this.agentPhone; - } - - public final String getAgentName() { - return this.agentName; - } - - public final String getAgentTeamName() { - return this.agentTeamName; - } - - public final String getAgentTeamNameInHierarchy() { - return this.agentTeamNameInHierarchy; - } - - public final String getAgentLink() { - return this.agentLink; - } - - public final String getCustomerPhone() { - return this.customerPhone; - } - - public final String getCustomerName() { - return this.customerName; - } - - public final String getCustomerLink() { - return this.customerLink; - } - - public final String getSegmentRecordingOffset() { - return this.segmentRecordingOffset; - } - - public final Map getMedia() { - return this.media; - } - - public final Map getAssessmentType() { - return this.assessmentType; - } - - public final Map getAssessmentPercentage() { - return this.assessmentPercentage; - } - - public final URI getUrl() { - return this.url; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -268,67 +199,60 @@ public boolean equals(final Object o) { } InsightsSegments other = (InsightsSegments) o; - return ( - Objects.equals(segmentId, other.segmentId) && - Objects.equals(externalId, other.externalId) && - Objects.equals(queue, other.queue) && - Objects.equals(externalContact, other.externalContact) && - Objects.equals( - externalSegmentLinkId, - other.externalSegmentLinkId - ) && - Objects.equals(date, other.date) && - Objects.equals(accountId, other.accountId) && - Objects.equals(externalSegmentLink, other.externalSegmentLink) && - Objects.equals(agentId, other.agentId) && - Objects.equals(agentPhone, other.agentPhone) && - Objects.equals(agentName, other.agentName) && - Objects.equals(agentTeamName, other.agentTeamName) && - Objects.equals( - agentTeamNameInHierarchy, - other.agentTeamNameInHierarchy - ) && - Objects.equals(agentLink, other.agentLink) && - Objects.equals(customerPhone, other.customerPhone) && - Objects.equals(customerName, other.customerName) && - Objects.equals(customerLink, other.customerLink) && - Objects.equals( - segmentRecordingOffset, - other.segmentRecordingOffset - ) && - Objects.equals(media, other.media) && - Objects.equals(assessmentType, other.assessmentType) && - Objects.equals(assessmentPercentage, other.assessmentPercentage) && - Objects.equals(url, other.url) + Objects.equals(accountId, other.accountId) && + Objects.equals(agentId, other.agentId) && + Objects.equals(agentLink, other.agentLink) && + Objects.equals(agentName, other.agentName) && + Objects.equals(agentPhone, other.agentPhone) && + Objects.equals(agentTeamName, other.agentTeamName) && + Objects.equals(agentTeamNameInHierarchy, other.agentTeamNameInHierarchy) && + Objects.equals(assessmentPercentage, other.assessmentPercentage) && + Objects.equals(assessmentType, other.assessmentType) && + Objects.equals(customerLink, other.customerLink) && + Objects.equals(customerName, other.customerName) && + Objects.equals(customerPhone, other.customerPhone) && + Objects.equals(date, other.date) && + Objects.equals(externalContact, other.externalContact) && + Objects.equals(externalId, other.externalId) && + Objects.equals(externalSegmentLink, other.externalSegmentLink) && + Objects.equals(externalSegmentLinkId, other.externalSegmentLinkId) && + Objects.equals(media, other.media) && + Objects.equals(queue, other.queue) && + Objects.equals(segmentId, other.segmentId) && + Objects.equals(segmentRecordingOffset, other.segmentRecordingOffset) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - segmentId, - externalId, - queue, - externalContact, - externalSegmentLinkId, - date, - accountId, - externalSegmentLink, - agentId, - agentPhone, - agentName, - agentTeamName, - agentTeamNameInHierarchy, - agentLink, - customerPhone, - customerName, - customerLink, - segmentRecordingOffset, - media, - assessmentType, - assessmentPercentage, - url + accountId, + agentId, + agentLink, + agentName, + agentPhone, + agentTeamName, + agentTeamNameInHierarchy, + assessmentPercentage, + assessmentType, + customerLink, + customerName, + customerPhone, + date, + externalContact, + externalId, + externalSegmentLink, + externalSegmentLinkId, + media, + queue, + segmentId, + segmentRecordingOffset, + url ); } + + } + diff --git a/src/main/java/com/twilio/rest/flexapi/v1/InsightsSegmentsReader.java b/src/main/java/com/twilio/rest/flexapi/v1/InsightsSegmentsReader.java index 97a793dbef..1a2ccfea6e 100644 --- a/src/main/java/com/twilio/rest/flexapi/v1/InsightsSegmentsReader.java +++ b/src/main/java/com/twilio/rest/flexapi/v1/InsightsSegmentsReader.java @@ -17,8 +17,9 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; import com.twilio.converter.Promoter; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,30 +28,27 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.util.List; public class InsightsSegmentsReader extends Reader { - private String authorization; private String segmentId; private List reservationId; private Long pageSize; + private String authorization; - public InsightsSegmentsReader() {} - - public InsightsSegmentsReader setAuthorization(final String authorization) { - this.authorization = authorization; - return this; + public InsightsSegmentsReader() { } + public InsightsSegmentsReader setSegmentId(final String segmentId) { this.segmentId = segmentId; return this; } - public InsightsSegmentsReader setReservationId( - final List reservationId - ) { + + public InsightsSegmentsReader setReservationId(final List reservationId) { this.reservationId = reservationId; return this; } @@ -64,113 +62,101 @@ public InsightsSegmentsReader setPageSize(final Long pageSize) { return this; } + + public InsightsSegmentsReader setAuthorization(final String authorization) { + this.authorization = authorization; + return this; + } + + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/Insights/Segments"; + Request request = new Request( - HttpMethod.GET, - Domains.FLEXAPI.toString(), - path + HttpMethod.GET, + Domains.FLEXAPI.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addHeaderParams(request); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "InsightsSegments read failed: Unable to connect to server" - ); + throw new ApiConnectionException("InsightsSegments read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "segments", - response.getContent(), - InsightsSegments.class, - client.getObjectMapper() - ); + "segments", + response.getContent(), + InsightsSegments.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.FLEXAPI.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.FLEXAPI.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } - private void addHeaderParams(final Request request) { - if (authorization != null) { - request.addHeaderParam("Authorization", authorization); - } - } - private void addQueryParams(final Request request) { + + if (segmentId != null) { - request.addQueryParam("SegmentId", segmentId); + Serializer.toString(request, "SegmentId", segmentId, ParameterType.QUERY); } + + if (reservationId != null) { - for (String prop : reservationId) { - request.addQueryParam("ReservationId", prop); + for (String param : reservationId) { + Serializer.toString(request, "ReservationId", param, ParameterType.QUERY); } } + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); + + } + + private void addHeaderParams(final Request request) { + + if (authorization != null) { + Serializer.toString(request, "Authorization", authorization, ParameterType.HEADER); } + } } diff --git a/src/main/java/com/twilio/rest/flexapi/v1/InsightsSession.java b/src/main/java/com/twilio/rest/flexapi/v1/InsightsSession.java index 648283e6e7..c999da8d9b 100644 --- a/src/main/java/com/twilio/rest/flexapi/v1/InsightsSession.java +++ b/src/main/java/com/twilio/rest/flexapi/v1/InsightsSession.java @@ -18,39 +18,40 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class InsightsSession extends Resource { - private static final long serialVersionUID = 184746612300929L; public static InsightsSessionCreator creator() { - return new InsightsSessionCreator(); + return new InsightsSessionCreator( + + ); } + /** * Converts a JSON String into a InsightsSession object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return InsightsSession object represented by the provided JSON */ - public static InsightsSession fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static InsightsSession fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, InsightsSession.class); @@ -65,14 +66,11 @@ public static InsightsSession fromJson( * Converts a JSON InputStream into a InsightsSession object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return InsightsSession object represented by the provided JSON */ - public static InsightsSession fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static InsightsSession fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, InsightsSession.class); @@ -83,45 +81,43 @@ public static InsightsSession fromJson( } } - private final String workspaceId; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter + private final String baseUrl; + @Getter private final String sessionExpiry; + @Getter private final String sessionId; - private final String baseUrl; + @Getter private final URI url; + @Getter + private final String workspaceId; @JsonCreator private InsightsSession( - @JsonProperty("workspace_id") final String workspaceId, - @JsonProperty("session_expiry") final String sessionExpiry, - @JsonProperty("session_id") final String sessionId, - @JsonProperty("base_url") final String baseUrl, - @JsonProperty("url") final URI url + @JsonProperty("base_url") final String baseUrl, + @JsonProperty("session_expiry") final String sessionExpiry, + @JsonProperty("session_id") final String sessionId, + @JsonProperty("url") final URI url, + @JsonProperty("workspace_id") final String workspaceId ) { - this.workspaceId = workspaceId; + this.baseUrl = baseUrl; this.sessionExpiry = sessionExpiry; this.sessionId = sessionId; - this.baseUrl = baseUrl; this.url = url; - } - - public final String getWorkspaceId() { - return this.workspaceId; - } - - public final String getSessionExpiry() { - return this.sessionExpiry; - } - - public final String getSessionId() { - return this.sessionId; - } - - public final String getBaseUrl() { - return this.baseUrl; - } - - public final URI getUrl() { - return this.url; + this.workspaceId = workspaceId; } @Override @@ -135,24 +131,26 @@ public boolean equals(final Object o) { } InsightsSession other = (InsightsSession) o; - return ( - Objects.equals(workspaceId, other.workspaceId) && - Objects.equals(sessionExpiry, other.sessionExpiry) && - Objects.equals(sessionId, other.sessionId) && - Objects.equals(baseUrl, other.baseUrl) && - Objects.equals(url, other.url) + Objects.equals(baseUrl, other.baseUrl) && + Objects.equals(sessionExpiry, other.sessionExpiry) && + Objects.equals(sessionId, other.sessionId) && + Objects.equals(url, other.url) && + Objects.equals(workspaceId, other.workspaceId) ); } @Override public int hashCode() { return Objects.hash( - workspaceId, - sessionExpiry, - sessionId, - baseUrl, - url + baseUrl, + sessionExpiry, + sessionId, + url, + workspaceId ); } + + } + diff --git a/src/main/java/com/twilio/rest/flexapi/v1/InsightsSessionCreator.java b/src/main/java/com/twilio/rest/flexapi/v1/InsightsSessionCreator.java index 4e93d84947..9178c9a034 100644 --- a/src/main/java/com/twilio/rest/flexapi/v1/InsightsSessionCreator.java +++ b/src/main/java/com/twilio/rest/flexapi/v1/InsightsSessionCreator.java @@ -14,8 +14,10 @@ package com.twilio.rest.flexapi.v1; + import com.twilio.base.Creator; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,52 +31,52 @@ public class InsightsSessionCreator extends Creator { private String authorization; - public InsightsSessionCreator() {} + public InsightsSessionCreator() { + } + public InsightsSessionCreator setAuthorization(final String authorization) { this.authorization = authorization; return this; } + @Override public InsightsSession create(final TwilioRestClient client) { + String path = "/v1/Insights/Session"; + Request request = new Request( - HttpMethod.POST, - Domains.FLEXAPI.toString(), - path + HttpMethod.POST, + Domains.FLEXAPI.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addHeaderParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "InsightsSession creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("InsightsSession creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return InsightsSession.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return InsightsSession.fromJson(response.getStream(), client.getObjectMapper()); } private void addHeaderParams(final Request request) { + if (authorization != null) { - request.addHeaderParam("Authorization", authorization); + Serializer.toString(request, "Authorization", authorization, ParameterType.HEADER); } + } } diff --git a/src/main/java/com/twilio/rest/flexapi/v1/InsightsSettingsAnswerSets.java b/src/main/java/com/twilio/rest/flexapi/v1/InsightsSettingsAnswerSets.java index bb24d95eb5..9f01863e0e 100644 --- a/src/main/java/com/twilio/rest/flexapi/v1/InsightsSettingsAnswerSets.java +++ b/src/main/java/com/twilio/rest/flexapi/v1/InsightsSettingsAnswerSets.java @@ -18,47 +18,43 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; -import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class InsightsSettingsAnswerSets extends Resource { - private static final long serialVersionUID = 252326702169213L; public static InsightsSettingsAnswerSetsFetcher fetcher() { - return new InsightsSettingsAnswerSetsFetcher(); + return new InsightsSettingsAnswerSetsFetcher( + + ); } + /** * Converts a JSON String into a InsightsSettingsAnswerSets object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return InsightsSettingsAnswerSets object represented by the provided JSON */ - public static InsightsSettingsAnswerSets fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static InsightsSettingsAnswerSets fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { - return objectMapper.readValue( - json, - InsightsSettingsAnswerSets.class - ); + return objectMapper.readValue(json, InsightsSettingsAnswerSets.class); } catch (final JsonMappingException | JsonParseException e) { throw new ApiException(e.getMessage(), e); } catch (final IOException e) { @@ -70,20 +66,14 @@ public static InsightsSettingsAnswerSets fromJson( * Converts a JSON InputStream into a InsightsSettingsAnswerSets object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return InsightsSettingsAnswerSets object represented by the provided JSON */ - public static InsightsSettingsAnswerSets fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static InsightsSettingsAnswerSets fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { - return objectMapper.readValue( - json, - InsightsSettingsAnswerSets.class - ); + return objectMapper.readValue(json, InsightsSettingsAnswerSets.class); } catch (final JsonMappingException | JsonParseException e) { throw new ApiException(e.getMessage(), e); } catch (final IOException e) { @@ -91,50 +81,45 @@ public static InsightsSettingsAnswerSets fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final Map answerSets; - private final Map answerSetCategories; - private final Map notApplicable; + @Getter + private final Object answerSetCategories; + @Getter + private final Object answerSets; + @Getter + private final Object notApplicable; + @Getter private final URI url; @JsonCreator private InsightsSettingsAnswerSets( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("answer_sets") final Map answerSets, - @JsonProperty("answer_set_categories") final Map< - String, - Object - > answerSetCategories, - @JsonProperty("not_applicable") final Map notApplicable, - @JsonProperty("url") final URI url + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("answer_set_categories") final Object answerSetCategories, + @JsonProperty("answer_sets") final Object answerSets, + @JsonProperty("not_applicable") final Object notApplicable, + @JsonProperty("url") final URI url ) { this.accountSid = accountSid; - this.answerSets = answerSets; this.answerSetCategories = answerSetCategories; + this.answerSets = answerSets; this.notApplicable = notApplicable; this.url = url; } - public final String getAccountSid() { - return this.accountSid; - } - - public final Map getAnswerSets() { - return this.answerSets; - } - - public final Map getAnswerSetCategories() { - return this.answerSetCategories; - } - - public final Map getNotApplicable() { - return this.notApplicable; - } - - public final URI getUrl() { - return this.url; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -146,24 +131,26 @@ public boolean equals(final Object o) { } InsightsSettingsAnswerSets other = (InsightsSettingsAnswerSets) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(answerSets, other.answerSets) && - Objects.equals(answerSetCategories, other.answerSetCategories) && - Objects.equals(notApplicable, other.notApplicable) && - Objects.equals(url, other.url) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(answerSetCategories, other.answerSetCategories) && + Objects.equals(answerSets, other.answerSets) && + Objects.equals(notApplicable, other.notApplicable) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - accountSid, - answerSets, - answerSetCategories, - notApplicable, - url + accountSid, + answerSetCategories, + answerSets, + notApplicable, + url ); } + + } + diff --git a/src/main/java/com/twilio/rest/flexapi/v1/InsightsSettingsAnswerSetsFetcher.java b/src/main/java/com/twilio/rest/flexapi/v1/InsightsSettingsAnswerSetsFetcher.java index e78b56ea1e..c3b6353c51 100644 --- a/src/main/java/com/twilio/rest/flexapi/v1/InsightsSettingsAnswerSetsFetcher.java +++ b/src/main/java/com/twilio/rest/flexapi/v1/InsightsSettingsAnswerSetsFetcher.java @@ -15,7 +15,8 @@ package com.twilio.rest.flexapi.v1; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,60 +26,55 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class InsightsSettingsAnswerSetsFetcher - extends Fetcher { +public class InsightsSettingsAnswerSetsFetcher extends Fetcher { private String authorization; - public InsightsSettingsAnswerSetsFetcher() {} + public InsightsSettingsAnswerSetsFetcher() { + } + - public InsightsSettingsAnswerSetsFetcher setAuthorization( - final String authorization - ) { + public InsightsSettingsAnswerSetsFetcher setAuthorization(final String authorization) { this.authorization = authorization; return this; } + @Override public InsightsSettingsAnswerSets fetch(final TwilioRestClient client) { + String path = "/v1/Insights/QualityManagement/Settings/AnswerSets"; + Request request = new Request( - HttpMethod.GET, - Domains.FLEXAPI.toString(), - path + HttpMethod.GET, + Domains.FLEXAPI.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addHeaderParams(request); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "InsightsSettingsAnswerSets fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("InsightsSettingsAnswerSets fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return InsightsSettingsAnswerSets.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return InsightsSettingsAnswerSets.fromJson(response.getStream(), client.getObjectMapper()); } private void addHeaderParams(final Request request) { + if (authorization != null) { - request.addHeaderParam("Authorization", authorization); + Serializer.toString(request, "Authorization", authorization, ParameterType.HEADER); } + } } diff --git a/src/main/java/com/twilio/rest/flexapi/v1/InsightsSettingsComment.java b/src/main/java/com/twilio/rest/flexapi/v1/InsightsSettingsComment.java index 90afe4c870..2face9278d 100644 --- a/src/main/java/com/twilio/rest/flexapi/v1/InsightsSettingsComment.java +++ b/src/main/java/com/twilio/rest/flexapi/v1/InsightsSettingsComment.java @@ -18,41 +18,40 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; -import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class InsightsSettingsComment extends Resource { - private static final long serialVersionUID = 241533672645071L; public static InsightsSettingsCommentFetcher fetcher() { - return new InsightsSettingsCommentFetcher(); + return new InsightsSettingsCommentFetcher( + + ); } + /** * Converts a JSON String into a InsightsSettingsComment object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return InsightsSettingsComment object represented by the provided JSON */ - public static InsightsSettingsComment fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static InsightsSettingsComment fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, InsightsSettingsComment.class); @@ -67,14 +66,11 @@ public static InsightsSettingsComment fromJson( * Converts a JSON InputStream into a InsightsSettingsComment object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return InsightsSettingsComment object represented by the provided JSON */ - public static InsightsSettingsComment fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static InsightsSettingsComment fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, InsightsSettingsComment.class); @@ -85,33 +81,37 @@ public static InsightsSettingsComment fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final Map comments; + @Getter + private final Object comments; + @Getter private final URI url; @JsonCreator private InsightsSettingsComment( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("comments") final Map comments, - @JsonProperty("url") final URI url + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("comments") final Object comments, + @JsonProperty("url") final URI url ) { this.accountSid = accountSid; this.comments = comments; this.url = url; } - public final String getAccountSid() { - return this.accountSid; - } - - public final Map getComments() { - return this.comments; - } - - public final URI getUrl() { - return this.url; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -123,16 +123,22 @@ public boolean equals(final Object o) { } InsightsSettingsComment other = (InsightsSettingsComment) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(comments, other.comments) && - Objects.equals(url, other.url) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(comments, other.comments) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { - return Objects.hash(accountSid, comments, url); + return Objects.hash( + accountSid, + comments, + url + ); } + + } + diff --git a/src/main/java/com/twilio/rest/flexapi/v1/InsightsSettingsCommentFetcher.java b/src/main/java/com/twilio/rest/flexapi/v1/InsightsSettingsCommentFetcher.java index 06985e4856..09febda027 100644 --- a/src/main/java/com/twilio/rest/flexapi/v1/InsightsSettingsCommentFetcher.java +++ b/src/main/java/com/twilio/rest/flexapi/v1/InsightsSettingsCommentFetcher.java @@ -15,7 +15,8 @@ package com.twilio.rest.flexapi.v1; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,60 +26,55 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class InsightsSettingsCommentFetcher - extends Fetcher { +public class InsightsSettingsCommentFetcher extends Fetcher { private String authorization; - public InsightsSettingsCommentFetcher() {} + public InsightsSettingsCommentFetcher() { + } + - public InsightsSettingsCommentFetcher setAuthorization( - final String authorization - ) { + public InsightsSettingsCommentFetcher setAuthorization(final String authorization) { this.authorization = authorization; return this; } + @Override public InsightsSettingsComment fetch(final TwilioRestClient client) { + String path = "/v1/Insights/QualityManagement/Settings/CommentTags"; + Request request = new Request( - HttpMethod.GET, - Domains.FLEXAPI.toString(), - path + HttpMethod.GET, + Domains.FLEXAPI.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addHeaderParams(request); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "InsightsSettingsComment fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("InsightsSettingsComment fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return InsightsSettingsComment.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return InsightsSettingsComment.fromJson(response.getStream(), client.getObjectMapper()); } private void addHeaderParams(final Request request) { + if (authorization != null) { - request.addHeaderParam("Authorization", authorization); + Serializer.toString(request, "Authorization", authorization, ParameterType.HEADER); } + } } diff --git a/src/main/java/com/twilio/rest/flexapi/v1/InsightsUserRoles.java b/src/main/java/com/twilio/rest/flexapi/v1/InsightsUserRoles.java index f9a82520c0..c5cede9ef7 100644 --- a/src/main/java/com/twilio/rest/flexapi/v1/InsightsUserRoles.java +++ b/src/main/java/com/twilio/rest/flexapi/v1/InsightsUserRoles.java @@ -18,40 +18,41 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.util.List; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class InsightsUserRoles extends Resource { - private static final long serialVersionUID = 154216272914379L; public static InsightsUserRolesFetcher fetcher() { - return new InsightsUserRolesFetcher(); + return new InsightsUserRolesFetcher( + + ); } + /** * Converts a JSON String into a InsightsUserRoles object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return InsightsUserRoles object represented by the provided JSON */ - public static InsightsUserRoles fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static InsightsUserRoles fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, InsightsUserRoles.class); @@ -66,14 +67,11 @@ public static InsightsUserRoles fromJson( * Converts a JSON InputStream into a InsightsUserRoles object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return InsightsUserRoles object represented by the provided JSON */ - public static InsightsUserRoles fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static InsightsUserRoles fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, InsightsUserRoles.class); @@ -84,26 +82,33 @@ public static InsightsUserRoles fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final List roles; + @Getter private final URI url; @JsonCreator private InsightsUserRoles( - @JsonProperty("roles") final List roles, - @JsonProperty("url") final URI url + @JsonProperty("roles") final List roles, + @JsonProperty("url") final URI url ) { this.roles = roles; this.url = url; } - public final List getRoles() { - return this.roles; - } - - public final URI getUrl() { - return this.url; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -115,14 +120,20 @@ public boolean equals(final Object o) { } InsightsUserRoles other = (InsightsUserRoles) o; - return ( - Objects.equals(roles, other.roles) && Objects.equals(url, other.url) + Objects.equals(roles, other.roles) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { - return Objects.hash(roles, url); + return Objects.hash( + roles, + url + ); } + + } + diff --git a/src/main/java/com/twilio/rest/flexapi/v1/InsightsUserRolesFetcher.java b/src/main/java/com/twilio/rest/flexapi/v1/InsightsUserRolesFetcher.java index 0fabd9e5aa..0601fe6623 100644 --- a/src/main/java/com/twilio/rest/flexapi/v1/InsightsUserRolesFetcher.java +++ b/src/main/java/com/twilio/rest/flexapi/v1/InsightsUserRolesFetcher.java @@ -15,7 +15,8 @@ package com.twilio.rest.flexapi.v1; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,55 +30,51 @@ public class InsightsUserRolesFetcher extends Fetcher { private String authorization; - public InsightsUserRolesFetcher() {} + public InsightsUserRolesFetcher() { + } + - public InsightsUserRolesFetcher setAuthorization( - final String authorization - ) { + public InsightsUserRolesFetcher setAuthorization(final String authorization) { this.authorization = authorization; return this; } + @Override public InsightsUserRoles fetch(final TwilioRestClient client) { + String path = "/v1/Insights/UserRoles"; + Request request = new Request( - HttpMethod.GET, - Domains.FLEXAPI.toString(), - path + HttpMethod.GET, + Domains.FLEXAPI.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addHeaderParams(request); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "InsightsUserRoles fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("InsightsUserRoles fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return InsightsUserRoles.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return InsightsUserRoles.fromJson(response.getStream(), client.getObjectMapper()); } private void addHeaderParams(final Request request) { + if (authorization != null) { - request.addHeaderParam("Authorization", authorization); + Serializer.toString(request, "Authorization", authorization, ParameterType.HEADER); } + } } diff --git a/src/main/java/com/twilio/rest/flexapi/v1/Interaction.java b/src/main/java/com/twilio/rest/flexapi/v1/Interaction.java index 99af3da8ff..ad987fdbc1 100644 --- a/src/main/java/com/twilio/rest/flexapi/v1/Interaction.java +++ b/src/main/java/com/twilio/rest/flexapi/v1/Interaction.java @@ -18,49 +18,55 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Interaction extends Resource { - private static final long serialVersionUID = 256485735361091L; public static InteractionCreator creator(final Object channel) { - return new InteractionCreator(channel); + return new InteractionCreator( + channel + ); } - public static InteractionFetcher fetcher(final String pathSid) { - return new InteractionFetcher(pathSid); + + public static InteractionFetcher fetcher(final String pathsid) { + return new InteractionFetcher( + pathsid + ); } - public static InteractionUpdater updater(final String pathSid) { - return new InteractionUpdater(pathSid); + + public static InteractionUpdater updater(final String pathsid) { + return new InteractionUpdater( + pathsid + ); } + /** * Converts a JSON String into a Interaction object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Interaction object represented by the provided JSON */ - public static Interaction fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Interaction fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Interaction.class); @@ -75,14 +81,11 @@ public static Interaction fromJson( * Converts a JSON InputStream into a Interaction object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Interaction object represented by the provided JSON */ - public static Interaction fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Interaction fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Interaction.class); @@ -93,63 +96,53 @@ public static Interaction fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter + private final Object channel; + @Getter + private final String interactionContextSid; + @Getter + private final Map links; + @Getter + private final Object routing; + @Getter private final String sid; - private final Map channel; - private final Map routing; + @Getter private final URI url; - private final Map links; - private final String interactionContextSid; + @Getter private final String webhookTtid; @JsonCreator private Interaction( - @JsonProperty("sid") final String sid, - @JsonProperty("channel") final Map channel, - @JsonProperty("routing") final Map routing, - @JsonProperty("url") final URI url, - @JsonProperty("links") final Map links, - @JsonProperty( - "interaction_context_sid" - ) final String interactionContextSid, - @JsonProperty("webhook_ttid") final String webhookTtid + @JsonProperty("channel") final Object channel, + @JsonProperty("interaction_context_sid") final String interactionContextSid, + @JsonProperty("links") final Map links, + @JsonProperty("routing") final Object routing, + @JsonProperty("sid") final String sid, + @JsonProperty("url") final URI url, + @JsonProperty("webhook_ttid") final String webhookTtid ) { - this.sid = sid; this.channel = channel; + this.interactionContextSid = interactionContextSid; + this.links = links; this.routing = routing; + this.sid = sid; this.url = url; - this.links = links; - this.interactionContextSid = interactionContextSid; this.webhookTtid = webhookTtid; } - public final String getSid() { - return this.sid; - } - - public final Map getChannel() { - return this.channel; - } - - public final Map getRouting() { - return this.routing; - } - - public final URI getUrl() { - return this.url; - } - - public final Map getLinks() { - return this.links; - } - - public final String getInteractionContextSid() { - return this.interactionContextSid; - } - - public final String getWebhookTtid() { - return this.webhookTtid; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -161,31 +154,30 @@ public boolean equals(final Object o) { } Interaction other = (Interaction) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(channel, other.channel) && - Objects.equals(routing, other.routing) && - Objects.equals(url, other.url) && - Objects.equals(links, other.links) && - Objects.equals( - interactionContextSid, - other.interactionContextSid - ) && - Objects.equals(webhookTtid, other.webhookTtid) + Objects.equals(channel, other.channel) && + Objects.equals(interactionContextSid, other.interactionContextSid) && + Objects.equals(links, other.links) && + Objects.equals(routing, other.routing) && + Objects.equals(sid, other.sid) && + Objects.equals(url, other.url) && + Objects.equals(webhookTtid, other.webhookTtid) ); } @Override public int hashCode() { return Objects.hash( - sid, - channel, - routing, - url, - links, - interactionContextSid, - webhookTtid + channel, + interactionContextSid, + links, + routing, + sid, + url, + webhookTtid ); } + + } + diff --git a/src/main/java/com/twilio/rest/flexapi/v1/InteractionCreator.java b/src/main/java/com/twilio/rest/flexapi/v1/InteractionCreator.java index 4ac64c4b4a..479a9e99a7 100644 --- a/src/main/java/com/twilio/rest/flexapi/v1/InteractionCreator.java +++ b/src/main/java/com/twilio/rest/flexapi/v1/InteractionCreator.java @@ -14,10 +14,11 @@ package com.twilio.rest.flexapi.v1; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; -import com.twilio.converter.Converter; -import com.twilio.converter.Converter; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -38,81 +39,84 @@ public InteractionCreator(final Object channel) { this.channel = channel; } + public InteractionCreator setChannel(final Object channel) { this.channel = channel; return this; } + public InteractionCreator setRouting(final Object routing) { this.routing = routing; return this; } - public InteractionCreator setInteractionContextSid( - final String interactionContextSid - ) { + + public InteractionCreator setInteractionContextSid(final String interactionContextSid) { this.interactionContextSid = interactionContextSid; return this; } + public InteractionCreator setWebhookTtid(final String webhookTtid) { this.webhookTtid = webhookTtid; return this; } + @Override public Interaction create(final TwilioRestClient client) { + String path = "/v1/Interactions"; - path = path.replace("{" + "Channel" + "}", this.channel.toString()); Request request = new Request( - HttpMethod.POST, - Domains.FLEXAPI.toString(), - path + HttpMethod.POST, + Domains.FLEXAPI.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Interaction creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("Interaction creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Interaction.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Interaction.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (channel != null) { - request.addPostParam("Channel", Converter.objectToJson(channel)); + Serializer.toString(request, "Channel", channel, ParameterType.URLENCODED); } + + if (routing != null) { - request.addPostParam("Routing", Converter.objectToJson(routing)); + Serializer.toString(request, "Routing", routing, ParameterType.URLENCODED); } + + if (interactionContextSid != null) { - request.addPostParam( - "InteractionContextSid", - interactionContextSid - ); + Serializer.toString(request, "InteractionContextSid", interactionContextSid, ParameterType.URLENCODED); } + + if (webhookTtid != null) { - request.addPostParam("WebhookTtid", webhookTtid); + Serializer.toString(request, "WebhookTtid", webhookTtid, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/flexapi/v1/InteractionFetcher.java b/src/main/java/com/twilio/rest/flexapi/v1/InteractionFetcher.java index edbdb97d2d..5dcb88c2a9 100644 --- a/src/main/java/com/twilio/rest/flexapi/v1/InteractionFetcher.java +++ b/src/main/java/com/twilio/rest/flexapi/v1/InteractionFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.flexapi.v1; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,47 +26,41 @@ public class InteractionFetcher extends Fetcher { - private String pathSid; + private String pathsid; - public InteractionFetcher(final String pathSid) { - this.pathSid = pathSid; + public InteractionFetcher(final String pathsid) { + this.pathsid = pathsid; } + @Override public Interaction fetch(final TwilioRestClient client) { + String path = "/v1/Interactions/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.FLEXAPI.toString(), - path + HttpMethod.GET, + Domains.FLEXAPI.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Interaction fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Interaction fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return Interaction.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Interaction.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/flexapi/v1/InteractionUpdater.java b/src/main/java/com/twilio/rest/flexapi/v1/InteractionUpdater.java index 56c6dd4842..cc80ae00c1 100644 --- a/src/main/java/com/twilio/rest/flexapi/v1/InteractionUpdater.java +++ b/src/main/java/com/twilio/rest/flexapi/v1/InteractionUpdater.java @@ -16,6 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -26,60 +28,60 @@ import com.twilio.rest.Domains; public class InteractionUpdater extends Updater { - - private String pathSid; + private String pathsid; private String webhookTtid; - public InteractionUpdater(final String pathSid) { - this.pathSid = pathSid; + public InteractionUpdater(final String pathsid) { + this.pathsid = pathsid; } + public InteractionUpdater setWebhookTtid(final String webhookTtid) { this.webhookTtid = webhookTtid; return this; } + @Override public Interaction update(final TwilioRestClient client) { + String path = "/v1/Interactions/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.FLEXAPI.toString(), - path + HttpMethod.POST, + Domains.FLEXAPI.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Interaction update failed: Unable to connect to server" - ); + throw new ApiConnectionException("Interaction update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Interaction.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Interaction.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (webhookTtid != null) { - request.addPostParam("WebhookTtid", webhookTtid); + Serializer.toString(request, "WebhookTtid", webhookTtid, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/flexapi/v1/Plugin.java b/src/main/java/com/twilio/rest/flexapi/v1/Plugin.java index d750b08344..19b7d18e8f 100644 --- a/src/main/java/com/twilio/rest/flexapi/v1/Plugin.java +++ b/src/main/java/com/twilio/rest/flexapi/v1/Plugin.java @@ -18,55 +18,64 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Plugin extends Resource { - private static final long serialVersionUID = 14560759513120L; public static PluginCreator creator(final String uniqueName) { - return new PluginCreator(uniqueName); + return new PluginCreator( + uniqueName + ); } - public static PluginFetcher fetcher(final String pathSid) { - return new PluginFetcher(pathSid); + + public static PluginFetcher fetcher(final String pathsid) { + return new PluginFetcher( + pathsid + ); } + public static PluginReader reader() { - return new PluginReader(); + return new PluginReader( + + ); } - public static PluginUpdater updater(final String pathSid) { - return new PluginUpdater(pathSid); + + public static PluginUpdater updater(final String pathsid) { + return new PluginUpdater( + pathsid + ); } + /** * Converts a JSON String into a Plugin object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Plugin object represented by the provided JSON */ - public static Plugin fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Plugin fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Plugin.class); @@ -81,14 +90,11 @@ public static Plugin fromJson( * Converts a JSON InputStream into a Plugin object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Plugin object represented by the provided JSON */ - public static Plugin fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Plugin fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Plugin.class); @@ -99,80 +105,65 @@ public static Plugin fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String uniqueName; - private final String friendlyName; - private final String description; + @Getter private final Boolean archived; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; - private final URI url; + @Getter + private final String description; + @Getter + private final String friendlyName; + @Getter private final Map links; + @Getter + private final String sid; + @Getter + private final String uniqueName; + @Getter + private final URI url; @JsonCreator private Plugin( - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("unique_name") final String uniqueName, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("description") final String description, - @JsonProperty("archived") final Boolean archived, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("url") final URI url, - @JsonProperty("links") final Map links + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("archived") final Boolean archived, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("description") final String description, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("links") final Map links, + @JsonProperty("sid") final String sid, + @JsonProperty("unique_name") final String uniqueName, + @JsonProperty("url") final URI url ) { - this.sid = sid; this.accountSid = accountSid; - this.uniqueName = uniqueName; - this.friendlyName = friendlyName; - this.description = description; this.archived = archived; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); - this.url = url; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; + this.description = description; + this.friendlyName = friendlyName; this.links = links; - } - - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getUniqueName() { - return this.uniqueName; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final String getDescription() { - return this.description; - } - - public final Boolean getArchived() { - return this.archived; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final URI getUrl() { - return this.url; - } - - public final Map getLinks() { - return this.links; + this.sid = sid; + this.uniqueName = uniqueName; + this.url = url; } @Override @@ -186,34 +177,36 @@ public boolean equals(final Object o) { } Plugin other = (Plugin) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(uniqueName, other.uniqueName) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(description, other.description) && - Objects.equals(archived, other.archived) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(url, other.url) && - Objects.equals(links, other.links) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(archived, other.archived) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(description, other.description) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(links, other.links) && + Objects.equals(sid, other.sid) && + Objects.equals(uniqueName, other.uniqueName) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - sid, - accountSid, - uniqueName, - friendlyName, - description, - archived, - dateCreated, - dateUpdated, - url, - links + accountSid, + archived, + dateCreated, + dateUpdated, + description, + friendlyName, + links, + sid, + uniqueName, + url ); } + + } + diff --git a/src/main/java/com/twilio/rest/flexapi/v1/PluginArchive.java b/src/main/java/com/twilio/rest/flexapi/v1/PluginArchive.java index a97475f540..801d6d5923 100644 --- a/src/main/java/com/twilio/rest/flexapi/v1/PluginArchive.java +++ b/src/main/java/com/twilio/rest/flexapi/v1/PluginArchive.java @@ -18,41 +18,42 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class PluginArchive extends Resource { - private static final long serialVersionUID = 213623992989715L; - public static PluginArchiveUpdater updater(final String pathSid) { - return new PluginArchiveUpdater(pathSid); + public static PluginArchiveUpdater updater(final String pathsid) { + return new PluginArchiveUpdater( + pathsid + ); } + /** * Converts a JSON String into a PluginArchive object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return PluginArchive object represented by the provided JSON */ - public static PluginArchive fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static PluginArchive fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, PluginArchive.class); @@ -67,14 +68,11 @@ public static PluginArchive fromJson( * Converts a JSON InputStream into a PluginArchive object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return PluginArchive object represented by the provided JSON */ - public static PluginArchive fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static PluginArchive fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, PluginArchive.class); @@ -85,75 +83,63 @@ public static PluginArchive fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String uniqueName; - private final String friendlyName; - private final String description; + @Getter private final Boolean archived; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; + @Getter + private final String description; + @Getter + private final String friendlyName; + @Getter + private final String sid; + @Getter + private final String uniqueName; + @Getter private final URI url; @JsonCreator private PluginArchive( - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("unique_name") final String uniqueName, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("description") final String description, - @JsonProperty("archived") final Boolean archived, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("url") final URI url + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("archived") final Boolean archived, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("description") final String description, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("sid") final String sid, + @JsonProperty("unique_name") final String uniqueName, + @JsonProperty("url") final URI url ) { - this.sid = sid; this.accountSid = accountSid; - this.uniqueName = uniqueName; - this.friendlyName = friendlyName; - this.description = description; this.archived = archived; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; + this.description = description; + this.friendlyName = friendlyName; + this.sid = sid; + this.uniqueName = uniqueName; this.url = url; } - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getUniqueName() { - return this.uniqueName; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final String getDescription() { - return this.description; - } - - public final Boolean getArchived() { - return this.archived; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final URI getUrl() { - return this.url; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -165,32 +151,34 @@ public boolean equals(final Object o) { } PluginArchive other = (PluginArchive) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(uniqueName, other.uniqueName) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(description, other.description) && - Objects.equals(archived, other.archived) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(url, other.url) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(archived, other.archived) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(description, other.description) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(sid, other.sid) && + Objects.equals(uniqueName, other.uniqueName) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - sid, - accountSid, - uniqueName, - friendlyName, - description, - archived, - dateCreated, - dateUpdated, - url + accountSid, + archived, + dateCreated, + dateUpdated, + description, + friendlyName, + sid, + uniqueName, + url ); } + + } + diff --git a/src/main/java/com/twilio/rest/flexapi/v1/PluginArchiveUpdater.java b/src/main/java/com/twilio/rest/flexapi/v1/PluginArchiveUpdater.java index e7f26d76b5..c52b31d620 100644 --- a/src/main/java/com/twilio/rest/flexapi/v1/PluginArchiveUpdater.java +++ b/src/main/java/com/twilio/rest/flexapi/v1/PluginArchiveUpdater.java @@ -15,7 +15,8 @@ package com.twilio.rest.flexapi.v1; import com.twilio.base.Updater; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -26,60 +27,58 @@ import com.twilio.rest.Domains; public class PluginArchiveUpdater extends Updater { - - private String pathSid; + private String pathsid; private String flexMetadata; - public PluginArchiveUpdater(final String pathSid) { - this.pathSid = pathSid; + public PluginArchiveUpdater(final String pathsid) { + this.pathsid = pathsid; } + public PluginArchiveUpdater setFlexMetadata(final String flexMetadata) { this.flexMetadata = flexMetadata; return this; } + @Override public PluginArchive update(final TwilioRestClient client) { + String path = "/v1/PluginService/Plugins/{Sid}/Archive"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.FLEXAPI.toString(), - path + HttpMethod.POST, + Domains.FLEXAPI.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addHeaderParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "PluginArchive update failed: Unable to connect to server" - ); + throw new ApiConnectionException("PluginArchive update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return PluginArchive.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return PluginArchive.fromJson(response.getStream(), client.getObjectMapper()); } private void addHeaderParams(final Request request) { + if (flexMetadata != null) { - request.addHeaderParam("Flex-Metadata", flexMetadata); + Serializer.toString(request, "Flex-Metadata", flexMetadata, ParameterType.HEADER); } + } } diff --git a/src/main/java/com/twilio/rest/flexapi/v1/PluginConfiguration.java b/src/main/java/com/twilio/rest/flexapi/v1/PluginConfiguration.java index b620de21ad..e980fe5dcc 100644 --- a/src/main/java/com/twilio/rest/flexapi/v1/PluginConfiguration.java +++ b/src/main/java/com/twilio/rest/flexapi/v1/PluginConfiguration.java @@ -18,51 +18,57 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class PluginConfiguration extends Resource { - private static final long serialVersionUID = 179388614074571L; public static PluginConfigurationCreator creator(final String name) { - return new PluginConfigurationCreator(name); + return new PluginConfigurationCreator( + name + ); } - public static PluginConfigurationFetcher fetcher(final String pathSid) { - return new PluginConfigurationFetcher(pathSid); + + public static PluginConfigurationFetcher fetcher(final String pathsid) { + return new PluginConfigurationFetcher( + pathsid + ); } + public static PluginConfigurationReader reader() { - return new PluginConfigurationReader(); + return new PluginConfigurationReader( + + ); } + /** * Converts a JSON String into a PluginConfiguration object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return PluginConfiguration object represented by the provided JSON */ - public static PluginConfiguration fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static PluginConfiguration fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, PluginConfiguration.class); @@ -77,14 +83,11 @@ public static PluginConfiguration fromJson( * Converts a JSON InputStream into a PluginConfiguration object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return PluginConfiguration object represented by the provided JSON */ - public static PluginConfiguration fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static PluginConfiguration fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, PluginConfiguration.class); @@ -95,66 +98,56 @@ public static PluginConfiguration fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String name; - private final String description; + @Getter private final Boolean archived; + @Getter private final ZonedDateTime dateCreated; - private final URI url; + @Getter + private final String description; + @Getter private final Map links; + @Getter + private final String name; + @Getter + private final String sid; + @Getter + private final URI url; @JsonCreator private PluginConfiguration( - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("name") final String name, - @JsonProperty("description") final String description, - @JsonProperty("archived") final Boolean archived, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("url") final URI url, - @JsonProperty("links") final Map links + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("archived") final Boolean archived, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("description") final String description, + @JsonProperty("links") final Map links, + @JsonProperty("name") final String name, + @JsonProperty("sid") final String sid, + @JsonProperty("url") final URI url ) { - this.sid = sid; this.accountSid = accountSid; - this.name = name; - this.description = description; this.archived = archived; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.url = url; + this.dateCreated = dateCreated; + this.description = description; this.links = links; - } - - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getName() { - return this.name; - } - - public final String getDescription() { - return this.description; - } - - public final Boolean getArchived() { - return this.archived; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final URI getUrl() { - return this.url; - } - - public final Map getLinks() { - return this.links; + this.name = name; + this.sid = sid; + this.url = url; } @Override @@ -168,30 +161,32 @@ public boolean equals(final Object o) { } PluginConfiguration other = (PluginConfiguration) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(name, other.name) && - Objects.equals(description, other.description) && - Objects.equals(archived, other.archived) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(url, other.url) && - Objects.equals(links, other.links) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(archived, other.archived) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(description, other.description) && + Objects.equals(links, other.links) && + Objects.equals(name, other.name) && + Objects.equals(sid, other.sid) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - sid, - accountSid, - name, - description, - archived, - dateCreated, - url, - links + accountSid, + archived, + dateCreated, + description, + links, + name, + sid, + url ); } + + } + diff --git a/src/main/java/com/twilio/rest/flexapi/v1/PluginConfigurationArchive.java b/src/main/java/com/twilio/rest/flexapi/v1/PluginConfigurationArchive.java index 80c22599a6..b6797f0ed7 100644 --- a/src/main/java/com/twilio/rest/flexapi/v1/PluginConfigurationArchive.java +++ b/src/main/java/com/twilio/rest/flexapi/v1/PluginConfigurationArchive.java @@ -18,49 +18,45 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class PluginConfigurationArchive extends Resource { - private static final long serialVersionUID = 208571008215124L; - public static PluginConfigurationArchiveUpdater updater( - final String pathSid - ) { - return new PluginConfigurationArchiveUpdater(pathSid); + public static PluginConfigurationArchiveUpdater updater(final String pathsid) { + return new PluginConfigurationArchiveUpdater( + pathsid + ); } + /** * Converts a JSON String into a PluginConfigurationArchive object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return PluginConfigurationArchive object represented by the provided JSON */ - public static PluginConfigurationArchive fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static PluginConfigurationArchive fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { - return objectMapper.readValue( - json, - PluginConfigurationArchive.class - ); + return objectMapper.readValue(json, PluginConfigurationArchive.class); } catch (final JsonMappingException | JsonParseException e) { throw new ApiException(e.getMessage(), e); } catch (final IOException e) { @@ -72,20 +68,14 @@ public static PluginConfigurationArchive fromJson( * Converts a JSON InputStream into a PluginConfigurationArchive object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return PluginConfigurationArchive object represented by the provided JSON */ - public static PluginConfigurationArchive fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static PluginConfigurationArchive fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { - return objectMapper.readValue( - json, - PluginConfigurationArchive.class - ); + return objectMapper.readValue(json, PluginConfigurationArchive.class); } catch (final JsonMappingException | JsonParseException e) { throw new ApiException(e.getMessage(), e); } catch (final IOException e) { @@ -93,61 +83,54 @@ public static PluginConfigurationArchive fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String name; - private final String description; + @Getter private final Boolean archived; + @Getter private final ZonedDateTime dateCreated; + @Getter + private final String description; + @Getter + private final String name; + @Getter + private final String sid; + @Getter private final URI url; @JsonCreator private PluginConfigurationArchive( - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("name") final String name, - @JsonProperty("description") final String description, - @JsonProperty("archived") final Boolean archived, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("url") final URI url + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("archived") final Boolean archived, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("description") final String description, + @JsonProperty("name") final String name, + @JsonProperty("sid") final String sid, + @JsonProperty("url") final URI url ) { - this.sid = sid; this.accountSid = accountSid; - this.name = name; - this.description = description; this.archived = archived; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); + this.dateCreated = dateCreated; + this.description = description; + this.name = name; + this.sid = sid; this.url = url; } - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getName() { - return this.name; - } - - public final String getDescription() { - return this.description; - } - - public final Boolean getArchived() { - return this.archived; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final URI getUrl() { - return this.url; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -159,28 +142,30 @@ public boolean equals(final Object o) { } PluginConfigurationArchive other = (PluginConfigurationArchive) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(name, other.name) && - Objects.equals(description, other.description) && - Objects.equals(archived, other.archived) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(url, other.url) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(archived, other.archived) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(description, other.description) && + Objects.equals(name, other.name) && + Objects.equals(sid, other.sid) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - sid, - accountSid, - name, - description, - archived, - dateCreated, - url + accountSid, + archived, + dateCreated, + description, + name, + sid, + url ); } + + } + diff --git a/src/main/java/com/twilio/rest/flexapi/v1/PluginConfigurationArchiveUpdater.java b/src/main/java/com/twilio/rest/flexapi/v1/PluginConfigurationArchiveUpdater.java index 7b106c81cc..5d112d8a9b 100644 --- a/src/main/java/com/twilio/rest/flexapi/v1/PluginConfigurationArchiveUpdater.java +++ b/src/main/java/com/twilio/rest/flexapi/v1/PluginConfigurationArchiveUpdater.java @@ -15,7 +15,8 @@ package com.twilio.rest.flexapi.v1; import com.twilio.base.Updater; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,64 +26,59 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class PluginConfigurationArchiveUpdater - extends Updater { - - private String pathSid; +public class PluginConfigurationArchiveUpdater extends Updater { + private String pathsid; private String flexMetadata; - public PluginConfigurationArchiveUpdater(final String pathSid) { - this.pathSid = pathSid; + public PluginConfigurationArchiveUpdater(final String pathsid) { + this.pathsid = pathsid; } - public PluginConfigurationArchiveUpdater setFlexMetadata( - final String flexMetadata - ) { + + public PluginConfigurationArchiveUpdater setFlexMetadata(final String flexMetadata) { this.flexMetadata = flexMetadata; return this; } + @Override public PluginConfigurationArchive update(final TwilioRestClient client) { + String path = "/v1/PluginService/Configurations/{Sid}/Archive"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.FLEXAPI.toString(), - path + HttpMethod.POST, + Domains.FLEXAPI.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addHeaderParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "PluginConfigurationArchive update failed: Unable to connect to server" - ); + throw new ApiConnectionException("PluginConfigurationArchive update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return PluginConfigurationArchive.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return PluginConfigurationArchive.fromJson(response.getStream(), client.getObjectMapper()); } private void addHeaderParams(final Request request) { + if (flexMetadata != null) { - request.addHeaderParam("Flex-Metadata", flexMetadata); + Serializer.toString(request, "Flex-Metadata", flexMetadata, ParameterType.HEADER); } + } } diff --git a/src/main/java/com/twilio/rest/flexapi/v1/PluginConfigurationCreator.java b/src/main/java/com/twilio/rest/flexapi/v1/PluginConfigurationCreator.java index 3fc0e2b9d8..ada11c15d5 100644 --- a/src/main/java/com/twilio/rest/flexapi/v1/PluginConfigurationCreator.java +++ b/src/main/java/com/twilio/rest/flexapi/v1/PluginConfigurationCreator.java @@ -14,11 +14,12 @@ package com.twilio.rest.flexapi.v1; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; -import com.twilio.converter.Converter; -import com.twilio.converter.Converter; +import com.twilio.constant.EnumConstants.ParameterType; import com.twilio.converter.Promoter; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,13 +28,13 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -import java.util.List; + import java.util.List; public class PluginConfigurationCreator extends Creator { - private String name; private String flexMetadata; + private String name; private List plugins; private String description; @@ -41,17 +42,12 @@ public PluginConfigurationCreator(final String name) { this.name = name; } + public PluginConfigurationCreator setName(final String name) { this.name = name; return this; } - public PluginConfigurationCreator setFlexMetadata( - final String flexMetadata - ) { - this.flexMetadata = flexMetadata; - return this; - } public PluginConfigurationCreator setPlugins(final List plugins) { this.plugins = plugins; @@ -67,62 +63,72 @@ public PluginConfigurationCreator setDescription(final String description) { return this; } + + public PluginConfigurationCreator setFlexMetadata(final String flexMetadata) { + this.flexMetadata = flexMetadata; + return this; + } + + @Override public PluginConfiguration create(final TwilioRestClient client) { + String path = "/v1/PluginService/Configurations"; - path = path.replace("{" + "Name" + "}", this.name.toString()); Request request = new Request( - HttpMethod.POST, - Domains.FLEXAPI.toString(), - path + HttpMethod.POST, + Domains.FLEXAPI.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); - addPostParams(request); addHeaderParams(request); + addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "PluginConfiguration creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("PluginConfiguration creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return PluginConfiguration.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return PluginConfiguration.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (name != null) { - request.addPostParam("Name", name); + Serializer.toString(request, "Name", name, ParameterType.URLENCODED); } + + if (plugins != null) { - for (Object prop : plugins) { - request.addPostParam("Plugins", Converter.objectToJson(prop)); + for (Object param : plugins) { + Serializer.toString(request, "Plugins", param, ParameterType.URLENCODED); } } + + if (description != null) { - request.addPostParam("Description", description); + Serializer.toString(request, "Description", description, ParameterType.URLENCODED); } + + } private void addHeaderParams(final Request request) { + if (flexMetadata != null) { - request.addHeaderParam("Flex-Metadata", flexMetadata); + Serializer.toString(request, "Flex-Metadata", flexMetadata, ParameterType.HEADER); } + } } diff --git a/src/main/java/com/twilio/rest/flexapi/v1/PluginConfigurationFetcher.java b/src/main/java/com/twilio/rest/flexapi/v1/PluginConfigurationFetcher.java index f2ed80e0bb..b68b154c81 100644 --- a/src/main/java/com/twilio/rest/flexapi/v1/PluginConfigurationFetcher.java +++ b/src/main/java/com/twilio/rest/flexapi/v1/PluginConfigurationFetcher.java @@ -15,7 +15,8 @@ package com.twilio.rest.flexapi.v1; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,62 +28,57 @@ public class PluginConfigurationFetcher extends Fetcher { - private String pathSid; + private String pathsid; private String flexMetadata; - public PluginConfigurationFetcher(final String pathSid) { - this.pathSid = pathSid; + public PluginConfigurationFetcher(final String pathsid) { + this.pathsid = pathsid; } - public PluginConfigurationFetcher setFlexMetadata( - final String flexMetadata - ) { + + public PluginConfigurationFetcher setFlexMetadata(final String flexMetadata) { this.flexMetadata = flexMetadata; return this; } + @Override public PluginConfiguration fetch(final TwilioRestClient client) { + String path = "/v1/PluginService/Configurations/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.FLEXAPI.toString(), - path + HttpMethod.GET, + Domains.FLEXAPI.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addHeaderParams(request); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "PluginConfiguration fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("PluginConfiguration fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return PluginConfiguration.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return PluginConfiguration.fromJson(response.getStream(), client.getObjectMapper()); } private void addHeaderParams(final Request request) { + if (flexMetadata != null) { - request.addHeaderParam("Flex-Metadata", flexMetadata); + Serializer.toString(request, "Flex-Metadata", flexMetadata, ParameterType.HEADER); } + } } diff --git a/src/main/java/com/twilio/rest/flexapi/v1/PluginConfigurationReader.java b/src/main/java/com/twilio/rest/flexapi/v1/PluginConfigurationReader.java index fc4070bc35..c5f6947f58 100644 --- a/src/main/java/com/twilio/rest/flexapi/v1/PluginConfigurationReader.java +++ b/src/main/java/com/twilio/rest/flexapi/v1/PluginConfigurationReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,124 +30,101 @@ public class PluginConfigurationReader extends Reader { - private String flexMetadata; private Long pageSize; + private String flexMetadata; - public PluginConfigurationReader() {} - - public PluginConfigurationReader setFlexMetadata( - final String flexMetadata - ) { - this.flexMetadata = flexMetadata; - return this; + public PluginConfigurationReader() { } + public PluginConfigurationReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + + public PluginConfigurationReader setFlexMetadata(final String flexMetadata) { + this.flexMetadata = flexMetadata; + return this; + } + + @Override - public ResourceSet read( - final TwilioRestClient client - ) { + public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/PluginService/Configurations"; + Request request = new Request( - HttpMethod.GET, - Domains.FLEXAPI.toString(), - path + HttpMethod.GET, + Domains.FLEXAPI.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addHeaderParams(request); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "PluginConfiguration read failed: Unable to connect to server" - ); + throw new ApiConnectionException("PluginConfiguration read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "configurations", - response.getContent(), - PluginConfiguration.class, - client.getObjectMapper() - ); + "configurations", + response.getContent(), + PluginConfiguration.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.FLEXAPI.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.FLEXAPI.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } - private void addHeaderParams(final Request request) { - if (flexMetadata != null) { - request.addHeaderParam("Flex-Metadata", flexMetadata); - } - } - private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); + + } + + private void addHeaderParams(final Request request) { + + if (flexMetadata != null) { + Serializer.toString(request, "Flex-Metadata", flexMetadata, ParameterType.HEADER); } + } } diff --git a/src/main/java/com/twilio/rest/flexapi/v1/PluginCreator.java b/src/main/java/com/twilio/rest/flexapi/v1/PluginCreator.java index f2aaaecef5..bc7d98d314 100644 --- a/src/main/java/com/twilio/rest/flexapi/v1/PluginCreator.java +++ b/src/main/java/com/twilio/rest/flexapi/v1/PluginCreator.java @@ -14,8 +14,11 @@ package com.twilio.rest.flexapi.v1; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,8 +30,8 @@ public class PluginCreator extends Creator { - private String uniqueName; private String flexMetadata; + private String uniqueName; private String friendlyName; private String description; @@ -36,56 +39,57 @@ public PluginCreator(final String uniqueName) { this.uniqueName = uniqueName; } + public PluginCreator setUniqueName(final String uniqueName) { this.uniqueName = uniqueName; return this; } - public PluginCreator setFlexMetadata(final String flexMetadata) { - this.flexMetadata = flexMetadata; - return this; - } public PluginCreator setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + public PluginCreator setDescription(final String description) { this.description = description; return this; } + + public PluginCreator setFlexMetadata(final String flexMetadata) { + this.flexMetadata = flexMetadata; + return this; + } + + @Override public Plugin create(final TwilioRestClient client) { + String path = "/v1/PluginService/Plugins"; - path = - path.replace("{" + "UniqueName" + "}", this.uniqueName.toString()); Request request = new Request( - HttpMethod.POST, - Domains.FLEXAPI.toString(), - path + HttpMethod.POST, + Domains.FLEXAPI.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); - addPostParams(request); addHeaderParams(request); + addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Plugin creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("Plugin creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -94,20 +98,29 @@ public Plugin create(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (uniqueName != null) { - request.addPostParam("UniqueName", uniqueName); + Serializer.toString(request, "UniqueName", uniqueName, ParameterType.URLENCODED); } + + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + if (description != null) { - request.addPostParam("Description", description); + Serializer.toString(request, "Description", description, ParameterType.URLENCODED); } + + } private void addHeaderParams(final Request request) { + if (flexMetadata != null) { - request.addHeaderParam("Flex-Metadata", flexMetadata); + Serializer.toString(request, "Flex-Metadata", flexMetadata, ParameterType.HEADER); } + } } diff --git a/src/main/java/com/twilio/rest/flexapi/v1/PluginFetcher.java b/src/main/java/com/twilio/rest/flexapi/v1/PluginFetcher.java index 66a20d1a08..b098d889da 100644 --- a/src/main/java/com/twilio/rest/flexapi/v1/PluginFetcher.java +++ b/src/main/java/com/twilio/rest/flexapi/v1/PluginFetcher.java @@ -15,7 +15,8 @@ package com.twilio.rest.flexapi.v1; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,57 +28,57 @@ public class PluginFetcher extends Fetcher { - private String pathSid; + private String pathsid; private String flexMetadata; - public PluginFetcher(final String pathSid) { - this.pathSid = pathSid; + public PluginFetcher(final String pathsid) { + this.pathsid = pathsid; } + public PluginFetcher setFlexMetadata(final String flexMetadata) { this.flexMetadata = flexMetadata; return this; } + @Override public Plugin fetch(final TwilioRestClient client) { + String path = "/v1/PluginService/Plugins/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.FLEXAPI.toString(), - path + HttpMethod.GET, + Domains.FLEXAPI.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addHeaderParams(request); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Plugin fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Plugin fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Plugin.fromJson(response.getStream(), client.getObjectMapper()); } private void addHeaderParams(final Request request) { + if (flexMetadata != null) { - request.addHeaderParam("Flex-Metadata", flexMetadata); + Serializer.toString(request, "Flex-Metadata", flexMetadata, ParameterType.HEADER); } + } } diff --git a/src/main/java/com/twilio/rest/flexapi/v1/PluginReader.java b/src/main/java/com/twilio/rest/flexapi/v1/PluginReader.java index 04658aa8ca..fd4cfd7a90 100644 --- a/src/main/java/com/twilio/rest/flexapi/v1/PluginReader.java +++ b/src/main/java/com/twilio/rest/flexapi/v1/PluginReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,120 +30,101 @@ public class PluginReader extends Reader { - private String flexMetadata; private Long pageSize; + private String flexMetadata; - public PluginReader() {} - - public PluginReader setFlexMetadata(final String flexMetadata) { - this.flexMetadata = flexMetadata; - return this; + public PluginReader() { } + public PluginReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + + public PluginReader setFlexMetadata(final String flexMetadata) { + this.flexMetadata = flexMetadata; + return this; + } + + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/PluginService/Plugins"; + Request request = new Request( - HttpMethod.GET, - Domains.FLEXAPI.toString(), - path + HttpMethod.GET, + Domains.FLEXAPI.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addHeaderParams(request); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Plugin read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Plugin read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "plugins", - response.getContent(), - Plugin.class, - client.getObjectMapper() - ); + "plugins", + response.getContent(), + Plugin.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.FLEXAPI.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.FLEXAPI.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } - private void addHeaderParams(final Request request) { - if (flexMetadata != null) { - request.addHeaderParam("Flex-Metadata", flexMetadata); - } - } - private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); + + } + + private void addHeaderParams(final Request request) { + + if (flexMetadata != null) { + Serializer.toString(request, "Flex-Metadata", flexMetadata, ParameterType.HEADER); } + } } diff --git a/src/main/java/com/twilio/rest/flexapi/v1/PluginRelease.java b/src/main/java/com/twilio/rest/flexapi/v1/PluginRelease.java index 2d59202bd6..7e52efae63 100644 --- a/src/main/java/com/twilio/rest/flexapi/v1/PluginRelease.java +++ b/src/main/java/com/twilio/rest/flexapi/v1/PluginRelease.java @@ -18,49 +18,56 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class PluginRelease extends Resource { - private static final long serialVersionUID = 6792045414097L; public static PluginReleaseCreator creator(final String configurationId) { - return new PluginReleaseCreator(configurationId); + return new PluginReleaseCreator( + configurationId + ); } - public static PluginReleaseFetcher fetcher(final String pathSid) { - return new PluginReleaseFetcher(pathSid); + + public static PluginReleaseFetcher fetcher(final String pathsid) { + return new PluginReleaseFetcher( + pathsid + ); } + public static PluginReleaseReader reader() { - return new PluginReleaseReader(); + return new PluginReleaseReader( + + ); } + /** * Converts a JSON String into a PluginRelease object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return PluginRelease object represented by the provided JSON */ - public static PluginRelease fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static PluginRelease fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, PluginRelease.class); @@ -75,14 +82,11 @@ public static PluginRelease fromJson( * Converts a JSON InputStream into a PluginRelease object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return PluginRelease object represented by the provided JSON */ - public static PluginRelease fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static PluginRelease fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, PluginRelease.class); @@ -93,47 +97,46 @@ public static PluginRelease fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; + @Getter private final String configurationSid; + @Getter private final ZonedDateTime dateCreated; + @Getter + private final String sid; + @Getter private final URI url; @JsonCreator private PluginRelease( - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("configuration_sid") final String configurationSid, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("url") final URI url + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("configuration_sid") final String configurationSid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("sid") final String sid, + @JsonProperty("url") final URI url ) { - this.sid = sid; this.accountSid = accountSid; this.configurationSid = configurationSid; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); + this.dateCreated = dateCreated; + this.sid = sid; this.url = url; } - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getConfigurationSid() { - return this.configurationSid; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final URI getUrl() { - return this.url; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -145,24 +148,26 @@ public boolean equals(final Object o) { } PluginRelease other = (PluginRelease) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(configurationSid, other.configurationSid) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(url, other.url) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(configurationSid, other.configurationSid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(sid, other.sid) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - sid, - accountSid, - configurationSid, - dateCreated, - url + accountSid, + configurationSid, + dateCreated, + sid, + url ); } + + } + diff --git a/src/main/java/com/twilio/rest/flexapi/v1/PluginReleaseCreator.java b/src/main/java/com/twilio/rest/flexapi/v1/PluginReleaseCreator.java index fb4e42b455..a1c50fe3f3 100644 --- a/src/main/java/com/twilio/rest/flexapi/v1/PluginReleaseCreator.java +++ b/src/main/java/com/twilio/rest/flexapi/v1/PluginReleaseCreator.java @@ -14,8 +14,11 @@ package com.twilio.rest.flexapi.v1; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,77 +30,73 @@ public class PluginReleaseCreator extends Creator { - private String configurationId; private String flexMetadata; + private String configurationId; public PluginReleaseCreator(final String configurationId) { this.configurationId = configurationId; } - public PluginReleaseCreator setConfigurationId( - final String configurationId - ) { + + public PluginReleaseCreator setConfigurationId(final String configurationId) { this.configurationId = configurationId; return this; } + public PluginReleaseCreator setFlexMetadata(final String flexMetadata) { this.flexMetadata = flexMetadata; return this; } + @Override public PluginRelease create(final TwilioRestClient client) { + String path = "/v1/PluginService/Releases"; - path = - path.replace( - "{" + "ConfigurationId" + "}", - this.configurationId.toString() - ); Request request = new Request( - HttpMethod.POST, - Domains.FLEXAPI.toString(), - path + HttpMethod.POST, + Domains.FLEXAPI.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); - addPostParams(request); addHeaderParams(request); + addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "PluginRelease creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("PluginRelease creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return PluginRelease.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return PluginRelease.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (configurationId != null) { - request.addPostParam("ConfigurationId", configurationId); + Serializer.toString(request, "ConfigurationId", configurationId, ParameterType.URLENCODED); } + + } private void addHeaderParams(final Request request) { + if (flexMetadata != null) { - request.addHeaderParam("Flex-Metadata", flexMetadata); + Serializer.toString(request, "Flex-Metadata", flexMetadata, ParameterType.HEADER); } + } } diff --git a/src/main/java/com/twilio/rest/flexapi/v1/PluginReleaseFetcher.java b/src/main/java/com/twilio/rest/flexapi/v1/PluginReleaseFetcher.java index c569e24343..73971e3371 100644 --- a/src/main/java/com/twilio/rest/flexapi/v1/PluginReleaseFetcher.java +++ b/src/main/java/com/twilio/rest/flexapi/v1/PluginReleaseFetcher.java @@ -15,7 +15,8 @@ package com.twilio.rest.flexapi.v1; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,60 +28,57 @@ public class PluginReleaseFetcher extends Fetcher { - private String pathSid; + private String pathsid; private String flexMetadata; - public PluginReleaseFetcher(final String pathSid) { - this.pathSid = pathSid; + public PluginReleaseFetcher(final String pathsid) { + this.pathsid = pathsid; } + public PluginReleaseFetcher setFlexMetadata(final String flexMetadata) { this.flexMetadata = flexMetadata; return this; } + @Override public PluginRelease fetch(final TwilioRestClient client) { + String path = "/v1/PluginService/Releases/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.FLEXAPI.toString(), - path + HttpMethod.GET, + Domains.FLEXAPI.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addHeaderParams(request); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "PluginRelease fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("PluginRelease fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return PluginRelease.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return PluginRelease.fromJson(response.getStream(), client.getObjectMapper()); } private void addHeaderParams(final Request request) { + if (flexMetadata != null) { - request.addHeaderParam("Flex-Metadata", flexMetadata); + Serializer.toString(request, "Flex-Metadata", flexMetadata, ParameterType.HEADER); } + } } diff --git a/src/main/java/com/twilio/rest/flexapi/v1/PluginReleaseReader.java b/src/main/java/com/twilio/rest/flexapi/v1/PluginReleaseReader.java index c91b71c49e..a23673086b 100644 --- a/src/main/java/com/twilio/rest/flexapi/v1/PluginReleaseReader.java +++ b/src/main/java/com/twilio/rest/flexapi/v1/PluginReleaseReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,120 +30,101 @@ public class PluginReleaseReader extends Reader { - private String flexMetadata; private Long pageSize; + private String flexMetadata; - public PluginReleaseReader() {} - - public PluginReleaseReader setFlexMetadata(final String flexMetadata) { - this.flexMetadata = flexMetadata; - return this; + public PluginReleaseReader() { } + public PluginReleaseReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + + public PluginReleaseReader setFlexMetadata(final String flexMetadata) { + this.flexMetadata = flexMetadata; + return this; + } + + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/PluginService/Releases"; + Request request = new Request( - HttpMethod.GET, - Domains.FLEXAPI.toString(), - path + HttpMethod.GET, + Domains.FLEXAPI.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addHeaderParams(request); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "PluginRelease read failed: Unable to connect to server" - ); + throw new ApiConnectionException("PluginRelease read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "releases", - response.getContent(), - PluginRelease.class, - client.getObjectMapper() - ); + "releases", + response.getContent(), + PluginRelease.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.FLEXAPI.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.FLEXAPI.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } - private void addHeaderParams(final Request request) { - if (flexMetadata != null) { - request.addHeaderParam("Flex-Metadata", flexMetadata); - } - } - private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); + + } + + private void addHeaderParams(final Request request) { + + if (flexMetadata != null) { + Serializer.toString(request, "Flex-Metadata", flexMetadata, ParameterType.HEADER); } + } } diff --git a/src/main/java/com/twilio/rest/flexapi/v1/PluginUpdater.java b/src/main/java/com/twilio/rest/flexapi/v1/PluginUpdater.java index 2dd9a98034..27a4292647 100644 --- a/src/main/java/com/twilio/rest/flexapi/v1/PluginUpdater.java +++ b/src/main/java/com/twilio/rest/flexapi/v1/PluginUpdater.java @@ -16,6 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -26,60 +28,62 @@ import com.twilio.rest.Domains; public class PluginUpdater extends Updater { - - private String pathSid; + private String pathsid; private String flexMetadata; private String friendlyName; private String description; - public PluginUpdater(final String pathSid) { - this.pathSid = pathSid; + public PluginUpdater(final String pathsid) { + this.pathsid = pathsid; } - public PluginUpdater setFlexMetadata(final String flexMetadata) { - this.flexMetadata = flexMetadata; - return this; - } public PluginUpdater setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + public PluginUpdater setDescription(final String description) { this.description = description; return this; } + + public PluginUpdater setFlexMetadata(final String flexMetadata) { + this.flexMetadata = flexMetadata; + return this; + } + + @Override public Plugin update(final TwilioRestClient client) { + String path = "/v1/PluginService/Plugins/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.FLEXAPI.toString(), - path + HttpMethod.POST, + Domains.FLEXAPI.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); - addPostParams(request); addHeaderParams(request); + addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Plugin update failed: Unable to connect to server" - ); + throw new ApiConnectionException("Plugin update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -88,17 +92,24 @@ public Plugin update(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + if (description != null) { - request.addPostParam("Description", description); + Serializer.toString(request, "Description", description, ParameterType.URLENCODED); } + + } private void addHeaderParams(final Request request) { + if (flexMetadata != null) { - request.addHeaderParam("Flex-Metadata", flexMetadata); + Serializer.toString(request, "Flex-Metadata", flexMetadata, ParameterType.HEADER); } + } } diff --git a/src/main/java/com/twilio/rest/flexapi/v1/PluginVersionArchive.java b/src/main/java/com/twilio/rest/flexapi/v1/PluginVersionArchive.java index 58939843dc..b4d27e5be7 100644 --- a/src/main/java/com/twilio/rest/flexapi/v1/PluginVersionArchive.java +++ b/src/main/java/com/twilio/rest/flexapi/v1/PluginVersionArchive.java @@ -18,44 +18,42 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class PluginVersionArchive extends Resource { - private static final long serialVersionUID = 255808209327953L; - public static PluginVersionArchiveUpdater updater( - final String pathPluginSid, - final String pathSid - ) { - return new PluginVersionArchiveUpdater(pathPluginSid, pathSid); + public static PluginVersionArchiveUpdater updater(final String pathpluginSid, final String pathsid) { + return new PluginVersionArchiveUpdater( + pathpluginSid, pathsid + ); } + /** * Converts a JSON String into a PluginVersionArchive object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return PluginVersionArchive object represented by the provided JSON */ - public static PluginVersionArchive fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static PluginVersionArchive fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, PluginVersionArchive.class); @@ -70,14 +68,11 @@ public static PluginVersionArchive fromJson( * Converts a JSON InputStream into a PluginVersionArchive object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return PluginVersionArchive object represented by the provided JSON */ - public static PluginVersionArchive fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static PluginVersionArchive fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, PluginVersionArchive.class); @@ -88,80 +83,64 @@ public static PluginVersionArchive fromJson( } } - private final String sid; - private final String pluginSid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String version; - private final URI pluginUrl; - private final String changelog; - private final Boolean _private; + @Getter private final Boolean archived; + @Getter + private final String changelog; + @Getter private final ZonedDateTime dateCreated; + @Getter + private final String pluginSid; + @Getter + private final URI pluginUrl; + @Getter + private final Boolean _private; + @Getter + private final String sid; + @Getter private final URI url; + @Getter + private final String version; @JsonCreator private PluginVersionArchive( - @JsonProperty("sid") final String sid, - @JsonProperty("plugin_sid") final String pluginSid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("version") final String version, - @JsonProperty("plugin_url") final URI pluginUrl, - @JsonProperty("changelog") final String changelog, - @JsonProperty("_private") final Boolean _private, - @JsonProperty("archived") final Boolean archived, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("url") final URI url + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("archived") final Boolean archived, + @JsonProperty("changelog") final String changelog, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("plugin_sid") final String pluginSid, + @JsonProperty("plugin_url") final URI pluginUrl, + @JsonProperty("private") final Boolean _private, + @JsonProperty("sid") final String sid, + @JsonProperty("url") final URI url, + @JsonProperty("version") final String version ) { - this.sid = sid; - this.pluginSid = pluginSid; this.accountSid = accountSid; - this.version = version; - this.pluginUrl = pluginUrl; + this.archived = archived; this.changelog = changelog; + this.dateCreated = dateCreated; + this.pluginSid = pluginSid; + this.pluginUrl = pluginUrl; this._private = _private; - this.archived = archived; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); + this.sid = sid; this.url = url; - } - - public final String getSid() { - return this.sid; - } - - public final String getPluginSid() { - return this.pluginSid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getVersion() { - return this.version; - } - - public final URI getPluginUrl() { - return this.pluginUrl; - } - - public final String getChangelog() { - return this.changelog; - } - - public final Boolean get_private() { - return this._private; - } - - public final Boolean getArchived() { - return this.archived; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final URI getUrl() { - return this.url; + this.version = version; } @Override @@ -175,34 +154,36 @@ public boolean equals(final Object o) { } PluginVersionArchive other = (PluginVersionArchive) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(pluginSid, other.pluginSid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(version, other.version) && - Objects.equals(pluginUrl, other.pluginUrl) && - Objects.equals(changelog, other.changelog) && - Objects.equals(_private, other._private) && - Objects.equals(archived, other.archived) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(url, other.url) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(archived, other.archived) && + Objects.equals(changelog, other.changelog) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(pluginSid, other.pluginSid) && + Objects.equals(pluginUrl, other.pluginUrl) && + Objects.equals(_private, other._private) && + Objects.equals(sid, other.sid) && + Objects.equals(url, other.url) && + Objects.equals(version, other.version) ); } @Override public int hashCode() { return Objects.hash( - sid, - pluginSid, - accountSid, - version, - pluginUrl, - changelog, - _private, - archived, - dateCreated, - url + accountSid, + archived, + changelog, + dateCreated, + pluginSid, + pluginUrl, + _private, + sid, + url, + version ); } + + } + diff --git a/src/main/java/com/twilio/rest/flexapi/v1/PluginVersionArchiveUpdater.java b/src/main/java/com/twilio/rest/flexapi/v1/PluginVersionArchiveUpdater.java index bd69c79012..eebddd443f 100644 --- a/src/main/java/com/twilio/rest/flexapi/v1/PluginVersionArchiveUpdater.java +++ b/src/main/java/com/twilio/rest/flexapi/v1/PluginVersionArchiveUpdater.java @@ -15,7 +15,8 @@ package com.twilio.rest.flexapi.v1; import com.twilio.base.Updater; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -26,73 +27,61 @@ import com.twilio.rest.Domains; public class PluginVersionArchiveUpdater extends Updater { - - private String pathPluginSid; - private String pathSid; + private String pathpluginSid; + private String pathsid; private String flexMetadata; - public PluginVersionArchiveUpdater( - final String pathPluginSid, - final String pathSid - ) { - this.pathPluginSid = pathPluginSid; - this.pathSid = pathSid; + public PluginVersionArchiveUpdater(final String pathpluginSid, final String pathsid) { + this.pathpluginSid = pathpluginSid; + this.pathsid = pathsid; } - public PluginVersionArchiveUpdater setFlexMetadata( - final String flexMetadata - ) { + + public PluginVersionArchiveUpdater setFlexMetadata(final String flexMetadata) { this.flexMetadata = flexMetadata; return this; } + @Override public PluginVersionArchive update(final TwilioRestClient client) { - String path = - "/v1/PluginService/Plugins/{PluginSid}/Versions/{Sid}/Archive"; - path = - path.replace( - "{" + "PluginSid" + "}", - this.pathPluginSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/v1/PluginService/Plugins/{PluginSid}/Versions/{Sid}/Archive"; + + path = path.replace("{" + "PluginSid" + "}", this.pathpluginSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.FLEXAPI.toString(), - path + HttpMethod.POST, + Domains.FLEXAPI.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addHeaderParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "PluginVersionArchive update failed: Unable to connect to server" - ); + throw new ApiConnectionException("PluginVersionArchive update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return PluginVersionArchive.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return PluginVersionArchive.fromJson(response.getStream(), client.getObjectMapper()); } private void addHeaderParams(final Request request) { + if (flexMetadata != null) { - request.addHeaderParam("Flex-Metadata", flexMetadata); + Serializer.toString(request, "Flex-Metadata", flexMetadata, ParameterType.HEADER); } + } } diff --git a/src/main/java/com/twilio/rest/flexapi/v1/ProvisioningStatus.java b/src/main/java/com/twilio/rest/flexapi/v1/ProvisioningStatus.java index 48fd242415..a8748b2096 100644 --- a/src/main/java/com/twilio/rest/flexapi/v1/ProvisioningStatus.java +++ b/src/main/java/com/twilio/rest/flexapi/v1/ProvisioningStatus.java @@ -18,40 +18,64 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class ProvisioningStatus extends Resource { - private static final long serialVersionUID = 116877818354472L; public static ProvisioningStatusFetcher fetcher() { - return new ProvisioningStatusFetcher(); + return new ProvisioningStatusFetcher( + + ); + } + + + public enum Status { + ACTIVE("active"), + IN_PROGRESS("in-progress"), + NOT_CONFIGURED("not-configured"), + FAILED("failed"); + + private final String value; + + private Status(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static Status forValue(final String value) { + return Promoter.enumFromString(value, Status.values()); + } } + /** * Converts a JSON String into a ProvisioningStatus object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return ProvisioningStatus object represented by the provided JSON */ - public static ProvisioningStatus fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static ProvisioningStatus fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, ProvisioningStatus.class); @@ -66,14 +90,11 @@ public static ProvisioningStatus fromJson( * Converts a JSON InputStream into a ProvisioningStatus object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return ProvisioningStatus object represented by the provided JSON */ - public static ProvisioningStatus fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static ProvisioningStatus fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, ProvisioningStatus.class); @@ -84,26 +105,33 @@ public static ProvisioningStatus fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final ProvisioningStatus.Status status; + @Getter private final URI url; @JsonCreator private ProvisioningStatus( - @JsonProperty("status") final ProvisioningStatus.Status status, - @JsonProperty("url") final URI url + @JsonProperty("status") final ProvisioningStatus.Status status, + @JsonProperty("url") final URI url ) { this.status = status; this.url = url; } - public final ProvisioningStatus.Status getStatus() { - return this.status; - } - - public final URI getUrl() { - return this.url; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -115,37 +143,20 @@ public boolean equals(final Object o) { } ProvisioningStatus other = (ProvisioningStatus) o; - return ( - Objects.equals(status, other.status) && - Objects.equals(url, other.url) + Objects.equals(status, other.status) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { - return Objects.hash(status, url); + return Objects.hash( + status, + url + ); } - public enum Status { - ACTIVE("active"), - IN_PROGRESS("in-progress"), - NOT_CONFIGURED("not-configured"), - FAILED("failed"); - - private final String value; - private Status(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static Status forValue(final String value) { - return Promoter.enumFromString(value, Status.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/flexapi/v1/ProvisioningStatusFetcher.java b/src/main/java/com/twilio/rest/flexapi/v1/ProvisioningStatusFetcher.java index e1a2d64dae..b94d9f5d60 100644 --- a/src/main/java/com/twilio/rest/flexapi/v1/ProvisioningStatusFetcher.java +++ b/src/main/java/com/twilio/rest/flexapi/v1/ProvisioningStatusFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.flexapi.v1; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,41 +26,37 @@ public class ProvisioningStatusFetcher extends Fetcher { - public ProvisioningStatusFetcher() {} + + public ProvisioningStatusFetcher() { + } + @Override public ProvisioningStatus fetch(final TwilioRestClient client) { + String path = "/v1/account/provision/status"; + Request request = new Request( - HttpMethod.GET, - Domains.FLEXAPI.toString(), - path + HttpMethod.GET, + Domains.FLEXAPI.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "ProvisioningStatus fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("ProvisioningStatus fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return ProvisioningStatus.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return ProvisioningStatus.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/flexapi/v1/WebChannel.java b/src/main/java/com/twilio/rest/flexapi/v1/WebChannel.java index 3702252495..2f8034cf80 100644 --- a/src/main/java/com/twilio/rest/flexapi/v1/WebChannel.java +++ b/src/main/java/com/twilio/rest/flexapi/v1/WebChannel.java @@ -18,68 +18,91 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class WebChannel extends Resource { - private static final long serialVersionUID = 55535071818984L; - public static WebChannelCreator creator( - final String flexFlowSid, - final String identity, - final String customerFriendlyName, - final String chatFriendlyName - ) { + public static WebChannelCreator creator(final String flexFlowSid, final String identity, final String customerFriendlyName, final String chatFriendlyName) { return new WebChannelCreator( - flexFlowSid, - identity, - customerFriendlyName, - chatFriendlyName + flexFlowSid, identity, customerFriendlyName, chatFriendlyName ); } - public static WebChannelDeleter deleter(final String pathSid) { - return new WebChannelDeleter(pathSid); + + public static WebChannelDeleter deleter(final String pathsid) { + return new WebChannelDeleter( + pathsid + ); } - public static WebChannelFetcher fetcher(final String pathSid) { - return new WebChannelFetcher(pathSid); + + public static WebChannelFetcher fetcher(final String pathsid) { + return new WebChannelFetcher( + pathsid + ); } + public static WebChannelReader reader() { - return new WebChannelReader(); + return new WebChannelReader( + + ); } - public static WebChannelUpdater updater(final String pathSid) { - return new WebChannelUpdater(pathSid); + + public static WebChannelUpdater updater(final String pathsid) { + return new WebChannelUpdater( + pathsid + ); } + + public enum ChatStatus { + INACTIVE("inactive"); + + private final String value; + + private ChatStatus(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static ChatStatus forValue(final String value) { + return Promoter.enumFromString(value, ChatStatus.values()); + } + } + + /** * Converts a JSON String into a WebChannel object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return WebChannel object represented by the provided JSON */ - public static WebChannel fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static WebChannel fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, WebChannel.class); @@ -94,14 +117,11 @@ public static WebChannel fromJson( * Converts a JSON InputStream into a WebChannel object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return WebChannel object represented by the provided JSON */ - public static WebChannel fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static WebChannel fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, WebChannel.class); @@ -112,52 +132,49 @@ public static WebChannel fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; + @Getter + private final ZonedDateTime dateCreated; + @Getter + private final ZonedDateTime dateUpdated; + @Getter private final String flexFlowSid; + @Getter private final String sid; + @Getter private final URI url; - private final ZonedDateTime dateCreated; - private final ZonedDateTime dateUpdated; @JsonCreator private WebChannel( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("flex_flow_sid") final String flexFlowSid, - @JsonProperty("sid") final String sid, - @JsonProperty("url") final URI url, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("flex_flow_sid") final String flexFlowSid, + @JsonProperty("sid") final String sid, + @JsonProperty("url") final URI url ) { this.accountSid = accountSid; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.flexFlowSid = flexFlowSid; this.sid = sid; this.url = url; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getFlexFlowSid() { - return this.flexFlowSid; - } - - public final String getSid() { - return this.sid; - } - - public final URI getUrl() { - return this.url; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; } @Override @@ -171,45 +188,28 @@ public boolean equals(final Object o) { } WebChannel other = (WebChannel) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(flexFlowSid, other.flexFlowSid) && - Objects.equals(sid, other.sid) && - Objects.equals(url, other.url) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(flexFlowSid, other.flexFlowSid) && + Objects.equals(sid, other.sid) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - accountSid, - flexFlowSid, - sid, - url, - dateCreated, - dateUpdated + accountSid, + dateCreated, + dateUpdated, + flexFlowSid, + sid, + url ); } - public enum ChatStatus { - INACTIVE("inactive"); - - private final String value; - - private ChatStatus(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - @JsonCreator - public static ChatStatus forValue(final String value) { - return Promoter.enumFromString(value, ChatStatus.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/flexapi/v1/WebChannelCreator.java b/src/main/java/com/twilio/rest/flexapi/v1/WebChannelCreator.java index 8112e90aa9..f95472719b 100644 --- a/src/main/java/com/twilio/rest/flexapi/v1/WebChannelCreator.java +++ b/src/main/java/com/twilio/rest/flexapi/v1/WebChannelCreator.java @@ -14,8 +14,11 @@ package com.twilio.rest.flexapi.v1; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -34,125 +37,113 @@ public class WebChannelCreator extends Creator { private String chatUniqueName; private String preEngagementData; - public WebChannelCreator( - final String flexFlowSid, - final String identity, - final String customerFriendlyName, - final String chatFriendlyName - ) { + public WebChannelCreator(final String flexFlowSid, final String identity, final String customerFriendlyName, final String chatFriendlyName) { this.flexFlowSid = flexFlowSid; this.identity = identity; this.customerFriendlyName = customerFriendlyName; this.chatFriendlyName = chatFriendlyName; } + public WebChannelCreator setFlexFlowSid(final String flexFlowSid) { this.flexFlowSid = flexFlowSid; return this; } + public WebChannelCreator setIdentity(final String identity) { this.identity = identity; return this; } - public WebChannelCreator setCustomerFriendlyName( - final String customerFriendlyName - ) { + + public WebChannelCreator setCustomerFriendlyName(final String customerFriendlyName) { this.customerFriendlyName = customerFriendlyName; return this; } - public WebChannelCreator setChatFriendlyName( - final String chatFriendlyName - ) { + + public WebChannelCreator setChatFriendlyName(final String chatFriendlyName) { this.chatFriendlyName = chatFriendlyName; return this; } + public WebChannelCreator setChatUniqueName(final String chatUniqueName) { this.chatUniqueName = chatUniqueName; return this; } - public WebChannelCreator setPreEngagementData( - final String preEngagementData - ) { + + public WebChannelCreator setPreEngagementData(final String preEngagementData) { this.preEngagementData = preEngagementData; return this; } + @Override public WebChannel create(final TwilioRestClient client) { + String path = "/v1/WebChannels"; - path = - path.replace( - "{" + "FlexFlowSid" + "}", - this.flexFlowSid.toString() - ); - path = path.replace("{" + "Identity" + "}", this.identity.toString()); - path = - path.replace( - "{" + "CustomerFriendlyName" + "}", - this.customerFriendlyName.toString() - ); - path = - path.replace( - "{" + "ChatFriendlyName" + "}", - this.chatFriendlyName.toString() - ); Request request = new Request( - HttpMethod.POST, - Domains.FLEXAPI.toString(), - path + HttpMethod.POST, + Domains.FLEXAPI.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "WebChannel creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("WebChannel creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return WebChannel.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return WebChannel.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (flexFlowSid != null) { - request.addPostParam("FlexFlowSid", flexFlowSid); + Serializer.toString(request, "FlexFlowSid", flexFlowSid, ParameterType.URLENCODED); } + + if (identity != null) { - request.addPostParam("Identity", identity); + Serializer.toString(request, "Identity", identity, ParameterType.URLENCODED); } + + if (customerFriendlyName != null) { - request.addPostParam("CustomerFriendlyName", customerFriendlyName); + Serializer.toString(request, "CustomerFriendlyName", customerFriendlyName, ParameterType.URLENCODED); } + + if (chatFriendlyName != null) { - request.addPostParam("ChatFriendlyName", chatFriendlyName); + Serializer.toString(request, "ChatFriendlyName", chatFriendlyName, ParameterType.URLENCODED); } + + if (chatUniqueName != null) { - request.addPostParam("ChatUniqueName", chatUniqueName); + Serializer.toString(request, "ChatUniqueName", chatUniqueName, ParameterType.URLENCODED); } + + if (preEngagementData != null) { - request.addPostParam("PreEngagementData", preEngagementData); + Serializer.toString(request, "PreEngagementData", preEngagementData, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/flexapi/v1/WebChannelDeleter.java b/src/main/java/com/twilio/rest/flexapi/v1/WebChannelDeleter.java index 7c1126a38f..6ecf3331cf 100644 --- a/src/main/java/com/twilio/rest/flexapi/v1/WebChannelDeleter.java +++ b/src/main/java/com/twilio/rest/flexapi/v1/WebChannelDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.flexapi.v1; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,40 +26,38 @@ public class WebChannelDeleter extends Deleter { - private String pathSid; + private String pathsid; - public WebChannelDeleter(final String pathSid) { - this.pathSid = pathSid; + public WebChannelDeleter(final String pathsid) { + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/v1/WebChannels/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.FLEXAPI.toString(), - path + HttpMethod.DELETE, + Domains.FLEXAPI.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "WebChannel delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("WebChannel delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/flexapi/v1/WebChannelFetcher.java b/src/main/java/com/twilio/rest/flexapi/v1/WebChannelFetcher.java index 79463886d7..2c5587c2a0 100644 --- a/src/main/java/com/twilio/rest/flexapi/v1/WebChannelFetcher.java +++ b/src/main/java/com/twilio/rest/flexapi/v1/WebChannelFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.flexapi.v1; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,47 +26,41 @@ public class WebChannelFetcher extends Fetcher { - private String pathSid; + private String pathsid; - public WebChannelFetcher(final String pathSid) { - this.pathSid = pathSid; + public WebChannelFetcher(final String pathsid) { + this.pathsid = pathsid; } + @Override public WebChannel fetch(final TwilioRestClient client) { + String path = "/v1/WebChannels/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.FLEXAPI.toString(), - path + HttpMethod.GET, + Domains.FLEXAPI.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "WebChannel fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("WebChannel fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return WebChannel.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return WebChannel.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/flexapi/v1/WebChannelReader.java b/src/main/java/com/twilio/rest/flexapi/v1/WebChannelReader.java index bef81d8397..23de1b5b56 100644 --- a/src/main/java/com/twilio/rest/flexapi/v1/WebChannelReader.java +++ b/src/main/java/com/twilio/rest/flexapi/v1/WebChannelReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -31,105 +32,83 @@ public class WebChannelReader extends Reader { private Long pageSize; - public WebChannelReader() {} + public WebChannelReader() { + } + public WebChannelReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/WebChannels"; + Request request = new Request( - HttpMethod.GET, - Domains.FLEXAPI.toString(), - path + HttpMethod.GET, + Domains.FLEXAPI.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "WebChannel read failed: Unable to connect to server" - ); + throw new ApiConnectionException("WebChannel read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "flex_chat_channels", - response.getContent(), - WebChannel.class, - client.getObjectMapper() - ); + "flex_chat_channels", + response.getContent(), + WebChannel.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.FLEXAPI.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.FLEXAPI.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/flexapi/v1/WebChannelUpdater.java b/src/main/java/com/twilio/rest/flexapi/v1/WebChannelUpdater.java index 65522e24f3..af83174e59 100644 --- a/src/main/java/com/twilio/rest/flexapi/v1/WebChannelUpdater.java +++ b/src/main/java/com/twilio/rest/flexapi/v1/WebChannelUpdater.java @@ -16,6 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -26,73 +28,72 @@ import com.twilio.rest.Domains; public class WebChannelUpdater extends Updater { - - private String pathSid; + private String pathsid; private WebChannel.ChatStatus chatStatus; private String postEngagementData; - public WebChannelUpdater(final String pathSid) { - this.pathSid = pathSid; + public WebChannelUpdater(final String pathsid) { + this.pathsid = pathsid; } - public WebChannelUpdater setChatStatus( - final WebChannel.ChatStatus chatStatus - ) { + + public WebChannelUpdater setChatStatus(final WebChannel.ChatStatus chatStatus) { this.chatStatus = chatStatus; return this; } - public WebChannelUpdater setPostEngagementData( - final String postEngagementData - ) { + + public WebChannelUpdater setPostEngagementData(final String postEngagementData) { this.postEngagementData = postEngagementData; return this; } + @Override public WebChannel update(final TwilioRestClient client) { + String path = "/v1/WebChannels/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.FLEXAPI.toString(), - path + HttpMethod.POST, + Domains.FLEXAPI.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "WebChannel update failed: Unable to connect to server" - ); + throw new ApiConnectionException("WebChannel update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return WebChannel.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return WebChannel.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (chatStatus != null) { - request.addPostParam("ChatStatus", chatStatus.toString()); + Serializer.toString(request, "ChatStatus", chatStatus, ParameterType.URLENCODED); } + + if (postEngagementData != null) { - request.addPostParam("PostEngagementData", postEngagementData); + Serializer.toString(request, "PostEngagementData", postEngagementData, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/flexapi/v1/interaction/InteractionChannel.java b/src/main/java/com/twilio/rest/flexapi/v1/interaction/InteractionChannel.java index 9c1d778e34..ef9eaffddd 100644 --- a/src/main/java/com/twilio/rest/flexapi/v1/interaction/InteractionChannel.java +++ b/src/main/java/com/twilio/rest/flexapi/v1/interaction/InteractionChannel.java @@ -18,63 +18,127 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class InteractionChannel extends Resource { - private static final long serialVersionUID = 96183028905472L; - public static InteractionChannelFetcher fetcher( - final String pathInteractionSid, - final String pathSid - ) { - return new InteractionChannelFetcher(pathInteractionSid, pathSid); + public static InteractionChannelFetcher fetcher(final String pathinteractionSid, final String pathsid) { + return new InteractionChannelFetcher( + pathinteractionSid, pathsid + ); } - public static InteractionChannelReader reader( - final String pathInteractionSid - ) { - return new InteractionChannelReader(pathInteractionSid); + + public static InteractionChannelReader reader(final String pathinteractionSid) { + return new InteractionChannelReader( + pathinteractionSid + ); } - public static InteractionChannelUpdater updater( - final String pathInteractionSid, - final String pathSid, - final InteractionChannel.UpdateChannelStatus status - ) { + + public static InteractionChannelUpdater updater(final String pathinteractionSid, final String pathsid, final InteractionChannel.UpdateChannelStatus status) { return new InteractionChannelUpdater( - pathInteractionSid, - pathSid, - status + pathinteractionSid, pathsid, status ); } + + public enum Type { + VOICE("voice"), + SMS("sms"), + EMAIL("email"), + WEB("web"), + WHATSAPP("whatsapp"), + CHAT("chat"), + MESSENGER("messenger"), + GBM("gbm"); + + private final String value; + + private Type(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static Type forValue(final String value) { + return Promoter.enumFromString(value, Type.values()); + } + } + + public enum ChannelStatus { + SETUP("setup"), + ACTIVE("active"), + FAILED("failed"), + CLOSED("closed"), + INACTIVE("inactive"), + PAUSE("pause"); + + private final String value; + + private ChannelStatus(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static ChannelStatus forValue(final String value) { + return Promoter.enumFromString(value, ChannelStatus.values()); + } + } + + public enum UpdateChannelStatus { + CLOSED("closed"), + INACTIVE("inactive"); + + private final String value; + + private UpdateChannelStatus(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static UpdateChannelStatus forValue(final String value) { + return Promoter.enumFromString(value, UpdateChannelStatus.values()); + } + } + + /** * Converts a JSON String into a InteractionChannel object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return InteractionChannel object represented by the provided JSON */ - public static InteractionChannel fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static InteractionChannel fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, InteractionChannel.class); @@ -89,14 +153,11 @@ public static InteractionChannel fromJson( * Converts a JSON InputStream into a InteractionChannel object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return InteractionChannel object represented by the provided JSON */ - public static InteractionChannel fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static InteractionChannel fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, InteractionChannel.class); @@ -107,66 +168,55 @@ public static InteractionChannel fromJson( } } - private final String sid; - private final String interactionSid; - private final InteractionChannel.Type type; - private final InteractionChannel.ChannelStatus status; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final Integer errorCode; + @Getter private final String errorMessage; - private final URI url; + @Getter + private final String interactionSid; + @Getter private final Map links; + @Getter + private final String sid; + @Getter + private final InteractionChannel.ChannelStatus status; + @Getter + private final InteractionChannel.Type type; + @Getter + private final URI url; @JsonCreator private InteractionChannel( - @JsonProperty("sid") final String sid, - @JsonProperty("interaction_sid") final String interactionSid, - @JsonProperty("type") final InteractionChannel.Type type, - @JsonProperty("status") final InteractionChannel.ChannelStatus status, - @JsonProperty("error_code") final Integer errorCode, - @JsonProperty("error_message") final String errorMessage, - @JsonProperty("url") final URI url, - @JsonProperty("links") final Map links + @JsonProperty("error_code") final Integer errorCode, + @JsonProperty("error_message") final String errorMessage, + @JsonProperty("interaction_sid") final String interactionSid, + @JsonProperty("links") final Map links, + @JsonProperty("sid") final String sid, + @JsonProperty("status") final InteractionChannel.ChannelStatus status, + @JsonProperty("type") final InteractionChannel.Type type, + @JsonProperty("url") final URI url ) { - this.sid = sid; - this.interactionSid = interactionSid; - this.type = type; - this.status = status; this.errorCode = errorCode; this.errorMessage = errorMessage; - this.url = url; + this.interactionSid = interactionSid; this.links = links; - } - - public final String getSid() { - return this.sid; - } - - public final String getInteractionSid() { - return this.interactionSid; - } - - public final InteractionChannel.Type getType() { - return this.type; - } - - public final InteractionChannel.ChannelStatus getStatus() { - return this.status; - } - - public final Integer getErrorCode() { - return this.errorCode; - } - - public final String getErrorMessage() { - return this.errorMessage; - } - - public final URI getUrl() { - return this.url; - } - - public final Map getLinks() { - return this.links; + this.sid = sid; + this.status = status; + this.type = type; + this.url = url; } @Override @@ -180,99 +230,32 @@ public boolean equals(final Object o) { } InteractionChannel other = (InteractionChannel) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(interactionSid, other.interactionSid) && - Objects.equals(type, other.type) && - Objects.equals(status, other.status) && - Objects.equals(errorCode, other.errorCode) && - Objects.equals(errorMessage, other.errorMessage) && - Objects.equals(url, other.url) && - Objects.equals(links, other.links) + Objects.equals(errorCode, other.errorCode) && + Objects.equals(errorMessage, other.errorMessage) && + Objects.equals(interactionSid, other.interactionSid) && + Objects.equals(links, other.links) && + Objects.equals(sid, other.sid) && + Objects.equals(status, other.status) && + Objects.equals(type, other.type) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - sid, - interactionSid, - type, - status, - errorCode, - errorMessage, - url, - links + errorCode, + errorMessage, + interactionSid, + links, + sid, + status, + type, + url ); } - public enum Type { - VOICE("voice"), - SMS("sms"), - EMAIL("email"), - WEB("web"), - WHATSAPP("whatsapp"), - CHAT("chat"), - MESSENGER("messenger"), - GBM("gbm"); - - private final String value; - - private Type(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - @JsonCreator - public static Type forValue(final String value) { - return Promoter.enumFromString(value, Type.values()); - } - } - - public enum UpdateChannelStatus { - CLOSED("closed"), - INACTIVE("inactive"); - - private final String value; - - private UpdateChannelStatus(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static UpdateChannelStatus forValue(final String value) { - return Promoter.enumFromString(value, UpdateChannelStatus.values()); - } - } - - public enum ChannelStatus { - SETUP("setup"), - ACTIVE("active"), - FAILED("failed"), - CLOSED("closed"), - INACTIVE("inactive"); - - private final String value; - - private ChannelStatus(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static ChannelStatus forValue(final String value) { - return Promoter.enumFromString(value, ChannelStatus.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/flexapi/v1/interaction/InteractionChannelFetcher.java b/src/main/java/com/twilio/rest/flexapi/v1/interaction/InteractionChannelFetcher.java index f71a7e5b75..3da15f4499 100644 --- a/src/main/java/com/twilio/rest/flexapi/v1/interaction/InteractionChannelFetcher.java +++ b/src/main/java/com/twilio/rest/flexapi/v1/interaction/InteractionChannelFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.flexapi.v1.interaction; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,57 +26,44 @@ public class InteractionChannelFetcher extends Fetcher { - private String pathInteractionSid; - private String pathSid; + private String pathinteractionSid; + private String pathsid; - public InteractionChannelFetcher( - final String pathInteractionSid, - final String pathSid - ) { - this.pathInteractionSid = pathInteractionSid; - this.pathSid = pathSid; + public InteractionChannelFetcher(final String pathinteractionSid, final String pathsid) { + this.pathinteractionSid = pathinteractionSid; + this.pathsid = pathsid; } + @Override public InteractionChannel fetch(final TwilioRestClient client) { + String path = "/v1/Interactions/{InteractionSid}/Channels/{Sid}"; - path = - path.replace( - "{" + "InteractionSid" + "}", - this.pathInteractionSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "InteractionSid" + "}", this.pathinteractionSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.FLEXAPI.toString(), - path + HttpMethod.GET, + Domains.FLEXAPI.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "InteractionChannel fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("InteractionChannel fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return InteractionChannel.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return InteractionChannel.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/flexapi/v1/interaction/InteractionChannelReader.java b/src/main/java/com/twilio/rest/flexapi/v1/interaction/InteractionChannelReader.java index e747ef46b8..9eda2d9343 100644 --- a/src/main/java/com/twilio/rest/flexapi/v1/interaction/InteractionChannelReader.java +++ b/src/main/java/com/twilio/rest/flexapi/v1/interaction/InteractionChannelReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,115 +30,88 @@ public class InteractionChannelReader extends Reader { - private String pathInteractionSid; + private String pathinteractionSid; private Long pageSize; - public InteractionChannelReader(final String pathInteractionSid) { - this.pathInteractionSid = pathInteractionSid; + public InteractionChannelReader(final String pathinteractionSid) { + this.pathinteractionSid = pathinteractionSid; } + public InteractionChannelReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/Interactions/{InteractionSid}/Channels"; - path = - path.replace( - "{" + "InteractionSid" + "}", - this.pathInteractionSid.toString() - ); + + path = path.replace("{" + "InteractionSid" + "}", this.pathinteractionSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.FLEXAPI.toString(), - path + HttpMethod.GET, + Domains.FLEXAPI.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "InteractionChannel read failed: Unable to connect to server" - ); + throw new ApiConnectionException("InteractionChannel read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "channels", - response.getContent(), - InteractionChannel.class, - client.getObjectMapper() - ); + "channels", + response.getContent(), + InteractionChannel.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.FLEXAPI.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.FLEXAPI.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/flexapi/v1/interaction/InteractionChannelUpdater.java b/src/main/java/com/twilio/rest/flexapi/v1/interaction/InteractionChannelUpdater.java index 3c61717b83..fde8e7a806 100644 --- a/src/main/java/com/twilio/rest/flexapi/v1/interaction/InteractionChannelUpdater.java +++ b/src/main/java/com/twilio/rest/flexapi/v1/interaction/InteractionChannelUpdater.java @@ -16,7 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; -import com.twilio.converter.Converter; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,84 +28,76 @@ import com.twilio.rest.Domains; public class InteractionChannelUpdater extends Updater { - - private String pathInteractionSid; - private String pathSid; + private String pathinteractionSid; + private String pathsid; private InteractionChannel.UpdateChannelStatus status; private Object routing; - public InteractionChannelUpdater( - final String pathInteractionSid, - final String pathSid, - final InteractionChannel.UpdateChannelStatus status - ) { - this.pathInteractionSid = pathInteractionSid; - this.pathSid = pathSid; + public InteractionChannelUpdater(final String pathinteractionSid, final String pathsid, final InteractionChannel.UpdateChannelStatus status) { + this.pathinteractionSid = pathinteractionSid; + this.pathsid = pathsid; this.status = status; } - public InteractionChannelUpdater setStatus( - final InteractionChannel.UpdateChannelStatus status - ) { + + public InteractionChannelUpdater setStatus(final InteractionChannel.UpdateChannelStatus status) { this.status = status; return this; } + public InteractionChannelUpdater setRouting(final Object routing) { this.routing = routing; return this; } + @Override public InteractionChannel update(final TwilioRestClient client) { + String path = "/v1/Interactions/{InteractionSid}/Channels/{Sid}"; - path = - path.replace( - "{" + "InteractionSid" + "}", - this.pathInteractionSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); - path = path.replace("{" + "Status" + "}", this.status.toString()); + path = path.replace("{" + "InteractionSid" + "}", this.pathinteractionSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.FLEXAPI.toString(), - path + HttpMethod.POST, + Domains.FLEXAPI.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "InteractionChannel update failed: Unable to connect to server" - ); + throw new ApiConnectionException("InteractionChannel update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return InteractionChannel.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return InteractionChannel.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (status != null) { - request.addPostParam("Status", status.toString()); + Serializer.toString(request, "Status", status, ParameterType.URLENCODED); } + + if (routing != null) { - request.addPostParam("Routing", Converter.objectToJson(routing)); + Serializer.toString(request, "Routing", routing, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/flexapi/v1/interaction/interactionchannel/InteractionChannelInvite.java b/src/main/java/com/twilio/rest/flexapi/v1/interaction/interactionchannel/InteractionChannelInvite.java index da656b886a..2d367410eb 100644 --- a/src/main/java/com/twilio/rest/flexapi/v1/interaction/interactionchannel/InteractionChannelInvite.java +++ b/src/main/java/com/twilio/rest/flexapi/v1/interaction/interactionchannel/InteractionChannelInvite.java @@ -18,59 +18,47 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; -import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class InteractionChannelInvite extends Resource { - private static final long serialVersionUID = 96456011706810L; - public static InteractionChannelInviteCreator creator( - final String pathInteractionSid, - final String pathChannelSid, - final Object routing - ) { + public static InteractionChannelInviteCreator creator(final String pathinteractionSid, final String pathchannelSid, final Object routing) { return new InteractionChannelInviteCreator( - pathInteractionSid, - pathChannelSid, - routing + pathinteractionSid, pathchannelSid, routing ); } - public static InteractionChannelInviteReader reader( - final String pathInteractionSid, - final String pathChannelSid - ) { + + public static InteractionChannelInviteReader reader(final String pathinteractionSid, final String pathchannelSid) { return new InteractionChannelInviteReader( - pathInteractionSid, - pathChannelSid + pathinteractionSid, pathchannelSid ); } + /** * Converts a JSON String into a InteractionChannelInvite object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return InteractionChannelInvite object represented by the provided JSON */ - public static InteractionChannelInvite fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static InteractionChannelInvite fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, InteractionChannelInvite.class); @@ -85,14 +73,11 @@ public static InteractionChannelInvite fromJson( * Converts a JSON InputStream into a InteractionChannelInvite object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return InteractionChannelInvite object represented by the provided JSON */ - public static InteractionChannelInvite fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static InteractionChannelInvite fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, InteractionChannelInvite.class); @@ -103,47 +88,45 @@ public static InteractionChannelInvite fromJson( } } - private final String sid; - private final String interactionSid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String channelSid; - private final Map routing; + @Getter + private final String interactionSid; + @Getter + private final Object routing; + @Getter + private final String sid; + @Getter private final URI url; @JsonCreator private InteractionChannelInvite( - @JsonProperty("sid") final String sid, - @JsonProperty("interaction_sid") final String interactionSid, - @JsonProperty("channel_sid") final String channelSid, - @JsonProperty("routing") final Map routing, - @JsonProperty("url") final URI url + @JsonProperty("channel_sid") final String channelSid, + @JsonProperty("interaction_sid") final String interactionSid, + @JsonProperty("routing") final Object routing, + @JsonProperty("sid") final String sid, + @JsonProperty("url") final URI url ) { - this.sid = sid; - this.interactionSid = interactionSid; this.channelSid = channelSid; + this.interactionSid = interactionSid; this.routing = routing; + this.sid = sid; this.url = url; } - public final String getSid() { - return this.sid; - } - - public final String getInteractionSid() { - return this.interactionSid; - } - - public final String getChannelSid() { - return this.channelSid; - } - - public final Map getRouting() { - return this.routing; - } - - public final URI getUrl() { - return this.url; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -155,18 +138,26 @@ public boolean equals(final Object o) { } InteractionChannelInvite other = (InteractionChannelInvite) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(interactionSid, other.interactionSid) && - Objects.equals(channelSid, other.channelSid) && - Objects.equals(routing, other.routing) && - Objects.equals(url, other.url) + Objects.equals(channelSid, other.channelSid) && + Objects.equals(interactionSid, other.interactionSid) && + Objects.equals(routing, other.routing) && + Objects.equals(sid, other.sid) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { - return Objects.hash(sid, interactionSid, channelSid, routing, url); + return Objects.hash( + channelSid, + interactionSid, + routing, + sid, + url + ); } + + } + diff --git a/src/main/java/com/twilio/rest/flexapi/v1/interaction/interactionchannel/InteractionChannelInviteCreator.java b/src/main/java/com/twilio/rest/flexapi/v1/interaction/interactionchannel/InteractionChannelInviteCreator.java index 89dd3e12be..272425c4c4 100644 --- a/src/main/java/com/twilio/rest/flexapi/v1/interaction/interactionchannel/InteractionChannelInviteCreator.java +++ b/src/main/java/com/twilio/rest/flexapi/v1/interaction/interactionchannel/InteractionChannelInviteCreator.java @@ -14,10 +14,11 @@ package com.twilio.rest.flexapi.v1.interaction.interactionchannel; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; -import com.twilio.converter.Converter; -import com.twilio.converter.Converter; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,80 +28,66 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class InteractionChannelInviteCreator - extends Creator { +public class InteractionChannelInviteCreator extends Creator { - private String pathInteractionSid; - private String pathChannelSid; + private String pathinteractionSid; + private String pathchannelSid; private Object routing; - public InteractionChannelInviteCreator( - final String pathInteractionSid, - final String pathChannelSid, - final Object routing - ) { - this.pathInteractionSid = pathInteractionSid; - this.pathChannelSid = pathChannelSid; + public InteractionChannelInviteCreator(final String pathinteractionSid, final String pathchannelSid, final Object routing) { + this.pathinteractionSid = pathinteractionSid; + this.pathchannelSid = pathchannelSid; this.routing = routing; } + public InteractionChannelInviteCreator setRouting(final Object routing) { this.routing = routing; return this; } + @Override public InteractionChannelInvite create(final TwilioRestClient client) { - String path = - "/v1/Interactions/{InteractionSid}/Channels/{ChannelSid}/Invites"; - path = - path.replace( - "{" + "InteractionSid" + "}", - this.pathInteractionSid.toString() - ); - path = - path.replace( - "{" + "ChannelSid" + "}", - this.pathChannelSid.toString() - ); - path = path.replace("{" + "Routing" + "}", this.routing.toString()); + String path = "/v1/Interactions/{InteractionSid}/Channels/{ChannelSid}/Invites"; + + path = path.replace("{" + "InteractionSid" + "}", this.pathinteractionSid.toString()); + path = path.replace("{" + "ChannelSid" + "}", this.pathchannelSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.FLEXAPI.toString(), - path + HttpMethod.POST, + Domains.FLEXAPI.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "InteractionChannelInvite creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("InteractionChannelInvite creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return InteractionChannelInvite.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return InteractionChannelInvite.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (routing != null) { - request.addPostParam("Routing", Converter.objectToJson(routing)); + Serializer.toString(request, "Routing", routing, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/flexapi/v1/interaction/interactionchannel/InteractionChannelInviteReader.java b/src/main/java/com/twilio/rest/flexapi/v1/interaction/interactionchannel/InteractionChannelInviteReader.java index 4eb3957a49..c3d1f90f62 100644 --- a/src/main/java/com/twilio/rest/flexapi/v1/interaction/interactionchannel/InteractionChannelInviteReader.java +++ b/src/main/java/com/twilio/rest/flexapi/v1/interaction/interactionchannel/InteractionChannelInviteReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,133 +28,93 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class InteractionChannelInviteReader - extends Reader { +public class InteractionChannelInviteReader extends Reader { - private String pathInteractionSid; - private String pathChannelSid; + private String pathinteractionSid; + private String pathchannelSid; private Long pageSize; - public InteractionChannelInviteReader( - final String pathInteractionSid, - final String pathChannelSid - ) { - this.pathInteractionSid = pathInteractionSid; - this.pathChannelSid = pathChannelSid; + public InteractionChannelInviteReader(final String pathinteractionSid, final String pathchannelSid) { + this.pathinteractionSid = pathinteractionSid; + this.pathchannelSid = pathchannelSid; } + public InteractionChannelInviteReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override - public ResourceSet read( - final TwilioRestClient client - ) { + public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } - public Page firstPage( - final TwilioRestClient client - ) { - String path = - "/v1/Interactions/{InteractionSid}/Channels/{ChannelSid}/Invites"; - path = - path.replace( - "{" + "InteractionSid" + "}", - this.pathInteractionSid.toString() - ); - path = - path.replace( - "{" + "ChannelSid" + "}", - this.pathChannelSid.toString() - ); + public Page firstPage(final TwilioRestClient client) { + + String path = "/v1/Interactions/{InteractionSid}/Channels/{ChannelSid}/Invites"; + + path = path.replace("{" + "InteractionSid" + "}", this.pathinteractionSid.toString()); + path = path.replace("{" + "ChannelSid" + "}", this.pathchannelSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.FLEXAPI.toString(), - path + HttpMethod.GET, + Domains.FLEXAPI.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "InteractionChannelInvite read failed: Unable to connect to server" - ); + throw new ApiConnectionException("InteractionChannelInvite read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "invites", - response.getContent(), - InteractionChannelInvite.class, - client.getObjectMapper() - ); + "invites", + response.getContent(), + InteractionChannelInvite.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.FLEXAPI.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.FLEXAPI.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/flexapi/v1/interaction/interactionchannel/InteractionChannelParticipant.java b/src/main/java/com/twilio/rest/flexapi/v1/interaction/interactionchannel/InteractionChannelParticipant.java index 16c65ee470..7b63571eff 100644 --- a/src/main/java/com/twilio/rest/flexapi/v1/interaction/interactionchannel/InteractionChannelParticipant.java +++ b/src/main/java/com/twilio/rest/flexapi/v1/interaction/interactionchannel/InteractionChannelParticipant.java @@ -18,82 +18,102 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; -import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class InteractionChannelParticipant extends Resource { - private static final long serialVersionUID = 13330803139630L; - public static InteractionChannelParticipantCreator creator( - final String pathInteractionSid, - final String pathChannelSid, - final InteractionChannelParticipant.Type type, - final Object mediaProperties - ) { + public static InteractionChannelParticipantCreator creator(final String pathinteractionSid, final String pathchannelSid, final InteractionChannelParticipant.Type type, final Object mediaProperties) { return new InteractionChannelParticipantCreator( - pathInteractionSid, - pathChannelSid, - type, - mediaProperties + pathinteractionSid, pathchannelSid, type, mediaProperties ); } - public static InteractionChannelParticipantReader reader( - final String pathInteractionSid, - final String pathChannelSid - ) { + + public static InteractionChannelParticipantReader reader(final String pathinteractionSid, final String pathchannelSid) { return new InteractionChannelParticipantReader( - pathInteractionSid, - pathChannelSid + pathinteractionSid, pathchannelSid ); } - public static InteractionChannelParticipantUpdater updater( - final String pathInteractionSid, - final String pathChannelSid, - final String pathSid, - final InteractionChannelParticipant.Status status - ) { + + public static InteractionChannelParticipantUpdater updater(final String pathinteractionSid, final String pathchannelSid, final String pathsid, final InteractionChannelParticipant.Status status) { return new InteractionChannelParticipantUpdater( - pathInteractionSid, - pathChannelSid, - pathSid, - status + pathinteractionSid, pathchannelSid, pathsid, status ); } + + public enum Status { + CLOSED("closed"), + WRAPUP("wrapup"); + + private final String value; + + private Status(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static Status forValue(final String value) { + return Promoter.enumFromString(value, Status.values()); + } + } + + public enum Type { + SUPERVISOR("supervisor"), + CUSTOMER("customer"), + EXTERNAL("external"), + AGENT("agent"), + UNKNOWN("unknown"); + + private final String value; + + private Type(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static Type forValue(final String value) { + return Promoter.enumFromString(value, Type.values()); + } + } + + /** * Converts a JSON String into a InteractionChannelParticipant object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return InteractionChannelParticipant object represented by the provided JSON */ - public static InteractionChannelParticipant fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static InteractionChannelParticipant fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { - return objectMapper.readValue( - json, - InteractionChannelParticipant.class - ); + return objectMapper.readValue(json, InteractionChannelParticipant.class); } catch (final JsonMappingException | JsonParseException e) { throw new ApiException(e.getMessage(), e); } catch (final IOException e) { @@ -105,20 +125,14 @@ public static InteractionChannelParticipant fromJson( * Converts a JSON InputStream into a InteractionChannelParticipant object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return InteractionChannelParticipant object represented by the provided JSON */ - public static InteractionChannelParticipant fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static InteractionChannelParticipant fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { - return objectMapper.readValue( - json, - InteractionChannelParticipant.class - ); + return objectMapper.readValue(json, InteractionChannelParticipant.class); } catch (final JsonMappingException | JsonParseException e) { throw new ApiException(e.getMessage(), e); } catch (final IOException e) { @@ -126,55 +140,47 @@ public static InteractionChannelParticipant fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter + private final String channelSid; + @Getter + private final String interactionSid; + @Getter + private final Object routingProperties; + @Getter private final String sid; + @Getter private final InteractionChannelParticipant.Type type; - private final String interactionSid; - private final String channelSid; + @Getter private final URI url; - private final Map routingProperties; @JsonCreator private InteractionChannelParticipant( - @JsonProperty("sid") final String sid, - @JsonProperty("type") final InteractionChannelParticipant.Type type, - @JsonProperty("interaction_sid") final String interactionSid, - @JsonProperty("channel_sid") final String channelSid, - @JsonProperty("url") final URI url, - @JsonProperty("routing_properties") final Map< - String, - Object - > routingProperties + @JsonProperty("channel_sid") final String channelSid, + @JsonProperty("interaction_sid") final String interactionSid, + @JsonProperty("routing_properties") final Object routingProperties, + @JsonProperty("sid") final String sid, + @JsonProperty("type") final InteractionChannelParticipant.Type type, + @JsonProperty("url") final URI url ) { + this.channelSid = channelSid; + this.interactionSid = interactionSid; + this.routingProperties = routingProperties; this.sid = sid; this.type = type; - this.interactionSid = interactionSid; - this.channelSid = channelSid; this.url = url; - this.routingProperties = routingProperties; - } - - public final String getSid() { - return this.sid; - } - - public final InteractionChannelParticipant.Type getType() { - return this.type; - } - - public final String getInteractionSid() { - return this.interactionSid; - } - - public final String getChannelSid() { - return this.channelSid; - } - - public final URI getUrl() { - return this.url; - } - - public final Map getRoutingProperties() { - return this.routingProperties; } @Override @@ -188,69 +194,28 @@ public boolean equals(final Object o) { } InteractionChannelParticipant other = (InteractionChannelParticipant) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(type, other.type) && - Objects.equals(interactionSid, other.interactionSid) && - Objects.equals(channelSid, other.channelSid) && - Objects.equals(url, other.url) && - Objects.equals(routingProperties, other.routingProperties) + Objects.equals(channelSid, other.channelSid) && + Objects.equals(interactionSid, other.interactionSid) && + Objects.equals(routingProperties, other.routingProperties) && + Objects.equals(sid, other.sid) && + Objects.equals(type, other.type) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - sid, - type, - interactionSid, - channelSid, - url, - routingProperties + channelSid, + interactionSid, + routingProperties, + sid, + type, + url ); } - public enum Status { - CLOSED("closed"), - WRAPUP("wrapup"); - - private final String value; - - private Status(final String value) { - this.value = value; - } - public String toString() { - return value; - } - - @JsonCreator - public static Status forValue(final String value) { - return Promoter.enumFromString(value, Status.values()); - } - } - - public enum Type { - SUPERVISOR("supervisor"), - CUSTOMER("customer"), - EXTERNAL("external"), - AGENT("agent"), - UNKNOWN("unknown"); - - private final String value; - - private Type(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static Type forValue(final String value) { - return Promoter.enumFromString(value, Type.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/flexapi/v1/interaction/interactionchannel/InteractionChannelParticipantCreator.java b/src/main/java/com/twilio/rest/flexapi/v1/interaction/interactionchannel/InteractionChannelParticipantCreator.java index 0de36280bf..f5b34cfef7 100644 --- a/src/main/java/com/twilio/rest/flexapi/v1/interaction/interactionchannel/InteractionChannelParticipantCreator.java +++ b/src/main/java/com/twilio/rest/flexapi/v1/interaction/interactionchannel/InteractionChannelParticipantCreator.java @@ -14,10 +14,11 @@ package com.twilio.rest.flexapi.v1.interaction.interactionchannel; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; -import com.twilio.converter.Converter; -import com.twilio.converter.Converter; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,117 +28,91 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class InteractionChannelParticipantCreator - extends Creator { +public class InteractionChannelParticipantCreator extends Creator { - private String pathInteractionSid; - private String pathChannelSid; + private String pathinteractionSid; + private String pathchannelSid; private InteractionChannelParticipant.Type type; private Object mediaProperties; private Object routingProperties; - public InteractionChannelParticipantCreator( - final String pathInteractionSid, - final String pathChannelSid, - final InteractionChannelParticipant.Type type, - final Object mediaProperties - ) { - this.pathInteractionSid = pathInteractionSid; - this.pathChannelSid = pathChannelSid; + public InteractionChannelParticipantCreator(final String pathinteractionSid, final String pathchannelSid, final InteractionChannelParticipant.Type type, final Object mediaProperties) { + this.pathinteractionSid = pathinteractionSid; + this.pathchannelSid = pathchannelSid; this.type = type; this.mediaProperties = mediaProperties; } - public InteractionChannelParticipantCreator setType( - final InteractionChannelParticipant.Type type - ) { + + public InteractionChannelParticipantCreator setType(final InteractionChannelParticipant.Type type) { this.type = type; return this; } - public InteractionChannelParticipantCreator setMediaProperties( - final Object mediaProperties - ) { + + public InteractionChannelParticipantCreator setMediaProperties(final Object mediaProperties) { this.mediaProperties = mediaProperties; return this; } - public InteractionChannelParticipantCreator setRoutingProperties( - final Object routingProperties - ) { + + public InteractionChannelParticipantCreator setRoutingProperties(final Object routingProperties) { this.routingProperties = routingProperties; return this; } + @Override public InteractionChannelParticipant create(final TwilioRestClient client) { - String path = - "/v1/Interactions/{InteractionSid}/Channels/{ChannelSid}/Participants"; - path = - path.replace( - "{" + "InteractionSid" + "}", - this.pathInteractionSid.toString() - ); - path = - path.replace( - "{" + "ChannelSid" + "}", - this.pathChannelSid.toString() - ); - path = path.replace("{" + "Type" + "}", this.type.toString()); - path = - path.replace( - "{" + "MediaProperties" + "}", - this.mediaProperties.toString() - ); + String path = "/v1/Interactions/{InteractionSid}/Channels/{ChannelSid}/Participants"; + + path = path.replace("{" + "InteractionSid" + "}", this.pathinteractionSid.toString()); + path = path.replace("{" + "ChannelSid" + "}", this.pathchannelSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.FLEXAPI.toString(), - path + HttpMethod.POST, + Domains.FLEXAPI.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "InteractionChannelParticipant creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("InteractionChannelParticipant creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return InteractionChannelParticipant.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return InteractionChannelParticipant.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (type != null) { - request.addPostParam("Type", type.toString()); + Serializer.toString(request, "Type", type, ParameterType.URLENCODED); } + + if (mediaProperties != null) { - request.addPostParam( - "MediaProperties", - Converter.objectToJson(mediaProperties) - ); + Serializer.toString(request, "MediaProperties", mediaProperties, ParameterType.URLENCODED); } + + if (routingProperties != null) { - request.addPostParam( - "RoutingProperties", - Converter.objectToJson(routingProperties) - ); + Serializer.toString(request, "RoutingProperties", routingProperties, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/flexapi/v1/interaction/interactionchannel/InteractionChannelParticipantReader.java b/src/main/java/com/twilio/rest/flexapi/v1/interaction/interactionchannel/InteractionChannelParticipantReader.java index ff527d3df5..76d334e49d 100644 --- a/src/main/java/com/twilio/rest/flexapi/v1/interaction/interactionchannel/InteractionChannelParticipantReader.java +++ b/src/main/java/com/twilio/rest/flexapi/v1/interaction/interactionchannel/InteractionChannelParticipantReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,135 +28,93 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class InteractionChannelParticipantReader - extends Reader { +public class InteractionChannelParticipantReader extends Reader { - private String pathInteractionSid; - private String pathChannelSid; + private String pathinteractionSid; + private String pathchannelSid; private Long pageSize; - public InteractionChannelParticipantReader( - final String pathInteractionSid, - final String pathChannelSid - ) { - this.pathInteractionSid = pathInteractionSid; - this.pathChannelSid = pathChannelSid; + public InteractionChannelParticipantReader(final String pathinteractionSid, final String pathchannelSid) { + this.pathinteractionSid = pathinteractionSid; + this.pathchannelSid = pathchannelSid; } - public InteractionChannelParticipantReader setPageSize( - final Long pageSize - ) { + + public InteractionChannelParticipantReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override - public ResourceSet read( - final TwilioRestClient client - ) { + public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } - public Page firstPage( - final TwilioRestClient client - ) { - String path = - "/v1/Interactions/{InteractionSid}/Channels/{ChannelSid}/Participants"; - path = - path.replace( - "{" + "InteractionSid" + "}", - this.pathInteractionSid.toString() - ); - path = - path.replace( - "{" + "ChannelSid" + "}", - this.pathChannelSid.toString() - ); + public Page firstPage(final TwilioRestClient client) { + + String path = "/v1/Interactions/{InteractionSid}/Channels/{ChannelSid}/Participants"; + + path = path.replace("{" + "InteractionSid" + "}", this.pathinteractionSid.toString()); + path = path.replace("{" + "ChannelSid" + "}", this.pathchannelSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.FLEXAPI.toString(), - path + HttpMethod.GET, + Domains.FLEXAPI.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "InteractionChannelParticipant read failed: Unable to connect to server" - ); + throw new ApiConnectionException("InteractionChannelParticipant read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "participants", - response.getContent(), - InteractionChannelParticipant.class, - client.getObjectMapper() - ); + "participants", + response.getContent(), + InteractionChannelParticipant.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.FLEXAPI.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.FLEXAPI.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/flexapi/v1/interaction/interactionchannel/InteractionChannelParticipantUpdater.java b/src/main/java/com/twilio/rest/flexapi/v1/interaction/interactionchannel/InteractionChannelParticipantUpdater.java index 1d66e2a2e4..9f5405e817 100644 --- a/src/main/java/com/twilio/rest/flexapi/v1/interaction/interactionchannel/InteractionChannelParticipantUpdater.java +++ b/src/main/java/com/twilio/rest/flexapi/v1/interaction/interactionchannel/InteractionChannelParticipantUpdater.java @@ -16,6 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,86 +27,68 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class InteractionChannelParticipantUpdater - extends Updater { - - private String pathInteractionSid; - private String pathChannelSid; - private String pathSid; +public class InteractionChannelParticipantUpdater extends Updater { + private String pathinteractionSid; + private String pathchannelSid; + private String pathsid; private InteractionChannelParticipant.Status status; - public InteractionChannelParticipantUpdater( - final String pathInteractionSid, - final String pathChannelSid, - final String pathSid, - final InteractionChannelParticipant.Status status - ) { - this.pathInteractionSid = pathInteractionSid; - this.pathChannelSid = pathChannelSid; - this.pathSid = pathSid; + public InteractionChannelParticipantUpdater(final String pathinteractionSid, final String pathchannelSid, final String pathsid, final InteractionChannelParticipant.Status status) { + this.pathinteractionSid = pathinteractionSid; + this.pathchannelSid = pathchannelSid; + this.pathsid = pathsid; this.status = status; } - public InteractionChannelParticipantUpdater setStatus( - final InteractionChannelParticipant.Status status - ) { + + public InteractionChannelParticipantUpdater setStatus(final InteractionChannelParticipant.Status status) { this.status = status; return this; } + @Override public InteractionChannelParticipant update(final TwilioRestClient client) { - String path = - "/v1/Interactions/{InteractionSid}/Channels/{ChannelSid}/Participants/{Sid}"; - path = - path.replace( - "{" + "InteractionSid" + "}", - this.pathInteractionSid.toString() - ); - path = - path.replace( - "{" + "ChannelSid" + "}", - this.pathChannelSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); - path = path.replace("{" + "Status" + "}", this.status.toString()); + String path = "/v1/Interactions/{InteractionSid}/Channels/{ChannelSid}/Participants/{Sid}"; + + path = path.replace("{" + "InteractionSid" + "}", this.pathinteractionSid.toString()); + path = path.replace("{" + "ChannelSid" + "}", this.pathchannelSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.FLEXAPI.toString(), - path + HttpMethod.POST, + Domains.FLEXAPI.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "InteractionChannelParticipant update failed: Unable to connect to server" - ); + throw new ApiConnectionException("InteractionChannelParticipant update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return InteractionChannelParticipant.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return InteractionChannelParticipant.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (status != null) { - request.addPostParam("Status", status.toString()); + Serializer.toString(request, "Status", status, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/flexapi/v1/interaction/interactionchannel/InteractionTransfer.java b/src/main/java/com/twilio/rest/flexapi/v1/interaction/interactionchannel/InteractionTransfer.java index 40779ee7de..0ff881fbb6 100644 --- a/src/main/java/com/twilio/rest/flexapi/v1/interaction/interactionchannel/InteractionTransfer.java +++ b/src/main/java/com/twilio/rest/flexapi/v1/interaction/interactionchannel/InteractionTransfer.java @@ -21,70 +21,97 @@ import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class InteractionTransfer extends Resource { - private static final long serialVersionUID = 149249433338910L; - public static InteractionTransferCreator creator( - final String pathInteractionSid, - final String pathChannelSid - ) { + public static InteractionTransferCreator creator(final String pathinteractionSid, final String pathchannelSid) { return new InteractionTransferCreator( - pathInteractionSid, - pathChannelSid + pathinteractionSid, pathchannelSid ); } - public static InteractionTransferFetcher fetcher( - final String pathInteractionSid, - final String pathChannelSid, - final String pathSid - ) { + + public static InteractionTransferFetcher fetcher(final String pathinteractionSid, final String pathchannelSid, final String pathsid) { return new InteractionTransferFetcher( - pathInteractionSid, - pathChannelSid, - pathSid + pathinteractionSid, pathchannelSid, pathsid ); } - public static InteractionTransferUpdater updater( - final String pathInteractionSid, - final String pathChannelSid, - final String pathSid - ) { + + public static InteractionTransferUpdater updater(final String pathinteractionSid, final String pathchannelSid, final String pathsid) { return new InteractionTransferUpdater( - pathInteractionSid, - pathChannelSid, - pathSid + pathinteractionSid, pathchannelSid, pathsid ); } + + public enum TransferStatus { + ACTIVE("active"), + FAILED("failed"), + COMPLETED("completed"); + + private final String value; + + private TransferStatus(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static TransferStatus forValue(final String value) { + return Promoter.enumFromString(value, TransferStatus.values()); + } + } + + public enum TransferType { + WARM("warm"), + COLD("cold"), + EXTERNAL("external"); + + private final String value; + + private TransferType(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static TransferType forValue(final String value) { + return Promoter.enumFromString(value, TransferType.values()); + } + } + + /** * Converts a JSON String into a InteractionTransfer object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return InteractionTransfer object represented by the provided JSON */ - public static InteractionTransfer fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static InteractionTransfer fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, InteractionTransfer.class); @@ -99,14 +126,11 @@ public static InteractionTransfer fromJson( * Converts a JSON InputStream into a InteractionTransfer object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return InteractionTransfer object represented by the provided JSON */ - public static InteractionTransfer fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static InteractionTransfer fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, InteractionTransfer.class); @@ -129,117 +153,75 @@ public static String toJson(Object object, ObjectMapper mapper) { } } - private final String sid; - private final String instanceSid; + + @Getter private final String accountSid; - private final String interactionSid; + @Getter private final String channelSid; + @Getter + private final ZonedDateTime dateCreated; + @Getter + private final ZonedDateTime dateUpdated; + @Getter private final String executionSid; - private final InteractionTransfer.TransferType type; - private final InteractionTransfer.TransferStatus status; + @Getter private final String from; - private final String to; + @Getter + private final String instanceSid; + @Getter + private final String interactionSid; + @Getter private final String noteSid; + @Getter + private final String sid; + @Getter + private final InteractionTransfer.TransferStatus status; + @Getter private final String summarySid; - private final ZonedDateTime dateCreated; - private final ZonedDateTime dateUpdated; + @Getter + private final String to; + @Getter + private final InteractionTransfer.TransferType type; + @Getter private final URI url; @JsonCreator private InteractionTransfer( - @JsonProperty("sid") final String sid, - @JsonProperty("instance_sid") final String instanceSid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("interaction_sid") final String interactionSid, - @JsonProperty("channel_sid") final String channelSid, - @JsonProperty("execution_sid") final String executionSid, - @JsonProperty("type") final InteractionTransfer.TransferType type, - @JsonProperty("status") final InteractionTransfer.TransferStatus status, - @JsonProperty("from") final String from, - @JsonProperty("to") final String to, - @JsonProperty("note_sid") final String noteSid, - @JsonProperty("summary_sid") final String summarySid, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("url") final URI url + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("channel_sid") final String channelSid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("execution_sid") final String executionSid, + @JsonProperty("from") final String from, + @JsonProperty("instance_sid") final String instanceSid, + @JsonProperty("interaction_sid") final String interactionSid, + @JsonProperty("note_sid") final String noteSid, + @JsonProperty("sid") final String sid, + @JsonProperty("status") final InteractionTransfer.TransferStatus status, + @JsonProperty("summary_sid") final String summarySid, + @JsonProperty("to") final String to, + @JsonProperty("type") final InteractionTransfer.TransferType type, + @JsonProperty("url") final URI url ) { - this.sid = sid; - this.instanceSid = instanceSid; this.accountSid = accountSid; - this.interactionSid = interactionSid; this.channelSid = channelSid; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.executionSid = executionSid; - this.type = type; - this.status = status; this.from = from; - this.to = to; + this.instanceSid = instanceSid; + this.interactionSid = interactionSid; this.noteSid = noteSid; + this.sid = sid; + this.status = status; this.summarySid = summarySid; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); + this.to = to; + this.type = type; this.url = url; } - public final String getSid() { - return this.sid; - } - - public final String getInstanceSid() { - return this.instanceSid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getInteractionSid() { - return this.interactionSid; - } - - public final String getChannelSid() { - return this.channelSid; - } - - public final String getExecutionSid() { - return this.executionSid; - } - - public final InteractionTransfer.TransferType getType() { - return this.type; - } - - public final InteractionTransfer.TransferStatus getStatus() { - return this.status; - } - - public final String getFrom() { - return this.from; - } - - public final String getTo() { - return this.to; - } - - public final String getNoteSid() { - return this.noteSid; - } - - public final String getSummarySid() { - return this.summarySid; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final URI getUrl() { - return this.url; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -251,86 +233,46 @@ public boolean equals(final Object o) { } InteractionTransfer other = (InteractionTransfer) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(instanceSid, other.instanceSid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(interactionSid, other.interactionSid) && - Objects.equals(channelSid, other.channelSid) && - Objects.equals(executionSid, other.executionSid) && - Objects.equals(type, other.type) && - Objects.equals(status, other.status) && - Objects.equals(from, other.from) && - Objects.equals(to, other.to) && - Objects.equals(noteSid, other.noteSid) && - Objects.equals(summarySid, other.summarySid) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(url, other.url) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(channelSid, other.channelSid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(executionSid, other.executionSid) && + Objects.equals(from, other.from) && + Objects.equals(instanceSid, other.instanceSid) && + Objects.equals(interactionSid, other.interactionSid) && + Objects.equals(noteSid, other.noteSid) && + Objects.equals(sid, other.sid) && + Objects.equals(status, other.status) && + Objects.equals(summarySid, other.summarySid) && + Objects.equals(to, other.to) && + Objects.equals(type, other.type) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - sid, - instanceSid, - accountSid, - interactionSid, - channelSid, - executionSid, - type, - status, - from, - to, - noteSid, - summarySid, - dateCreated, - dateUpdated, - url + accountSid, + channelSid, + dateCreated, + dateUpdated, + executionSid, + from, + instanceSid, + interactionSid, + noteSid, + sid, + status, + summarySid, + to, + type, + url ); } - public enum TransferType { - WARM("warm"), - COLD("cold"), - EXTERNAL("external"); - - private final String value; - - private TransferType(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static TransferType forValue(final String value) { - return Promoter.enumFromString(value, TransferType.values()); - } - } - - public enum TransferStatus { - ACTIVE("active"), - FAILED("failed"), - COMPLETED("completed"); - - private final String value; - private TransferStatus(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static TransferStatus forValue(final String value) { - return Promoter.enumFromString(value, TransferStatus.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/flexapi/v1/interaction/interactionchannel/InteractionTransferCreator.java b/src/main/java/com/twilio/rest/flexapi/v1/interaction/interactionchannel/InteractionTransferCreator.java index 2e751d566a..a610b0bcd7 100644 --- a/src/main/java/com/twilio/rest/flexapi/v1/interaction/interactionchannel/InteractionTransferCreator.java +++ b/src/main/java/com/twilio/rest/flexapi/v1/interaction/interactionchannel/InteractionTransferCreator.java @@ -28,69 +28,55 @@ public class InteractionTransferCreator extends Creator { - private String pathInteractionSid; - private String pathChannelSid; + private String pathinteractionSid; + private String pathchannelSid; private Object body; - public InteractionTransferCreator( - final String pathInteractionSid, - final String pathChannelSid - ) { - this.pathInteractionSid = pathInteractionSid; - this.pathChannelSid = pathChannelSid; + public InteractionTransferCreator(final String pathinteractionSid, final String pathchannelSid) { + this.pathinteractionSid = pathinteractionSid; + this.pathchannelSid = pathchannelSid; } + public InteractionTransferCreator setBody(final Object body) { this.body = body; return this; } + @Override public InteractionTransfer create(final TwilioRestClient client) { - String path = - "/v1/Interactions/{InteractionSid}/Channels/{ChannelSid}/Transfers"; - path = - path.replace( - "{" + "InteractionSid" + "}", - this.pathInteractionSid.toString() - ); - path = - path.replace( - "{" + "ChannelSid" + "}", - this.pathChannelSid.toString() - ); + String path = "/v1/Interactions/{InteractionSid}/Channels/{ChannelSid}/Transfers"; + + path = path.replace("{" + "InteractionSid" + "}", this.pathinteractionSid.toString()); + path = path.replace("{" + "ChannelSid" + "}", this.pathchannelSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.FLEXAPI.toString(), - path + HttpMethod.POST, + Domains.FLEXAPI.toString(), + path ); request.setContentType(EnumConstants.ContentType.JSON); addPostParams(request, client); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "InteractionTransfer creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("InteractionTransfer creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return InteractionTransfer.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return InteractionTransfer.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request, TwilioRestClient client) { diff --git a/src/main/java/com/twilio/rest/flexapi/v1/interaction/interactionchannel/InteractionTransferFetcher.java b/src/main/java/com/twilio/rest/flexapi/v1/interaction/interactionchannel/InteractionTransferFetcher.java index 653cf0ef97..030fd1bf4f 100644 --- a/src/main/java/com/twilio/rest/flexapi/v1/interaction/interactionchannel/InteractionTransferFetcher.java +++ b/src/main/java/com/twilio/rest/flexapi/v1/interaction/interactionchannel/InteractionTransferFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.flexapi.v1.interaction.interactionchannel; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,66 +26,47 @@ public class InteractionTransferFetcher extends Fetcher { - private String pathInteractionSid; - private String pathChannelSid; - private String pathSid; + private String pathinteractionSid; + private String pathchannelSid; + private String pathsid; - public InteractionTransferFetcher( - final String pathInteractionSid, - final String pathChannelSid, - final String pathSid - ) { - this.pathInteractionSid = pathInteractionSid; - this.pathChannelSid = pathChannelSid; - this.pathSid = pathSid; + public InteractionTransferFetcher(final String pathinteractionSid, final String pathchannelSid, final String pathsid) { + this.pathinteractionSid = pathinteractionSid; + this.pathchannelSid = pathchannelSid; + this.pathsid = pathsid; } + @Override public InteractionTransfer fetch(final TwilioRestClient client) { - String path = - "/v1/Interactions/{InteractionSid}/Channels/{ChannelSid}/Transfers/{Sid}"; - path = - path.replace( - "{" + "InteractionSid" + "}", - this.pathInteractionSid.toString() - ); - path = - path.replace( - "{" + "ChannelSid" + "}", - this.pathChannelSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/v1/Interactions/{InteractionSid}/Channels/{ChannelSid}/Transfers/{Sid}"; + + path = path.replace("{" + "InteractionSid" + "}", this.pathinteractionSid.toString()); + path = path.replace("{" + "ChannelSid" + "}", this.pathchannelSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.FLEXAPI.toString(), - path + HttpMethod.GET, + Domains.FLEXAPI.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "InteractionTransfer fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("InteractionTransfer fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return InteractionTransfer.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return InteractionTransfer.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/flexapi/v1/interaction/interactionchannel/InteractionTransferUpdater.java b/src/main/java/com/twilio/rest/flexapi/v1/interaction/interactionchannel/InteractionTransferUpdater.java index 4c544c73da..443f180e07 100644 --- a/src/main/java/com/twilio/rest/flexapi/v1/interaction/interactionchannel/InteractionTransferUpdater.java +++ b/src/main/java/com/twilio/rest/flexapi/v1/interaction/interactionchannel/InteractionTransferUpdater.java @@ -27,74 +27,58 @@ import com.twilio.rest.Domains; public class InteractionTransferUpdater extends Updater { - - private String pathInteractionSid; - private String pathChannelSid; - private String pathSid; + private String pathinteractionSid; + private String pathchannelSid; + private String pathsid; private Object body; - public InteractionTransferUpdater( - final String pathInteractionSid, - final String pathChannelSid, - final String pathSid - ) { - this.pathInteractionSid = pathInteractionSid; - this.pathChannelSid = pathChannelSid; - this.pathSid = pathSid; + public InteractionTransferUpdater(final String pathinteractionSid, final String pathchannelSid, final String pathsid) { + this.pathinteractionSid = pathinteractionSid; + this.pathchannelSid = pathchannelSid; + this.pathsid = pathsid; } + public InteractionTransferUpdater setBody(final Object body) { this.body = body; return this; } + @Override public InteractionTransfer update(final TwilioRestClient client) { - String path = - "/v1/Interactions/{InteractionSid}/Channels/{ChannelSid}/Transfers/{Sid}"; - path = - path.replace( - "{" + "InteractionSid" + "}", - this.pathInteractionSid.toString() - ); - path = - path.replace( - "{" + "ChannelSid" + "}", - this.pathChannelSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/v1/Interactions/{InteractionSid}/Channels/{ChannelSid}/Transfers/{Sid}"; + + path = path.replace("{" + "InteractionSid" + "}", this.pathinteractionSid.toString()); + path = path.replace("{" + "ChannelSid" + "}", this.pathchannelSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.FLEXAPI.toString(), - path + HttpMethod.POST, + Domains.FLEXAPI.toString(), + path ); request.setContentType(EnumConstants.ContentType.JSON); addPostParams(request, client); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "InteractionTransfer update failed: Unable to connect to server" - ); + throw new ApiConnectionException("InteractionTransfer update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return InteractionTransfer.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return InteractionTransfer.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request, TwilioRestClient client) { diff --git a/src/main/java/com/twilio/rest/flexapi/v1/plugin/PluginVersions.java b/src/main/java/com/twilio/rest/flexapi/v1/plugin/PluginVersions.java index 706319a8e6..ca48b941c2 100644 --- a/src/main/java/com/twilio/rest/flexapi/v1/plugin/PluginVersions.java +++ b/src/main/java/com/twilio/rest/flexapi/v1/plugin/PluginVersions.java @@ -18,56 +18,56 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class PluginVersions extends Resource { - private static final long serialVersionUID = 230518982157206L; - public static PluginVersionsCreator creator( - final String pathPluginSid, - final String version, - final URI pluginUrl - ) { - return new PluginVersionsCreator(pathPluginSid, version, pluginUrl); + public static PluginVersionsCreator creator(final String pathpluginSid, final String version, final URI pluginUrl) { + return new PluginVersionsCreator( + pathpluginSid, version, pluginUrl + ); } - public static PluginVersionsFetcher fetcher( - final String pathPluginSid, - final String pathSid - ) { - return new PluginVersionsFetcher(pathPluginSid, pathSid); + + public static PluginVersionsFetcher fetcher(final String pathpluginSid, final String pathsid) { + return new PluginVersionsFetcher( + pathpluginSid, pathsid + ); } - public static PluginVersionsReader reader(final String pathPluginSid) { - return new PluginVersionsReader(pathPluginSid); + + public static PluginVersionsReader reader(final String pathpluginSid) { + return new PluginVersionsReader( + pathpluginSid + ); } + /** * Converts a JSON String into a PluginVersions object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return PluginVersions object represented by the provided JSON */ - public static PluginVersions fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static PluginVersions fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, PluginVersions.class); @@ -82,14 +82,11 @@ public static PluginVersions fromJson( * Converts a JSON InputStream into a PluginVersions object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return PluginVersions object represented by the provided JSON */ - public static PluginVersions fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static PluginVersions fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, PluginVersions.class); @@ -100,87 +97,68 @@ public static PluginVersions fromJson( } } - private final String sid; - private final String pluginSid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String version; - private final URI pluginUrl; - private final String changelog; - private final Boolean _private; + @Getter private final Boolean archived; - private final Boolean validated; + @Getter + private final String changelog; + @Getter private final ZonedDateTime dateCreated; + @Getter + private final String pluginSid; + @Getter + private final URI pluginUrl; + @Getter + private final Boolean _private; + @Getter + private final String sid; + @Getter private final URI url; + @Getter + private final Boolean validated; + @Getter + private final String version; @JsonCreator private PluginVersions( - @JsonProperty("sid") final String sid, - @JsonProperty("plugin_sid") final String pluginSid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("version") final String version, - @JsonProperty("plugin_url") final URI pluginUrl, - @JsonProperty("changelog") final String changelog, - @JsonProperty("_private") final Boolean _private, - @JsonProperty("archived") final Boolean archived, - @JsonProperty("validated") final Boolean validated, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("url") final URI url + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("archived") final Boolean archived, + @JsonProperty("changelog") final String changelog, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("plugin_sid") final String pluginSid, + @JsonProperty("plugin_url") final URI pluginUrl, + @JsonProperty("private") final Boolean _private, + @JsonProperty("sid") final String sid, + @JsonProperty("url") final URI url, + @JsonProperty("validated") final Boolean validated, + @JsonProperty("version") final String version ) { - this.sid = sid; - this.pluginSid = pluginSid; this.accountSid = accountSid; - this.version = version; - this.pluginUrl = pluginUrl; + this.archived = archived; this.changelog = changelog; + this.dateCreated = dateCreated; + this.pluginSid = pluginSid; + this.pluginUrl = pluginUrl; this._private = _private; - this.archived = archived; - this.validated = validated; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); + this.sid = sid; this.url = url; - } - - public final String getSid() { - return this.sid; - } - - public final String getPluginSid() { - return this.pluginSid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getVersion() { - return this.version; - } - - public final URI getPluginUrl() { - return this.pluginUrl; - } - - public final String getChangelog() { - return this.changelog; - } - - public final Boolean get_private() { - return this._private; - } - - public final Boolean getArchived() { - return this.archived; - } - - public final Boolean getValidated() { - return this.validated; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final URI getUrl() { - return this.url; + this.validated = validated; + this.version = version; } @Override @@ -194,36 +172,38 @@ public boolean equals(final Object o) { } PluginVersions other = (PluginVersions) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(pluginSid, other.pluginSid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(version, other.version) && - Objects.equals(pluginUrl, other.pluginUrl) && - Objects.equals(changelog, other.changelog) && - Objects.equals(_private, other._private) && - Objects.equals(archived, other.archived) && - Objects.equals(validated, other.validated) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(url, other.url) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(archived, other.archived) && + Objects.equals(changelog, other.changelog) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(pluginSid, other.pluginSid) && + Objects.equals(pluginUrl, other.pluginUrl) && + Objects.equals(_private, other._private) && + Objects.equals(sid, other.sid) && + Objects.equals(url, other.url) && + Objects.equals(validated, other.validated) && + Objects.equals(version, other.version) ); } @Override public int hashCode() { return Objects.hash( - sid, - pluginSid, - accountSid, - version, - pluginUrl, - changelog, - _private, - archived, - validated, - dateCreated, - url + accountSid, + archived, + changelog, + dateCreated, + pluginSid, + pluginUrl, + _private, + sid, + url, + validated, + version ); } + + } + diff --git a/src/main/java/com/twilio/rest/flexapi/v1/plugin/PluginVersionsCreator.java b/src/main/java/com/twilio/rest/flexapi/v1/plugin/PluginVersionsCreator.java index 70894981fe..fb1f12dde1 100644 --- a/src/main/java/com/twilio/rest/flexapi/v1/plugin/PluginVersionsCreator.java +++ b/src/main/java/com/twilio/rest/flexapi/v1/plugin/PluginVersionsCreator.java @@ -14,9 +14,11 @@ package com.twilio.rest.flexapi.v1.plugin; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; -import com.twilio.converter.Promoter; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,140 +27,143 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -import java.net.URI; + import java.net.URI; public class PluginVersionsCreator extends Creator { - private String pathPluginSid; + private String pathpluginSid; + private String flexMetadata; private String version; private URI pluginUrl; - private String flexMetadata; private String changelog; private Boolean _private; private String cliVersion; private String validateStatus; - public PluginVersionsCreator( - final String pathPluginSid, - final String version, - final URI pluginUrl - ) { - this.pathPluginSid = pathPluginSid; + public PluginVersionsCreator(final String pathpluginSid, final String version, final URI pluginUrl) { + this.pathpluginSid = pathpluginSid; this.version = version; this.pluginUrl = pluginUrl; } + public PluginVersionsCreator setVersion(final String version) { this.version = version; return this; } + public PluginVersionsCreator setPluginUrl(final URI pluginUrl) { this.pluginUrl = pluginUrl; return this; } - public PluginVersionsCreator setPluginUrl(final String pluginUrl) { - return setPluginUrl(Promoter.uriFromString(pluginUrl)); - } - - public PluginVersionsCreator setFlexMetadata(final String flexMetadata) { - this.flexMetadata = flexMetadata; - return this; - } public PluginVersionsCreator setChangelog(final String changelog) { this.changelog = changelog; return this; } + public PluginVersionsCreator set_private(final Boolean _private) { this._private = _private; return this; } + public PluginVersionsCreator setCliVersion(final String cliVersion) { this.cliVersion = cliVersion; return this; } - public PluginVersionsCreator setValidateStatus( - final String validateStatus - ) { + + public PluginVersionsCreator setValidateStatus(final String validateStatus) { this.validateStatus = validateStatus; return this; } + + public PluginVersionsCreator setFlexMetadata(final String flexMetadata) { + this.flexMetadata = flexMetadata; + return this; + } + + @Override public PluginVersions create(final TwilioRestClient client) { + String path = "/v1/PluginService/Plugins/{PluginSid}/Versions"; - path = - path.replace( - "{" + "PluginSid" + "}", - this.pathPluginSid.toString() - ); - path = path.replace("{" + "Version" + "}", this.version.toString()); - path = path.replace("{" + "PluginUrl" + "}", this.pluginUrl.toString()); + path = path.replace("{" + "PluginSid" + "}", this.pathpluginSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.FLEXAPI.toString(), - path + HttpMethod.POST, + Domains.FLEXAPI.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); - addPostParams(request); addHeaderParams(request); + addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "PluginVersions creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("PluginVersions creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return PluginVersions.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return PluginVersions.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (version != null) { - request.addPostParam("Version", version); + Serializer.toString(request, "Version", version, ParameterType.URLENCODED); } + + if (pluginUrl != null) { - request.addPostParam("PluginUrl", pluginUrl.toString()); + Serializer.toString(request, "PluginUrl", pluginUrl, ParameterType.URLENCODED); } + + if (changelog != null) { - request.addPostParam("Changelog", changelog); + Serializer.toString(request, "Changelog", changelog, ParameterType.URLENCODED); } + + if (_private != null) { - request.addPostParam("Private", _private.toString()); + Serializer.toString(request, "Private", _private, ParameterType.URLENCODED); } + + if (cliVersion != null) { - request.addPostParam("CliVersion", cliVersion); + Serializer.toString(request, "CliVersion", cliVersion, ParameterType.URLENCODED); } + + if (validateStatus != null) { - request.addPostParam("ValidateStatus", validateStatus); + Serializer.toString(request, "ValidateStatus", validateStatus, ParameterType.URLENCODED); } + + } private void addHeaderParams(final Request request) { + if (flexMetadata != null) { - request.addHeaderParam("Flex-Metadata", flexMetadata); + Serializer.toString(request, "Flex-Metadata", flexMetadata, ParameterType.HEADER); } + } } diff --git a/src/main/java/com/twilio/rest/flexapi/v1/plugin/PluginVersionsFetcher.java b/src/main/java/com/twilio/rest/flexapi/v1/plugin/PluginVersionsFetcher.java index d2519dfcb6..b9710a63ca 100644 --- a/src/main/java/com/twilio/rest/flexapi/v1/plugin/PluginVersionsFetcher.java +++ b/src/main/java/com/twilio/rest/flexapi/v1/plugin/PluginVersionsFetcher.java @@ -15,7 +15,8 @@ package com.twilio.rest.flexapi.v1.plugin; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,70 +28,60 @@ public class PluginVersionsFetcher extends Fetcher { - private String pathPluginSid; - private String pathSid; + private String pathpluginSid; + private String pathsid; private String flexMetadata; - public PluginVersionsFetcher( - final String pathPluginSid, - final String pathSid - ) { - this.pathPluginSid = pathPluginSid; - this.pathSid = pathSid; + public PluginVersionsFetcher(final String pathpluginSid, final String pathsid) { + this.pathpluginSid = pathpluginSid; + this.pathsid = pathsid; } + public PluginVersionsFetcher setFlexMetadata(final String flexMetadata) { this.flexMetadata = flexMetadata; return this; } + @Override public PluginVersions fetch(final TwilioRestClient client) { + String path = "/v1/PluginService/Plugins/{PluginSid}/Versions/{Sid}"; - path = - path.replace( - "{" + "PluginSid" + "}", - this.pathPluginSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "PluginSid" + "}", this.pathpluginSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.FLEXAPI.toString(), - path + HttpMethod.GET, + Domains.FLEXAPI.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addHeaderParams(request); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "PluginVersions fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("PluginVersions fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return PluginVersions.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return PluginVersions.fromJson(response.getStream(), client.getObjectMapper()); } private void addHeaderParams(final Request request) { + if (flexMetadata != null) { - request.addHeaderParam("Flex-Metadata", flexMetadata); + Serializer.toString(request, "Flex-Metadata", flexMetadata, ParameterType.HEADER); } + } } diff --git a/src/main/java/com/twilio/rest/flexapi/v1/plugin/PluginVersionsReader.java b/src/main/java/com/twilio/rest/flexapi/v1/plugin/PluginVersionsReader.java index f3268d84b4..34893689c2 100644 --- a/src/main/java/com/twilio/rest/flexapi/v1/plugin/PluginVersionsReader.java +++ b/src/main/java/com/twilio/rest/flexapi/v1/plugin/PluginVersionsReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,128 +30,104 @@ public class PluginVersionsReader extends Reader { - private String pathPluginSid; - private String flexMetadata; + private String pathpluginSid; private Long pageSize; + private String flexMetadata; - public PluginVersionsReader(final String pathPluginSid) { - this.pathPluginSid = pathPluginSid; + public PluginVersionsReader(final String pathpluginSid) { + this.pathpluginSid = pathpluginSid; } - public PluginVersionsReader setFlexMetadata(final String flexMetadata) { - this.flexMetadata = flexMetadata; - return this; - } public PluginVersionsReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + + public PluginVersionsReader setFlexMetadata(final String flexMetadata) { + this.flexMetadata = flexMetadata; + return this; + } + + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/PluginService/Plugins/{PluginSid}/Versions"; - path = - path.replace( - "{" + "PluginSid" + "}", - this.pathPluginSid.toString() - ); + + path = path.replace("{" + "PluginSid" + "}", this.pathpluginSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.FLEXAPI.toString(), - path + HttpMethod.GET, + Domains.FLEXAPI.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addHeaderParams(request); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "PluginVersions read failed: Unable to connect to server" - ); + throw new ApiConnectionException("PluginVersions read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "plugin_versions", - response.getContent(), - PluginVersions.class, - client.getObjectMapper() - ); + "plugin_versions", + response.getContent(), + PluginVersions.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.FLEXAPI.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.FLEXAPI.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } - private void addHeaderParams(final Request request) { - if (flexMetadata != null) { - request.addHeaderParam("Flex-Metadata", flexMetadata); - } - } - private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); + + } + + private void addHeaderParams(final Request request) { + + if (flexMetadata != null) { + Serializer.toString(request, "Flex-Metadata", flexMetadata, ParameterType.HEADER); } + } } diff --git a/src/main/java/com/twilio/rest/flexapi/v1/pluginconfiguration/ConfiguredPlugin.java b/src/main/java/com/twilio/rest/flexapi/v1/pluginconfiguration/ConfiguredPlugin.java index 9155572a90..63f2af67d3 100644 --- a/src/main/java/com/twilio/rest/flexapi/v1/pluginconfiguration/ConfiguredPlugin.java +++ b/src/main/java/com/twilio/rest/flexapi/v1/pluginconfiguration/ConfiguredPlugin.java @@ -18,50 +18,49 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class ConfiguredPlugin extends Resource { - private static final long serialVersionUID = 274363191205170L; - public static ConfiguredPluginFetcher fetcher( - final String pathConfigurationSid, - final String pathPluginSid - ) { - return new ConfiguredPluginFetcher(pathConfigurationSid, pathPluginSid); + public static ConfiguredPluginFetcher fetcher(final String pathconfigurationSid, final String pathpluginSid) { + return new ConfiguredPluginFetcher( + pathconfigurationSid, pathpluginSid + ); } - public static ConfiguredPluginReader reader( - final String pathConfigurationSid - ) { - return new ConfiguredPluginReader(pathConfigurationSid); + + public static ConfiguredPluginReader reader(final String pathconfigurationSid) { + return new ConfiguredPluginReader( + pathconfigurationSid + ); } + /** * Converts a JSON String into a ConfiguredPlugin object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return ConfiguredPlugin object represented by the provided JSON */ - public static ConfiguredPlugin fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static ConfiguredPlugin fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, ConfiguredPlugin.class); @@ -76,14 +75,11 @@ public static ConfiguredPlugin fromJson( * Converts a JSON InputStream into a ConfiguredPlugin object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return ConfiguredPlugin object represented by the provided JSON */ - public static ConfiguredPlugin fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static ConfiguredPlugin fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, ConfiguredPlugin.class); @@ -94,124 +90,88 @@ public static ConfiguredPlugin fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; + @Getter + private final String changelog; + @Getter private final String configurationSid; - private final String pluginSid; - private final String pluginVersionSid; - private final Integer phase; - private final String pluginUrl; - private final String uniqueName; - private final String friendlyName; + @Getter + private final ZonedDateTime dateCreated; + @Getter private final String description; + @Getter + private final String friendlyName; + @Getter + private final Integer phase; + @Getter private final Boolean pluginArchived; - private final String version; - private final String changelog; + @Getter + private final String pluginSid; + @Getter + private final String pluginUrl; + @Getter private final Boolean pluginVersionArchived; + @Getter + private final String pluginVersionSid; + @Getter private final Boolean _private; - private final ZonedDateTime dateCreated; + @Getter + private final String uniqueName; + @Getter private final URI url; + @Getter + private final String version; @JsonCreator private ConfiguredPlugin( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("configuration_sid") final String configurationSid, - @JsonProperty("plugin_sid") final String pluginSid, - @JsonProperty("plugin_version_sid") final String pluginVersionSid, - @JsonProperty("phase") final Integer phase, - @JsonProperty("plugin_url") final String pluginUrl, - @JsonProperty("unique_name") final String uniqueName, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("description") final String description, - @JsonProperty("plugin_archived") final Boolean pluginArchived, - @JsonProperty("version") final String version, - @JsonProperty("changelog") final String changelog, - @JsonProperty( - "plugin_version_archived" - ) final Boolean pluginVersionArchived, - @JsonProperty("_private") final Boolean _private, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("url") final URI url + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("changelog") final String changelog, + @JsonProperty("configuration_sid") final String configurationSid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("description") final String description, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("phase") final Integer phase, + @JsonProperty("plugin_archived") final Boolean pluginArchived, + @JsonProperty("plugin_sid") final String pluginSid, + @JsonProperty("plugin_url") final String pluginUrl, + @JsonProperty("plugin_version_archived") final Boolean pluginVersionArchived, + @JsonProperty("plugin_version_sid") final String pluginVersionSid, + @JsonProperty("private") final Boolean _private, + @JsonProperty("unique_name") final String uniqueName, + @JsonProperty("url") final URI url, + @JsonProperty("version") final String version ) { this.accountSid = accountSid; + this.changelog = changelog; this.configurationSid = configurationSid; - this.pluginSid = pluginSid; - this.pluginVersionSid = pluginVersionSid; - this.phase = phase; - this.pluginUrl = pluginUrl; - this.uniqueName = uniqueName; - this.friendlyName = friendlyName; + this.dateCreated = dateCreated; this.description = description; + this.friendlyName = friendlyName; + this.phase = phase; this.pluginArchived = pluginArchived; - this.version = version; - this.changelog = changelog; + this.pluginSid = pluginSid; + this.pluginUrl = pluginUrl; this.pluginVersionArchived = pluginVersionArchived; + this.pluginVersionSid = pluginVersionSid; this._private = _private; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); + this.uniqueName = uniqueName; this.url = url; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getConfigurationSid() { - return this.configurationSid; - } - - public final String getPluginSid() { - return this.pluginSid; - } - - public final String getPluginVersionSid() { - return this.pluginVersionSid; - } - - public final Integer getPhase() { - return this.phase; - } - - public final String getPluginUrl() { - return this.pluginUrl; - } - - public final String getUniqueName() { - return this.uniqueName; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final String getDescription() { - return this.description; - } - - public final Boolean getPluginArchived() { - return this.pluginArchived; - } - - public final String getVersion() { - return this.version; - } - - public final String getChangelog() { - return this.changelog; - } - - public final Boolean getPluginVersionArchived() { - return this.pluginVersionArchived; - } - - public final Boolean get_private() { - return this._private; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final URI getUrl() { - return this.url; + this.version = version; } @Override @@ -225,49 +185,48 @@ public boolean equals(final Object o) { } ConfiguredPlugin other = (ConfiguredPlugin) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(configurationSid, other.configurationSid) && - Objects.equals(pluginSid, other.pluginSid) && - Objects.equals(pluginVersionSid, other.pluginVersionSid) && - Objects.equals(phase, other.phase) && - Objects.equals(pluginUrl, other.pluginUrl) && - Objects.equals(uniqueName, other.uniqueName) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(description, other.description) && - Objects.equals(pluginArchived, other.pluginArchived) && - Objects.equals(version, other.version) && - Objects.equals(changelog, other.changelog) && - Objects.equals( - pluginVersionArchived, - other.pluginVersionArchived - ) && - Objects.equals(_private, other._private) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(url, other.url) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(changelog, other.changelog) && + Objects.equals(configurationSid, other.configurationSid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(description, other.description) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(phase, other.phase) && + Objects.equals(pluginArchived, other.pluginArchived) && + Objects.equals(pluginSid, other.pluginSid) && + Objects.equals(pluginUrl, other.pluginUrl) && + Objects.equals(pluginVersionArchived, other.pluginVersionArchived) && + Objects.equals(pluginVersionSid, other.pluginVersionSid) && + Objects.equals(_private, other._private) && + Objects.equals(uniqueName, other.uniqueName) && + Objects.equals(url, other.url) && + Objects.equals(version, other.version) ); } @Override public int hashCode() { return Objects.hash( - accountSid, - configurationSid, - pluginSid, - pluginVersionSid, - phase, - pluginUrl, - uniqueName, - friendlyName, - description, - pluginArchived, - version, - changelog, - pluginVersionArchived, - _private, - dateCreated, - url + accountSid, + changelog, + configurationSid, + dateCreated, + description, + friendlyName, + phase, + pluginArchived, + pluginSid, + pluginUrl, + pluginVersionArchived, + pluginVersionSid, + _private, + uniqueName, + url, + version ); } + + } + diff --git a/src/main/java/com/twilio/rest/flexapi/v1/pluginconfiguration/ConfiguredPluginFetcher.java b/src/main/java/com/twilio/rest/flexapi/v1/pluginconfiguration/ConfiguredPluginFetcher.java index 0e28c45fce..b2c023af2a 100644 --- a/src/main/java/com/twilio/rest/flexapi/v1/pluginconfiguration/ConfiguredPluginFetcher.java +++ b/src/main/java/com/twilio/rest/flexapi/v1/pluginconfiguration/ConfiguredPluginFetcher.java @@ -15,7 +15,8 @@ package com.twilio.rest.flexapi.v1.pluginconfiguration; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,75 +28,60 @@ public class ConfiguredPluginFetcher extends Fetcher { - private String pathConfigurationSid; - private String pathPluginSid; + private String pathconfigurationSid; + private String pathpluginSid; private String flexMetadata; - public ConfiguredPluginFetcher( - final String pathConfigurationSid, - final String pathPluginSid - ) { - this.pathConfigurationSid = pathConfigurationSid; - this.pathPluginSid = pathPluginSid; + public ConfiguredPluginFetcher(final String pathconfigurationSid, final String pathpluginSid) { + this.pathconfigurationSid = pathconfigurationSid; + this.pathpluginSid = pathpluginSid; } + public ConfiguredPluginFetcher setFlexMetadata(final String flexMetadata) { this.flexMetadata = flexMetadata; return this; } + @Override public ConfiguredPlugin fetch(final TwilioRestClient client) { - String path = - "/v1/PluginService/Configurations/{ConfigurationSid}/Plugins/{PluginSid}"; - path = - path.replace( - "{" + "ConfigurationSid" + "}", - this.pathConfigurationSid.toString() - ); - path = - path.replace( - "{" + "PluginSid" + "}", - this.pathPluginSid.toString() - ); + String path = "/v1/PluginService/Configurations/{ConfigurationSid}/Plugins/{PluginSid}"; + + path = path.replace("{" + "ConfigurationSid" + "}", this.pathconfigurationSid.toString()); + path = path.replace("{" + "PluginSid" + "}", this.pathpluginSid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.FLEXAPI.toString(), - path + HttpMethod.GET, + Domains.FLEXAPI.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addHeaderParams(request); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "ConfiguredPlugin fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("ConfiguredPlugin fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return ConfiguredPlugin.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return ConfiguredPlugin.fromJson(response.getStream(), client.getObjectMapper()); } private void addHeaderParams(final Request request) { + if (flexMetadata != null) { - request.addHeaderParam("Flex-Metadata", flexMetadata); + Serializer.toString(request, "Flex-Metadata", flexMetadata, ParameterType.HEADER); } + } } diff --git a/src/main/java/com/twilio/rest/flexapi/v1/pluginconfiguration/ConfiguredPluginReader.java b/src/main/java/com/twilio/rest/flexapi/v1/pluginconfiguration/ConfiguredPluginReader.java index 72958fb8a9..ae1c467f94 100644 --- a/src/main/java/com/twilio/rest/flexapi/v1/pluginconfiguration/ConfiguredPluginReader.java +++ b/src/main/java/com/twilio/rest/flexapi/v1/pluginconfiguration/ConfiguredPluginReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,129 +30,104 @@ public class ConfiguredPluginReader extends Reader { - private String pathConfigurationSid; - private String flexMetadata; + private String pathconfigurationSid; private Long pageSize; + private String flexMetadata; - public ConfiguredPluginReader(final String pathConfigurationSid) { - this.pathConfigurationSid = pathConfigurationSid; + public ConfiguredPluginReader(final String pathconfigurationSid) { + this.pathconfigurationSid = pathconfigurationSid; } - public ConfiguredPluginReader setFlexMetadata(final String flexMetadata) { - this.flexMetadata = flexMetadata; - return this; - } public ConfiguredPluginReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + + public ConfiguredPluginReader setFlexMetadata(final String flexMetadata) { + this.flexMetadata = flexMetadata; + return this; + } + + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { - String path = - "/v1/PluginService/Configurations/{ConfigurationSid}/Plugins"; - path = - path.replace( - "{" + "ConfigurationSid" + "}", - this.pathConfigurationSid.toString() - ); + + String path = "/v1/PluginService/Configurations/{ConfigurationSid}/Plugins"; + + path = path.replace("{" + "ConfigurationSid" + "}", this.pathconfigurationSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.FLEXAPI.toString(), - path + HttpMethod.GET, + Domains.FLEXAPI.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addHeaderParams(request); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "ConfiguredPlugin read failed: Unable to connect to server" - ); + throw new ApiConnectionException("ConfiguredPlugin read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "plugins", - response.getContent(), - ConfiguredPlugin.class, - client.getObjectMapper() - ); + "plugins", + response.getContent(), + ConfiguredPlugin.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.FLEXAPI.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.FLEXAPI.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } - private void addHeaderParams(final Request request) { - if (flexMetadata != null) { - request.addHeaderParam("Flex-Metadata", flexMetadata); - } - } - private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); + + } + + private void addHeaderParams(final Request request) { + + if (flexMetadata != null) { + Serializer.toString(request, "Flex-Metadata", flexMetadata, ParameterType.HEADER); } + } } diff --git a/src/main/java/com/twilio/rest/flexapi/v2/FlexUser.java b/src/main/java/com/twilio/rest/flexapi/v2/FlexUser.java index 6c24fef3c1..389a5a6c97 100644 --- a/src/main/java/com/twilio/rest/flexapi/v2/FlexUser.java +++ b/src/main/java/com/twilio/rest/flexapi/v2/FlexUser.java @@ -18,52 +18,50 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.List; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class FlexUser extends Resource { - private static final long serialVersionUID = 33792747593719L; - public static FlexUserFetcher fetcher( - final String pathInstanceSid, - final String pathFlexUserSid - ) { - return new FlexUserFetcher(pathInstanceSid, pathFlexUserSid); + public static FlexUserFetcher fetcher(final String pathinstanceSid, final String pathflexUserSid) { + return new FlexUserFetcher( + pathinstanceSid, pathflexUserSid + ); } - public static FlexUserUpdater updater( - final String pathInstanceSid, - final String pathFlexUserSid - ) { - return new FlexUserUpdater(pathInstanceSid, pathFlexUserSid); + + public static FlexUserUpdater updater(final String pathinstanceSid, final String pathflexUserSid) { + return new FlexUserUpdater( + pathinstanceSid, pathflexUserSid + ); } + /** * Converts a JSON String into a FlexUser object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return FlexUser object represented by the provided JSON */ - public static FlexUser fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static FlexUser fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, FlexUser.class); @@ -78,14 +76,11 @@ public static FlexUser fromJson( * Converts a JSON InputStream into a FlexUser object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return FlexUser object represented by the provided JSON */ - public static FlexUser fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static FlexUser fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, FlexUser.class); @@ -96,115 +91,85 @@ public static FlexUser fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String instanceSid; - private final String userSid; - private final String flexUserSid; - private final String workerSid; - private final String workspaceSid; - private final String flexTeamSid; - private final String username; + @Getter + private final ZonedDateTime createdDate; + @Getter private final String email; + @Getter + private final String flexTeamSid; + @Getter + private final String flexUserSid; + @Getter + private final String instanceSid; + @Getter private final String locale; + @Getter private final List roles; - private final ZonedDateTime createdDate; + @Getter private final ZonedDateTime updatedDate; - private final Integer version; + @Getter private final URI url; + @Getter + private final String userSid; + @Getter + private final String username; + @Getter + private final Integer version; + @Getter + private final String workerSid; + @Getter + private final String workspaceSid; @JsonCreator private FlexUser( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("instance_sid") final String instanceSid, - @JsonProperty("user_sid") final String userSid, - @JsonProperty("flex_user_sid") final String flexUserSid, - @JsonProperty("worker_sid") final String workerSid, - @JsonProperty("workspace_sid") final String workspaceSid, - @JsonProperty("flex_team_sid") final String flexTeamSid, - @JsonProperty("username") final String username, - @JsonProperty("email") final String email, - @JsonProperty("locale") final String locale, - @JsonProperty("roles") final List roles, - @JsonProperty("created_date") final String createdDate, - @JsonProperty("updated_date") final String updatedDate, - @JsonProperty("version") final Integer version, - @JsonProperty("url") final URI url + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("created_date") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime createdDate, + @JsonProperty("email") final String email, + @JsonProperty("flex_team_sid") final String flexTeamSid, + @JsonProperty("flex_user_sid") final String flexUserSid, + @JsonProperty("instance_sid") final String instanceSid, + @JsonProperty("locale") final String locale, + @JsonProperty("roles") final List roles, + @JsonProperty("updated_date") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime updatedDate, + @JsonProperty("url") final URI url, + @JsonProperty("user_sid") final String userSid, + @JsonProperty("username") final String username, + @JsonProperty("version") final Integer version, + @JsonProperty("worker_sid") final String workerSid, + @JsonProperty("workspace_sid") final String workspaceSid ) { this.accountSid = accountSid; - this.instanceSid = instanceSid; - this.userSid = userSid; - this.flexUserSid = flexUserSid; - this.workerSid = workerSid; - this.workspaceSid = workspaceSid; - this.flexTeamSid = flexTeamSid; - this.username = username; + this.createdDate = createdDate; this.email = email; + this.flexTeamSid = flexTeamSid; + this.flexUserSid = flexUserSid; + this.instanceSid = instanceSid; this.locale = locale; this.roles = roles; - this.createdDate = DateConverter.iso8601DateTimeFromString(createdDate); - this.updatedDate = DateConverter.iso8601DateTimeFromString(updatedDate); - this.version = version; + this.updatedDate = updatedDate; this.url = url; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getInstanceSid() { - return this.instanceSid; - } - - public final String getUserSid() { - return this.userSid; - } - - public final String getFlexUserSid() { - return this.flexUserSid; - } - - public final String getWorkerSid() { - return this.workerSid; - } - - public final String getWorkspaceSid() { - return this.workspaceSid; - } - - public final String getFlexTeamSid() { - return this.flexTeamSid; - } - - public final String getUsername() { - return this.username; - } - - public final String getEmail() { - return this.email; - } - - public final String getLocale() { - return this.locale; - } - - public final List getRoles() { - return this.roles; - } - - public final ZonedDateTime getCreatedDate() { - return this.createdDate; - } - - public final ZonedDateTime getUpdatedDate() { - return this.updatedDate; - } - - public final Integer getVersion() { - return this.version; - } - - public final URI getUrl() { - return this.url; + this.userSid = userSid; + this.username = username; + this.version = version; + this.workerSid = workerSid; + this.workspaceSid = workspaceSid; } @Override @@ -218,44 +183,46 @@ public boolean equals(final Object o) { } FlexUser other = (FlexUser) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(instanceSid, other.instanceSid) && - Objects.equals(userSid, other.userSid) && - Objects.equals(flexUserSid, other.flexUserSid) && - Objects.equals(workerSid, other.workerSid) && - Objects.equals(workspaceSid, other.workspaceSid) && - Objects.equals(flexTeamSid, other.flexTeamSid) && - Objects.equals(username, other.username) && - Objects.equals(email, other.email) && - Objects.equals(locale, other.locale) && - Objects.equals(roles, other.roles) && - Objects.equals(createdDate, other.createdDate) && - Objects.equals(updatedDate, other.updatedDate) && - Objects.equals(version, other.version) && - Objects.equals(url, other.url) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(createdDate, other.createdDate) && + Objects.equals(email, other.email) && + Objects.equals(flexTeamSid, other.flexTeamSid) && + Objects.equals(flexUserSid, other.flexUserSid) && + Objects.equals(instanceSid, other.instanceSid) && + Objects.equals(locale, other.locale) && + Objects.equals(roles, other.roles) && + Objects.equals(updatedDate, other.updatedDate) && + Objects.equals(url, other.url) && + Objects.equals(userSid, other.userSid) && + Objects.equals(username, other.username) && + Objects.equals(version, other.version) && + Objects.equals(workerSid, other.workerSid) && + Objects.equals(workspaceSid, other.workspaceSid) ); } @Override public int hashCode() { return Objects.hash( - accountSid, - instanceSid, - userSid, - flexUserSid, - workerSid, - workspaceSid, - flexTeamSid, - username, - email, - locale, - roles, - createdDate, - updatedDate, - version, - url + accountSid, + createdDate, + email, + flexTeamSid, + flexUserSid, + instanceSid, + locale, + roles, + updatedDate, + url, + userSid, + username, + version, + workerSid, + workspaceSid ); } + + } + diff --git a/src/main/java/com/twilio/rest/flexapi/v2/FlexUserFetcher.java b/src/main/java/com/twilio/rest/flexapi/v2/FlexUserFetcher.java index 1f3762a395..4a2fd69528 100644 --- a/src/main/java/com/twilio/rest/flexapi/v2/FlexUserFetcher.java +++ b/src/main/java/com/twilio/rest/flexapi/v2/FlexUserFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.flexapi.v2; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,61 +26,44 @@ public class FlexUserFetcher extends Fetcher { - private String pathInstanceSid; - private String pathFlexUserSid; + private String pathinstanceSid; + private String pathflexUserSid; - public FlexUserFetcher( - final String pathInstanceSid, - final String pathFlexUserSid - ) { - this.pathInstanceSid = pathInstanceSid; - this.pathFlexUserSid = pathFlexUserSid; + public FlexUserFetcher(final String pathinstanceSid, final String pathflexUserSid) { + this.pathinstanceSid = pathinstanceSid; + this.pathflexUserSid = pathflexUserSid; } + @Override public FlexUser fetch(final TwilioRestClient client) { + String path = "/v2/Instances/{InstanceSid}/Users/{FlexUserSid}"; - path = - path.replace( - "{" + "InstanceSid" + "}", - this.pathInstanceSid.toString() - ); - path = - path.replace( - "{" + "FlexUserSid" + "}", - this.pathFlexUserSid.toString() - ); + path = path.replace("{" + "InstanceSid" + "}", this.pathinstanceSid.toString()); + path = path.replace("{" + "FlexUserSid" + "}", this.pathflexUserSid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.FLEXAPI.toString(), - path + HttpMethod.GET, + Domains.FLEXAPI.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "FlexUser fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("FlexUser fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return FlexUser.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return FlexUser.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/flexapi/v2/FlexUserUpdater.java b/src/main/java/com/twilio/rest/flexapi/v2/FlexUserUpdater.java index 342550ec0f..297310f2a7 100644 --- a/src/main/java/com/twilio/rest/flexapi/v2/FlexUserUpdater.java +++ b/src/main/java/com/twilio/rest/flexapi/v2/FlexUserUpdater.java @@ -16,6 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -26,92 +28,87 @@ import com.twilio.rest.Domains; public class FlexUserUpdater extends Updater { - - private String pathInstanceSid; - private String pathFlexUserSid; + private String pathinstanceSid; + private String pathflexUserSid; private String email; private String userSid; private String locale; - public FlexUserUpdater( - final String pathInstanceSid, - final String pathFlexUserSid - ) { - this.pathInstanceSid = pathInstanceSid; - this.pathFlexUserSid = pathFlexUserSid; + public FlexUserUpdater(final String pathinstanceSid, final String pathflexUserSid) { + this.pathinstanceSid = pathinstanceSid; + this.pathflexUserSid = pathflexUserSid; } + public FlexUserUpdater setEmail(final String email) { this.email = email; return this; } + public FlexUserUpdater setUserSid(final String userSid) { this.userSid = userSid; return this; } + public FlexUserUpdater setLocale(final String locale) { this.locale = locale; return this; } + @Override public FlexUser update(final TwilioRestClient client) { + String path = "/v2/Instances/{InstanceSid}/Users/{FlexUserSid}"; - path = - path.replace( - "{" + "InstanceSid" + "}", - this.pathInstanceSid.toString() - ); - path = - path.replace( - "{" + "FlexUserSid" + "}", - this.pathFlexUserSid.toString() - ); + path = path.replace("{" + "InstanceSid" + "}", this.pathinstanceSid.toString()); + path = path.replace("{" + "FlexUserSid" + "}", this.pathflexUserSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.FLEXAPI.toString(), - path + HttpMethod.POST, + Domains.FLEXAPI.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "FlexUser update failed: Unable to connect to server" - ); + throw new ApiConnectionException("FlexUser update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return FlexUser.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return FlexUser.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (email != null) { - request.addPostParam("Email", email); + Serializer.toString(request, "Email", email, ParameterType.URLENCODED); } + + if (userSid != null) { - request.addPostParam("UserSid", userSid); + Serializer.toString(request, "UserSid", userSid, ParameterType.URLENCODED); } + + if (locale != null) { - request.addPostParam("Locale", locale); + Serializer.toString(request, "Locale", locale, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/flexapi/v2/WebChannels.java b/src/main/java/com/twilio/rest/flexapi/v2/WebChannels.java index dfa57a58df..22044a306e 100644 --- a/src/main/java/com/twilio/rest/flexapi/v2/WebChannels.java +++ b/src/main/java/com/twilio/rest/flexapi/v2/WebChannels.java @@ -18,38 +18,39 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class WebChannels extends Resource { - private static final long serialVersionUID = 110421660015552L; public static WebChannelsCreator creator(final String addressSid) { - return new WebChannelsCreator(addressSid); + return new WebChannelsCreator( + addressSid + ); } + /** * Converts a JSON String into a WebChannels object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return WebChannels object represented by the provided JSON */ - public static WebChannels fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static WebChannels fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, WebChannels.class); @@ -64,14 +65,11 @@ public static WebChannels fromJson( * Converts a JSON InputStream into a WebChannels object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return WebChannels object represented by the provided JSON */ - public static WebChannels fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static WebChannels fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, WebChannels.class); @@ -82,26 +80,33 @@ public static WebChannels fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String conversationSid; + @Getter private final String identity; @JsonCreator private WebChannels( - @JsonProperty("conversation_sid") final String conversationSid, - @JsonProperty("identity") final String identity + @JsonProperty("conversation_sid") final String conversationSid, + @JsonProperty("identity") final String identity ) { this.conversationSid = conversationSid; this.identity = identity; } - public final String getConversationSid() { - return this.conversationSid; - } - - public final String getIdentity() { - return this.identity; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -113,15 +118,20 @@ public boolean equals(final Object o) { } WebChannels other = (WebChannels) o; - return ( - Objects.equals(conversationSid, other.conversationSid) && - Objects.equals(identity, other.identity) + Objects.equals(conversationSid, other.conversationSid) && + Objects.equals(identity, other.identity) ); } @Override public int hashCode() { - return Objects.hash(conversationSid, identity); + return Objects.hash( + conversationSid, + identity + ); } + + } + diff --git a/src/main/java/com/twilio/rest/flexapi/v2/WebChannelsCreator.java b/src/main/java/com/twilio/rest/flexapi/v2/WebChannelsCreator.java index 764380105a..79b30b93ed 100644 --- a/src/main/java/com/twilio/rest/flexapi/v2/WebChannelsCreator.java +++ b/src/main/java/com/twilio/rest/flexapi/v2/WebChannelsCreator.java @@ -14,8 +14,11 @@ package com.twilio.rest.flexapi.v2; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,8 +30,8 @@ public class WebChannelsCreator extends Creator { - private String addressSid; private String uiVersion; + private String addressSid; private String chatFriendlyName; private String customerFriendlyName; private String preEngagementData; @@ -38,103 +41,110 @@ public WebChannelsCreator(final String addressSid) { this.addressSid = addressSid; } + public WebChannelsCreator setAddressSid(final String addressSid) { this.addressSid = addressSid; return this; } - public WebChannelsCreator setUiVersion(final String uiVersion) { - this.uiVersion = uiVersion; - return this; - } - public WebChannelsCreator setChatFriendlyName( - final String chatFriendlyName - ) { + public WebChannelsCreator setChatFriendlyName(final String chatFriendlyName) { this.chatFriendlyName = chatFriendlyName; return this; } - public WebChannelsCreator setCustomerFriendlyName( - final String customerFriendlyName - ) { + + public WebChannelsCreator setCustomerFriendlyName(final String customerFriendlyName) { this.customerFriendlyName = customerFriendlyName; return this; } - public WebChannelsCreator setPreEngagementData( - final String preEngagementData - ) { + + public WebChannelsCreator setPreEngagementData(final String preEngagementData) { this.preEngagementData = preEngagementData; return this; } + public WebChannelsCreator setIdentity(final String identity) { this.identity = identity; return this; } + + public WebChannelsCreator setUiVersion(final String uiVersion) { + this.uiVersion = uiVersion; + return this; + } + + @Override public WebChannels create(final TwilioRestClient client) { + String path = "/v2/WebChats"; - path = - path.replace("{" + "AddressSid" + "}", this.addressSid.toString()); Request request = new Request( - HttpMethod.POST, - Domains.FLEXAPI.toString(), - path + HttpMethod.POST, + Domains.FLEXAPI.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); - addPostParams(request); addHeaderParams(request); + addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "WebChannels creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("WebChannels creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return WebChannels.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return WebChannels.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (addressSid != null) { - request.addPostParam("AddressSid", addressSid); + Serializer.toString(request, "AddressSid", addressSid, ParameterType.URLENCODED); } + + if (chatFriendlyName != null) { - request.addPostParam("ChatFriendlyName", chatFriendlyName); + Serializer.toString(request, "ChatFriendlyName", chatFriendlyName, ParameterType.URLENCODED); } + + if (customerFriendlyName != null) { - request.addPostParam("CustomerFriendlyName", customerFriendlyName); + Serializer.toString(request, "CustomerFriendlyName", customerFriendlyName, ParameterType.URLENCODED); } + + if (preEngagementData != null) { - request.addPostParam("PreEngagementData", preEngagementData); + Serializer.toString(request, "PreEngagementData", preEngagementData, ParameterType.URLENCODED); } + + if (identity != null) { - request.addPostParam("Identity", identity); + Serializer.toString(request, "Identity", identity, ParameterType.URLENCODED); } + + } private void addHeaderParams(final Request request) { + if (uiVersion != null) { - request.addHeaderParam("Ui-Version", uiVersion); + Serializer.toString(request, "Ui-Version", uiVersion, ParameterType.HEADER); } + } } diff --git a/src/main/java/com/twilio/rest/frontlineapi/v1/User.java b/src/main/java/com/twilio/rest/frontlineapi/v1/User.java index 3534892247..f179ad1ce9 100644 --- a/src/main/java/com/twilio/rest/frontlineapi/v1/User.java +++ b/src/main/java/com/twilio/rest/frontlineapi/v1/User.java @@ -18,44 +18,69 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class User extends Resource { - private static final long serialVersionUID = 253333531578389L; - public static UserFetcher fetcher(final String pathSid) { - return new UserFetcher(pathSid); + public static UserFetcher fetcher(final String pathsid) { + return new UserFetcher( + pathsid + ); } - public static UserUpdater updater(final String pathSid) { - return new UserUpdater(pathSid); + + public static UserUpdater updater(final String pathsid) { + return new UserUpdater( + pathsid + ); } + + public enum StateType { + ACTIVE("active"), + DEACTIVATED("deactivated"); + + private final String value; + + private StateType(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static StateType forValue(final String value) { + return Promoter.enumFromString(value, StateType.values()); + } + } + + /** * Converts a JSON String into a User object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return User object represented by the provided JSON */ - public static User fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static User fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, User.class); @@ -70,14 +95,11 @@ public static User fromJson( * Converts a JSON InputStream into a User object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return User object represented by the provided JSON */ - public static User fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static User fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, User.class); @@ -88,61 +110,53 @@ public static User fromJson( } } - private final String sid; - private final String identity; - private final String friendlyName; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String avatar; - private final User.StateType state; + @Getter + private final String friendlyName; + @Getter + private final String identity; + @Getter private final Boolean isAvailable; + @Getter + private final String sid; + @Getter + private final User.StateType state; + @Getter private final URI url; @JsonCreator private User( - @JsonProperty("sid") final String sid, - @JsonProperty("identity") final String identity, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("avatar") final String avatar, - @JsonProperty("state") final User.StateType state, - @JsonProperty("is_available") final Boolean isAvailable, - @JsonProperty("url") final URI url + @JsonProperty("avatar") final String avatar, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("identity") final String identity, + @JsonProperty("is_available") final Boolean isAvailable, + @JsonProperty("sid") final String sid, + @JsonProperty("state") final User.StateType state, + @JsonProperty("url") final URI url ) { - this.sid = sid; - this.identity = identity; - this.friendlyName = friendlyName; this.avatar = avatar; - this.state = state; + this.friendlyName = friendlyName; + this.identity = identity; this.isAvailable = isAvailable; + this.sid = sid; + this.state = state; this.url = url; } - public final String getSid() { - return this.sid; - } - - public final String getIdentity() { - return this.identity; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final String getAvatar() { - return this.avatar; - } - - public final User.StateType getState() { - return this.state; - } - - public final Boolean getIsAvailable() { - return this.isAvailable; - } - - public final URI getUrl() { - return this.url; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -154,48 +168,30 @@ public boolean equals(final Object o) { } User other = (User) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(identity, other.identity) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(avatar, other.avatar) && - Objects.equals(state, other.state) && - Objects.equals(isAvailable, other.isAvailable) && - Objects.equals(url, other.url) + Objects.equals(avatar, other.avatar) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(identity, other.identity) && + Objects.equals(isAvailable, other.isAvailable) && + Objects.equals(sid, other.sid) && + Objects.equals(state, other.state) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - sid, - identity, - friendlyName, - avatar, - state, - isAvailable, - url + avatar, + friendlyName, + identity, + isAvailable, + sid, + state, + url ); } - public enum StateType { - ACTIVE("active"), - DEACTIVATED("deactivated"); - - private final String value; - - private StateType(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - @JsonCreator - public static StateType forValue(final String value) { - return Promoter.enumFromString(value, StateType.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/frontlineapi/v1/UserFetcher.java b/src/main/java/com/twilio/rest/frontlineapi/v1/UserFetcher.java index bf1d38fbe7..8239379026 100644 --- a/src/main/java/com/twilio/rest/frontlineapi/v1/UserFetcher.java +++ b/src/main/java/com/twilio/rest/frontlineapi/v1/UserFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.frontlineapi.v1; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,44 +26,41 @@ public class UserFetcher extends Fetcher { - private String pathSid; + private String pathsid; - public UserFetcher(final String pathSid) { - this.pathSid = pathSid; + public UserFetcher(final String pathsid) { + this.pathsid = pathsid; } + @Override public User fetch(final TwilioRestClient client) { + String path = "/v1/Users/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.FRONTLINEAPI.toString(), - path + HttpMethod.GET, + Domains.FRONTLINEAPI.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "User fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("User fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return User.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/frontlineapi/v1/UserUpdater.java b/src/main/java/com/twilio/rest/frontlineapi/v1/UserUpdater.java index a143663167..00d6155fcf 100644 --- a/src/main/java/com/twilio/rest/frontlineapi/v1/UserUpdater.java +++ b/src/main/java/com/twilio/rest/frontlineapi/v1/UserUpdater.java @@ -16,6 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -26,65 +28,68 @@ import com.twilio.rest.Domains; public class UserUpdater extends Updater { - - private String pathSid; + private String pathsid; private String friendlyName; private String avatar; private User.StateType state; private Boolean isAvailable; - public UserUpdater(final String pathSid) { - this.pathSid = pathSid; + public UserUpdater(final String pathsid) { + this.pathsid = pathsid; } + public UserUpdater setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + public UserUpdater setAvatar(final String avatar) { this.avatar = avatar; return this; } + public UserUpdater setState(final User.StateType state) { this.state = state; return this; } + public UserUpdater setIsAvailable(final Boolean isAvailable) { this.isAvailable = isAvailable; return this; } + @Override public User update(final TwilioRestClient client) { + String path = "/v1/Users/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.FRONTLINEAPI.toString(), - path + HttpMethod.POST, + Domains.FRONTLINEAPI.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "User update failed: Unable to connect to server" - ); + throw new ApiConnectionException("User update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -93,17 +98,26 @@ public User update(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + if (avatar != null) { - request.addPostParam("Avatar", avatar); + Serializer.toString(request, "Avatar", avatar, ParameterType.URLENCODED); } + + if (state != null) { - request.addPostParam("State", state.toString()); + Serializer.toString(request, "State", state, ParameterType.URLENCODED); } + + if (isAvailable != null) { - request.addPostParam("IsAvailable", isAvailable.toString()); + Serializer.toString(request, "IsAvailable", isAvailable, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/iam/v1/ApiKey.java b/src/main/java/com/twilio/rest/iam/v1/ApiKey.java index 519cee74ea..5791f4e6ed 100644 --- a/src/main/java/com/twilio/rest/iam/v1/ApiKey.java +++ b/src/main/java/com/twilio/rest/iam/v1/ApiKey.java @@ -18,50 +18,55 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.time.ZonedDateTime; -import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class ApiKey extends Resource { - private static final long serialVersionUID = 99197666922652L; - public static ApiKeyDeleter deleter(final String pathSid) { - return new ApiKeyDeleter(pathSid); + public static ApiKeyDeleter deleter(final String pathsid) { + return new ApiKeyDeleter( + pathsid + ); } - public static ApiKeyFetcher fetcher(final String pathSid) { - return new ApiKeyFetcher(pathSid); + + public static ApiKeyFetcher fetcher(final String pathsid) { + return new ApiKeyFetcher( + pathsid + ); } - public static ApiKeyUpdater updater(final String pathSid) { - return new ApiKeyUpdater(pathSid); + + public static ApiKeyUpdater updater(final String pathsid) { + return new ApiKeyUpdater( + pathsid + ); } + /** * Converts a JSON String into a ApiKey object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return ApiKey object represented by the provided JSON */ - public static ApiKey fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static ApiKey fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, ApiKey.class); @@ -76,14 +81,11 @@ public static ApiKey fromJson( * Converts a JSON InputStream into a ApiKey object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return ApiKey object represented by the provided JSON */ - public static ApiKey fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static ApiKey fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, ApiKey.class); @@ -94,45 +96,45 @@ public static ApiKey fromJson( } } - private final String sid; - private final String friendlyName; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; - private final Map policy; + @Getter + private final String friendlyName; + @Getter + private final Object policy; + @Getter + private final String sid; @JsonCreator private ApiKey( - @JsonProperty("sid") final String sid, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("policy") final Map policy + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.RFC2822Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.RFC2822Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("policy") final Object policy, + @JsonProperty("sid") final String sid ) { - this.sid = sid; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.friendlyName = friendlyName; - this.dateCreated = DateConverter.rfc2822DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.rfc2822DateTimeFromString(dateUpdated); this.policy = policy; - } - - public final String getSid() { - return this.sid; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final Map getPolicy() { - return this.policy; + this.sid = sid; } @Override @@ -146,24 +148,26 @@ public boolean equals(final Object o) { } ApiKey other = (ApiKey) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(policy, other.policy) + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(policy, other.policy) && + Objects.equals(sid, other.sid) ); } @Override public int hashCode() { return Objects.hash( - sid, - friendlyName, - dateCreated, - dateUpdated, - policy + dateCreated, + dateUpdated, + friendlyName, + policy, + sid ); } + + } + diff --git a/src/main/java/com/twilio/rest/iam/v1/ApiKeyDeleter.java b/src/main/java/com/twilio/rest/iam/v1/ApiKeyDeleter.java index a615f94712..94a78756cf 100644 --- a/src/main/java/com/twilio/rest/iam/v1/ApiKeyDeleter.java +++ b/src/main/java/com/twilio/rest/iam/v1/ApiKeyDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.iam.v1; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,40 +26,38 @@ public class ApiKeyDeleter extends Deleter { - private String pathSid; + private String pathsid; - public ApiKeyDeleter(final String pathSid) { - this.pathSid = pathSid; + public ApiKeyDeleter(final String pathsid) { + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/v1/Keys/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.IAM.toString(), - path + HttpMethod.DELETE, + Domains.IAM.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "ApiKey delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("ApiKey delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/iam/v1/ApiKeyFetcher.java b/src/main/java/com/twilio/rest/iam/v1/ApiKeyFetcher.java index ade5a6daa7..3117b9af30 100644 --- a/src/main/java/com/twilio/rest/iam/v1/ApiKeyFetcher.java +++ b/src/main/java/com/twilio/rest/iam/v1/ApiKeyFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.iam.v1; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,44 +26,41 @@ public class ApiKeyFetcher extends Fetcher { - private String pathSid; + private String pathsid; - public ApiKeyFetcher(final String pathSid) { - this.pathSid = pathSid; + public ApiKeyFetcher(final String pathsid) { + this.pathsid = pathsid; } + @Override public ApiKey fetch(final TwilioRestClient client) { + String path = "/v1/Keys/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.IAM.toString(), - path + HttpMethod.GET, + Domains.IAM.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "ApiKey fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("ApiKey fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return ApiKey.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/iam/v1/ApiKeyUpdater.java b/src/main/java/com/twilio/rest/iam/v1/ApiKeyUpdater.java index 4d33ce3945..6c9d44e01e 100644 --- a/src/main/java/com/twilio/rest/iam/v1/ApiKeyUpdater.java +++ b/src/main/java/com/twilio/rest/iam/v1/ApiKeyUpdater.java @@ -16,7 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; -import com.twilio.converter.Converter; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,53 +28,54 @@ import com.twilio.rest.Domains; public class ApiKeyUpdater extends Updater { - - private String pathSid; + private String pathsid; private String friendlyName; private Object policy; - public ApiKeyUpdater(final String pathSid) { - this.pathSid = pathSid; + public ApiKeyUpdater(final String pathsid) { + this.pathsid = pathsid; } + public ApiKeyUpdater setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + public ApiKeyUpdater setPolicy(final Object policy) { this.policy = policy; return this; } + @Override public ApiKey update(final TwilioRestClient client) { + String path = "/v1/Keys/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.IAM.toString(), - path + HttpMethod.POST, + Domains.IAM.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "ApiKey update failed: Unable to connect to server" - ); + throw new ApiConnectionException("ApiKey update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -82,11 +84,16 @@ public ApiKey update(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + if (policy != null) { - request.addPostParam("Policy", Converter.objectToJson(policy)); + Serializer.toString(request, "Policy", policy, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/iam/v1/GetApiKeys.java b/src/main/java/com/twilio/rest/iam/v1/GetApiKeys.java index 9357e8697e..271364911f 100644 --- a/src/main/java/com/twilio/rest/iam/v1/GetApiKeys.java +++ b/src/main/java/com/twilio/rest/iam/v1/GetApiKeys.java @@ -18,41 +18,42 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.time.ZonedDateTime; import java.util.List; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class GetApiKeys extends Resource { - private static final long serialVersionUID = 72145637372666L; public static GetApiKeysReader reader(final String accountSid) { - return new GetApiKeysReader(accountSid); + return new GetApiKeysReader( + accountSid + ); } + /** * Converts a JSON String into a GetApiKeys object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return GetApiKeys object represented by the provided JSON */ - public static GetApiKeys fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static GetApiKeys fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, GetApiKeys.class); @@ -67,14 +68,11 @@ public static GetApiKeys fromJson( * Converts a JSON InputStream into a GetApiKeys object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return GetApiKeys object represented by the provided JSON */ - public static GetApiKeys fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static GetApiKeys fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, GetApiKeys.class); @@ -85,45 +83,45 @@ public static GetApiKeys fromJson( } } - private final String sid; - private final String friendlyName; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; + @Getter private final List flags; + @Getter + private final String friendlyName; + @Getter + private final String sid; @JsonCreator private GetApiKeys( - @JsonProperty("sid") final String sid, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("flags") final List flags + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.RFC2822Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.RFC2822Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("flags") final List flags, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("sid") final String sid ) { - this.sid = sid; - this.friendlyName = friendlyName; - this.dateCreated = DateConverter.rfc2822DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.rfc2822DateTimeFromString(dateUpdated); + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.flags = flags; - } - - public final String getSid() { - return this.sid; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final List getFlags() { - return this.flags; + this.friendlyName = friendlyName; + this.sid = sid; } @Override @@ -137,18 +135,26 @@ public boolean equals(final Object o) { } GetApiKeys other = (GetApiKeys) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(flags, other.flags) + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(flags, other.flags) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(sid, other.sid) ); } @Override public int hashCode() { - return Objects.hash(sid, friendlyName, dateCreated, dateUpdated, flags); + return Objects.hash( + dateCreated, + dateUpdated, + flags, + friendlyName, + sid + ); } + + } + diff --git a/src/main/java/com/twilio/rest/iam/v1/GetApiKeysReader.java b/src/main/java/com/twilio/rest/iam/v1/GetApiKeysReader.java index 8a19aa84fa..4224601f7f 100644 --- a/src/main/java/com/twilio/rest/iam/v1/GetApiKeysReader.java +++ b/src/main/java/com/twilio/rest/iam/v1/GetApiKeysReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -36,113 +37,91 @@ public GetApiKeysReader(final String accountSid) { this.accountSid = accountSid; } + public GetApiKeysReader setAccountSid(final String accountSid) { this.accountSid = accountSid; return this; } + public GetApiKeysReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/Keys"; - path = - path.replace("{" + "AccountSid" + "}", this.accountSid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.IAM.toString(), - path + HttpMethod.GET, + Domains.IAM.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "GetApiKeys read failed: Unable to connect to server" - ); + throw new ApiConnectionException("GetApiKeys read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "keys", - response.getContent(), - GetApiKeys.class, - client.getObjectMapper() - ); + "keys", + response.getContent(), + GetApiKeys.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.IAM.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.IAM.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (accountSid != null) { - request.addQueryParam("AccountSid", accountSid); + Serializer.toString(request, "AccountSid", accountSid, ParameterType.QUERY); } + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/iam/v1/NewApiKey.java b/src/main/java/com/twilio/rest/iam/v1/NewApiKey.java index 366a2d71c9..dfc24e8019 100644 --- a/src/main/java/com/twilio/rest/iam/v1/NewApiKey.java +++ b/src/main/java/com/twilio/rest/iam/v1/NewApiKey.java @@ -18,43 +18,62 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.time.ZonedDateTime; -import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class NewApiKey extends Resource { - private static final long serialVersionUID = 217181042856619L; public static NewApiKeyCreator creator(final String accountSid) { - return new NewApiKeyCreator(accountSid); + return new NewApiKeyCreator( + accountSid + ); + } + + + public enum Keytype { + RESTRICTED("restricted"); + + private final String value; + + private Keytype(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static Keytype forValue(final String value) { + return Promoter.enumFromString(value, Keytype.values()); + } } + /** * Converts a JSON String into a NewApiKey object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return NewApiKey object represented by the provided JSON */ - public static NewApiKey fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static NewApiKey fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, NewApiKey.class); @@ -69,14 +88,11 @@ public static NewApiKey fromJson( * Converts a JSON InputStream into a NewApiKey object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return NewApiKey object represented by the provided JSON */ - public static NewApiKey fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static NewApiKey fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, NewApiKey.class); @@ -87,52 +103,49 @@ public static NewApiKey fromJson( } } - private final String sid; - private final String friendlyName; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; + @Getter + private final String friendlyName; + @Getter + private final Object policy; + @Getter private final String secret; - private final Map policy; + @Getter + private final String sid; @JsonCreator private NewApiKey( - @JsonProperty("sid") final String sid, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("secret") final String secret, - @JsonProperty("policy") final Map policy + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.RFC2822Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.RFC2822Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("policy") final Object policy, + @JsonProperty("secret") final String secret, + @JsonProperty("sid") final String sid ) { - this.sid = sid; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.friendlyName = friendlyName; - this.dateCreated = DateConverter.rfc2822DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.rfc2822DateTimeFromString(dateUpdated); - this.secret = secret; this.policy = policy; - } - - public final String getSid() { - return this.sid; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final String getSecret() { - return this.secret; - } - - public final Map getPolicy() { - return this.policy; + this.secret = secret; + this.sid = sid; } @Override @@ -146,45 +159,28 @@ public boolean equals(final Object o) { } NewApiKey other = (NewApiKey) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(secret, other.secret) && - Objects.equals(policy, other.policy) + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(policy, other.policy) && + Objects.equals(secret, other.secret) && + Objects.equals(sid, other.sid) ); } @Override public int hashCode() { return Objects.hash( - sid, - friendlyName, - dateCreated, - dateUpdated, - secret, - policy + dateCreated, + dateUpdated, + friendlyName, + policy, + secret, + sid ); } - public enum Keytype { - RESTRICTED("restricted"); - - private final String value; - - private Keytype(final String value) { - this.value = value; - } - public String toString() { - return value; - } - - @JsonCreator - public static Keytype forValue(final String value) { - return Promoter.enumFromString(value, Keytype.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/iam/v1/NewApiKeyCreator.java b/src/main/java/com/twilio/rest/iam/v1/NewApiKeyCreator.java index df5c0c2a42..49eef33b74 100644 --- a/src/main/java/com/twilio/rest/iam/v1/NewApiKeyCreator.java +++ b/src/main/java/com/twilio/rest/iam/v1/NewApiKeyCreator.java @@ -14,10 +14,11 @@ package com.twilio.rest.iam.v1; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; -import com.twilio.converter.Converter; -import com.twilio.converter.Converter; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -38,77 +39,84 @@ public NewApiKeyCreator(final String accountSid) { this.accountSid = accountSid; } + public NewApiKeyCreator setAccountSid(final String accountSid) { this.accountSid = accountSid; return this; } + public NewApiKeyCreator setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + public NewApiKeyCreator setKeyType(final NewApiKey.Keytype keyType) { this.keyType = keyType; return this; } + public NewApiKeyCreator setPolicy(final Object policy) { this.policy = policy; return this; } + @Override public NewApiKey create(final TwilioRestClient client) { + String path = "/v1/Keys"; - path = - path.replace("{" + "AccountSid" + "}", this.accountSid.toString()); Request request = new Request( - HttpMethod.POST, - Domains.IAM.toString(), - path + HttpMethod.POST, + Domains.IAM.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "NewApiKey creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("NewApiKey creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return NewApiKey.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return NewApiKey.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (accountSid != null) { - request.addPostParam("AccountSid", accountSid); + Serializer.toString(request, "AccountSid", accountSid, ParameterType.URLENCODED); } + + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + if (keyType != null) { - request.addPostParam("KeyType", keyType.toString()); + Serializer.toString(request, "KeyType", keyType, ParameterType.URLENCODED); } + + if (policy != null) { - request.addPostParam("Policy", Converter.objectToJson(policy)); + Serializer.toString(request, "Policy", policy, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/iam/v1/Token.java b/src/main/java/com/twilio/rest/iam/v1/Token.java index e81303e1db..55b1be2802 100644 --- a/src/main/java/com/twilio/rest/iam/v1/Token.java +++ b/src/main/java/com/twilio/rest/iam/v1/Token.java @@ -18,41 +18,39 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Token extends Resource { - private static final long serialVersionUID = 258139119277894L; - public static TokenCreator creator( - final String grantType, - final String clientId - ) { - return new TokenCreator(grantType, clientId); + public static TokenCreator creator(final String grantType, final String clientId) { + return new TokenCreator( + grantType, clientId + ); } + /** * Converts a JSON String into a Token object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Token object represented by the provided JSON */ - public static Token fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Token fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Token.class); @@ -67,14 +65,11 @@ public static Token fromJson( * Converts a JSON InputStream into a Token object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Token object represented by the provided JSON */ - public static Token fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Token fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Token.class); @@ -85,45 +80,43 @@ public static Token fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accessToken; - private final String refreshToken; + @Getter + private final Long expiresIn; + @Getter private final String idToken; + @Getter + private final String refreshToken; + @Getter private final String tokenType; - private final Long expiresIn; @JsonCreator private Token( - @JsonProperty("access_token") final String accessToken, - @JsonProperty("refresh_token") final String refreshToken, - @JsonProperty("id_token") final String idToken, - @JsonProperty("token_type") final String tokenType, - @JsonProperty("expires_in") final Long expiresIn + @JsonProperty("access_token") final String accessToken, + @JsonProperty("expires_in") final Long expiresIn, + @JsonProperty("id_token") final String idToken, + @JsonProperty("refresh_token") final String refreshToken, + @JsonProperty("token_type") final String tokenType ) { this.accessToken = accessToken; - this.refreshToken = refreshToken; + this.expiresIn = expiresIn; this.idToken = idToken; + this.refreshToken = refreshToken; this.tokenType = tokenType; - this.expiresIn = expiresIn; - } - - public final String getAccessToken() { - return this.accessToken; - } - - public final String getRefreshToken() { - return this.refreshToken; - } - - public final String getIdToken() { - return this.idToken; - } - - public final String getTokenType() { - return this.tokenType; - } - - public final Long getExpiresIn() { - return this.expiresIn; } @Override @@ -137,24 +130,26 @@ public boolean equals(final Object o) { } Token other = (Token) o; - return ( - Objects.equals(accessToken, other.accessToken) && - Objects.equals(refreshToken, other.refreshToken) && - Objects.equals(idToken, other.idToken) && - Objects.equals(tokenType, other.tokenType) && - Objects.equals(expiresIn, other.expiresIn) + Objects.equals(accessToken, other.accessToken) && + Objects.equals(expiresIn, other.expiresIn) && + Objects.equals(idToken, other.idToken) && + Objects.equals(refreshToken, other.refreshToken) && + Objects.equals(tokenType, other.tokenType) ); } @Override public int hashCode() { return Objects.hash( - accessToken, - refreshToken, - idToken, - tokenType, - expiresIn + accessToken, + expiresIn, + idToken, + refreshToken, + tokenType ); } + + } + diff --git a/src/main/java/com/twilio/rest/iam/v1/TokenCreator.java b/src/main/java/com/twilio/rest/iam/v1/TokenCreator.java index 66b5f2e181..ce01cded12 100644 --- a/src/main/java/com/twilio/rest/iam/v1/TokenCreator.java +++ b/src/main/java/com/twilio/rest/iam/v1/TokenCreator.java @@ -14,9 +14,12 @@ package com.twilio.rest.iam.v1; + import com.twilio.auth_strategy.NoAuthStrategy; import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -42,79 +45,81 @@ public TokenCreator(final String grantType, final String clientId) { this.clientId = clientId; } + public TokenCreator setGrantType(final String grantType) { this.grantType = grantType; return this; } + public TokenCreator setClientId(final String clientId) { this.clientId = clientId; return this; } + public TokenCreator setClientSecret(final String clientSecret) { this.clientSecret = clientSecret; return this; } + public TokenCreator setCode(final String code) { this.code = code; return this; } + public TokenCreator setRedirectUri(final String redirectUri) { this.redirectUri = redirectUri; return this; } + public TokenCreator setAudience(final String audience) { this.audience = audience; return this; } + public TokenCreator setRefreshToken(final String refreshToken) { this.refreshToken = refreshToken; return this; } + public TokenCreator setScope(final String scope) { this.scope = scope; return this; } + @Override public Token create(final TwilioRestClient client) { + String path = "/v1/token"; - path = - path.replace("{" + "grant_type" + "}", this.grantType.toString()); - path = path.replace("{" + "client_id" + "}", this.clientId.toString()); Request request = new Request( - HttpMethod.POST, - Domains.IAM.toString(), - path + HttpMethod.POST, + Domains.IAM.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); request.setAuth(NoAuthStrategy.getInstance()); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Token creation failed: Unable to connect to server" - ); - } else if ( - !TwilioRestClient.SUCCESS.test(response.getStatusCode()) - ) { + throw new ApiConnectionException("Token creation failed: Unable to connect to server"); + } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -123,29 +128,46 @@ public Token create(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (grantType != null) { - request.addPostParam("grant_type", grantType); + Serializer.toString(request, "grant_type", grantType, ParameterType.URLENCODED); } + + if (clientId != null) { - request.addPostParam("client_id", clientId); + Serializer.toString(request, "client_id", clientId, ParameterType.URLENCODED); } + + if (clientSecret != null) { - request.addPostParam("client_secret", clientSecret); + Serializer.toString(request, "client_secret", clientSecret, ParameterType.URLENCODED); } + + if (code != null) { - request.addPostParam("code", code); + Serializer.toString(request, "code", code, ParameterType.URLENCODED); } + + if (redirectUri != null) { - request.addPostParam("redirect_uri", redirectUri); + Serializer.toString(request, "redirect_uri", redirectUri, ParameterType.URLENCODED); } + + if (audience != null) { - request.addPostParam("audience", audience); + Serializer.toString(request, "audience", audience, ParameterType.URLENCODED); } + + if (refreshToken != null) { - request.addPostParam("refresh_token", refreshToken); + Serializer.toString(request, "refresh_token", refreshToken, ParameterType.URLENCODED); } + + if (scope != null) { - request.addPostParam("scope", scope); + Serializer.toString(request, "scope", scope, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/insights/v1/Call.java b/src/main/java/com/twilio/rest/insights/v1/Call.java index 73c6b95c51..48c74e7e75 100644 --- a/src/main/java/com/twilio/rest/insights/v1/Call.java +++ b/src/main/java/com/twilio/rest/insights/v1/Call.java @@ -18,41 +18,41 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Call extends Resource { - private static final long serialVersionUID = 241148031780577L; - public static CallFetcher fetcher(final String pathSid) { - return new CallFetcher(pathSid); + public static CallFetcher fetcher(final String pathsid) { + return new CallFetcher( + pathsid + ); } + /** * Converts a JSON String into a Call object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Call object represented by the provided JSON */ - public static Call fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Call fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Call.class); @@ -67,14 +67,11 @@ public static Call fromJson( * Converts a JSON InputStream into a Call object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Call object represented by the provided JSON */ - public static Call fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Call fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Call.class); @@ -85,31 +82,35 @@ public static Call fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter + private final Map links; + @Getter private final String sid; + @Getter private final URI url; - private final Map links; @JsonCreator private Call( - @JsonProperty("sid") final String sid, - @JsonProperty("url") final URI url, - @JsonProperty("links") final Map links + @JsonProperty("links") final Map links, + @JsonProperty("sid") final String sid, + @JsonProperty("url") final URI url ) { + this.links = links; this.sid = sid; this.url = url; - this.links = links; - } - - public final String getSid() { - return this.sid; - } - - public final URI getUrl() { - return this.url; - } - - public final Map getLinks() { - return this.links; } @Override @@ -123,16 +124,22 @@ public boolean equals(final Object o) { } Call other = (Call) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(url, other.url) && - Objects.equals(links, other.links) + Objects.equals(links, other.links) && + Objects.equals(sid, other.sid) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { - return Objects.hash(sid, url, links); + return Objects.hash( + links, + sid, + url + ); } + + } + diff --git a/src/main/java/com/twilio/rest/insights/v1/CallFetcher.java b/src/main/java/com/twilio/rest/insights/v1/CallFetcher.java index 4d9697d69f..61b29e5244 100644 --- a/src/main/java/com/twilio/rest/insights/v1/CallFetcher.java +++ b/src/main/java/com/twilio/rest/insights/v1/CallFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.insights.v1; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,44 +26,41 @@ public class CallFetcher extends Fetcher { - private String pathSid; + private String pathsid; - public CallFetcher(final String pathSid) { - this.pathSid = pathSid; + public CallFetcher(final String pathsid) { + this.pathsid = pathsid; } + @Override public Call fetch(final TwilioRestClient client) { + String path = "/v1/Voice/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.INSIGHTS.toString(), - path + HttpMethod.GET, + Domains.INSIGHTS.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Call fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Call fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Call.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/insights/v1/CallSummaries.java b/src/main/java/com/twilio/rest/insights/v1/CallSummaries.java index 9741233555..dfd48a6282 100644 --- a/src/main/java/com/twilio/rest/insights/v1/CallSummaries.java +++ b/src/main/java/com/twilio/rest/insights/v1/CallSummaries.java @@ -18,312 +18,54 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.List; -import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class CallSummaries extends Resource { - private static final long serialVersionUID = 2737605187627L; public static CallSummariesReader reader() { - return new CallSummariesReader(); - } - - /** - * Converts a JSON String into a CallSummaries object using the provided ObjectMapper. - * - * @param json Raw JSON String - * @param objectMapper Jackson ObjectMapper - * @return CallSummaries object represented by the provided JSON - */ - public static CallSummaries fromJson( - final String json, - final ObjectMapper objectMapper - ) { - // Convert all checked exceptions to Runtime - try { - return objectMapper.readValue(json, CallSummaries.class); - } catch (final JsonMappingException | JsonParseException e) { - throw new ApiException(e.getMessage(), e); - } catch (final IOException e) { - throw new ApiConnectionException(e.getMessage(), e); - } - } - - /** - * Converts a JSON InputStream into a CallSummaries object using the provided - * ObjectMapper. - * - * @param json Raw JSON InputStream - * @param objectMapper Jackson ObjectMapper - * @return CallSummaries object represented by the provided JSON - */ - public static CallSummaries fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { - // Convert all checked exceptions to Runtime - try { - return objectMapper.readValue(json, CallSummaries.class); - } catch (final JsonMappingException | JsonParseException e) { - throw new ApiException(e.getMessage(), e); - } catch (final IOException e) { - throw new ApiConnectionException(e.getMessage(), e); - } - } - - private final String accountSid; - private final String callSid; - private final CallSummaries.AnsweredBy answeredBy; - private final CallSummaries.CallType callType; - private final CallSummaries.CallState callState; - private final CallSummaries.ProcessingState processingState; - private final ZonedDateTime createdTime; - private final ZonedDateTime startTime; - private final ZonedDateTime endTime; - private final Integer duration; - private final Integer connectDuration; - private final Map from; - private final Map to; - private final Map carrierEdge; - private final Map clientEdge; - private final Map sdkEdge; - private final Map sipEdge; - private final List tags; - private final URI url; - private final Map attributes; - private final Map properties; - private final Map trust; - private final Map annotation; - - @JsonCreator - private CallSummaries( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("call_sid") final String callSid, - @JsonProperty("answered_by") final CallSummaries.AnsweredBy answeredBy, - @JsonProperty("call_type") final CallSummaries.CallType callType, - @JsonProperty("call_state") final CallSummaries.CallState callState, - @JsonProperty( - "processing_state" - ) final CallSummaries.ProcessingState processingState, - @JsonProperty("created_time") final String createdTime, - @JsonProperty("start_time") final String startTime, - @JsonProperty("end_time") final String endTime, - @JsonProperty("duration") final Integer duration, - @JsonProperty("connect_duration") final Integer connectDuration, - @JsonProperty("from") final Map from, - @JsonProperty("to") final Map to, - @JsonProperty("carrier_edge") final Map carrierEdge, - @JsonProperty("client_edge") final Map clientEdge, - @JsonProperty("sdk_edge") final Map sdkEdge, - @JsonProperty("sip_edge") final Map sipEdge, - @JsonProperty("tags") final List tags, - @JsonProperty("url") final URI url, - @JsonProperty("attributes") final Map attributes, - @JsonProperty("properties") final Map properties, - @JsonProperty("trust") final Map trust, - @JsonProperty("annotation") final Map annotation - ) { - this.accountSid = accountSid; - this.callSid = callSid; - this.answeredBy = answeredBy; - this.callType = callType; - this.callState = callState; - this.processingState = processingState; - this.createdTime = DateConverter.iso8601DateTimeFromString(createdTime); - this.startTime = DateConverter.iso8601DateTimeFromString(startTime); - this.endTime = DateConverter.iso8601DateTimeFromString(endTime); - this.duration = duration; - this.connectDuration = connectDuration; - this.from = from; - this.to = to; - this.carrierEdge = carrierEdge; - this.clientEdge = clientEdge; - this.sdkEdge = sdkEdge; - this.sipEdge = sipEdge; - this.tags = tags; - this.url = url; - this.attributes = attributes; - this.properties = properties; - this.trust = trust; - this.annotation = annotation; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getCallSid() { - return this.callSid; - } - - public final CallSummaries.AnsweredBy getAnsweredBy() { - return this.answeredBy; - } - - public final CallSummaries.CallType getCallType() { - return this.callType; - } - - public final CallSummaries.CallState getCallState() { - return this.callState; - } - - public final CallSummaries.ProcessingState getProcessingState() { - return this.processingState; - } - - public final ZonedDateTime getCreatedTime() { - return this.createdTime; - } - - public final ZonedDateTime getStartTime() { - return this.startTime; - } - - public final ZonedDateTime getEndTime() { - return this.endTime; - } - - public final Integer getDuration() { - return this.duration; - } - - public final Integer getConnectDuration() { - return this.connectDuration; - } - - public final Map getFrom() { - return this.from; - } - - public final Map getTo() { - return this.to; - } - - public final Map getCarrierEdge() { - return this.carrierEdge; - } - - public final Map getClientEdge() { - return this.clientEdge; - } - - public final Map getSdkEdge() { - return this.sdkEdge; - } - - public final Map getSipEdge() { - return this.sipEdge; - } - - public final List getTags() { - return this.tags; - } - - public final URI getUrl() { - return this.url; - } + return new CallSummariesReader( - public final Map getAttributes() { - return this.attributes; + ); } - public final Map getProperties() { - return this.properties; - } - public final Map getTrust() { - return this.trust; - } + public enum SortBy { + START_TIME("start_time"), + END_TIME("end_time"); - public final Map getAnnotation() { - return this.annotation; - } + private final String value; - @Override - public boolean equals(final Object o) { - if (this == o) { - return true; + private SortBy(final String value) { + this.value = value; } - if (o == null || getClass() != o.getClass()) { - return false; + public String toString() { + return value; } - CallSummaries other = (CallSummaries) o; - - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(callSid, other.callSid) && - Objects.equals(answeredBy, other.answeredBy) && - Objects.equals(callType, other.callType) && - Objects.equals(callState, other.callState) && - Objects.equals(processingState, other.processingState) && - Objects.equals(createdTime, other.createdTime) && - Objects.equals(startTime, other.startTime) && - Objects.equals(endTime, other.endTime) && - Objects.equals(duration, other.duration) && - Objects.equals(connectDuration, other.connectDuration) && - Objects.equals(from, other.from) && - Objects.equals(to, other.to) && - Objects.equals(carrierEdge, other.carrierEdge) && - Objects.equals(clientEdge, other.clientEdge) && - Objects.equals(sdkEdge, other.sdkEdge) && - Objects.equals(sipEdge, other.sipEdge) && - Objects.equals(tags, other.tags) && - Objects.equals(url, other.url) && - Objects.equals(attributes, other.attributes) && - Objects.equals(properties, other.properties) && - Objects.equals(trust, other.trust) && - Objects.equals(annotation, other.annotation) - ); - } - - @Override - public int hashCode() { - return Objects.hash( - accountSid, - callSid, - answeredBy, - callType, - callState, - processingState, - createdTime, - startTime, - endTime, - duration, - connectDuration, - from, - to, - carrierEdge, - clientEdge, - sdkEdge, - sipEdge, - tags, - url, - attributes, - properties, - trust, - annotation - ); + @JsonCreator + public static SortBy forValue(final String value) { + return Promoter.enumFromString(value, SortBy.values()); + } } public enum CallType { @@ -349,26 +91,6 @@ public static CallType forValue(final String value) { } } - public enum ProcessingState { - COMPLETE("complete"), - PARTIAL("partial"); - - private final String value; - - private ProcessingState(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static ProcessingState forValue(final String value) { - return Promoter.enumFromString(value, ProcessingState.values()); - } - } - public enum ProcessingStateRequest { COMPLETED("completed"), STARTED("started"), @@ -387,10 +109,7 @@ public String toString() { @JsonCreator public static ProcessingStateRequest forValue(final String value) { - return Promoter.enumFromString( - value, - ProcessingStateRequest.values() - ); + return Promoter.enumFromString(value, ProcessingStateRequest.values()); } } @@ -445,13 +164,13 @@ public static AnsweredBy forValue(final String value) { } } - public enum SortBy { - START_TIME("start_time"), - END_TIME("end_time"); + public enum ProcessingState { + COMPLETE("complete"), + PARTIAL("partial"); private final String value; - private SortBy(final String value) { + private ProcessingState(final String value) { this.value = value; } @@ -460,8 +179,230 @@ public String toString() { } @JsonCreator - public static SortBy forValue(final String value) { - return Promoter.enumFromString(value, SortBy.values()); + public static ProcessingState forValue(final String value) { + return Promoter.enumFromString(value, ProcessingState.values()); + } + } + + + /** + * Converts a JSON String into a CallSummaries object using the provided ObjectMapper. + * + * @param json Raw JSON String + * @param objectMapper Jackson ObjectMapper + * @return CallSummaries object represented by the provided JSON + */ + public static CallSummaries fromJson(final String json, final ObjectMapper objectMapper) { + // Convert all checked exceptions to Runtime + try { + return objectMapper.readValue(json, CallSummaries.class); + } catch (final JsonMappingException | JsonParseException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); } } + + /** + * Converts a JSON InputStream into a CallSummaries object using the provided + * ObjectMapper. + * + * @param json Raw JSON InputStream + * @param objectMapper Jackson ObjectMapper + * @return CallSummaries object represented by the provided JSON + */ + public static CallSummaries fromJson(final InputStream json, final ObjectMapper objectMapper) { + // Convert all checked exceptions to Runtime + try { + return objectMapper.readValue(json, CallSummaries.class); + } catch (final JsonMappingException | JsonParseException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter + private final String accountSid; + @Getter + private final Object annotation; + @Getter + private final CallSummaries.AnsweredBy answeredBy; + @Getter + private final Object attributes; + @Getter + private final String callSid; + @Getter + private final CallSummaries.CallState callState; + @Getter + private final CallSummaries.CallType callType; + @Getter + private final Object carrierEdge; + @Getter + private final Object clientEdge; + @Getter + private final Integer connectDuration; + @Getter + private final ZonedDateTime createdTime; + @Getter + private final Integer duration; + @Getter + private final ZonedDateTime endTime; + @Getter + private final Object from; + @Getter + private final CallSummaries.ProcessingState processingState; + @Getter + private final Object properties; + @Getter + private final Object sdkEdge; + @Getter + private final Object sipEdge; + @Getter + private final ZonedDateTime startTime; + @Getter + private final List tags; + @Getter + private final Object to; + @Getter + private final Object trust; + @Getter + private final URI url; + + @JsonCreator + private CallSummaries( + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("annotation") final Object annotation, + @JsonProperty("answered_by") final CallSummaries.AnsweredBy answeredBy, + @JsonProperty("attributes") final Object attributes, + @JsonProperty("call_sid") final String callSid, + @JsonProperty("call_state") final CallSummaries.CallState callState, + @JsonProperty("call_type") final CallSummaries.CallType callType, + @JsonProperty("carrier_edge") final Object carrierEdge, + @JsonProperty("client_edge") final Object clientEdge, + @JsonProperty("connect_duration") final Integer connectDuration, + @JsonProperty("created_time") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime createdTime, + @JsonProperty("duration") final Integer duration, + @JsonProperty("end_time") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime endTime, + @JsonProperty("from") final Object from, + @JsonProperty("processing_state") final CallSummaries.ProcessingState processingState, + @JsonProperty("properties") final Object properties, + @JsonProperty("sdk_edge") final Object sdkEdge, + @JsonProperty("sip_edge") final Object sipEdge, + @JsonProperty("start_time") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime startTime, + @JsonProperty("tags") final List tags, + @JsonProperty("to") final Object to, + @JsonProperty("trust") final Object trust, + @JsonProperty("url") final URI url + ) { + this.accountSid = accountSid; + this.annotation = annotation; + this.answeredBy = answeredBy; + this.attributes = attributes; + this.callSid = callSid; + this.callState = callState; + this.callType = callType; + this.carrierEdge = carrierEdge; + this.clientEdge = clientEdge; + this.connectDuration = connectDuration; + this.createdTime = createdTime; + this.duration = duration; + this.endTime = endTime; + this.from = from; + this.processingState = processingState; + this.properties = properties; + this.sdkEdge = sdkEdge; + this.sipEdge = sipEdge; + this.startTime = startTime; + this.tags = tags; + this.to = to; + this.trust = trust; + this.url = url; + } + + @Override + public boolean equals(final Object o) { + if (this == o) { + return true; + } + + if (o == null || getClass() != o.getClass()) { + return false; + } + + CallSummaries other = (CallSummaries) o; + return ( + Objects.equals(accountSid, other.accountSid) && + Objects.equals(annotation, other.annotation) && + Objects.equals(answeredBy, other.answeredBy) && + Objects.equals(attributes, other.attributes) && + Objects.equals(callSid, other.callSid) && + Objects.equals(callState, other.callState) && + Objects.equals(callType, other.callType) && + Objects.equals(carrierEdge, other.carrierEdge) && + Objects.equals(clientEdge, other.clientEdge) && + Objects.equals(connectDuration, other.connectDuration) && + Objects.equals(createdTime, other.createdTime) && + Objects.equals(duration, other.duration) && + Objects.equals(endTime, other.endTime) && + Objects.equals(from, other.from) && + Objects.equals(processingState, other.processingState) && + Objects.equals(properties, other.properties) && + Objects.equals(sdkEdge, other.sdkEdge) && + Objects.equals(sipEdge, other.sipEdge) && + Objects.equals(startTime, other.startTime) && + Objects.equals(tags, other.tags) && + Objects.equals(to, other.to) && + Objects.equals(trust, other.trust) && + Objects.equals(url, other.url) + ); + } + + @Override + public int hashCode() { + return Objects.hash( + accountSid, + annotation, + answeredBy, + attributes, + callSid, + callState, + callType, + carrierEdge, + clientEdge, + connectDuration, + createdTime, + duration, + endTime, + from, + processingState, + properties, + sdkEdge, + sipEdge, + startTime, + tags, + to, + trust, + url + ); + } + + } + diff --git a/src/main/java/com/twilio/rest/insights/v1/CallSummariesReader.java b/src/main/java/com/twilio/rest/insights/v1/CallSummariesReader.java index b298cde879..668667b053 100644 --- a/src/main/java/com/twilio/rest/insights/v1/CallSummariesReader.java +++ b/src/main/java/com/twilio/rest/insights/v1/CallSummariesReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -67,457 +68,479 @@ public class CallSummariesReader extends Reader { private String businessProfileType; private Long pageSize; - public CallSummariesReader() {} + public CallSummariesReader() { + } + public CallSummariesReader setFrom(final String from) { this.from = from; return this; } + public CallSummariesReader setTo(final String to) { this.to = to; return this; } + public CallSummariesReader setFromCarrier(final String fromCarrier) { this.fromCarrier = fromCarrier; return this; } + public CallSummariesReader setToCarrier(final String toCarrier) { this.toCarrier = toCarrier; return this; } - public CallSummariesReader setFromCountryCode( - final String fromCountryCode - ) { + + public CallSummariesReader setFromCountryCode(final String fromCountryCode) { this.fromCountryCode = fromCountryCode; return this; } + public CallSummariesReader setToCountryCode(final String toCountryCode) { this.toCountryCode = toCountryCode; return this; } + public CallSummariesReader setVerifiedCaller(final Boolean verifiedCaller) { this.verifiedCaller = verifiedCaller; return this; } + public CallSummariesReader setHasTag(final Boolean hasTag) { this.hasTag = hasTag; return this; } + public CallSummariesReader setStartTime(final String startTime) { this.startTime = startTime; return this; } + public CallSummariesReader setEndTime(final String endTime) { this.endTime = endTime; return this; } + public CallSummariesReader setCallType(final String callType) { this.callType = callType; return this; } + public CallSummariesReader setCallState(final String callState) { this.callState = callState; return this; } + public CallSummariesReader setDirection(final String direction) { this.direction = direction; return this; } - public CallSummariesReader setProcessingState( - final CallSummaries.ProcessingStateRequest processingState - ) { + + public CallSummariesReader setProcessingState(final CallSummaries.ProcessingStateRequest processingState) { this.processingState = processingState; return this; } + public CallSummariesReader setSortBy(final CallSummaries.SortBy sortBy) { this.sortBy = sortBy; return this; } + public CallSummariesReader setSubaccount(final String subaccount) { this.subaccount = subaccount; return this; } - public CallSummariesReader setAbnormalSession( - final Boolean abnormalSession - ) { + + public CallSummariesReader setAbnormalSession(final Boolean abnormalSession) { this.abnormalSession = abnormalSession; return this; } - public CallSummariesReader setAnsweredBy( - final CallSummaries.AnsweredBy answeredBy - ) { + + public CallSummariesReader setAnsweredBy(final CallSummaries.AnsweredBy answeredBy) { this.answeredBy = answeredBy; return this; } - public CallSummariesReader setAnsweredByAnnotation( - final String answeredByAnnotation - ) { + + public CallSummariesReader setAnsweredByAnnotation(final String answeredByAnnotation) { this.answeredByAnnotation = answeredByAnnotation; return this; } - public CallSummariesReader setConnectivityIssueAnnotation( - final String connectivityIssueAnnotation - ) { + + public CallSummariesReader setConnectivityIssueAnnotation(final String connectivityIssueAnnotation) { this.connectivityIssueAnnotation = connectivityIssueAnnotation; return this; } - public CallSummariesReader setQualityIssueAnnotation( - final String qualityIssueAnnotation - ) { + + public CallSummariesReader setQualityIssueAnnotation(final String qualityIssueAnnotation) { this.qualityIssueAnnotation = qualityIssueAnnotation; return this; } + public CallSummariesReader setSpamAnnotation(final Boolean spamAnnotation) { this.spamAnnotation = spamAnnotation; return this; } - public CallSummariesReader setCallScoreAnnotation( - final String callScoreAnnotation - ) { + + public CallSummariesReader setCallScoreAnnotation(final String callScoreAnnotation) { this.callScoreAnnotation = callScoreAnnotation; return this; } + public CallSummariesReader setBrandedEnabled(final Boolean brandedEnabled) { this.brandedEnabled = brandedEnabled; return this; } - public CallSummariesReader setVoiceIntegrityEnabled( - final Boolean voiceIntegrityEnabled - ) { + + public CallSummariesReader setVoiceIntegrityEnabled(final Boolean voiceIntegrityEnabled) { this.voiceIntegrityEnabled = voiceIntegrityEnabled; return this; } - public CallSummariesReader setBrandedBundleSid( - final String brandedBundleSid - ) { + + public CallSummariesReader setBrandedBundleSid(final String brandedBundleSid) { this.brandedBundleSid = brandedBundleSid; return this; } + public CallSummariesReader setBrandedLogo(final Boolean brandedLogo) { this.brandedLogo = brandedLogo; return this; } + public CallSummariesReader setBrandedType(final String brandedType) { this.brandedType = brandedType; return this; } + public CallSummariesReader setBrandedUseCase(final String brandedUseCase) { this.brandedUseCase = brandedUseCase; return this; } - public CallSummariesReader setBrandedCallReason( - final String brandedCallReason - ) { + + public CallSummariesReader setBrandedCallReason(final String brandedCallReason) { this.brandedCallReason = brandedCallReason; return this; } - public CallSummariesReader setVoiceIntegrityBundleSid( - final String voiceIntegrityBundleSid - ) { + + public CallSummariesReader setVoiceIntegrityBundleSid(final String voiceIntegrityBundleSid) { this.voiceIntegrityBundleSid = voiceIntegrityBundleSid; return this; } - public CallSummariesReader setVoiceIntegrityUseCase( - final String voiceIntegrityUseCase - ) { + + public CallSummariesReader setVoiceIntegrityUseCase(final String voiceIntegrityUseCase) { this.voiceIntegrityUseCase = voiceIntegrityUseCase; return this; } - public CallSummariesReader setBusinessProfileIdentity( - final String businessProfileIdentity - ) { + + public CallSummariesReader setBusinessProfileIdentity(final String businessProfileIdentity) { this.businessProfileIdentity = businessProfileIdentity; return this; } - public CallSummariesReader setBusinessProfileIndustry( - final String businessProfileIndustry - ) { + + public CallSummariesReader setBusinessProfileIndustry(final String businessProfileIndustry) { this.businessProfileIndustry = businessProfileIndustry; return this; } - public CallSummariesReader setBusinessProfileBundleSid( - final String businessProfileBundleSid - ) { + + public CallSummariesReader setBusinessProfileBundleSid(final String businessProfileBundleSid) { this.businessProfileBundleSid = businessProfileBundleSid; return this; } - public CallSummariesReader setBusinessProfileType( - final String businessProfileType - ) { + + public CallSummariesReader setBusinessProfileType(final String businessProfileType) { this.businessProfileType = businessProfileType; return this; } + public CallSummariesReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/Voice/Summaries"; + Request request = new Request( - HttpMethod.GET, - Domains.INSIGHTS.toString(), - path + HttpMethod.GET, + Domains.INSIGHTS.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "CallSummaries read failed: Unable to connect to server" - ); + throw new ApiConnectionException("CallSummaries read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "call_summaries", - response.getContent(), - CallSummaries.class, - client.getObjectMapper() - ); + "call_summaries", + response.getContent(), + CallSummaries.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.INSIGHTS.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.INSIGHTS.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (from != null) { - request.addQueryParam("From", from); + Serializer.toString(request, "From", from, ParameterType.QUERY); } + + if (to != null) { - request.addQueryParam("To", to); + Serializer.toString(request, "To", to, ParameterType.QUERY); } + + if (fromCarrier != null) { - request.addQueryParam("FromCarrier", fromCarrier); + Serializer.toString(request, "FromCarrier", fromCarrier, ParameterType.QUERY); } + + if (toCarrier != null) { - request.addQueryParam("ToCarrier", toCarrier); + Serializer.toString(request, "ToCarrier", toCarrier, ParameterType.QUERY); } + + if (fromCountryCode != null) { - request.addQueryParam("FromCountryCode", fromCountryCode); + Serializer.toString(request, "FromCountryCode", fromCountryCode, ParameterType.QUERY); } + + if (toCountryCode != null) { - request.addQueryParam("ToCountryCode", toCountryCode); + Serializer.toString(request, "ToCountryCode", toCountryCode, ParameterType.QUERY); } + + if (verifiedCaller != null) { - request.addQueryParam("VerifiedCaller", verifiedCaller.toString()); + Serializer.toString(request, "VerifiedCaller", verifiedCaller, ParameterType.QUERY); } + + if (hasTag != null) { - request.addQueryParam("HasTag", hasTag.toString()); + Serializer.toString(request, "HasTag", hasTag, ParameterType.QUERY); } + + if (startTime != null) { - request.addQueryParam("StartTime", startTime); + Serializer.toString(request, "StartTime", startTime, ParameterType.QUERY); } + + if (endTime != null) { - request.addQueryParam("EndTime", endTime); + Serializer.toString(request, "EndTime", endTime, ParameterType.QUERY); } + + if (callType != null) { - request.addQueryParam("CallType", callType); + Serializer.toString(request, "CallType", callType, ParameterType.QUERY); } + + if (callState != null) { - request.addQueryParam("CallState", callState); + Serializer.toString(request, "CallState", callState, ParameterType.QUERY); } + + if (direction != null) { - request.addQueryParam("Direction", direction); + Serializer.toString(request, "Direction", direction, ParameterType.QUERY); } + + if (processingState != null) { - request.addQueryParam( - "ProcessingState", - processingState.toString() - ); + Serializer.toString(request, "ProcessingState", processingState, ParameterType.QUERY); } + + if (sortBy != null) { - request.addQueryParam("SortBy", sortBy.toString()); + Serializer.toString(request, "SortBy", sortBy, ParameterType.QUERY); } + + if (subaccount != null) { - request.addQueryParam("Subaccount", subaccount); + Serializer.toString(request, "Subaccount", subaccount, ParameterType.QUERY); } + + if (abnormalSession != null) { - request.addQueryParam( - "AbnormalSession", - abnormalSession.toString() - ); + Serializer.toString(request, "AbnormalSession", abnormalSession, ParameterType.QUERY); } + + if (answeredBy != null) { - request.addQueryParam("AnsweredBy", answeredBy.toString()); + Serializer.toString(request, "AnsweredBy", answeredBy, ParameterType.QUERY); } + + if (answeredByAnnotation != null) { - request.addQueryParam("AnsweredByAnnotation", answeredByAnnotation); + Serializer.toString(request, "AnsweredByAnnotation", answeredByAnnotation, ParameterType.QUERY); } + + if (connectivityIssueAnnotation != null) { - request.addQueryParam( - "ConnectivityIssueAnnotation", - connectivityIssueAnnotation - ); + Serializer.toString(request, "ConnectivityIssueAnnotation", connectivityIssueAnnotation, ParameterType.QUERY); } + + if (qualityIssueAnnotation != null) { - request.addQueryParam( - "QualityIssueAnnotation", - qualityIssueAnnotation - ); + Serializer.toString(request, "QualityIssueAnnotation", qualityIssueAnnotation, ParameterType.QUERY); } + + if (spamAnnotation != null) { - request.addQueryParam("SpamAnnotation", spamAnnotation.toString()); + Serializer.toString(request, "SpamAnnotation", spamAnnotation, ParameterType.QUERY); } + + if (callScoreAnnotation != null) { - request.addQueryParam("CallScoreAnnotation", callScoreAnnotation); + Serializer.toString(request, "CallScoreAnnotation", callScoreAnnotation, ParameterType.QUERY); } + + if (brandedEnabled != null) { - request.addQueryParam("BrandedEnabled", brandedEnabled.toString()); + Serializer.toString(request, "BrandedEnabled", brandedEnabled, ParameterType.QUERY); } + + if (voiceIntegrityEnabled != null) { - request.addQueryParam( - "VoiceIntegrityEnabled", - voiceIntegrityEnabled.toString() - ); + Serializer.toString(request, "VoiceIntegrityEnabled", voiceIntegrityEnabled, ParameterType.QUERY); } + + if (brandedBundleSid != null) { - request.addQueryParam("BrandedBundleSid", brandedBundleSid); + Serializer.toString(request, "BrandedBundleSid", brandedBundleSid, ParameterType.QUERY); } + + if (brandedLogo != null) { - request.addQueryParam("BrandedLogo", brandedLogo.toString()); + Serializer.toString(request, "BrandedLogo", brandedLogo, ParameterType.QUERY); } + + if (brandedType != null) { - request.addQueryParam("BrandedType", brandedType); + Serializer.toString(request, "BrandedType", brandedType, ParameterType.QUERY); } + + if (brandedUseCase != null) { - request.addQueryParam("BrandedUseCase", brandedUseCase); + Serializer.toString(request, "BrandedUseCase", brandedUseCase, ParameterType.QUERY); } + + if (brandedCallReason != null) { - request.addQueryParam("BrandedCallReason", brandedCallReason); + Serializer.toString(request, "BrandedCallReason", brandedCallReason, ParameterType.QUERY); } + + if (voiceIntegrityBundleSid != null) { - request.addQueryParam( - "VoiceIntegrityBundleSid", - voiceIntegrityBundleSid - ); + Serializer.toString(request, "VoiceIntegrityBundleSid", voiceIntegrityBundleSid, ParameterType.QUERY); } + + if (voiceIntegrityUseCase != null) { - request.addQueryParam( - "VoiceIntegrityUseCase", - voiceIntegrityUseCase - ); + Serializer.toString(request, "VoiceIntegrityUseCase", voiceIntegrityUseCase, ParameterType.QUERY); } + + if (businessProfileIdentity != null) { - request.addQueryParam( - "BusinessProfileIdentity", - businessProfileIdentity - ); + Serializer.toString(request, "BusinessProfileIdentity", businessProfileIdentity, ParameterType.QUERY); } + + if (businessProfileIndustry != null) { - request.addQueryParam( - "BusinessProfileIndustry", - businessProfileIndustry - ); + Serializer.toString(request, "BusinessProfileIndustry", businessProfileIndustry, ParameterType.QUERY); } + + if (businessProfileBundleSid != null) { - request.addQueryParam( - "BusinessProfileBundleSid", - businessProfileBundleSid - ); + Serializer.toString(request, "BusinessProfileBundleSid", businessProfileBundleSid, ParameterType.QUERY); } + + if (businessProfileType != null) { - request.addQueryParam("BusinessProfileType", businessProfileType); + Serializer.toString(request, "BusinessProfileType", businessProfileType, ParameterType.QUERY); } + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/insights/v1/Conference.java b/src/main/java/com/twilio/rest/insights/v1/Conference.java index c6a41efe28..ffdd940159 100644 --- a/src/main/java/com/twilio/rest/insights/v1/Conference.java +++ b/src/main/java/com/twilio/rest/insights/v1/Conference.java @@ -18,345 +18,102 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.List; import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Conference extends Resource { - private static final long serialVersionUID = 40059120188961L; - - public static ConferenceFetcher fetcher(final String pathConferenceSid) { - return new ConferenceFetcher(pathConferenceSid); - } - - public static ConferenceReader reader() { - return new ConferenceReader(); - } - - /** - * Converts a JSON String into a Conference object using the provided ObjectMapper. - * - * @param json Raw JSON String - * @param objectMapper Jackson ObjectMapper - * @return Conference object represented by the provided JSON - */ - public static Conference fromJson( - final String json, - final ObjectMapper objectMapper - ) { - // Convert all checked exceptions to Runtime - try { - return objectMapper.readValue(json, Conference.class); - } catch (final JsonMappingException | JsonParseException e) { - throw new ApiException(e.getMessage(), e); - } catch (final IOException e) { - throw new ApiConnectionException(e.getMessage(), e); - } - } - - /** - * Converts a JSON InputStream into a Conference object using the provided - * ObjectMapper. - * - * @param json Raw JSON InputStream - * @param objectMapper Jackson ObjectMapper - * @return Conference object represented by the provided JSON - */ - public static Conference fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { - // Convert all checked exceptions to Runtime - try { - return objectMapper.readValue(json, Conference.class); - } catch (final JsonMappingException | JsonParseException e) { - throw new ApiException(e.getMessage(), e); - } catch (final IOException e) { - throw new ApiConnectionException(e.getMessage(), e); - } - } - - private final String conferenceSid; - private final String accountSid; - private final String friendlyName; - private final ZonedDateTime createTime; - private final ZonedDateTime startTime; - private final ZonedDateTime endTime; - private final Integer durationSeconds; - private final Integer connectDurationSeconds; - private final Conference.ConferenceStatus status; - private final Integer maxParticipants; - private final Integer maxConcurrentParticipants; - private final Integer uniqueParticipants; - private final Conference.ConferenceEndReason endReason; - private final String endedBy; - private final Conference.Region mixerRegion; - private final Conference.Region mixerRegionRequested; - private final Boolean recordingEnabled; - private final Map detectedIssues; - private final List tags; - private final Map tagInfo; - private final Conference.ProcessingState processingState; - private final URI url; - private final Map links; - @JsonCreator - private Conference( - @JsonProperty("conference_sid") final String conferenceSid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("create_time") final String createTime, - @JsonProperty("start_time") final String startTime, - @JsonProperty("end_time") final String endTime, - @JsonProperty("duration_seconds") final Integer durationSeconds, - @JsonProperty( - "connect_duration_seconds" - ) final Integer connectDurationSeconds, - @JsonProperty("status") final Conference.ConferenceStatus status, - @JsonProperty("max_participants") final Integer maxParticipants, - @JsonProperty( - "max_concurrent_participants" - ) final Integer maxConcurrentParticipants, - @JsonProperty("unique_participants") final Integer uniqueParticipants, - @JsonProperty( - "end_reason" - ) final Conference.ConferenceEndReason endReason, - @JsonProperty("ended_by") final String endedBy, - @JsonProperty("mixer_region") final Conference.Region mixerRegion, - @JsonProperty( - "mixer_region_requested" - ) final Conference.Region mixerRegionRequested, - @JsonProperty("recording_enabled") final Boolean recordingEnabled, - @JsonProperty("detected_issues") final Map< - String, - Object - > detectedIssues, - @JsonProperty("tags") final List tags, - @JsonProperty("tag_info") final Map tagInfo, - @JsonProperty( - "processing_state" - ) final Conference.ProcessingState processingState, - @JsonProperty("url") final URI url, - @JsonProperty("links") final Map links - ) { - this.conferenceSid = conferenceSid; - this.accountSid = accountSid; - this.friendlyName = friendlyName; - this.createTime = DateConverter.iso8601DateTimeFromString(createTime); - this.startTime = DateConverter.iso8601DateTimeFromString(startTime); - this.endTime = DateConverter.iso8601DateTimeFromString(endTime); - this.durationSeconds = durationSeconds; - this.connectDurationSeconds = connectDurationSeconds; - this.status = status; - this.maxParticipants = maxParticipants; - this.maxConcurrentParticipants = maxConcurrentParticipants; - this.uniqueParticipants = uniqueParticipants; - this.endReason = endReason; - this.endedBy = endedBy; - this.mixerRegion = mixerRegion; - this.mixerRegionRequested = mixerRegionRequested; - this.recordingEnabled = recordingEnabled; - this.detectedIssues = detectedIssues; - this.tags = tags; - this.tagInfo = tagInfo; - this.processingState = processingState; - this.url = url; - this.links = links; - } - - public final String getConferenceSid() { - return this.conferenceSid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final ZonedDateTime getCreateTime() { - return this.createTime; - } - - public final ZonedDateTime getStartTime() { - return this.startTime; - } - - public final ZonedDateTime getEndTime() { - return this.endTime; - } - - public final Integer getDurationSeconds() { - return this.durationSeconds; - } - - public final Integer getConnectDurationSeconds() { - return this.connectDurationSeconds; - } - - public final Conference.ConferenceStatus getStatus() { - return this.status; - } - - public final Integer getMaxParticipants() { - return this.maxParticipants; - } - - public final Integer getMaxConcurrentParticipants() { - return this.maxConcurrentParticipants; - } - - public final Integer getUniqueParticipants() { - return this.uniqueParticipants; + public static ConferenceFetcher fetcher(final String pathconferenceSid) { + return new ConferenceFetcher( + pathconferenceSid + ); } - public final Conference.ConferenceEndReason getEndReason() { - return this.endReason; - } - public final String getEndedBy() { - return this.endedBy; - } + public static ConferenceReader reader() { + return new ConferenceReader( - public final Conference.Region getMixerRegion() { - return this.mixerRegion; + ); } - public final Conference.Region getMixerRegionRequested() { - return this.mixerRegionRequested; - } - public final Boolean getRecordingEnabled() { - return this.recordingEnabled; - } + public enum ConferenceConferenceTag { + INVALID_REQUESTED_REGION("invalid_requested_region"), + DUPLICATE_IDENTITY("duplicate_identity"), + START_FAILURE("start_failure"), + REGION_CONFIGURATION_ISSUES("region_configuration_issues"), + QUALITY_WARNINGS("quality_warnings"), + PARTICIPANT_BEHAVIOR_ISSUES("participant_behavior_issues"), + HIGH_PACKET_LOSS("high_packet_loss"), + HIGH_JITTER("high_jitter"), + HIGH_LATENCY("high_latency"), + LOW_MOS("low_mos"), + DETECTED_SILENCE("detected_silence"), + NO_CONCURRENT_PARTICIPANTS("no_concurrent_participants"); - public final Map getDetectedIssues() { - return this.detectedIssues; - } + private final String value; - public final List getTags() { - return this.tags; - } + private ConferenceConferenceTag(final String value) { + this.value = value; + } - public final Map getTagInfo() { - return this.tagInfo; - } + public String toString() { + return value; + } - public final Conference.ProcessingState getProcessingState() { - return this.processingState; + @JsonCreator + public static ConferenceConferenceTag forValue(final String value) { + return Promoter.enumFromString(value, ConferenceConferenceTag.values()); + } } - public final URI getUrl() { - return this.url; - } + public enum ConferenceStatus { + IN_PROGRESS("in_progress"), + NOT_STARTED("not_started"), + COMPLETED("completed"), + SUMMARY_TIMEOUT("summary_timeout"); - public final Map getLinks() { - return this.links; - } + private final String value; - @Override - public boolean equals(final Object o) { - if (this == o) { - return true; + private ConferenceStatus(final String value) { + this.value = value; } - if (o == null || getClass() != o.getClass()) { - return false; + public String toString() { + return value; } - Conference other = (Conference) o; - - return ( - Objects.equals(conferenceSid, other.conferenceSid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(createTime, other.createTime) && - Objects.equals(startTime, other.startTime) && - Objects.equals(endTime, other.endTime) && - Objects.equals(durationSeconds, other.durationSeconds) && - Objects.equals( - connectDurationSeconds, - other.connectDurationSeconds - ) && - Objects.equals(status, other.status) && - Objects.equals(maxParticipants, other.maxParticipants) && - Objects.equals( - maxConcurrentParticipants, - other.maxConcurrentParticipants - ) && - Objects.equals(uniqueParticipants, other.uniqueParticipants) && - Objects.equals(endReason, other.endReason) && - Objects.equals(endedBy, other.endedBy) && - Objects.equals(mixerRegion, other.mixerRegion) && - Objects.equals(mixerRegionRequested, other.mixerRegionRequested) && - Objects.equals(recordingEnabled, other.recordingEnabled) && - Objects.equals(detectedIssues, other.detectedIssues) && - Objects.equals(tags, other.tags) && - Objects.equals(tagInfo, other.tagInfo) && - Objects.equals(processingState, other.processingState) && - Objects.equals(url, other.url) && - Objects.equals(links, other.links) - ); - } - - @Override - public int hashCode() { - return Objects.hash( - conferenceSid, - accountSid, - friendlyName, - createTime, - startTime, - endTime, - durationSeconds, - connectDurationSeconds, - status, - maxParticipants, - maxConcurrentParticipants, - uniqueParticipants, - endReason, - endedBy, - mixerRegion, - mixerRegionRequested, - recordingEnabled, - detectedIssues, - tags, - tagInfo, - processingState, - url, - links - ); + @JsonCreator + public static ConferenceStatus forValue(final String value) { + return Promoter.enumFromString(value, ConferenceStatus.values()); + } } public enum ConferenceEndReason { LAST_PARTICIPANT_LEFT("last_participant_left"), CONFERENCE_ENDED_VIA_API("conference_ended_via_api"), - PARTICIPANT_WITH_END_CONFERENCE_ON_EXIT_LEFT( - "participant_with_end_conference_on_exit_left" - ), + PARTICIPANT_WITH_END_CONFERENCE_ON_EXIT_LEFT("participant_with_end_conference_on_exit_left"), LAST_PARTICIPANT_KICKED("last_participant_kicked"), - PARTICIPANT_WITH_END_CONFERENCE_ON_EXIT_KICKED( - "participant_with_end_conference_on_exit_kicked" - ); + PARTICIPANT_WITH_END_CONFERENCE_ON_EXIT_KICKED("participant_with_end_conference_on_exit_kicked"); private final String value; @@ -374,7 +131,7 @@ public static ConferenceEndReason forValue(final String value) { } } - public enum Tag { + public enum ConferenceTag { INVALID_REQUESTED_REGION("invalid_requested_region"), DUPLICATE_IDENTITY("duplicate_identity"), START_FAILURE("start_failure"), @@ -390,7 +147,7 @@ public enum Tag { private final String value; - private Tag(final String value) { + private ConferenceTag(final String value) { this.value = value; } @@ -399,8 +156,8 @@ public String toString() { } @JsonCreator - public static Tag forValue(final String value) { - return Promoter.enumFromString(value, Tag.values()); + public static ConferenceTag forValue(final String value) { + return Promoter.enumFromString(value, ConferenceTag.values()); } } @@ -431,6 +188,66 @@ public static Region forValue(final String value) { } } + public enum Tag { + INVALID_REQUESTED_REGION("invalid_requested_region"), + DUPLICATE_IDENTITY("duplicate_identity"), + START_FAILURE("start_failure"), + REGION_CONFIGURATION_ISSUES("region_configuration_issues"), + QUALITY_WARNINGS("quality_warnings"), + PARTICIPANT_BEHAVIOR_ISSUES("participant_behavior_issues"), + HIGH_PACKET_LOSS("high_packet_loss"), + HIGH_JITTER("high_jitter"), + HIGH_LATENCY("high_latency"), + LOW_MOS("low_mos"), + DETECTED_SILENCE("detected_silence"), + NO_CONCURRENT_PARTICIPANTS("no_concurrent_participants"); + + private final String value; + + private Tag(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static Tag forValue(final String value) { + return Promoter.enumFromString(value, Tag.values()); + } + } + + public enum ConferenceConferenceConferenceTag { + INVALID_REQUESTED_REGION("invalid_requested_region"), + DUPLICATE_IDENTITY("duplicate_identity"), + START_FAILURE("start_failure"), + REGION_CONFIGURATION_ISSUES("region_configuration_issues"), + QUALITY_WARNINGS("quality_warnings"), + PARTICIPANT_BEHAVIOR_ISSUES("participant_behavior_issues"), + HIGH_PACKET_LOSS("high_packet_loss"), + HIGH_JITTER("high_jitter"), + HIGH_LATENCY("high_latency"), + LOW_MOS("low_mos"), + DETECTED_SILENCE("detected_silence"), + NO_CONCURRENT_PARTICIPANTS("no_concurrent_participants"); + + private final String value; + + private ConferenceConferenceConferenceTag(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static ConferenceConferenceConferenceTag forValue(final String value) { + return Promoter.enumFromString(value, ConferenceConferenceConferenceTag.values()); + } + } + public enum ProcessingState { COMPLETE("complete"), IN_PROGRESS("in_progress"), @@ -452,25 +269,225 @@ public static ProcessingState forValue(final String value) { } } - public enum ConferenceStatus { - IN_PROGRESS("in_progress"), - NOT_STARTED("not_started"), - COMPLETED("completed"), - SUMMARY_TIMEOUT("summary_timeout"); - private final String value; + /** + * Converts a JSON String into a Conference object using the provided ObjectMapper. + * + * @param json Raw JSON String + * @param objectMapper Jackson ObjectMapper + * @return Conference object represented by the provided JSON + */ + public static Conference fromJson(final String json, final ObjectMapper objectMapper) { + // Convert all checked exceptions to Runtime + try { + return objectMapper.readValue(json, Conference.class); + } catch (final JsonMappingException | JsonParseException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } - private ConferenceStatus(final String value) { - this.value = value; + /** + * Converts a JSON InputStream into a Conference object using the provided + * ObjectMapper. + * + * @param json Raw JSON InputStream + * @param objectMapper Jackson ObjectMapper + * @return Conference object represented by the provided JSON + */ + public static Conference fromJson(final InputStream json, final ObjectMapper objectMapper) { + // Convert all checked exceptions to Runtime + try { + return objectMapper.readValue(json, Conference.class); + } catch (final JsonMappingException | JsonParseException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); } + } - public String toString() { - return value; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); } + } - @JsonCreator - public static ConferenceStatus forValue(final String value) { - return Promoter.enumFromString(value, ConferenceStatus.values()); + + @Getter + private final String accountSid; + @Getter + private final String conferenceSid; + @Getter + private final Integer connectDurationSeconds; + @Getter + private final ZonedDateTime createTime; + @Getter + private final Object detectedIssues; + @Getter + private final Integer durationSeconds; + @Getter + private final Conference.ConferenceEndReason endReason; + @Getter + private final ZonedDateTime endTime; + @Getter + private final String endedBy; + @Getter + private final String friendlyName; + @Getter + private final Map links; + @Getter + private final Integer maxConcurrentParticipants; + @Getter + private final Integer maxParticipants; + @Getter + private final Conference.Region mixerRegion; + @Getter + private final Conference.Region mixerRegionRequested; + @Getter + private final Conference.ProcessingState processingState; + @Getter + private final Boolean recordingEnabled; + @Getter + private final ZonedDateTime startTime; + @Getter + private final Conference.ConferenceStatus status; + @Getter + private final Object tagInfo; + @Getter + private final List tags; + @Getter + private final Integer uniqueParticipants; + @Getter + private final URI url; + + @JsonCreator + private Conference( + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("conference_sid") final String conferenceSid, + @JsonProperty("connect_duration_seconds") final Integer connectDurationSeconds, + @JsonProperty("create_time") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime createTime, + @JsonProperty("detected_issues") final Object detectedIssues, + @JsonProperty("duration_seconds") final Integer durationSeconds, + @JsonProperty("end_reason") final Conference.ConferenceEndReason endReason, + @JsonProperty("end_time") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime endTime, + @JsonProperty("ended_by") final String endedBy, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("links") final Map links, + @JsonProperty("max_concurrent_participants") final Integer maxConcurrentParticipants, + @JsonProperty("max_participants") final Integer maxParticipants, + @JsonProperty("mixer_region") final Conference.Region mixerRegion, + @JsonProperty("mixer_region_requested") final Conference.Region mixerRegionRequested, + @JsonProperty("processing_state") final Conference.ProcessingState processingState, + @JsonProperty("recording_enabled") final Boolean recordingEnabled, + @JsonProperty("start_time") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime startTime, + @JsonProperty("status") final Conference.ConferenceStatus status, + @JsonProperty("tag_info") final Object tagInfo, + @JsonProperty("tags") final List tags, + @JsonProperty("unique_participants") final Integer uniqueParticipants, + @JsonProperty("url") final URI url + ) { + this.accountSid = accountSid; + this.conferenceSid = conferenceSid; + this.connectDurationSeconds = connectDurationSeconds; + this.createTime = createTime; + this.detectedIssues = detectedIssues; + this.durationSeconds = durationSeconds; + this.endReason = endReason; + this.endTime = endTime; + this.endedBy = endedBy; + this.friendlyName = friendlyName; + this.links = links; + this.maxConcurrentParticipants = maxConcurrentParticipants; + this.maxParticipants = maxParticipants; + this.mixerRegion = mixerRegion; + this.mixerRegionRequested = mixerRegionRequested; + this.processingState = processingState; + this.recordingEnabled = recordingEnabled; + this.startTime = startTime; + this.status = status; + this.tagInfo = tagInfo; + this.tags = tags; + this.uniqueParticipants = uniqueParticipants; + this.url = url; + } + + @Override + public boolean equals(final Object o) { + if (this == o) { + return true; } + + if (o == null || getClass() != o.getClass()) { + return false; + } + + Conference other = (Conference) o; + return ( + Objects.equals(accountSid, other.accountSid) && + Objects.equals(conferenceSid, other.conferenceSid) && + Objects.equals(connectDurationSeconds, other.connectDurationSeconds) && + Objects.equals(createTime, other.createTime) && + Objects.equals(detectedIssues, other.detectedIssues) && + Objects.equals(durationSeconds, other.durationSeconds) && + Objects.equals(endReason, other.endReason) && + Objects.equals(endTime, other.endTime) && + Objects.equals(endedBy, other.endedBy) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(links, other.links) && + Objects.equals(maxConcurrentParticipants, other.maxConcurrentParticipants) && + Objects.equals(maxParticipants, other.maxParticipants) && + Objects.equals(mixerRegion, other.mixerRegion) && + Objects.equals(mixerRegionRequested, other.mixerRegionRequested) && + Objects.equals(processingState, other.processingState) && + Objects.equals(recordingEnabled, other.recordingEnabled) && + Objects.equals(startTime, other.startTime) && + Objects.equals(status, other.status) && + Objects.equals(tagInfo, other.tagInfo) && + Objects.equals(tags, other.tags) && + Objects.equals(uniqueParticipants, other.uniqueParticipants) && + Objects.equals(url, other.url) + ); } + + @Override + public int hashCode() { + return Objects.hash( + accountSid, + conferenceSid, + connectDurationSeconds, + createTime, + detectedIssues, + durationSeconds, + endReason, + endTime, + endedBy, + friendlyName, + links, + maxConcurrentParticipants, + maxParticipants, + mixerRegion, + mixerRegionRequested, + processingState, + recordingEnabled, + startTime, + status, + tagInfo, + tags, + uniqueParticipants, + url + ); + } + + } + diff --git a/src/main/java/com/twilio/rest/insights/v1/ConferenceFetcher.java b/src/main/java/com/twilio/rest/insights/v1/ConferenceFetcher.java index 1422b3bd92..b930c88b84 100644 --- a/src/main/java/com/twilio/rest/insights/v1/ConferenceFetcher.java +++ b/src/main/java/com/twilio/rest/insights/v1/ConferenceFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.insights.v1; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,51 +26,41 @@ public class ConferenceFetcher extends Fetcher { - private String pathConferenceSid; + private String pathconferenceSid; - public ConferenceFetcher(final String pathConferenceSid) { - this.pathConferenceSid = pathConferenceSid; + public ConferenceFetcher(final String pathconferenceSid) { + this.pathconferenceSid = pathconferenceSid; } + @Override public Conference fetch(final TwilioRestClient client) { + String path = "/v1/Conferences/{ConferenceSid}"; - path = - path.replace( - "{" + "ConferenceSid" + "}", - this.pathConferenceSid.toString() - ); + path = path.replace("{" + "ConferenceSid" + "}", this.pathconferenceSid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.INSIGHTS.toString(), - path + HttpMethod.GET, + Domains.INSIGHTS.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Conference fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Conference fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return Conference.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Conference.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/insights/v1/ConferenceReader.java b/src/main/java/com/twilio/rest/insights/v1/ConferenceReader.java index 31e2ca0069..c2ae93d4fc 100644 --- a/src/main/java/com/twilio/rest/insights/v1/ConferenceReader.java +++ b/src/main/java/com/twilio/rest/insights/v1/ConferenceReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -41,185 +42,193 @@ public class ConferenceReader extends Reader { private String endReason; private Long pageSize; - public ConferenceReader() {} + public ConferenceReader() { + } + public ConferenceReader setConferenceSid(final String conferenceSid) { this.conferenceSid = conferenceSid; return this; } + public ConferenceReader setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + public ConferenceReader setStatus(final String status) { this.status = status; return this; } + public ConferenceReader setCreatedAfter(final String createdAfter) { this.createdAfter = createdAfter; return this; } + public ConferenceReader setCreatedBefore(final String createdBefore) { this.createdBefore = createdBefore; return this; } + public ConferenceReader setMixerRegion(final String mixerRegion) { this.mixerRegion = mixerRegion; return this; } + public ConferenceReader setTags(final String tags) { this.tags = tags; return this; } + public ConferenceReader setSubaccount(final String subaccount) { this.subaccount = subaccount; return this; } + public ConferenceReader setDetectedIssues(final String detectedIssues) { this.detectedIssues = detectedIssues; return this; } + public ConferenceReader setEndReason(final String endReason) { this.endReason = endReason; return this; } + public ConferenceReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/Conferences"; + Request request = new Request( - HttpMethod.GET, - Domains.INSIGHTS.toString(), - path + HttpMethod.GET, + Domains.INSIGHTS.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Conference read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Conference read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "conferences", - response.getContent(), - Conference.class, - client.getObjectMapper() - ); + "conferences", + response.getContent(), + Conference.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.INSIGHTS.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.INSIGHTS.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (conferenceSid != null) { - request.addQueryParam("ConferenceSid", conferenceSid); + Serializer.toString(request, "ConferenceSid", conferenceSid, ParameterType.QUERY); } + + if (friendlyName != null) { - request.addQueryParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.QUERY); } + + if (status != null) { - request.addQueryParam("Status", status); + Serializer.toString(request, "Status", status, ParameterType.QUERY); } + + if (createdAfter != null) { - request.addQueryParam("CreatedAfter", createdAfter); + Serializer.toString(request, "CreatedAfter", createdAfter, ParameterType.QUERY); } + + if (createdBefore != null) { - request.addQueryParam("CreatedBefore", createdBefore); + Serializer.toString(request, "CreatedBefore", createdBefore, ParameterType.QUERY); } + + if (mixerRegion != null) { - request.addQueryParam("MixerRegion", mixerRegion); + Serializer.toString(request, "MixerRegion", mixerRegion, ParameterType.QUERY); } + + if (tags != null) { - request.addQueryParam("Tags", tags); + Serializer.toString(request, "Tags", tags, ParameterType.QUERY); } + + if (subaccount != null) { - request.addQueryParam("Subaccount", subaccount); + Serializer.toString(request, "Subaccount", subaccount, ParameterType.QUERY); } + + if (detectedIssues != null) { - request.addQueryParam("DetectedIssues", detectedIssues); + Serializer.toString(request, "DetectedIssues", detectedIssues, ParameterType.QUERY); } + + if (endReason != null) { - request.addQueryParam("EndReason", endReason); + Serializer.toString(request, "EndReason", endReason, ParameterType.QUERY); } + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/insights/v1/Room.java b/src/main/java/com/twilio/rest/insights/v1/Room.java index 762e15d75d..a1fda0a4ac 100644 --- a/src/main/java/com/twilio/rest/insights/v1/Room.java +++ b/src/main/java/com/twilio/rest/insights/v1/Room.java @@ -18,371 +18,107 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.http.HttpMethod; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.List; import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Room extends Resource { - private static final long serialVersionUID = 140614978057184L; - - public static RoomFetcher fetcher(final String pathRoomSid) { - return new RoomFetcher(pathRoomSid); - } - - public static RoomReader reader() { - return new RoomReader(); - } - - /** - * Converts a JSON String into a Room object using the provided ObjectMapper. - * - * @param json Raw JSON String - * @param objectMapper Jackson ObjectMapper - * @return Room object represented by the provided JSON - */ - public static Room fromJson( - final String json, - final ObjectMapper objectMapper - ) { - // Convert all checked exceptions to Runtime - try { - return objectMapper.readValue(json, Room.class); - } catch (final JsonMappingException | JsonParseException e) { - throw new ApiException(e.getMessage(), e); - } catch (final IOException e) { - throw new ApiConnectionException(e.getMessage(), e); - } - } - - /** - * Converts a JSON InputStream into a Room object using the provided - * ObjectMapper. - * - * @param json Raw JSON InputStream - * @param objectMapper Jackson ObjectMapper - * @return Room object represented by the provided JSON - */ - public static Room fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { - // Convert all checked exceptions to Runtime - try { - return objectMapper.readValue(json, Room.class); - } catch (final JsonMappingException | JsonParseException e) { - throw new ApiException(e.getMessage(), e); - } catch (final IOException e) { - throw new ApiConnectionException(e.getMessage(), e); - } - } - private final String accountSid; - private final String roomSid; - private final String roomName; - private final ZonedDateTime createTime; - private final ZonedDateTime endTime; - private final Room.RoomType roomType; - private final Room.RoomStatus roomStatus; - private final URI statusCallback; - private final HttpMethod statusCallbackMethod; - private final Room.CreatedMethod createdMethod; - private final Room.EndReason endReason; - private final Integer maxParticipants; - private final Integer uniqueParticipants; - private final Integer uniqueParticipantIdentities; - private final Integer concurrentParticipants; - private final Integer maxConcurrentParticipants; - private final List codecs; - private final Room.TwilioRealm mediaRegion; - private final Long durationSec; - private final Long totalParticipantDurationSec; - private final Long totalRecordingDurationSec; - private final Room.ProcessingState processingState; - private final Boolean recordingEnabled; - private final Room.EdgeLocation edgeLocation; - private final URI url; - private final Map links; - - @JsonCreator - private Room( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("room_sid") final String roomSid, - @JsonProperty("room_name") final String roomName, - @JsonProperty("create_time") final String createTime, - @JsonProperty("end_time") final String endTime, - @JsonProperty("room_type") final Room.RoomType roomType, - @JsonProperty("room_status") final Room.RoomStatus roomStatus, - @JsonProperty("status_callback") final URI statusCallback, - @JsonProperty( - "status_callback_method" - ) final HttpMethod statusCallbackMethod, - @JsonProperty("created_method") final Room.CreatedMethod createdMethod, - @JsonProperty("end_reason") final Room.EndReason endReason, - @JsonProperty("max_participants") final Integer maxParticipants, - @JsonProperty("unique_participants") final Integer uniqueParticipants, - @JsonProperty( - "unique_participant_identities" - ) final Integer uniqueParticipantIdentities, - @JsonProperty( - "concurrent_participants" - ) final Integer concurrentParticipants, - @JsonProperty( - "max_concurrent_participants" - ) final Integer maxConcurrentParticipants, - @JsonProperty("codecs") final List codecs, - @JsonProperty("media_region") final Room.TwilioRealm mediaRegion, - @JsonProperty("duration_sec") final Long durationSec, - @JsonProperty( - "total_participant_duration_sec" - ) final Long totalParticipantDurationSec, - @JsonProperty( - "total_recording_duration_sec" - ) final Long totalRecordingDurationSec, - @JsonProperty( - "processing_state" - ) final Room.ProcessingState processingState, - @JsonProperty("recording_enabled") final Boolean recordingEnabled, - @JsonProperty("edge_location") final Room.EdgeLocation edgeLocation, - @JsonProperty("url") final URI url, - @JsonProperty("links") final Map links - ) { - this.accountSid = accountSid; - this.roomSid = roomSid; - this.roomName = roomName; - this.createTime = DateConverter.iso8601DateTimeFromString(createTime); - this.endTime = DateConverter.iso8601DateTimeFromString(endTime); - this.roomType = roomType; - this.roomStatus = roomStatus; - this.statusCallback = statusCallback; - this.statusCallbackMethod = statusCallbackMethod; - this.createdMethod = createdMethod; - this.endReason = endReason; - this.maxParticipants = maxParticipants; - this.uniqueParticipants = uniqueParticipants; - this.uniqueParticipantIdentities = uniqueParticipantIdentities; - this.concurrentParticipants = concurrentParticipants; - this.maxConcurrentParticipants = maxConcurrentParticipants; - this.codecs = codecs; - this.mediaRegion = mediaRegion; - this.durationSec = durationSec; - this.totalParticipantDurationSec = totalParticipantDurationSec; - this.totalRecordingDurationSec = totalRecordingDurationSec; - this.processingState = processingState; - this.recordingEnabled = recordingEnabled; - this.edgeLocation = edgeLocation; - this.url = url; - this.links = links; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getRoomSid() { - return this.roomSid; - } - - public final String getRoomName() { - return this.roomName; - } - - public final ZonedDateTime getCreateTime() { - return this.createTime; - } - - public final ZonedDateTime getEndTime() { - return this.endTime; - } - - public final Room.RoomType getRoomType() { - return this.roomType; - } - - public final Room.RoomStatus getRoomStatus() { - return this.roomStatus; - } - - public final URI getStatusCallback() { - return this.statusCallback; - } - - public final HttpMethod getStatusCallbackMethod() { - return this.statusCallbackMethod; + public static RoomFetcher fetcher(final String pathroomSid) { + return new RoomFetcher( + pathroomSid + ); } - public final Room.CreatedMethod getCreatedMethod() { - return this.createdMethod; - } - public final Room.EndReason getEndReason() { - return this.endReason; - } + public static RoomReader reader() { + return new RoomReader( - public final Integer getMaxParticipants() { - return this.maxParticipants; + ); } - public final Integer getUniqueParticipants() { - return this.uniqueParticipants; - } - public final Integer getUniqueParticipantIdentities() { - return this.uniqueParticipantIdentities; - } - - public final Integer getConcurrentParticipants() { - return this.concurrentParticipants; - } + public enum Codec { + VP8("VP8"), + H264("H264"), + VP9("VP9"), + OPUS("opus"); - public final Integer getMaxConcurrentParticipants() { - return this.maxConcurrentParticipants; - } + private final String value; - public final List getCodecs() { - return this.codecs; - } + private Codec(final String value) { + this.value = value; + } - public final Room.TwilioRealm getMediaRegion() { - return this.mediaRegion; - } + public String toString() { + return value; + } - public final Long getDurationSec() { - return this.durationSec; + @JsonCreator + public static Codec forValue(final String value) { + return Promoter.enumFromString(value, Codec.values()); + } } - public final Long getTotalParticipantDurationSec() { - return this.totalParticipantDurationSec; - } + public enum RoomType { + GO("go"), + PEER_TO_PEER("peer_to_peer"), + GROUP("group"), + GROUP_SMALL("group_small"); - public final Long getTotalRecordingDurationSec() { - return this.totalRecordingDurationSec; - } + private final String value; - public final Room.ProcessingState getProcessingState() { - return this.processingState; - } + private RoomType(final String value) { + this.value = value; + } - public final Boolean getRecordingEnabled() { - return this.recordingEnabled; - } + public String toString() { + return value; + } - public final Room.EdgeLocation getEdgeLocation() { - return this.edgeLocation; + @JsonCreator + public static RoomType forValue(final String value) { + return Promoter.enumFromString(value, RoomType.values()); + } } - public final URI getUrl() { - return this.url; - } + public enum RoomStatus { + IN_PROGRESS("in_progress"), + COMPLETED("completed"); - public final Map getLinks() { - return this.links; - } + private final String value; - @Override - public boolean equals(final Object o) { - if (this == o) { - return true; + private RoomStatus(final String value) { + this.value = value; } - if (o == null || getClass() != o.getClass()) { - return false; + public String toString() { + return value; } - Room other = (Room) o; - - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(roomSid, other.roomSid) && - Objects.equals(roomName, other.roomName) && - Objects.equals(createTime, other.createTime) && - Objects.equals(endTime, other.endTime) && - Objects.equals(roomType, other.roomType) && - Objects.equals(roomStatus, other.roomStatus) && - Objects.equals(statusCallback, other.statusCallback) && - Objects.equals(statusCallbackMethod, other.statusCallbackMethod) && - Objects.equals(createdMethod, other.createdMethod) && - Objects.equals(endReason, other.endReason) && - Objects.equals(maxParticipants, other.maxParticipants) && - Objects.equals(uniqueParticipants, other.uniqueParticipants) && - Objects.equals( - uniqueParticipantIdentities, - other.uniqueParticipantIdentities - ) && - Objects.equals( - concurrentParticipants, - other.concurrentParticipants - ) && - Objects.equals( - maxConcurrentParticipants, - other.maxConcurrentParticipants - ) && - Objects.equals(codecs, other.codecs) && - Objects.equals(mediaRegion, other.mediaRegion) && - Objects.equals(durationSec, other.durationSec) && - Objects.equals( - totalParticipantDurationSec, - other.totalParticipantDurationSec - ) && - Objects.equals( - totalRecordingDurationSec, - other.totalRecordingDurationSec - ) && - Objects.equals(processingState, other.processingState) && - Objects.equals(recordingEnabled, other.recordingEnabled) && - Objects.equals(edgeLocation, other.edgeLocation) && - Objects.equals(url, other.url) && - Objects.equals(links, other.links) - ); - } - - @Override - public int hashCode() { - return Objects.hash( - accountSid, - roomSid, - roomName, - createTime, - endTime, - roomType, - roomStatus, - statusCallback, - statusCallbackMethod, - createdMethod, - endReason, - maxParticipants, - uniqueParticipants, - uniqueParticipantIdentities, - concurrentParticipants, - maxConcurrentParticipants, - codecs, - mediaRegion, - durationSec, - totalParticipantDurationSec, - totalRecordingDurationSec, - processingState, - recordingEnabled, - edgeLocation, - url, - links - ); + @JsonCreator + public static RoomStatus forValue(final String value) { + return Promoter.enumFromString(value, RoomStatus.values()); + } } public enum EndReason { @@ -405,15 +141,15 @@ public static EndReason forValue(final String value) { } } - public enum ProcessingState { - COMPLETE("complete"), - IN_PROGRESS("in_progress"), - TIMEOUT("timeout"), - NOT_STARTED("not_started"); + public enum RoomRoomCodec { + VP8("VP8"), + H264("H264"), + VP9("VP9"), + OPUS("opus"); private final String value; - private ProcessingState(final String value) { + private RoomRoomCodec(final String value) { this.value = value; } @@ -422,26 +158,20 @@ public String toString() { } @JsonCreator - public static ProcessingState forValue(final String value) { - return Promoter.enumFromString(value, ProcessingState.values()); + public static RoomRoomCodec forValue(final String value) { + return Promoter.enumFromString(value, RoomRoomCodec.values()); } } - public enum TwilioRealm { - US1("us1"), - US2("us2"), - AU1("au1"), - BR1("br1"), - IE1("ie1"), - JP1("jp1"), - SG1("sg1"), - IN1("in1"), - DE1("de1"), - GLL("gll"); + public enum RoomRoomRoomCodec { + VP8("VP8"), + H264("H264"), + VP9("VP9"), + OPUS("opus"); private final String value; - private TwilioRealm(final String value) { + private RoomRoomRoomCodec(final String value) { this.value = value; } @@ -450,20 +180,26 @@ public String toString() { } @JsonCreator - public static TwilioRealm forValue(final String value) { - return Promoter.enumFromString(value, TwilioRealm.values()); + public static RoomRoomRoomCodec forValue(final String value) { + return Promoter.enumFromString(value, RoomRoomRoomCodec.values()); } } - public enum RoomType { - GO("go"), - PEER_TO_PEER("peer_to_peer"), - GROUP("group"), - GROUP_SMALL("group_small"); + public enum TwilioRealm { + US1("us1"), + US2("us2"), + AU1("au1"), + BR1("br1"), + IE1("ie1"), + JP1("jp1"), + SG1("sg1"), + IN1("in1"), + DE1("de1"), + GLL("gll"); private final String value; - private RoomType(final String value) { + private TwilioRealm(final String value) { this.value = value; } @@ -472,12 +208,12 @@ public String toString() { } @JsonCreator - public static RoomType forValue(final String value) { - return Promoter.enumFromString(value, RoomType.values()); + public static TwilioRealm forValue(final String value) { + return Promoter.enumFromString(value, TwilioRealm.values()); } } - public enum Codec { + public enum RoomCodec { VP8("VP8"), H264("H264"), VP9("VP9"), @@ -485,7 +221,7 @@ public enum Codec { private final String value; - private Codec(final String value) { + private RoomCodec(final String value) { this.value = value; } @@ -494,18 +230,19 @@ public String toString() { } @JsonCreator - public static Codec forValue(final String value) { - return Promoter.enumFromString(value, Codec.values()); + public static RoomCodec forValue(final String value) { + return Promoter.enumFromString(value, RoomCodec.values()); } } - public enum RoomStatus { - IN_PROGRESS("in_progress"), - COMPLETED("completed"); + public enum CreatedMethod { + SDK("sdk"), + AD_HOC("ad_hoc"), + API("api"); private final String value; - private RoomStatus(final String value) { + private CreatedMethod(final String value) { this.value = value; } @@ -514,19 +251,20 @@ public String toString() { } @JsonCreator - public static RoomStatus forValue(final String value) { - return Promoter.enumFromString(value, RoomStatus.values()); + public static CreatedMethod forValue(final String value) { + return Promoter.enumFromString(value, CreatedMethod.values()); } } - public enum CreatedMethod { - SDK("sdk"), - AD_HOC("ad_hoc"), - API("api"); + public enum ProcessingState { + COMPLETE("complete"), + IN_PROGRESS("in_progress"), + TIMEOUT("timeout"), + NOT_STARTED("not_started"); private final String value; - private CreatedMethod(final String value) { + private ProcessingState(final String value) { this.value = value; } @@ -535,8 +273,8 @@ public String toString() { } @JsonCreator - public static CreatedMethod forValue(final String value) { - return Promoter.enumFromString(value, CreatedMethod.values()); + public static ProcessingState forValue(final String value) { + return Promoter.enumFromString(value, ProcessingState.values()); } } @@ -566,4 +304,243 @@ public static EdgeLocation forValue(final String value) { return Promoter.enumFromString(value, EdgeLocation.values()); } } + + + /** + * Converts a JSON String into a Room object using the provided ObjectMapper. + * + * @param json Raw JSON String + * @param objectMapper Jackson ObjectMapper + * @return Room object represented by the provided JSON + */ + public static Room fromJson(final String json, final ObjectMapper objectMapper) { + // Convert all checked exceptions to Runtime + try { + return objectMapper.readValue(json, Room.class); + } catch (final JsonMappingException | JsonParseException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + /** + * Converts a JSON InputStream into a Room object using the provided + * ObjectMapper. + * + * @param json Raw JSON InputStream + * @param objectMapper Jackson ObjectMapper + * @return Room object represented by the provided JSON + */ + public static Room fromJson(final InputStream json, final ObjectMapper objectMapper) { + // Convert all checked exceptions to Runtime + try { + return objectMapper.readValue(json, Room.class); + } catch (final JsonMappingException | JsonParseException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter + private final String accountSid; + @Getter + private final List codecs; + @Getter + private final Integer concurrentParticipants; + @Getter + private final ZonedDateTime createTime; + @Getter + private final Room.CreatedMethod createdMethod; + @Getter + private final Long durationSec; + @Getter + private final Room.EdgeLocation edgeLocation; + @Getter + private final Room.EndReason endReason; + @Getter + private final ZonedDateTime endTime; + @Getter + private final Map links; + @Getter + private final Integer maxConcurrentParticipants; + @Getter + private final Integer maxParticipants; + @Getter + private final Room.TwilioRealm mediaRegion; + @Getter + private final Room.ProcessingState processingState; + @Getter + private final Boolean recordingEnabled; + @Getter + private final String roomName; + @Getter + private final String roomSid; + @Getter + private final Room.RoomStatus roomStatus; + @Getter + private final Room.RoomType roomType; + @Getter + private final URI statusCallback; + @Getter + private final HttpMethod statusCallbackMethod; + @Getter + private final Long totalParticipantDurationSec; + @Getter + private final Long totalRecordingDurationSec; + @Getter + private final Integer uniqueParticipantIdentities; + @Getter + private final Integer uniqueParticipants; + @Getter + private final URI url; + + @JsonCreator + private Room( + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("codecs") final List codecs, + @JsonProperty("concurrent_participants") final Integer concurrentParticipants, + @JsonProperty("create_time") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime createTime, + @JsonProperty("created_method") final Room.CreatedMethod createdMethod, + @JsonProperty("duration_sec") final Long durationSec, + @JsonProperty("edge_location") final Room.EdgeLocation edgeLocation, + @JsonProperty("end_reason") final Room.EndReason endReason, + @JsonProperty("end_time") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime endTime, + @JsonProperty("links") final Map links, + @JsonProperty("max_concurrent_participants") final Integer maxConcurrentParticipants, + @JsonProperty("max_participants") final Integer maxParticipants, + @JsonProperty("media_region") final Room.TwilioRealm mediaRegion, + @JsonProperty("processing_state") final Room.ProcessingState processingState, + @JsonProperty("recording_enabled") final Boolean recordingEnabled, + @JsonProperty("room_name") final String roomName, + @JsonProperty("room_sid") final String roomSid, + @JsonProperty("room_status") final Room.RoomStatus roomStatus, + @JsonProperty("room_type") final Room.RoomType roomType, + @JsonProperty("status_callback") final URI statusCallback, + @JsonProperty("status_callback_method") final HttpMethod statusCallbackMethod, + @JsonProperty("total_participant_duration_sec") final Long totalParticipantDurationSec, + @JsonProperty("total_recording_duration_sec") final Long totalRecordingDurationSec, + @JsonProperty("unique_participant_identities") final Integer uniqueParticipantIdentities, + @JsonProperty("unique_participants") final Integer uniqueParticipants, + @JsonProperty("url") final URI url + ) { + this.accountSid = accountSid; + this.codecs = codecs; + this.concurrentParticipants = concurrentParticipants; + this.createTime = createTime; + this.createdMethod = createdMethod; + this.durationSec = durationSec; + this.edgeLocation = edgeLocation; + this.endReason = endReason; + this.endTime = endTime; + this.links = links; + this.maxConcurrentParticipants = maxConcurrentParticipants; + this.maxParticipants = maxParticipants; + this.mediaRegion = mediaRegion; + this.processingState = processingState; + this.recordingEnabled = recordingEnabled; + this.roomName = roomName; + this.roomSid = roomSid; + this.roomStatus = roomStatus; + this.roomType = roomType; + this.statusCallback = statusCallback; + this.statusCallbackMethod = statusCallbackMethod; + this.totalParticipantDurationSec = totalParticipantDurationSec; + this.totalRecordingDurationSec = totalRecordingDurationSec; + this.uniqueParticipantIdentities = uniqueParticipantIdentities; + this.uniqueParticipants = uniqueParticipants; + this.url = url; + } + + @Override + public boolean equals(final Object o) { + if (this == o) { + return true; + } + + if (o == null || getClass() != o.getClass()) { + return false; + } + + Room other = (Room) o; + return ( + Objects.equals(accountSid, other.accountSid) && + Objects.equals(codecs, other.codecs) && + Objects.equals(concurrentParticipants, other.concurrentParticipants) && + Objects.equals(createTime, other.createTime) && + Objects.equals(createdMethod, other.createdMethod) && + Objects.equals(durationSec, other.durationSec) && + Objects.equals(edgeLocation, other.edgeLocation) && + Objects.equals(endReason, other.endReason) && + Objects.equals(endTime, other.endTime) && + Objects.equals(links, other.links) && + Objects.equals(maxConcurrentParticipants, other.maxConcurrentParticipants) && + Objects.equals(maxParticipants, other.maxParticipants) && + Objects.equals(mediaRegion, other.mediaRegion) && + Objects.equals(processingState, other.processingState) && + Objects.equals(recordingEnabled, other.recordingEnabled) && + Objects.equals(roomName, other.roomName) && + Objects.equals(roomSid, other.roomSid) && + Objects.equals(roomStatus, other.roomStatus) && + Objects.equals(roomType, other.roomType) && + Objects.equals(statusCallback, other.statusCallback) && + Objects.equals(statusCallbackMethod, other.statusCallbackMethod) && + Objects.equals(totalParticipantDurationSec, other.totalParticipantDurationSec) && + Objects.equals(totalRecordingDurationSec, other.totalRecordingDurationSec) && + Objects.equals(uniqueParticipantIdentities, other.uniqueParticipantIdentities) && + Objects.equals(uniqueParticipants, other.uniqueParticipants) && + Objects.equals(url, other.url) + ); + } + + @Override + public int hashCode() { + return Objects.hash( + accountSid, + codecs, + concurrentParticipants, + createTime, + createdMethod, + durationSec, + edgeLocation, + endReason, + endTime, + links, + maxConcurrentParticipants, + maxParticipants, + mediaRegion, + processingState, + recordingEnabled, + roomName, + roomSid, + roomStatus, + roomType, + statusCallback, + statusCallbackMethod, + totalParticipantDurationSec, + totalRecordingDurationSec, + uniqueParticipantIdentities, + uniqueParticipants, + url + ); + } + + } + diff --git a/src/main/java/com/twilio/rest/insights/v1/RoomFetcher.java b/src/main/java/com/twilio/rest/insights/v1/RoomFetcher.java index 7c5bc2a24d..b0c1a8efc4 100644 --- a/src/main/java/com/twilio/rest/insights/v1/RoomFetcher.java +++ b/src/main/java/com/twilio/rest/insights/v1/RoomFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.insights.v1; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,44 +26,41 @@ public class RoomFetcher extends Fetcher { - private String pathRoomSid; + private String pathroomSid; - public RoomFetcher(final String pathRoomSid) { - this.pathRoomSid = pathRoomSid; + public RoomFetcher(final String pathroomSid) { + this.pathroomSid = pathroomSid; } + @Override public Room fetch(final TwilioRestClient client) { + String path = "/v1/Video/Rooms/{RoomSid}"; - path = path.replace("{" + "RoomSid" + "}", this.pathRoomSid.toString()); + path = path.replace("{" + "RoomSid" + "}", this.pathroomSid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.INSIGHTS.toString(), - path + HttpMethod.GET, + Domains.INSIGHTS.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Room fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Room fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Room.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/insights/v1/RoomReader.java b/src/main/java/com/twilio/rest/insights/v1/RoomReader.java index da50025667..66efa6c46c 100644 --- a/src/main/java/com/twilio/rest/insights/v1/RoomReader.java +++ b/src/main/java/com/twilio/rest/insights/v1/RoomReader.java @@ -17,8 +17,9 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; import com.twilio.converter.Promoter; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,6 +28,7 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.time.ZonedDateTime; import java.util.List; @@ -39,7 +41,9 @@ public class RoomReader extends Reader { private ZonedDateTime createdBefore; private Long pageSize; - public RoomReader() {} + public RoomReader() { + } + public RoomReader setRoomType(final List roomType) { this.roomType = roomType; @@ -64,140 +68,121 @@ public RoomReader setRoomName(final String roomName) { return this; } + public RoomReader setCreatedAfter(final ZonedDateTime createdAfter) { this.createdAfter = createdAfter; return this; } + public RoomReader setCreatedBefore(final ZonedDateTime createdBefore) { this.createdBefore = createdBefore; return this; } + public RoomReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/Video/Rooms"; + Request request = new Request( - HttpMethod.GET, - Domains.INSIGHTS.toString(), - path + HttpMethod.GET, + Domains.INSIGHTS.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Room read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Room read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "rooms", - response.getContent(), - Room.class, - client.getObjectMapper() - ); + "rooms", + response.getContent(), + Room.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.INSIGHTS.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.INSIGHTS.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (roomType != null) { - for (Room.RoomType prop : roomType) { - request.addQueryParam("RoomType", prop.toString()); + for (Room.RoomType param : roomType) { + Serializer.toString(request, "RoomType", param, ParameterType.QUERY); } } + + if (codec != null) { - for (Room.Codec prop : codec) { - request.addQueryParam("Codec", prop.toString()); + for (Room.Codec param : codec) { + Serializer.toString(request, "Codec", param, ParameterType.QUERY); } } + + if (roomName != null) { - request.addQueryParam("RoomName", roomName); + Serializer.toString(request, "RoomName", roomName, ParameterType.QUERY); } + + if (createdAfter != null) { - request.addQueryParam( - "CreatedAfter", - createdAfter.toInstant().toString() - ); + Serializer.toString(request, "CreatedAfter", createdAfter, ParameterType.QUERY); } + if (createdBefore != null) { - request.addQueryParam( - "CreatedBefore", - createdBefore.toInstant().toString() - ); + Serializer.toString(request, "CreatedBefore", createdBefore, ParameterType.QUERY); } + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/insights/v1/Setting.java b/src/main/java/com/twilio/rest/insights/v1/Setting.java index d2515f77d3..98df72bb14 100644 --- a/src/main/java/com/twilio/rest/insights/v1/Setting.java +++ b/src/main/java/com/twilio/rest/insights/v1/Setting.java @@ -18,43 +18,47 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Setting extends Resource { - private static final long serialVersionUID = 24698393526973L; public static SettingFetcher fetcher() { - return new SettingFetcher(); + return new SettingFetcher( + + ); } + public static SettingUpdater updater() { - return new SettingUpdater(); + return new SettingUpdater( + + ); } + /** * Converts a JSON String into a Setting object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Setting object represented by the provided JSON */ - public static Setting fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Setting fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Setting.class); @@ -69,14 +73,11 @@ public static Setting fromJson( * Converts a JSON InputStream into a Setting object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Setting object represented by the provided JSON */ - public static Setting fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Setting fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Setting.class); @@ -87,38 +88,39 @@ public static Setting fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; + @Getter private final Boolean advancedFeatures; - private final Boolean voiceTrace; + @Getter private final URI url; + @Getter + private final Boolean voiceTrace; @JsonCreator private Setting( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("advanced_features") final Boolean advancedFeatures, - @JsonProperty("voice_trace") final Boolean voiceTrace, - @JsonProperty("url") final URI url + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("advanced_features") final Boolean advancedFeatures, + @JsonProperty("url") final URI url, + @JsonProperty("voice_trace") final Boolean voiceTrace ) { this.accountSid = accountSid; this.advancedFeatures = advancedFeatures; - this.voiceTrace = voiceTrace; this.url = url; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final Boolean getAdvancedFeatures() { - return this.advancedFeatures; - } - - public final Boolean getVoiceTrace() { - return this.voiceTrace; - } - - public final URI getUrl() { - return this.url; + this.voiceTrace = voiceTrace; } @Override @@ -132,17 +134,24 @@ public boolean equals(final Object o) { } Setting other = (Setting) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(advancedFeatures, other.advancedFeatures) && - Objects.equals(voiceTrace, other.voiceTrace) && - Objects.equals(url, other.url) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(advancedFeatures, other.advancedFeatures) && + Objects.equals(url, other.url) && + Objects.equals(voiceTrace, other.voiceTrace) ); } @Override public int hashCode() { - return Objects.hash(accountSid, advancedFeatures, voiceTrace, url); + return Objects.hash( + accountSid, + advancedFeatures, + url, + voiceTrace + ); } + + } + diff --git a/src/main/java/com/twilio/rest/insights/v1/SettingFetcher.java b/src/main/java/com/twilio/rest/insights/v1/SettingFetcher.java index 99d4c471fc..bce3f0c170 100644 --- a/src/main/java/com/twilio/rest/insights/v1/SettingFetcher.java +++ b/src/main/java/com/twilio/rest/insights/v1/SettingFetcher.java @@ -15,7 +15,8 @@ package com.twilio.rest.insights.v1; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,50 +30,53 @@ public class SettingFetcher extends Fetcher { private String subaccountSid; - public SettingFetcher() {} + public SettingFetcher() { + } + public SettingFetcher setSubaccountSid(final String subaccountSid) { this.subaccountSid = subaccountSid; return this; } + @Override public Setting fetch(final TwilioRestClient client) { + String path = "/v1/Voice/Settings"; + Request request = new Request( - HttpMethod.GET, - Domains.INSIGHTS.toString(), - path + HttpMethod.GET, + Domains.INSIGHTS.toString(), + path ); addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Setting fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Setting fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Setting.fromJson(response.getStream(), client.getObjectMapper()); } private void addQueryParams(final Request request) { + + if (subaccountSid != null) { - request.addQueryParam("SubaccountSid", subaccountSid); + Serializer.toString(request, "SubaccountSid", subaccountSid, ParameterType.QUERY); } + + } } diff --git a/src/main/java/com/twilio/rest/insights/v1/SettingUpdater.java b/src/main/java/com/twilio/rest/insights/v1/SettingUpdater.java index 8c2a8ce5f1..9db84610f4 100644 --- a/src/main/java/com/twilio/rest/insights/v1/SettingUpdater.java +++ b/src/main/java/com/twilio/rest/insights/v1/SettingUpdater.java @@ -16,6 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -26,54 +28,57 @@ import com.twilio.rest.Domains; public class SettingUpdater extends Updater { - private Boolean advancedFeatures; private Boolean voiceTrace; private String subaccountSid; - public SettingUpdater() {} + public SettingUpdater() { + } + public SettingUpdater setAdvancedFeatures(final Boolean advancedFeatures) { this.advancedFeatures = advancedFeatures; return this; } + public SettingUpdater setVoiceTrace(final Boolean voiceTrace) { this.voiceTrace = voiceTrace; return this; } + public SettingUpdater setSubaccountSid(final String subaccountSid) { this.subaccountSid = subaccountSid; return this; } + @Override public Setting update(final TwilioRestClient client) { + String path = "/v1/Voice/Settings"; + Request request = new Request( - HttpMethod.POST, - Domains.INSIGHTS.toString(), - path + HttpMethod.POST, + Domains.INSIGHTS.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Setting update failed: Unable to connect to server" - ); + throw new ApiConnectionException("Setting update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -82,17 +87,21 @@ public Setting update(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (advancedFeatures != null) { - request.addPostParam( - "AdvancedFeatures", - advancedFeatures.toString() - ); + Serializer.toString(request, "AdvancedFeatures", advancedFeatures, ParameterType.URLENCODED); } + + if (voiceTrace != null) { - request.addPostParam("VoiceTrace", voiceTrace.toString()); + Serializer.toString(request, "VoiceTrace", voiceTrace, ParameterType.URLENCODED); } + + if (subaccountSid != null) { - request.addPostParam("SubaccountSid", subaccountSid); + Serializer.toString(request, "SubaccountSid", subaccountSid, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/insights/v1/call/Annotation.java b/src/main/java/com/twilio/rest/insights/v1/call/Annotation.java index 0821e30210..487c55e2ac 100644 --- a/src/main/java/com/twilio/rest/insights/v1/call/Annotation.java +++ b/src/main/java/com/twilio/rest/insights/v1/call/Annotation.java @@ -18,45 +18,95 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.util.List; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Annotation extends Resource { - private static final long serialVersionUID = 9735005754677L; - public static AnnotationFetcher fetcher(final String pathCallSid) { - return new AnnotationFetcher(pathCallSid); + public static AnnotationFetcher fetcher(final String pathcallSid) { + return new AnnotationFetcher( + pathcallSid + ); } - public static AnnotationUpdater updater(final String pathCallSid) { - return new AnnotationUpdater(pathCallSid); + + public static AnnotationUpdater updater(final String pathcallSid) { + return new AnnotationUpdater( + pathcallSid + ); } + + public enum AnsweredBy { + UNKNOWN_ANSWERED_BY("unknown_answered_by"), + HUMAN("human"), + MACHINE("machine"); + + private final String value; + + private AnsweredBy(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static AnsweredBy forValue(final String value) { + return Promoter.enumFromString(value, AnsweredBy.values()); + } + } + + public enum ConnectivityIssue { + UNKNOWN_CONNECTIVITY_ISSUE("unknown_connectivity_issue"), + NO_CONNECTIVITY_ISSUE("no_connectivity_issue"), + INVALID_NUMBER("invalid_number"), + CALLER_ID("caller_id"), + DROPPED_CALL("dropped_call"), + NUMBER_REACHABILITY("number_reachability"); + + private final String value; + + private ConnectivityIssue(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static ConnectivityIssue forValue(final String value) { + return Promoter.enumFromString(value, ConnectivityIssue.values()); + } + } + + /** * Converts a JSON String into a Annotation object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Annotation object represented by the provided JSON */ - public static Annotation fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Annotation fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Annotation.class); @@ -71,14 +121,11 @@ public static Annotation fromJson( * Converts a JSON InputStream into a Annotation object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Annotation object represented by the provided JSON */ - public static Annotation fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Annotation fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Annotation.class); @@ -89,84 +136,65 @@ public static Annotation fromJson( } } - private final String callSid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; + @Getter private final Annotation.AnsweredBy answeredBy; - private final Annotation.ConnectivityIssue connectivityIssue; - private final List qualityIssues; - private final Boolean spam; + @Getter private final Integer callScore; + @Getter + private final String callSid; + @Getter private final String comment; + @Getter + private final Annotation.ConnectivityIssue connectivityIssue; + @Getter private final String incident; + @Getter + private final List qualityIssues; + @Getter + private final Boolean spam; + @Getter private final URI url; @JsonCreator private Annotation( - @JsonProperty("call_sid") final String callSid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("answered_by") final Annotation.AnsweredBy answeredBy, - @JsonProperty( - "connectivity_issue" - ) final Annotation.ConnectivityIssue connectivityIssue, - @JsonProperty("quality_issues") final List qualityIssues, - @JsonProperty("spam") final Boolean spam, - @JsonProperty("call_score") final Integer callScore, - @JsonProperty("comment") final String comment, - @JsonProperty("incident") final String incident, - @JsonProperty("url") final URI url + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("answered_by") final Annotation.AnsweredBy answeredBy, + @JsonProperty("call_score") final Integer callScore, + @JsonProperty("call_sid") final String callSid, + @JsonProperty("comment") final String comment, + @JsonProperty("connectivity_issue") final Annotation.ConnectivityIssue connectivityIssue, + @JsonProperty("incident") final String incident, + @JsonProperty("quality_issues") final List qualityIssues, + @JsonProperty("spam") final Boolean spam, + @JsonProperty("url") final URI url ) { - this.callSid = callSid; this.accountSid = accountSid; this.answeredBy = answeredBy; - this.connectivityIssue = connectivityIssue; - this.qualityIssues = qualityIssues; - this.spam = spam; this.callScore = callScore; + this.callSid = callSid; this.comment = comment; + this.connectivityIssue = connectivityIssue; this.incident = incident; + this.qualityIssues = qualityIssues; + this.spam = spam; this.url = url; } - public final String getCallSid() { - return this.callSid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final Annotation.AnsweredBy getAnsweredBy() { - return this.answeredBy; - } - - public final Annotation.ConnectivityIssue getConnectivityIssue() { - return this.connectivityIssue; - } - - public final List getQualityIssues() { - return this.qualityIssues; - } - - public final Boolean getSpam() { - return this.spam; - } - - public final Integer getCallScore() { - return this.callScore; - } - - public final String getComment() { - return this.comment; - } - - public final String getIncident() { - return this.incident; - } - - public final URI getUrl() { - return this.url; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -178,79 +206,36 @@ public boolean equals(final Object o) { } Annotation other = (Annotation) o; - return ( - Objects.equals(callSid, other.callSid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(answeredBy, other.answeredBy) && - Objects.equals(connectivityIssue, other.connectivityIssue) && - Objects.equals(qualityIssues, other.qualityIssues) && - Objects.equals(spam, other.spam) && - Objects.equals(callScore, other.callScore) && - Objects.equals(comment, other.comment) && - Objects.equals(incident, other.incident) && - Objects.equals(url, other.url) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(answeredBy, other.answeredBy) && + Objects.equals(callScore, other.callScore) && + Objects.equals(callSid, other.callSid) && + Objects.equals(comment, other.comment) && + Objects.equals(connectivityIssue, other.connectivityIssue) && + Objects.equals(incident, other.incident) && + Objects.equals(qualityIssues, other.qualityIssues) && + Objects.equals(spam, other.spam) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - callSid, - accountSid, - answeredBy, - connectivityIssue, - qualityIssues, - spam, - callScore, - comment, - incident, - url + accountSid, + answeredBy, + callScore, + callSid, + comment, + connectivityIssue, + incident, + qualityIssues, + spam, + url ); } - public enum ConnectivityIssue { - UNKNOWN_CONNECTIVITY_ISSUE("unknown_connectivity_issue"), - NO_CONNECTIVITY_ISSUE("no_connectivity_issue"), - INVALID_NUMBER("invalid_number"), - CALLER_ID("caller_id"), - DROPPED_CALL("dropped_call"), - NUMBER_REACHABILITY("number_reachability"); - private final String value; - - private ConnectivityIssue(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static ConnectivityIssue forValue(final String value) { - return Promoter.enumFromString(value, ConnectivityIssue.values()); - } - } - - public enum AnsweredBy { - UNKNOWN_ANSWERED_BY("unknown_answered_by"), - HUMAN("human"), - MACHINE("machine"); - - private final String value; - - private AnsweredBy(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static AnsweredBy forValue(final String value) { - return Promoter.enumFromString(value, AnsweredBy.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/insights/v1/call/AnnotationFetcher.java b/src/main/java/com/twilio/rest/insights/v1/call/AnnotationFetcher.java index 40f6a78a80..cd9e6c768f 100644 --- a/src/main/java/com/twilio/rest/insights/v1/call/AnnotationFetcher.java +++ b/src/main/java/com/twilio/rest/insights/v1/call/AnnotationFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.insights.v1.call; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,47 +26,41 @@ public class AnnotationFetcher extends Fetcher { - private String pathCallSid; + private String pathcallSid; - public AnnotationFetcher(final String pathCallSid) { - this.pathCallSid = pathCallSid; + public AnnotationFetcher(final String pathcallSid) { + this.pathcallSid = pathcallSid; } + @Override public Annotation fetch(final TwilioRestClient client) { + String path = "/v1/Voice/{CallSid}/Annotation"; - path = path.replace("{" + "CallSid" + "}", this.pathCallSid.toString()); + path = path.replace("{" + "CallSid" + "}", this.pathcallSid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.INSIGHTS.toString(), - path + HttpMethod.GET, + Domains.INSIGHTS.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Annotation fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Annotation fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return Annotation.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Annotation.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/insights/v1/call/AnnotationUpdater.java b/src/main/java/com/twilio/rest/insights/v1/call/AnnotationUpdater.java index e3d5fc9c8a..1924c3d8ad 100644 --- a/src/main/java/com/twilio/rest/insights/v1/call/AnnotationUpdater.java +++ b/src/main/java/com/twilio/rest/insights/v1/call/AnnotationUpdater.java @@ -16,6 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -26,8 +28,7 @@ import com.twilio.rest.Domains; public class AnnotationUpdater extends Updater { - - private String pathCallSid; + private String pathcallSid; private Annotation.AnsweredBy answeredBy; private Annotation.ConnectivityIssue connectivityIssue; private String qualityIssues; @@ -36,111 +37,123 @@ public class AnnotationUpdater extends Updater { private String comment; private String incident; - public AnnotationUpdater(final String pathCallSid) { - this.pathCallSid = pathCallSid; + public AnnotationUpdater(final String pathcallSid) { + this.pathcallSid = pathcallSid; } - public AnnotationUpdater setAnsweredBy( - final Annotation.AnsweredBy answeredBy - ) { + + public AnnotationUpdater setAnsweredBy(final Annotation.AnsweredBy answeredBy) { this.answeredBy = answeredBy; return this; } - public AnnotationUpdater setConnectivityIssue( - final Annotation.ConnectivityIssue connectivityIssue - ) { + + public AnnotationUpdater setConnectivityIssue(final Annotation.ConnectivityIssue connectivityIssue) { this.connectivityIssue = connectivityIssue; return this; } + public AnnotationUpdater setQualityIssues(final String qualityIssues) { this.qualityIssues = qualityIssues; return this; } + public AnnotationUpdater setSpam(final Boolean spam) { this.spam = spam; return this; } + public AnnotationUpdater setCallScore(final Integer callScore) { this.callScore = callScore; return this; } + public AnnotationUpdater setComment(final String comment) { this.comment = comment; return this; } + public AnnotationUpdater setIncident(final String incident) { this.incident = incident; return this; } + @Override public Annotation update(final TwilioRestClient client) { + String path = "/v1/Voice/{CallSid}/Annotation"; - path = path.replace("{" + "CallSid" + "}", this.pathCallSid.toString()); + path = path.replace("{" + "CallSid" + "}", this.pathcallSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.INSIGHTS.toString(), - path + HttpMethod.POST, + Domains.INSIGHTS.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Annotation update failed: Unable to connect to server" - ); + throw new ApiConnectionException("Annotation update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Annotation.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Annotation.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (answeredBy != null) { - request.addPostParam("AnsweredBy", answeredBy.toString()); + Serializer.toString(request, "AnsweredBy", answeredBy, ParameterType.URLENCODED); } + + if (connectivityIssue != null) { - request.addPostParam( - "ConnectivityIssue", - connectivityIssue.toString() - ); + Serializer.toString(request, "ConnectivityIssue", connectivityIssue, ParameterType.URLENCODED); } + + if (qualityIssues != null) { - request.addPostParam("QualityIssues", qualityIssues); + Serializer.toString(request, "QualityIssues", qualityIssues, ParameterType.URLENCODED); } + + if (spam != null) { - request.addPostParam("Spam", spam.toString()); + Serializer.toString(request, "Spam", spam, ParameterType.URLENCODED); } + + if (callScore != null) { - request.addPostParam("CallScore", callScore.toString()); + Serializer.toString(request, "CallScore", callScore, ParameterType.URLENCODED); } + + if (comment != null) { - request.addPostParam("Comment", comment); + Serializer.toString(request, "Comment", comment, ParameterType.URLENCODED); } + + if (incident != null) { - request.addPostParam("Incident", incident); + Serializer.toString(request, "Incident", incident, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/insights/v1/call/CallSummary.java b/src/main/java/com/twilio/rest/insights/v1/call/CallSummary.java index ae8c1be46a..9dd656135c 100644 --- a/src/main/java/com/twilio/rest/insights/v1/call/CallSummary.java +++ b/src/main/java/com/twilio/rest/insights/v1/call/CallSummary.java @@ -18,313 +18,35 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.List; -import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class CallSummary extends Resource { - private static final long serialVersionUID = 200007638188409L; - - public static CallSummaryFetcher fetcher(final String pathCallSid) { - return new CallSummaryFetcher(pathCallSid); - } - - /** - * Converts a JSON String into a CallSummary object using the provided ObjectMapper. - * - * @param json Raw JSON String - * @param objectMapper Jackson ObjectMapper - * @return CallSummary object represented by the provided JSON - */ - public static CallSummary fromJson( - final String json, - final ObjectMapper objectMapper - ) { - // Convert all checked exceptions to Runtime - try { - return objectMapper.readValue(json, CallSummary.class); - } catch (final JsonMappingException | JsonParseException e) { - throw new ApiException(e.getMessage(), e); - } catch (final IOException e) { - throw new ApiConnectionException(e.getMessage(), e); - } - } - - /** - * Converts a JSON InputStream into a CallSummary object using the provided - * ObjectMapper. - * - * @param json Raw JSON InputStream - * @param objectMapper Jackson ObjectMapper - * @return CallSummary object represented by the provided JSON - */ - public static CallSummary fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { - // Convert all checked exceptions to Runtime - try { - return objectMapper.readValue(json, CallSummary.class); - } catch (final JsonMappingException | JsonParseException e) { - throw new ApiException(e.getMessage(), e); - } catch (final IOException e) { - throw new ApiConnectionException(e.getMessage(), e); - } - } - - private final String accountSid; - private final String callSid; - private final CallSummary.CallType callType; - private final CallSummary.CallState callState; - private final CallSummary.AnsweredBy answeredBy; - private final CallSummary.ProcessingState processingState; - private final ZonedDateTime createdTime; - private final ZonedDateTime startTime; - private final ZonedDateTime endTime; - private final Integer duration; - private final Integer connectDuration; - private final Map from; - private final Map to; - private final Map carrierEdge; - private final Map clientEdge; - private final Map sdkEdge; - private final Map sipEdge; - private final List tags; - private final URI url; - private final Map attributes; - private final Map properties; - private final Map trust; - private final Map annotation; - - @JsonCreator - private CallSummary( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("call_sid") final String callSid, - @JsonProperty("call_type") final CallSummary.CallType callType, - @JsonProperty("call_state") final CallSummary.CallState callState, - @JsonProperty("answered_by") final CallSummary.AnsweredBy answeredBy, - @JsonProperty( - "processing_state" - ) final CallSummary.ProcessingState processingState, - @JsonProperty("created_time") final String createdTime, - @JsonProperty("start_time") final String startTime, - @JsonProperty("end_time") final String endTime, - @JsonProperty("duration") final Integer duration, - @JsonProperty("connect_duration") final Integer connectDuration, - @JsonProperty("from") final Map from, - @JsonProperty("to") final Map to, - @JsonProperty("carrier_edge") final Map carrierEdge, - @JsonProperty("client_edge") final Map clientEdge, - @JsonProperty("sdk_edge") final Map sdkEdge, - @JsonProperty("sip_edge") final Map sipEdge, - @JsonProperty("tags") final List tags, - @JsonProperty("url") final URI url, - @JsonProperty("attributes") final Map attributes, - @JsonProperty("properties") final Map properties, - @JsonProperty("trust") final Map trust, - @JsonProperty("annotation") final Map annotation - ) { - this.accountSid = accountSid; - this.callSid = callSid; - this.callType = callType; - this.callState = callState; - this.answeredBy = answeredBy; - this.processingState = processingState; - this.createdTime = DateConverter.iso8601DateTimeFromString(createdTime); - this.startTime = DateConverter.iso8601DateTimeFromString(startTime); - this.endTime = DateConverter.iso8601DateTimeFromString(endTime); - this.duration = duration; - this.connectDuration = connectDuration; - this.from = from; - this.to = to; - this.carrierEdge = carrierEdge; - this.clientEdge = clientEdge; - this.sdkEdge = sdkEdge; - this.sipEdge = sipEdge; - this.tags = tags; - this.url = url; - this.attributes = attributes; - this.properties = properties; - this.trust = trust; - this.annotation = annotation; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getCallSid() { - return this.callSid; - } - - public final CallSummary.CallType getCallType() { - return this.callType; - } - - public final CallSummary.CallState getCallState() { - return this.callState; - } - - public final CallSummary.AnsweredBy getAnsweredBy() { - return this.answeredBy; - } - - public final CallSummary.ProcessingState getProcessingState() { - return this.processingState; - } - - public final ZonedDateTime getCreatedTime() { - return this.createdTime; - } - - public final ZonedDateTime getStartTime() { - return this.startTime; - } - - public final ZonedDateTime getEndTime() { - return this.endTime; - } - - public final Integer getDuration() { - return this.duration; - } - - public final Integer getConnectDuration() { - return this.connectDuration; - } - - public final Map getFrom() { - return this.from; - } - - public final Map getTo() { - return this.to; - } - - public final Map getCarrierEdge() { - return this.carrierEdge; - } - - public final Map getClientEdge() { - return this.clientEdge; - } - - public final Map getSdkEdge() { - return this.sdkEdge; - } - - public final Map getSipEdge() { - return this.sipEdge; - } - - public final List getTags() { - return this.tags; - } - - public final URI getUrl() { - return this.url; - } - - public final Map getAttributes() { - return this.attributes; - } - - public final Map getProperties() { - return this.properties; - } - - public final Map getTrust() { - return this.trust; - } - - public final Map getAnnotation() { - return this.annotation; - } - - @Override - public boolean equals(final Object o) { - if (this == o) { - return true; - } - - if (o == null || getClass() != o.getClass()) { - return false; - } - - CallSummary other = (CallSummary) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(callSid, other.callSid) && - Objects.equals(callType, other.callType) && - Objects.equals(callState, other.callState) && - Objects.equals(answeredBy, other.answeredBy) && - Objects.equals(processingState, other.processingState) && - Objects.equals(createdTime, other.createdTime) && - Objects.equals(startTime, other.startTime) && - Objects.equals(endTime, other.endTime) && - Objects.equals(duration, other.duration) && - Objects.equals(connectDuration, other.connectDuration) && - Objects.equals(from, other.from) && - Objects.equals(to, other.to) && - Objects.equals(carrierEdge, other.carrierEdge) && - Objects.equals(clientEdge, other.clientEdge) && - Objects.equals(sdkEdge, other.sdkEdge) && - Objects.equals(sipEdge, other.sipEdge) && - Objects.equals(tags, other.tags) && - Objects.equals(url, other.url) && - Objects.equals(attributes, other.attributes) && - Objects.equals(properties, other.properties) && - Objects.equals(trust, other.trust) && - Objects.equals(annotation, other.annotation) + public static CallSummaryFetcher fetcher(final String pathcallSid) { + return new CallSummaryFetcher( + pathcallSid ); } - @Override - public int hashCode() { - return Objects.hash( - accountSid, - callSid, - callType, - callState, - answeredBy, - processingState, - createdTime, - startTime, - endTime, - duration, - connectDuration, - from, - to, - carrierEdge, - clientEdge, - sdkEdge, - sipEdge, - tags, - url, - attributes, - properties, - trust, - annotation - ); - } public enum CallType { CARRIER("carrier"), @@ -419,4 +141,226 @@ public static ProcessingState forValue(final String value) { return Promoter.enumFromString(value, ProcessingState.values()); } } + + + /** + * Converts a JSON String into a CallSummary object using the provided ObjectMapper. + * + * @param json Raw JSON String + * @param objectMapper Jackson ObjectMapper + * @return CallSummary object represented by the provided JSON + */ + public static CallSummary fromJson(final String json, final ObjectMapper objectMapper) { + // Convert all checked exceptions to Runtime + try { + return objectMapper.readValue(json, CallSummary.class); + } catch (final JsonMappingException | JsonParseException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + /** + * Converts a JSON InputStream into a CallSummary object using the provided + * ObjectMapper. + * + * @param json Raw JSON InputStream + * @param objectMapper Jackson ObjectMapper + * @return CallSummary object represented by the provided JSON + */ + public static CallSummary fromJson(final InputStream json, final ObjectMapper objectMapper) { + // Convert all checked exceptions to Runtime + try { + return objectMapper.readValue(json, CallSummary.class); + } catch (final JsonMappingException | JsonParseException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter + private final String accountSid; + @Getter + private final Object annotation; + @Getter + private final CallSummary.AnsweredBy answeredBy; + @Getter + private final Object attributes; + @Getter + private final String callSid; + @Getter + private final CallSummary.CallState callState; + @Getter + private final CallSummary.CallType callType; + @Getter + private final Object carrierEdge; + @Getter + private final Object clientEdge; + @Getter + private final Integer connectDuration; + @Getter + private final ZonedDateTime createdTime; + @Getter + private final Integer duration; + @Getter + private final ZonedDateTime endTime; + @Getter + private final Object from; + @Getter + private final CallSummary.ProcessingState processingState; + @Getter + private final Object properties; + @Getter + private final Object sdkEdge; + @Getter + private final Object sipEdge; + @Getter + private final ZonedDateTime startTime; + @Getter + private final List tags; + @Getter + private final Object to; + @Getter + private final Object trust; + @Getter + private final URI url; + + @JsonCreator + private CallSummary( + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("annotation") final Object annotation, + @JsonProperty("answered_by") final CallSummary.AnsweredBy answeredBy, + @JsonProperty("attributes") final Object attributes, + @JsonProperty("call_sid") final String callSid, + @JsonProperty("call_state") final CallSummary.CallState callState, + @JsonProperty("call_type") final CallSummary.CallType callType, + @JsonProperty("carrier_edge") final Object carrierEdge, + @JsonProperty("client_edge") final Object clientEdge, + @JsonProperty("connect_duration") final Integer connectDuration, + @JsonProperty("created_time") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime createdTime, + @JsonProperty("duration") final Integer duration, + @JsonProperty("end_time") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime endTime, + @JsonProperty("from") final Object from, + @JsonProperty("processing_state") final CallSummary.ProcessingState processingState, + @JsonProperty("properties") final Object properties, + @JsonProperty("sdk_edge") final Object sdkEdge, + @JsonProperty("sip_edge") final Object sipEdge, + @JsonProperty("start_time") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime startTime, + @JsonProperty("tags") final List tags, + @JsonProperty("to") final Object to, + @JsonProperty("trust") final Object trust, + @JsonProperty("url") final URI url + ) { + this.accountSid = accountSid; + this.annotation = annotation; + this.answeredBy = answeredBy; + this.attributes = attributes; + this.callSid = callSid; + this.callState = callState; + this.callType = callType; + this.carrierEdge = carrierEdge; + this.clientEdge = clientEdge; + this.connectDuration = connectDuration; + this.createdTime = createdTime; + this.duration = duration; + this.endTime = endTime; + this.from = from; + this.processingState = processingState; + this.properties = properties; + this.sdkEdge = sdkEdge; + this.sipEdge = sipEdge; + this.startTime = startTime; + this.tags = tags; + this.to = to; + this.trust = trust; + this.url = url; + } + + @Override + public boolean equals(final Object o) { + if (this == o) { + return true; + } + + if (o == null || getClass() != o.getClass()) { + return false; + } + + CallSummary other = (CallSummary) o; + return ( + Objects.equals(accountSid, other.accountSid) && + Objects.equals(annotation, other.annotation) && + Objects.equals(answeredBy, other.answeredBy) && + Objects.equals(attributes, other.attributes) && + Objects.equals(callSid, other.callSid) && + Objects.equals(callState, other.callState) && + Objects.equals(callType, other.callType) && + Objects.equals(carrierEdge, other.carrierEdge) && + Objects.equals(clientEdge, other.clientEdge) && + Objects.equals(connectDuration, other.connectDuration) && + Objects.equals(createdTime, other.createdTime) && + Objects.equals(duration, other.duration) && + Objects.equals(endTime, other.endTime) && + Objects.equals(from, other.from) && + Objects.equals(processingState, other.processingState) && + Objects.equals(properties, other.properties) && + Objects.equals(sdkEdge, other.sdkEdge) && + Objects.equals(sipEdge, other.sipEdge) && + Objects.equals(startTime, other.startTime) && + Objects.equals(tags, other.tags) && + Objects.equals(to, other.to) && + Objects.equals(trust, other.trust) && + Objects.equals(url, other.url) + ); + } + + @Override + public int hashCode() { + return Objects.hash( + accountSid, + annotation, + answeredBy, + attributes, + callSid, + callState, + callType, + carrierEdge, + clientEdge, + connectDuration, + createdTime, + duration, + endTime, + from, + processingState, + properties, + sdkEdge, + sipEdge, + startTime, + tags, + to, + trust, + url + ); + } + + } + diff --git a/src/main/java/com/twilio/rest/insights/v1/call/CallSummaryFetcher.java b/src/main/java/com/twilio/rest/insights/v1/call/CallSummaryFetcher.java index f225256d29..6b1b66249c 100644 --- a/src/main/java/com/twilio/rest/insights/v1/call/CallSummaryFetcher.java +++ b/src/main/java/com/twilio/rest/insights/v1/call/CallSummaryFetcher.java @@ -15,7 +15,8 @@ package com.twilio.rest.insights.v1.call; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,65 +28,59 @@ public class CallSummaryFetcher extends Fetcher { - private String pathCallSid; + private String pathcallSid; private CallSummary.ProcessingState processingState; - public CallSummaryFetcher(final String pathCallSid) { - this.pathCallSid = pathCallSid; + public CallSummaryFetcher(final String pathcallSid) { + this.pathcallSid = pathcallSid; } - public CallSummaryFetcher setProcessingState( - final CallSummary.ProcessingState processingState - ) { + + public CallSummaryFetcher setProcessingState(final CallSummary.ProcessingState processingState) { this.processingState = processingState; return this; } + @Override public CallSummary fetch(final TwilioRestClient client) { + String path = "/v1/Voice/{CallSid}/Summary"; - path = path.replace("{" + "CallSid" + "}", this.pathCallSid.toString()); + path = path.replace("{" + "CallSid" + "}", this.pathcallSid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.INSIGHTS.toString(), - path + HttpMethod.GET, + Domains.INSIGHTS.toString(), + path ); addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "CallSummary fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("CallSummary fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return CallSummary.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return CallSummary.fromJson(response.getStream(), client.getObjectMapper()); } private void addQueryParams(final Request request) { + + if (processingState != null) { - request.addQueryParam( - "ProcessingState", - processingState.toString() - ); + Serializer.toString(request, "ProcessingState", processingState, ParameterType.QUERY); } + + } } diff --git a/src/main/java/com/twilio/rest/insights/v1/call/Event.java b/src/main/java/com/twilio/rest/insights/v1/call/Event.java index 3d5803e58c..a9eaa9c391 100644 --- a/src/main/java/com/twilio/rest/insights/v1/call/Event.java +++ b/src/main/java/com/twilio/rest/insights/v1/call/Event.java @@ -18,41 +18,87 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; -import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Event extends Resource { - private static final long serialVersionUID = 246803433322501L; - public static EventReader reader(final String pathCallSid) { - return new EventReader(pathCallSid); + public static EventReader reader(final String pathcallSid) { + return new EventReader( + pathcallSid + ); } + + public enum TwilioEdge { + UNKNOWN_EDGE("unknown_edge"), + CARRIER_EDGE("carrier_edge"), + SIP_EDGE("sip_edge"), + SDK_EDGE("sdk_edge"), + CLIENT_EDGE("client_edge"); + + private final String value; + + private TwilioEdge(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static TwilioEdge forValue(final String value) { + return Promoter.enumFromString(value, TwilioEdge.values()); + } + } + + public enum Level { + UNKNOWN("UNKNOWN"), + DEBUG("DEBUG"), + INFO("INFO"), + WARNING("WARNING"), + ERROR("ERROR"); + + private final String value; + + private Level(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static Level forValue(final String value) { + return Promoter.enumFromString(value, Level.values()); + } + } + + /** * Converts a JSON String into a Event object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Event object represented by the provided JSON */ - public static Event fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Event fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Event.class); @@ -67,14 +113,11 @@ public static Event fromJson( * Converts a JSON InputStream into a Event object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Event object represented by the provided JSON */ - public static Event fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Event fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Event.class); @@ -85,87 +128,67 @@ public static Event fromJson( } } - private final String timestamp; - private final String callSid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; + @Getter + private final String callSid; + @Getter + private final Object carrierEdge; + @Getter + private final Object clientEdge; + @Getter private final Event.TwilioEdge edge; + @Getter private final String group; + @Getter private final Event.Level level; + @Getter private final String name; - private final Map carrierEdge; - private final Map sipEdge; - private final Map sdkEdge; - private final Map clientEdge; + @Getter + private final Object sdkEdge; + @Getter + private final Object sipEdge; + @Getter + private final String timestamp; @JsonCreator private Event( - @JsonProperty("timestamp") final String timestamp, - @JsonProperty("call_sid") final String callSid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("edge") final Event.TwilioEdge edge, - @JsonProperty("group") final String group, - @JsonProperty("level") final Event.Level level, - @JsonProperty("name") final String name, - @JsonProperty("carrier_edge") final Map carrierEdge, - @JsonProperty("sip_edge") final Map sipEdge, - @JsonProperty("sdk_edge") final Map sdkEdge, - @JsonProperty("client_edge") final Map clientEdge + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("call_sid") final String callSid, + @JsonProperty("carrier_edge") final Object carrierEdge, + @JsonProperty("client_edge") final Object clientEdge, + @JsonProperty("edge") final Event.TwilioEdge edge, + @JsonProperty("group") final String group, + @JsonProperty("level") final Event.Level level, + @JsonProperty("name") final String name, + @JsonProperty("sdk_edge") final Object sdkEdge, + @JsonProperty("sip_edge") final Object sipEdge, + @JsonProperty("timestamp") final String timestamp ) { - this.timestamp = timestamp; - this.callSid = callSid; this.accountSid = accountSid; + this.callSid = callSid; + this.carrierEdge = carrierEdge; + this.clientEdge = clientEdge; this.edge = edge; this.group = group; this.level = level; this.name = name; - this.carrierEdge = carrierEdge; - this.sipEdge = sipEdge; this.sdkEdge = sdkEdge; - this.clientEdge = clientEdge; - } - - public final String getTimestamp() { - return this.timestamp; - } - - public final String getCallSid() { - return this.callSid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final Event.TwilioEdge getEdge() { - return this.edge; - } - - public final String getGroup() { - return this.group; - } - - public final Event.Level getLevel() { - return this.level; - } - - public final String getName() { - return this.name; - } - - public final Map getCarrierEdge() { - return this.carrierEdge; - } - - public final Map getSipEdge() { - return this.sipEdge; - } - - public final Map getSdkEdge() { - return this.sdkEdge; - } - - public final Map getClientEdge() { - return this.clientEdge; + this.sipEdge = sipEdge; + this.timestamp = timestamp; } @Override @@ -179,82 +202,38 @@ public boolean equals(final Object o) { } Event other = (Event) o; - return ( - Objects.equals(timestamp, other.timestamp) && - Objects.equals(callSid, other.callSid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(edge, other.edge) && - Objects.equals(group, other.group) && - Objects.equals(level, other.level) && - Objects.equals(name, other.name) && - Objects.equals(carrierEdge, other.carrierEdge) && - Objects.equals(sipEdge, other.sipEdge) && - Objects.equals(sdkEdge, other.sdkEdge) && - Objects.equals(clientEdge, other.clientEdge) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(callSid, other.callSid) && + Objects.equals(carrierEdge, other.carrierEdge) && + Objects.equals(clientEdge, other.clientEdge) && + Objects.equals(edge, other.edge) && + Objects.equals(group, other.group) && + Objects.equals(level, other.level) && + Objects.equals(name, other.name) && + Objects.equals(sdkEdge, other.sdkEdge) && + Objects.equals(sipEdge, other.sipEdge) && + Objects.equals(timestamp, other.timestamp) ); } @Override public int hashCode() { return Objects.hash( - timestamp, - callSid, - accountSid, - edge, - group, - level, - name, - carrierEdge, - sipEdge, - sdkEdge, - clientEdge + accountSid, + callSid, + carrierEdge, + clientEdge, + edge, + group, + level, + name, + sdkEdge, + sipEdge, + timestamp ); } - public enum Level { - UNKNOWN("UNKNOWN"), - DEBUG("DEBUG"), - INFO("INFO"), - WARNING("WARNING"), - ERROR("ERROR"); - - private final String value; - private Level(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static Level forValue(final String value) { - return Promoter.enumFromString(value, Level.values()); - } - } - - public enum TwilioEdge { - UNKNOWN_EDGE("unknown_edge"), - CARRIER_EDGE("carrier_edge"), - SIP_EDGE("sip_edge"), - SDK_EDGE("sdk_edge"), - CLIENT_EDGE("client_edge"); - - private final String value; - - private TwilioEdge(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static TwilioEdge forValue(final String value) { - return Promoter.enumFromString(value, TwilioEdge.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/insights/v1/call/EventReader.java b/src/main/java/com/twilio/rest/insights/v1/call/EventReader.java index 92e4b6b719..cdcc83a2cb 100644 --- a/src/main/java/com/twilio/rest/insights/v1/call/EventReader.java +++ b/src/main/java/com/twilio/rest/insights/v1/call/EventReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,120 +30,100 @@ public class EventReader extends Reader { - private String pathCallSid; + private String pathcallSid; private Event.TwilioEdge edge; private Long pageSize; - public EventReader(final String pathCallSid) { - this.pathCallSid = pathCallSid; + public EventReader(final String pathcallSid) { + this.pathcallSid = pathcallSid; } + public EventReader setEdge(final Event.TwilioEdge edge) { this.edge = edge; return this; } + public EventReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/Voice/{CallSid}/Events"; - path = path.replace("{" + "CallSid" + "}", this.pathCallSid.toString()); + + path = path.replace("{" + "CallSid" + "}", this.pathcallSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.INSIGHTS.toString(), - path + HttpMethod.GET, + Domains.INSIGHTS.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Event read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Event read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "events", - response.getContent(), - Event.class, - client.getObjectMapper() - ); + "events", + response.getContent(), + Event.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.INSIGHTS.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.INSIGHTS.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (edge != null) { - request.addQueryParam("Edge", edge.toString()); + Serializer.toString(request, "Edge", edge, ParameterType.QUERY); } + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/insights/v1/call/Metric.java b/src/main/java/com/twilio/rest/insights/v1/call/Metric.java index c5bc8315e8..040f9440d6 100644 --- a/src/main/java/com/twilio/rest/insights/v1/call/Metric.java +++ b/src/main/java/com/twilio/rest/insights/v1/call/Metric.java @@ -18,41 +18,86 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; -import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Metric extends Resource { - private static final long serialVersionUID = 250651350148240L; - public static MetricReader reader(final String pathCallSid) { - return new MetricReader(pathCallSid); + public static MetricReader reader(final String pathcallSid) { + return new MetricReader( + pathcallSid + ); + } + + + public enum TwilioEdge { + UNKNOWN_EDGE("unknown_edge"), + CARRIER_EDGE("carrier_edge"), + SIP_EDGE("sip_edge"), + SDK_EDGE("sdk_edge"), + CLIENT_EDGE("client_edge"); + + private final String value; + + private TwilioEdge(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static TwilioEdge forValue(final String value) { + return Promoter.enumFromString(value, TwilioEdge.values()); + } + } + + public enum StreamDirection { + UNKNOWN("unknown"), + INBOUND("inbound"), + OUTBOUND("outbound"), + BOTH("both"); + + private final String value; + + private StreamDirection(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static StreamDirection forValue(final String value) { + return Promoter.enumFromString(value, StreamDirection.values()); + } } + /** * Converts a JSON String into a Metric object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Metric object represented by the provided JSON */ - public static Metric fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Metric fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Metric.class); @@ -67,14 +112,11 @@ public static Metric fromJson( * Converts a JSON InputStream into a Metric object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Metric object represented by the provided JSON */ - public static Metric fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Metric fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Metric.class); @@ -85,73 +127,59 @@ public static Metric fromJson( } } - private final String timestamp; - private final String callSid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final Metric.TwilioEdge edge; + @Getter + private final String callSid; + @Getter + private final Object carrierEdge; + @Getter + private final Object clientEdge; + @Getter private final Metric.StreamDirection direction; - private final Map carrierEdge; - private final Map sipEdge; - private final Map sdkEdge; - private final Map clientEdge; + @Getter + private final Metric.TwilioEdge edge; + @Getter + private final Object sdkEdge; + @Getter + private final Object sipEdge; + @Getter + private final String timestamp; @JsonCreator private Metric( - @JsonProperty("timestamp") final String timestamp, - @JsonProperty("call_sid") final String callSid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("edge") final Metric.TwilioEdge edge, - @JsonProperty("direction") final Metric.StreamDirection direction, - @JsonProperty("carrier_edge") final Map carrierEdge, - @JsonProperty("sip_edge") final Map sipEdge, - @JsonProperty("sdk_edge") final Map sdkEdge, - @JsonProperty("client_edge") final Map clientEdge + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("call_sid") final String callSid, + @JsonProperty("carrier_edge") final Object carrierEdge, + @JsonProperty("client_edge") final Object clientEdge, + @JsonProperty("direction") final Metric.StreamDirection direction, + @JsonProperty("edge") final Metric.TwilioEdge edge, + @JsonProperty("sdk_edge") final Object sdkEdge, + @JsonProperty("sip_edge") final Object sipEdge, + @JsonProperty("timestamp") final String timestamp ) { - this.timestamp = timestamp; - this.callSid = callSid; this.accountSid = accountSid; - this.edge = edge; - this.direction = direction; + this.callSid = callSid; this.carrierEdge = carrierEdge; - this.sipEdge = sipEdge; - this.sdkEdge = sdkEdge; this.clientEdge = clientEdge; - } - - public final String getTimestamp() { - return this.timestamp; - } - - public final String getCallSid() { - return this.callSid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final Metric.TwilioEdge getEdge() { - return this.edge; - } - - public final Metric.StreamDirection getDirection() { - return this.direction; - } - - public final Map getCarrierEdge() { - return this.carrierEdge; - } - - public final Map getSipEdge() { - return this.sipEdge; - } - - public final Map getSdkEdge() { - return this.sdkEdge; - } - - public final Map getClientEdge() { - return this.clientEdge; + this.direction = direction; + this.edge = edge; + this.sdkEdge = sdkEdge; + this.sipEdge = sipEdge; + this.timestamp = timestamp; } @Override @@ -165,77 +193,34 @@ public boolean equals(final Object o) { } Metric other = (Metric) o; - return ( - Objects.equals(timestamp, other.timestamp) && - Objects.equals(callSid, other.callSid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(edge, other.edge) && - Objects.equals(direction, other.direction) && - Objects.equals(carrierEdge, other.carrierEdge) && - Objects.equals(sipEdge, other.sipEdge) && - Objects.equals(sdkEdge, other.sdkEdge) && - Objects.equals(clientEdge, other.clientEdge) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(callSid, other.callSid) && + Objects.equals(carrierEdge, other.carrierEdge) && + Objects.equals(clientEdge, other.clientEdge) && + Objects.equals(direction, other.direction) && + Objects.equals(edge, other.edge) && + Objects.equals(sdkEdge, other.sdkEdge) && + Objects.equals(sipEdge, other.sipEdge) && + Objects.equals(timestamp, other.timestamp) ); } @Override public int hashCode() { return Objects.hash( - timestamp, - callSid, - accountSid, - edge, - direction, - carrierEdge, - sipEdge, - sdkEdge, - clientEdge + accountSid, + callSid, + carrierEdge, + clientEdge, + direction, + edge, + sdkEdge, + sipEdge, + timestamp ); } - public enum StreamDirection { - UNKNOWN("unknown"), - INBOUND("inbound"), - OUTBOUND("outbound"), - BOTH("both"); - - private final String value; - - private StreamDirection(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static StreamDirection forValue(final String value) { - return Promoter.enumFromString(value, StreamDirection.values()); - } - } - - public enum TwilioEdge { - UNKNOWN_EDGE("unknown_edge"), - CARRIER_EDGE("carrier_edge"), - SIP_EDGE("sip_edge"), - SDK_EDGE("sdk_edge"), - CLIENT_EDGE("client_edge"); - - private final String value; - - private TwilioEdge(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - @JsonCreator - public static TwilioEdge forValue(final String value) { - return Promoter.enumFromString(value, TwilioEdge.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/insights/v1/call/MetricReader.java b/src/main/java/com/twilio/rest/insights/v1/call/MetricReader.java index dce5e091d7..1e92870085 100644 --- a/src/main/java/com/twilio/rest/insights/v1/call/MetricReader.java +++ b/src/main/java/com/twilio/rest/insights/v1/call/MetricReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,129 +30,112 @@ public class MetricReader extends Reader { - private String pathCallSid; + private String pathcallSid; private Metric.TwilioEdge edge; private Metric.StreamDirection direction; private Long pageSize; - public MetricReader(final String pathCallSid) { - this.pathCallSid = pathCallSid; + public MetricReader(final String pathcallSid) { + this.pathcallSid = pathcallSid; } + public MetricReader setEdge(final Metric.TwilioEdge edge) { this.edge = edge; return this; } + public MetricReader setDirection(final Metric.StreamDirection direction) { this.direction = direction; return this; } + public MetricReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/Voice/{CallSid}/Metrics"; - path = path.replace("{" + "CallSid" + "}", this.pathCallSid.toString()); + + path = path.replace("{" + "CallSid" + "}", this.pathcallSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.INSIGHTS.toString(), - path + HttpMethod.GET, + Domains.INSIGHTS.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Metric read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Metric read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "metrics", - response.getContent(), - Metric.class, - client.getObjectMapper() - ); + "metrics", + response.getContent(), + Metric.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.INSIGHTS.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.INSIGHTS.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (edge != null) { - request.addQueryParam("Edge", edge.toString()); + Serializer.toString(request, "Edge", edge, ParameterType.QUERY); } + + if (direction != null) { - request.addQueryParam("Direction", direction.toString()); + Serializer.toString(request, "Direction", direction, ParameterType.QUERY); } + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/insights/v1/conference/ConferenceParticipant.java b/src/main/java/com/twilio/rest/insights/v1/conference/ConferenceParticipant.java index d62a3c56fd..d619899d71 100644 --- a/src/main/java/com/twilio/rest/insights/v1/conference/ConferenceParticipant.java +++ b/src/main/java/com/twilio/rest/insights/v1/conference/ConferenceParticipant.java @@ -18,378 +18,129 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.List; -import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class ConferenceParticipant extends Resource { - private static final long serialVersionUID = 67216866718855L; - public static ConferenceParticipantFetcher fetcher( - final String pathConferenceSid, - final String pathParticipantSid - ) { + public static ConferenceParticipantFetcher fetcher(final String pathconferenceSid, final String pathparticipantSid) { return new ConferenceParticipantFetcher( - pathConferenceSid, - pathParticipantSid + pathconferenceSid, pathparticipantSid ); } - public static ConferenceParticipantReader reader( - final String pathConferenceSid - ) { - return new ConferenceParticipantReader(pathConferenceSid); - } - - /** - * Converts a JSON String into a ConferenceParticipant object using the provided ObjectMapper. - * - * @param json Raw JSON String - * @param objectMapper Jackson ObjectMapper - * @return ConferenceParticipant object represented by the provided JSON - */ - public static ConferenceParticipant fromJson( - final String json, - final ObjectMapper objectMapper - ) { - // Convert all checked exceptions to Runtime - try { - return objectMapper.readValue(json, ConferenceParticipant.class); - } catch (final JsonMappingException | JsonParseException e) { - throw new ApiException(e.getMessage(), e); - } catch (final IOException e) { - throw new ApiConnectionException(e.getMessage(), e); - } - } - - /** - * Converts a JSON InputStream into a ConferenceParticipant object using the provided - * ObjectMapper. - * - * @param json Raw JSON InputStream - * @param objectMapper Jackson ObjectMapper - * @return ConferenceParticipant object represented by the provided JSON - */ - public static ConferenceParticipant fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { - // Convert all checked exceptions to Runtime - try { - return objectMapper.readValue(json, ConferenceParticipant.class); - } catch (final JsonMappingException | JsonParseException e) { - throw new ApiException(e.getMessage(), e); - } catch (final IOException e) { - throw new ApiConnectionException(e.getMessage(), e); - } - } - - private final String participantSid; - private final String label; - private final String conferenceSid; - private final String callSid; - private final String accountSid; - private final ConferenceParticipant.CallDirection callDirection; - private final String from; - private final String to; - private final ConferenceParticipant.CallStatus callStatus; - private final String countryCode; - private final Boolean isModerator; - private final ZonedDateTime joinTime; - private final ZonedDateTime leaveTime; - private final Integer durationSeconds; - private final Integer outboundQueueLength; - private final Integer outboundTimeInQueue; - private final ConferenceParticipant.JitterBufferSize jitterBufferSize; - private final Boolean isCoach; - private final List coachedParticipants; - private final ConferenceParticipant.Region participantRegion; - private final ConferenceParticipant.Region conferenceRegion; - private final ConferenceParticipant.CallType callType; - private final ConferenceParticipant.ProcessingState processingState; - private final Map properties; - private final Map events; - private final Map metrics; - private final URI url; - - @JsonCreator - private ConferenceParticipant( - @JsonProperty("participant_sid") final String participantSid, - @JsonProperty("label") final String label, - @JsonProperty("conference_sid") final String conferenceSid, - @JsonProperty("call_sid") final String callSid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty( - "call_direction" - ) final ConferenceParticipant.CallDirection callDirection, - @JsonProperty("from") final String from, - @JsonProperty("to") final String to, - @JsonProperty( - "call_status" - ) final ConferenceParticipant.CallStatus callStatus, - @JsonProperty("country_code") final String countryCode, - @JsonProperty("is_moderator") final Boolean isModerator, - @JsonProperty("join_time") final String joinTime, - @JsonProperty("leave_time") final String leaveTime, - @JsonProperty("duration_seconds") final Integer durationSeconds, - @JsonProperty( - "outbound_queue_length" - ) final Integer outboundQueueLength, - @JsonProperty( - "outbound_time_in_queue" - ) final Integer outboundTimeInQueue, - @JsonProperty( - "jitter_buffer_size" - ) final ConferenceParticipant.JitterBufferSize jitterBufferSize, - @JsonProperty("is_coach") final Boolean isCoach, - @JsonProperty("coached_participants") final List< - String - > coachedParticipants, - @JsonProperty( - "participant_region" - ) final ConferenceParticipant.Region participantRegion, - @JsonProperty( - "conference_region" - ) final ConferenceParticipant.Region conferenceRegion, - @JsonProperty( - "call_type" - ) final ConferenceParticipant.CallType callType, - @JsonProperty( - "processing_state" - ) final ConferenceParticipant.ProcessingState processingState, - @JsonProperty("properties") final Map properties, - @JsonProperty("events") final Map events, - @JsonProperty("metrics") final Map metrics, - @JsonProperty("url") final URI url - ) { - this.participantSid = participantSid; - this.label = label; - this.conferenceSid = conferenceSid; - this.callSid = callSid; - this.accountSid = accountSid; - this.callDirection = callDirection; - this.from = from; - this.to = to; - this.callStatus = callStatus; - this.countryCode = countryCode; - this.isModerator = isModerator; - this.joinTime = DateConverter.iso8601DateTimeFromString(joinTime); - this.leaveTime = DateConverter.iso8601DateTimeFromString(leaveTime); - this.durationSeconds = durationSeconds; - this.outboundQueueLength = outboundQueueLength; - this.outboundTimeInQueue = outboundTimeInQueue; - this.jitterBufferSize = jitterBufferSize; - this.isCoach = isCoach; - this.coachedParticipants = coachedParticipants; - this.participantRegion = participantRegion; - this.conferenceRegion = conferenceRegion; - this.callType = callType; - this.processingState = processingState; - this.properties = properties; - this.events = events; - this.metrics = metrics; - this.url = url; - } - - public final String getParticipantSid() { - return this.participantSid; - } - - public final String getLabel() { - return this.label; - } - - public final String getConferenceSid() { - return this.conferenceSid; - } - - public final String getCallSid() { - return this.callSid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final ConferenceParticipant.CallDirection getCallDirection() { - return this.callDirection; - } - - public final String getFrom() { - return this.from; - } - - public final String getTo() { - return this.to; - } - public final ConferenceParticipant.CallStatus getCallStatus() { - return this.callStatus; + public static ConferenceParticipantReader reader(final String pathconferenceSid) { + return new ConferenceParticipantReader( + pathconferenceSid + ); } - public final String getCountryCode() { - return this.countryCode; - } - public final Boolean getIsModerator() { - return this.isModerator; - } + public enum CallDirection { + INBOUND("inbound"), + OUTBOUND("outbound"); - public final ZonedDateTime getJoinTime() { - return this.joinTime; - } + private final String value; - public final ZonedDateTime getLeaveTime() { - return this.leaveTime; - } + private CallDirection(final String value) { + this.value = value; + } - public final Integer getDurationSeconds() { - return this.durationSeconds; - } + public String toString() { + return value; + } - public final Integer getOutboundQueueLength() { - return this.outboundQueueLength; + @JsonCreator + public static CallDirection forValue(final String value) { + return Promoter.enumFromString(value, CallDirection.values()); + } } - public final Integer getOutboundTimeInQueue() { - return this.outboundTimeInQueue; - } + public enum JitterBufferSize { + LARGE("large"), + SMALL("small"), + MEDIUM("medium"), + OFF("off"); - public final ConferenceParticipant.JitterBufferSize getJitterBufferSize() { - return this.jitterBufferSize; - } + private final String value; - public final Boolean getIsCoach() { - return this.isCoach; - } + private JitterBufferSize(final String value) { + this.value = value; + } - public final List getCoachedParticipants() { - return this.coachedParticipants; - } + public String toString() { + return value; + } - public final ConferenceParticipant.Region getParticipantRegion() { - return this.participantRegion; + @JsonCreator + public static JitterBufferSize forValue(final String value) { + return Promoter.enumFromString(value, JitterBufferSize.values()); + } } - public final ConferenceParticipant.Region getConferenceRegion() { - return this.conferenceRegion; - } + public enum CallType { + CARRIER("carrier"), + CLIENT("client"), + SIP("sip"); - public final ConferenceParticipant.CallType getCallType() { - return this.callType; - } + private final String value; - public final ConferenceParticipant.ProcessingState getProcessingState() { - return this.processingState; - } + private CallType(final String value) { + this.value = value; + } - public final Map getProperties() { - return this.properties; - } + public String toString() { + return value; + } - public final Map getEvents() { - return this.events; + @JsonCreator + public static CallType forValue(final String value) { + return Promoter.enumFromString(value, CallType.values()); + } } - public final Map getMetrics() { - return this.metrics; - } + public enum CallStatus { + ANSWERED("answered"), + COMPLETED("completed"), + BUSY("busy"), + FAIL("fail"), + NOANSWER("noanswer"), + RINGING("ringing"), + CANCELED("canceled"); - public final URI getUrl() { - return this.url; - } + private final String value; - @Override - public boolean equals(final Object o) { - if (this == o) { - return true; + private CallStatus(final String value) { + this.value = value; } - if (o == null || getClass() != o.getClass()) { - return false; + public String toString() { + return value; } - ConferenceParticipant other = (ConferenceParticipant) o; - - return ( - Objects.equals(participantSid, other.participantSid) && - Objects.equals(label, other.label) && - Objects.equals(conferenceSid, other.conferenceSid) && - Objects.equals(callSid, other.callSid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(callDirection, other.callDirection) && - Objects.equals(from, other.from) && - Objects.equals(to, other.to) && - Objects.equals(callStatus, other.callStatus) && - Objects.equals(countryCode, other.countryCode) && - Objects.equals(isModerator, other.isModerator) && - Objects.equals(joinTime, other.joinTime) && - Objects.equals(leaveTime, other.leaveTime) && - Objects.equals(durationSeconds, other.durationSeconds) && - Objects.equals(outboundQueueLength, other.outboundQueueLength) && - Objects.equals(outboundTimeInQueue, other.outboundTimeInQueue) && - Objects.equals(jitterBufferSize, other.jitterBufferSize) && - Objects.equals(isCoach, other.isCoach) && - Objects.equals(coachedParticipants, other.coachedParticipants) && - Objects.equals(participantRegion, other.participantRegion) && - Objects.equals(conferenceRegion, other.conferenceRegion) && - Objects.equals(callType, other.callType) && - Objects.equals(processingState, other.processingState) && - Objects.equals(properties, other.properties) && - Objects.equals(events, other.events) && - Objects.equals(metrics, other.metrics) && - Objects.equals(url, other.url) - ); - } - - @Override - public int hashCode() { - return Objects.hash( - participantSid, - label, - conferenceSid, - callSid, - accountSid, - callDirection, - from, - to, - callStatus, - countryCode, - isModerator, - joinTime, - leaveTime, - durationSeconds, - outboundQueueLength, - outboundTimeInQueue, - jitterBufferSize, - isCoach, - coachedParticipants, - participantRegion, - conferenceRegion, - callType, - processingState, - properties, - events, - metrics, - url - ); + @JsonCreator + public static CallStatus forValue(final String value) { + return Promoter.enumFromString(value, CallStatus.values()); + } } public enum Region { @@ -419,26 +170,6 @@ public static Region forValue(final String value) { } } - public enum CallDirection { - INBOUND("inbound"), - OUTBOUND("outbound"); - - private final String value; - - private CallDirection(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static CallDirection forValue(final String value) { - return Promoter.enumFromString(value, CallDirection.values()); - } - } - public enum ProcessingState { COMPLETE("complete"), IN_PROGRESS("in_progress"), @@ -460,71 +191,248 @@ public static ProcessingState forValue(final String value) { } } - public enum JitterBufferSize { - LARGE("large"), - SMALL("small"), - MEDIUM("medium"), - OFF("off"); - - private final String value; - private JitterBufferSize(final String value) { - this.value = value; + /** + * Converts a JSON String into a ConferenceParticipant object using the provided ObjectMapper. + * + * @param json Raw JSON String + * @param objectMapper Jackson ObjectMapper + * @return ConferenceParticipant object represented by the provided JSON + */ + public static ConferenceParticipant fromJson(final String json, final ObjectMapper objectMapper) { + // Convert all checked exceptions to Runtime + try { + return objectMapper.readValue(json, ConferenceParticipant.class); + } catch (final JsonMappingException | JsonParseException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); } + } - public String toString() { - return value; + /** + * Converts a JSON InputStream into a ConferenceParticipant object using the provided + * ObjectMapper. + * + * @param json Raw JSON InputStream + * @param objectMapper Jackson ObjectMapper + * @return ConferenceParticipant object represented by the provided JSON + */ + public static ConferenceParticipant fromJson(final InputStream json, final ObjectMapper objectMapper) { + // Convert all checked exceptions to Runtime + try { + return objectMapper.readValue(json, ConferenceParticipant.class); + } catch (final JsonMappingException | JsonParseException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); } + } - @JsonCreator - public static JitterBufferSize forValue(final String value) { - return Promoter.enumFromString(value, JitterBufferSize.values()); + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); } } - public enum CallStatus { - ANSWERED("answered"), - COMPLETED("completed"), - BUSY("busy"), - FAIL("fail"), - NOANSWER("noanswer"), - RINGING("ringing"), - CANCELED("canceled"); - private final String value; + @Getter + private final String accountSid; + @Getter + private final ConferenceParticipant.CallDirection callDirection; + @Getter + private final String callSid; + @Getter + private final ConferenceParticipant.CallStatus callStatus; + @Getter + private final ConferenceParticipant.CallType callType; + @Getter + private final List coachedParticipants; + @Getter + private final ConferenceParticipant.Region conferenceRegion; + @Getter + private final String conferenceSid; + @Getter + private final String countryCode; + @Getter + private final Integer durationSeconds; + @Getter + private final Object events; + @Getter + private final String from; + @Getter + private final Boolean isCoach; + @Getter + private final Boolean isModerator; + @Getter + private final ConferenceParticipant.JitterBufferSize jitterBufferSize; + @Getter + private final ZonedDateTime joinTime; + @Getter + private final String label; + @Getter + private final ZonedDateTime leaveTime; + @Getter + private final Object metrics; + @Getter + private final Integer outboundQueueLength; + @Getter + private final Integer outboundTimeInQueue; + @Getter + private final ConferenceParticipant.Region participantRegion; + @Getter + private final String participantSid; + @Getter + private final ConferenceParticipant.ProcessingState processingState; + @Getter + private final Object properties; + @Getter + private final String to; + @Getter + private final URI url; - private CallStatus(final String value) { - this.value = value; - } + @JsonCreator + private ConferenceParticipant( + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("call_direction") final ConferenceParticipant.CallDirection callDirection, + @JsonProperty("call_sid") final String callSid, + @JsonProperty("call_status") final ConferenceParticipant.CallStatus callStatus, + @JsonProperty("call_type") final ConferenceParticipant.CallType callType, + @JsonProperty("coached_participants") final List coachedParticipants, + @JsonProperty("conference_region") final ConferenceParticipant.Region conferenceRegion, + @JsonProperty("conference_sid") final String conferenceSid, + @JsonProperty("country_code") final String countryCode, + @JsonProperty("duration_seconds") final Integer durationSeconds, + @JsonProperty("events") final Object events, + @JsonProperty("from") final String from, + @JsonProperty("is_coach") final Boolean isCoach, + @JsonProperty("is_moderator") final Boolean isModerator, + @JsonProperty("jitter_buffer_size") final ConferenceParticipant.JitterBufferSize jitterBufferSize, + @JsonProperty("join_time") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime joinTime, + @JsonProperty("label") final String label, + @JsonProperty("leave_time") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime leaveTime, + @JsonProperty("metrics") final Object metrics, + @JsonProperty("outbound_queue_length") final Integer outboundQueueLength, + @JsonProperty("outbound_time_in_queue") final Integer outboundTimeInQueue, + @JsonProperty("participant_region") final ConferenceParticipant.Region participantRegion, + @JsonProperty("participant_sid") final String participantSid, + @JsonProperty("processing_state") final ConferenceParticipant.ProcessingState processingState, + @JsonProperty("properties") final Object properties, + @JsonProperty("to") final String to, + @JsonProperty("url") final URI url + ) { + this.accountSid = accountSid; + this.callDirection = callDirection; + this.callSid = callSid; + this.callStatus = callStatus; + this.callType = callType; + this.coachedParticipants = coachedParticipants; + this.conferenceRegion = conferenceRegion; + this.conferenceSid = conferenceSid; + this.countryCode = countryCode; + this.durationSeconds = durationSeconds; + this.events = events; + this.from = from; + this.isCoach = isCoach; + this.isModerator = isModerator; + this.jitterBufferSize = jitterBufferSize; + this.joinTime = joinTime; + this.label = label; + this.leaveTime = leaveTime; + this.metrics = metrics; + this.outboundQueueLength = outboundQueueLength; + this.outboundTimeInQueue = outboundTimeInQueue; + this.participantRegion = participantRegion; + this.participantSid = participantSid; + this.processingState = processingState; + this.properties = properties; + this.to = to; + this.url = url; + } - public String toString() { - return value; + @Override + public boolean equals(final Object o) { + if (this == o) { + return true; } - @JsonCreator - public static CallStatus forValue(final String value) { - return Promoter.enumFromString(value, CallStatus.values()); + if (o == null || getClass() != o.getClass()) { + return false; } - } - public enum CallType { - CARRIER("carrier"), - CLIENT("client"), - SIP("sip"); - - private final String value; + ConferenceParticipant other = (ConferenceParticipant) o; + return ( + Objects.equals(accountSid, other.accountSid) && + Objects.equals(callDirection, other.callDirection) && + Objects.equals(callSid, other.callSid) && + Objects.equals(callStatus, other.callStatus) && + Objects.equals(callType, other.callType) && + Objects.equals(coachedParticipants, other.coachedParticipants) && + Objects.equals(conferenceRegion, other.conferenceRegion) && + Objects.equals(conferenceSid, other.conferenceSid) && + Objects.equals(countryCode, other.countryCode) && + Objects.equals(durationSeconds, other.durationSeconds) && + Objects.equals(events, other.events) && + Objects.equals(from, other.from) && + Objects.equals(isCoach, other.isCoach) && + Objects.equals(isModerator, other.isModerator) && + Objects.equals(jitterBufferSize, other.jitterBufferSize) && + Objects.equals(joinTime, other.joinTime) && + Objects.equals(label, other.label) && + Objects.equals(leaveTime, other.leaveTime) && + Objects.equals(metrics, other.metrics) && + Objects.equals(outboundQueueLength, other.outboundQueueLength) && + Objects.equals(outboundTimeInQueue, other.outboundTimeInQueue) && + Objects.equals(participantRegion, other.participantRegion) && + Objects.equals(participantSid, other.participantSid) && + Objects.equals(processingState, other.processingState) && + Objects.equals(properties, other.properties) && + Objects.equals(to, other.to) && + Objects.equals(url, other.url) + ); + } - private CallType(final String value) { - this.value = value; - } + @Override + public int hashCode() { + return Objects.hash( + accountSid, + callDirection, + callSid, + callStatus, + callType, + coachedParticipants, + conferenceRegion, + conferenceSid, + countryCode, + durationSeconds, + events, + from, + isCoach, + isModerator, + jitterBufferSize, + joinTime, + label, + leaveTime, + metrics, + outboundQueueLength, + outboundTimeInQueue, + participantRegion, + participantSid, + processingState, + properties, + to, + url + ); + } - public String toString() { - return value; - } - @JsonCreator - public static CallType forValue(final String value) { - return Promoter.enumFromString(value, CallType.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/insights/v1/conference/ConferenceParticipantFetcher.java b/src/main/java/com/twilio/rest/insights/v1/conference/ConferenceParticipantFetcher.java index f688fec0d0..288bfc2f1b 100644 --- a/src/main/java/com/twilio/rest/insights/v1/conference/ConferenceParticipantFetcher.java +++ b/src/main/java/com/twilio/rest/insights/v1/conference/ConferenceParticipantFetcher.java @@ -15,7 +15,8 @@ package com.twilio.rest.insights.v1.conference; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,87 +26,76 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class ConferenceParticipantFetcher - extends Fetcher { +public class ConferenceParticipantFetcher extends Fetcher { - private String pathConferenceSid; - private String pathParticipantSid; + private String pathconferenceSid; + private String pathparticipantSid; private String events; private String metrics; - public ConferenceParticipantFetcher( - final String pathConferenceSid, - final String pathParticipantSid - ) { - this.pathConferenceSid = pathConferenceSid; - this.pathParticipantSid = pathParticipantSid; + public ConferenceParticipantFetcher(final String pathconferenceSid, final String pathparticipantSid) { + this.pathconferenceSid = pathconferenceSid; + this.pathparticipantSid = pathparticipantSid; } + public ConferenceParticipantFetcher setEvents(final String events) { this.events = events; return this; } + public ConferenceParticipantFetcher setMetrics(final String metrics) { this.metrics = metrics; return this; } + @Override public ConferenceParticipant fetch(final TwilioRestClient client) { - String path = - "/v1/Conferences/{ConferenceSid}/Participants/{ParticipantSid}"; - path = - path.replace( - "{" + "ConferenceSid" + "}", - this.pathConferenceSid.toString() - ); - path = - path.replace( - "{" + "ParticipantSid" + "}", - this.pathParticipantSid.toString() - ); + String path = "/v1/Conferences/{ConferenceSid}/Participants/{ParticipantSid}"; + + path = path.replace("{" + "ConferenceSid" + "}", this.pathconferenceSid.toString()); + path = path.replace("{" + "ParticipantSid" + "}", this.pathparticipantSid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.INSIGHTS.toString(), - path + HttpMethod.GET, + Domains.INSIGHTS.toString(), + path ); addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "ConferenceParticipant fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("ConferenceParticipant fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return ConferenceParticipant.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return ConferenceParticipant.fromJson(response.getStream(), client.getObjectMapper()); } private void addQueryParams(final Request request) { + + if (events != null) { - request.addQueryParam("Events", events); + Serializer.toString(request, "Events", events, ParameterType.QUERY); } + + if (metrics != null) { - request.addQueryParam("Metrics", metrics); + Serializer.toString(request, "Metrics", metrics, ParameterType.QUERY); } + + } } diff --git a/src/main/java/com/twilio/rest/insights/v1/conference/ConferenceParticipantReader.java b/src/main/java/com/twilio/rest/insights/v1/conference/ConferenceParticipantReader.java index 96fab30b5b..0225315d17 100644 --- a/src/main/java/com/twilio/rest/insights/v1/conference/ConferenceParticipantReader.java +++ b/src/main/java/com/twilio/rest/insights/v1/conference/ConferenceParticipantReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,148 +30,124 @@ public class ConferenceParticipantReader extends Reader { - private String pathConferenceSid; + private String pathconferenceSid; private String participantSid; private String label; private String events; private Long pageSize; - public ConferenceParticipantReader(final String pathConferenceSid) { - this.pathConferenceSid = pathConferenceSid; + public ConferenceParticipantReader(final String pathconferenceSid) { + this.pathconferenceSid = pathconferenceSid; } - public ConferenceParticipantReader setParticipantSid( - final String participantSid - ) { + + public ConferenceParticipantReader setParticipantSid(final String participantSid) { this.participantSid = participantSid; return this; } + public ConferenceParticipantReader setLabel(final String label) { this.label = label; return this; } + public ConferenceParticipantReader setEvents(final String events) { this.events = events; return this; } + public ConferenceParticipantReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override - public ResourceSet read( - final TwilioRestClient client - ) { + public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } - public Page firstPage( - final TwilioRestClient client - ) { + public Page firstPage(final TwilioRestClient client) { + String path = "/v1/Conferences/{ConferenceSid}/Participants"; - path = - path.replace( - "{" + "ConferenceSid" + "}", - this.pathConferenceSid.toString() - ); + + path = path.replace("{" + "ConferenceSid" + "}", this.pathconferenceSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.INSIGHTS.toString(), - path + HttpMethod.GET, + Domains.INSIGHTS.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "ConferenceParticipant read failed: Unable to connect to server" - ); + throw new ApiConnectionException("ConferenceParticipant read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "participants", - response.getContent(), - ConferenceParticipant.class, - client.getObjectMapper() - ); + "participants", + response.getContent(), + ConferenceParticipant.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.INSIGHTS.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.INSIGHTS.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (participantSid != null) { - request.addQueryParam("ParticipantSid", participantSid); + Serializer.toString(request, "ParticipantSid", participantSid, ParameterType.QUERY); } + + if (label != null) { - request.addQueryParam("Label", label); + Serializer.toString(request, "Label", label, ParameterType.QUERY); } + + if (events != null) { - request.addQueryParam("Events", events); + Serializer.toString(request, "Events", events, ParameterType.QUERY); } + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/insights/v1/room/Participant.java b/src/main/java/com/twilio/rest/insights/v1/room/Participant.java index b575a7042a..7b8011aac3 100644 --- a/src/main/java/com/twilio/rest/insights/v1/room/Participant.java +++ b/src/main/java/com/twilio/rest/insights/v1/room/Participant.java @@ -18,265 +18,107 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.List; -import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Participant extends Resource { - private static final long serialVersionUID = 21473393957377L; - - public static ParticipantFetcher fetcher( - final String pathRoomSid, - final String pathParticipantSid - ) { - return new ParticipantFetcher(pathRoomSid, pathParticipantSid); - } - - public static ParticipantReader reader(final String pathRoomSid) { - return new ParticipantReader(pathRoomSid); - } - - /** - * Converts a JSON String into a Participant object using the provided ObjectMapper. - * - * @param json Raw JSON String - * @param objectMapper Jackson ObjectMapper - * @return Participant object represented by the provided JSON - */ - public static Participant fromJson( - final String json, - final ObjectMapper objectMapper - ) { - // Convert all checked exceptions to Runtime - try { - return objectMapper.readValue(json, Participant.class); - } catch (final JsonMappingException | JsonParseException e) { - throw new ApiException(e.getMessage(), e); - } catch (final IOException e) { - throw new ApiConnectionException(e.getMessage(), e); - } - } - - /** - * Converts a JSON InputStream into a Participant object using the provided - * ObjectMapper. - * - * @param json Raw JSON InputStream - * @param objectMapper Jackson ObjectMapper - * @return Participant object represented by the provided JSON - */ - public static Participant fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { - // Convert all checked exceptions to Runtime - try { - return objectMapper.readValue(json, Participant.class); - } catch (final JsonMappingException | JsonParseException e) { - throw new ApiException(e.getMessage(), e); - } catch (final IOException e) { - throw new ApiConnectionException(e.getMessage(), e); - } - } - - private final String participantSid; - private final String participantIdentity; - private final ZonedDateTime joinTime; - private final ZonedDateTime leaveTime; - private final Long durationSec; - private final String accountSid; - private final String roomSid; - private final Participant.RoomStatus status; - private final List codecs; - private final String endReason; - private final Integer errorCode; - private final String errorCodeUrl; - private final Participant.TwilioRealm mediaRegion; - private final Map properties; - private final Participant.EdgeLocation edgeLocation; - private final Map publisherInfo; - private final URI url; - - @JsonCreator - private Participant( - @JsonProperty("participant_sid") final String participantSid, - @JsonProperty("participant_identity") final String participantIdentity, - @JsonProperty("join_time") final String joinTime, - @JsonProperty("leave_time") final String leaveTime, - @JsonProperty("duration_sec") final Long durationSec, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("room_sid") final String roomSid, - @JsonProperty("status") final Participant.RoomStatus status, - @JsonProperty("codecs") final List codecs, - @JsonProperty("end_reason") final String endReason, - @JsonProperty("error_code") final Integer errorCode, - @JsonProperty("error_code_url") final String errorCodeUrl, - @JsonProperty("media_region") final Participant.TwilioRealm mediaRegion, - @JsonProperty("properties") final Map properties, - @JsonProperty( - "edge_location" - ) final Participant.EdgeLocation edgeLocation, - @JsonProperty("publisher_info") final Map publisherInfo, - @JsonProperty("url") final URI url - ) { - this.participantSid = participantSid; - this.participantIdentity = participantIdentity; - this.joinTime = DateConverter.iso8601DateTimeFromString(joinTime); - this.leaveTime = DateConverter.iso8601DateTimeFromString(leaveTime); - this.durationSec = durationSec; - this.accountSid = accountSid; - this.roomSid = roomSid; - this.status = status; - this.codecs = codecs; - this.endReason = endReason; - this.errorCode = errorCode; - this.errorCodeUrl = errorCodeUrl; - this.mediaRegion = mediaRegion; - this.properties = properties; - this.edgeLocation = edgeLocation; - this.publisherInfo = publisherInfo; - this.url = url; - } - - public final String getParticipantSid() { - return this.participantSid; - } - public final String getParticipantIdentity() { - return this.participantIdentity; + public static ParticipantFetcher fetcher(final String pathroomSid, final String pathparticipantSid) { + return new ParticipantFetcher( + pathroomSid, pathparticipantSid + ); } - public final ZonedDateTime getJoinTime() { - return this.joinTime; - } - public final ZonedDateTime getLeaveTime() { - return this.leaveTime; + public static ParticipantReader reader(final String pathroomSid) { + return new ParticipantReader( + pathroomSid + ); } - public final Long getDurationSec() { - return this.durationSec; - } - public final String getAccountSid() { - return this.accountSid; - } + public enum Codec { + VP8("VP8"), + H264("H264"), + VP9("VP9"), + OPUS("opus"); - public final String getRoomSid() { - return this.roomSid; - } + private final String value; - public final Participant.RoomStatus getStatus() { - return this.status; - } + private Codec(final String value) { + this.value = value; + } - public final List getCodecs() { - return this.codecs; - } + public String toString() { + return value; + } - public final String getEndReason() { - return this.endReason; + @JsonCreator + public static Codec forValue(final String value) { + return Promoter.enumFromString(value, Codec.values()); + } } - public final Integer getErrorCode() { - return this.errorCode; - } + public enum ParticipantParticipantCodec { + VP8("VP8"), + H264("H264"), + VP9("VP9"), + OPUS("opus"); - public final String getErrorCodeUrl() { - return this.errorCodeUrl; - } + private final String value; - public final Participant.TwilioRealm getMediaRegion() { - return this.mediaRegion; - } + private ParticipantParticipantCodec(final String value) { + this.value = value; + } - public final Map getProperties() { - return this.properties; - } + public String toString() { + return value; + } - public final Participant.EdgeLocation getEdgeLocation() { - return this.edgeLocation; + @JsonCreator + public static ParticipantParticipantCodec forValue(final String value) { + return Promoter.enumFromString(value, ParticipantParticipantCodec.values()); + } } - public final Map getPublisherInfo() { - return this.publisherInfo; - } + public enum RoomStatus { + IN_PROGRESS("in_progress"), + CONNECTED("connected"), + COMPLETED("completed"), + DISCONNECTED("disconnected"); - public final URI getUrl() { - return this.url; - } + private final String value; - @Override - public boolean equals(final Object o) { - if (this == o) { - return true; + private RoomStatus(final String value) { + this.value = value; } - if (o == null || getClass() != o.getClass()) { - return false; + public String toString() { + return value; } - Participant other = (Participant) o; - - return ( - Objects.equals(participantSid, other.participantSid) && - Objects.equals(participantIdentity, other.participantIdentity) && - Objects.equals(joinTime, other.joinTime) && - Objects.equals(leaveTime, other.leaveTime) && - Objects.equals(durationSec, other.durationSec) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(roomSid, other.roomSid) && - Objects.equals(status, other.status) && - Objects.equals(codecs, other.codecs) && - Objects.equals(endReason, other.endReason) && - Objects.equals(errorCode, other.errorCode) && - Objects.equals(errorCodeUrl, other.errorCodeUrl) && - Objects.equals(mediaRegion, other.mediaRegion) && - Objects.equals(properties, other.properties) && - Objects.equals(edgeLocation, other.edgeLocation) && - Objects.equals(publisherInfo, other.publisherInfo) && - Objects.equals(url, other.url) - ); - } - - @Override - public int hashCode() { - return Objects.hash( - participantSid, - participantIdentity, - joinTime, - leaveTime, - durationSec, - accountSid, - roomSid, - status, - codecs, - endReason, - errorCode, - errorCodeUrl, - mediaRegion, - properties, - edgeLocation, - publisherInfo, - url - ); + @JsonCreator + public static RoomStatus forValue(final String value) { + return Promoter.enumFromString(value, RoomStatus.values()); + } } public enum TwilioRealm { @@ -307,15 +149,15 @@ public static TwilioRealm forValue(final String value) { } } - public enum RoomStatus { - IN_PROGRESS("in_progress"), - CONNECTED("connected"), - COMPLETED("completed"), - DISCONNECTED("disconnected"); + public enum ParticipantParticipantParticipantCodec { + VP8("VP8"), + H264("H264"), + VP9("VP9"), + OPUS("opus"); private final String value; - private RoomStatus(final String value) { + private ParticipantParticipantParticipantCodec(final String value) { this.value = value; } @@ -324,12 +166,12 @@ public String toString() { } @JsonCreator - public static RoomStatus forValue(final String value) { - return Promoter.enumFromString(value, RoomStatus.values()); + public static ParticipantParticipantParticipantCodec forValue(final String value) { + return Promoter.enumFromString(value, ParticipantParticipantParticipantCodec.values()); } } - public enum Codec { + public enum ParticipantCodec { VP8("VP8"), H264("H264"), VP9("VP9"), @@ -337,7 +179,7 @@ public enum Codec { private final String value; - private Codec(final String value) { + private ParticipantCodec(final String value) { this.value = value; } @@ -346,8 +188,8 @@ public String toString() { } @JsonCreator - public static Codec forValue(final String value) { - return Promoter.enumFromString(value, Codec.values()); + public static ParticipantCodec forValue(final String value) { + return Promoter.enumFromString(value, ParticipantCodec.values()); } } @@ -377,4 +219,189 @@ public static EdgeLocation forValue(final String value) { return Promoter.enumFromString(value, EdgeLocation.values()); } } + + + /** + * Converts a JSON String into a Participant object using the provided ObjectMapper. + * + * @param json Raw JSON String + * @param objectMapper Jackson ObjectMapper + * @return Participant object represented by the provided JSON + */ + public static Participant fromJson(final String json, final ObjectMapper objectMapper) { + // Convert all checked exceptions to Runtime + try { + return objectMapper.readValue(json, Participant.class); + } catch (final JsonMappingException | JsonParseException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + /** + * Converts a JSON InputStream into a Participant object using the provided + * ObjectMapper. + * + * @param json Raw JSON InputStream + * @param objectMapper Jackson ObjectMapper + * @return Participant object represented by the provided JSON + */ + public static Participant fromJson(final InputStream json, final ObjectMapper objectMapper) { + // Convert all checked exceptions to Runtime + try { + return objectMapper.readValue(json, Participant.class); + } catch (final JsonMappingException | JsonParseException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter + private final String accountSid; + @Getter + private final List codecs; + @Getter + private final Long durationSec; + @Getter + private final Participant.EdgeLocation edgeLocation; + @Getter + private final String endReason; + @Getter + private final Integer errorCode; + @Getter + private final String errorCodeUrl; + @Getter + private final ZonedDateTime joinTime; + @Getter + private final ZonedDateTime leaveTime; + @Getter + private final Participant.TwilioRealm mediaRegion; + @Getter + private final String participantIdentity; + @Getter + private final String participantSid; + @Getter + private final Object properties; + @Getter + private final Object publisherInfo; + @Getter + private final String roomSid; + @Getter + private final Participant.RoomStatus status; + @Getter + private final URI url; + + @JsonCreator + private Participant( + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("codecs") final List codecs, + @JsonProperty("duration_sec") final Long durationSec, + @JsonProperty("edge_location") final Participant.EdgeLocation edgeLocation, + @JsonProperty("end_reason") final String endReason, + @JsonProperty("error_code") final Integer errorCode, + @JsonProperty("error_code_url") final String errorCodeUrl, + @JsonProperty("join_time") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime joinTime, + @JsonProperty("leave_time") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime leaveTime, + @JsonProperty("media_region") final Participant.TwilioRealm mediaRegion, + @JsonProperty("participant_identity") final String participantIdentity, + @JsonProperty("participant_sid") final String participantSid, + @JsonProperty("properties") final Object properties, + @JsonProperty("publisher_info") final Object publisherInfo, + @JsonProperty("room_sid") final String roomSid, + @JsonProperty("status") final Participant.RoomStatus status, + @JsonProperty("url") final URI url + ) { + this.accountSid = accountSid; + this.codecs = codecs; + this.durationSec = durationSec; + this.edgeLocation = edgeLocation; + this.endReason = endReason; + this.errorCode = errorCode; + this.errorCodeUrl = errorCodeUrl; + this.joinTime = joinTime; + this.leaveTime = leaveTime; + this.mediaRegion = mediaRegion; + this.participantIdentity = participantIdentity; + this.participantSid = participantSid; + this.properties = properties; + this.publisherInfo = publisherInfo; + this.roomSid = roomSid; + this.status = status; + this.url = url; + } + + @Override + public boolean equals(final Object o) { + if (this == o) { + return true; + } + + if (o == null || getClass() != o.getClass()) { + return false; + } + + Participant other = (Participant) o; + return ( + Objects.equals(accountSid, other.accountSid) && + Objects.equals(codecs, other.codecs) && + Objects.equals(durationSec, other.durationSec) && + Objects.equals(edgeLocation, other.edgeLocation) && + Objects.equals(endReason, other.endReason) && + Objects.equals(errorCode, other.errorCode) && + Objects.equals(errorCodeUrl, other.errorCodeUrl) && + Objects.equals(joinTime, other.joinTime) && + Objects.equals(leaveTime, other.leaveTime) && + Objects.equals(mediaRegion, other.mediaRegion) && + Objects.equals(participantIdentity, other.participantIdentity) && + Objects.equals(participantSid, other.participantSid) && + Objects.equals(properties, other.properties) && + Objects.equals(publisherInfo, other.publisherInfo) && + Objects.equals(roomSid, other.roomSid) && + Objects.equals(status, other.status) && + Objects.equals(url, other.url) + ); + } + + @Override + public int hashCode() { + return Objects.hash( + accountSid, + codecs, + durationSec, + edgeLocation, + endReason, + errorCode, + errorCodeUrl, + joinTime, + leaveTime, + mediaRegion, + participantIdentity, + participantSid, + properties, + publisherInfo, + roomSid, + status, + url + ); + } + + } + diff --git a/src/main/java/com/twilio/rest/insights/v1/room/ParticipantFetcher.java b/src/main/java/com/twilio/rest/insights/v1/room/ParticipantFetcher.java index b61549cd83..af16b3d1d0 100644 --- a/src/main/java/com/twilio/rest/insights/v1/room/ParticipantFetcher.java +++ b/src/main/java/com/twilio/rest/insights/v1/room/ParticipantFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.insights.v1.room; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,57 +26,44 @@ public class ParticipantFetcher extends Fetcher { - private String pathRoomSid; - private String pathParticipantSid; + private String pathroomSid; + private String pathparticipantSid; - public ParticipantFetcher( - final String pathRoomSid, - final String pathParticipantSid - ) { - this.pathRoomSid = pathRoomSid; - this.pathParticipantSid = pathParticipantSid; + public ParticipantFetcher(final String pathroomSid, final String pathparticipantSid) { + this.pathroomSid = pathroomSid; + this.pathparticipantSid = pathparticipantSid; } + @Override public Participant fetch(final TwilioRestClient client) { + String path = "/v1/Video/Rooms/{RoomSid}/Participants/{ParticipantSid}"; - path = path.replace("{" + "RoomSid" + "}", this.pathRoomSid.toString()); - path = - path.replace( - "{" + "ParticipantSid" + "}", - this.pathParticipantSid.toString() - ); + path = path.replace("{" + "RoomSid" + "}", this.pathroomSid.toString()); + path = path.replace("{" + "ParticipantSid" + "}", this.pathparticipantSid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.INSIGHTS.toString(), - path + HttpMethod.GET, + Domains.INSIGHTS.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Participant fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Participant fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return Participant.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Participant.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/insights/v1/room/ParticipantReader.java b/src/main/java/com/twilio/rest/insights/v1/room/ParticipantReader.java index 13d453ed0c..72460cadfd 100644 --- a/src/main/java/com/twilio/rest/insights/v1/room/ParticipantReader.java +++ b/src/main/java/com/twilio/rest/insights/v1/room/ParticipantReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,111 +30,88 @@ public class ParticipantReader extends Reader { - private String pathRoomSid; + private String pathroomSid; private Long pageSize; - public ParticipantReader(final String pathRoomSid) { - this.pathRoomSid = pathRoomSid; + public ParticipantReader(final String pathroomSid) { + this.pathroomSid = pathroomSid; } + public ParticipantReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/Video/Rooms/{RoomSid}/Participants"; - path = path.replace("{" + "RoomSid" + "}", this.pathRoomSid.toString()); + + path = path.replace("{" + "RoomSid" + "}", this.pathroomSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.INSIGHTS.toString(), - path + HttpMethod.GET, + Domains.INSIGHTS.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Participant read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Participant read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "participants", - response.getContent(), - Participant.class, - client.getObjectMapper() - ); + "participants", + response.getContent(), + Participant.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.INSIGHTS.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.INSIGHTS.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/intelligence/v2/CustomOperator.java b/src/main/java/com/twilio/rest/intelligence/v2/CustomOperator.java index 577770f332..948e9376f2 100644 --- a/src/main/java/com/twilio/rest/intelligence/v2/CustomOperator.java +++ b/src/main/java/com/twilio/rest/intelligence/v2/CustomOperator.java @@ -18,68 +18,94 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; -import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class CustomOperator extends Resource { - private static final long serialVersionUID = 100488785268469L; - public static CustomOperatorCreator creator( - final String friendlyName, - final String operatorType, - final Object config - ) { - return new CustomOperatorCreator(friendlyName, operatorType, config); + public static CustomOperatorCreator creator(final String friendlyName, final String operatorType, final Object config) { + return new CustomOperatorCreator( + friendlyName, operatorType, config + ); } - public static CustomOperatorDeleter deleter(final String pathSid) { - return new CustomOperatorDeleter(pathSid); + + public static CustomOperatorDeleter deleter(final String pathsid) { + return new CustomOperatorDeleter( + pathsid + ); } - public static CustomOperatorFetcher fetcher(final String pathSid) { - return new CustomOperatorFetcher(pathSid); + + public static CustomOperatorFetcher fetcher(final String pathsid) { + return new CustomOperatorFetcher( + pathsid + ); } + public static CustomOperatorReader reader() { - return new CustomOperatorReader(); + return new CustomOperatorReader( + + ); } - public static CustomOperatorUpdater updater( - final String pathSid, - final String friendlyName, - final Object config - ) { - return new CustomOperatorUpdater(pathSid, friendlyName, config); + + public static CustomOperatorUpdater updater(final String pathsid, final String friendlyName, final Object config) { + return new CustomOperatorUpdater( + pathsid, friendlyName, config + ); } + + public enum Availability { + INTERNAL("internal"), + BETA("beta"), + PUBLIC("public"), + RETIRED("retired"); + + private final String value; + + private Availability(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static Availability forValue(final String value) { + return Promoter.enumFromString(value, Availability.values()); + } + } + + /** * Converts a JSON String into a CustomOperator object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return CustomOperator object represented by the provided JSON */ - public static CustomOperator fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static CustomOperator fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, CustomOperator.class); @@ -94,14 +120,11 @@ public static CustomOperator fromJson( * Converts a JSON InputStream into a CustomOperator object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return CustomOperator object represented by the provided JSON */ - public static CustomOperator fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static CustomOperator fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, CustomOperator.class); @@ -112,96 +135,73 @@ public static CustomOperator fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String sid; - private final String friendlyName; - private final String description; + @Getter private final String author; - private final String operatorType; - private final Integer version; + @Getter private final CustomOperator.Availability availability; - private final Map config; + @Getter + private final Object config; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; + @Getter + private final String description; + @Getter + private final String friendlyName; + @Getter + private final String operatorType; + @Getter + private final String sid; + @Getter private final URI url; + @Getter + private final Integer version; @JsonCreator private CustomOperator( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("sid") final String sid, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("description") final String description, - @JsonProperty("author") final String author, - @JsonProperty("operator_type") final String operatorType, - @JsonProperty("version") final Integer version, - @JsonProperty( - "availability" - ) final CustomOperator.Availability availability, - @JsonProperty("config") final Map config, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("url") final URI url + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("author") final String author, + @JsonProperty("availability") final CustomOperator.Availability availability, + @JsonProperty("config") final Object config, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("description") final String description, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("operator_type") final String operatorType, + @JsonProperty("sid") final String sid, + @JsonProperty("url") final URI url, + @JsonProperty("version") final Integer version ) { this.accountSid = accountSid; - this.sid = sid; - this.friendlyName = friendlyName; - this.description = description; this.author = author; - this.operatorType = operatorType; - this.version = version; this.availability = availability; this.config = config; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; + this.description = description; + this.friendlyName = friendlyName; + this.operatorType = operatorType; + this.sid = sid; this.url = url; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getSid() { - return this.sid; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final String getDescription() { - return this.description; - } - - public final String getAuthor() { - return this.author; - } - - public final String getOperatorType() { - return this.operatorType; - } - - public final Integer getVersion() { - return this.version; - } - - public final CustomOperator.Availability getAvailability() { - return this.availability; - } - - public final Map getConfig() { - return this.config; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final URI getUrl() { - return this.url; + this.version = version; } @Override @@ -215,60 +215,40 @@ public boolean equals(final Object o) { } CustomOperator other = (CustomOperator) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(sid, other.sid) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(description, other.description) && - Objects.equals(author, other.author) && - Objects.equals(operatorType, other.operatorType) && - Objects.equals(version, other.version) && - Objects.equals(availability, other.availability) && - Objects.equals(config, other.config) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(url, other.url) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(author, other.author) && + Objects.equals(availability, other.availability) && + Objects.equals(config, other.config) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(description, other.description) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(operatorType, other.operatorType) && + Objects.equals(sid, other.sid) && + Objects.equals(url, other.url) && + Objects.equals(version, other.version) ); } @Override public int hashCode() { return Objects.hash( - accountSid, - sid, - friendlyName, - description, - author, - operatorType, - version, - availability, - config, - dateCreated, - dateUpdated, - url + accountSid, + author, + availability, + config, + dateCreated, + dateUpdated, + description, + friendlyName, + operatorType, + sid, + url, + version ); } - public enum Availability { - INTERNAL("internal"), - BETA("beta"), - PUBLIC("public"), - RETIRED("retired"); - - private final String value; - private Availability(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static Availability forValue(final String value) { - return Promoter.enumFromString(value, Availability.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/intelligence/v2/CustomOperatorCreator.java b/src/main/java/com/twilio/rest/intelligence/v2/CustomOperatorCreator.java index 85535d3191..70c60f13bf 100644 --- a/src/main/java/com/twilio/rest/intelligence/v2/CustomOperatorCreator.java +++ b/src/main/java/com/twilio/rest/intelligence/v2/CustomOperatorCreator.java @@ -14,10 +14,11 @@ package com.twilio.rest.intelligence.v2; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; -import com.twilio.converter.Converter; -import com.twilio.converter.Converter; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -33,88 +34,79 @@ public class CustomOperatorCreator extends Creator { private String operatorType; private Object config; - public CustomOperatorCreator( - final String friendlyName, - final String operatorType, - final Object config - ) { + public CustomOperatorCreator(final String friendlyName, final String operatorType, final Object config) { this.friendlyName = friendlyName; this.operatorType = operatorType; this.config = config; } + public CustomOperatorCreator setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + public CustomOperatorCreator setOperatorType(final String operatorType) { this.operatorType = operatorType; return this; } + public CustomOperatorCreator setConfig(final Object config) { this.config = config; return this; } + @Override public CustomOperator create(final TwilioRestClient client) { + String path = "/v2/Operators/Custom"; - path = - path.replace( - "{" + "FriendlyName" + "}", - this.friendlyName.toString() - ); - path = - path.replace( - "{" + "OperatorType" + "}", - this.operatorType.toString() - ); - path = path.replace("{" + "Config" + "}", this.config.toString()); Request request = new Request( - HttpMethod.POST, - Domains.INTELLIGENCE.toString(), - path + HttpMethod.POST, + Domains.INTELLIGENCE.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "CustomOperator creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("CustomOperator creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return CustomOperator.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return CustomOperator.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + if (operatorType != null) { - request.addPostParam("OperatorType", operatorType); + Serializer.toString(request, "OperatorType", operatorType, ParameterType.URLENCODED); } + + if (config != null) { - request.addPostParam("Config", Converter.objectToJson(config)); + Serializer.toString(request, "Config", config, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/intelligence/v2/CustomOperatorDeleter.java b/src/main/java/com/twilio/rest/intelligence/v2/CustomOperatorDeleter.java index 46945ffe4f..71d2cce5df 100644 --- a/src/main/java/com/twilio/rest/intelligence/v2/CustomOperatorDeleter.java +++ b/src/main/java/com/twilio/rest/intelligence/v2/CustomOperatorDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.intelligence.v2; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,40 +26,38 @@ public class CustomOperatorDeleter extends Deleter { - private String pathSid; + private String pathsid; - public CustomOperatorDeleter(final String pathSid) { - this.pathSid = pathSid; + public CustomOperatorDeleter(final String pathsid) { + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/v2/Operators/Custom/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.INTELLIGENCE.toString(), - path + HttpMethod.DELETE, + Domains.INTELLIGENCE.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "CustomOperator delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("CustomOperator delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/intelligence/v2/CustomOperatorFetcher.java b/src/main/java/com/twilio/rest/intelligence/v2/CustomOperatorFetcher.java index e669b02cbd..d3128d97fe 100644 --- a/src/main/java/com/twilio/rest/intelligence/v2/CustomOperatorFetcher.java +++ b/src/main/java/com/twilio/rest/intelligence/v2/CustomOperatorFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.intelligence.v2; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,47 +26,41 @@ public class CustomOperatorFetcher extends Fetcher { - private String pathSid; + private String pathsid; - public CustomOperatorFetcher(final String pathSid) { - this.pathSid = pathSid; + public CustomOperatorFetcher(final String pathsid) { + this.pathsid = pathsid; } + @Override public CustomOperator fetch(final TwilioRestClient client) { + String path = "/v2/Operators/Custom/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.INTELLIGENCE.toString(), - path + HttpMethod.GET, + Domains.INTELLIGENCE.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "CustomOperator fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("CustomOperator fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return CustomOperator.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return CustomOperator.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/intelligence/v2/CustomOperatorReader.java b/src/main/java/com/twilio/rest/intelligence/v2/CustomOperatorReader.java index 2438c46e57..f6cfb368ea 100644 --- a/src/main/java/com/twilio/rest/intelligence/v2/CustomOperatorReader.java +++ b/src/main/java/com/twilio/rest/intelligence/v2/CustomOperatorReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -33,123 +34,105 @@ public class CustomOperatorReader extends Reader { private String languageCode; private Long pageSize; - public CustomOperatorReader() {} + public CustomOperatorReader() { + } + - public CustomOperatorReader setAvailability( - final CustomOperator.Availability availability - ) { + public CustomOperatorReader setAvailability(final CustomOperator.Availability availability) { this.availability = availability; return this; } + public CustomOperatorReader setLanguageCode(final String languageCode) { this.languageCode = languageCode; return this; } + public CustomOperatorReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v2/Operators/Custom"; + Request request = new Request( - HttpMethod.GET, - Domains.INTELLIGENCE.toString(), - path + HttpMethod.GET, + Domains.INTELLIGENCE.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "CustomOperator read failed: Unable to connect to server" - ); + throw new ApiConnectionException("CustomOperator read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "operators", - response.getContent(), - CustomOperator.class, - client.getObjectMapper() - ); + "operators", + response.getContent(), + CustomOperator.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.INTELLIGENCE.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.INTELLIGENCE.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (availability != null) { - request.addQueryParam("Availability", availability.toString()); + Serializer.toString(request, "Availability", availability, ParameterType.QUERY); } + + if (languageCode != null) { - request.addQueryParam("LanguageCode", languageCode); + Serializer.toString(request, "LanguageCode", languageCode, ParameterType.QUERY); } + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/intelligence/v2/CustomOperatorUpdater.java b/src/main/java/com/twilio/rest/intelligence/v2/CustomOperatorUpdater.java index 73c396b60d..346da8b134 100644 --- a/src/main/java/com/twilio/rest/intelligence/v2/CustomOperatorUpdater.java +++ b/src/main/java/com/twilio/rest/intelligence/v2/CustomOperatorUpdater.java @@ -16,7 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; -import com.twilio.converter.Converter; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,94 +28,90 @@ import com.twilio.rest.Domains; public class CustomOperatorUpdater extends Updater { - - private String pathSid; + private String pathsid; + private String ifMatch; private String friendlyName; private Object config; - private String ifMatch; - public CustomOperatorUpdater( - final String pathSid, - final String friendlyName, - final Object config - ) { - this.pathSid = pathSid; + public CustomOperatorUpdater(final String pathsid, final String friendlyName, final Object config) { + this.pathsid = pathsid; this.friendlyName = friendlyName; this.config = config; } + public CustomOperatorUpdater setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + public CustomOperatorUpdater setConfig(final Object config) { this.config = config; return this; } + public CustomOperatorUpdater setIfMatch(final String ifMatch) { this.ifMatch = ifMatch; return this; } + @Override public CustomOperator update(final TwilioRestClient client) { + String path = "/v2/Operators/Custom/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); - path = - path.replace( - "{" + "FriendlyName" + "}", - this.friendlyName.toString() - ); - path = path.replace("{" + "Config" + "}", this.config.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.INTELLIGENCE.toString(), - path + HttpMethod.POST, + Domains.INTELLIGENCE.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); - addPostParams(request); addHeaderParams(request); + addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "CustomOperator update failed: Unable to connect to server" - ); + throw new ApiConnectionException("CustomOperator update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return CustomOperator.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return CustomOperator.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + if (config != null) { - request.addPostParam("Config", Converter.objectToJson(config)); + Serializer.toString(request, "Config", config, ParameterType.URLENCODED); } + + } private void addHeaderParams(final Request request) { + if (ifMatch != null) { - request.addHeaderParam("If-Match", ifMatch); + Serializer.toString(request, "If-Match", ifMatch, ParameterType.HEADER); } + } } diff --git a/src/main/java/com/twilio/rest/intelligence/v2/Operator.java b/src/main/java/com/twilio/rest/intelligence/v2/Operator.java index a9c425c153..bca3d4175f 100644 --- a/src/main/java/com/twilio/rest/intelligence/v2/Operator.java +++ b/src/main/java/com/twilio/rest/intelligence/v2/Operator.java @@ -18,48 +18,73 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; -import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Operator extends Resource { - private static final long serialVersionUID = 163994409447138L; - public static OperatorFetcher fetcher(final String pathSid) { - return new OperatorFetcher(pathSid); + public static OperatorFetcher fetcher(final String pathsid) { + return new OperatorFetcher( + pathsid + ); } + public static OperatorReader reader() { - return new OperatorReader(); + return new OperatorReader( + + ); } + + public enum Availability { + INTERNAL("internal"), + BETA("beta"), + PUBLIC("public"), + RETIRED("retired"); + + private final String value; + + private Availability(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static Availability forValue(final String value) { + return Promoter.enumFromString(value, Availability.values()); + } + } + + /** * Converts a JSON String into a Operator object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Operator object represented by the provided JSON */ - public static Operator fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Operator fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Operator.class); @@ -74,14 +99,11 @@ public static Operator fromJson( * Converts a JSON InputStream into a Operator object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Operator object represented by the provided JSON */ - public static Operator fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Operator fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Operator.class); @@ -92,94 +114,73 @@ public static Operator fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String sid; - private final String friendlyName; - private final String description; + @Getter private final String author; - private final String operatorType; - private final Integer version; + @Getter private final Operator.Availability availability; - private final Map config; + @Getter + private final Object config; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; + @Getter + private final String description; + @Getter + private final String friendlyName; + @Getter + private final String operatorType; + @Getter + private final String sid; + @Getter private final URI url; + @Getter + private final Integer version; @JsonCreator private Operator( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("sid") final String sid, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("description") final String description, - @JsonProperty("author") final String author, - @JsonProperty("operator_type") final String operatorType, - @JsonProperty("version") final Integer version, - @JsonProperty("availability") final Operator.Availability availability, - @JsonProperty("config") final Map config, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("url") final URI url + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("author") final String author, + @JsonProperty("availability") final Operator.Availability availability, + @JsonProperty("config") final Object config, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("description") final String description, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("operator_type") final String operatorType, + @JsonProperty("sid") final String sid, + @JsonProperty("url") final URI url, + @JsonProperty("version") final Integer version ) { this.accountSid = accountSid; - this.sid = sid; - this.friendlyName = friendlyName; - this.description = description; this.author = author; - this.operatorType = operatorType; - this.version = version; this.availability = availability; this.config = config; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; + this.description = description; + this.friendlyName = friendlyName; + this.operatorType = operatorType; + this.sid = sid; this.url = url; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getSid() { - return this.sid; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final String getDescription() { - return this.description; - } - - public final String getAuthor() { - return this.author; - } - - public final String getOperatorType() { - return this.operatorType; - } - - public final Integer getVersion() { - return this.version; - } - - public final Operator.Availability getAvailability() { - return this.availability; - } - - public final Map getConfig() { - return this.config; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final URI getUrl() { - return this.url; + this.version = version; } @Override @@ -193,60 +194,40 @@ public boolean equals(final Object o) { } Operator other = (Operator) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(sid, other.sid) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(description, other.description) && - Objects.equals(author, other.author) && - Objects.equals(operatorType, other.operatorType) && - Objects.equals(version, other.version) && - Objects.equals(availability, other.availability) && - Objects.equals(config, other.config) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(url, other.url) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(author, other.author) && + Objects.equals(availability, other.availability) && + Objects.equals(config, other.config) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(description, other.description) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(operatorType, other.operatorType) && + Objects.equals(sid, other.sid) && + Objects.equals(url, other.url) && + Objects.equals(version, other.version) ); } @Override public int hashCode() { return Objects.hash( - accountSid, - sid, - friendlyName, - description, - author, - operatorType, - version, - availability, - config, - dateCreated, - dateUpdated, - url + accountSid, + author, + availability, + config, + dateCreated, + dateUpdated, + description, + friendlyName, + operatorType, + sid, + url, + version ); } - public enum Availability { - INTERNAL("internal"), - BETA("beta"), - PUBLIC("public"), - RETIRED("retired"); - - private final String value; - private Availability(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static Availability forValue(final String value) { - return Promoter.enumFromString(value, Availability.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/intelligence/v2/OperatorAttachment.java b/src/main/java/com/twilio/rest/intelligence/v2/OperatorAttachment.java index 4625ba914e..6c24c26207 100644 --- a/src/main/java/com/twilio/rest/intelligence/v2/OperatorAttachment.java +++ b/src/main/java/com/twilio/rest/intelligence/v2/OperatorAttachment.java @@ -18,49 +18,47 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class OperatorAttachment extends Resource { - private static final long serialVersionUID = 412105030184L; - public static OperatorAttachmentCreator creator( - final String pathServiceSid, - final String pathOperatorSid - ) { - return new OperatorAttachmentCreator(pathServiceSid, pathOperatorSid); + public static OperatorAttachmentCreator creator(final String pathserviceSid, final String pathoperatorSid) { + return new OperatorAttachmentCreator( + pathserviceSid, pathoperatorSid + ); } - public static OperatorAttachmentDeleter deleter( - final String pathServiceSid, - final String pathOperatorSid - ) { - return new OperatorAttachmentDeleter(pathServiceSid, pathOperatorSid); + + public static OperatorAttachmentDeleter deleter(final String pathserviceSid, final String pathoperatorSid) { + return new OperatorAttachmentDeleter( + pathserviceSid, pathoperatorSid + ); } + /** * Converts a JSON String into a OperatorAttachment object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return OperatorAttachment object represented by the provided JSON */ - public static OperatorAttachment fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static OperatorAttachment fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, OperatorAttachment.class); @@ -75,14 +73,11 @@ public static OperatorAttachment fromJson( * Converts a JSON InputStream into a OperatorAttachment object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return OperatorAttachment object represented by the provided JSON */ - public static OperatorAttachment fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static OperatorAttachment fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, OperatorAttachment.class); @@ -93,33 +88,37 @@ public static OperatorAttachment fromJson( } } - private final String serviceSid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String operatorSid; + @Getter + private final String serviceSid; + @Getter private final URI url; @JsonCreator private OperatorAttachment( - @JsonProperty("service_sid") final String serviceSid, - @JsonProperty("operator_sid") final String operatorSid, - @JsonProperty("url") final URI url + @JsonProperty("operator_sid") final String operatorSid, + @JsonProperty("service_sid") final String serviceSid, + @JsonProperty("url") final URI url ) { - this.serviceSid = serviceSid; this.operatorSid = operatorSid; + this.serviceSid = serviceSid; this.url = url; } - public final String getServiceSid() { - return this.serviceSid; - } - - public final String getOperatorSid() { - return this.operatorSid; - } - - public final URI getUrl() { - return this.url; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -131,16 +130,22 @@ public boolean equals(final Object o) { } OperatorAttachment other = (OperatorAttachment) o; - return ( - Objects.equals(serviceSid, other.serviceSid) && - Objects.equals(operatorSid, other.operatorSid) && - Objects.equals(url, other.url) + Objects.equals(operatorSid, other.operatorSid) && + Objects.equals(serviceSid, other.serviceSid) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { - return Objects.hash(serviceSid, operatorSid, url); + return Objects.hash( + operatorSid, + serviceSid, + url + ); } + + } + diff --git a/src/main/java/com/twilio/rest/intelligence/v2/OperatorAttachmentCreator.java b/src/main/java/com/twilio/rest/intelligence/v2/OperatorAttachmentCreator.java index e4bf57d78b..cd5a38b684 100644 --- a/src/main/java/com/twilio/rest/intelligence/v2/OperatorAttachmentCreator.java +++ b/src/main/java/com/twilio/rest/intelligence/v2/OperatorAttachmentCreator.java @@ -14,8 +14,8 @@ package com.twilio.rest.intelligence.v2; + import com.twilio.base.Creator; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,60 +27,45 @@ public class OperatorAttachmentCreator extends Creator { - private String pathServiceSid; - private String pathOperatorSid; + private String pathserviceSid; + private String pathoperatorSid; - public OperatorAttachmentCreator( - final String pathServiceSid, - final String pathOperatorSid - ) { - this.pathServiceSid = pathServiceSid; - this.pathOperatorSid = pathOperatorSid; + public OperatorAttachmentCreator(final String pathserviceSid, final String pathoperatorSid) { + this.pathserviceSid = pathserviceSid; + this.pathoperatorSid = pathoperatorSid; } + @Override public OperatorAttachment create(final TwilioRestClient client) { + String path = "/v2/Services/{ServiceSid}/Operators/{OperatorSid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = - path.replace( - "{" + "OperatorSid" + "}", - this.pathOperatorSid.toString() - ); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "OperatorSid" + "}", this.pathoperatorSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.INTELLIGENCE.toString(), - path + HttpMethod.POST, + Domains.INTELLIGENCE.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "OperatorAttachment creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("OperatorAttachment creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return OperatorAttachment.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return OperatorAttachment.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/intelligence/v2/OperatorAttachmentDeleter.java b/src/main/java/com/twilio/rest/intelligence/v2/OperatorAttachmentDeleter.java index 704264971c..46badc843f 100644 --- a/src/main/java/com/twilio/rest/intelligence/v2/OperatorAttachmentDeleter.java +++ b/src/main/java/com/twilio/rest/intelligence/v2/OperatorAttachmentDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.intelligence.v2; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,54 +26,41 @@ public class OperatorAttachmentDeleter extends Deleter { - private String pathServiceSid; - private String pathOperatorSid; + private String pathserviceSid; + private String pathoperatorSid; - public OperatorAttachmentDeleter( - final String pathServiceSid, - final String pathOperatorSid - ) { - this.pathServiceSid = pathServiceSid; - this.pathOperatorSid = pathOperatorSid; + public OperatorAttachmentDeleter(final String pathserviceSid, final String pathoperatorSid) { + this.pathserviceSid = pathserviceSid; + this.pathoperatorSid = pathoperatorSid; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/v2/Services/{ServiceSid}/Operators/{OperatorSid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = - path.replace( - "{" + "OperatorSid" + "}", - this.pathOperatorSid.toString() - ); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "OperatorSid" + "}", this.pathoperatorSid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.INTELLIGENCE.toString(), - path + HttpMethod.DELETE, + Domains.INTELLIGENCE.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "OperatorAttachment delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("OperatorAttachment delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/intelligence/v2/OperatorAttachments.java b/src/main/java/com/twilio/rest/intelligence/v2/OperatorAttachments.java index d37a09ec26..5f4d7d8356 100644 --- a/src/main/java/com/twilio/rest/intelligence/v2/OperatorAttachments.java +++ b/src/main/java/com/twilio/rest/intelligence/v2/OperatorAttachments.java @@ -18,42 +18,41 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.util.List; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class OperatorAttachments extends Resource { - private static final long serialVersionUID = 34922173315166L; - public static OperatorAttachmentsFetcher fetcher( - final String pathServiceSid - ) { - return new OperatorAttachmentsFetcher(pathServiceSid); + public static OperatorAttachmentsFetcher fetcher(final String pathserviceSid) { + return new OperatorAttachmentsFetcher( + pathserviceSid + ); } + /** * Converts a JSON String into a OperatorAttachments object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return OperatorAttachments object represented by the provided JSON */ - public static OperatorAttachments fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static OperatorAttachments fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, OperatorAttachments.class); @@ -68,14 +67,11 @@ public static OperatorAttachments fromJson( * Converts a JSON InputStream into a OperatorAttachments object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return OperatorAttachments object represented by the provided JSON */ - public static OperatorAttachments fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static OperatorAttachments fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, OperatorAttachments.class); @@ -86,33 +82,37 @@ public static OperatorAttachments fromJson( } } - private final String serviceSid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final List operatorSids; + @Getter + private final String serviceSid; + @Getter private final URI url; @JsonCreator private OperatorAttachments( - @JsonProperty("service_sid") final String serviceSid, - @JsonProperty("operator_sids") final List operatorSids, - @JsonProperty("url") final URI url + @JsonProperty("operator_sids") final List operatorSids, + @JsonProperty("service_sid") final String serviceSid, + @JsonProperty("url") final URI url ) { - this.serviceSid = serviceSid; this.operatorSids = operatorSids; + this.serviceSid = serviceSid; this.url = url; } - public final String getServiceSid() { - return this.serviceSid; - } - - public final List getOperatorSids() { - return this.operatorSids; - } - - public final URI getUrl() { - return this.url; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -124,16 +124,22 @@ public boolean equals(final Object o) { } OperatorAttachments other = (OperatorAttachments) o; - return ( - Objects.equals(serviceSid, other.serviceSid) && - Objects.equals(operatorSids, other.operatorSids) && - Objects.equals(url, other.url) + Objects.equals(operatorSids, other.operatorSids) && + Objects.equals(serviceSid, other.serviceSid) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { - return Objects.hash(serviceSid, operatorSids, url); + return Objects.hash( + operatorSids, + serviceSid, + url + ); } + + } + diff --git a/src/main/java/com/twilio/rest/intelligence/v2/OperatorAttachmentsFetcher.java b/src/main/java/com/twilio/rest/intelligence/v2/OperatorAttachmentsFetcher.java index 25d49f1f4f..f65e806f87 100644 --- a/src/main/java/com/twilio/rest/intelligence/v2/OperatorAttachmentsFetcher.java +++ b/src/main/java/com/twilio/rest/intelligence/v2/OperatorAttachmentsFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.intelligence.v2; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,51 +26,41 @@ public class OperatorAttachmentsFetcher extends Fetcher { - private String pathServiceSid; + private String pathserviceSid; - public OperatorAttachmentsFetcher(final String pathServiceSid) { - this.pathServiceSid = pathServiceSid; + public OperatorAttachmentsFetcher(final String pathserviceSid) { + this.pathserviceSid = pathserviceSid; } + @Override public OperatorAttachments fetch(final TwilioRestClient client) { + String path = "/v2/Services/{ServiceSid}/Operators"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.INTELLIGENCE.toString(), - path + HttpMethod.GET, + Domains.INTELLIGENCE.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "OperatorAttachments fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("OperatorAttachments fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return OperatorAttachments.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return OperatorAttachments.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/intelligence/v2/OperatorFetcher.java b/src/main/java/com/twilio/rest/intelligence/v2/OperatorFetcher.java index a923ac06f6..517cc86187 100644 --- a/src/main/java/com/twilio/rest/intelligence/v2/OperatorFetcher.java +++ b/src/main/java/com/twilio/rest/intelligence/v2/OperatorFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.intelligence.v2; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,47 +26,41 @@ public class OperatorFetcher extends Fetcher { - private String pathSid; + private String pathsid; - public OperatorFetcher(final String pathSid) { - this.pathSid = pathSid; + public OperatorFetcher(final String pathsid) { + this.pathsid = pathsid; } + @Override public Operator fetch(final TwilioRestClient client) { + String path = "/v2/Operators/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.INTELLIGENCE.toString(), - path + HttpMethod.GET, + Domains.INTELLIGENCE.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Operator fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Operator fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return Operator.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Operator.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/intelligence/v2/OperatorReader.java b/src/main/java/com/twilio/rest/intelligence/v2/OperatorReader.java index 3d2364b33d..ece39483e8 100644 --- a/src/main/java/com/twilio/rest/intelligence/v2/OperatorReader.java +++ b/src/main/java/com/twilio/rest/intelligence/v2/OperatorReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -33,123 +34,105 @@ public class OperatorReader extends Reader { private String languageCode; private Long pageSize; - public OperatorReader() {} + public OperatorReader() { + } + - public OperatorReader setAvailability( - final Operator.Availability availability - ) { + public OperatorReader setAvailability(final Operator.Availability availability) { this.availability = availability; return this; } + public OperatorReader setLanguageCode(final String languageCode) { this.languageCode = languageCode; return this; } + public OperatorReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v2/Operators"; + Request request = new Request( - HttpMethod.GET, - Domains.INTELLIGENCE.toString(), - path + HttpMethod.GET, + Domains.INTELLIGENCE.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Operator read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Operator read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "operators", - response.getContent(), - Operator.class, - client.getObjectMapper() - ); + "operators", + response.getContent(), + Operator.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.INTELLIGENCE.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.INTELLIGENCE.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (availability != null) { - request.addQueryParam("Availability", availability.toString()); + Serializer.toString(request, "Availability", availability, ParameterType.QUERY); } + + if (languageCode != null) { - request.addQueryParam("LanguageCode", languageCode); + Serializer.toString(request, "LanguageCode", languageCode, ParameterType.QUERY); } + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/intelligence/v2/OperatorType.java b/src/main/java/com/twilio/rest/intelligence/v2/OperatorType.java index 566ab5cb66..475e0a75f6 100644 --- a/src/main/java/com/twilio/rest/intelligence/v2/OperatorType.java +++ b/src/main/java/com/twilio/rest/intelligence/v2/OperatorType.java @@ -18,49 +18,118 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.List; -import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class OperatorType extends Resource { - private static final long serialVersionUID = 227558057824727L; - public static OperatorTypeFetcher fetcher(final String pathSid) { - return new OperatorTypeFetcher(pathSid); + public static OperatorTypeFetcher fetcher(final String pathsid) { + return new OperatorTypeFetcher( + pathsid + ); } + public static OperatorTypeReader reader() { - return new OperatorTypeReader(); + return new OperatorTypeReader( + + ); + } + + + public enum Availability { + INTERNAL("internal"), + BETA("beta"), + GENERAL_AVAILABILITY("general-availability"), + RETIRED("retired"), + DEPRECATED("deprecated"); + + private final String value; + + private Availability(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static Availability forValue(final String value) { + return Promoter.enumFromString(value, Availability.values()); + } + } + + public enum OutputType { + TEXT_CLASSIFICATION("text-classification"), + TEXT_EXTRACTION("text-extraction"), + TEXT_EXTRACTION_NORMALIZED("text-extraction-normalized"), + TEXT_GENERATION("text-generation"); + + private final String value; + + private OutputType(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static OutputType forValue(final String value) { + return Promoter.enumFromString(value, OutputType.values()); + } } + public enum Provider { + TWILIO("twilio"), + AMAZON("amazon"), + OPENAI("openai"); + + private final String value; + + private Provider(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static Provider forValue(final String value) { + return Promoter.enumFromString(value, Provider.values()); + } + } + + /** * Converts a JSON String into a OperatorType object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return OperatorType object represented by the provided JSON */ - public static OperatorType fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static OperatorType fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, OperatorType.class); @@ -75,14 +144,11 @@ public static OperatorType fromJson( * Converts a JSON InputStream into a OperatorType object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return OperatorType object represented by the provided JSON */ - public static OperatorType fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static OperatorType fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, OperatorType.class); @@ -93,114 +159,83 @@ public static OperatorType fromJson( } } - private final String name; - private final String sid; - private final String friendlyName; - private final String description; - private final URI docsLink; - private final OperatorType.OutputType outputType; - private final List supportedLanguages; - private final OperatorType.Provider provider; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final OperatorType.Availability availability; + @Getter + private final Object configSchema; + @Getter private final Boolean configurable; - private final Map configSchema; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; + @Getter + private final String description; + @Getter + private final URI docsLink; + @Getter + private final String friendlyName; + @Getter + private final String name; + @Getter + private final OperatorType.OutputType outputType; + @Getter + private final OperatorType.Provider provider; + @Getter + private final String sid; + @Getter + private final List supportedLanguages; + @Getter private final URI url; @JsonCreator private OperatorType( - @JsonProperty("name") final String name, - @JsonProperty("sid") final String sid, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("description") final String description, - @JsonProperty("docs_link") final URI docsLink, - @JsonProperty("output_type") final OperatorType.OutputType outputType, - @JsonProperty("supported_languages") final List< - String - > supportedLanguages, - @JsonProperty("provider") final OperatorType.Provider provider, - @JsonProperty( - "availability" - ) final OperatorType.Availability availability, - @JsonProperty("configurable") final Boolean configurable, - @JsonProperty("config_schema") final Map configSchema, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("url") final URI url + @JsonProperty("availability") final OperatorType.Availability availability, + @JsonProperty("config_schema") final Object configSchema, + @JsonProperty("configurable") final Boolean configurable, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("description") final String description, + @JsonProperty("docs_link") final URI docsLink, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("name") final String name, + @JsonProperty("output_type") final OperatorType.OutputType outputType, + @JsonProperty("provider") final OperatorType.Provider provider, + @JsonProperty("sid") final String sid, + @JsonProperty("supported_languages") final List supportedLanguages, + @JsonProperty("url") final URI url ) { - this.name = name; - this.sid = sid; - this.friendlyName = friendlyName; + this.availability = availability; + this.configSchema = configSchema; + this.configurable = configurable; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.description = description; this.docsLink = docsLink; + this.friendlyName = friendlyName; + this.name = name; this.outputType = outputType; - this.supportedLanguages = supportedLanguages; this.provider = provider; - this.availability = availability; - this.configurable = configurable; - this.configSchema = configSchema; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); + this.sid = sid; + this.supportedLanguages = supportedLanguages; this.url = url; } - public final String getName() { - return this.name; - } - - public final String getSid() { - return this.sid; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final String getDescription() { - return this.description; - } - - public final URI getDocsLink() { - return this.docsLink; - } - - public final OperatorType.OutputType getOutputType() { - return this.outputType; - } - - public final List getSupportedLanguages() { - return this.supportedLanguages; - } - - public final OperatorType.Provider getProvider() { - return this.provider; - } - - public final OperatorType.Availability getAvailability() { - return this.availability; - } - - public final Boolean getConfigurable() { - return this.configurable; - } - - public final Map getConfigSchema() { - return this.configSchema; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final URI getUrl() { - return this.url; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -212,108 +247,44 @@ public boolean equals(final Object o) { } OperatorType other = (OperatorType) o; - return ( - Objects.equals(name, other.name) && - Objects.equals(sid, other.sid) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(description, other.description) && - Objects.equals(docsLink, other.docsLink) && - Objects.equals(outputType, other.outputType) && - Objects.equals(supportedLanguages, other.supportedLanguages) && - Objects.equals(provider, other.provider) && - Objects.equals(availability, other.availability) && - Objects.equals(configurable, other.configurable) && - Objects.equals(configSchema, other.configSchema) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(url, other.url) + Objects.equals(availability, other.availability) && + Objects.equals(configSchema, other.configSchema) && + Objects.equals(configurable, other.configurable) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(description, other.description) && + Objects.equals(docsLink, other.docsLink) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(name, other.name) && + Objects.equals(outputType, other.outputType) && + Objects.equals(provider, other.provider) && + Objects.equals(sid, other.sid) && + Objects.equals(supportedLanguages, other.supportedLanguages) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - name, - sid, - friendlyName, - description, - docsLink, - outputType, - supportedLanguages, - provider, - availability, - configurable, - configSchema, - dateCreated, - dateUpdated, - url + availability, + configSchema, + configurable, + dateCreated, + dateUpdated, + description, + docsLink, + friendlyName, + name, + outputType, + provider, + sid, + supportedLanguages, + url ); } - public enum Availability { - INTERNAL("internal"), - BETA("beta"), - GENERAL_AVAILABILITY("general-availability"), - RETIRED("retired"), - DEPRECATED("deprecated"); - private final String value; - - private Availability(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static Availability forValue(final String value) { - return Promoter.enumFromString(value, Availability.values()); - } - } - - public enum OutputType { - TEXT_CLASSIFICATION("text-classification"), - TEXT_EXTRACTION("text-extraction"), - TEXT_EXTRACTION_NORMALIZED("text-extraction-normalized"), - TEXT_GENERATION("text-generation"); - - private final String value; - - private OutputType(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static OutputType forValue(final String value) { - return Promoter.enumFromString(value, OutputType.values()); - } - } - - public enum Provider { - TWILIO("twilio"), - AMAZON("amazon"), - OPENAI("openai"); - - private final String value; - - private Provider(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static Provider forValue(final String value) { - return Promoter.enumFromString(value, Provider.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/intelligence/v2/OperatorTypeFetcher.java b/src/main/java/com/twilio/rest/intelligence/v2/OperatorTypeFetcher.java index b24a5e6871..b8fdf0d3bc 100644 --- a/src/main/java/com/twilio/rest/intelligence/v2/OperatorTypeFetcher.java +++ b/src/main/java/com/twilio/rest/intelligence/v2/OperatorTypeFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.intelligence.v2; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,47 +26,41 @@ public class OperatorTypeFetcher extends Fetcher { - private String pathSid; + private String pathsid; - public OperatorTypeFetcher(final String pathSid) { - this.pathSid = pathSid; + public OperatorTypeFetcher(final String pathsid) { + this.pathsid = pathsid; } + @Override public OperatorType fetch(final TwilioRestClient client) { + String path = "/v2/OperatorTypes/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.INTELLIGENCE.toString(), - path + HttpMethod.GET, + Domains.INTELLIGENCE.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "OperatorType fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("OperatorType fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return OperatorType.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return OperatorType.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/intelligence/v2/OperatorTypeReader.java b/src/main/java/com/twilio/rest/intelligence/v2/OperatorTypeReader.java index 2aaa8913f0..51b37cad84 100644 --- a/src/main/java/com/twilio/rest/intelligence/v2/OperatorTypeReader.java +++ b/src/main/java/com/twilio/rest/intelligence/v2/OperatorTypeReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -31,105 +32,83 @@ public class OperatorTypeReader extends Reader { private Long pageSize; - public OperatorTypeReader() {} + public OperatorTypeReader() { + } + public OperatorTypeReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v2/OperatorTypes"; + Request request = new Request( - HttpMethod.GET, - Domains.INTELLIGENCE.toString(), - path + HttpMethod.GET, + Domains.INTELLIGENCE.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "OperatorType read failed: Unable to connect to server" - ); + throw new ApiConnectionException("OperatorType read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "operator_types", - response.getContent(), - OperatorType.class, - client.getObjectMapper() - ); + "operator_types", + response.getContent(), + OperatorType.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.INTELLIGENCE.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.INTELLIGENCE.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/intelligence/v2/PrebuiltOperator.java b/src/main/java/com/twilio/rest/intelligence/v2/PrebuiltOperator.java index c9b414a546..58cf72c192 100644 --- a/src/main/java/com/twilio/rest/intelligence/v2/PrebuiltOperator.java +++ b/src/main/java/com/twilio/rest/intelligence/v2/PrebuiltOperator.java @@ -18,48 +18,73 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; -import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class PrebuiltOperator extends Resource { - private static final long serialVersionUID = 114402468875706L; - public static PrebuiltOperatorFetcher fetcher(final String pathSid) { - return new PrebuiltOperatorFetcher(pathSid); + public static PrebuiltOperatorFetcher fetcher(final String pathsid) { + return new PrebuiltOperatorFetcher( + pathsid + ); } + public static PrebuiltOperatorReader reader() { - return new PrebuiltOperatorReader(); + return new PrebuiltOperatorReader( + + ); } + + public enum Availability { + INTERNAL("internal"), + BETA("beta"), + PUBLIC("public"), + RETIRED("retired"); + + private final String value; + + private Availability(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static Availability forValue(final String value) { + return Promoter.enumFromString(value, Availability.values()); + } + } + + /** * Converts a JSON String into a PrebuiltOperator object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return PrebuiltOperator object represented by the provided JSON */ - public static PrebuiltOperator fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static PrebuiltOperator fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, PrebuiltOperator.class); @@ -74,14 +99,11 @@ public static PrebuiltOperator fromJson( * Converts a JSON InputStream into a PrebuiltOperator object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return PrebuiltOperator object represented by the provided JSON */ - public static PrebuiltOperator fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static PrebuiltOperator fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, PrebuiltOperator.class); @@ -92,96 +114,73 @@ public static PrebuiltOperator fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String sid; - private final String friendlyName; - private final String description; + @Getter private final String author; - private final String operatorType; - private final Integer version; + @Getter private final PrebuiltOperator.Availability availability; - private final Map config; + @Getter + private final Object config; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; + @Getter + private final String description; + @Getter + private final String friendlyName; + @Getter + private final String operatorType; + @Getter + private final String sid; + @Getter private final URI url; + @Getter + private final Integer version; @JsonCreator private PrebuiltOperator( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("sid") final String sid, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("description") final String description, - @JsonProperty("author") final String author, - @JsonProperty("operator_type") final String operatorType, - @JsonProperty("version") final Integer version, - @JsonProperty( - "availability" - ) final PrebuiltOperator.Availability availability, - @JsonProperty("config") final Map config, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("url") final URI url + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("author") final String author, + @JsonProperty("availability") final PrebuiltOperator.Availability availability, + @JsonProperty("config") final Object config, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("description") final String description, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("operator_type") final String operatorType, + @JsonProperty("sid") final String sid, + @JsonProperty("url") final URI url, + @JsonProperty("version") final Integer version ) { this.accountSid = accountSid; - this.sid = sid; - this.friendlyName = friendlyName; - this.description = description; this.author = author; - this.operatorType = operatorType; - this.version = version; this.availability = availability; this.config = config; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; + this.description = description; + this.friendlyName = friendlyName; + this.operatorType = operatorType; + this.sid = sid; this.url = url; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getSid() { - return this.sid; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final String getDescription() { - return this.description; - } - - public final String getAuthor() { - return this.author; - } - - public final String getOperatorType() { - return this.operatorType; - } - - public final Integer getVersion() { - return this.version; - } - - public final PrebuiltOperator.Availability getAvailability() { - return this.availability; - } - - public final Map getConfig() { - return this.config; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final URI getUrl() { - return this.url; + this.version = version; } @Override @@ -195,60 +194,40 @@ public boolean equals(final Object o) { } PrebuiltOperator other = (PrebuiltOperator) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(sid, other.sid) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(description, other.description) && - Objects.equals(author, other.author) && - Objects.equals(operatorType, other.operatorType) && - Objects.equals(version, other.version) && - Objects.equals(availability, other.availability) && - Objects.equals(config, other.config) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(url, other.url) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(author, other.author) && + Objects.equals(availability, other.availability) && + Objects.equals(config, other.config) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(description, other.description) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(operatorType, other.operatorType) && + Objects.equals(sid, other.sid) && + Objects.equals(url, other.url) && + Objects.equals(version, other.version) ); } @Override public int hashCode() { return Objects.hash( - accountSid, - sid, - friendlyName, - description, - author, - operatorType, - version, - availability, - config, - dateCreated, - dateUpdated, - url + accountSid, + author, + availability, + config, + dateCreated, + dateUpdated, + description, + friendlyName, + operatorType, + sid, + url, + version ); } - public enum Availability { - INTERNAL("internal"), - BETA("beta"), - PUBLIC("public"), - RETIRED("retired"); - - private final String value; - private Availability(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static Availability forValue(final String value) { - return Promoter.enumFromString(value, Availability.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/intelligence/v2/PrebuiltOperatorFetcher.java b/src/main/java/com/twilio/rest/intelligence/v2/PrebuiltOperatorFetcher.java index a2da4df081..6acb412c6a 100644 --- a/src/main/java/com/twilio/rest/intelligence/v2/PrebuiltOperatorFetcher.java +++ b/src/main/java/com/twilio/rest/intelligence/v2/PrebuiltOperatorFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.intelligence.v2; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,47 +26,41 @@ public class PrebuiltOperatorFetcher extends Fetcher { - private String pathSid; + private String pathsid; - public PrebuiltOperatorFetcher(final String pathSid) { - this.pathSid = pathSid; + public PrebuiltOperatorFetcher(final String pathsid) { + this.pathsid = pathsid; } + @Override public PrebuiltOperator fetch(final TwilioRestClient client) { + String path = "/v2/Operators/PreBuilt/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.INTELLIGENCE.toString(), - path + HttpMethod.GET, + Domains.INTELLIGENCE.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "PrebuiltOperator fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("PrebuiltOperator fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return PrebuiltOperator.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return PrebuiltOperator.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/intelligence/v2/PrebuiltOperatorReader.java b/src/main/java/com/twilio/rest/intelligence/v2/PrebuiltOperatorReader.java index 4e0b3eb368..1f551bbeb3 100644 --- a/src/main/java/com/twilio/rest/intelligence/v2/PrebuiltOperatorReader.java +++ b/src/main/java/com/twilio/rest/intelligence/v2/PrebuiltOperatorReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -33,123 +34,105 @@ public class PrebuiltOperatorReader extends Reader { private String languageCode; private Long pageSize; - public PrebuiltOperatorReader() {} + public PrebuiltOperatorReader() { + } + - public PrebuiltOperatorReader setAvailability( - final PrebuiltOperator.Availability availability - ) { + public PrebuiltOperatorReader setAvailability(final PrebuiltOperator.Availability availability) { this.availability = availability; return this; } + public PrebuiltOperatorReader setLanguageCode(final String languageCode) { this.languageCode = languageCode; return this; } + public PrebuiltOperatorReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v2/Operators/PreBuilt"; + Request request = new Request( - HttpMethod.GET, - Domains.INTELLIGENCE.toString(), - path + HttpMethod.GET, + Domains.INTELLIGENCE.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "PrebuiltOperator read failed: Unable to connect to server" - ); + throw new ApiConnectionException("PrebuiltOperator read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "operators", - response.getContent(), - PrebuiltOperator.class, - client.getObjectMapper() - ); + "operators", + response.getContent(), + PrebuiltOperator.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.INTELLIGENCE.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.INTELLIGENCE.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (availability != null) { - request.addQueryParam("Availability", availability.toString()); + Serializer.toString(request, "Availability", availability, ParameterType.QUERY); } + + if (languageCode != null) { - request.addQueryParam("LanguageCode", languageCode); + Serializer.toString(request, "LanguageCode", languageCode, ParameterType.QUERY); } + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/intelligence/v2/Service.java b/src/main/java/com/twilio/rest/intelligence/v2/Service.java index 6a14108124..cd2e79dcf7 100644 --- a/src/main/java/com/twilio/rest/intelligence/v2/Service.java +++ b/src/main/java/com/twilio/rest/intelligence/v2/Service.java @@ -18,60 +18,94 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; -import com.twilio.http.HttpMethod; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.List; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Service extends Resource { - private static final long serialVersionUID = 262371223820934L; public static ServiceCreator creator(final String uniqueName) { - return new ServiceCreator(uniqueName); + return new ServiceCreator( + uniqueName + ); } - public static ServiceDeleter deleter(final String pathSid) { - return new ServiceDeleter(pathSid); + + public static ServiceDeleter deleter(final String pathsid) { + return new ServiceDeleter( + pathsid + ); } - public static ServiceFetcher fetcher(final String pathSid) { - return new ServiceFetcher(pathSid); + + public static ServiceFetcher fetcher(final String pathsid) { + return new ServiceFetcher( + pathsid + ); } + public static ServiceReader reader() { - return new ServiceReader(); + return new ServiceReader( + + ); + } + + + public static ServiceUpdater updater(final String pathsid) { + return new ServiceUpdater( + pathsid + ); } - public static ServiceUpdater updater(final String pathSid) { - return new ServiceUpdater(pathSid); + + public enum HttpMethod { + GET("GET"), + POST("POST"), + NULL("NULL"); + + private final String value; + + private HttpMethod(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static HttpMethod forValue(final String value) { + return Promoter.enumFromString(value, HttpMethod.values()); + } } + /** * Converts a JSON String into a Service object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Service object represented by the provided JSON */ - public static Service fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Service fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Service.class); @@ -86,14 +120,11 @@ public static Service fromJson( * Converts a JSON InputStream into a Service object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Service object represented by the provided JSON */ - public static Service fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Service fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Service.class); @@ -104,126 +135,93 @@ public static Service fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; + @Getter private final Boolean autoRedaction; - private final Boolean mediaRedaction; + @Getter private final Boolean autoTranscribe; + @Getter private final Boolean dataLogging; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; + @Getter + private final String encryptionCredentialSid; + @Getter private final String friendlyName; + @Getter private final String languageCode; + @Getter + private final Boolean mediaRedaction; + @Getter + private final List readOnlyAttachedOperatorSids; + @Getter private final String sid; + @Getter private final String uniqueName; + @Getter private final URI url; - private final String webhookUrl; - private final Service.HttpMethod webhookHttpMethod; - private final List readOnlyAttachedOperatorSids; + @Getter private final Integer version; + @Getter + private final Service.HttpMethod webhookHttpMethod; + @Getter + private final String webhookUrl; @JsonCreator private Service( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("auto_redaction") final Boolean autoRedaction, - @JsonProperty("media_redaction") final Boolean mediaRedaction, - @JsonProperty("auto_transcribe") final Boolean autoTranscribe, - @JsonProperty("data_logging") final Boolean dataLogging, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("language_code") final String languageCode, - @JsonProperty("sid") final String sid, - @JsonProperty("unique_name") final String uniqueName, - @JsonProperty("url") final URI url, - @JsonProperty("webhook_url") final String webhookUrl, - @JsonProperty( - "webhook_http_method" - ) final Service.HttpMethod webhookHttpMethod, - @JsonProperty("read_only_attached_operator_sids") final List< - String - > readOnlyAttachedOperatorSids, - @JsonProperty("version") final Integer version + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("auto_redaction") final Boolean autoRedaction, + @JsonProperty("auto_transcribe") final Boolean autoTranscribe, + @JsonProperty("data_logging") final Boolean dataLogging, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("encryption_credential_sid") final String encryptionCredentialSid, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("language_code") final String languageCode, + @JsonProperty("media_redaction") final Boolean mediaRedaction, + @JsonProperty("read_only_attached_operator_sids") final List readOnlyAttachedOperatorSids, + @JsonProperty("sid") final String sid, + @JsonProperty("unique_name") final String uniqueName, + @JsonProperty("url") final URI url, + @JsonProperty("version") final Integer version, + @JsonProperty("webhook_http_method") final Service.HttpMethod webhookHttpMethod, + @JsonProperty("webhook_url") final String webhookUrl ) { this.accountSid = accountSid; this.autoRedaction = autoRedaction; - this.mediaRedaction = mediaRedaction; this.autoTranscribe = autoTranscribe; this.dataLogging = dataLogging; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; + this.encryptionCredentialSid = encryptionCredentialSid; this.friendlyName = friendlyName; this.languageCode = languageCode; + this.mediaRedaction = mediaRedaction; + this.readOnlyAttachedOperatorSids = readOnlyAttachedOperatorSids; this.sid = sid; this.uniqueName = uniqueName; this.url = url; - this.webhookUrl = webhookUrl; - this.webhookHttpMethod = webhookHttpMethod; - this.readOnlyAttachedOperatorSids = readOnlyAttachedOperatorSids; this.version = version; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final Boolean getAutoRedaction() { - return this.autoRedaction; - } - - public final Boolean getMediaRedaction() { - return this.mediaRedaction; - } - - public final Boolean getAutoTranscribe() { - return this.autoTranscribe; - } - - public final Boolean getDataLogging() { - return this.dataLogging; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final String getLanguageCode() { - return this.languageCode; - } - - public final String getSid() { - return this.sid; - } - - public final String getUniqueName() { - return this.uniqueName; - } - - public final URI getUrl() { - return this.url; - } - - public final String getWebhookUrl() { - return this.webhookUrl; - } - - public final Service.HttpMethod getWebhookHttpMethod() { - return this.webhookHttpMethod; - } - - public final List getReadOnlyAttachedOperatorSids() { - return this.readOnlyAttachedOperatorSids; - } - - public final Integer getVersion() { - return this.version; + this.webhookHttpMethod = webhookHttpMethod; + this.webhookUrl = webhookUrl; } @Override @@ -237,70 +235,50 @@ public boolean equals(final Object o) { } Service other = (Service) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(autoRedaction, other.autoRedaction) && - Objects.equals(mediaRedaction, other.mediaRedaction) && - Objects.equals(autoTranscribe, other.autoTranscribe) && - Objects.equals(dataLogging, other.dataLogging) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(languageCode, other.languageCode) && - Objects.equals(sid, other.sid) && - Objects.equals(uniqueName, other.uniqueName) && - Objects.equals(url, other.url) && - Objects.equals(webhookUrl, other.webhookUrl) && - Objects.equals(webhookHttpMethod, other.webhookHttpMethod) && - Objects.equals( - readOnlyAttachedOperatorSids, - other.readOnlyAttachedOperatorSids - ) && - Objects.equals(version, other.version) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(autoRedaction, other.autoRedaction) && + Objects.equals(autoTranscribe, other.autoTranscribe) && + Objects.equals(dataLogging, other.dataLogging) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(encryptionCredentialSid, other.encryptionCredentialSid) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(languageCode, other.languageCode) && + Objects.equals(mediaRedaction, other.mediaRedaction) && + Objects.equals(readOnlyAttachedOperatorSids, other.readOnlyAttachedOperatorSids) && + Objects.equals(sid, other.sid) && + Objects.equals(uniqueName, other.uniqueName) && + Objects.equals(url, other.url) && + Objects.equals(version, other.version) && + Objects.equals(webhookHttpMethod, other.webhookHttpMethod) && + Objects.equals(webhookUrl, other.webhookUrl) ); } @Override public int hashCode() { return Objects.hash( - accountSid, - autoRedaction, - mediaRedaction, - autoTranscribe, - dataLogging, - dateCreated, - dateUpdated, - friendlyName, - languageCode, - sid, - uniqueName, - url, - webhookUrl, - webhookHttpMethod, - readOnlyAttachedOperatorSids, - version + accountSid, + autoRedaction, + autoTranscribe, + dataLogging, + dateCreated, + dateUpdated, + encryptionCredentialSid, + friendlyName, + languageCode, + mediaRedaction, + readOnlyAttachedOperatorSids, + sid, + uniqueName, + url, + version, + webhookHttpMethod, + webhookUrl ); } - public enum HttpMethod { - GET("GET"), - POST("POST"), - NULL("NULL"); - - private final String value; - private HttpMethod(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static HttpMethod forValue(final String value) { - return Promoter.enumFromString(value, HttpMethod.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/intelligence/v2/ServiceCreator.java b/src/main/java/com/twilio/rest/intelligence/v2/ServiceCreator.java index 9d7496a11c..39a6173a43 100644 --- a/src/main/java/com/twilio/rest/intelligence/v2/ServiceCreator.java +++ b/src/main/java/com/twilio/rest/intelligence/v2/ServiceCreator.java @@ -14,8 +14,11 @@ package com.twilio.rest.intelligence.v2; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -36,87 +39,98 @@ public class ServiceCreator extends Creator { private Boolean mediaRedaction; private String webhookUrl; private Service.HttpMethod webhookHttpMethod; + private String encryptionCredentialSid; public ServiceCreator(final String uniqueName) { this.uniqueName = uniqueName; } + public ServiceCreator setUniqueName(final String uniqueName) { this.uniqueName = uniqueName; return this; } + public ServiceCreator setAutoTranscribe(final Boolean autoTranscribe) { this.autoTranscribe = autoTranscribe; return this; } + public ServiceCreator setDataLogging(final Boolean dataLogging) { this.dataLogging = dataLogging; return this; } + public ServiceCreator setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + public ServiceCreator setLanguageCode(final String languageCode) { this.languageCode = languageCode; return this; } + public ServiceCreator setAutoRedaction(final Boolean autoRedaction) { this.autoRedaction = autoRedaction; return this; } + public ServiceCreator setMediaRedaction(final Boolean mediaRedaction) { this.mediaRedaction = mediaRedaction; return this; } + public ServiceCreator setWebhookUrl(final String webhookUrl) { this.webhookUrl = webhookUrl; return this; } - public ServiceCreator setWebhookHttpMethod( - final Service.HttpMethod webhookHttpMethod - ) { + + public ServiceCreator setWebhookHttpMethod(final Service.HttpMethod webhookHttpMethod) { this.webhookHttpMethod = webhookHttpMethod; return this; } + + public ServiceCreator setEncryptionCredentialSid(final String encryptionCredentialSid) { + this.encryptionCredentialSid = encryptionCredentialSid; + return this; + } + + @Override public Service create(final TwilioRestClient client) { + String path = "/v2/Services"; - path = - path.replace("{" + "UniqueName" + "}", this.uniqueName.toString()); Request request = new Request( - HttpMethod.POST, - Domains.INTELLIGENCE.toString(), - path + HttpMethod.POST, + Domains.INTELLIGENCE.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Service creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("Service creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -125,35 +139,56 @@ public Service create(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (uniqueName != null) { - request.addPostParam("UniqueName", uniqueName); + Serializer.toString(request, "UniqueName", uniqueName, ParameterType.URLENCODED); } + + if (autoTranscribe != null) { - request.addPostParam("AutoTranscribe", autoTranscribe.toString()); + Serializer.toString(request, "AutoTranscribe", autoTranscribe, ParameterType.URLENCODED); } + + if (dataLogging != null) { - request.addPostParam("DataLogging", dataLogging.toString()); + Serializer.toString(request, "DataLogging", dataLogging, ParameterType.URLENCODED); } + + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + if (languageCode != null) { - request.addPostParam("LanguageCode", languageCode); + Serializer.toString(request, "LanguageCode", languageCode, ParameterType.URLENCODED); } + + if (autoRedaction != null) { - request.addPostParam("AutoRedaction", autoRedaction.toString()); + Serializer.toString(request, "AutoRedaction", autoRedaction, ParameterType.URLENCODED); } + + if (mediaRedaction != null) { - request.addPostParam("MediaRedaction", mediaRedaction.toString()); + Serializer.toString(request, "MediaRedaction", mediaRedaction, ParameterType.URLENCODED); } + + if (webhookUrl != null) { - request.addPostParam("WebhookUrl", webhookUrl); + Serializer.toString(request, "WebhookUrl", webhookUrl, ParameterType.URLENCODED); } + + if (webhookHttpMethod != null) { - request.addPostParam( - "WebhookHttpMethod", - webhookHttpMethod.toString() - ); + Serializer.toString(request, "WebhookHttpMethod", webhookHttpMethod, ParameterType.URLENCODED); } + + + if (encryptionCredentialSid != null) { + Serializer.toString(request, "EncryptionCredentialSid", encryptionCredentialSid, ParameterType.URLENCODED); + } + + } } diff --git a/src/main/java/com/twilio/rest/intelligence/v2/ServiceDeleter.java b/src/main/java/com/twilio/rest/intelligence/v2/ServiceDeleter.java index a67deec222..c84a48577d 100644 --- a/src/main/java/com/twilio/rest/intelligence/v2/ServiceDeleter.java +++ b/src/main/java/com/twilio/rest/intelligence/v2/ServiceDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.intelligence.v2; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,40 +26,38 @@ public class ServiceDeleter extends Deleter { - private String pathSid; + private String pathsid; - public ServiceDeleter(final String pathSid) { - this.pathSid = pathSid; + public ServiceDeleter(final String pathsid) { + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/v2/Services/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.INTELLIGENCE.toString(), - path + HttpMethod.DELETE, + Domains.INTELLIGENCE.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Service delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("Service delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/intelligence/v2/ServiceFetcher.java b/src/main/java/com/twilio/rest/intelligence/v2/ServiceFetcher.java index 6fe8481693..23f1f29d87 100644 --- a/src/main/java/com/twilio/rest/intelligence/v2/ServiceFetcher.java +++ b/src/main/java/com/twilio/rest/intelligence/v2/ServiceFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.intelligence.v2; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,44 +26,41 @@ public class ServiceFetcher extends Fetcher { - private String pathSid; + private String pathsid; - public ServiceFetcher(final String pathSid) { - this.pathSid = pathSid; + public ServiceFetcher(final String pathsid) { + this.pathsid = pathsid; } + @Override public Service fetch(final TwilioRestClient client) { + String path = "/v2/Services/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.INTELLIGENCE.toString(), - path + HttpMethod.GET, + Domains.INTELLIGENCE.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Service fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Service fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Service.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/intelligence/v2/ServiceReader.java b/src/main/java/com/twilio/rest/intelligence/v2/ServiceReader.java index 55d6ef3302..21ed74df19 100644 --- a/src/main/java/com/twilio/rest/intelligence/v2/ServiceReader.java +++ b/src/main/java/com/twilio/rest/intelligence/v2/ServiceReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -31,105 +32,83 @@ public class ServiceReader extends Reader { private Long pageSize; - public ServiceReader() {} + public ServiceReader() { + } + public ServiceReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v2/Services"; + Request request = new Request( - HttpMethod.GET, - Domains.INTELLIGENCE.toString(), - path + HttpMethod.GET, + Domains.INTELLIGENCE.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Service read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Service read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "services", - response.getContent(), - Service.class, - client.getObjectMapper() - ); + "services", + response.getContent(), + Service.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.INTELLIGENCE.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.INTELLIGENCE.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/intelligence/v2/ServiceUpdater.java b/src/main/java/com/twilio/rest/intelligence/v2/ServiceUpdater.java index e0b577bb75..9d32d10ec5 100644 --- a/src/main/java/com/twilio/rest/intelligence/v2/ServiceUpdater.java +++ b/src/main/java/com/twilio/rest/intelligence/v2/ServiceUpdater.java @@ -16,6 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -26,8 +28,7 @@ import com.twilio.rest.Domains; public class ServiceUpdater extends Updater { - - private String pathSid; + private String pathsid; private String ifMatch; private Boolean autoTranscribe; private Boolean dataLogging; @@ -37,87 +38,101 @@ public class ServiceUpdater extends Updater { private Boolean mediaRedaction; private String webhookUrl; private Service.HttpMethod webhookHttpMethod; + private String encryptionCredentialSid; - public ServiceUpdater(final String pathSid) { - this.pathSid = pathSid; + public ServiceUpdater(final String pathsid) { + this.pathsid = pathsid; } - public ServiceUpdater setIfMatch(final String ifMatch) { - this.ifMatch = ifMatch; - return this; - } public ServiceUpdater setAutoTranscribe(final Boolean autoTranscribe) { this.autoTranscribe = autoTranscribe; return this; } + public ServiceUpdater setDataLogging(final Boolean dataLogging) { this.dataLogging = dataLogging; return this; } + public ServiceUpdater setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + public ServiceUpdater setUniqueName(final String uniqueName) { this.uniqueName = uniqueName; return this; } + public ServiceUpdater setAutoRedaction(final Boolean autoRedaction) { this.autoRedaction = autoRedaction; return this; } + public ServiceUpdater setMediaRedaction(final Boolean mediaRedaction) { this.mediaRedaction = mediaRedaction; return this; } + public ServiceUpdater setWebhookUrl(final String webhookUrl) { this.webhookUrl = webhookUrl; return this; } - public ServiceUpdater setWebhookHttpMethod( - final Service.HttpMethod webhookHttpMethod - ) { + + public ServiceUpdater setWebhookHttpMethod(final Service.HttpMethod webhookHttpMethod) { this.webhookHttpMethod = webhookHttpMethod; return this; } + + public ServiceUpdater setEncryptionCredentialSid(final String encryptionCredentialSid) { + this.encryptionCredentialSid = encryptionCredentialSid; + return this; + } + + + public ServiceUpdater setIfMatch(final String ifMatch) { + this.ifMatch = ifMatch; + return this; + } + + @Override public Service update(final TwilioRestClient client) { + String path = "/v2/Services/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.INTELLIGENCE.toString(), - path + HttpMethod.POST, + Domains.INTELLIGENCE.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); - addPostParams(request); addHeaderParams(request); + addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Service update failed: Unable to connect to server" - ); + throw new ApiConnectionException("Service update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -126,38 +141,59 @@ public Service update(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (autoTranscribe != null) { - request.addPostParam("AutoTranscribe", autoTranscribe.toString()); + Serializer.toString(request, "AutoTranscribe", autoTranscribe, ParameterType.URLENCODED); } + + if (dataLogging != null) { - request.addPostParam("DataLogging", dataLogging.toString()); + Serializer.toString(request, "DataLogging", dataLogging, ParameterType.URLENCODED); } + + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + if (uniqueName != null) { - request.addPostParam("UniqueName", uniqueName); + Serializer.toString(request, "UniqueName", uniqueName, ParameterType.URLENCODED); } + + if (autoRedaction != null) { - request.addPostParam("AutoRedaction", autoRedaction.toString()); + Serializer.toString(request, "AutoRedaction", autoRedaction, ParameterType.URLENCODED); } + + if (mediaRedaction != null) { - request.addPostParam("MediaRedaction", mediaRedaction.toString()); + Serializer.toString(request, "MediaRedaction", mediaRedaction, ParameterType.URLENCODED); } + + if (webhookUrl != null) { - request.addPostParam("WebhookUrl", webhookUrl); + Serializer.toString(request, "WebhookUrl", webhookUrl, ParameterType.URLENCODED); } + + if (webhookHttpMethod != null) { - request.addPostParam( - "WebhookHttpMethod", - webhookHttpMethod.toString() - ); + Serializer.toString(request, "WebhookHttpMethod", webhookHttpMethod, ParameterType.URLENCODED); } + + + if (encryptionCredentialSid != null) { + Serializer.toString(request, "EncryptionCredentialSid", encryptionCredentialSid, ParameterType.URLENCODED); + } + + } private void addHeaderParams(final Request request) { + if (ifMatch != null) { - request.addHeaderParam("If-Match", ifMatch); + Serializer.toString(request, "If-Match", ifMatch, ParameterType.HEADER); } + } } diff --git a/src/main/java/com/twilio/rest/intelligence/v2/Transcript.java b/src/main/java/com/twilio/rest/intelligence/v2/Transcript.java index 0e19d311a1..762a19d13e 100644 --- a/src/main/java/com/twilio/rest/intelligence/v2/Transcript.java +++ b/src/main/java/com/twilio/rest/intelligence/v2/Transcript.java @@ -18,59 +18,89 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Transcript extends Resource { - private static final long serialVersionUID = 35462753187463L; - public static TranscriptCreator creator( - final String serviceSid, - final Object channel - ) { - return new TranscriptCreator(serviceSid, channel); + public static TranscriptCreator creator(final String serviceSid, final Object channel) { + return new TranscriptCreator( + serviceSid, channel + ); } - public static TranscriptDeleter deleter(final String pathSid) { - return new TranscriptDeleter(pathSid); + + public static TranscriptDeleter deleter(final String pathsid) { + return new TranscriptDeleter( + pathsid + ); } - public static TranscriptFetcher fetcher(final String pathSid) { - return new TranscriptFetcher(pathSid); + + public static TranscriptFetcher fetcher(final String pathsid) { + return new TranscriptFetcher( + pathsid + ); } + public static TranscriptReader reader() { - return new TranscriptReader(); + return new TranscriptReader( + + ); } + + public enum Status { + QUEUED("queued"), + IN_PROGRESS("in-progress"), + COMPLETED("completed"), + FAILED("failed"), + CANCELED("canceled"); + + private final String value; + + private Status(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static Status forValue(final String value) { + return Promoter.enumFromString(value, Status.values()); + } + } + + /** * Converts a JSON String into a Transcript object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Transcript object represented by the provided JSON */ - public static Transcript fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Transcript fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Transcript.class); @@ -85,14 +115,11 @@ public static Transcript fromJson( * Converts a JSON InputStream into a Transcript object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Transcript object represented by the provided JSON */ - public static Transcript fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Transcript fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Transcript.class); @@ -103,116 +130,90 @@ public static Transcript fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String serviceSid; - private final String sid; + @Getter + private final Object channel; + @Getter + private final String customerKey; + @Getter + private final Boolean dataLogging; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; - private final Transcript.Status status; - private final Map channel; - private final Boolean dataLogging; + @Getter + private final Integer duration; + @Getter + private final String encryptionCredentialSid; + @Getter private final String languageCode; - private final String customerKey; + @Getter + private final Map links; + @Getter private final ZonedDateTime mediaStartTime; - private final Integer duration; - private final URI url; + @Getter private final Boolean redaction; - private final Map links; + @Getter + private final String serviceSid; + @Getter + private final String sid; + @Getter + private final Transcript.Status status; + @Getter + private final URI url; @JsonCreator private Transcript( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("service_sid") final String serviceSid, - @JsonProperty("sid") final String sid, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("status") final Transcript.Status status, - @JsonProperty("channel") final Map channel, - @JsonProperty("data_logging") final Boolean dataLogging, - @JsonProperty("language_code") final String languageCode, - @JsonProperty("customer_key") final String customerKey, - @JsonProperty("media_start_time") final String mediaStartTime, - @JsonProperty("duration") final Integer duration, - @JsonProperty("url") final URI url, - @JsonProperty("redaction") final Boolean redaction, - @JsonProperty("links") final Map links + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("channel") final Object channel, + @JsonProperty("customer_key") final String customerKey, + @JsonProperty("data_logging") final Boolean dataLogging, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("duration") final Integer duration, + @JsonProperty("encryption_credential_sid") final String encryptionCredentialSid, + @JsonProperty("language_code") final String languageCode, + @JsonProperty("links") final Map links, + @JsonProperty("media_start_time") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime mediaStartTime, + @JsonProperty("redaction") final Boolean redaction, + @JsonProperty("service_sid") final String serviceSid, + @JsonProperty("sid") final String sid, + @JsonProperty("status") final Transcript.Status status, + @JsonProperty("url") final URI url ) { this.accountSid = accountSid; - this.serviceSid = serviceSid; - this.sid = sid; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); - this.status = status; this.channel = channel; - this.dataLogging = dataLogging; - this.languageCode = languageCode; this.customerKey = customerKey; - this.mediaStartTime = - DateConverter.iso8601DateTimeFromString(mediaStartTime); + this.dataLogging = dataLogging; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.duration = duration; - this.url = url; - this.redaction = redaction; + this.encryptionCredentialSid = encryptionCredentialSid; + this.languageCode = languageCode; this.links = links; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getServiceSid() { - return this.serviceSid; - } - - public final String getSid() { - return this.sid; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final Transcript.Status getStatus() { - return this.status; - } - - public final Map getChannel() { - return this.channel; - } - - public final Boolean getDataLogging() { - return this.dataLogging; - } - - public final String getLanguageCode() { - return this.languageCode; - } - - public final String getCustomerKey() { - return this.customerKey; - } - - public final ZonedDateTime getMediaStartTime() { - return this.mediaStartTime; - } - - public final Integer getDuration() { - return this.duration; - } - - public final URI getUrl() { - return this.url; - } - - public final Boolean getRedaction() { - return this.redaction; - } - - public final Map getLinks() { - return this.links; + this.mediaStartTime = mediaStartTime; + this.redaction = redaction; + this.serviceSid = serviceSid; + this.sid = sid; + this.status = status; + this.url = url; } @Override @@ -226,67 +227,48 @@ public boolean equals(final Object o) { } Transcript other = (Transcript) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(serviceSid, other.serviceSid) && - Objects.equals(sid, other.sid) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(status, other.status) && - Objects.equals(channel, other.channel) && - Objects.equals(dataLogging, other.dataLogging) && - Objects.equals(languageCode, other.languageCode) && - Objects.equals(customerKey, other.customerKey) && - Objects.equals(mediaStartTime, other.mediaStartTime) && - Objects.equals(duration, other.duration) && - Objects.equals(url, other.url) && - Objects.equals(redaction, other.redaction) && - Objects.equals(links, other.links) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(channel, other.channel) && + Objects.equals(customerKey, other.customerKey) && + Objects.equals(dataLogging, other.dataLogging) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(duration, other.duration) && + Objects.equals(encryptionCredentialSid, other.encryptionCredentialSid) && + Objects.equals(languageCode, other.languageCode) && + Objects.equals(links, other.links) && + Objects.equals(mediaStartTime, other.mediaStartTime) && + Objects.equals(redaction, other.redaction) && + Objects.equals(serviceSid, other.serviceSid) && + Objects.equals(sid, other.sid) && + Objects.equals(status, other.status) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - accountSid, - serviceSid, - sid, - dateCreated, - dateUpdated, - status, - channel, - dataLogging, - languageCode, - customerKey, - mediaStartTime, - duration, - url, - redaction, - links + accountSid, + channel, + customerKey, + dataLogging, + dateCreated, + dateUpdated, + duration, + encryptionCredentialSid, + languageCode, + links, + mediaStartTime, + redaction, + serviceSid, + sid, + status, + url ); } - public enum Status { - QUEUED("queued"), - IN_PROGRESS("in-progress"), - COMPLETED("completed"), - FAILED("failed"), - CANCELED("canceled"); - private final String value; - - private Status(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static Status forValue(final String value) { - return Promoter.enumFromString(value, Status.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/intelligence/v2/TranscriptCreator.java b/src/main/java/com/twilio/rest/intelligence/v2/TranscriptCreator.java index 7a9249f442..2427b61cc7 100644 --- a/src/main/java/com/twilio/rest/intelligence/v2/TranscriptCreator.java +++ b/src/main/java/com/twilio/rest/intelligence/v2/TranscriptCreator.java @@ -14,10 +14,11 @@ package com.twilio.rest.intelligence.v2; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; -import com.twilio.converter.Converter; -import com.twilio.converter.Converter; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -26,6 +27,7 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.time.ZonedDateTime; public class TranscriptCreator extends Creator { @@ -40,83 +42,84 @@ public TranscriptCreator(final String serviceSid, final Object channel) { this.channel = channel; } + public TranscriptCreator setServiceSid(final String serviceSid) { this.serviceSid = serviceSid; return this; } + public TranscriptCreator setChannel(final Object channel) { this.channel = channel; return this; } + public TranscriptCreator setCustomerKey(final String customerKey) { this.customerKey = customerKey; return this; } - public TranscriptCreator setMediaStartTime( - final ZonedDateTime mediaStartTime - ) { + + public TranscriptCreator setMediaStartTime(final ZonedDateTime mediaStartTime) { this.mediaStartTime = mediaStartTime; return this; } + @Override public Transcript create(final TwilioRestClient client) { + String path = "/v2/Transcripts"; - path = - path.replace("{" + "ServiceSid" + "}", this.serviceSid.toString()); - path = path.replace("{" + "Channel" + "}", this.channel.toString()); Request request = new Request( - HttpMethod.POST, - Domains.INTELLIGENCE.toString(), - path + HttpMethod.POST, + Domains.INTELLIGENCE.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Transcript creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("Transcript creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Transcript.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Transcript.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (serviceSid != null) { - request.addPostParam("ServiceSid", serviceSid); + Serializer.toString(request, "ServiceSid", serviceSid, ParameterType.URLENCODED); } + + if (channel != null) { - request.addPostParam("Channel", Converter.objectToJson(channel)); + Serializer.toString(request, "Channel", channel, ParameterType.URLENCODED); } + + if (customerKey != null) { - request.addPostParam("CustomerKey", customerKey); + Serializer.toString(request, "CustomerKey", customerKey, ParameterType.URLENCODED); } + + if (mediaStartTime != null) { - request.addPostParam( - "MediaStartTime", - mediaStartTime.toInstant().toString() - ); + Serializer.toString(request, "MediaStartTime", mediaStartTime, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/intelligence/v2/TranscriptDeleter.java b/src/main/java/com/twilio/rest/intelligence/v2/TranscriptDeleter.java index 994e3b40cb..fc5586099d 100644 --- a/src/main/java/com/twilio/rest/intelligence/v2/TranscriptDeleter.java +++ b/src/main/java/com/twilio/rest/intelligence/v2/TranscriptDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.intelligence.v2; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,40 +26,38 @@ public class TranscriptDeleter extends Deleter { - private String pathSid; + private String pathsid; - public TranscriptDeleter(final String pathSid) { - this.pathSid = pathSid; + public TranscriptDeleter(final String pathsid) { + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/v2/Transcripts/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.INTELLIGENCE.toString(), - path + HttpMethod.DELETE, + Domains.INTELLIGENCE.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Transcript delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("Transcript delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/intelligence/v2/TranscriptFetcher.java b/src/main/java/com/twilio/rest/intelligence/v2/TranscriptFetcher.java index 93fdf166c5..38dcb79f55 100644 --- a/src/main/java/com/twilio/rest/intelligence/v2/TranscriptFetcher.java +++ b/src/main/java/com/twilio/rest/intelligence/v2/TranscriptFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.intelligence.v2; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,47 +26,41 @@ public class TranscriptFetcher extends Fetcher { - private String pathSid; + private String pathsid; - public TranscriptFetcher(final String pathSid) { - this.pathSid = pathSid; + public TranscriptFetcher(final String pathsid) { + this.pathsid = pathsid; } + @Override public Transcript fetch(final TwilioRestClient client) { + String path = "/v2/Transcripts/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.INTELLIGENCE.toString(), - path + HttpMethod.GET, + Domains.INTELLIGENCE.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Transcript fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Transcript fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return Transcript.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Transcript.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/intelligence/v2/TranscriptReader.java b/src/main/java/com/twilio/rest/intelligence/v2/TranscriptReader.java index 20269f2065..b90b202c8d 100644 --- a/src/main/java/com/twilio/rest/intelligence/v2/TranscriptReader.java +++ b/src/main/java/com/twilio/rest/intelligence/v2/TranscriptReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -39,171 +40,171 @@ public class TranscriptReader extends Reader { private String sourceSid; private Long pageSize; - public TranscriptReader() {} + public TranscriptReader() { + } + public TranscriptReader setServiceSid(final String serviceSid) { this.serviceSid = serviceSid; return this; } + public TranscriptReader setBeforeStartTime(final String beforeStartTime) { this.beforeStartTime = beforeStartTime; return this; } + public TranscriptReader setAfterStartTime(final String afterStartTime) { this.afterStartTime = afterStartTime; return this; } - public TranscriptReader setBeforeDateCreated( - final String beforeDateCreated - ) { + + public TranscriptReader setBeforeDateCreated(final String beforeDateCreated) { this.beforeDateCreated = beforeDateCreated; return this; } + public TranscriptReader setAfterDateCreated(final String afterDateCreated) { this.afterDateCreated = afterDateCreated; return this; } + public TranscriptReader setStatus(final String status) { this.status = status; return this; } + public TranscriptReader setLanguageCode(final String languageCode) { this.languageCode = languageCode; return this; } + public TranscriptReader setSourceSid(final String sourceSid) { this.sourceSid = sourceSid; return this; } + public TranscriptReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v2/Transcripts"; + Request request = new Request( - HttpMethod.GET, - Domains.INTELLIGENCE.toString(), - path + HttpMethod.GET, + Domains.INTELLIGENCE.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Transcript read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Transcript read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "transcripts", - response.getContent(), - Transcript.class, - client.getObjectMapper() - ); + "transcripts", + response.getContent(), + Transcript.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.INTELLIGENCE.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.INTELLIGENCE.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (serviceSid != null) { - request.addQueryParam("ServiceSid", serviceSid); + Serializer.toString(request, "ServiceSid", serviceSid, ParameterType.QUERY); } + + if (beforeStartTime != null) { - request.addQueryParam("BeforeStartTime", beforeStartTime); + Serializer.toString(request, "BeforeStartTime", beforeStartTime, ParameterType.QUERY); } + + if (afterStartTime != null) { - request.addQueryParam("AfterStartTime", afterStartTime); + Serializer.toString(request, "AfterStartTime", afterStartTime, ParameterType.QUERY); } + + if (beforeDateCreated != null) { - request.addQueryParam("BeforeDateCreated", beforeDateCreated); + Serializer.toString(request, "BeforeDateCreated", beforeDateCreated, ParameterType.QUERY); } + + if (afterDateCreated != null) { - request.addQueryParam("AfterDateCreated", afterDateCreated); + Serializer.toString(request, "AfterDateCreated", afterDateCreated, ParameterType.QUERY); } + + if (status != null) { - request.addQueryParam("Status", status); + Serializer.toString(request, "Status", status, ParameterType.QUERY); } + + if (languageCode != null) { - request.addQueryParam("LanguageCode", languageCode); + Serializer.toString(request, "LanguageCode", languageCode, ParameterType.QUERY); } + + if (sourceSid != null) { - request.addQueryParam("SourceSid", sourceSid); + Serializer.toString(request, "SourceSid", sourceSid, ParameterType.QUERY); } + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/intelligence/v2/transcript/EncryptedOperatorResults.java b/src/main/java/com/twilio/rest/intelligence/v2/transcript/EncryptedOperatorResults.java new file mode 100644 index 0000000000..c05ccefb24 --- /dev/null +++ b/src/main/java/com/twilio/rest/intelligence/v2/transcript/EncryptedOperatorResults.java @@ -0,0 +1,145 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Intelligence + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package com.twilio.rest.intelligence.v2.transcript; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.twilio.base.Resource; +import com.twilio.exception.ApiConnectionException; +import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + +import java.io.IOException; +import java.io.InputStream; +import java.net.URI; +import java.util.List; +import java.util.Objects; + +@JsonIgnoreProperties(ignoreUnknown = true) +@ToString +public class EncryptedOperatorResults extends Resource { + + + public static EncryptedOperatorResultsFetcher fetcher(final String pathtranscriptSid) { + return new EncryptedOperatorResultsFetcher( + pathtranscriptSid + ); + } + + + /** + * Converts a JSON String into a EncryptedOperatorResults object using the provided ObjectMapper. + * + * @param json Raw JSON String + * @param objectMapper Jackson ObjectMapper + * @return EncryptedOperatorResults object represented by the provided JSON + */ + public static EncryptedOperatorResults fromJson(final String json, final ObjectMapper objectMapper) { + // Convert all checked exceptions to Runtime + try { + return objectMapper.readValue(json, EncryptedOperatorResults.class); + } catch (final JsonMappingException | JsonParseException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + /** + * Converts a JSON InputStream into a EncryptedOperatorResults object using the provided + * ObjectMapper. + * + * @param json Raw JSON InputStream + * @param objectMapper Jackson ObjectMapper + * @return EncryptedOperatorResults object represented by the provided JSON + */ + public static EncryptedOperatorResults fromJson(final InputStream json, final ObjectMapper objectMapper) { + // Convert all checked exceptions to Runtime + try { + return objectMapper.readValue(json, EncryptedOperatorResults.class); + } catch (final JsonMappingException | JsonParseException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter + private final List locations; + @Getter + private final String transcriptSid; + @Getter + private final URI url; + + @JsonCreator + private EncryptedOperatorResults( + @JsonProperty("locations") final List locations, + @JsonProperty("transcript_sid") final String transcriptSid, + @JsonProperty("url") final URI url + ) { + this.locations = locations; + this.transcriptSid = transcriptSid; + this.url = url; + } + + @Override + public boolean equals(final Object o) { + if (this == o) { + return true; + } + + if (o == null || getClass() != o.getClass()) { + return false; + } + + EncryptedOperatorResults other = (EncryptedOperatorResults) o; + return ( + Objects.equals(locations, other.locations) && + Objects.equals(transcriptSid, other.transcriptSid) && + Objects.equals(url, other.url) + ); + } + + @Override + public int hashCode() { + return Objects.hash( + locations, + transcriptSid, + url + ); + } + + +} + diff --git a/src/main/java/com/twilio/rest/intelligence/v2/transcript/EncryptedOperatorResultsFetcher.java b/src/main/java/com/twilio/rest/intelligence/v2/transcript/EncryptedOperatorResultsFetcher.java new file mode 100644 index 0000000000..d48f1fd31e --- /dev/null +++ b/src/main/java/com/twilio/rest/intelligence/v2/transcript/EncryptedOperatorResultsFetcher.java @@ -0,0 +1,86 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Intelligence + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package com.twilio.rest.intelligence.v2.transcript; + +import com.twilio.base.Fetcher; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; +import com.twilio.exception.ApiConnectionException; +import com.twilio.exception.ApiException; +import com.twilio.exception.RestException; +import com.twilio.http.HttpMethod; +import com.twilio.http.Request; +import com.twilio.http.Response; +import com.twilio.http.TwilioRestClient; +import com.twilio.rest.Domains; + +public class EncryptedOperatorResultsFetcher extends Fetcher { + + private String pathtranscriptSid; + private Boolean redacted; + + public EncryptedOperatorResultsFetcher(final String pathtranscriptSid) { + this.pathtranscriptSid = pathtranscriptSid; + } + + + public EncryptedOperatorResultsFetcher setRedacted(final Boolean redacted) { + this.redacted = redacted; + return this; + } + + + @Override + public EncryptedOperatorResults fetch(final TwilioRestClient client) { + + String path = "/v2/Transcripts/{TranscriptSid}/OperatorResults/Encrypted"; + + path = path.replace("{" + "TranscriptSid" + "}", this.pathtranscriptSid.toString()); + + + Request request = new Request( + HttpMethod.GET, + Domains.INTELLIGENCE.toString(), + path + ); + addQueryParams(request); + + Response response = client.request(request); + + if (response == null) { + throw new ApiConnectionException("EncryptedOperatorResults fetch failed: Unable to connect to server"); + } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { + RestException restException = RestException.fromJson( + response.getStream(), + client.getObjectMapper() + ); + if (restException == null) { + throw new ApiException("Server Error, no content", response.getStatusCode()); + } + throw new ApiException(restException); + } + return EncryptedOperatorResults.fromJson(response.getStream(), client.getObjectMapper()); + } + + private void addQueryParams(final Request request) { + + + if (redacted != null) { + Serializer.toString(request, "Redacted", redacted, ParameterType.QUERY); + } + + + } +} diff --git a/src/main/java/com/twilio/rest/intelligence/v2/transcript/EncryptedSentences.java b/src/main/java/com/twilio/rest/intelligence/v2/transcript/EncryptedSentences.java new file mode 100644 index 0000000000..67430770cf --- /dev/null +++ b/src/main/java/com/twilio/rest/intelligence/v2/transcript/EncryptedSentences.java @@ -0,0 +1,144 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Intelligence + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package com.twilio.rest.intelligence.v2.transcript; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.twilio.base.Resource; +import com.twilio.exception.ApiConnectionException; +import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + +import java.io.IOException; +import java.io.InputStream; +import java.net.URI; +import java.util.Objects; + +@JsonIgnoreProperties(ignoreUnknown = true) +@ToString +public class EncryptedSentences extends Resource { + + + public static EncryptedSentencesFetcher fetcher(final String pathtranscriptSid) { + return new EncryptedSentencesFetcher( + pathtranscriptSid + ); + } + + + /** + * Converts a JSON String into a EncryptedSentences object using the provided ObjectMapper. + * + * @param json Raw JSON String + * @param objectMapper Jackson ObjectMapper + * @return EncryptedSentences object represented by the provided JSON + */ + public static EncryptedSentences fromJson(final String json, final ObjectMapper objectMapper) { + // Convert all checked exceptions to Runtime + try { + return objectMapper.readValue(json, EncryptedSentences.class); + } catch (final JsonMappingException | JsonParseException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + /** + * Converts a JSON InputStream into a EncryptedSentences object using the provided + * ObjectMapper. + * + * @param json Raw JSON InputStream + * @param objectMapper Jackson ObjectMapper + * @return EncryptedSentences object represented by the provided JSON + */ + public static EncryptedSentences fromJson(final InputStream json, final ObjectMapper objectMapper) { + // Convert all checked exceptions to Runtime + try { + return objectMapper.readValue(json, EncryptedSentences.class); + } catch (final JsonMappingException | JsonParseException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter + private final URI location; + @Getter + private final String transcriptSid; + @Getter + private final URI url; + + @JsonCreator + private EncryptedSentences( + @JsonProperty("location") final URI location, + @JsonProperty("transcript_sid") final String transcriptSid, + @JsonProperty("url") final URI url + ) { + this.location = location; + this.transcriptSid = transcriptSid; + this.url = url; + } + + @Override + public boolean equals(final Object o) { + if (this == o) { + return true; + } + + if (o == null || getClass() != o.getClass()) { + return false; + } + + EncryptedSentences other = (EncryptedSentences) o; + return ( + Objects.equals(location, other.location) && + Objects.equals(transcriptSid, other.transcriptSid) && + Objects.equals(url, other.url) + ); + } + + @Override + public int hashCode() { + return Objects.hash( + location, + transcriptSid, + url + ); + } + + +} + diff --git a/src/main/java/com/twilio/rest/intelligence/v2/transcript/EncryptedSentencesFetcher.java b/src/main/java/com/twilio/rest/intelligence/v2/transcript/EncryptedSentencesFetcher.java new file mode 100644 index 0000000000..ecd81e64f5 --- /dev/null +++ b/src/main/java/com/twilio/rest/intelligence/v2/transcript/EncryptedSentencesFetcher.java @@ -0,0 +1,86 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Intelligence + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package com.twilio.rest.intelligence.v2.transcript; + +import com.twilio.base.Fetcher; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; +import com.twilio.exception.ApiConnectionException; +import com.twilio.exception.ApiException; +import com.twilio.exception.RestException; +import com.twilio.http.HttpMethod; +import com.twilio.http.Request; +import com.twilio.http.Response; +import com.twilio.http.TwilioRestClient; +import com.twilio.rest.Domains; + +public class EncryptedSentencesFetcher extends Fetcher { + + private String pathtranscriptSid; + private Boolean redacted; + + public EncryptedSentencesFetcher(final String pathtranscriptSid) { + this.pathtranscriptSid = pathtranscriptSid; + } + + + public EncryptedSentencesFetcher setRedacted(final Boolean redacted) { + this.redacted = redacted; + return this; + } + + + @Override + public EncryptedSentences fetch(final TwilioRestClient client) { + + String path = "/v2/Transcripts/{TranscriptSid}/Sentences/Encrypted"; + + path = path.replace("{" + "TranscriptSid" + "}", this.pathtranscriptSid.toString()); + + + Request request = new Request( + HttpMethod.GET, + Domains.INTELLIGENCE.toString(), + path + ); + addQueryParams(request); + + Response response = client.request(request); + + if (response == null) { + throw new ApiConnectionException("EncryptedSentences fetch failed: Unable to connect to server"); + } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { + RestException restException = RestException.fromJson( + response.getStream(), + client.getObjectMapper() + ); + if (restException == null) { + throw new ApiException("Server Error, no content", response.getStatusCode()); + } + throw new ApiException(restException); + } + return EncryptedSentences.fromJson(response.getStream(), client.getObjectMapper()); + } + + private void addQueryParams(final Request request) { + + + if (redacted != null) { + Serializer.toString(request, "Redacted", redacted, ParameterType.QUERY); + } + + + } +} diff --git a/src/main/java/com/twilio/rest/intelligence/v2/transcript/Media.java b/src/main/java/com/twilio/rest/intelligence/v2/transcript/Media.java index 5ada494f55..6883cfc5ed 100644 --- a/src/main/java/com/twilio/rest/intelligence/v2/transcript/Media.java +++ b/src/main/java/com/twilio/rest/intelligence/v2/transcript/Media.java @@ -18,39 +18,40 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Media extends Resource { - private static final long serialVersionUID = 207829674287272L; - public static MediaFetcher fetcher(final String pathSid) { - return new MediaFetcher(pathSid); + public static MediaFetcher fetcher(final String pathsid) { + return new MediaFetcher( + pathsid + ); } + /** * Converts a JSON String into a Media object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Media object represented by the provided JSON */ - public static Media fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Media fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Media.class); @@ -65,14 +66,11 @@ public static Media fromJson( * Converts a JSON InputStream into a Media object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Media object represented by the provided JSON */ - public static Media fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Media fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Media.class); @@ -83,19 +81,37 @@ public static Media fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; + @Getter private final URI mediaUrl; + @Getter private final String serviceSid; + @Getter private final String sid; + @Getter private final URI url; @JsonCreator private Media( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("media_url") final URI mediaUrl, - @JsonProperty("service_sid") final String serviceSid, - @JsonProperty("sid") final String sid, - @JsonProperty("url") final URI url + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("media_url") final URI mediaUrl, + @JsonProperty("service_sid") final String serviceSid, + @JsonProperty("sid") final String sid, + @JsonProperty("url") final URI url ) { this.accountSid = accountSid; this.mediaUrl = mediaUrl; @@ -104,26 +120,6 @@ private Media( this.url = url; } - public final String getAccountSid() { - return this.accountSid; - } - - public final URI getMediaUrl() { - return this.mediaUrl; - } - - public final String getServiceSid() { - return this.serviceSid; - } - - public final String getSid() { - return this.sid; - } - - public final URI getUrl() { - return this.url; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -135,18 +131,26 @@ public boolean equals(final Object o) { } Media other = (Media) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(mediaUrl, other.mediaUrl) && - Objects.equals(serviceSid, other.serviceSid) && - Objects.equals(sid, other.sid) && - Objects.equals(url, other.url) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(mediaUrl, other.mediaUrl) && + Objects.equals(serviceSid, other.serviceSid) && + Objects.equals(sid, other.sid) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { - return Objects.hash(accountSid, mediaUrl, serviceSid, sid, url); + return Objects.hash( + accountSid, + mediaUrl, + serviceSid, + sid, + url + ); } + + } + diff --git a/src/main/java/com/twilio/rest/intelligence/v2/transcript/MediaFetcher.java b/src/main/java/com/twilio/rest/intelligence/v2/transcript/MediaFetcher.java index adb0677dc5..fbfe984caa 100644 --- a/src/main/java/com/twilio/rest/intelligence/v2/transcript/MediaFetcher.java +++ b/src/main/java/com/twilio/rest/intelligence/v2/transcript/MediaFetcher.java @@ -15,7 +15,8 @@ package com.twilio.rest.intelligence.v2.transcript; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,57 +28,59 @@ public class MediaFetcher extends Fetcher { - private String pathSid; + private String pathsid; private Boolean redacted; - public MediaFetcher(final String pathSid) { - this.pathSid = pathSid; + public MediaFetcher(final String pathsid) { + this.pathsid = pathsid; } + public MediaFetcher setRedacted(final Boolean redacted) { this.redacted = redacted; return this; } + @Override public Media fetch(final TwilioRestClient client) { + String path = "/v2/Transcripts/{Sid}/Media"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.INTELLIGENCE.toString(), - path + HttpMethod.GET, + Domains.INTELLIGENCE.toString(), + path ); addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Media fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Media fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Media.fromJson(response.getStream(), client.getObjectMapper()); } private void addQueryParams(final Request request) { + + if (redacted != null) { - request.addQueryParam("Redacted", redacted.toString()); + Serializer.toString(request, "Redacted", redacted, ParameterType.QUERY); } + + } } diff --git a/src/main/java/com/twilio/rest/intelligence/v2/transcript/OperatorResult.java b/src/main/java/com/twilio/rest/intelligence/v2/transcript/OperatorResult.java index 8e734ee75a..2749410857 100644 --- a/src/main/java/com/twilio/rest/intelligence/v2/transcript/OperatorResult.java +++ b/src/main/java/com/twilio/rest/intelligence/v2/transcript/OperatorResult.java @@ -18,51 +18,76 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.math.BigDecimal; import java.net.URI; import java.util.List; -import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class OperatorResult extends Resource { - private static final long serialVersionUID = 110796815402135L; - public static OperatorResultFetcher fetcher( - final String pathTranscriptSid, - final String pathOperatorSid - ) { - return new OperatorResultFetcher(pathTranscriptSid, pathOperatorSid); + public static OperatorResultFetcher fetcher(final String pathtranscriptSid, final String pathoperatorSid) { + return new OperatorResultFetcher( + pathtranscriptSid, pathoperatorSid + ); } - public static OperatorResultReader reader(final String pathTranscriptSid) { - return new OperatorResultReader(pathTranscriptSid); + + public static OperatorResultReader reader(final String pathtranscriptSid) { + return new OperatorResultReader( + pathtranscriptSid + ); } + + public enum OperatorType { + CONVERSATION_CLASSIFY("conversation_classify"), + UTTERANCE_CLASSIFY("utterance_classify"), + EXTRACT("extract"), + EXTRACT_NORMALIZE("extract_normalize"), + PII_EXTRACT("pii_extract"), + TEXT_GENERATION("text_generation"), + JSON("json"); + + private final String value; + + private OperatorType(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static OperatorType forValue(final String value) { + return Promoter.enumFromString(value, OperatorType.values()); + } + } + + /** * Converts a JSON String into a OperatorResult object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return OperatorResult object represented by the provided JSON */ - public static OperatorResult fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static OperatorResult fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, OperatorResult.class); @@ -77,14 +102,11 @@ public static OperatorResult fromJson( * Converts a JSON InputStream into a OperatorResult object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return OperatorResult object represented by the provided JSON */ - public static OperatorResult fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static OperatorResult fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, OperatorResult.class); @@ -95,137 +117,87 @@ public static OperatorResult fromJson( } } - private final OperatorResult.OperatorType operatorType; - private final String name; - private final String operatorSid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final Boolean extractMatch; + @Getter + private final Object extractResults; + @Getter + private final Object jsonResults; + @Getter + private final Object labelProbabilities; + @Getter private final BigDecimal matchProbability; + @Getter + private final String name; + @Getter private final String normalizedResult; - private final List> utteranceResults; - private final Boolean utteranceMatch; + @Getter + private final String operatorSid; + @Getter + private final OperatorResult.OperatorType operatorType; + @Getter private final String predictedLabel; + @Getter private final BigDecimal predictedProbability; - private final Map labelProbabilities; - private final Map extractResults; - private final Map textGenerationResults; - private final Map jsonResults; + @Getter + private final Object textGenerationResults; + @Getter private final String transcriptSid; + @Getter private final URI url; + @Getter + private final Boolean utteranceMatch; + @Getter + private final List utteranceResults; @JsonCreator private OperatorResult( - @JsonProperty( - "operator_type" - ) final OperatorResult.OperatorType operatorType, - @JsonProperty("name") final String name, - @JsonProperty("operator_sid") final String operatorSid, - @JsonProperty("extract_match") final Boolean extractMatch, - @JsonProperty("match_probability") final BigDecimal matchProbability, - @JsonProperty("normalized_result") final String normalizedResult, - @JsonProperty("utterance_results") final List< - Map - > utteranceResults, - @JsonProperty("utterance_match") final Boolean utteranceMatch, - @JsonProperty("predicted_label") final String predictedLabel, - @JsonProperty( - "predicted_probability" - ) final BigDecimal predictedProbability, - @JsonProperty("label_probabilities") final Map< - String, - Object - > labelProbabilities, - @JsonProperty("extract_results") final Map< - String, - Object - > extractResults, - @JsonProperty("text_generation_results") final Map< - String, - Object - > textGenerationResults, - @JsonProperty("json_results") final Map jsonResults, - @JsonProperty("transcript_sid") final String transcriptSid, - @JsonProperty("url") final URI url + @JsonProperty("extract_match") final Boolean extractMatch, + @JsonProperty("extract_results") final Object extractResults, + @JsonProperty("json_results") final Object jsonResults, + @JsonProperty("label_probabilities") final Object labelProbabilities, + @JsonProperty("match_probability") final BigDecimal matchProbability, + @JsonProperty("name") final String name, + @JsonProperty("normalized_result") final String normalizedResult, + @JsonProperty("operator_sid") final String operatorSid, + @JsonProperty("operator_type") final OperatorResult.OperatorType operatorType, + @JsonProperty("predicted_label") final String predictedLabel, + @JsonProperty("predicted_probability") final BigDecimal predictedProbability, + @JsonProperty("text_generation_results") final Object textGenerationResults, + @JsonProperty("transcript_sid") final String transcriptSid, + @JsonProperty("url") final URI url, + @JsonProperty("utterance_match") final Boolean utteranceMatch, + @JsonProperty("utterance_results") final List utteranceResults ) { - this.operatorType = operatorType; - this.name = name; - this.operatorSid = operatorSid; this.extractMatch = extractMatch; + this.extractResults = extractResults; + this.jsonResults = jsonResults; + this.labelProbabilities = labelProbabilities; this.matchProbability = matchProbability; + this.name = name; this.normalizedResult = normalizedResult; - this.utteranceResults = utteranceResults; - this.utteranceMatch = utteranceMatch; + this.operatorSid = operatorSid; + this.operatorType = operatorType; this.predictedLabel = predictedLabel; this.predictedProbability = predictedProbability; - this.labelProbabilities = labelProbabilities; - this.extractResults = extractResults; this.textGenerationResults = textGenerationResults; - this.jsonResults = jsonResults; this.transcriptSid = transcriptSid; this.url = url; - } - - public final OperatorResult.OperatorType getOperatorType() { - return this.operatorType; - } - - public final String getName() { - return this.name; - } - - public final String getOperatorSid() { - return this.operatorSid; - } - - public final Boolean getExtractMatch() { - return this.extractMatch; - } - - public final BigDecimal getMatchProbability() { - return this.matchProbability; - } - - public final String getNormalizedResult() { - return this.normalizedResult; - } - - public final List> getUtteranceResults() { - return this.utteranceResults; - } - - public final Boolean getUtteranceMatch() { - return this.utteranceMatch; - } - - public final String getPredictedLabel() { - return this.predictedLabel; - } - - public final BigDecimal getPredictedProbability() { - return this.predictedProbability; - } - - public final Map getLabelProbabilities() { - return this.labelProbabilities; - } - - public final Map getExtractResults() { - return this.extractResults; - } - - public final Map getTextGenerationResults() { - return this.textGenerationResults; - } - - public final Map getJsonResults() { - return this.jsonResults; - } - - public final String getTranscriptSid() { - return this.transcriptSid; - } - - public final URI getUrl() { - return this.url; + this.utteranceMatch = utteranceMatch; + this.utteranceResults = utteranceResults; } @Override @@ -239,74 +211,48 @@ public boolean equals(final Object o) { } OperatorResult other = (OperatorResult) o; - return ( - Objects.equals(operatorType, other.operatorType) && - Objects.equals(name, other.name) && - Objects.equals(operatorSid, other.operatorSid) && - Objects.equals(extractMatch, other.extractMatch) && - Objects.equals(matchProbability, other.matchProbability) && - Objects.equals(normalizedResult, other.normalizedResult) && - Objects.equals(utteranceResults, other.utteranceResults) && - Objects.equals(utteranceMatch, other.utteranceMatch) && - Objects.equals(predictedLabel, other.predictedLabel) && - Objects.equals(predictedProbability, other.predictedProbability) && - Objects.equals(labelProbabilities, other.labelProbabilities) && - Objects.equals(extractResults, other.extractResults) && - Objects.equals( - textGenerationResults, - other.textGenerationResults - ) && - Objects.equals(jsonResults, other.jsonResults) && - Objects.equals(transcriptSid, other.transcriptSid) && - Objects.equals(url, other.url) + Objects.equals(extractMatch, other.extractMatch) && + Objects.equals(extractResults, other.extractResults) && + Objects.equals(jsonResults, other.jsonResults) && + Objects.equals(labelProbabilities, other.labelProbabilities) && + Objects.equals(matchProbability, other.matchProbability) && + Objects.equals(name, other.name) && + Objects.equals(normalizedResult, other.normalizedResult) && + Objects.equals(operatorSid, other.operatorSid) && + Objects.equals(operatorType, other.operatorType) && + Objects.equals(predictedLabel, other.predictedLabel) && + Objects.equals(predictedProbability, other.predictedProbability) && + Objects.equals(textGenerationResults, other.textGenerationResults) && + Objects.equals(transcriptSid, other.transcriptSid) && + Objects.equals(url, other.url) && + Objects.equals(utteranceMatch, other.utteranceMatch) && + Objects.equals(utteranceResults, other.utteranceResults) ); } @Override public int hashCode() { return Objects.hash( - operatorType, - name, - operatorSid, - extractMatch, - matchProbability, - normalizedResult, - utteranceResults, - utteranceMatch, - predictedLabel, - predictedProbability, - labelProbabilities, - extractResults, - textGenerationResults, - jsonResults, - transcriptSid, - url + extractMatch, + extractResults, + jsonResults, + labelProbabilities, + matchProbability, + name, + normalizedResult, + operatorSid, + operatorType, + predictedLabel, + predictedProbability, + textGenerationResults, + transcriptSid, + url, + utteranceMatch, + utteranceResults ); } - public enum OperatorType { - CONVERSATION_CLASSIFY("conversation_classify"), - UTTERANCE_CLASSIFY("utterance_classify"), - EXTRACT("extract"), - EXTRACT_NORMALIZE("extract_normalize"), - PII_EXTRACT("pii_extract"), - TEXT_GENERATION("text_generation"), - JSON("json"); - - private final String value; - - private OperatorType(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - @JsonCreator - public static OperatorType forValue(final String value) { - return Promoter.enumFromString(value, OperatorType.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/intelligence/v2/transcript/OperatorResultFetcher.java b/src/main/java/com/twilio/rest/intelligence/v2/transcript/OperatorResultFetcher.java index 515fec1ed0..e7150fd8a8 100644 --- a/src/main/java/com/twilio/rest/intelligence/v2/transcript/OperatorResultFetcher.java +++ b/src/main/java/com/twilio/rest/intelligence/v2/transcript/OperatorResultFetcher.java @@ -15,7 +15,8 @@ package com.twilio.rest.intelligence.v2.transcript; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,75 +28,62 @@ public class OperatorResultFetcher extends Fetcher { - private String pathTranscriptSid; - private String pathOperatorSid; + private String pathtranscriptSid; + private String pathoperatorSid; private Boolean redacted; - public OperatorResultFetcher( - final String pathTranscriptSid, - final String pathOperatorSid - ) { - this.pathTranscriptSid = pathTranscriptSid; - this.pathOperatorSid = pathOperatorSid; + public OperatorResultFetcher(final String pathtranscriptSid, final String pathoperatorSid) { + this.pathtranscriptSid = pathtranscriptSid; + this.pathoperatorSid = pathoperatorSid; } + public OperatorResultFetcher setRedacted(final Boolean redacted) { this.redacted = redacted; return this; } + @Override public OperatorResult fetch(final TwilioRestClient client) { - String path = - "/v2/Transcripts/{TranscriptSid}/OperatorResults/{OperatorSid}"; - path = - path.replace( - "{" + "TranscriptSid" + "}", - this.pathTranscriptSid.toString() - ); - path = - path.replace( - "{" + "OperatorSid" + "}", - this.pathOperatorSid.toString() - ); + String path = "/v2/Transcripts/{TranscriptSid}/OperatorResults/{OperatorSid}"; + + path = path.replace("{" + "TranscriptSid" + "}", this.pathtranscriptSid.toString()); + path = path.replace("{" + "OperatorSid" + "}", this.pathoperatorSid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.INTELLIGENCE.toString(), - path + HttpMethod.GET, + Domains.INTELLIGENCE.toString(), + path ); addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "OperatorResult fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("OperatorResult fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return OperatorResult.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return OperatorResult.fromJson(response.getStream(), client.getObjectMapper()); } private void addQueryParams(final Request request) { + + if (redacted != null) { - request.addQueryParam("Redacted", redacted.toString()); + Serializer.toString(request, "Redacted", redacted, ParameterType.QUERY); } + + } } diff --git a/src/main/java/com/twilio/rest/intelligence/v2/transcript/OperatorResultReader.java b/src/main/java/com/twilio/rest/intelligence/v2/transcript/OperatorResultReader.java index 13d64bda3d..76ca6aaf1a 100644 --- a/src/main/java/com/twilio/rest/intelligence/v2/transcript/OperatorResultReader.java +++ b/src/main/java/com/twilio/rest/intelligence/v2/transcript/OperatorResultReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,124 +30,100 @@ public class OperatorResultReader extends Reader { - private String pathTranscriptSid; + private String pathtranscriptSid; private Boolean redacted; private Long pageSize; - public OperatorResultReader(final String pathTranscriptSid) { - this.pathTranscriptSid = pathTranscriptSid; + public OperatorResultReader(final String pathtranscriptSid) { + this.pathtranscriptSid = pathtranscriptSid; } + public OperatorResultReader setRedacted(final Boolean redacted) { this.redacted = redacted; return this; } + public OperatorResultReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v2/Transcripts/{TranscriptSid}/OperatorResults"; - path = - path.replace( - "{" + "TranscriptSid" + "}", - this.pathTranscriptSid.toString() - ); + + path = path.replace("{" + "TranscriptSid" + "}", this.pathtranscriptSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.INTELLIGENCE.toString(), - path + HttpMethod.GET, + Domains.INTELLIGENCE.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "OperatorResult read failed: Unable to connect to server" - ); + throw new ApiConnectionException("OperatorResult read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "operator_results", - response.getContent(), - OperatorResult.class, - client.getObjectMapper() - ); + "operator_results", + response.getContent(), + OperatorResult.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.INTELLIGENCE.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.INTELLIGENCE.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (redacted != null) { - request.addQueryParam("Redacted", redacted.toString()); + Serializer.toString(request, "Redacted", redacted, ParameterType.QUERY); } + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/intelligence/v2/transcript/Sentence.java b/src/main/java/com/twilio/rest/intelligence/v2/transcript/Sentence.java index 522844d3d7..304c084785 100644 --- a/src/main/java/com/twilio/rest/intelligence/v2/transcript/Sentence.java +++ b/src/main/java/com/twilio/rest/intelligence/v2/transcript/Sentence.java @@ -18,42 +18,41 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.math.BigDecimal; import java.util.List; -import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Sentence extends Resource { - private static final long serialVersionUID = 171585913029090L; - public static SentenceReader reader(final String pathTranscriptSid) { - return new SentenceReader(pathTranscriptSid); + public static SentenceReader reader(final String pathtranscriptSid) { + return new SentenceReader( + pathtranscriptSid + ); } + /** * Converts a JSON String into a Sentence object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Sentence object represented by the provided JSON */ - public static Sentence fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Sentence fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Sentence.class); @@ -68,14 +67,11 @@ public static Sentence fromJson( * Converts a JSON InputStream into a Sentence object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Sentence object represented by the provided JSON */ - public static Sentence fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Sentence fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Sentence.class); @@ -86,68 +82,57 @@ public static Sentence fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter + private final BigDecimal confidence; + @Getter + private final BigDecimal endTime; + @Getter private final Integer mediaChannel; + @Getter private final Integer sentenceIndex; + @Getter + private final String sid; + @Getter private final BigDecimal startTime; - private final BigDecimal endTime; + @Getter private final String transcript; - private final String sid; - private final BigDecimal confidence; - private final List> words; + @Getter + private final List words; @JsonCreator private Sentence( - @JsonProperty("media_channel") final Integer mediaChannel, - @JsonProperty("sentence_index") final Integer sentenceIndex, - @JsonProperty("start_time") final BigDecimal startTime, - @JsonProperty("end_time") final BigDecimal endTime, - @JsonProperty("transcript") final String transcript, - @JsonProperty("sid") final String sid, - @JsonProperty("confidence") final BigDecimal confidence, - @JsonProperty("words") final List> words + @JsonProperty("confidence") final BigDecimal confidence, + @JsonProperty("end_time") final BigDecimal endTime, + @JsonProperty("media_channel") final Integer mediaChannel, + @JsonProperty("sentence_index") final Integer sentenceIndex, + @JsonProperty("sid") final String sid, + @JsonProperty("start_time") final BigDecimal startTime, + @JsonProperty("transcript") final String transcript, + @JsonProperty("words") final List words ) { + this.confidence = confidence; + this.endTime = endTime; this.mediaChannel = mediaChannel; this.sentenceIndex = sentenceIndex; + this.sid = sid; this.startTime = startTime; - this.endTime = endTime; this.transcript = transcript; - this.sid = sid; - this.confidence = confidence; this.words = words; } - public final Integer getMediaChannel() { - return this.mediaChannel; - } - - public final Integer getSentenceIndex() { - return this.sentenceIndex; - } - - public final BigDecimal getStartTime() { - return this.startTime; - } - - public final BigDecimal getEndTime() { - return this.endTime; - } - - public final String getTranscript() { - return this.transcript; - } - - public final String getSid() { - return this.sid; - } - - public final BigDecimal getConfidence() { - return this.confidence; - } - - public final List> getWords() { - return this.words; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -159,30 +144,32 @@ public boolean equals(final Object o) { } Sentence other = (Sentence) o; - return ( - Objects.equals(mediaChannel, other.mediaChannel) && - Objects.equals(sentenceIndex, other.sentenceIndex) && - Objects.equals(startTime, other.startTime) && - Objects.equals(endTime, other.endTime) && - Objects.equals(transcript, other.transcript) && - Objects.equals(sid, other.sid) && - Objects.equals(confidence, other.confidence) && - Objects.equals(words, other.words) + Objects.equals(confidence, other.confidence) && + Objects.equals(endTime, other.endTime) && + Objects.equals(mediaChannel, other.mediaChannel) && + Objects.equals(sentenceIndex, other.sentenceIndex) && + Objects.equals(sid, other.sid) && + Objects.equals(startTime, other.startTime) && + Objects.equals(transcript, other.transcript) && + Objects.equals(words, other.words) ); } @Override public int hashCode() { return Objects.hash( - mediaChannel, - sentenceIndex, - startTime, - endTime, - transcript, - sid, - confidence, - words + confidence, + endTime, + mediaChannel, + sentenceIndex, + sid, + startTime, + transcript, + words ); } + + } + diff --git a/src/main/java/com/twilio/rest/intelligence/v2/transcript/SentenceReader.java b/src/main/java/com/twilio/rest/intelligence/v2/transcript/SentenceReader.java index ebecf5844d..9aac9afb13 100644 --- a/src/main/java/com/twilio/rest/intelligence/v2/transcript/SentenceReader.java +++ b/src/main/java/com/twilio/rest/intelligence/v2/transcript/SentenceReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,133 +30,112 @@ public class SentenceReader extends Reader { - private String pathTranscriptSid; + private String pathtranscriptSid; private Boolean redacted; private Boolean wordTimestamps; private Long pageSize; - public SentenceReader(final String pathTranscriptSid) { - this.pathTranscriptSid = pathTranscriptSid; + public SentenceReader(final String pathtranscriptSid) { + this.pathtranscriptSid = pathtranscriptSid; } + public SentenceReader setRedacted(final Boolean redacted) { this.redacted = redacted; return this; } + public SentenceReader setWordTimestamps(final Boolean wordTimestamps) { this.wordTimestamps = wordTimestamps; return this; } + public SentenceReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v2/Transcripts/{TranscriptSid}/Sentences"; - path = - path.replace( - "{" + "TranscriptSid" + "}", - this.pathTranscriptSid.toString() - ); + + path = path.replace("{" + "TranscriptSid" + "}", this.pathtranscriptSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.INTELLIGENCE.toString(), - path + HttpMethod.GET, + Domains.INTELLIGENCE.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Sentence read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Sentence read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "sentences", - response.getContent(), - Sentence.class, - client.getObjectMapper() - ); + "sentences", + response.getContent(), + Sentence.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.INTELLIGENCE.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.INTELLIGENCE.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (redacted != null) { - request.addQueryParam("Redacted", redacted.toString()); + Serializer.toString(request, "Redacted", redacted, ParameterType.QUERY); } + + if (wordTimestamps != null) { - request.addQueryParam("WordTimestamps", wordTimestamps.toString()); + Serializer.toString(request, "WordTimestamps", wordTimestamps, ParameterType.QUERY); } + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/ipmessaging/v1/Credential.java b/src/main/java/com/twilio/rest/ipmessaging/v1/Credential.java index c18921f709..1ddbba06ed 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v1/Credential.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v1/Credential.java @@ -18,58 +18,93 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Credential extends Resource { - private static final long serialVersionUID = 161183169234848L; public static CredentialCreator creator(final Credential.PushService type) { - return new CredentialCreator(type); + return new CredentialCreator( + type + ); } - public static CredentialDeleter deleter(final String pathSid) { - return new CredentialDeleter(pathSid); + + public static CredentialDeleter deleter(final String pathsid) { + return new CredentialDeleter( + pathsid + ); } - public static CredentialFetcher fetcher(final String pathSid) { - return new CredentialFetcher(pathSid); + + public static CredentialFetcher fetcher(final String pathsid) { + return new CredentialFetcher( + pathsid + ); } + public static CredentialReader reader() { - return new CredentialReader(); + return new CredentialReader( + + ); } - public static CredentialUpdater updater(final String pathSid) { - return new CredentialUpdater(pathSid); + + public static CredentialUpdater updater(final String pathsid) { + return new CredentialUpdater( + pathsid + ); } + + public enum PushService { + GCM("gcm"), + APN("apn"), + FCM("fcm"); + + private final String value; + + private PushService(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static PushService forValue(final String value) { + return Promoter.enumFromString(value, PushService.values()); + } + } + + /** * Converts a JSON String into a Credential object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Credential object represented by the provided JSON */ - public static Credential fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Credential fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Credential.class); @@ -84,14 +119,11 @@ public static Credential fromJson( * Converts a JSON InputStream into a Credential object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Credential object represented by the provided JSON */ - public static Credential fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Credential fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Credential.class); @@ -102,68 +134,59 @@ public static Credential fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String friendlyName; - private final Credential.PushService type; - private final String sandbox; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; + @Getter + private final String friendlyName; + @Getter + private final String sandbox; + @Getter + private final String sid; + @Getter + private final Credential.PushService type; + @Getter private final URI url; @JsonCreator private Credential( - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("type") final Credential.PushService type, - @JsonProperty("sandbox") final String sandbox, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("url") final URI url + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("sandbox") final String sandbox, + @JsonProperty("sid") final String sid, + @JsonProperty("type") final Credential.PushService type, + @JsonProperty("url") final URI url ) { - this.sid = sid; this.accountSid = accountSid; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.friendlyName = friendlyName; - this.type = type; this.sandbox = sandbox; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); + this.sid = sid; + this.type = type; this.url = url; } - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final Credential.PushService getType() { - return this.type; - } - - public final String getSandbox() { - return this.sandbox; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final URI getUrl() { - return this.url; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -175,51 +198,32 @@ public boolean equals(final Object o) { } Credential other = (Credential) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(type, other.type) && - Objects.equals(sandbox, other.sandbox) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(url, other.url) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(sandbox, other.sandbox) && + Objects.equals(sid, other.sid) && + Objects.equals(type, other.type) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - sid, - accountSid, - friendlyName, - type, - sandbox, - dateCreated, - dateUpdated, - url + accountSid, + dateCreated, + dateUpdated, + friendlyName, + sandbox, + sid, + type, + url ); } - public enum PushService { - GCM("gcm"), - APN("apn"), - FCM("fcm"); - - private final String value; - - private PushService(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - @JsonCreator - public static PushService forValue(final String value) { - return Promoter.enumFromString(value, PushService.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/ipmessaging/v1/CredentialCreator.java b/src/main/java/com/twilio/rest/ipmessaging/v1/CredentialCreator.java index faf3f5efee..48699a9e65 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v1/CredentialCreator.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v1/CredentialCreator.java @@ -14,8 +14,11 @@ package com.twilio.rest.ipmessaging.v1; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -39,100 +42,117 @@ public CredentialCreator(final Credential.PushService type) { this.type = type; } + public CredentialCreator setType(final Credential.PushService type) { this.type = type; return this; } + public CredentialCreator setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + public CredentialCreator setCertificate(final String certificate) { this.certificate = certificate; return this; } + public CredentialCreator setPrivateKey(final String privateKey) { this.privateKey = privateKey; return this; } + public CredentialCreator setSandbox(final Boolean sandbox) { this.sandbox = sandbox; return this; } + public CredentialCreator setApiKey(final String apiKey) { this.apiKey = apiKey; return this; } + public CredentialCreator setSecret(final String secret) { this.secret = secret; return this; } + @Override public Credential create(final TwilioRestClient client) { + String path = "/v1/Credentials"; - path = path.replace("{" + "Type" + "}", this.type.toString()); Request request = new Request( - HttpMethod.POST, - Domains.IPMESSAGING.toString(), - path + HttpMethod.POST, + Domains.IPMESSAGING.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Credential creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("Credential creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Credential.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Credential.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (type != null) { - request.addPostParam("Type", type.toString()); + Serializer.toString(request, "Type", type, ParameterType.URLENCODED); } + + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + if (certificate != null) { - request.addPostParam("Certificate", certificate); + Serializer.toString(request, "Certificate", certificate, ParameterType.URLENCODED); } + + if (privateKey != null) { - request.addPostParam("PrivateKey", privateKey); + Serializer.toString(request, "PrivateKey", privateKey, ParameterType.URLENCODED); } + + if (sandbox != null) { - request.addPostParam("Sandbox", sandbox.toString()); + Serializer.toString(request, "Sandbox", sandbox, ParameterType.URLENCODED); } + + if (apiKey != null) { - request.addPostParam("ApiKey", apiKey); + Serializer.toString(request, "ApiKey", apiKey, ParameterType.URLENCODED); } + + if (secret != null) { - request.addPostParam("Secret", secret); + Serializer.toString(request, "Secret", secret, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/ipmessaging/v1/CredentialDeleter.java b/src/main/java/com/twilio/rest/ipmessaging/v1/CredentialDeleter.java index b3fedb1bcd..69ab990652 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v1/CredentialDeleter.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v1/CredentialDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.ipmessaging.v1; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,40 +26,38 @@ public class CredentialDeleter extends Deleter { - private String pathSid; + private String pathsid; - public CredentialDeleter(final String pathSid) { - this.pathSid = pathSid; + public CredentialDeleter(final String pathsid) { + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/v1/Credentials/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.IPMESSAGING.toString(), - path + HttpMethod.DELETE, + Domains.IPMESSAGING.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Credential delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("Credential delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/ipmessaging/v1/CredentialFetcher.java b/src/main/java/com/twilio/rest/ipmessaging/v1/CredentialFetcher.java index 4700819e71..e93d65e44e 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v1/CredentialFetcher.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v1/CredentialFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.ipmessaging.v1; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,47 +26,41 @@ public class CredentialFetcher extends Fetcher { - private String pathSid; + private String pathsid; - public CredentialFetcher(final String pathSid) { - this.pathSid = pathSid; + public CredentialFetcher(final String pathsid) { + this.pathsid = pathsid; } + @Override public Credential fetch(final TwilioRestClient client) { + String path = "/v1/Credentials/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.IPMESSAGING.toString(), - path + HttpMethod.GET, + Domains.IPMESSAGING.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Credential fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Credential fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return Credential.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Credential.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/ipmessaging/v1/CredentialReader.java b/src/main/java/com/twilio/rest/ipmessaging/v1/CredentialReader.java index ee1a6da59b..8a089f116a 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v1/CredentialReader.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v1/CredentialReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -31,105 +32,83 @@ public class CredentialReader extends Reader { private Long pageSize; - public CredentialReader() {} + public CredentialReader() { + } + public CredentialReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/Credentials"; + Request request = new Request( - HttpMethod.GET, - Domains.IPMESSAGING.toString(), - path + HttpMethod.GET, + Domains.IPMESSAGING.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Credential read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Credential read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "credentials", - response.getContent(), - Credential.class, - client.getObjectMapper() - ); + "credentials", + response.getContent(), + Credential.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.IPMESSAGING.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.IPMESSAGING.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/ipmessaging/v1/CredentialUpdater.java b/src/main/java/com/twilio/rest/ipmessaging/v1/CredentialUpdater.java index 2a156dc1ff..b17274248d 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v1/CredentialUpdater.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v1/CredentialUpdater.java @@ -16,6 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -26,8 +28,7 @@ import com.twilio.rest.Domains; public class CredentialUpdater extends Updater { - - private String pathSid; + private String pathsid; private String friendlyName; private String certificate; private String privateKey; @@ -35,96 +36,112 @@ public class CredentialUpdater extends Updater { private String apiKey; private String secret; - public CredentialUpdater(final String pathSid) { - this.pathSid = pathSid; + public CredentialUpdater(final String pathsid) { + this.pathsid = pathsid; } + public CredentialUpdater setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + public CredentialUpdater setCertificate(final String certificate) { this.certificate = certificate; return this; } + public CredentialUpdater setPrivateKey(final String privateKey) { this.privateKey = privateKey; return this; } + public CredentialUpdater setSandbox(final Boolean sandbox) { this.sandbox = sandbox; return this; } + public CredentialUpdater setApiKey(final String apiKey) { this.apiKey = apiKey; return this; } + public CredentialUpdater setSecret(final String secret) { this.secret = secret; return this; } + @Override public Credential update(final TwilioRestClient client) { + String path = "/v1/Credentials/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.IPMESSAGING.toString(), - path + HttpMethod.POST, + Domains.IPMESSAGING.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Credential update failed: Unable to connect to server" - ); + throw new ApiConnectionException("Credential update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Credential.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Credential.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + if (certificate != null) { - request.addPostParam("Certificate", certificate); + Serializer.toString(request, "Certificate", certificate, ParameterType.URLENCODED); } + + if (privateKey != null) { - request.addPostParam("PrivateKey", privateKey); + Serializer.toString(request, "PrivateKey", privateKey, ParameterType.URLENCODED); } + + if (sandbox != null) { - request.addPostParam("Sandbox", sandbox.toString()); + Serializer.toString(request, "Sandbox", sandbox, ParameterType.URLENCODED); } + + if (apiKey != null) { - request.addPostParam("ApiKey", apiKey); + Serializer.toString(request, "ApiKey", apiKey, ParameterType.URLENCODED); } + + if (secret != null) { - request.addPostParam("Secret", secret); + Serializer.toString(request, "Secret", secret, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/ipmessaging/v1/Service.java b/src/main/java/com/twilio/rest/ipmessaging/v1/Service.java index d2ffa157c9..e38381aead 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v1/Service.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v1/Service.java @@ -18,60 +18,72 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.List; import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Service extends Resource { - private static final long serialVersionUID = 258386577185944L; public static ServiceCreator creator(final String friendlyName) { - return new ServiceCreator(friendlyName); + return new ServiceCreator( + friendlyName + ); } - public static ServiceDeleter deleter(final String pathSid) { - return new ServiceDeleter(pathSid); + + public static ServiceDeleter deleter(final String pathsid) { + return new ServiceDeleter( + pathsid + ); } - public static ServiceFetcher fetcher(final String pathSid) { - return new ServiceFetcher(pathSid); + + public static ServiceFetcher fetcher(final String pathsid) { + return new ServiceFetcher( + pathsid + ); } + public static ServiceReader reader() { - return new ServiceReader(); + return new ServiceReader( + + ); } - public static ServiceUpdater updater(final String pathSid) { - return new ServiceUpdater(pathSid); + + public static ServiceUpdater updater(final String pathsid) { + return new ServiceUpdater( + pathsid + ); } + /** * Converts a JSON String into a Service object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Service object represented by the provided JSON */ - public static Service fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Service fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Service.class); @@ -86,14 +98,11 @@ public static Service fromJson( * Converts a JSON InputStream into a Service object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Service object represented by the provided JSON */ - public static Service fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Service fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Service.class); @@ -104,167 +113,109 @@ public static Service fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String friendlyName; + @Getter + private final Integer consumptionReportInterval; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; - private final String defaultServiceRoleSid; - private final String defaultChannelRoleSid; + @Getter private final String defaultChannelCreatorRoleSid; - private final Boolean readStatusEnabled; + @Getter + private final String defaultChannelRoleSid; + @Getter + private final String defaultServiceRoleSid; + @Getter + private final String friendlyName; + @Getter + private final Object limits; + @Getter + private final Map links; + @Getter + private final Object notifications; + @Getter + private final String postWebhookUrl; + @Getter + private final String preWebhookUrl; + @Getter private final Boolean reachabilityEnabled; + @Getter + private final Boolean readStatusEnabled; + @Getter + private final String sid; + @Getter private final Integer typingIndicatorTimeout; - private final Integer consumptionReportInterval; - private final Map limits; - private final Map webhooks; - private final String preWebhookUrl; - private final String postWebhookUrl; - private final String webhookMethod; - private final List webhookFilters; - private final Map notifications; + @Getter private final URI url; - private final Map links; + @Getter + private final List webhookFilters; + @Getter + private final String webhookMethod; + @Getter + private final Object webhooks; @JsonCreator private Service( - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty( - "default_service_role_sid" - ) final String defaultServiceRoleSid, - @JsonProperty( - "default_channel_role_sid" - ) final String defaultChannelRoleSid, - @JsonProperty( - "default_channel_creator_role_sid" - ) final String defaultChannelCreatorRoleSid, - @JsonProperty("read_status_enabled") final Boolean readStatusEnabled, - @JsonProperty("reachability_enabled") final Boolean reachabilityEnabled, - @JsonProperty( - "typing_indicator_timeout" - ) final Integer typingIndicatorTimeout, - @JsonProperty( - "consumption_report_interval" - ) final Integer consumptionReportInterval, - @JsonProperty("limits") final Map limits, - @JsonProperty("webhooks") final Map webhooks, - @JsonProperty("pre_webhook_url") final String preWebhookUrl, - @JsonProperty("post_webhook_url") final String postWebhookUrl, - @JsonProperty("webhook_method") final String webhookMethod, - @JsonProperty("webhook_filters") final List webhookFilters, - @JsonProperty("notifications") final Map notifications, - @JsonProperty("url") final URI url, - @JsonProperty("links") final Map links + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("consumption_report_interval") final Integer consumptionReportInterval, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("default_channel_creator_role_sid") final String defaultChannelCreatorRoleSid, + @JsonProperty("default_channel_role_sid") final String defaultChannelRoleSid, + @JsonProperty("default_service_role_sid") final String defaultServiceRoleSid, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("limits") final Object limits, + @JsonProperty("links") final Map links, + @JsonProperty("notifications") final Object notifications, + @JsonProperty("post_webhook_url") final String postWebhookUrl, + @JsonProperty("pre_webhook_url") final String preWebhookUrl, + @JsonProperty("reachability_enabled") final Boolean reachabilityEnabled, + @JsonProperty("read_status_enabled") final Boolean readStatusEnabled, + @JsonProperty("sid") final String sid, + @JsonProperty("typing_indicator_timeout") final Integer typingIndicatorTimeout, + @JsonProperty("url") final URI url, + @JsonProperty("webhook_filters") final List webhookFilters, + @JsonProperty("webhook_method") final String webhookMethod, + @JsonProperty("webhooks") final Object webhooks ) { - this.sid = sid; this.accountSid = accountSid; - this.friendlyName = friendlyName; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); - this.defaultServiceRoleSid = defaultServiceRoleSid; - this.defaultChannelRoleSid = defaultChannelRoleSid; - this.defaultChannelCreatorRoleSid = defaultChannelCreatorRoleSid; - this.readStatusEnabled = readStatusEnabled; - this.reachabilityEnabled = reachabilityEnabled; - this.typingIndicatorTimeout = typingIndicatorTimeout; this.consumptionReportInterval = consumptionReportInterval; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; + this.defaultChannelCreatorRoleSid = defaultChannelCreatorRoleSid; + this.defaultChannelRoleSid = defaultChannelRoleSid; + this.defaultServiceRoleSid = defaultServiceRoleSid; + this.friendlyName = friendlyName; this.limits = limits; - this.webhooks = webhooks; - this.preWebhookUrl = preWebhookUrl; - this.postWebhookUrl = postWebhookUrl; - this.webhookMethod = webhookMethod; - this.webhookFilters = webhookFilters; + this.links = links; this.notifications = notifications; + this.postWebhookUrl = postWebhookUrl; + this.preWebhookUrl = preWebhookUrl; + this.reachabilityEnabled = reachabilityEnabled; + this.readStatusEnabled = readStatusEnabled; + this.sid = sid; + this.typingIndicatorTimeout = typingIndicatorTimeout; this.url = url; - this.links = links; - } - - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final String getDefaultServiceRoleSid() { - return this.defaultServiceRoleSid; - } - - public final String getDefaultChannelRoleSid() { - return this.defaultChannelRoleSid; - } - - public final String getDefaultChannelCreatorRoleSid() { - return this.defaultChannelCreatorRoleSid; - } - - public final Boolean getReadStatusEnabled() { - return this.readStatusEnabled; - } - - public final Boolean getReachabilityEnabled() { - return this.reachabilityEnabled; - } - - public final Integer getTypingIndicatorTimeout() { - return this.typingIndicatorTimeout; - } - - public final Integer getConsumptionReportInterval() { - return this.consumptionReportInterval; - } - - public final Map getLimits() { - return this.limits; - } - - public final Map getWebhooks() { - return this.webhooks; - } - - public final String getPreWebhookUrl() { - return this.preWebhookUrl; - } - - public final String getPostWebhookUrl() { - return this.postWebhookUrl; - } - - public final String getWebhookMethod() { - return this.webhookMethod; - } - - public final List getWebhookFilters() { - return this.webhookFilters; - } - - public final Map getNotifications() { - return this.notifications; - } - - public final URI getUrl() { - return this.url; - } - - public final Map getLinks() { - return this.links; + this.webhookFilters = webhookFilters; + this.webhookMethod = webhookMethod; + this.webhooks = webhooks; } @Override @@ -278,71 +229,58 @@ public boolean equals(final Object o) { } Service other = (Service) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals( - defaultServiceRoleSid, - other.defaultServiceRoleSid - ) && - Objects.equals( - defaultChannelRoleSid, - other.defaultChannelRoleSid - ) && - Objects.equals( - defaultChannelCreatorRoleSid, - other.defaultChannelCreatorRoleSid - ) && - Objects.equals(readStatusEnabled, other.readStatusEnabled) && - Objects.equals(reachabilityEnabled, other.reachabilityEnabled) && - Objects.equals( - typingIndicatorTimeout, - other.typingIndicatorTimeout - ) && - Objects.equals( - consumptionReportInterval, - other.consumptionReportInterval - ) && - Objects.equals(limits, other.limits) && - Objects.equals(webhooks, other.webhooks) && - Objects.equals(preWebhookUrl, other.preWebhookUrl) && - Objects.equals(postWebhookUrl, other.postWebhookUrl) && - Objects.equals(webhookMethod, other.webhookMethod) && - Objects.equals(webhookFilters, other.webhookFilters) && - Objects.equals(notifications, other.notifications) && - Objects.equals(url, other.url) && - Objects.equals(links, other.links) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(consumptionReportInterval, other.consumptionReportInterval) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(defaultChannelCreatorRoleSid, other.defaultChannelCreatorRoleSid) && + Objects.equals(defaultChannelRoleSid, other.defaultChannelRoleSid) && + Objects.equals(defaultServiceRoleSid, other.defaultServiceRoleSid) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(limits, other.limits) && + Objects.equals(links, other.links) && + Objects.equals(notifications, other.notifications) && + Objects.equals(postWebhookUrl, other.postWebhookUrl) && + Objects.equals(preWebhookUrl, other.preWebhookUrl) && + Objects.equals(reachabilityEnabled, other.reachabilityEnabled) && + Objects.equals(readStatusEnabled, other.readStatusEnabled) && + Objects.equals(sid, other.sid) && + Objects.equals(typingIndicatorTimeout, other.typingIndicatorTimeout) && + Objects.equals(url, other.url) && + Objects.equals(webhookFilters, other.webhookFilters) && + Objects.equals(webhookMethod, other.webhookMethod) && + Objects.equals(webhooks, other.webhooks) ); } @Override public int hashCode() { return Objects.hash( - sid, - accountSid, - friendlyName, - dateCreated, - dateUpdated, - defaultServiceRoleSid, - defaultChannelRoleSid, - defaultChannelCreatorRoleSid, - readStatusEnabled, - reachabilityEnabled, - typingIndicatorTimeout, - consumptionReportInterval, - limits, - webhooks, - preWebhookUrl, - postWebhookUrl, - webhookMethod, - webhookFilters, - notifications, - url, - links + accountSid, + consumptionReportInterval, + dateCreated, + dateUpdated, + defaultChannelCreatorRoleSid, + defaultChannelRoleSid, + defaultServiceRoleSid, + friendlyName, + limits, + links, + notifications, + postWebhookUrl, + preWebhookUrl, + reachabilityEnabled, + readStatusEnabled, + sid, + typingIndicatorTimeout, + url, + webhookFilters, + webhookMethod, + webhooks ); } + + } + diff --git a/src/main/java/com/twilio/rest/ipmessaging/v1/ServiceCreator.java b/src/main/java/com/twilio/rest/ipmessaging/v1/ServiceCreator.java index 49152424e9..e6872443f4 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v1/ServiceCreator.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v1/ServiceCreator.java @@ -14,8 +14,11 @@ package com.twilio.rest.ipmessaging.v1; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -33,43 +36,38 @@ public ServiceCreator(final String friendlyName) { this.friendlyName = friendlyName; } + public ServiceCreator setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + @Override public Service create(final TwilioRestClient client) { + String path = "/v1/Services"; - path = - path.replace( - "{" + "FriendlyName" + "}", - this.friendlyName.toString() - ); Request request = new Request( - HttpMethod.POST, - Domains.IPMESSAGING.toString(), - path + HttpMethod.POST, + Domains.IPMESSAGING.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Service creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("Service creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -78,8 +76,11 @@ public Service create(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/ipmessaging/v1/ServiceDeleter.java b/src/main/java/com/twilio/rest/ipmessaging/v1/ServiceDeleter.java index c3e6cd5350..194b7fd9f8 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v1/ServiceDeleter.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v1/ServiceDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.ipmessaging.v1; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,40 +26,38 @@ public class ServiceDeleter extends Deleter { - private String pathSid; + private String pathsid; - public ServiceDeleter(final String pathSid) { - this.pathSid = pathSid; + public ServiceDeleter(final String pathsid) { + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/v1/Services/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.IPMESSAGING.toString(), - path + HttpMethod.DELETE, + Domains.IPMESSAGING.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Service delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("Service delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/ipmessaging/v1/ServiceFetcher.java b/src/main/java/com/twilio/rest/ipmessaging/v1/ServiceFetcher.java index a78fc3b455..3e5b816faf 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v1/ServiceFetcher.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v1/ServiceFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.ipmessaging.v1; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,44 +26,41 @@ public class ServiceFetcher extends Fetcher { - private String pathSid; + private String pathsid; - public ServiceFetcher(final String pathSid) { - this.pathSid = pathSid; + public ServiceFetcher(final String pathsid) { + this.pathsid = pathsid; } + @Override public Service fetch(final TwilioRestClient client) { + String path = "/v1/Services/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.IPMESSAGING.toString(), - path + HttpMethod.GET, + Domains.IPMESSAGING.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Service fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Service fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Service.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/ipmessaging/v1/ServiceReader.java b/src/main/java/com/twilio/rest/ipmessaging/v1/ServiceReader.java index e5d697405a..d6ec119902 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v1/ServiceReader.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v1/ServiceReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -31,105 +32,83 @@ public class ServiceReader extends Reader { private Long pageSize; - public ServiceReader() {} + public ServiceReader() { + } + public ServiceReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/Services"; + Request request = new Request( - HttpMethod.GET, - Domains.IPMESSAGING.toString(), - path + HttpMethod.GET, + Domains.IPMESSAGING.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Service read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Service read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "services", - response.getContent(), - Service.class, - client.getObjectMapper() - ); + "services", + response.getContent(), + Service.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.IPMESSAGING.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.IPMESSAGING.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/ipmessaging/v1/ServiceUpdater.java b/src/main/java/com/twilio/rest/ipmessaging/v1/ServiceUpdater.java index 02c838a81f..cc8f424941 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v1/ServiceUpdater.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v1/ServiceUpdater.java @@ -16,7 +16,9 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; import com.twilio.converter.Promoter; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,12 +27,12 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.net.URI; import java.util.List; public class ServiceUpdater extends Updater { - - private String pathSid; + private String pathsid; private String friendlyName; private String defaultServiceRoleSid; private String defaultChannelRoleSid; @@ -86,149 +88,125 @@ public class ServiceUpdater extends Updater { private Integer limitsChannelMembers; private Integer limitsUserChannels; - public ServiceUpdater(final String pathSid) { - this.pathSid = pathSid; + public ServiceUpdater(final String pathsid) { + this.pathsid = pathsid; } + public ServiceUpdater setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } - public ServiceUpdater setDefaultServiceRoleSid( - final String defaultServiceRoleSid - ) { + + public ServiceUpdater setDefaultServiceRoleSid(final String defaultServiceRoleSid) { this.defaultServiceRoleSid = defaultServiceRoleSid; return this; } - public ServiceUpdater setDefaultChannelRoleSid( - final String defaultChannelRoleSid - ) { + + public ServiceUpdater setDefaultChannelRoleSid(final String defaultChannelRoleSid) { this.defaultChannelRoleSid = defaultChannelRoleSid; return this; } - public ServiceUpdater setDefaultChannelCreatorRoleSid( - final String defaultChannelCreatorRoleSid - ) { + + public ServiceUpdater setDefaultChannelCreatorRoleSid(final String defaultChannelCreatorRoleSid) { this.defaultChannelCreatorRoleSid = defaultChannelCreatorRoleSid; return this; } - public ServiceUpdater setReadStatusEnabled( - final Boolean readStatusEnabled - ) { + + public ServiceUpdater setReadStatusEnabled(final Boolean readStatusEnabled) { this.readStatusEnabled = readStatusEnabled; return this; } - public ServiceUpdater setReachabilityEnabled( - final Boolean reachabilityEnabled - ) { + + public ServiceUpdater setReachabilityEnabled(final Boolean reachabilityEnabled) { this.reachabilityEnabled = reachabilityEnabled; return this; } - public ServiceUpdater setTypingIndicatorTimeout( - final Integer typingIndicatorTimeout - ) { + + public ServiceUpdater setTypingIndicatorTimeout(final Integer typingIndicatorTimeout) { this.typingIndicatorTimeout = typingIndicatorTimeout; return this; } - public ServiceUpdater setConsumptionReportInterval( - final Integer consumptionReportInterval - ) { + + public ServiceUpdater setConsumptionReportInterval(final Integer consumptionReportInterval) { this.consumptionReportInterval = consumptionReportInterval; return this; } - public ServiceUpdater setNotificationsNewMessageEnabled( - final Boolean notificationsNewMessageEnabled - ) { + + public ServiceUpdater setNotificationsNewMessageEnabled(final Boolean notificationsNewMessageEnabled) { this.notificationsNewMessageEnabled = notificationsNewMessageEnabled; return this; } - public ServiceUpdater setNotificationsNewMessageTemplate( - final String notificationsNewMessageTemplate - ) { + + public ServiceUpdater setNotificationsNewMessageTemplate(final String notificationsNewMessageTemplate) { this.notificationsNewMessageTemplate = notificationsNewMessageTemplate; return this; } - public ServiceUpdater setNotificationsAddedToChannelEnabled( - final Boolean notificationsAddedToChannelEnabled - ) { - this.notificationsAddedToChannelEnabled = - notificationsAddedToChannelEnabled; + + public ServiceUpdater setNotificationsAddedToChannelEnabled(final Boolean notificationsAddedToChannelEnabled) { + this.notificationsAddedToChannelEnabled = notificationsAddedToChannelEnabled; return this; } - public ServiceUpdater setNotificationsAddedToChannelTemplate( - final String notificationsAddedToChannelTemplate - ) { - this.notificationsAddedToChannelTemplate = - notificationsAddedToChannelTemplate; + + public ServiceUpdater setNotificationsAddedToChannelTemplate(final String notificationsAddedToChannelTemplate) { + this.notificationsAddedToChannelTemplate = notificationsAddedToChannelTemplate; return this; } - public ServiceUpdater setNotificationsRemovedFromChannelEnabled( - final Boolean notificationsRemovedFromChannelEnabled - ) { - this.notificationsRemovedFromChannelEnabled = - notificationsRemovedFromChannelEnabled; + + public ServiceUpdater setNotificationsRemovedFromChannelEnabled(final Boolean notificationsRemovedFromChannelEnabled) { + this.notificationsRemovedFromChannelEnabled = notificationsRemovedFromChannelEnabled; return this; } - public ServiceUpdater setNotificationsRemovedFromChannelTemplate( - final String notificationsRemovedFromChannelTemplate - ) { - this.notificationsRemovedFromChannelTemplate = - notificationsRemovedFromChannelTemplate; + + public ServiceUpdater setNotificationsRemovedFromChannelTemplate(final String notificationsRemovedFromChannelTemplate) { + this.notificationsRemovedFromChannelTemplate = notificationsRemovedFromChannelTemplate; return this; } - public ServiceUpdater setNotificationsInvitedToChannelEnabled( - final Boolean notificationsInvitedToChannelEnabled - ) { - this.notificationsInvitedToChannelEnabled = - notificationsInvitedToChannelEnabled; + + public ServiceUpdater setNotificationsInvitedToChannelEnabled(final Boolean notificationsInvitedToChannelEnabled) { + this.notificationsInvitedToChannelEnabled = notificationsInvitedToChannelEnabled; return this; } - public ServiceUpdater setNotificationsInvitedToChannelTemplate( - final String notificationsInvitedToChannelTemplate - ) { - this.notificationsInvitedToChannelTemplate = - notificationsInvitedToChannelTemplate; + + public ServiceUpdater setNotificationsInvitedToChannelTemplate(final String notificationsInvitedToChannelTemplate) { + this.notificationsInvitedToChannelTemplate = notificationsInvitedToChannelTemplate; return this; } + public ServiceUpdater setPreWebhookUrl(final URI preWebhookUrl) { this.preWebhookUrl = preWebhookUrl; return this; } - public ServiceUpdater setPreWebhookUrl(final String preWebhookUrl) { - return setPreWebhookUrl(Promoter.uriFromString(preWebhookUrl)); - } public ServiceUpdater setPostWebhookUrl(final URI postWebhookUrl) { this.postWebhookUrl = postWebhookUrl; return this; } - public ServiceUpdater setPostWebhookUrl(final String postWebhookUrl) { - return setPostWebhookUrl(Promoter.uriFromString(postWebhookUrl)); - } public ServiceUpdater setWebhookMethod(final HttpMethod webhookMethod) { this.webhookMethod = webhookMethod; return this; } + public ServiceUpdater setWebhookFilters(final List webhookFilters) { this.webhookFilters = webhookFilters; return this; @@ -238,401 +216,237 @@ public ServiceUpdater setWebhookFilters(final String webhookFilters) { return setWebhookFilters(Promoter.listOfOne(webhookFilters)); } - public ServiceUpdater setWebhooksOnMessageSendUrl( - final URI webhooksOnMessageSendUrl - ) { + public ServiceUpdater setWebhooksOnMessageSendUrl(final URI webhooksOnMessageSendUrl) { this.webhooksOnMessageSendUrl = webhooksOnMessageSendUrl; return this; } - public ServiceUpdater setWebhooksOnMessageSendUrl( - final String webhooksOnMessageSendUrl - ) { - return setWebhooksOnMessageSendUrl( - Promoter.uriFromString(webhooksOnMessageSendUrl) - ); - } - public ServiceUpdater setWebhooksOnMessageSendMethod( - final HttpMethod webhooksOnMessageSendMethod - ) { + public ServiceUpdater setWebhooksOnMessageSendMethod(final HttpMethod webhooksOnMessageSendMethod) { this.webhooksOnMessageSendMethod = webhooksOnMessageSendMethod; return this; } - public ServiceUpdater setWebhooksOnMessageUpdateUrl( - final URI webhooksOnMessageUpdateUrl - ) { + + public ServiceUpdater setWebhooksOnMessageUpdateUrl(final URI webhooksOnMessageUpdateUrl) { this.webhooksOnMessageUpdateUrl = webhooksOnMessageUpdateUrl; return this; } - public ServiceUpdater setWebhooksOnMessageUpdateUrl( - final String webhooksOnMessageUpdateUrl - ) { - return setWebhooksOnMessageUpdateUrl( - Promoter.uriFromString(webhooksOnMessageUpdateUrl) - ); - } - public ServiceUpdater setWebhooksOnMessageUpdateMethod( - final HttpMethod webhooksOnMessageUpdateMethod - ) { + public ServiceUpdater setWebhooksOnMessageUpdateMethod(final HttpMethod webhooksOnMessageUpdateMethod) { this.webhooksOnMessageUpdateMethod = webhooksOnMessageUpdateMethod; return this; } - public ServiceUpdater setWebhooksOnMessageRemoveUrl( - final URI webhooksOnMessageRemoveUrl - ) { + + public ServiceUpdater setWebhooksOnMessageRemoveUrl(final URI webhooksOnMessageRemoveUrl) { this.webhooksOnMessageRemoveUrl = webhooksOnMessageRemoveUrl; return this; } - public ServiceUpdater setWebhooksOnMessageRemoveUrl( - final String webhooksOnMessageRemoveUrl - ) { - return setWebhooksOnMessageRemoveUrl( - Promoter.uriFromString(webhooksOnMessageRemoveUrl) - ); - } - public ServiceUpdater setWebhooksOnMessageRemoveMethod( - final HttpMethod webhooksOnMessageRemoveMethod - ) { + public ServiceUpdater setWebhooksOnMessageRemoveMethod(final HttpMethod webhooksOnMessageRemoveMethod) { this.webhooksOnMessageRemoveMethod = webhooksOnMessageRemoveMethod; return this; } - public ServiceUpdater setWebhooksOnChannelAddUrl( - final URI webhooksOnChannelAddUrl - ) { + + public ServiceUpdater setWebhooksOnChannelAddUrl(final URI webhooksOnChannelAddUrl) { this.webhooksOnChannelAddUrl = webhooksOnChannelAddUrl; return this; } - public ServiceUpdater setWebhooksOnChannelAddUrl( - final String webhooksOnChannelAddUrl - ) { - return setWebhooksOnChannelAddUrl( - Promoter.uriFromString(webhooksOnChannelAddUrl) - ); - } - public ServiceUpdater setWebhooksOnChannelAddMethod( - final HttpMethod webhooksOnChannelAddMethod - ) { + public ServiceUpdater setWebhooksOnChannelAddMethod(final HttpMethod webhooksOnChannelAddMethod) { this.webhooksOnChannelAddMethod = webhooksOnChannelAddMethod; return this; } - public ServiceUpdater setWebhooksOnChannelDestroyUrl( - final URI webhooksOnChannelDestroyUrl - ) { + + public ServiceUpdater setWebhooksOnChannelDestroyUrl(final URI webhooksOnChannelDestroyUrl) { this.webhooksOnChannelDestroyUrl = webhooksOnChannelDestroyUrl; return this; } - public ServiceUpdater setWebhooksOnChannelDestroyUrl( - final String webhooksOnChannelDestroyUrl - ) { - return setWebhooksOnChannelDestroyUrl( - Promoter.uriFromString(webhooksOnChannelDestroyUrl) - ); - } - public ServiceUpdater setWebhooksOnChannelDestroyMethod( - final HttpMethod webhooksOnChannelDestroyMethod - ) { + public ServiceUpdater setWebhooksOnChannelDestroyMethod(final HttpMethod webhooksOnChannelDestroyMethod) { this.webhooksOnChannelDestroyMethod = webhooksOnChannelDestroyMethod; return this; } - public ServiceUpdater setWebhooksOnChannelUpdateUrl( - final URI webhooksOnChannelUpdateUrl - ) { + + public ServiceUpdater setWebhooksOnChannelUpdateUrl(final URI webhooksOnChannelUpdateUrl) { this.webhooksOnChannelUpdateUrl = webhooksOnChannelUpdateUrl; return this; } - public ServiceUpdater setWebhooksOnChannelUpdateUrl( - final String webhooksOnChannelUpdateUrl - ) { - return setWebhooksOnChannelUpdateUrl( - Promoter.uriFromString(webhooksOnChannelUpdateUrl) - ); - } - public ServiceUpdater setWebhooksOnChannelUpdateMethod( - final HttpMethod webhooksOnChannelUpdateMethod - ) { + public ServiceUpdater setWebhooksOnChannelUpdateMethod(final HttpMethod webhooksOnChannelUpdateMethod) { this.webhooksOnChannelUpdateMethod = webhooksOnChannelUpdateMethod; return this; } - public ServiceUpdater setWebhooksOnMemberAddUrl( - final URI webhooksOnMemberAddUrl - ) { + + public ServiceUpdater setWebhooksOnMemberAddUrl(final URI webhooksOnMemberAddUrl) { this.webhooksOnMemberAddUrl = webhooksOnMemberAddUrl; return this; } - public ServiceUpdater setWebhooksOnMemberAddUrl( - final String webhooksOnMemberAddUrl - ) { - return setWebhooksOnMemberAddUrl( - Promoter.uriFromString(webhooksOnMemberAddUrl) - ); - } - public ServiceUpdater setWebhooksOnMemberAddMethod( - final HttpMethod webhooksOnMemberAddMethod - ) { + public ServiceUpdater setWebhooksOnMemberAddMethod(final HttpMethod webhooksOnMemberAddMethod) { this.webhooksOnMemberAddMethod = webhooksOnMemberAddMethod; return this; } - public ServiceUpdater setWebhooksOnMemberRemoveUrl( - final URI webhooksOnMemberRemoveUrl - ) { + + public ServiceUpdater setWebhooksOnMemberRemoveUrl(final URI webhooksOnMemberRemoveUrl) { this.webhooksOnMemberRemoveUrl = webhooksOnMemberRemoveUrl; return this; } - public ServiceUpdater setWebhooksOnMemberRemoveUrl( - final String webhooksOnMemberRemoveUrl - ) { - return setWebhooksOnMemberRemoveUrl( - Promoter.uriFromString(webhooksOnMemberRemoveUrl) - ); - } - public ServiceUpdater setWebhooksOnMemberRemoveMethod( - final HttpMethod webhooksOnMemberRemoveMethod - ) { + public ServiceUpdater setWebhooksOnMemberRemoveMethod(final HttpMethod webhooksOnMemberRemoveMethod) { this.webhooksOnMemberRemoveMethod = webhooksOnMemberRemoveMethod; return this; } - public ServiceUpdater setWebhooksOnMessageSentUrl( - final URI webhooksOnMessageSentUrl - ) { + + public ServiceUpdater setWebhooksOnMessageSentUrl(final URI webhooksOnMessageSentUrl) { this.webhooksOnMessageSentUrl = webhooksOnMessageSentUrl; return this; } - public ServiceUpdater setWebhooksOnMessageSentUrl( - final String webhooksOnMessageSentUrl - ) { - return setWebhooksOnMessageSentUrl( - Promoter.uriFromString(webhooksOnMessageSentUrl) - ); - } - public ServiceUpdater setWebhooksOnMessageSentMethod( - final HttpMethod webhooksOnMessageSentMethod - ) { + public ServiceUpdater setWebhooksOnMessageSentMethod(final HttpMethod webhooksOnMessageSentMethod) { this.webhooksOnMessageSentMethod = webhooksOnMessageSentMethod; return this; } - public ServiceUpdater setWebhooksOnMessageUpdatedUrl( - final URI webhooksOnMessageUpdatedUrl - ) { + + public ServiceUpdater setWebhooksOnMessageUpdatedUrl(final URI webhooksOnMessageUpdatedUrl) { this.webhooksOnMessageUpdatedUrl = webhooksOnMessageUpdatedUrl; return this; } - public ServiceUpdater setWebhooksOnMessageUpdatedUrl( - final String webhooksOnMessageUpdatedUrl - ) { - return setWebhooksOnMessageUpdatedUrl( - Promoter.uriFromString(webhooksOnMessageUpdatedUrl) - ); - } - public ServiceUpdater setWebhooksOnMessageUpdatedMethod( - final HttpMethod webhooksOnMessageUpdatedMethod - ) { + public ServiceUpdater setWebhooksOnMessageUpdatedMethod(final HttpMethod webhooksOnMessageUpdatedMethod) { this.webhooksOnMessageUpdatedMethod = webhooksOnMessageUpdatedMethod; return this; } - public ServiceUpdater setWebhooksOnMessageRemovedUrl( - final URI webhooksOnMessageRemovedUrl - ) { + + public ServiceUpdater setWebhooksOnMessageRemovedUrl(final URI webhooksOnMessageRemovedUrl) { this.webhooksOnMessageRemovedUrl = webhooksOnMessageRemovedUrl; return this; } - public ServiceUpdater setWebhooksOnMessageRemovedUrl( - final String webhooksOnMessageRemovedUrl - ) { - return setWebhooksOnMessageRemovedUrl( - Promoter.uriFromString(webhooksOnMessageRemovedUrl) - ); - } - public ServiceUpdater setWebhooksOnMessageRemovedMethod( - final HttpMethod webhooksOnMessageRemovedMethod - ) { + public ServiceUpdater setWebhooksOnMessageRemovedMethod(final HttpMethod webhooksOnMessageRemovedMethod) { this.webhooksOnMessageRemovedMethod = webhooksOnMessageRemovedMethod; return this; } - public ServiceUpdater setWebhooksOnChannelAddedUrl( - final URI webhooksOnChannelAddedUrl - ) { + + public ServiceUpdater setWebhooksOnChannelAddedUrl(final URI webhooksOnChannelAddedUrl) { this.webhooksOnChannelAddedUrl = webhooksOnChannelAddedUrl; return this; } - public ServiceUpdater setWebhooksOnChannelAddedUrl( - final String webhooksOnChannelAddedUrl - ) { - return setWebhooksOnChannelAddedUrl( - Promoter.uriFromString(webhooksOnChannelAddedUrl) - ); - } - public ServiceUpdater setWebhooksOnChannelAddedMethod( - final HttpMethod webhooksOnChannelAddedMethod - ) { + public ServiceUpdater setWebhooksOnChannelAddedMethod(final HttpMethod webhooksOnChannelAddedMethod) { this.webhooksOnChannelAddedMethod = webhooksOnChannelAddedMethod; return this; } - public ServiceUpdater setWebhooksOnChannelDestroyedUrl( - final URI webhooksOnChannelDestroyedUrl - ) { + + public ServiceUpdater setWebhooksOnChannelDestroyedUrl(final URI webhooksOnChannelDestroyedUrl) { this.webhooksOnChannelDestroyedUrl = webhooksOnChannelDestroyedUrl; return this; } - public ServiceUpdater setWebhooksOnChannelDestroyedUrl( - final String webhooksOnChannelDestroyedUrl - ) { - return setWebhooksOnChannelDestroyedUrl( - Promoter.uriFromString(webhooksOnChannelDestroyedUrl) - ); - } - public ServiceUpdater setWebhooksOnChannelDestroyedMethod( - final HttpMethod webhooksOnChannelDestroyedMethod - ) { - this.webhooksOnChannelDestroyedMethod = - webhooksOnChannelDestroyedMethod; + public ServiceUpdater setWebhooksOnChannelDestroyedMethod(final HttpMethod webhooksOnChannelDestroyedMethod) { + this.webhooksOnChannelDestroyedMethod = webhooksOnChannelDestroyedMethod; return this; } - public ServiceUpdater setWebhooksOnChannelUpdatedUrl( - final URI webhooksOnChannelUpdatedUrl - ) { + + public ServiceUpdater setWebhooksOnChannelUpdatedUrl(final URI webhooksOnChannelUpdatedUrl) { this.webhooksOnChannelUpdatedUrl = webhooksOnChannelUpdatedUrl; return this; } - public ServiceUpdater setWebhooksOnChannelUpdatedUrl( - final String webhooksOnChannelUpdatedUrl - ) { - return setWebhooksOnChannelUpdatedUrl( - Promoter.uriFromString(webhooksOnChannelUpdatedUrl) - ); - } - public ServiceUpdater setWebhooksOnChannelUpdatedMethod( - final HttpMethod webhooksOnChannelUpdatedMethod - ) { + public ServiceUpdater setWebhooksOnChannelUpdatedMethod(final HttpMethod webhooksOnChannelUpdatedMethod) { this.webhooksOnChannelUpdatedMethod = webhooksOnChannelUpdatedMethod; return this; } - public ServiceUpdater setWebhooksOnMemberAddedUrl( - final URI webhooksOnMemberAddedUrl - ) { + + public ServiceUpdater setWebhooksOnMemberAddedUrl(final URI webhooksOnMemberAddedUrl) { this.webhooksOnMemberAddedUrl = webhooksOnMemberAddedUrl; return this; } - public ServiceUpdater setWebhooksOnMemberAddedUrl( - final String webhooksOnMemberAddedUrl - ) { - return setWebhooksOnMemberAddedUrl( - Promoter.uriFromString(webhooksOnMemberAddedUrl) - ); - } - public ServiceUpdater setWebhooksOnMemberAddedMethod( - final HttpMethod webhooksOnMemberAddedMethod - ) { + public ServiceUpdater setWebhooksOnMemberAddedMethod(final HttpMethod webhooksOnMemberAddedMethod) { this.webhooksOnMemberAddedMethod = webhooksOnMemberAddedMethod; return this; } - public ServiceUpdater setWebhooksOnMemberRemovedUrl( - final URI webhooksOnMemberRemovedUrl - ) { + + public ServiceUpdater setWebhooksOnMemberRemovedUrl(final URI webhooksOnMemberRemovedUrl) { this.webhooksOnMemberRemovedUrl = webhooksOnMemberRemovedUrl; return this; } - public ServiceUpdater setWebhooksOnMemberRemovedUrl( - final String webhooksOnMemberRemovedUrl - ) { - return setWebhooksOnMemberRemovedUrl( - Promoter.uriFromString(webhooksOnMemberRemovedUrl) - ); - } - public ServiceUpdater setWebhooksOnMemberRemovedMethod( - final HttpMethod webhooksOnMemberRemovedMethod - ) { + public ServiceUpdater setWebhooksOnMemberRemovedMethod(final HttpMethod webhooksOnMemberRemovedMethod) { this.webhooksOnMemberRemovedMethod = webhooksOnMemberRemovedMethod; return this; } - public ServiceUpdater setLimitsChannelMembers( - final Integer limitsChannelMembers - ) { + + public ServiceUpdater setLimitsChannelMembers(final Integer limitsChannelMembers) { this.limitsChannelMembers = limitsChannelMembers; return this; } - public ServiceUpdater setLimitsUserChannels( - final Integer limitsUserChannels - ) { + + public ServiceUpdater setLimitsUserChannels(final Integer limitsUserChannels) { this.limitsUserChannels = limitsUserChannels; return this; } + @Override public Service update(final TwilioRestClient client) { + String path = "/v1/Services/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.IPMESSAGING.toString(), - path + HttpMethod.POST, + Domains.IPMESSAGING.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Service update failed: Unable to connect to server" - ); + throw new ApiConnectionException("Service update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -641,316 +455,278 @@ public Service update(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + if (defaultServiceRoleSid != null) { - request.addPostParam( - "DefaultServiceRoleSid", - defaultServiceRoleSid - ); + Serializer.toString(request, "DefaultServiceRoleSid", defaultServiceRoleSid, ParameterType.URLENCODED); } + + if (defaultChannelRoleSid != null) { - request.addPostParam( - "DefaultChannelRoleSid", - defaultChannelRoleSid - ); + Serializer.toString(request, "DefaultChannelRoleSid", defaultChannelRoleSid, ParameterType.URLENCODED); } + + if (defaultChannelCreatorRoleSid != null) { - request.addPostParam( - "DefaultChannelCreatorRoleSid", - defaultChannelCreatorRoleSid - ); + Serializer.toString(request, "DefaultChannelCreatorRoleSid", defaultChannelCreatorRoleSid, ParameterType.URLENCODED); } + + if (readStatusEnabled != null) { - request.addPostParam( - "ReadStatusEnabled", - readStatusEnabled.toString() - ); + Serializer.toString(request, "ReadStatusEnabled", readStatusEnabled, ParameterType.URLENCODED); } + + if (reachabilityEnabled != null) { - request.addPostParam( - "ReachabilityEnabled", - reachabilityEnabled.toString() - ); + Serializer.toString(request, "ReachabilityEnabled", reachabilityEnabled, ParameterType.URLENCODED); } + + if (typingIndicatorTimeout != null) { - request.addPostParam( - "TypingIndicatorTimeout", - typingIndicatorTimeout.toString() - ); + Serializer.toString(request, "TypingIndicatorTimeout", typingIndicatorTimeout, ParameterType.URLENCODED); } + + if (consumptionReportInterval != null) { - request.addPostParam( - "ConsumptionReportInterval", - consumptionReportInterval.toString() - ); + Serializer.toString(request, "ConsumptionReportInterval", consumptionReportInterval, ParameterType.URLENCODED); } + + if (notificationsNewMessageEnabled != null) { - request.addPostParam( - "Notifications.NewMessage.Enabled", - notificationsNewMessageEnabled.toString() - ); + Serializer.toString(request, "Notifications.NewMessage.Enabled", notificationsNewMessageEnabled, ParameterType.URLENCODED); } + + if (notificationsNewMessageTemplate != null) { - request.addPostParam( - "Notifications.NewMessage.Template", - notificationsNewMessageTemplate - ); + Serializer.toString(request, "Notifications.NewMessage.Template", notificationsNewMessageTemplate, ParameterType.URLENCODED); } + + if (notificationsAddedToChannelEnabled != null) { - request.addPostParam( - "Notifications.AddedToChannel.Enabled", - notificationsAddedToChannelEnabled.toString() - ); + Serializer.toString(request, "Notifications.AddedToChannel.Enabled", notificationsAddedToChannelEnabled, ParameterType.URLENCODED); } + + if (notificationsAddedToChannelTemplate != null) { - request.addPostParam( - "Notifications.AddedToChannel.Template", - notificationsAddedToChannelTemplate - ); + Serializer.toString(request, "Notifications.AddedToChannel.Template", notificationsAddedToChannelTemplate, ParameterType.URLENCODED); } + + if (notificationsRemovedFromChannelEnabled != null) { - request.addPostParam( - "Notifications.RemovedFromChannel.Enabled", - notificationsRemovedFromChannelEnabled.toString() - ); + Serializer.toString(request, "Notifications.RemovedFromChannel.Enabled", notificationsRemovedFromChannelEnabled, ParameterType.URLENCODED); } + + if (notificationsRemovedFromChannelTemplate != null) { - request.addPostParam( - "Notifications.RemovedFromChannel.Template", - notificationsRemovedFromChannelTemplate - ); + Serializer.toString(request, "Notifications.RemovedFromChannel.Template", notificationsRemovedFromChannelTemplate, ParameterType.URLENCODED); } + + if (notificationsInvitedToChannelEnabled != null) { - request.addPostParam( - "Notifications.InvitedToChannel.Enabled", - notificationsInvitedToChannelEnabled.toString() - ); + Serializer.toString(request, "Notifications.InvitedToChannel.Enabled", notificationsInvitedToChannelEnabled, ParameterType.URLENCODED); } + + if (notificationsInvitedToChannelTemplate != null) { - request.addPostParam( - "Notifications.InvitedToChannel.Template", - notificationsInvitedToChannelTemplate - ); + Serializer.toString(request, "Notifications.InvitedToChannel.Template", notificationsInvitedToChannelTemplate, ParameterType.URLENCODED); } + + if (preWebhookUrl != null) { - request.addPostParam("PreWebhookUrl", preWebhookUrl.toString()); + Serializer.toString(request, "PreWebhookUrl", preWebhookUrl, ParameterType.URLENCODED); } + + if (postWebhookUrl != null) { - request.addPostParam("PostWebhookUrl", postWebhookUrl.toString()); + Serializer.toString(request, "PostWebhookUrl", postWebhookUrl, ParameterType.URLENCODED); } + + if (webhookMethod != null) { - request.addPostParam("WebhookMethod", webhookMethod.toString()); + Serializer.toString(request, "WebhookMethod", webhookMethod, ParameterType.URLENCODED); } + + if (webhookFilters != null) { - for (String prop : webhookFilters) { - request.addPostParam("WebhookFilters", prop); + for (String param : webhookFilters) { + Serializer.toString(request, "WebhookFilters", param, ParameterType.URLENCODED); } } + + if (webhooksOnMessageSendUrl != null) { - request.addPostParam( - "Webhooks.OnMessageSend.Url", - webhooksOnMessageSendUrl.toString() - ); + Serializer.toString(request, "Webhooks.OnMessageSend.Url", webhooksOnMessageSendUrl, ParameterType.URLENCODED); } + + if (webhooksOnMessageSendMethod != null) { - request.addPostParam( - "Webhooks.OnMessageSend.Method", - webhooksOnMessageSendMethod.toString() - ); + Serializer.toString(request, "Webhooks.OnMessageSend.Method", webhooksOnMessageSendMethod, ParameterType.URLENCODED); } + + if (webhooksOnMessageUpdateUrl != null) { - request.addPostParam( - "Webhooks.OnMessageUpdate.Url", - webhooksOnMessageUpdateUrl.toString() - ); + Serializer.toString(request, "Webhooks.OnMessageUpdate.Url", webhooksOnMessageUpdateUrl, ParameterType.URLENCODED); } + + if (webhooksOnMessageUpdateMethod != null) { - request.addPostParam( - "Webhooks.OnMessageUpdate.Method", - webhooksOnMessageUpdateMethod.toString() - ); + Serializer.toString(request, "Webhooks.OnMessageUpdate.Method", webhooksOnMessageUpdateMethod, ParameterType.URLENCODED); } + + if (webhooksOnMessageRemoveUrl != null) { - request.addPostParam( - "Webhooks.OnMessageRemove.Url", - webhooksOnMessageRemoveUrl.toString() - ); + Serializer.toString(request, "Webhooks.OnMessageRemove.Url", webhooksOnMessageRemoveUrl, ParameterType.URLENCODED); } + + if (webhooksOnMessageRemoveMethod != null) { - request.addPostParam( - "Webhooks.OnMessageRemove.Method", - webhooksOnMessageRemoveMethod.toString() - ); + Serializer.toString(request, "Webhooks.OnMessageRemove.Method", webhooksOnMessageRemoveMethod, ParameterType.URLENCODED); } + + if (webhooksOnChannelAddUrl != null) { - request.addPostParam( - "Webhooks.OnChannelAdd.Url", - webhooksOnChannelAddUrl.toString() - ); + Serializer.toString(request, "Webhooks.OnChannelAdd.Url", webhooksOnChannelAddUrl, ParameterType.URLENCODED); } + + if (webhooksOnChannelAddMethod != null) { - request.addPostParam( - "Webhooks.OnChannelAdd.Method", - webhooksOnChannelAddMethod.toString() - ); + Serializer.toString(request, "Webhooks.OnChannelAdd.Method", webhooksOnChannelAddMethod, ParameterType.URLENCODED); } + + if (webhooksOnChannelDestroyUrl != null) { - request.addPostParam( - "Webhooks.OnChannelDestroy.Url", - webhooksOnChannelDestroyUrl.toString() - ); + Serializer.toString(request, "Webhooks.OnChannelDestroy.Url", webhooksOnChannelDestroyUrl, ParameterType.URLENCODED); } + + if (webhooksOnChannelDestroyMethod != null) { - request.addPostParam( - "Webhooks.OnChannelDestroy.Method", - webhooksOnChannelDestroyMethod.toString() - ); + Serializer.toString(request, "Webhooks.OnChannelDestroy.Method", webhooksOnChannelDestroyMethod, ParameterType.URLENCODED); } + + if (webhooksOnChannelUpdateUrl != null) { - request.addPostParam( - "Webhooks.OnChannelUpdate.Url", - webhooksOnChannelUpdateUrl.toString() - ); + Serializer.toString(request, "Webhooks.OnChannelUpdate.Url", webhooksOnChannelUpdateUrl, ParameterType.URLENCODED); } + + if (webhooksOnChannelUpdateMethod != null) { - request.addPostParam( - "Webhooks.OnChannelUpdate.Method", - webhooksOnChannelUpdateMethod.toString() - ); + Serializer.toString(request, "Webhooks.OnChannelUpdate.Method", webhooksOnChannelUpdateMethod, ParameterType.URLENCODED); } + + if (webhooksOnMemberAddUrl != null) { - request.addPostParam( - "Webhooks.OnMemberAdd.Url", - webhooksOnMemberAddUrl.toString() - ); + Serializer.toString(request, "Webhooks.OnMemberAdd.Url", webhooksOnMemberAddUrl, ParameterType.URLENCODED); } + + if (webhooksOnMemberAddMethod != null) { - request.addPostParam( - "Webhooks.OnMemberAdd.Method", - webhooksOnMemberAddMethod.toString() - ); + Serializer.toString(request, "Webhooks.OnMemberAdd.Method", webhooksOnMemberAddMethod, ParameterType.URLENCODED); } + + if (webhooksOnMemberRemoveUrl != null) { - request.addPostParam( - "Webhooks.OnMemberRemove.Url", - webhooksOnMemberRemoveUrl.toString() - ); + Serializer.toString(request, "Webhooks.OnMemberRemove.Url", webhooksOnMemberRemoveUrl, ParameterType.URLENCODED); } + + if (webhooksOnMemberRemoveMethod != null) { - request.addPostParam( - "Webhooks.OnMemberRemove.Method", - webhooksOnMemberRemoveMethod.toString() - ); + Serializer.toString(request, "Webhooks.OnMemberRemove.Method", webhooksOnMemberRemoveMethod, ParameterType.URLENCODED); } + + if (webhooksOnMessageSentUrl != null) { - request.addPostParam( - "Webhooks.OnMessageSent.Url", - webhooksOnMessageSentUrl.toString() - ); + Serializer.toString(request, "Webhooks.OnMessageSent.Url", webhooksOnMessageSentUrl, ParameterType.URLENCODED); } + + if (webhooksOnMessageSentMethod != null) { - request.addPostParam( - "Webhooks.OnMessageSent.Method", - webhooksOnMessageSentMethod.toString() - ); + Serializer.toString(request, "Webhooks.OnMessageSent.Method", webhooksOnMessageSentMethod, ParameterType.URLENCODED); } + + if (webhooksOnMessageUpdatedUrl != null) { - request.addPostParam( - "Webhooks.OnMessageUpdated.Url", - webhooksOnMessageUpdatedUrl.toString() - ); + Serializer.toString(request, "Webhooks.OnMessageUpdated.Url", webhooksOnMessageUpdatedUrl, ParameterType.URLENCODED); } + + if (webhooksOnMessageUpdatedMethod != null) { - request.addPostParam( - "Webhooks.OnMessageUpdated.Method", - webhooksOnMessageUpdatedMethod.toString() - ); + Serializer.toString(request, "Webhooks.OnMessageUpdated.Method", webhooksOnMessageUpdatedMethod, ParameterType.URLENCODED); } + + if (webhooksOnMessageRemovedUrl != null) { - request.addPostParam( - "Webhooks.OnMessageRemoved.Url", - webhooksOnMessageRemovedUrl.toString() - ); + Serializer.toString(request, "Webhooks.OnMessageRemoved.Url", webhooksOnMessageRemovedUrl, ParameterType.URLENCODED); } + + if (webhooksOnMessageRemovedMethod != null) { - request.addPostParam( - "Webhooks.OnMessageRemoved.Method", - webhooksOnMessageRemovedMethod.toString() - ); + Serializer.toString(request, "Webhooks.OnMessageRemoved.Method", webhooksOnMessageRemovedMethod, ParameterType.URLENCODED); } + + if (webhooksOnChannelAddedUrl != null) { - request.addPostParam( - "Webhooks.OnChannelAdded.Url", - webhooksOnChannelAddedUrl.toString() - ); + Serializer.toString(request, "Webhooks.OnChannelAdded.Url", webhooksOnChannelAddedUrl, ParameterType.URLENCODED); } + + if (webhooksOnChannelAddedMethod != null) { - request.addPostParam( - "Webhooks.OnChannelAdded.Method", - webhooksOnChannelAddedMethod.toString() - ); + Serializer.toString(request, "Webhooks.OnChannelAdded.Method", webhooksOnChannelAddedMethod, ParameterType.URLENCODED); } + + if (webhooksOnChannelDestroyedUrl != null) { - request.addPostParam( - "Webhooks.OnChannelDestroyed.Url", - webhooksOnChannelDestroyedUrl.toString() - ); + Serializer.toString(request, "Webhooks.OnChannelDestroyed.Url", webhooksOnChannelDestroyedUrl, ParameterType.URLENCODED); } + + if (webhooksOnChannelDestroyedMethod != null) { - request.addPostParam( - "Webhooks.OnChannelDestroyed.Method", - webhooksOnChannelDestroyedMethod.toString() - ); + Serializer.toString(request, "Webhooks.OnChannelDestroyed.Method", webhooksOnChannelDestroyedMethod, ParameterType.URLENCODED); } + + if (webhooksOnChannelUpdatedUrl != null) { - request.addPostParam( - "Webhooks.OnChannelUpdated.Url", - webhooksOnChannelUpdatedUrl.toString() - ); + Serializer.toString(request, "Webhooks.OnChannelUpdated.Url", webhooksOnChannelUpdatedUrl, ParameterType.URLENCODED); } + + if (webhooksOnChannelUpdatedMethod != null) { - request.addPostParam( - "Webhooks.OnChannelUpdated.Method", - webhooksOnChannelUpdatedMethod.toString() - ); + Serializer.toString(request, "Webhooks.OnChannelUpdated.Method", webhooksOnChannelUpdatedMethod, ParameterType.URLENCODED); } + + if (webhooksOnMemberAddedUrl != null) { - request.addPostParam( - "Webhooks.OnMemberAdded.Url", - webhooksOnMemberAddedUrl.toString() - ); + Serializer.toString(request, "Webhooks.OnMemberAdded.Url", webhooksOnMemberAddedUrl, ParameterType.URLENCODED); } + + if (webhooksOnMemberAddedMethod != null) { - request.addPostParam( - "Webhooks.OnMemberAdded.Method", - webhooksOnMemberAddedMethod.toString() - ); + Serializer.toString(request, "Webhooks.OnMemberAdded.Method", webhooksOnMemberAddedMethod, ParameterType.URLENCODED); } + + if (webhooksOnMemberRemovedUrl != null) { - request.addPostParam( - "Webhooks.OnMemberRemoved.Url", - webhooksOnMemberRemovedUrl.toString() - ); + Serializer.toString(request, "Webhooks.OnMemberRemoved.Url", webhooksOnMemberRemovedUrl, ParameterType.URLENCODED); } + + if (webhooksOnMemberRemovedMethod != null) { - request.addPostParam( - "Webhooks.OnMemberRemoved.Method", - webhooksOnMemberRemovedMethod.toString() - ); + Serializer.toString(request, "Webhooks.OnMemberRemoved.Method", webhooksOnMemberRemovedMethod, ParameterType.URLENCODED); } + + if (limitsChannelMembers != null) { - request.addPostParam( - "Limits.ChannelMembers", - limitsChannelMembers.toString() - ); + Serializer.toString(request, "Limits.ChannelMembers", limitsChannelMembers, ParameterType.URLENCODED); } + + if (limitsUserChannels != null) { - request.addPostParam( - "Limits.UserChannels", - limitsUserChannels.toString() - ); + Serializer.toString(request, "Limits.UserChannels", limitsUserChannels, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/ipmessaging/v1/service/Channel.java b/src/main/java/com/twilio/rest/ipmessaging/v1/service/Channel.java index 716231236c..62aae1bc9e 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v1/service/Channel.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v1/service/Channel.java @@ -18,69 +18,93 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Channel extends Resource { - private static final long serialVersionUID = 188288773259274L; - public static ChannelCreator creator(final String pathServiceSid) { - return new ChannelCreator(pathServiceSid); + public static ChannelCreator creator(final String pathserviceSid) { + return new ChannelCreator( + pathserviceSid + ); } - public static ChannelDeleter deleter( - final String pathServiceSid, - final String pathSid - ) { - return new ChannelDeleter(pathServiceSid, pathSid); + + public static ChannelDeleter deleter(final String pathserviceSid, final String pathsid) { + return new ChannelDeleter( + pathserviceSid, pathsid + ); } - public static ChannelFetcher fetcher( - final String pathServiceSid, - final String pathSid - ) { - return new ChannelFetcher(pathServiceSid, pathSid); + + public static ChannelFetcher fetcher(final String pathserviceSid, final String pathsid) { + return new ChannelFetcher( + pathserviceSid, pathsid + ); } - public static ChannelReader reader(final String pathServiceSid) { - return new ChannelReader(pathServiceSid); + + public static ChannelReader reader(final String pathserviceSid) { + return new ChannelReader( + pathserviceSid + ); } - public static ChannelUpdater updater( - final String pathServiceSid, - final String pathSid - ) { - return new ChannelUpdater(pathServiceSid, pathSid); + + public static ChannelUpdater updater(final String pathserviceSid, final String pathsid) { + return new ChannelUpdater( + pathserviceSid, pathsid + ); + } + + + public enum ChannelType { + PUBLIC("public"), + PRIVATE("private"); + + private final String value; + + private ChannelType(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static ChannelType forValue(final String value) { + return Promoter.enumFromString(value, ChannelType.values()); + } } + /** * Converts a JSON String into a Channel object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Channel object represented by the provided JSON */ - public static Channel fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Channel fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Channel.class); @@ -95,14 +119,11 @@ public static Channel fromJson( * Converts a JSON InputStream into a Channel object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Channel object represented by the provided JSON */ - public static Channel fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Channel fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Channel.class); @@ -113,108 +134,81 @@ public static Channel fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String serviceSid; - private final String friendlyName; - private final String uniqueName; + @Getter private final String attributes; - private final Channel.ChannelType type; + @Getter + private final String createdBy; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; - private final String createdBy; + @Getter + private final String friendlyName; + @Getter + private final Map links; + @Getter private final Integer membersCount; + @Getter private final Integer messagesCount; + @Getter + private final String serviceSid; + @Getter + private final String sid; + @Getter + private final Channel.ChannelType type; + @Getter + private final String uniqueName; + @Getter private final URI url; - private final Map links; @JsonCreator private Channel( - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("service_sid") final String serviceSid, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("unique_name") final String uniqueName, - @JsonProperty("attributes") final String attributes, - @JsonProperty("type") final Channel.ChannelType type, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("created_by") final String createdBy, - @JsonProperty("members_count") final Integer membersCount, - @JsonProperty("messages_count") final Integer messagesCount, - @JsonProperty("url") final URI url, - @JsonProperty("links") final Map links + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("attributes") final String attributes, + @JsonProperty("created_by") final String createdBy, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("links") final Map links, + @JsonProperty("members_count") final Integer membersCount, + @JsonProperty("messages_count") final Integer messagesCount, + @JsonProperty("service_sid") final String serviceSid, + @JsonProperty("sid") final String sid, + @JsonProperty("type") final Channel.ChannelType type, + @JsonProperty("unique_name") final String uniqueName, + @JsonProperty("url") final URI url ) { - this.sid = sid; this.accountSid = accountSid; - this.serviceSid = serviceSid; - this.friendlyName = friendlyName; - this.uniqueName = uniqueName; this.attributes = attributes; - this.type = type; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); this.createdBy = createdBy; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; + this.friendlyName = friendlyName; + this.links = links; this.membersCount = membersCount; this.messagesCount = messagesCount; + this.serviceSid = serviceSid; + this.sid = sid; + this.type = type; + this.uniqueName = uniqueName; this.url = url; - this.links = links; - } - - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getServiceSid() { - return this.serviceSid; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final String getUniqueName() { - return this.uniqueName; - } - - public final String getAttributes() { - return this.attributes; - } - - public final Channel.ChannelType getType() { - return this.type; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final String getCreatedBy() { - return this.createdBy; - } - - public final Integer getMembersCount() { - return this.membersCount; - } - - public final Integer getMessagesCount() { - return this.messagesCount; - } - - public final URI getUrl() { - return this.url; - } - - public final Map getLinks() { - return this.links; } @Override @@ -228,62 +222,44 @@ public boolean equals(final Object o) { } Channel other = (Channel) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(serviceSid, other.serviceSid) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(uniqueName, other.uniqueName) && - Objects.equals(attributes, other.attributes) && - Objects.equals(type, other.type) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(createdBy, other.createdBy) && - Objects.equals(membersCount, other.membersCount) && - Objects.equals(messagesCount, other.messagesCount) && - Objects.equals(url, other.url) && - Objects.equals(links, other.links) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(attributes, other.attributes) && + Objects.equals(createdBy, other.createdBy) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(links, other.links) && + Objects.equals(membersCount, other.membersCount) && + Objects.equals(messagesCount, other.messagesCount) && + Objects.equals(serviceSid, other.serviceSid) && + Objects.equals(sid, other.sid) && + Objects.equals(type, other.type) && + Objects.equals(uniqueName, other.uniqueName) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - sid, - accountSid, - serviceSid, - friendlyName, - uniqueName, - attributes, - type, - dateCreated, - dateUpdated, - createdBy, - membersCount, - messagesCount, - url, - links + accountSid, + attributes, + createdBy, + dateCreated, + dateUpdated, + friendlyName, + links, + membersCount, + messagesCount, + serviceSid, + sid, + type, + uniqueName, + url ); } - public enum ChannelType { - PUBLIC("public"), - PRIVATE("private"); - private final String value; - - private ChannelType(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static ChannelType forValue(final String value) { - return Promoter.enumFromString(value, ChannelType.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/ipmessaging/v1/service/ChannelCreator.java b/src/main/java/com/twilio/rest/ipmessaging/v1/service/ChannelCreator.java index c42261ee45..5efb1af4c8 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v1/service/ChannelCreator.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v1/service/ChannelCreator.java @@ -14,8 +14,11 @@ package com.twilio.rest.ipmessaging.v1.service; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,68 +30,68 @@ public class ChannelCreator extends Creator { - private String pathServiceSid; + private String pathserviceSid; private String friendlyName; private String uniqueName; private String attributes; private Channel.ChannelType type; - public ChannelCreator(final String pathServiceSid) { - this.pathServiceSid = pathServiceSid; + public ChannelCreator(final String pathserviceSid) { + this.pathserviceSid = pathserviceSid; } + public ChannelCreator setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + public ChannelCreator setUniqueName(final String uniqueName) { this.uniqueName = uniqueName; return this; } + public ChannelCreator setAttributes(final String attributes) { this.attributes = attributes; return this; } + public ChannelCreator setType(final Channel.ChannelType type) { this.type = type; return this; } + @Override public Channel create(final TwilioRestClient client) { + String path = "/v1/Services/{ServiceSid}/Channels"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.IPMESSAGING.toString(), - path + HttpMethod.POST, + Domains.IPMESSAGING.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Channel creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("Channel creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -97,17 +100,26 @@ public Channel create(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + if (uniqueName != null) { - request.addPostParam("UniqueName", uniqueName); + Serializer.toString(request, "UniqueName", uniqueName, ParameterType.URLENCODED); } + + if (attributes != null) { - request.addPostParam("Attributes", attributes); + Serializer.toString(request, "Attributes", attributes, ParameterType.URLENCODED); } + + if (type != null) { - request.addPostParam("Type", type.toString()); + Serializer.toString(request, "Type", type, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/ipmessaging/v1/service/ChannelDeleter.java b/src/main/java/com/twilio/rest/ipmessaging/v1/service/ChannelDeleter.java index 341c30a651..f63a97a2ed 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v1/service/ChannelDeleter.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v1/service/ChannelDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.ipmessaging.v1.service; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,47 +26,41 @@ public class ChannelDeleter extends Deleter { - private String pathServiceSid; - private String pathSid; + private String pathserviceSid; + private String pathsid; - public ChannelDeleter(final String pathServiceSid, final String pathSid) { - this.pathServiceSid = pathServiceSid; - this.pathSid = pathSid; + public ChannelDeleter(final String pathserviceSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/v1/Services/{ServiceSid}/Channels/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.IPMESSAGING.toString(), - path + HttpMethod.DELETE, + Domains.IPMESSAGING.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Channel delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("Channel delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/ipmessaging/v1/service/ChannelFetcher.java b/src/main/java/com/twilio/rest/ipmessaging/v1/service/ChannelFetcher.java index 8d24fbfe08..0b2a503fc3 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v1/service/ChannelFetcher.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v1/service/ChannelFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.ipmessaging.v1.service; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,51 +26,44 @@ public class ChannelFetcher extends Fetcher { - private String pathServiceSid; - private String pathSid; + private String pathserviceSid; + private String pathsid; - public ChannelFetcher(final String pathServiceSid, final String pathSid) { - this.pathServiceSid = pathServiceSid; - this.pathSid = pathSid; + public ChannelFetcher(final String pathserviceSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathsid = pathsid; } + @Override public Channel fetch(final TwilioRestClient client) { + String path = "/v1/Services/{ServiceSid}/Channels/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.IPMESSAGING.toString(), - path + HttpMethod.GET, + Domains.IPMESSAGING.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Channel fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Channel fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Channel.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/ipmessaging/v1/service/ChannelReader.java b/src/main/java/com/twilio/rest/ipmessaging/v1/service/ChannelReader.java index 941d377b65..ad5f1c30e7 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v1/service/ChannelReader.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v1/service/ChannelReader.java @@ -17,8 +17,9 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; import com.twilio.converter.Promoter; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,18 +28,20 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.util.List; public class ChannelReader extends Reader { - private String pathServiceSid; + private String pathserviceSid; private List type; private Long pageSize; - public ChannelReader(final String pathServiceSid) { - this.pathServiceSid = pathServiceSid; + public ChannelReader(final String pathserviceSid) { + this.pathserviceSid = pathserviceSid; } + public ChannelReader setType(final List type) { this.type = type; return this; @@ -53,108 +56,82 @@ public ChannelReader setPageSize(final Long pageSize) { return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/Services/{ServiceSid}/Channels"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.IPMESSAGING.toString(), - path + HttpMethod.GET, + Domains.IPMESSAGING.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Channel read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Channel read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "channels", - response.getContent(), - Channel.class, - client.getObjectMapper() - ); + "channels", + response.getContent(), + Channel.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.IPMESSAGING.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.IPMESSAGING.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (type != null) { - for (Channel.ChannelType prop : type) { - request.addQueryParam("Type", prop.toString()); + for (Channel.ChannelType param : type) { + Serializer.toString(request, "Type", param, ParameterType.QUERY); } } + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/ipmessaging/v1/service/ChannelUpdater.java b/src/main/java/com/twilio/rest/ipmessaging/v1/service/ChannelUpdater.java index 0f31d4c1fb..8f0f1bb6f8 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v1/service/ChannelUpdater.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v1/service/ChannelUpdater.java @@ -16,6 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -26,66 +28,64 @@ import com.twilio.rest.Domains; public class ChannelUpdater extends Updater { - - private String pathServiceSid; - private String pathSid; + private String pathserviceSid; + private String pathsid; private String friendlyName; private String uniqueName; private String attributes; - public ChannelUpdater(final String pathServiceSid, final String pathSid) { - this.pathServiceSid = pathServiceSid; - this.pathSid = pathSid; + public ChannelUpdater(final String pathserviceSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathsid = pathsid; } + public ChannelUpdater setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + public ChannelUpdater setUniqueName(final String uniqueName) { this.uniqueName = uniqueName; return this; } + public ChannelUpdater setAttributes(final String attributes) { this.attributes = attributes; return this; } + @Override public Channel update(final TwilioRestClient client) { + String path = "/v1/Services/{ServiceSid}/Channels/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.IPMESSAGING.toString(), - path + HttpMethod.POST, + Domains.IPMESSAGING.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Channel update failed: Unable to connect to server" - ); + throw new ApiConnectionException("Channel update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -94,14 +94,21 @@ public Channel update(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + if (uniqueName != null) { - request.addPostParam("UniqueName", uniqueName); + Serializer.toString(request, "UniqueName", uniqueName, ParameterType.URLENCODED); } + + if (attributes != null) { - request.addPostParam("Attributes", attributes); + Serializer.toString(request, "Attributes", attributes, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/ipmessaging/v1/service/Role.java b/src/main/java/com/twilio/rest/ipmessaging/v1/service/Role.java index 85ffef93d3..1129a7328c 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v1/service/Role.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v1/service/Role.java @@ -18,74 +18,93 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.List; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Role extends Resource { - private static final long serialVersionUID = 252065084446046L; - public static RoleCreator creator( - final String pathServiceSid, - final String friendlyName, - final Role.RoleType type, - final List permission - ) { - return new RoleCreator(pathServiceSid, friendlyName, type, permission); + public static RoleCreator creator(final String pathserviceSid, final String friendlyName, final Role.RoleType type, final List permission) { + return new RoleCreator( + pathserviceSid, friendlyName, type, permission + ); } - public static RoleDeleter deleter( - final String pathServiceSid, - final String pathSid - ) { - return new RoleDeleter(pathServiceSid, pathSid); + + public static RoleDeleter deleter(final String pathserviceSid, final String pathsid) { + return new RoleDeleter( + pathserviceSid, pathsid + ); } - public static RoleFetcher fetcher( - final String pathServiceSid, - final String pathSid - ) { - return new RoleFetcher(pathServiceSid, pathSid); + + public static RoleFetcher fetcher(final String pathserviceSid, final String pathsid) { + return new RoleFetcher( + pathserviceSid, pathsid + ); + } + + + public static RoleReader reader(final String pathserviceSid) { + return new RoleReader( + pathserviceSid + ); } - public static RoleReader reader(final String pathServiceSid) { - return new RoleReader(pathServiceSid); + + public static RoleUpdater updater(final String pathserviceSid, final String pathsid, final List permission) { + return new RoleUpdater( + pathserviceSid, pathsid, permission + ); } - public static RoleUpdater updater( - final String pathServiceSid, - final String pathSid, - final List permission - ) { - return new RoleUpdater(pathServiceSid, pathSid, permission); + + public enum RoleType { + CHANNEL("channel"), + DEPLOYMENT("deployment"); + + private final String value; + + private RoleType(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static RoleType forValue(final String value) { + return Promoter.enumFromString(value, RoleType.values()); + } } + /** * Converts a JSON String into a Role object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Role object represented by the provided JSON */ - public static Role fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Role fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Role.class); @@ -100,14 +119,11 @@ public static Role fromJson( * Converts a JSON InputStream into a Role object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Role object represented by the provided JSON */ - public static Role fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Role fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Role.class); @@ -118,75 +134,63 @@ public static Role fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String serviceSid; - private final String friendlyName; - private final Role.RoleType type; - private final List permissions; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; + @Getter + private final String friendlyName; + @Getter + private final List permissions; + @Getter + private final String serviceSid; + @Getter + private final String sid; + @Getter + private final Role.RoleType type; + @Getter private final URI url; @JsonCreator private Role( - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("service_sid") final String serviceSid, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("type") final Role.RoleType type, - @JsonProperty("permissions") final List permissions, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("url") final URI url + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("permissions") final List permissions, + @JsonProperty("service_sid") final String serviceSid, + @JsonProperty("sid") final String sid, + @JsonProperty("type") final Role.RoleType type, + @JsonProperty("url") final URI url ) { - this.sid = sid; this.accountSid = accountSid; - this.serviceSid = serviceSid; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.friendlyName = friendlyName; - this.type = type; this.permissions = permissions; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); + this.serviceSid = serviceSid; + this.sid = sid; + this.type = type; this.url = url; } - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getServiceSid() { - return this.serviceSid; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final Role.RoleType getType() { - return this.type; - } - - public final List getPermissions() { - return this.permissions; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final URI getUrl() { - return this.url; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -198,52 +202,34 @@ public boolean equals(final Object o) { } Role other = (Role) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(serviceSid, other.serviceSid) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(type, other.type) && - Objects.equals(permissions, other.permissions) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(url, other.url) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(permissions, other.permissions) && + Objects.equals(serviceSid, other.serviceSid) && + Objects.equals(sid, other.sid) && + Objects.equals(type, other.type) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - sid, - accountSid, - serviceSid, - friendlyName, - type, - permissions, - dateCreated, - dateUpdated, - url + accountSid, + dateCreated, + dateUpdated, + friendlyName, + permissions, + serviceSid, + sid, + type, + url ); } - public enum RoleType { - CHANNEL("channel"), - DEPLOYMENT("deployment"); - - private final String value; - - private RoleType(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - @JsonCreator - public static RoleType forValue(final String value) { - return Promoter.enumFromString(value, RoleType.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/ipmessaging/v1/service/RoleCreator.java b/src/main/java/com/twilio/rest/ipmessaging/v1/service/RoleCreator.java index af8f9b1bb9..4e93ac7de5 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v1/service/RoleCreator.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v1/service/RoleCreator.java @@ -14,9 +14,12 @@ package com.twilio.rest.ipmessaging.v1.service; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; import com.twilio.converter.Promoter; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,38 +28,36 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -import java.util.List; + import java.util.List; public class RoleCreator extends Creator { - private String pathServiceSid; + private String pathserviceSid; private String friendlyName; private Role.RoleType type; private List permission; - public RoleCreator( - final String pathServiceSid, - final String friendlyName, - final Role.RoleType type, - final List permission - ) { - this.pathServiceSid = pathServiceSid; + public RoleCreator(final String pathserviceSid, final String friendlyName, final Role.RoleType type, final List permission) { + this.pathserviceSid = pathserviceSid; this.friendlyName = friendlyName; this.type = type; this.permission = permission; } + public RoleCreator setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + public RoleCreator setType(final Role.RoleType type) { this.type = type; return this; } + public RoleCreator setPermission(final List permission) { this.permission = permission; return this; @@ -68,44 +69,31 @@ public RoleCreator setPermission(final String permission) { @Override public Role create(final TwilioRestClient client) { + String path = "/v1/Services/{ServiceSid}/Roles"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = - path.replace( - "{" + "FriendlyName" + "}", - this.friendlyName.toString() - ); - path = path.replace("{" + "Type" + "}", this.type.toString()); - path = - path.replace("{" + "Permission" + "}", this.permission.toString()); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.IPMESSAGING.toString(), - path + HttpMethod.POST, + Domains.IPMESSAGING.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Role creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("Role creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -114,16 +102,22 @@ public Role create(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + if (type != null) { - request.addPostParam("Type", type.toString()); + Serializer.toString(request, "Type", type, ParameterType.URLENCODED); } + + if (permission != null) { - for (String prop : permission) { - request.addPostParam("Permission", prop); + for (String param : permission) { + Serializer.toString(request, "Permission", param, ParameterType.URLENCODED); } } + } } diff --git a/src/main/java/com/twilio/rest/ipmessaging/v1/service/RoleDeleter.java b/src/main/java/com/twilio/rest/ipmessaging/v1/service/RoleDeleter.java index 5ee169d974..3ddd232cda 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v1/service/RoleDeleter.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v1/service/RoleDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.ipmessaging.v1.service; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,47 +26,41 @@ public class RoleDeleter extends Deleter { - private String pathServiceSid; - private String pathSid; + private String pathserviceSid; + private String pathsid; - public RoleDeleter(final String pathServiceSid, final String pathSid) { - this.pathServiceSid = pathServiceSid; - this.pathSid = pathSid; + public RoleDeleter(final String pathserviceSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/v1/Services/{ServiceSid}/Roles/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.IPMESSAGING.toString(), - path + HttpMethod.DELETE, + Domains.IPMESSAGING.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Role delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("Role delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/ipmessaging/v1/service/RoleFetcher.java b/src/main/java/com/twilio/rest/ipmessaging/v1/service/RoleFetcher.java index 103629b4ca..4d1c48bd56 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v1/service/RoleFetcher.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v1/service/RoleFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.ipmessaging.v1.service; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,51 +26,44 @@ public class RoleFetcher extends Fetcher { - private String pathServiceSid; - private String pathSid; + private String pathserviceSid; + private String pathsid; - public RoleFetcher(final String pathServiceSid, final String pathSid) { - this.pathServiceSid = pathServiceSid; - this.pathSid = pathSid; + public RoleFetcher(final String pathserviceSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathsid = pathsid; } + @Override public Role fetch(final TwilioRestClient client) { + String path = "/v1/Services/{ServiceSid}/Roles/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.IPMESSAGING.toString(), - path + HttpMethod.GET, + Domains.IPMESSAGING.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Role fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Role fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Role.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/ipmessaging/v1/service/RoleReader.java b/src/main/java/com/twilio/rest/ipmessaging/v1/service/RoleReader.java index 350092ae20..ee3834617a 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v1/service/RoleReader.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v1/service/RoleReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,115 +30,88 @@ public class RoleReader extends Reader { - private String pathServiceSid; + private String pathserviceSid; private Long pageSize; - public RoleReader(final String pathServiceSid) { - this.pathServiceSid = pathServiceSid; + public RoleReader(final String pathserviceSid) { + this.pathserviceSid = pathserviceSid; } + public RoleReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/Services/{ServiceSid}/Roles"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.IPMESSAGING.toString(), - path + HttpMethod.GET, + Domains.IPMESSAGING.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Role read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Role read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "roles", - response.getContent(), - Role.class, - client.getObjectMapper() - ); + "roles", + response.getContent(), + Role.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.IPMESSAGING.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.IPMESSAGING.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/ipmessaging/v1/service/RoleUpdater.java b/src/main/java/com/twilio/rest/ipmessaging/v1/service/RoleUpdater.java index 729b610a6d..2f9d90caa2 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v1/service/RoleUpdater.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v1/service/RoleUpdater.java @@ -16,7 +16,9 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; import com.twilio.converter.Promoter; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,24 +27,21 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.util.List; public class RoleUpdater extends Updater { - - private String pathServiceSid; - private String pathSid; + private String pathserviceSid; + private String pathsid; private List permission; - public RoleUpdater( - final String pathServiceSid, - final String pathSid, - final List permission - ) { - this.pathServiceSid = pathServiceSid; - this.pathSid = pathSid; + public RoleUpdater(final String pathserviceSid, final String pathsid, final List permission) { + this.pathserviceSid = pathserviceSid; + this.pathsid = pathsid; this.permission = permission; } + public RoleUpdater setPermission(final List permission) { this.permission = permission; return this; @@ -54,39 +53,32 @@ public RoleUpdater setPermission(final String permission) { @Override public Role update(final TwilioRestClient client) { + String path = "/v1/Services/{ServiceSid}/Roles/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); - path = - path.replace("{" + "Permission" + "}", this.permission.toString()); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.IPMESSAGING.toString(), - path + HttpMethod.POST, + Domains.IPMESSAGING.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Role update failed: Unable to connect to server" - ); + throw new ApiConnectionException("Role update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -95,10 +87,13 @@ public Role update(final TwilioRestClient client) { } private void addPostParams(final Request request) { + + if (permission != null) { - for (String prop : permission) { - request.addPostParam("Permission", prop); + for (String param : permission) { + Serializer.toString(request, "Permission", param, ParameterType.URLENCODED); } } + } } diff --git a/src/main/java/com/twilio/rest/ipmessaging/v1/service/User.java b/src/main/java/com/twilio/rest/ipmessaging/v1/service/User.java index 2acabb1e47..7175f1b0dd 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v1/service/User.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v1/service/User.java @@ -18,71 +18,71 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class User extends Resource { - private static final long serialVersionUID = 136391609300437L; - public static UserCreator creator( - final String pathServiceSid, - final String identity - ) { - return new UserCreator(pathServiceSid, identity); + public static UserCreator creator(final String pathserviceSid, final String identity) { + return new UserCreator( + pathserviceSid, identity + ); } - public static UserDeleter deleter( - final String pathServiceSid, - final String pathSid - ) { - return new UserDeleter(pathServiceSid, pathSid); + + public static UserDeleter deleter(final String pathserviceSid, final String pathsid) { + return new UserDeleter( + pathserviceSid, pathsid + ); } - public static UserFetcher fetcher( - final String pathServiceSid, - final String pathSid - ) { - return new UserFetcher(pathServiceSid, pathSid); + + public static UserFetcher fetcher(final String pathserviceSid, final String pathsid) { + return new UserFetcher( + pathserviceSid, pathsid + ); } - public static UserReader reader(final String pathServiceSid) { - return new UserReader(pathServiceSid); + + public static UserReader reader(final String pathserviceSid) { + return new UserReader( + pathserviceSid + ); } - public static UserUpdater updater( - final String pathServiceSid, - final String pathSid - ) { - return new UserUpdater(pathServiceSid, pathSid); + + public static UserUpdater updater(final String pathserviceSid, final String pathsid) { + return new UserUpdater( + pathserviceSid, pathsid + ); } + /** * Converts a JSON String into a User object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return User object represented by the provided JSON */ - public static User fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static User fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, User.class); @@ -97,14 +97,11 @@ public static User fromJson( * Converts a JSON InputStream into a User object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return User object represented by the provided JSON */ - public static User fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static User fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, User.class); @@ -115,112 +112,83 @@ public static User fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String serviceSid; + @Getter private final String attributes; + @Getter + private final ZonedDateTime dateCreated; + @Getter + private final ZonedDateTime dateUpdated; + @Getter private final String friendlyName; - private final String roleSid; + @Getter private final String identity; - private final Boolean isOnline; + @Getter private final Boolean isNotifiable; - private final ZonedDateTime dateCreated; - private final ZonedDateTime dateUpdated; + @Getter + private final Boolean isOnline; + @Getter private final Integer joinedChannelsCount; + @Getter private final Map links; + @Getter + private final String roleSid; + @Getter + private final String serviceSid; + @Getter + private final String sid; + @Getter private final URI url; @JsonCreator private User( - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("service_sid") final String serviceSid, - @JsonProperty("attributes") final String attributes, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("role_sid") final String roleSid, - @JsonProperty("identity") final String identity, - @JsonProperty("is_online") final Boolean isOnline, - @JsonProperty("is_notifiable") final Boolean isNotifiable, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty( - "joined_channels_count" - ) final Integer joinedChannelsCount, - @JsonProperty("links") final Map links, - @JsonProperty("url") final URI url + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("attributes") final String attributes, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("identity") final String identity, + @JsonProperty("is_notifiable") final Boolean isNotifiable, + @JsonProperty("is_online") final Boolean isOnline, + @JsonProperty("joined_channels_count") final Integer joinedChannelsCount, + @JsonProperty("links") final Map links, + @JsonProperty("role_sid") final String roleSid, + @JsonProperty("service_sid") final String serviceSid, + @JsonProperty("sid") final String sid, + @JsonProperty("url") final URI url ) { - this.sid = sid; this.accountSid = accountSid; - this.serviceSid = serviceSid; this.attributes = attributes; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.friendlyName = friendlyName; - this.roleSid = roleSid; this.identity = identity; - this.isOnline = isOnline; this.isNotifiable = isNotifiable; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); + this.isOnline = isOnline; this.joinedChannelsCount = joinedChannelsCount; this.links = links; + this.roleSid = roleSid; + this.serviceSid = serviceSid; + this.sid = sid; this.url = url; } - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getServiceSid() { - return this.serviceSid; - } - - public final String getAttributes() { - return this.attributes; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final String getRoleSid() { - return this.roleSid; - } - - public final String getIdentity() { - return this.identity; - } - - public final Boolean getIsOnline() { - return this.isOnline; - } - - public final Boolean getIsNotifiable() { - return this.isNotifiable; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final Integer getJoinedChannelsCount() { - return this.joinedChannelsCount; - } - - public final Map getLinks() { - return this.links; - } - - public final URI getUrl() { - return this.url; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -232,42 +200,44 @@ public boolean equals(final Object o) { } User other = (User) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(serviceSid, other.serviceSid) && - Objects.equals(attributes, other.attributes) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(roleSid, other.roleSid) && - Objects.equals(identity, other.identity) && - Objects.equals(isOnline, other.isOnline) && - Objects.equals(isNotifiable, other.isNotifiable) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(joinedChannelsCount, other.joinedChannelsCount) && - Objects.equals(links, other.links) && - Objects.equals(url, other.url) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(attributes, other.attributes) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(identity, other.identity) && + Objects.equals(isNotifiable, other.isNotifiable) && + Objects.equals(isOnline, other.isOnline) && + Objects.equals(joinedChannelsCount, other.joinedChannelsCount) && + Objects.equals(links, other.links) && + Objects.equals(roleSid, other.roleSid) && + Objects.equals(serviceSid, other.serviceSid) && + Objects.equals(sid, other.sid) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - sid, - accountSid, - serviceSid, - attributes, - friendlyName, - roleSid, - identity, - isOnline, - isNotifiable, - dateCreated, - dateUpdated, - joinedChannelsCount, - links, - url + accountSid, + attributes, + dateCreated, + dateUpdated, + friendlyName, + identity, + isNotifiable, + isOnline, + joinedChannelsCount, + links, + roleSid, + serviceSid, + sid, + url ); } + + } + diff --git a/src/main/java/com/twilio/rest/ipmessaging/v1/service/UserCreator.java b/src/main/java/com/twilio/rest/ipmessaging/v1/service/UserCreator.java index b0361ee59c..c9a532788d 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v1/service/UserCreator.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v1/service/UserCreator.java @@ -14,8 +14,11 @@ package com.twilio.rest.ipmessaging.v1.service; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,70 +30,69 @@ public class UserCreator extends Creator { - private String pathServiceSid; + private String pathserviceSid; private String identity; private String roleSid; private String attributes; private String friendlyName; - public UserCreator(final String pathServiceSid, final String identity) { - this.pathServiceSid = pathServiceSid; + public UserCreator(final String pathserviceSid, final String identity) { + this.pathserviceSid = pathserviceSid; this.identity = identity; } + public UserCreator setIdentity(final String identity) { this.identity = identity; return this; } + public UserCreator setRoleSid(final String roleSid) { this.roleSid = roleSid; return this; } + public UserCreator setAttributes(final String attributes) { this.attributes = attributes; return this; } + public UserCreator setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + @Override public User create(final TwilioRestClient client) { + String path = "/v1/Services/{ServiceSid}/Users"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = path.replace("{" + "Identity" + "}", this.identity.toString()); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.IPMESSAGING.toString(), - path + HttpMethod.POST, + Domains.IPMESSAGING.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "User creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("User creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -99,17 +101,26 @@ public User create(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (identity != null) { - request.addPostParam("Identity", identity); + Serializer.toString(request, "Identity", identity, ParameterType.URLENCODED); } + + if (roleSid != null) { - request.addPostParam("RoleSid", roleSid); + Serializer.toString(request, "RoleSid", roleSid, ParameterType.URLENCODED); } + + if (attributes != null) { - request.addPostParam("Attributes", attributes); + Serializer.toString(request, "Attributes", attributes, ParameterType.URLENCODED); } + + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/ipmessaging/v1/service/UserDeleter.java b/src/main/java/com/twilio/rest/ipmessaging/v1/service/UserDeleter.java index cb95e09193..995e03fb00 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v1/service/UserDeleter.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v1/service/UserDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.ipmessaging.v1.service; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,47 +26,41 @@ public class UserDeleter extends Deleter { - private String pathServiceSid; - private String pathSid; + private String pathserviceSid; + private String pathsid; - public UserDeleter(final String pathServiceSid, final String pathSid) { - this.pathServiceSid = pathServiceSid; - this.pathSid = pathSid; + public UserDeleter(final String pathserviceSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/v1/Services/{ServiceSid}/Users/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.IPMESSAGING.toString(), - path + HttpMethod.DELETE, + Domains.IPMESSAGING.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "User delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("User delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/ipmessaging/v1/service/UserFetcher.java b/src/main/java/com/twilio/rest/ipmessaging/v1/service/UserFetcher.java index ba488649f4..31e4ef7c1e 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v1/service/UserFetcher.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v1/service/UserFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.ipmessaging.v1.service; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,51 +26,44 @@ public class UserFetcher extends Fetcher { - private String pathServiceSid; - private String pathSid; + private String pathserviceSid; + private String pathsid; - public UserFetcher(final String pathServiceSid, final String pathSid) { - this.pathServiceSid = pathServiceSid; - this.pathSid = pathSid; + public UserFetcher(final String pathserviceSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathsid = pathsid; } + @Override public User fetch(final TwilioRestClient client) { + String path = "/v1/Services/{ServiceSid}/Users/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.IPMESSAGING.toString(), - path + HttpMethod.GET, + Domains.IPMESSAGING.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "User fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("User fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return User.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/ipmessaging/v1/service/UserReader.java b/src/main/java/com/twilio/rest/ipmessaging/v1/service/UserReader.java index 6ff3715c04..c219878d97 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v1/service/UserReader.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v1/service/UserReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,115 +30,88 @@ public class UserReader extends Reader { - private String pathServiceSid; + private String pathserviceSid; private Long pageSize; - public UserReader(final String pathServiceSid) { - this.pathServiceSid = pathServiceSid; + public UserReader(final String pathserviceSid) { + this.pathserviceSid = pathserviceSid; } + public UserReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/Services/{ServiceSid}/Users"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.IPMESSAGING.toString(), - path + HttpMethod.GET, + Domains.IPMESSAGING.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "User read failed: Unable to connect to server" - ); + throw new ApiConnectionException("User read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "users", - response.getContent(), - User.class, - client.getObjectMapper() - ); + "users", + response.getContent(), + User.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.IPMESSAGING.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.IPMESSAGING.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/ipmessaging/v1/service/UserUpdater.java b/src/main/java/com/twilio/rest/ipmessaging/v1/service/UserUpdater.java index 747ccdf4b0..4ce8389364 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v1/service/UserUpdater.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v1/service/UserUpdater.java @@ -16,6 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -26,66 +28,64 @@ import com.twilio.rest.Domains; public class UserUpdater extends Updater { - - private String pathServiceSid; - private String pathSid; + private String pathserviceSid; + private String pathsid; private String roleSid; private String attributes; private String friendlyName; - public UserUpdater(final String pathServiceSid, final String pathSid) { - this.pathServiceSid = pathServiceSid; - this.pathSid = pathSid; + public UserUpdater(final String pathserviceSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathsid = pathsid; } + public UserUpdater setRoleSid(final String roleSid) { this.roleSid = roleSid; return this; } + public UserUpdater setAttributes(final String attributes) { this.attributes = attributes; return this; } + public UserUpdater setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + @Override public User update(final TwilioRestClient client) { + String path = "/v1/Services/{ServiceSid}/Users/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.IPMESSAGING.toString(), - path + HttpMethod.POST, + Domains.IPMESSAGING.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "User update failed: Unable to connect to server" - ); + throw new ApiConnectionException("User update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -94,14 +94,21 @@ public User update(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (roleSid != null) { - request.addPostParam("RoleSid", roleSid); + Serializer.toString(request, "RoleSid", roleSid, ParameterType.URLENCODED); } + + if (attributes != null) { - request.addPostParam("Attributes", attributes); + Serializer.toString(request, "Attributes", attributes, ParameterType.URLENCODED); } + + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/ipmessaging/v1/service/channel/Invite.java b/src/main/java/com/twilio/rest/ipmessaging/v1/service/channel/Invite.java index 17d716e8e1..2a424c1807 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v1/service/channel/Invite.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v1/service/channel/Invite.java @@ -18,68 +18,63 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Invite extends Resource { - private static final long serialVersionUID = 148273166902210L; - public static InviteCreator creator( - final String pathServiceSid, - final String pathChannelSid, - final String identity - ) { - return new InviteCreator(pathServiceSid, pathChannelSid, identity); + public static InviteCreator creator(final String pathserviceSid, final String pathchannelSid, final String identity) { + return new InviteCreator( + pathserviceSid, pathchannelSid, identity + ); } - public static InviteDeleter deleter( - final String pathServiceSid, - final String pathChannelSid, - final String pathSid - ) { - return new InviteDeleter(pathServiceSid, pathChannelSid, pathSid); + + public static InviteDeleter deleter(final String pathserviceSid, final String pathchannelSid, final String pathsid) { + return new InviteDeleter( + pathserviceSid, pathchannelSid, pathsid + ); } - public static InviteFetcher fetcher( - final String pathServiceSid, - final String pathChannelSid, - final String pathSid - ) { - return new InviteFetcher(pathServiceSid, pathChannelSid, pathSid); + + public static InviteFetcher fetcher(final String pathserviceSid, final String pathchannelSid, final String pathsid) { + return new InviteFetcher( + pathserviceSid, pathchannelSid, pathsid + ); } - public static InviteReader reader( - final String pathServiceSid, - final String pathChannelSid - ) { - return new InviteReader(pathServiceSid, pathChannelSid); + + public static InviteReader reader(final String pathserviceSid, final String pathchannelSid) { + return new InviteReader( + pathserviceSid, pathchannelSid + ); } + /** * Converts a JSON String into a Invite object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Invite object represented by the provided JSON */ - public static Invite fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Invite fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Invite.class); @@ -94,14 +89,11 @@ public static Invite fromJson( * Converts a JSON InputStream into a Invite object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Invite object represented by the provided JSON */ - public static Invite fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Invite fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Invite.class); @@ -112,82 +104,67 @@ public static Invite fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; + @Getter private final String channelSid; - private final String serviceSid; - private final String identity; + @Getter + private final String createdBy; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; + @Getter + private final String identity; + @Getter private final String roleSid; - private final String createdBy; + @Getter + private final String serviceSid; + @Getter + private final String sid; + @Getter private final URI url; @JsonCreator private Invite( - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("channel_sid") final String channelSid, - @JsonProperty("service_sid") final String serviceSid, - @JsonProperty("identity") final String identity, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("role_sid") final String roleSid, - @JsonProperty("created_by") final String createdBy, - @JsonProperty("url") final URI url + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("channel_sid") final String channelSid, + @JsonProperty("created_by") final String createdBy, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("identity") final String identity, + @JsonProperty("role_sid") final String roleSid, + @JsonProperty("service_sid") final String serviceSid, + @JsonProperty("sid") final String sid, + @JsonProperty("url") final URI url ) { - this.sid = sid; this.accountSid = accountSid; this.channelSid = channelSid; - this.serviceSid = serviceSid; + this.createdBy = createdBy; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.identity = identity; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); this.roleSid = roleSid; - this.createdBy = createdBy; + this.serviceSid = serviceSid; + this.sid = sid; this.url = url; } - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getChannelSid() { - return this.channelSid; - } - - public final String getServiceSid() { - return this.serviceSid; - } - - public final String getIdentity() { - return this.identity; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final String getRoleSid() { - return this.roleSid; - } - - public final String getCreatedBy() { - return this.createdBy; - } - - public final URI getUrl() { - return this.url; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -199,34 +176,36 @@ public boolean equals(final Object o) { } Invite other = (Invite) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(channelSid, other.channelSid) && - Objects.equals(serviceSid, other.serviceSid) && - Objects.equals(identity, other.identity) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(roleSid, other.roleSid) && - Objects.equals(createdBy, other.createdBy) && - Objects.equals(url, other.url) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(channelSid, other.channelSid) && + Objects.equals(createdBy, other.createdBy) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(identity, other.identity) && + Objects.equals(roleSid, other.roleSid) && + Objects.equals(serviceSid, other.serviceSid) && + Objects.equals(sid, other.sid) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - sid, - accountSid, - channelSid, - serviceSid, - identity, - dateCreated, - dateUpdated, - roleSid, - createdBy, - url + accountSid, + channelSid, + createdBy, + dateCreated, + dateUpdated, + identity, + roleSid, + serviceSid, + sid, + url ); } + + } + diff --git a/src/main/java/com/twilio/rest/ipmessaging/v1/service/channel/InviteCreator.java b/src/main/java/com/twilio/rest/ipmessaging/v1/service/channel/InviteCreator.java index 0f4f90433b..bdf30694af 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v1/service/channel/InviteCreator.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v1/service/channel/InviteCreator.java @@ -14,8 +14,11 @@ package com.twilio.rest.ipmessaging.v1.service.channel; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,69 +30,58 @@ public class InviteCreator extends Creator { - private String pathServiceSid; - private String pathChannelSid; + private String pathserviceSid; + private String pathchannelSid; private String identity; private String roleSid; - public InviteCreator( - final String pathServiceSid, - final String pathChannelSid, - final String identity - ) { - this.pathServiceSid = pathServiceSid; - this.pathChannelSid = pathChannelSid; + public InviteCreator(final String pathserviceSid, final String pathchannelSid, final String identity) { + this.pathserviceSid = pathserviceSid; + this.pathchannelSid = pathchannelSid; this.identity = identity; } + public InviteCreator setIdentity(final String identity) { this.identity = identity; return this; } + public InviteCreator setRoleSid(final String roleSid) { this.roleSid = roleSid; return this; } + @Override public Invite create(final TwilioRestClient client) { + String path = "/v1/Services/{ServiceSid}/Channels/{ChannelSid}/Invites"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = - path.replace( - "{" + "ChannelSid" + "}", - this.pathChannelSid.toString() - ); - path = path.replace("{" + "Identity" + "}", this.identity.toString()); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "ChannelSid" + "}", this.pathchannelSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.IPMESSAGING.toString(), - path + HttpMethod.POST, + Domains.IPMESSAGING.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Invite creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("Invite creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -98,11 +90,16 @@ public Invite create(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (identity != null) { - request.addPostParam("Identity", identity); + Serializer.toString(request, "Identity", identity, ParameterType.URLENCODED); } + + if (roleSid != null) { - request.addPostParam("RoleSid", roleSid); + Serializer.toString(request, "RoleSid", roleSid, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/ipmessaging/v1/service/channel/InviteDeleter.java b/src/main/java/com/twilio/rest/ipmessaging/v1/service/channel/InviteDeleter.java index aa748728a1..037449375a 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v1/service/channel/InviteDeleter.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v1/service/channel/InviteDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.ipmessaging.v1.service.channel; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,59 +26,44 @@ public class InviteDeleter extends Deleter { - private String pathServiceSid; - private String pathChannelSid; - private String pathSid; + private String pathserviceSid; + private String pathchannelSid; + private String pathsid; - public InviteDeleter( - final String pathServiceSid, - final String pathChannelSid, - final String pathSid - ) { - this.pathServiceSid = pathServiceSid; - this.pathChannelSid = pathChannelSid; - this.pathSid = pathSid; + public InviteDeleter(final String pathserviceSid, final String pathchannelSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathchannelSid = pathchannelSid; + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { - String path = - "/v1/Services/{ServiceSid}/Channels/{ChannelSid}/Invites/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = - path.replace( - "{" + "ChannelSid" + "}", - this.pathChannelSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/v1/Services/{ServiceSid}/Channels/{ChannelSid}/Invites/{Sid}"; + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "ChannelSid" + "}", this.pathchannelSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.IPMESSAGING.toString(), - path + HttpMethod.DELETE, + Domains.IPMESSAGING.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Invite delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("Invite delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/ipmessaging/v1/service/channel/InviteFetcher.java b/src/main/java/com/twilio/rest/ipmessaging/v1/service/channel/InviteFetcher.java index 8f618d92aa..6d27a533e5 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v1/service/channel/InviteFetcher.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v1/service/channel/InviteFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.ipmessaging.v1.service.channel; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,63 +26,47 @@ public class InviteFetcher extends Fetcher { - private String pathServiceSid; - private String pathChannelSid; - private String pathSid; + private String pathserviceSid; + private String pathchannelSid; + private String pathsid; - public InviteFetcher( - final String pathServiceSid, - final String pathChannelSid, - final String pathSid - ) { - this.pathServiceSid = pathServiceSid; - this.pathChannelSid = pathChannelSid; - this.pathSid = pathSid; + public InviteFetcher(final String pathserviceSid, final String pathchannelSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathchannelSid = pathchannelSid; + this.pathsid = pathsid; } + @Override public Invite fetch(final TwilioRestClient client) { - String path = - "/v1/Services/{ServiceSid}/Channels/{ChannelSid}/Invites/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = - path.replace( - "{" + "ChannelSid" + "}", - this.pathChannelSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/v1/Services/{ServiceSid}/Channels/{ChannelSid}/Invites/{Sid}"; + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "ChannelSid" + "}", this.pathchannelSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.IPMESSAGING.toString(), - path + HttpMethod.GET, + Domains.IPMESSAGING.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Invite fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Invite fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Invite.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/ipmessaging/v1/service/channel/InviteReader.java b/src/main/java/com/twilio/rest/ipmessaging/v1/service/channel/InviteReader.java index 40a8b3b5e5..0e6a90f99c 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v1/service/channel/InviteReader.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v1/service/channel/InviteReader.java @@ -17,8 +17,9 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; import com.twilio.converter.Promoter; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,23 +28,22 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.util.List; public class InviteReader extends Reader { - private String pathServiceSid; - private String pathChannelSid; + private String pathserviceSid; + private String pathchannelSid; private List identity; private Long pageSize; - public InviteReader( - final String pathServiceSid, - final String pathChannelSid - ) { - this.pathServiceSid = pathServiceSid; - this.pathChannelSid = pathChannelSid; + public InviteReader(final String pathserviceSid, final String pathchannelSid) { + this.pathserviceSid = pathserviceSid; + this.pathchannelSid = pathchannelSid; } + public InviteReader setIdentity(final List identity) { this.identity = identity; return this; @@ -58,113 +58,83 @@ public InviteReader setPageSize(final Long pageSize) { return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/Services/{ServiceSid}/Channels/{ChannelSid}/Invites"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = - path.replace( - "{" + "ChannelSid" + "}", - this.pathChannelSid.toString() - ); + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "ChannelSid" + "}", this.pathchannelSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.IPMESSAGING.toString(), - path + HttpMethod.GET, + Domains.IPMESSAGING.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Invite read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Invite read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "invites", - response.getContent(), - Invite.class, - client.getObjectMapper() - ); + "invites", + response.getContent(), + Invite.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.IPMESSAGING.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.IPMESSAGING.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (identity != null) { - for (String prop : identity) { - request.addQueryParam("Identity", prop); + for (String param : identity) { + Serializer.toString(request, "Identity", param, ParameterType.QUERY); } } + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/ipmessaging/v1/service/channel/Member.java b/src/main/java/com/twilio/rest/ipmessaging/v1/service/channel/Member.java index e9cc609d97..06ab6703ee 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v1/service/channel/Member.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v1/service/channel/Member.java @@ -18,76 +18,70 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Member extends Resource { - private static final long serialVersionUID = 102757132179124L; - public static MemberCreator creator( - final String pathServiceSid, - final String pathChannelSid, - final String identity - ) { - return new MemberCreator(pathServiceSid, pathChannelSid, identity); + public static MemberCreator creator(final String pathserviceSid, final String pathchannelSid, final String identity) { + return new MemberCreator( + pathserviceSid, pathchannelSid, identity + ); } - public static MemberDeleter deleter( - final String pathServiceSid, - final String pathChannelSid, - final String pathSid - ) { - return new MemberDeleter(pathServiceSid, pathChannelSid, pathSid); + + public static MemberDeleter deleter(final String pathserviceSid, final String pathchannelSid, final String pathsid) { + return new MemberDeleter( + pathserviceSid, pathchannelSid, pathsid + ); } - public static MemberFetcher fetcher( - final String pathServiceSid, - final String pathChannelSid, - final String pathSid - ) { - return new MemberFetcher(pathServiceSid, pathChannelSid, pathSid); + + public static MemberFetcher fetcher(final String pathserviceSid, final String pathchannelSid, final String pathsid) { + return new MemberFetcher( + pathserviceSid, pathchannelSid, pathsid + ); } - public static MemberReader reader( - final String pathServiceSid, - final String pathChannelSid - ) { - return new MemberReader(pathServiceSid, pathChannelSid); + + public static MemberReader reader(final String pathserviceSid, final String pathchannelSid) { + return new MemberReader( + pathserviceSid, pathchannelSid + ); } - public static MemberUpdater updater( - final String pathServiceSid, - final String pathChannelSid, - final String pathSid - ) { - return new MemberUpdater(pathServiceSid, pathChannelSid, pathSid); + + public static MemberUpdater updater(final String pathserviceSid, final String pathchannelSid, final String pathsid) { + return new MemberUpdater( + pathserviceSid, pathchannelSid, pathsid + ); } + /** * Converts a JSON String into a Member object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Member object represented by the provided JSON */ - public static Member fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Member fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Member.class); @@ -102,14 +96,11 @@ public static Member fromJson( * Converts a JSON InputStream into a Member object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Member object represented by the provided JSON */ - public static Member fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Member fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Member.class); @@ -120,94 +111,72 @@ public static Member fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; + @Getter private final String channelSid; - private final String serviceSid; - private final String identity; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; - private final String roleSid; + @Getter + private final String identity; + @Getter private final Integer lastConsumedMessageIndex; + @Getter private final ZonedDateTime lastConsumptionTimestamp; + @Getter + private final String roleSid; + @Getter + private final String serviceSid; + @Getter + private final String sid; + @Getter private final URI url; @JsonCreator private Member( - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("channel_sid") final String channelSid, - @JsonProperty("service_sid") final String serviceSid, - @JsonProperty("identity") final String identity, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("role_sid") final String roleSid, - @JsonProperty( - "last_consumed_message_index" - ) final Integer lastConsumedMessageIndex, - @JsonProperty( - "last_consumption_timestamp" - ) final String lastConsumptionTimestamp, - @JsonProperty("url") final URI url + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("channel_sid") final String channelSid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("identity") final String identity, + @JsonProperty("last_consumed_message_index") final Integer lastConsumedMessageIndex, + @JsonProperty("last_consumption_timestamp") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime lastConsumptionTimestamp, + @JsonProperty("role_sid") final String roleSid, + @JsonProperty("service_sid") final String serviceSid, + @JsonProperty("sid") final String sid, + @JsonProperty("url") final URI url ) { - this.sid = sid; this.accountSid = accountSid; this.channelSid = channelSid; - this.serviceSid = serviceSid; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.identity = identity; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); - this.roleSid = roleSid; this.lastConsumedMessageIndex = lastConsumedMessageIndex; - this.lastConsumptionTimestamp = - DateConverter.iso8601DateTimeFromString(lastConsumptionTimestamp); + this.lastConsumptionTimestamp = lastConsumptionTimestamp; + this.roleSid = roleSid; + this.serviceSid = serviceSid; + this.sid = sid; this.url = url; } - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getChannelSid() { - return this.channelSid; - } - - public final String getServiceSid() { - return this.serviceSid; - } - - public final String getIdentity() { - return this.identity; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final String getRoleSid() { - return this.roleSid; - } - - public final Integer getLastConsumedMessageIndex() { - return this.lastConsumedMessageIndex; - } - - public final ZonedDateTime getLastConsumptionTimestamp() { - return this.lastConsumptionTimestamp; - } - - public final URI getUrl() { - return this.url; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -219,42 +188,38 @@ public boolean equals(final Object o) { } Member other = (Member) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(channelSid, other.channelSid) && - Objects.equals(serviceSid, other.serviceSid) && - Objects.equals(identity, other.identity) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(roleSid, other.roleSid) && - Objects.equals( - lastConsumedMessageIndex, - other.lastConsumedMessageIndex - ) && - Objects.equals( - lastConsumptionTimestamp, - other.lastConsumptionTimestamp - ) && - Objects.equals(url, other.url) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(channelSid, other.channelSid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(identity, other.identity) && + Objects.equals(lastConsumedMessageIndex, other.lastConsumedMessageIndex) && + Objects.equals(lastConsumptionTimestamp, other.lastConsumptionTimestamp) && + Objects.equals(roleSid, other.roleSid) && + Objects.equals(serviceSid, other.serviceSid) && + Objects.equals(sid, other.sid) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - sid, - accountSid, - channelSid, - serviceSid, - identity, - dateCreated, - dateUpdated, - roleSid, - lastConsumedMessageIndex, - lastConsumptionTimestamp, - url + accountSid, + channelSid, + dateCreated, + dateUpdated, + identity, + lastConsumedMessageIndex, + lastConsumptionTimestamp, + roleSid, + serviceSid, + sid, + url ); } + + } + diff --git a/src/main/java/com/twilio/rest/ipmessaging/v1/service/channel/MemberCreator.java b/src/main/java/com/twilio/rest/ipmessaging/v1/service/channel/MemberCreator.java index e5e8be3eea..b9d3c5240a 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v1/service/channel/MemberCreator.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v1/service/channel/MemberCreator.java @@ -14,8 +14,11 @@ package com.twilio.rest.ipmessaging.v1.service.channel; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,69 +30,58 @@ public class MemberCreator extends Creator { - private String pathServiceSid; - private String pathChannelSid; + private String pathserviceSid; + private String pathchannelSid; private String identity; private String roleSid; - public MemberCreator( - final String pathServiceSid, - final String pathChannelSid, - final String identity - ) { - this.pathServiceSid = pathServiceSid; - this.pathChannelSid = pathChannelSid; + public MemberCreator(final String pathserviceSid, final String pathchannelSid, final String identity) { + this.pathserviceSid = pathserviceSid; + this.pathchannelSid = pathchannelSid; this.identity = identity; } + public MemberCreator setIdentity(final String identity) { this.identity = identity; return this; } + public MemberCreator setRoleSid(final String roleSid) { this.roleSid = roleSid; return this; } + @Override public Member create(final TwilioRestClient client) { + String path = "/v1/Services/{ServiceSid}/Channels/{ChannelSid}/Members"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = - path.replace( - "{" + "ChannelSid" + "}", - this.pathChannelSid.toString() - ); - path = path.replace("{" + "Identity" + "}", this.identity.toString()); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "ChannelSid" + "}", this.pathchannelSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.IPMESSAGING.toString(), - path + HttpMethod.POST, + Domains.IPMESSAGING.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Member creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("Member creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -98,11 +90,16 @@ public Member create(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (identity != null) { - request.addPostParam("Identity", identity); + Serializer.toString(request, "Identity", identity, ParameterType.URLENCODED); } + + if (roleSid != null) { - request.addPostParam("RoleSid", roleSid); + Serializer.toString(request, "RoleSid", roleSid, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/ipmessaging/v1/service/channel/MemberDeleter.java b/src/main/java/com/twilio/rest/ipmessaging/v1/service/channel/MemberDeleter.java index 672df0b7a5..e290b1fdab 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v1/service/channel/MemberDeleter.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v1/service/channel/MemberDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.ipmessaging.v1.service.channel; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,59 +26,44 @@ public class MemberDeleter extends Deleter { - private String pathServiceSid; - private String pathChannelSid; - private String pathSid; + private String pathserviceSid; + private String pathchannelSid; + private String pathsid; - public MemberDeleter( - final String pathServiceSid, - final String pathChannelSid, - final String pathSid - ) { - this.pathServiceSid = pathServiceSid; - this.pathChannelSid = pathChannelSid; - this.pathSid = pathSid; + public MemberDeleter(final String pathserviceSid, final String pathchannelSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathchannelSid = pathchannelSid; + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { - String path = - "/v1/Services/{ServiceSid}/Channels/{ChannelSid}/Members/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = - path.replace( - "{" + "ChannelSid" + "}", - this.pathChannelSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/v1/Services/{ServiceSid}/Channels/{ChannelSid}/Members/{Sid}"; + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "ChannelSid" + "}", this.pathchannelSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.IPMESSAGING.toString(), - path + HttpMethod.DELETE, + Domains.IPMESSAGING.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Member delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("Member delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/ipmessaging/v1/service/channel/MemberFetcher.java b/src/main/java/com/twilio/rest/ipmessaging/v1/service/channel/MemberFetcher.java index c7f7c1ddda..d7c8cf748e 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v1/service/channel/MemberFetcher.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v1/service/channel/MemberFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.ipmessaging.v1.service.channel; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,63 +26,47 @@ public class MemberFetcher extends Fetcher { - private String pathServiceSid; - private String pathChannelSid; - private String pathSid; + private String pathserviceSid; + private String pathchannelSid; + private String pathsid; - public MemberFetcher( - final String pathServiceSid, - final String pathChannelSid, - final String pathSid - ) { - this.pathServiceSid = pathServiceSid; - this.pathChannelSid = pathChannelSid; - this.pathSid = pathSid; + public MemberFetcher(final String pathserviceSid, final String pathchannelSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathchannelSid = pathchannelSid; + this.pathsid = pathsid; } + @Override public Member fetch(final TwilioRestClient client) { - String path = - "/v1/Services/{ServiceSid}/Channels/{ChannelSid}/Members/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = - path.replace( - "{" + "ChannelSid" + "}", - this.pathChannelSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/v1/Services/{ServiceSid}/Channels/{ChannelSid}/Members/{Sid}"; + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "ChannelSid" + "}", this.pathchannelSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.IPMESSAGING.toString(), - path + HttpMethod.GET, + Domains.IPMESSAGING.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Member fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Member fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Member.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/ipmessaging/v1/service/channel/MemberReader.java b/src/main/java/com/twilio/rest/ipmessaging/v1/service/channel/MemberReader.java index e7b1b96b8c..da2e3df074 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v1/service/channel/MemberReader.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v1/service/channel/MemberReader.java @@ -17,8 +17,9 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; import com.twilio.converter.Promoter; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,23 +28,22 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.util.List; public class MemberReader extends Reader { - private String pathServiceSid; - private String pathChannelSid; + private String pathserviceSid; + private String pathchannelSid; private List identity; private Long pageSize; - public MemberReader( - final String pathServiceSid, - final String pathChannelSid - ) { - this.pathServiceSid = pathServiceSid; - this.pathChannelSid = pathChannelSid; + public MemberReader(final String pathserviceSid, final String pathchannelSid) { + this.pathserviceSid = pathserviceSid; + this.pathchannelSid = pathchannelSid; } + public MemberReader setIdentity(final List identity) { this.identity = identity; return this; @@ -58,113 +58,83 @@ public MemberReader setPageSize(final Long pageSize) { return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/Services/{ServiceSid}/Channels/{ChannelSid}/Members"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = - path.replace( - "{" + "ChannelSid" + "}", - this.pathChannelSid.toString() - ); + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "ChannelSid" + "}", this.pathchannelSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.IPMESSAGING.toString(), - path + HttpMethod.GET, + Domains.IPMESSAGING.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Member read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Member read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "members", - response.getContent(), - Member.class, - client.getObjectMapper() - ); + "members", + response.getContent(), + Member.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.IPMESSAGING.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.IPMESSAGING.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (identity != null) { - for (String prop : identity) { - request.addQueryParam("Identity", prop); + for (String param : identity) { + Serializer.toString(request, "Identity", param, ParameterType.QUERY); } } + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/ipmessaging/v1/service/channel/MemberUpdater.java b/src/main/java/com/twilio/rest/ipmessaging/v1/service/channel/MemberUpdater.java index 6b4d02d642..aba64d58b3 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v1/service/channel/MemberUpdater.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v1/service/channel/MemberUpdater.java @@ -16,6 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -26,74 +28,60 @@ import com.twilio.rest.Domains; public class MemberUpdater extends Updater { - - private String pathServiceSid; - private String pathChannelSid; - private String pathSid; + private String pathserviceSid; + private String pathchannelSid; + private String pathsid; private String roleSid; private Integer lastConsumedMessageIndex; - public MemberUpdater( - final String pathServiceSid, - final String pathChannelSid, - final String pathSid - ) { - this.pathServiceSid = pathServiceSid; - this.pathChannelSid = pathChannelSid; - this.pathSid = pathSid; + public MemberUpdater(final String pathserviceSid, final String pathchannelSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathchannelSid = pathchannelSid; + this.pathsid = pathsid; } + public MemberUpdater setRoleSid(final String roleSid) { this.roleSid = roleSid; return this; } - public MemberUpdater setLastConsumedMessageIndex( - final Integer lastConsumedMessageIndex - ) { + + public MemberUpdater setLastConsumedMessageIndex(final Integer lastConsumedMessageIndex) { this.lastConsumedMessageIndex = lastConsumedMessageIndex; return this; } + @Override public Member update(final TwilioRestClient client) { - String path = - "/v1/Services/{ServiceSid}/Channels/{ChannelSid}/Members/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = - path.replace( - "{" + "ChannelSid" + "}", - this.pathChannelSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/v1/Services/{ServiceSid}/Channels/{ChannelSid}/Members/{Sid}"; + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "ChannelSid" + "}", this.pathchannelSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.IPMESSAGING.toString(), - path + HttpMethod.POST, + Domains.IPMESSAGING.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Member update failed: Unable to connect to server" - ); + throw new ApiConnectionException("Member update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -102,14 +90,16 @@ public Member update(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (roleSid != null) { - request.addPostParam("RoleSid", roleSid); + Serializer.toString(request, "RoleSid", roleSid, ParameterType.URLENCODED); } + + if (lastConsumedMessageIndex != null) { - request.addPostParam( - "LastConsumedMessageIndex", - lastConsumedMessageIndex.toString() - ); + Serializer.toString(request, "LastConsumedMessageIndex", lastConsumedMessageIndex, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/ipmessaging/v1/service/channel/Message.java b/src/main/java/com/twilio/rest/ipmessaging/v1/service/channel/Message.java index 727c2537f1..e216d92228 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v1/service/channel/Message.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v1/service/channel/Message.java @@ -18,77 +18,92 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Message extends Resource { - private static final long serialVersionUID = 148235601690422L; - public static MessageCreator creator( - final String pathServiceSid, - final String pathChannelSid, - final String body - ) { - return new MessageCreator(pathServiceSid, pathChannelSid, body); + public static MessageCreator creator(final String pathserviceSid, final String pathchannelSid, final String body) { + return new MessageCreator( + pathserviceSid, pathchannelSid, body + ); } - public static MessageDeleter deleter( - final String pathServiceSid, - final String pathChannelSid, - final String pathSid - ) { - return new MessageDeleter(pathServiceSid, pathChannelSid, pathSid); + + public static MessageDeleter deleter(final String pathserviceSid, final String pathchannelSid, final String pathsid) { + return new MessageDeleter( + pathserviceSid, pathchannelSid, pathsid + ); } - public static MessageFetcher fetcher( - final String pathServiceSid, - final String pathChannelSid, - final String pathSid - ) { - return new MessageFetcher(pathServiceSid, pathChannelSid, pathSid); + + public static MessageFetcher fetcher(final String pathserviceSid, final String pathchannelSid, final String pathsid) { + return new MessageFetcher( + pathserviceSid, pathchannelSid, pathsid + ); } - public static MessageReader reader( - final String pathServiceSid, - final String pathChannelSid - ) { - return new MessageReader(pathServiceSid, pathChannelSid); + + public static MessageReader reader(final String pathserviceSid, final String pathchannelSid) { + return new MessageReader( + pathserviceSid, pathchannelSid + ); } - public static MessageUpdater updater( - final String pathServiceSid, - final String pathChannelSid, - final String pathSid - ) { - return new MessageUpdater(pathServiceSid, pathChannelSid, pathSid); + + public static MessageUpdater updater(final String pathserviceSid, final String pathchannelSid, final String pathsid) { + return new MessageUpdater( + pathserviceSid, pathchannelSid, pathsid + ); } + + public enum OrderType { + ASC("asc"), + DESC("desc"); + + private final String value; + + private OrderType(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static OrderType forValue(final String value) { + return Promoter.enumFromString(value, OrderType.values()); + } + } + + /** * Converts a JSON String into a Message object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Message object represented by the provided JSON */ - public static Message fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Message fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Message.class); @@ -103,14 +118,11 @@ public static Message fromJson( * Converts a JSON InputStream into a Message object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Message object represented by the provided JSON */ - public static Message fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Message fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Message.class); @@ -121,101 +133,77 @@ public static Message fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; + @Getter private final String attributes; - private final String serviceSid; - private final String to; + @Getter + private final String body; + @Getter private final String channelSid; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; - private final Boolean wasEdited; + @Getter private final String from; - private final String body; + @Getter private final Integer index; + @Getter + private final String serviceSid; + @Getter + private final String sid; + @Getter + private final String to; + @Getter private final URI url; + @Getter + private final Boolean wasEdited; @JsonCreator private Message( - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("attributes") final String attributes, - @JsonProperty("service_sid") final String serviceSid, - @JsonProperty("to") final String to, - @JsonProperty("channel_sid") final String channelSid, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("was_edited") final Boolean wasEdited, - @JsonProperty("from") final String from, - @JsonProperty("body") final String body, - @JsonProperty("index") final Integer index, - @JsonProperty("url") final URI url + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("attributes") final String attributes, + @JsonProperty("body") final String body, + @JsonProperty("channel_sid") final String channelSid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("from") final String from, + @JsonProperty("index") final Integer index, + @JsonProperty("service_sid") final String serviceSid, + @JsonProperty("sid") final String sid, + @JsonProperty("to") final String to, + @JsonProperty("url") final URI url, + @JsonProperty("was_edited") final Boolean wasEdited ) { - this.sid = sid; this.accountSid = accountSid; this.attributes = attributes; - this.serviceSid = serviceSid; - this.to = to; + this.body = body; this.channelSid = channelSid; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); - this.wasEdited = wasEdited; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.from = from; - this.body = body; this.index = index; + this.serviceSid = serviceSid; + this.sid = sid; + this.to = to; this.url = url; - } - - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getAttributes() { - return this.attributes; - } - - public final String getServiceSid() { - return this.serviceSid; - } - - public final String getTo() { - return this.to; - } - - public final String getChannelSid() { - return this.channelSid; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final Boolean getWasEdited() { - return this.wasEdited; - } - - public final String getFrom() { - return this.from; - } - - public final String getBody() { - return this.body; - } - - public final Integer getIndex() { - return this.index; - } - - public final URI getUrl() { - return this.url; + this.wasEdited = wasEdited; } @Override @@ -229,60 +217,42 @@ public boolean equals(final Object o) { } Message other = (Message) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(attributes, other.attributes) && - Objects.equals(serviceSid, other.serviceSid) && - Objects.equals(to, other.to) && - Objects.equals(channelSid, other.channelSid) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(wasEdited, other.wasEdited) && - Objects.equals(from, other.from) && - Objects.equals(body, other.body) && - Objects.equals(index, other.index) && - Objects.equals(url, other.url) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(attributes, other.attributes) && + Objects.equals(body, other.body) && + Objects.equals(channelSid, other.channelSid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(from, other.from) && + Objects.equals(index, other.index) && + Objects.equals(serviceSid, other.serviceSid) && + Objects.equals(sid, other.sid) && + Objects.equals(to, other.to) && + Objects.equals(url, other.url) && + Objects.equals(wasEdited, other.wasEdited) ); } @Override public int hashCode() { return Objects.hash( - sid, - accountSid, - attributes, - serviceSid, - to, - channelSid, - dateCreated, - dateUpdated, - wasEdited, - from, - body, - index, - url + accountSid, + attributes, + body, + channelSid, + dateCreated, + dateUpdated, + from, + index, + serviceSid, + sid, + to, + url, + wasEdited ); } - public enum OrderType { - ASC("asc"), - DESC("desc"); - - private final String value; - private OrderType(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static OrderType forValue(final String value) { - return Promoter.enumFromString(value, OrderType.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/ipmessaging/v1/service/channel/MessageCreator.java b/src/main/java/com/twilio/rest/ipmessaging/v1/service/channel/MessageCreator.java index 0c382851d4..0957928668 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v1/service/channel/MessageCreator.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v1/service/channel/MessageCreator.java @@ -14,8 +14,11 @@ package com.twilio.rest.ipmessaging.v1.service.channel; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,76 +30,65 @@ public class MessageCreator extends Creator { - private String pathServiceSid; - private String pathChannelSid; + private String pathserviceSid; + private String pathchannelSid; private String body; private String from; private String attributes; - public MessageCreator( - final String pathServiceSid, - final String pathChannelSid, - final String body - ) { - this.pathServiceSid = pathServiceSid; - this.pathChannelSid = pathChannelSid; + public MessageCreator(final String pathserviceSid, final String pathchannelSid, final String body) { + this.pathserviceSid = pathserviceSid; + this.pathchannelSid = pathchannelSid; this.body = body; } + public MessageCreator setBody(final String body) { this.body = body; return this; } + public MessageCreator setFrom(final String from) { this.from = from; return this; } + public MessageCreator setAttributes(final String attributes) { this.attributes = attributes; return this; } + @Override public Message create(final TwilioRestClient client) { - String path = - "/v1/Services/{ServiceSid}/Channels/{ChannelSid}/Messages"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = - path.replace( - "{" + "ChannelSid" + "}", - this.pathChannelSid.toString() - ); - path = path.replace("{" + "Body" + "}", this.body.toString()); + String path = "/v1/Services/{ServiceSid}/Channels/{ChannelSid}/Messages"; + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "ChannelSid" + "}", this.pathchannelSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.IPMESSAGING.toString(), - path + HttpMethod.POST, + Domains.IPMESSAGING.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Message creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("Message creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -105,14 +97,21 @@ public Message create(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (body != null) { - request.addPostParam("Body", body); + Serializer.toString(request, "Body", body, ParameterType.URLENCODED); } + + if (from != null) { - request.addPostParam("From", from); + Serializer.toString(request, "From", from, ParameterType.URLENCODED); } + + if (attributes != null) { - request.addPostParam("Attributes", attributes); + Serializer.toString(request, "Attributes", attributes, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/ipmessaging/v1/service/channel/MessageDeleter.java b/src/main/java/com/twilio/rest/ipmessaging/v1/service/channel/MessageDeleter.java index 87470adcc9..c8c4ae91ea 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v1/service/channel/MessageDeleter.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v1/service/channel/MessageDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.ipmessaging.v1.service.channel; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,59 +26,44 @@ public class MessageDeleter extends Deleter { - private String pathServiceSid; - private String pathChannelSid; - private String pathSid; + private String pathserviceSid; + private String pathchannelSid; + private String pathsid; - public MessageDeleter( - final String pathServiceSid, - final String pathChannelSid, - final String pathSid - ) { - this.pathServiceSid = pathServiceSid; - this.pathChannelSid = pathChannelSid; - this.pathSid = pathSid; + public MessageDeleter(final String pathserviceSid, final String pathchannelSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathchannelSid = pathchannelSid; + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { - String path = - "/v1/Services/{ServiceSid}/Channels/{ChannelSid}/Messages/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = - path.replace( - "{" + "ChannelSid" + "}", - this.pathChannelSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/v1/Services/{ServiceSid}/Channels/{ChannelSid}/Messages/{Sid}"; + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "ChannelSid" + "}", this.pathchannelSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.IPMESSAGING.toString(), - path + HttpMethod.DELETE, + Domains.IPMESSAGING.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Message delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("Message delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/ipmessaging/v1/service/channel/MessageFetcher.java b/src/main/java/com/twilio/rest/ipmessaging/v1/service/channel/MessageFetcher.java index c80201f6b4..57f32a69f2 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v1/service/channel/MessageFetcher.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v1/service/channel/MessageFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.ipmessaging.v1.service.channel; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,63 +26,47 @@ public class MessageFetcher extends Fetcher { - private String pathServiceSid; - private String pathChannelSid; - private String pathSid; + private String pathserviceSid; + private String pathchannelSid; + private String pathsid; - public MessageFetcher( - final String pathServiceSid, - final String pathChannelSid, - final String pathSid - ) { - this.pathServiceSid = pathServiceSid; - this.pathChannelSid = pathChannelSid; - this.pathSid = pathSid; + public MessageFetcher(final String pathserviceSid, final String pathchannelSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathchannelSid = pathchannelSid; + this.pathsid = pathsid; } + @Override public Message fetch(final TwilioRestClient client) { - String path = - "/v1/Services/{ServiceSid}/Channels/{ChannelSid}/Messages/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = - path.replace( - "{" + "ChannelSid" + "}", - this.pathChannelSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/v1/Services/{ServiceSid}/Channels/{ChannelSid}/Messages/{Sid}"; + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "ChannelSid" + "}", this.pathchannelSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.IPMESSAGING.toString(), - path + HttpMethod.GET, + Domains.IPMESSAGING.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Message fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Message fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Message.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/ipmessaging/v1/service/channel/MessageReader.java b/src/main/java/com/twilio/rest/ipmessaging/v1/service/channel/MessageReader.java index 96a210478a..bdd85cb6ec 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v1/service/channel/MessageReader.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v1/service/channel/MessageReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,135 +30,103 @@ public class MessageReader extends Reader { - private String pathServiceSid; - private String pathChannelSid; + private String pathserviceSid; + private String pathchannelSid; private Message.OrderType order; private Long pageSize; - public MessageReader( - final String pathServiceSid, - final String pathChannelSid - ) { - this.pathServiceSid = pathServiceSid; - this.pathChannelSid = pathChannelSid; + public MessageReader(final String pathserviceSid, final String pathchannelSid) { + this.pathserviceSid = pathserviceSid; + this.pathchannelSid = pathchannelSid; } + public MessageReader setOrder(final Message.OrderType order) { this.order = order; return this; } + public MessageReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { - String path = - "/v1/Services/{ServiceSid}/Channels/{ChannelSid}/Messages"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = - path.replace( - "{" + "ChannelSid" + "}", - this.pathChannelSid.toString() - ); + + String path = "/v1/Services/{ServiceSid}/Channels/{ChannelSid}/Messages"; + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "ChannelSid" + "}", this.pathchannelSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.IPMESSAGING.toString(), - path + HttpMethod.GET, + Domains.IPMESSAGING.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Message read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Message read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "messages", - response.getContent(), - Message.class, - client.getObjectMapper() - ); + "messages", + response.getContent(), + Message.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.IPMESSAGING.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.IPMESSAGING.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (order != null) { - request.addQueryParam("Order", order.toString()); + Serializer.toString(request, "Order", order, ParameterType.QUERY); } + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/ipmessaging/v1/service/channel/MessageUpdater.java b/src/main/java/com/twilio/rest/ipmessaging/v1/service/channel/MessageUpdater.java index 3b0c0bbc18..396db57f33 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v1/service/channel/MessageUpdater.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v1/service/channel/MessageUpdater.java @@ -16,6 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -26,72 +28,60 @@ import com.twilio.rest.Domains; public class MessageUpdater extends Updater { - - private String pathServiceSid; - private String pathChannelSid; - private String pathSid; + private String pathserviceSid; + private String pathchannelSid; + private String pathsid; private String body; private String attributes; - public MessageUpdater( - final String pathServiceSid, - final String pathChannelSid, - final String pathSid - ) { - this.pathServiceSid = pathServiceSid; - this.pathChannelSid = pathChannelSid; - this.pathSid = pathSid; + public MessageUpdater(final String pathserviceSid, final String pathchannelSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathchannelSid = pathchannelSid; + this.pathsid = pathsid; } + public MessageUpdater setBody(final String body) { this.body = body; return this; } + public MessageUpdater setAttributes(final String attributes) { this.attributes = attributes; return this; } + @Override public Message update(final TwilioRestClient client) { - String path = - "/v1/Services/{ServiceSid}/Channels/{ChannelSid}/Messages/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = - path.replace( - "{" + "ChannelSid" + "}", - this.pathChannelSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/v1/Services/{ServiceSid}/Channels/{ChannelSid}/Messages/{Sid}"; + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "ChannelSid" + "}", this.pathchannelSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.IPMESSAGING.toString(), - path + HttpMethod.POST, + Domains.IPMESSAGING.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Message update failed: Unable to connect to server" - ); + throw new ApiConnectionException("Message update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -100,11 +90,16 @@ public Message update(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (body != null) { - request.addPostParam("Body", body); + Serializer.toString(request, "Body", body, ParameterType.URLENCODED); } + + if (attributes != null) { - request.addPostParam("Attributes", attributes); + Serializer.toString(request, "Attributes", attributes, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/ipmessaging/v1/service/user/UserChannel.java b/src/main/java/com/twilio/rest/ipmessaging/v1/service/user/UserChannel.java index 05ee6541e0..015432cbc9 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v1/service/user/UserChannel.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v1/service/user/UserChannel.java @@ -18,44 +18,63 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class UserChannel extends Resource { - private static final long serialVersionUID = 5311313114138L; - public static UserChannelReader reader( - final String pathServiceSid, - final String pathUserSid - ) { - return new UserChannelReader(pathServiceSid, pathUserSid); + public static UserChannelReader reader(final String pathserviceSid, final String pathuserSid) { + return new UserChannelReader( + pathserviceSid, pathuserSid + ); + } + + + public enum ChannelStatus { + JOINED("joined"), + INVITED("invited"), + NOT_PARTICIPATING("not_participating"); + + private final String value; + + private ChannelStatus(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static ChannelStatus forValue(final String value) { + return Promoter.enumFromString(value, ChannelStatus.values()); + } } + /** * Converts a JSON String into a UserChannel object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return UserChannel object represented by the provided JSON */ - public static UserChannel fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static UserChannel fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, UserChannel.class); @@ -70,14 +89,11 @@ public static UserChannel fromJson( * Converts a JSON InputStream into a UserChannel object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return UserChannel object represented by the provided JSON */ - public static UserChannel fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static UserChannel fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, UserChannel.class); @@ -88,70 +104,55 @@ public static UserChannel fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String serviceSid; + @Getter private final String channelSid; + @Getter + private final Integer lastConsumedMessageIndex; + @Getter + private final Map links; + @Getter private final String memberSid; + @Getter + private final String serviceSid; + @Getter private final UserChannel.ChannelStatus status; - private final Integer lastConsumedMessageIndex; + @Getter private final Integer unreadMessagesCount; - private final Map links; @JsonCreator private UserChannel( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("service_sid") final String serviceSid, - @JsonProperty("channel_sid") final String channelSid, - @JsonProperty("member_sid") final String memberSid, - @JsonProperty("status") final UserChannel.ChannelStatus status, - @JsonProperty( - "last_consumed_message_index" - ) final Integer lastConsumedMessageIndex, - @JsonProperty( - "unread_messages_count" - ) final Integer unreadMessagesCount, - @JsonProperty("links") final Map links + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("channel_sid") final String channelSid, + @JsonProperty("last_consumed_message_index") final Integer lastConsumedMessageIndex, + @JsonProperty("links") final Map links, + @JsonProperty("member_sid") final String memberSid, + @JsonProperty("service_sid") final String serviceSid, + @JsonProperty("status") final UserChannel.ChannelStatus status, + @JsonProperty("unread_messages_count") final Integer unreadMessagesCount ) { this.accountSid = accountSid; - this.serviceSid = serviceSid; this.channelSid = channelSid; + this.lastConsumedMessageIndex = lastConsumedMessageIndex; + this.links = links; this.memberSid = memberSid; + this.serviceSid = serviceSid; this.status = status; - this.lastConsumedMessageIndex = lastConsumedMessageIndex; this.unreadMessagesCount = unreadMessagesCount; - this.links = links; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getServiceSid() { - return this.serviceSid; - } - - public final String getChannelSid() { - return this.channelSid; - } - - public final String getMemberSid() { - return this.memberSid; - } - - public final UserChannel.ChannelStatus getStatus() { - return this.status; - } - - public final Integer getLastConsumedMessageIndex() { - return this.lastConsumedMessageIndex; - } - - public final Integer getUnreadMessagesCount() { - return this.unreadMessagesCount; - } - - public final Map getLinks() { - return this.links; } @Override @@ -165,54 +166,32 @@ public boolean equals(final Object o) { } UserChannel other = (UserChannel) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(serviceSid, other.serviceSid) && - Objects.equals(channelSid, other.channelSid) && - Objects.equals(memberSid, other.memberSid) && - Objects.equals(status, other.status) && - Objects.equals( - lastConsumedMessageIndex, - other.lastConsumedMessageIndex - ) && - Objects.equals(unreadMessagesCount, other.unreadMessagesCount) && - Objects.equals(links, other.links) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(channelSid, other.channelSid) && + Objects.equals(lastConsumedMessageIndex, other.lastConsumedMessageIndex) && + Objects.equals(links, other.links) && + Objects.equals(memberSid, other.memberSid) && + Objects.equals(serviceSid, other.serviceSid) && + Objects.equals(status, other.status) && + Objects.equals(unreadMessagesCount, other.unreadMessagesCount) ); } @Override public int hashCode() { return Objects.hash( - accountSid, - serviceSid, - channelSid, - memberSid, - status, - lastConsumedMessageIndex, - unreadMessagesCount, - links + accountSid, + channelSid, + lastConsumedMessageIndex, + links, + memberSid, + serviceSid, + status, + unreadMessagesCount ); } - public enum ChannelStatus { - JOINED("joined"), - INVITED("invited"), - NOT_PARTICIPATING("not_participating"); - - private final String value; - private ChannelStatus(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static ChannelStatus forValue(final String value) { - return Promoter.enumFromString(value, ChannelStatus.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/ipmessaging/v1/service/user/UserChannelReader.java b/src/main/java/com/twilio/rest/ipmessaging/v1/service/user/UserChannelReader.java index f9fb892945..7da5999e90 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v1/service/user/UserChannelReader.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v1/service/user/UserChannelReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,121 +30,91 @@ public class UserChannelReader extends Reader { - private String pathServiceSid; - private String pathUserSid; + private String pathserviceSid; + private String pathuserSid; private Long pageSize; - public UserChannelReader( - final String pathServiceSid, - final String pathUserSid - ) { - this.pathServiceSid = pathServiceSid; - this.pathUserSid = pathUserSid; + public UserChannelReader(final String pathserviceSid, final String pathuserSid) { + this.pathserviceSid = pathserviceSid; + this.pathuserSid = pathuserSid; } + public UserChannelReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/Services/{ServiceSid}/Users/{UserSid}/Channels"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = path.replace("{" + "UserSid" + "}", this.pathUserSid.toString()); + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "UserSid" + "}", this.pathuserSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.IPMESSAGING.toString(), - path + HttpMethod.GET, + Domains.IPMESSAGING.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "UserChannel read failed: Unable to connect to server" - ); + throw new ApiConnectionException("UserChannel read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "channels", - response.getContent(), - UserChannel.class, - client.getObjectMapper() - ); + "channels", + response.getContent(), + UserChannel.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.IPMESSAGING.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.IPMESSAGING.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/ipmessaging/v2/Credential.java b/src/main/java/com/twilio/rest/ipmessaging/v2/Credential.java index 9f6267c773..86f722150e 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v2/Credential.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v2/Credential.java @@ -18,58 +18,93 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Credential extends Resource { - private static final long serialVersionUID = 161183169234848L; public static CredentialCreator creator(final Credential.PushService type) { - return new CredentialCreator(type); + return new CredentialCreator( + type + ); } - public static CredentialDeleter deleter(final String pathSid) { - return new CredentialDeleter(pathSid); + + public static CredentialDeleter deleter(final String pathsid) { + return new CredentialDeleter( + pathsid + ); } - public static CredentialFetcher fetcher(final String pathSid) { - return new CredentialFetcher(pathSid); + + public static CredentialFetcher fetcher(final String pathsid) { + return new CredentialFetcher( + pathsid + ); } + public static CredentialReader reader() { - return new CredentialReader(); + return new CredentialReader( + + ); } - public static CredentialUpdater updater(final String pathSid) { - return new CredentialUpdater(pathSid); + + public static CredentialUpdater updater(final String pathsid) { + return new CredentialUpdater( + pathsid + ); } + + public enum PushService { + GCM("gcm"), + APN("apn"), + FCM("fcm"); + + private final String value; + + private PushService(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static PushService forValue(final String value) { + return Promoter.enumFromString(value, PushService.values()); + } + } + + /** * Converts a JSON String into a Credential object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Credential object represented by the provided JSON */ - public static Credential fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Credential fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Credential.class); @@ -84,14 +119,11 @@ public static Credential fromJson( * Converts a JSON InputStream into a Credential object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Credential object represented by the provided JSON */ - public static Credential fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Credential fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Credential.class); @@ -102,68 +134,59 @@ public static Credential fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String friendlyName; - private final Credential.PushService type; - private final String sandbox; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; + @Getter + private final String friendlyName; + @Getter + private final String sandbox; + @Getter + private final String sid; + @Getter + private final Credential.PushService type; + @Getter private final URI url; @JsonCreator private Credential( - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("type") final Credential.PushService type, - @JsonProperty("sandbox") final String sandbox, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("url") final URI url + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("sandbox") final String sandbox, + @JsonProperty("sid") final String sid, + @JsonProperty("type") final Credential.PushService type, + @JsonProperty("url") final URI url ) { - this.sid = sid; this.accountSid = accountSid; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.friendlyName = friendlyName; - this.type = type; this.sandbox = sandbox; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); + this.sid = sid; + this.type = type; this.url = url; } - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final Credential.PushService getType() { - return this.type; - } - - public final String getSandbox() { - return this.sandbox; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final URI getUrl() { - return this.url; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -175,51 +198,32 @@ public boolean equals(final Object o) { } Credential other = (Credential) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(type, other.type) && - Objects.equals(sandbox, other.sandbox) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(url, other.url) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(sandbox, other.sandbox) && + Objects.equals(sid, other.sid) && + Objects.equals(type, other.type) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - sid, - accountSid, - friendlyName, - type, - sandbox, - dateCreated, - dateUpdated, - url + accountSid, + dateCreated, + dateUpdated, + friendlyName, + sandbox, + sid, + type, + url ); } - public enum PushService { - GCM("gcm"), - APN("apn"), - FCM("fcm"); - - private final String value; - - private PushService(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - @JsonCreator - public static PushService forValue(final String value) { - return Promoter.enumFromString(value, PushService.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/ipmessaging/v2/CredentialCreator.java b/src/main/java/com/twilio/rest/ipmessaging/v2/CredentialCreator.java index bf50b01eaa..4bb735095c 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v2/CredentialCreator.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v2/CredentialCreator.java @@ -14,8 +14,11 @@ package com.twilio.rest.ipmessaging.v2; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -39,100 +42,117 @@ public CredentialCreator(final Credential.PushService type) { this.type = type; } + public CredentialCreator setType(final Credential.PushService type) { this.type = type; return this; } + public CredentialCreator setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + public CredentialCreator setCertificate(final String certificate) { this.certificate = certificate; return this; } + public CredentialCreator setPrivateKey(final String privateKey) { this.privateKey = privateKey; return this; } + public CredentialCreator setSandbox(final Boolean sandbox) { this.sandbox = sandbox; return this; } + public CredentialCreator setApiKey(final String apiKey) { this.apiKey = apiKey; return this; } + public CredentialCreator setSecret(final String secret) { this.secret = secret; return this; } + @Override public Credential create(final TwilioRestClient client) { + String path = "/v2/Credentials"; - path = path.replace("{" + "Type" + "}", this.type.toString()); Request request = new Request( - HttpMethod.POST, - Domains.IPMESSAGING.toString(), - path + HttpMethod.POST, + Domains.IPMESSAGING.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Credential creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("Credential creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Credential.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Credential.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (type != null) { - request.addPostParam("Type", type.toString()); + Serializer.toString(request, "Type", type, ParameterType.URLENCODED); } + + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + if (certificate != null) { - request.addPostParam("Certificate", certificate); + Serializer.toString(request, "Certificate", certificate, ParameterType.URLENCODED); } + + if (privateKey != null) { - request.addPostParam("PrivateKey", privateKey); + Serializer.toString(request, "PrivateKey", privateKey, ParameterType.URLENCODED); } + + if (sandbox != null) { - request.addPostParam("Sandbox", sandbox.toString()); + Serializer.toString(request, "Sandbox", sandbox, ParameterType.URLENCODED); } + + if (apiKey != null) { - request.addPostParam("ApiKey", apiKey); + Serializer.toString(request, "ApiKey", apiKey, ParameterType.URLENCODED); } + + if (secret != null) { - request.addPostParam("Secret", secret); + Serializer.toString(request, "Secret", secret, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/ipmessaging/v2/CredentialDeleter.java b/src/main/java/com/twilio/rest/ipmessaging/v2/CredentialDeleter.java index db8c80b4e5..1fb6a44728 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v2/CredentialDeleter.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v2/CredentialDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.ipmessaging.v2; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,40 +26,38 @@ public class CredentialDeleter extends Deleter { - private String pathSid; + private String pathsid; - public CredentialDeleter(final String pathSid) { - this.pathSid = pathSid; + public CredentialDeleter(final String pathsid) { + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/v2/Credentials/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.IPMESSAGING.toString(), - path + HttpMethod.DELETE, + Domains.IPMESSAGING.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Credential delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("Credential delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/ipmessaging/v2/CredentialFetcher.java b/src/main/java/com/twilio/rest/ipmessaging/v2/CredentialFetcher.java index f6ea7bbd01..a3f332c870 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v2/CredentialFetcher.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v2/CredentialFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.ipmessaging.v2; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,47 +26,41 @@ public class CredentialFetcher extends Fetcher { - private String pathSid; + private String pathsid; - public CredentialFetcher(final String pathSid) { - this.pathSid = pathSid; + public CredentialFetcher(final String pathsid) { + this.pathsid = pathsid; } + @Override public Credential fetch(final TwilioRestClient client) { + String path = "/v2/Credentials/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.IPMESSAGING.toString(), - path + HttpMethod.GET, + Domains.IPMESSAGING.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Credential fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Credential fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return Credential.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Credential.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/ipmessaging/v2/CredentialReader.java b/src/main/java/com/twilio/rest/ipmessaging/v2/CredentialReader.java index 7a44f2476a..907f98f35e 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v2/CredentialReader.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v2/CredentialReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -31,105 +32,83 @@ public class CredentialReader extends Reader { private Long pageSize; - public CredentialReader() {} + public CredentialReader() { + } + public CredentialReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v2/Credentials"; + Request request = new Request( - HttpMethod.GET, - Domains.IPMESSAGING.toString(), - path + HttpMethod.GET, + Domains.IPMESSAGING.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Credential read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Credential read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "credentials", - response.getContent(), - Credential.class, - client.getObjectMapper() - ); + "credentials", + response.getContent(), + Credential.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.IPMESSAGING.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.IPMESSAGING.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/ipmessaging/v2/CredentialUpdater.java b/src/main/java/com/twilio/rest/ipmessaging/v2/CredentialUpdater.java index 7b2c42d923..d73df32e70 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v2/CredentialUpdater.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v2/CredentialUpdater.java @@ -16,6 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -26,8 +28,7 @@ import com.twilio.rest.Domains; public class CredentialUpdater extends Updater { - - private String pathSid; + private String pathsid; private String friendlyName; private String certificate; private String privateKey; @@ -35,96 +36,112 @@ public class CredentialUpdater extends Updater { private String apiKey; private String secret; - public CredentialUpdater(final String pathSid) { - this.pathSid = pathSid; + public CredentialUpdater(final String pathsid) { + this.pathsid = pathsid; } + public CredentialUpdater setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + public CredentialUpdater setCertificate(final String certificate) { this.certificate = certificate; return this; } + public CredentialUpdater setPrivateKey(final String privateKey) { this.privateKey = privateKey; return this; } + public CredentialUpdater setSandbox(final Boolean sandbox) { this.sandbox = sandbox; return this; } + public CredentialUpdater setApiKey(final String apiKey) { this.apiKey = apiKey; return this; } + public CredentialUpdater setSecret(final String secret) { this.secret = secret; return this; } + @Override public Credential update(final TwilioRestClient client) { + String path = "/v2/Credentials/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.IPMESSAGING.toString(), - path + HttpMethod.POST, + Domains.IPMESSAGING.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Credential update failed: Unable to connect to server" - ); + throw new ApiConnectionException("Credential update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Credential.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Credential.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + if (certificate != null) { - request.addPostParam("Certificate", certificate); + Serializer.toString(request, "Certificate", certificate, ParameterType.URLENCODED); } + + if (privateKey != null) { - request.addPostParam("PrivateKey", privateKey); + Serializer.toString(request, "PrivateKey", privateKey, ParameterType.URLENCODED); } + + if (sandbox != null) { - request.addPostParam("Sandbox", sandbox.toString()); + Serializer.toString(request, "Sandbox", sandbox, ParameterType.URLENCODED); } + + if (apiKey != null) { - request.addPostParam("ApiKey", apiKey); + Serializer.toString(request, "ApiKey", apiKey, ParameterType.URLENCODED); } + + if (secret != null) { - request.addPostParam("Secret", secret); + Serializer.toString(request, "Secret", secret, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/ipmessaging/v2/Service.java b/src/main/java/com/twilio/rest/ipmessaging/v2/Service.java index f375007c6d..ef9ff0a500 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v2/Service.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v2/Service.java @@ -18,60 +18,72 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.List; import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Service extends Resource { - private static final long serialVersionUID = 187047184630676L; public static ServiceCreator creator(final String friendlyName) { - return new ServiceCreator(friendlyName); + return new ServiceCreator( + friendlyName + ); } - public static ServiceDeleter deleter(final String pathSid) { - return new ServiceDeleter(pathSid); + + public static ServiceDeleter deleter(final String pathsid) { + return new ServiceDeleter( + pathsid + ); } - public static ServiceFetcher fetcher(final String pathSid) { - return new ServiceFetcher(pathSid); + + public static ServiceFetcher fetcher(final String pathsid) { + return new ServiceFetcher( + pathsid + ); } + public static ServiceReader reader() { - return new ServiceReader(); + return new ServiceReader( + + ); } - public static ServiceUpdater updater(final String pathSid) { - return new ServiceUpdater(pathSid); + + public static ServiceUpdater updater(final String pathsid) { + return new ServiceUpdater( + pathsid + ); } + /** * Converts a JSON String into a Service object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Service object represented by the provided JSON */ - public static Service fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Service fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Service.class); @@ -86,14 +98,11 @@ public static Service fromJson( * Converts a JSON InputStream into a Service object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Service object represented by the provided JSON */ - public static Service fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Service fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Service.class); @@ -104,185 +113,117 @@ public static Service fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String friendlyName; + @Getter + private final Integer consumptionReportInterval; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; - private final String defaultServiceRoleSid; - private final String defaultChannelRoleSid; + @Getter private final String defaultChannelCreatorRoleSid; - private final Boolean readStatusEnabled; - private final Boolean reachabilityEnabled; - private final Integer typingIndicatorTimeout; - private final Integer consumptionReportInterval; - private final Map limits; - private final String preWebhookUrl; + @Getter + private final String defaultChannelRoleSid; + @Getter + private final String defaultServiceRoleSid; + @Getter + private final String friendlyName; + @Getter + private final Object limits; + @Getter + private final Map links; + @Getter + private final Object media; + @Getter + private final Object notifications; + @Getter + private final Integer postWebhookRetryCount; + @Getter private final String postWebhookUrl; - private final String webhookMethod; - private final List webhookFilters; + @Getter private final Integer preWebhookRetryCount; - private final Integer postWebhookRetryCount; - private final Map notifications; - private final Map media; + @Getter + private final String preWebhookUrl; + @Getter + private final Boolean reachabilityEnabled; + @Getter + private final Boolean readStatusEnabled; + @Getter + private final String sid; + @Getter + private final Integer typingIndicatorTimeout; + @Getter private final URI url; - private final Map links; + @Getter + private final List webhookFilters; + @Getter + private final String webhookMethod; @JsonCreator private Service( - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty( - "default_service_role_sid" - ) final String defaultServiceRoleSid, - @JsonProperty( - "default_channel_role_sid" - ) final String defaultChannelRoleSid, - @JsonProperty( - "default_channel_creator_role_sid" - ) final String defaultChannelCreatorRoleSid, - @JsonProperty("read_status_enabled") final Boolean readStatusEnabled, - @JsonProperty("reachability_enabled") final Boolean reachabilityEnabled, - @JsonProperty( - "typing_indicator_timeout" - ) final Integer typingIndicatorTimeout, - @JsonProperty( - "consumption_report_interval" - ) final Integer consumptionReportInterval, - @JsonProperty("limits") final Map limits, - @JsonProperty("pre_webhook_url") final String preWebhookUrl, - @JsonProperty("post_webhook_url") final String postWebhookUrl, - @JsonProperty("webhook_method") final String webhookMethod, - @JsonProperty("webhook_filters") final List webhookFilters, - @JsonProperty( - "pre_webhook_retry_count" - ) final Integer preWebhookRetryCount, - @JsonProperty( - "post_webhook_retry_count" - ) final Integer postWebhookRetryCount, - @JsonProperty("notifications") final Map notifications, - @JsonProperty("media") final Map media, - @JsonProperty("url") final URI url, - @JsonProperty("links") final Map links + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("consumption_report_interval") final Integer consumptionReportInterval, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("default_channel_creator_role_sid") final String defaultChannelCreatorRoleSid, + @JsonProperty("default_channel_role_sid") final String defaultChannelRoleSid, + @JsonProperty("default_service_role_sid") final String defaultServiceRoleSid, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("limits") final Object limits, + @JsonProperty("links") final Map links, + @JsonProperty("media") final Object media, + @JsonProperty("notifications") final Object notifications, + @JsonProperty("post_webhook_retry_count") final Integer postWebhookRetryCount, + @JsonProperty("post_webhook_url") final String postWebhookUrl, + @JsonProperty("pre_webhook_retry_count") final Integer preWebhookRetryCount, + @JsonProperty("pre_webhook_url") final String preWebhookUrl, + @JsonProperty("reachability_enabled") final Boolean reachabilityEnabled, + @JsonProperty("read_status_enabled") final Boolean readStatusEnabled, + @JsonProperty("sid") final String sid, + @JsonProperty("typing_indicator_timeout") final Integer typingIndicatorTimeout, + @JsonProperty("url") final URI url, + @JsonProperty("webhook_filters") final List webhookFilters, + @JsonProperty("webhook_method") final String webhookMethod ) { - this.sid = sid; this.accountSid = accountSid; - this.friendlyName = friendlyName; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); - this.defaultServiceRoleSid = defaultServiceRoleSid; - this.defaultChannelRoleSid = defaultChannelRoleSid; - this.defaultChannelCreatorRoleSid = defaultChannelCreatorRoleSid; - this.readStatusEnabled = readStatusEnabled; - this.reachabilityEnabled = reachabilityEnabled; - this.typingIndicatorTimeout = typingIndicatorTimeout; this.consumptionReportInterval = consumptionReportInterval; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; + this.defaultChannelCreatorRoleSid = defaultChannelCreatorRoleSid; + this.defaultChannelRoleSid = defaultChannelRoleSid; + this.defaultServiceRoleSid = defaultServiceRoleSid; + this.friendlyName = friendlyName; this.limits = limits; - this.preWebhookUrl = preWebhookUrl; + this.links = links; + this.media = media; + this.notifications = notifications; + this.postWebhookRetryCount = postWebhookRetryCount; this.postWebhookUrl = postWebhookUrl; - this.webhookMethod = webhookMethod; - this.webhookFilters = webhookFilters; this.preWebhookRetryCount = preWebhookRetryCount; - this.postWebhookRetryCount = postWebhookRetryCount; - this.notifications = notifications; - this.media = media; + this.preWebhookUrl = preWebhookUrl; + this.reachabilityEnabled = reachabilityEnabled; + this.readStatusEnabled = readStatusEnabled; + this.sid = sid; + this.typingIndicatorTimeout = typingIndicatorTimeout; this.url = url; - this.links = links; - } - - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final String getDefaultServiceRoleSid() { - return this.defaultServiceRoleSid; - } - - public final String getDefaultChannelRoleSid() { - return this.defaultChannelRoleSid; - } - - public final String getDefaultChannelCreatorRoleSid() { - return this.defaultChannelCreatorRoleSid; - } - - public final Boolean getReadStatusEnabled() { - return this.readStatusEnabled; - } - - public final Boolean getReachabilityEnabled() { - return this.reachabilityEnabled; - } - - public final Integer getTypingIndicatorTimeout() { - return this.typingIndicatorTimeout; - } - - public final Integer getConsumptionReportInterval() { - return this.consumptionReportInterval; - } - - public final Map getLimits() { - return this.limits; - } - - public final String getPreWebhookUrl() { - return this.preWebhookUrl; - } - - public final String getPostWebhookUrl() { - return this.postWebhookUrl; - } - - public final String getWebhookMethod() { - return this.webhookMethod; - } - - public final List getWebhookFilters() { - return this.webhookFilters; - } - - public final Integer getPreWebhookRetryCount() { - return this.preWebhookRetryCount; - } - - public final Integer getPostWebhookRetryCount() { - return this.postWebhookRetryCount; - } - - public final Map getNotifications() { - return this.notifications; - } - - public final Map getMedia() { - return this.media; - } - - public final URI getUrl() { - return this.url; - } - - public final Map getLinks() { - return this.links; + this.webhookFilters = webhookFilters; + this.webhookMethod = webhookMethod; } @Override @@ -296,78 +237,62 @@ public boolean equals(final Object o) { } Service other = (Service) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals( - defaultServiceRoleSid, - other.defaultServiceRoleSid - ) && - Objects.equals( - defaultChannelRoleSid, - other.defaultChannelRoleSid - ) && - Objects.equals( - defaultChannelCreatorRoleSid, - other.defaultChannelCreatorRoleSid - ) && - Objects.equals(readStatusEnabled, other.readStatusEnabled) && - Objects.equals(reachabilityEnabled, other.reachabilityEnabled) && - Objects.equals( - typingIndicatorTimeout, - other.typingIndicatorTimeout - ) && - Objects.equals( - consumptionReportInterval, - other.consumptionReportInterval - ) && - Objects.equals(limits, other.limits) && - Objects.equals(preWebhookUrl, other.preWebhookUrl) && - Objects.equals(postWebhookUrl, other.postWebhookUrl) && - Objects.equals(webhookMethod, other.webhookMethod) && - Objects.equals(webhookFilters, other.webhookFilters) && - Objects.equals(preWebhookRetryCount, other.preWebhookRetryCount) && - Objects.equals( - postWebhookRetryCount, - other.postWebhookRetryCount - ) && - Objects.equals(notifications, other.notifications) && - Objects.equals(media, other.media) && - Objects.equals(url, other.url) && - Objects.equals(links, other.links) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(consumptionReportInterval, other.consumptionReportInterval) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(defaultChannelCreatorRoleSid, other.defaultChannelCreatorRoleSid) && + Objects.equals(defaultChannelRoleSid, other.defaultChannelRoleSid) && + Objects.equals(defaultServiceRoleSid, other.defaultServiceRoleSid) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(limits, other.limits) && + Objects.equals(links, other.links) && + Objects.equals(media, other.media) && + Objects.equals(notifications, other.notifications) && + Objects.equals(postWebhookRetryCount, other.postWebhookRetryCount) && + Objects.equals(postWebhookUrl, other.postWebhookUrl) && + Objects.equals(preWebhookRetryCount, other.preWebhookRetryCount) && + Objects.equals(preWebhookUrl, other.preWebhookUrl) && + Objects.equals(reachabilityEnabled, other.reachabilityEnabled) && + Objects.equals(readStatusEnabled, other.readStatusEnabled) && + Objects.equals(sid, other.sid) && + Objects.equals(typingIndicatorTimeout, other.typingIndicatorTimeout) && + Objects.equals(url, other.url) && + Objects.equals(webhookFilters, other.webhookFilters) && + Objects.equals(webhookMethod, other.webhookMethod) ); } @Override public int hashCode() { return Objects.hash( - sid, - accountSid, - friendlyName, - dateCreated, - dateUpdated, - defaultServiceRoleSid, - defaultChannelRoleSid, - defaultChannelCreatorRoleSid, - readStatusEnabled, - reachabilityEnabled, - typingIndicatorTimeout, - consumptionReportInterval, - limits, - preWebhookUrl, - postWebhookUrl, - webhookMethod, - webhookFilters, - preWebhookRetryCount, - postWebhookRetryCount, - notifications, - media, - url, - links + accountSid, + consumptionReportInterval, + dateCreated, + dateUpdated, + defaultChannelCreatorRoleSid, + defaultChannelRoleSid, + defaultServiceRoleSid, + friendlyName, + limits, + links, + media, + notifications, + postWebhookRetryCount, + postWebhookUrl, + preWebhookRetryCount, + preWebhookUrl, + reachabilityEnabled, + readStatusEnabled, + sid, + typingIndicatorTimeout, + url, + webhookFilters, + webhookMethod ); } + + } + diff --git a/src/main/java/com/twilio/rest/ipmessaging/v2/ServiceCreator.java b/src/main/java/com/twilio/rest/ipmessaging/v2/ServiceCreator.java index 01a32ea434..34795c5b96 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v2/ServiceCreator.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v2/ServiceCreator.java @@ -14,8 +14,11 @@ package com.twilio.rest.ipmessaging.v2; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -33,43 +36,38 @@ public ServiceCreator(final String friendlyName) { this.friendlyName = friendlyName; } + public ServiceCreator setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + @Override public Service create(final TwilioRestClient client) { + String path = "/v2/Services"; - path = - path.replace( - "{" + "FriendlyName" + "}", - this.friendlyName.toString() - ); Request request = new Request( - HttpMethod.POST, - Domains.IPMESSAGING.toString(), - path + HttpMethod.POST, + Domains.IPMESSAGING.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Service creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("Service creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -78,8 +76,11 @@ public Service create(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/ipmessaging/v2/ServiceDeleter.java b/src/main/java/com/twilio/rest/ipmessaging/v2/ServiceDeleter.java index 25c41011dc..db71d0bc26 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v2/ServiceDeleter.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v2/ServiceDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.ipmessaging.v2; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,40 +26,38 @@ public class ServiceDeleter extends Deleter { - private String pathSid; + private String pathsid; - public ServiceDeleter(final String pathSid) { - this.pathSid = pathSid; + public ServiceDeleter(final String pathsid) { + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/v2/Services/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.IPMESSAGING.toString(), - path + HttpMethod.DELETE, + Domains.IPMESSAGING.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Service delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("Service delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/ipmessaging/v2/ServiceFetcher.java b/src/main/java/com/twilio/rest/ipmessaging/v2/ServiceFetcher.java index 52959e1c17..74d55a10f3 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v2/ServiceFetcher.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v2/ServiceFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.ipmessaging.v2; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,44 +26,41 @@ public class ServiceFetcher extends Fetcher { - private String pathSid; + private String pathsid; - public ServiceFetcher(final String pathSid) { - this.pathSid = pathSid; + public ServiceFetcher(final String pathsid) { + this.pathsid = pathsid; } + @Override public Service fetch(final TwilioRestClient client) { + String path = "/v2/Services/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.IPMESSAGING.toString(), - path + HttpMethod.GET, + Domains.IPMESSAGING.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Service fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Service fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Service.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/ipmessaging/v2/ServiceReader.java b/src/main/java/com/twilio/rest/ipmessaging/v2/ServiceReader.java index 6ef3e19825..8ae3bc2886 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v2/ServiceReader.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v2/ServiceReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -31,105 +32,83 @@ public class ServiceReader extends Reader { private Long pageSize; - public ServiceReader() {} + public ServiceReader() { + } + public ServiceReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v2/Services"; + Request request = new Request( - HttpMethod.GET, - Domains.IPMESSAGING.toString(), - path + HttpMethod.GET, + Domains.IPMESSAGING.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Service read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Service read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "services", - response.getContent(), - Service.class, - client.getObjectMapper() - ); + "services", + response.getContent(), + Service.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.IPMESSAGING.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.IPMESSAGING.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/ipmessaging/v2/ServiceUpdater.java b/src/main/java/com/twilio/rest/ipmessaging/v2/ServiceUpdater.java index 6bf3f6d07c..edaf54df17 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v2/ServiceUpdater.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v2/ServiceUpdater.java @@ -16,7 +16,9 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; import com.twilio.converter.Promoter; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,12 +27,12 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.net.URI; import java.util.List; public class ServiceUpdater extends Updater { - - private String pathSid; + private String pathsid; private String friendlyName; private String defaultServiceRoleSid; private String defaultChannelRoleSid; @@ -63,188 +65,155 @@ public class ServiceUpdater extends Updater { private Integer postWebhookRetryCount; private Boolean notificationsLogEnabled; - public ServiceUpdater(final String pathSid) { - this.pathSid = pathSid; + public ServiceUpdater(final String pathsid) { + this.pathsid = pathsid; } + public ServiceUpdater setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } - public ServiceUpdater setDefaultServiceRoleSid( - final String defaultServiceRoleSid - ) { + + public ServiceUpdater setDefaultServiceRoleSid(final String defaultServiceRoleSid) { this.defaultServiceRoleSid = defaultServiceRoleSid; return this; } - public ServiceUpdater setDefaultChannelRoleSid( - final String defaultChannelRoleSid - ) { + + public ServiceUpdater setDefaultChannelRoleSid(final String defaultChannelRoleSid) { this.defaultChannelRoleSid = defaultChannelRoleSid; return this; } - public ServiceUpdater setDefaultChannelCreatorRoleSid( - final String defaultChannelCreatorRoleSid - ) { + + public ServiceUpdater setDefaultChannelCreatorRoleSid(final String defaultChannelCreatorRoleSid) { this.defaultChannelCreatorRoleSid = defaultChannelCreatorRoleSid; return this; } - public ServiceUpdater setReadStatusEnabled( - final Boolean readStatusEnabled - ) { + + public ServiceUpdater setReadStatusEnabled(final Boolean readStatusEnabled) { this.readStatusEnabled = readStatusEnabled; return this; } - public ServiceUpdater setReachabilityEnabled( - final Boolean reachabilityEnabled - ) { + + public ServiceUpdater setReachabilityEnabled(final Boolean reachabilityEnabled) { this.reachabilityEnabled = reachabilityEnabled; return this; } - public ServiceUpdater setTypingIndicatorTimeout( - final Integer typingIndicatorTimeout - ) { + + public ServiceUpdater setTypingIndicatorTimeout(final Integer typingIndicatorTimeout) { this.typingIndicatorTimeout = typingIndicatorTimeout; return this; } - public ServiceUpdater setConsumptionReportInterval( - final Integer consumptionReportInterval - ) { + + public ServiceUpdater setConsumptionReportInterval(final Integer consumptionReportInterval) { this.consumptionReportInterval = consumptionReportInterval; return this; } - public ServiceUpdater setNotificationsNewMessageEnabled( - final Boolean notificationsNewMessageEnabled - ) { + + public ServiceUpdater setNotificationsNewMessageEnabled(final Boolean notificationsNewMessageEnabled) { this.notificationsNewMessageEnabled = notificationsNewMessageEnabled; return this; } - public ServiceUpdater setNotificationsNewMessageTemplate( - final String notificationsNewMessageTemplate - ) { + + public ServiceUpdater setNotificationsNewMessageTemplate(final String notificationsNewMessageTemplate) { this.notificationsNewMessageTemplate = notificationsNewMessageTemplate; return this; } - public ServiceUpdater setNotificationsNewMessageSound( - final String notificationsNewMessageSound - ) { + + public ServiceUpdater setNotificationsNewMessageSound(final String notificationsNewMessageSound) { this.notificationsNewMessageSound = notificationsNewMessageSound; return this; } - public ServiceUpdater setNotificationsNewMessageBadgeCountEnabled( - final Boolean notificationsNewMessageBadgeCountEnabled - ) { - this.notificationsNewMessageBadgeCountEnabled = - notificationsNewMessageBadgeCountEnabled; + + public ServiceUpdater setNotificationsNewMessageBadgeCountEnabled(final Boolean notificationsNewMessageBadgeCountEnabled) { + this.notificationsNewMessageBadgeCountEnabled = notificationsNewMessageBadgeCountEnabled; return this; } - public ServiceUpdater setNotificationsAddedToChannelEnabled( - final Boolean notificationsAddedToChannelEnabled - ) { - this.notificationsAddedToChannelEnabled = - notificationsAddedToChannelEnabled; + + public ServiceUpdater setNotificationsAddedToChannelEnabled(final Boolean notificationsAddedToChannelEnabled) { + this.notificationsAddedToChannelEnabled = notificationsAddedToChannelEnabled; return this; } - public ServiceUpdater setNotificationsAddedToChannelTemplate( - final String notificationsAddedToChannelTemplate - ) { - this.notificationsAddedToChannelTemplate = - notificationsAddedToChannelTemplate; + + public ServiceUpdater setNotificationsAddedToChannelTemplate(final String notificationsAddedToChannelTemplate) { + this.notificationsAddedToChannelTemplate = notificationsAddedToChannelTemplate; return this; } - public ServiceUpdater setNotificationsAddedToChannelSound( - final String notificationsAddedToChannelSound - ) { - this.notificationsAddedToChannelSound = - notificationsAddedToChannelSound; + + public ServiceUpdater setNotificationsAddedToChannelSound(final String notificationsAddedToChannelSound) { + this.notificationsAddedToChannelSound = notificationsAddedToChannelSound; return this; } - public ServiceUpdater setNotificationsRemovedFromChannelEnabled( - final Boolean notificationsRemovedFromChannelEnabled - ) { - this.notificationsRemovedFromChannelEnabled = - notificationsRemovedFromChannelEnabled; + + public ServiceUpdater setNotificationsRemovedFromChannelEnabled(final Boolean notificationsRemovedFromChannelEnabled) { + this.notificationsRemovedFromChannelEnabled = notificationsRemovedFromChannelEnabled; return this; } - public ServiceUpdater setNotificationsRemovedFromChannelTemplate( - final String notificationsRemovedFromChannelTemplate - ) { - this.notificationsRemovedFromChannelTemplate = - notificationsRemovedFromChannelTemplate; + + public ServiceUpdater setNotificationsRemovedFromChannelTemplate(final String notificationsRemovedFromChannelTemplate) { + this.notificationsRemovedFromChannelTemplate = notificationsRemovedFromChannelTemplate; return this; } - public ServiceUpdater setNotificationsRemovedFromChannelSound( - final String notificationsRemovedFromChannelSound - ) { - this.notificationsRemovedFromChannelSound = - notificationsRemovedFromChannelSound; + + public ServiceUpdater setNotificationsRemovedFromChannelSound(final String notificationsRemovedFromChannelSound) { + this.notificationsRemovedFromChannelSound = notificationsRemovedFromChannelSound; return this; } - public ServiceUpdater setNotificationsInvitedToChannelEnabled( - final Boolean notificationsInvitedToChannelEnabled - ) { - this.notificationsInvitedToChannelEnabled = - notificationsInvitedToChannelEnabled; + + public ServiceUpdater setNotificationsInvitedToChannelEnabled(final Boolean notificationsInvitedToChannelEnabled) { + this.notificationsInvitedToChannelEnabled = notificationsInvitedToChannelEnabled; return this; } - public ServiceUpdater setNotificationsInvitedToChannelTemplate( - final String notificationsInvitedToChannelTemplate - ) { - this.notificationsInvitedToChannelTemplate = - notificationsInvitedToChannelTemplate; + + public ServiceUpdater setNotificationsInvitedToChannelTemplate(final String notificationsInvitedToChannelTemplate) { + this.notificationsInvitedToChannelTemplate = notificationsInvitedToChannelTemplate; return this; } - public ServiceUpdater setNotificationsInvitedToChannelSound( - final String notificationsInvitedToChannelSound - ) { - this.notificationsInvitedToChannelSound = - notificationsInvitedToChannelSound; + + public ServiceUpdater setNotificationsInvitedToChannelSound(final String notificationsInvitedToChannelSound) { + this.notificationsInvitedToChannelSound = notificationsInvitedToChannelSound; return this; } + public ServiceUpdater setPreWebhookUrl(final URI preWebhookUrl) { this.preWebhookUrl = preWebhookUrl; return this; } - public ServiceUpdater setPreWebhookUrl(final String preWebhookUrl) { - return setPreWebhookUrl(Promoter.uriFromString(preWebhookUrl)); - } public ServiceUpdater setPostWebhookUrl(final URI postWebhookUrl) { this.postWebhookUrl = postWebhookUrl; return this; } - public ServiceUpdater setPostWebhookUrl(final String postWebhookUrl) { - return setPostWebhookUrl(Promoter.uriFromString(postWebhookUrl)); - } public ServiceUpdater setWebhookMethod(final HttpMethod webhookMethod) { this.webhookMethod = webhookMethod; return this; } + public ServiceUpdater setWebhookFilters(final List webhookFilters) { this.webhookFilters = webhookFilters; return this; @@ -254,76 +223,69 @@ public ServiceUpdater setWebhookFilters(final String webhookFilters) { return setWebhookFilters(Promoter.listOfOne(webhookFilters)); } - public ServiceUpdater setLimitsChannelMembers( - final Integer limitsChannelMembers - ) { + public ServiceUpdater setLimitsChannelMembers(final Integer limitsChannelMembers) { this.limitsChannelMembers = limitsChannelMembers; return this; } - public ServiceUpdater setLimitsUserChannels( - final Integer limitsUserChannels - ) { + + public ServiceUpdater setLimitsUserChannels(final Integer limitsUserChannels) { this.limitsUserChannels = limitsUserChannels; return this; } - public ServiceUpdater setMediaCompatibilityMessage( - final String mediaCompatibilityMessage - ) { + + public ServiceUpdater setMediaCompatibilityMessage(final String mediaCompatibilityMessage) { this.mediaCompatibilityMessage = mediaCompatibilityMessage; return this; } - public ServiceUpdater setPreWebhookRetryCount( - final Integer preWebhookRetryCount - ) { + + public ServiceUpdater setPreWebhookRetryCount(final Integer preWebhookRetryCount) { this.preWebhookRetryCount = preWebhookRetryCount; return this; } - public ServiceUpdater setPostWebhookRetryCount( - final Integer postWebhookRetryCount - ) { + + public ServiceUpdater setPostWebhookRetryCount(final Integer postWebhookRetryCount) { this.postWebhookRetryCount = postWebhookRetryCount; return this; } - public ServiceUpdater setNotificationsLogEnabled( - final Boolean notificationsLogEnabled - ) { + + public ServiceUpdater setNotificationsLogEnabled(final Boolean notificationsLogEnabled) { this.notificationsLogEnabled = notificationsLogEnabled; return this; } + @Override public Service update(final TwilioRestClient client) { + String path = "/v2/Services/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.IPMESSAGING.toString(), - path + HttpMethod.POST, + Domains.IPMESSAGING.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Service update failed: Unable to connect to server" - ); + throw new ApiConnectionException("Service update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -332,178 +294,163 @@ public Service update(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + if (defaultServiceRoleSid != null) { - request.addPostParam( - "DefaultServiceRoleSid", - defaultServiceRoleSid - ); + Serializer.toString(request, "DefaultServiceRoleSid", defaultServiceRoleSid, ParameterType.URLENCODED); } + + if (defaultChannelRoleSid != null) { - request.addPostParam( - "DefaultChannelRoleSid", - defaultChannelRoleSid - ); + Serializer.toString(request, "DefaultChannelRoleSid", defaultChannelRoleSid, ParameterType.URLENCODED); } + + if (defaultChannelCreatorRoleSid != null) { - request.addPostParam( - "DefaultChannelCreatorRoleSid", - defaultChannelCreatorRoleSid - ); + Serializer.toString(request, "DefaultChannelCreatorRoleSid", defaultChannelCreatorRoleSid, ParameterType.URLENCODED); } + + if (readStatusEnabled != null) { - request.addPostParam( - "ReadStatusEnabled", - readStatusEnabled.toString() - ); + Serializer.toString(request, "ReadStatusEnabled", readStatusEnabled, ParameterType.URLENCODED); } + + if (reachabilityEnabled != null) { - request.addPostParam( - "ReachabilityEnabled", - reachabilityEnabled.toString() - ); + Serializer.toString(request, "ReachabilityEnabled", reachabilityEnabled, ParameterType.URLENCODED); } + + if (typingIndicatorTimeout != null) { - request.addPostParam( - "TypingIndicatorTimeout", - typingIndicatorTimeout.toString() - ); + Serializer.toString(request, "TypingIndicatorTimeout", typingIndicatorTimeout, ParameterType.URLENCODED); } + + if (consumptionReportInterval != null) { - request.addPostParam( - "ConsumptionReportInterval", - consumptionReportInterval.toString() - ); + Serializer.toString(request, "ConsumptionReportInterval", consumptionReportInterval, ParameterType.URLENCODED); } + + if (notificationsNewMessageEnabled != null) { - request.addPostParam( - "Notifications.NewMessage.Enabled", - notificationsNewMessageEnabled.toString() - ); + Serializer.toString(request, "Notifications.NewMessage.Enabled", notificationsNewMessageEnabled, ParameterType.URLENCODED); } + + if (notificationsNewMessageTemplate != null) { - request.addPostParam( - "Notifications.NewMessage.Template", - notificationsNewMessageTemplate - ); + Serializer.toString(request, "Notifications.NewMessage.Template", notificationsNewMessageTemplate, ParameterType.URLENCODED); } + + if (notificationsNewMessageSound != null) { - request.addPostParam( - "Notifications.NewMessage.Sound", - notificationsNewMessageSound - ); + Serializer.toString(request, "Notifications.NewMessage.Sound", notificationsNewMessageSound, ParameterType.URLENCODED); } + + if (notificationsNewMessageBadgeCountEnabled != null) { - request.addPostParam( - "Notifications.NewMessage.BadgeCountEnabled", - notificationsNewMessageBadgeCountEnabled.toString() - ); + Serializer.toString(request, "Notifications.NewMessage.BadgeCountEnabled", notificationsNewMessageBadgeCountEnabled, ParameterType.URLENCODED); } + + if (notificationsAddedToChannelEnabled != null) { - request.addPostParam( - "Notifications.AddedToChannel.Enabled", - notificationsAddedToChannelEnabled.toString() - ); + Serializer.toString(request, "Notifications.AddedToChannel.Enabled", notificationsAddedToChannelEnabled, ParameterType.URLENCODED); } + + if (notificationsAddedToChannelTemplate != null) { - request.addPostParam( - "Notifications.AddedToChannel.Template", - notificationsAddedToChannelTemplate - ); + Serializer.toString(request, "Notifications.AddedToChannel.Template", notificationsAddedToChannelTemplate, ParameterType.URLENCODED); } + + if (notificationsAddedToChannelSound != null) { - request.addPostParam( - "Notifications.AddedToChannel.Sound", - notificationsAddedToChannelSound - ); + Serializer.toString(request, "Notifications.AddedToChannel.Sound", notificationsAddedToChannelSound, ParameterType.URLENCODED); } + + if (notificationsRemovedFromChannelEnabled != null) { - request.addPostParam( - "Notifications.RemovedFromChannel.Enabled", - notificationsRemovedFromChannelEnabled.toString() - ); + Serializer.toString(request, "Notifications.RemovedFromChannel.Enabled", notificationsRemovedFromChannelEnabled, ParameterType.URLENCODED); } + + if (notificationsRemovedFromChannelTemplate != null) { - request.addPostParam( - "Notifications.RemovedFromChannel.Template", - notificationsRemovedFromChannelTemplate - ); + Serializer.toString(request, "Notifications.RemovedFromChannel.Template", notificationsRemovedFromChannelTemplate, ParameterType.URLENCODED); } + + if (notificationsRemovedFromChannelSound != null) { - request.addPostParam( - "Notifications.RemovedFromChannel.Sound", - notificationsRemovedFromChannelSound - ); + Serializer.toString(request, "Notifications.RemovedFromChannel.Sound", notificationsRemovedFromChannelSound, ParameterType.URLENCODED); } + + if (notificationsInvitedToChannelEnabled != null) { - request.addPostParam( - "Notifications.InvitedToChannel.Enabled", - notificationsInvitedToChannelEnabled.toString() - ); + Serializer.toString(request, "Notifications.InvitedToChannel.Enabled", notificationsInvitedToChannelEnabled, ParameterType.URLENCODED); } + + if (notificationsInvitedToChannelTemplate != null) { - request.addPostParam( - "Notifications.InvitedToChannel.Template", - notificationsInvitedToChannelTemplate - ); + Serializer.toString(request, "Notifications.InvitedToChannel.Template", notificationsInvitedToChannelTemplate, ParameterType.URLENCODED); } + + if (notificationsInvitedToChannelSound != null) { - request.addPostParam( - "Notifications.InvitedToChannel.Sound", - notificationsInvitedToChannelSound - ); + Serializer.toString(request, "Notifications.InvitedToChannel.Sound", notificationsInvitedToChannelSound, ParameterType.URLENCODED); } + + if (preWebhookUrl != null) { - request.addPostParam("PreWebhookUrl", preWebhookUrl.toString()); + Serializer.toString(request, "PreWebhookUrl", preWebhookUrl, ParameterType.URLENCODED); } + + if (postWebhookUrl != null) { - request.addPostParam("PostWebhookUrl", postWebhookUrl.toString()); + Serializer.toString(request, "PostWebhookUrl", postWebhookUrl, ParameterType.URLENCODED); } + + if (webhookMethod != null) { - request.addPostParam("WebhookMethod", webhookMethod.toString()); + Serializer.toString(request, "WebhookMethod", webhookMethod, ParameterType.URLENCODED); } + + if (webhookFilters != null) { - for (String prop : webhookFilters) { - request.addPostParam("WebhookFilters", prop); + for (String param : webhookFilters) { + Serializer.toString(request, "WebhookFilters", param, ParameterType.URLENCODED); } } + + if (limitsChannelMembers != null) { - request.addPostParam( - "Limits.ChannelMembers", - limitsChannelMembers.toString() - ); + Serializer.toString(request, "Limits.ChannelMembers", limitsChannelMembers, ParameterType.URLENCODED); } + + if (limitsUserChannels != null) { - request.addPostParam( - "Limits.UserChannels", - limitsUserChannels.toString() - ); + Serializer.toString(request, "Limits.UserChannels", limitsUserChannels, ParameterType.URLENCODED); } + + if (mediaCompatibilityMessage != null) { - request.addPostParam( - "Media.CompatibilityMessage", - mediaCompatibilityMessage - ); + Serializer.toString(request, "Media.CompatibilityMessage", mediaCompatibilityMessage, ParameterType.URLENCODED); } + + if (preWebhookRetryCount != null) { - request.addPostParam( - "PreWebhookRetryCount", - preWebhookRetryCount.toString() - ); + Serializer.toString(request, "PreWebhookRetryCount", preWebhookRetryCount, ParameterType.URLENCODED); } + + if (postWebhookRetryCount != null) { - request.addPostParam( - "PostWebhookRetryCount", - postWebhookRetryCount.toString() - ); + Serializer.toString(request, "PostWebhookRetryCount", postWebhookRetryCount, ParameterType.URLENCODED); } + + if (notificationsLogEnabled != null) { - request.addPostParam( - "Notifications.LogEnabled", - notificationsLogEnabled.toString() - ); + Serializer.toString(request, "Notifications.LogEnabled", notificationsLogEnabled, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/ipmessaging/v2/service/Binding.java b/src/main/java/com/twilio/rest/ipmessaging/v2/service/Binding.java index 3004b0a963..8c8ec6a8f7 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v2/service/Binding.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v2/service/Binding.java @@ -18,59 +18,81 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.List; import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Binding extends Resource { - private static final long serialVersionUID = 223064407729885L; - public static BindingDeleter deleter( - final String pathServiceSid, - final String pathSid - ) { - return new BindingDeleter(pathServiceSid, pathSid); + public static BindingDeleter deleter(final String pathserviceSid, final String pathsid) { + return new BindingDeleter( + pathserviceSid, pathsid + ); } - public static BindingFetcher fetcher( - final String pathServiceSid, - final String pathSid - ) { - return new BindingFetcher(pathServiceSid, pathSid); + + public static BindingFetcher fetcher(final String pathserviceSid, final String pathsid) { + return new BindingFetcher( + pathserviceSid, pathsid + ); + } + + + public static BindingReader reader(final String pathserviceSid) { + return new BindingReader( + pathserviceSid + ); } - public static BindingReader reader(final String pathServiceSid) { - return new BindingReader(pathServiceSid); + + public enum BindingType { + GCM("gcm"), + APN("apn"), + FCM("fcm"); + + private final String value; + + private BindingType(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static BindingType forValue(final String value) { + return Promoter.enumFromString(value, BindingType.values()); + } } + /** * Converts a JSON String into a Binding object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Binding object represented by the provided JSON */ - public static Binding fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Binding fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Binding.class); @@ -85,14 +107,11 @@ public static Binding fromJson( * Converts a JSON InputStream into a Binding object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Binding object represented by the provided JSON */ - public static Binding fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Binding fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Binding.class); @@ -103,94 +122,73 @@ public static Binding fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String serviceSid; + @Getter + private final Binding.BindingType bindingType; + @Getter + private final String credentialSid; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; + @Getter private final String endpoint; + @Getter private final String identity; - private final String credentialSid; - private final Binding.BindingType bindingType; + @Getter + private final Map links; + @Getter private final List messageTypes; + @Getter + private final String serviceSid; + @Getter + private final String sid; + @Getter private final URI url; - private final Map links; @JsonCreator private Binding( - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("service_sid") final String serviceSid, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("endpoint") final String endpoint, - @JsonProperty("identity") final String identity, - @JsonProperty("credential_sid") final String credentialSid, - @JsonProperty("binding_type") final Binding.BindingType bindingType, - @JsonProperty("message_types") final List messageTypes, - @JsonProperty("url") final URI url, - @JsonProperty("links") final Map links + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("binding_type") final Binding.BindingType bindingType, + @JsonProperty("credential_sid") final String credentialSid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("endpoint") final String endpoint, + @JsonProperty("identity") final String identity, + @JsonProperty("links") final Map links, + @JsonProperty("message_types") final List messageTypes, + @JsonProperty("service_sid") final String serviceSid, + @JsonProperty("sid") final String sid, + @JsonProperty("url") final URI url ) { - this.sid = sid; this.accountSid = accountSid; - this.serviceSid = serviceSid; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); + this.bindingType = bindingType; + this.credentialSid = credentialSid; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.endpoint = endpoint; this.identity = identity; - this.credentialSid = credentialSid; - this.bindingType = bindingType; + this.links = links; this.messageTypes = messageTypes; + this.serviceSid = serviceSid; + this.sid = sid; this.url = url; - this.links = links; - } - - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getServiceSid() { - return this.serviceSid; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final String getEndpoint() { - return this.endpoint; - } - - public final String getIdentity() { - return this.identity; - } - - public final String getCredentialSid() { - return this.credentialSid; - } - - public final Binding.BindingType getBindingType() { - return this.bindingType; - } - - public final List getMessageTypes() { - return this.messageTypes; - } - - public final URI getUrl() { - return this.url; - } - - public final Map getLinks() { - return this.links; } @Override @@ -204,59 +202,40 @@ public boolean equals(final Object o) { } Binding other = (Binding) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(serviceSid, other.serviceSid) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(endpoint, other.endpoint) && - Objects.equals(identity, other.identity) && - Objects.equals(credentialSid, other.credentialSid) && - Objects.equals(bindingType, other.bindingType) && - Objects.equals(messageTypes, other.messageTypes) && - Objects.equals(url, other.url) && - Objects.equals(links, other.links) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(bindingType, other.bindingType) && + Objects.equals(credentialSid, other.credentialSid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(endpoint, other.endpoint) && + Objects.equals(identity, other.identity) && + Objects.equals(links, other.links) && + Objects.equals(messageTypes, other.messageTypes) && + Objects.equals(serviceSid, other.serviceSid) && + Objects.equals(sid, other.sid) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - sid, - accountSid, - serviceSid, - dateCreated, - dateUpdated, - endpoint, - identity, - credentialSid, - bindingType, - messageTypes, - url, - links + accountSid, + bindingType, + credentialSid, + dateCreated, + dateUpdated, + endpoint, + identity, + links, + messageTypes, + serviceSid, + sid, + url ); } - public enum BindingType { - GCM("gcm"), - APN("apn"), - FCM("fcm"); - private final String value; - - private BindingType(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static BindingType forValue(final String value) { - return Promoter.enumFromString(value, BindingType.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/ipmessaging/v2/service/BindingDeleter.java b/src/main/java/com/twilio/rest/ipmessaging/v2/service/BindingDeleter.java index 5cb4af7c99..90c9f89e38 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v2/service/BindingDeleter.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v2/service/BindingDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.ipmessaging.v2.service; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,47 +26,41 @@ public class BindingDeleter extends Deleter { - private String pathServiceSid; - private String pathSid; + private String pathserviceSid; + private String pathsid; - public BindingDeleter(final String pathServiceSid, final String pathSid) { - this.pathServiceSid = pathServiceSid; - this.pathSid = pathSid; + public BindingDeleter(final String pathserviceSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/v2/Services/{ServiceSid}/Bindings/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.IPMESSAGING.toString(), - path + HttpMethod.DELETE, + Domains.IPMESSAGING.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Binding delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("Binding delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/ipmessaging/v2/service/BindingFetcher.java b/src/main/java/com/twilio/rest/ipmessaging/v2/service/BindingFetcher.java index 6ab7b48b2b..ef81e10c75 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v2/service/BindingFetcher.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v2/service/BindingFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.ipmessaging.v2.service; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,51 +26,44 @@ public class BindingFetcher extends Fetcher { - private String pathServiceSid; - private String pathSid; + private String pathserviceSid; + private String pathsid; - public BindingFetcher(final String pathServiceSid, final String pathSid) { - this.pathServiceSid = pathServiceSid; - this.pathSid = pathSid; + public BindingFetcher(final String pathserviceSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathsid = pathsid; } + @Override public Binding fetch(final TwilioRestClient client) { + String path = "/v2/Services/{ServiceSid}/Bindings/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.IPMESSAGING.toString(), - path + HttpMethod.GET, + Domains.IPMESSAGING.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Binding fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Binding fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Binding.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/ipmessaging/v2/service/BindingReader.java b/src/main/java/com/twilio/rest/ipmessaging/v2/service/BindingReader.java index 83a3400e90..82a52e2984 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v2/service/BindingReader.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v2/service/BindingReader.java @@ -17,8 +17,9 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; import com.twilio.converter.Promoter; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,22 +28,22 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.util.List; public class BindingReader extends Reader { - private String pathServiceSid; + private String pathserviceSid; private List bindingType; private List identity; private Long pageSize; - public BindingReader(final String pathServiceSid) { - this.pathServiceSid = pathServiceSid; + public BindingReader(final String pathserviceSid) { + this.pathserviceSid = pathserviceSid; } - public BindingReader setBindingType( - final List bindingType - ) { + + public BindingReader setBindingType(final List bindingType) { this.bindingType = bindingType; return this; } @@ -65,113 +66,89 @@ public BindingReader setPageSize(final Long pageSize) { return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v2/Services/{ServiceSid}/Bindings"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.IPMESSAGING.toString(), - path + HttpMethod.GET, + Domains.IPMESSAGING.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Binding read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Binding read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "bindings", - response.getContent(), - Binding.class, - client.getObjectMapper() - ); + "bindings", + response.getContent(), + Binding.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.IPMESSAGING.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.IPMESSAGING.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (bindingType != null) { - for (Binding.BindingType prop : bindingType) { - request.addQueryParam("BindingType", prop.toString()); + for (Binding.BindingType param : bindingType) { + Serializer.toString(request, "BindingType", param, ParameterType.QUERY); } } + + if (identity != null) { - for (String prop : identity) { - request.addQueryParam("Identity", prop); + for (String param : identity) { + Serializer.toString(request, "Identity", param, ParameterType.QUERY); } } + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/ipmessaging/v2/service/Channel.java b/src/main/java/com/twilio/rest/ipmessaging/v2/service/Channel.java index 19ae5463c6..7002d569cb 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v2/service/Channel.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v2/service/Channel.java @@ -18,69 +18,113 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Channel extends Resource { - private static final long serialVersionUID = 188288773259274L; - public static ChannelCreator creator(final String pathServiceSid) { - return new ChannelCreator(pathServiceSid); + public static ChannelCreator creator(final String pathserviceSid) { + return new ChannelCreator( + pathserviceSid + ); } - public static ChannelDeleter deleter( - final String pathServiceSid, - final String pathSid - ) { - return new ChannelDeleter(pathServiceSid, pathSid); + + public static ChannelDeleter deleter(final String pathserviceSid, final String pathsid) { + return new ChannelDeleter( + pathserviceSid, pathsid + ); } - public static ChannelFetcher fetcher( - final String pathServiceSid, - final String pathSid - ) { - return new ChannelFetcher(pathServiceSid, pathSid); + + public static ChannelFetcher fetcher(final String pathserviceSid, final String pathsid) { + return new ChannelFetcher( + pathserviceSid, pathsid + ); } - public static ChannelReader reader(final String pathServiceSid) { - return new ChannelReader(pathServiceSid); + + public static ChannelReader reader(final String pathserviceSid) { + return new ChannelReader( + pathserviceSid + ); } - public static ChannelUpdater updater( - final String pathServiceSid, - final String pathSid - ) { - return new ChannelUpdater(pathServiceSid, pathSid); + + public static ChannelUpdater updater(final String pathserviceSid, final String pathsid) { + return new ChannelUpdater( + pathserviceSid, pathsid + ); + } + + + public enum WebhookEnabledType { + TRUE("true"), + FALSE("false"); + + private final String value; + + private WebhookEnabledType(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static WebhookEnabledType forValue(final String value) { + return Promoter.enumFromString(value, WebhookEnabledType.values()); + } + } + + public enum ChannelType { + PUBLIC("public"), + PRIVATE("private"); + + private final String value; + + private ChannelType(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static ChannelType forValue(final String value) { + return Promoter.enumFromString(value, ChannelType.values()); + } } + /** * Converts a JSON String into a Channel object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Channel object represented by the provided JSON */ - public static Channel fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Channel fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Channel.class); @@ -95,14 +139,11 @@ public static Channel fromJson( * Converts a JSON InputStream into a Channel object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Channel object represented by the provided JSON */ - public static Channel fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Channel fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Channel.class); @@ -113,108 +154,81 @@ public static Channel fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String serviceSid; - private final String friendlyName; - private final String uniqueName; + @Getter private final String attributes; - private final Channel.ChannelType type; + @Getter + private final String createdBy; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; - private final String createdBy; + @Getter + private final String friendlyName; + @Getter + private final Map links; + @Getter private final Integer membersCount; + @Getter private final Integer messagesCount; + @Getter + private final String serviceSid; + @Getter + private final String sid; + @Getter + private final Channel.ChannelType type; + @Getter + private final String uniqueName; + @Getter private final URI url; - private final Map links; @JsonCreator private Channel( - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("service_sid") final String serviceSid, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("unique_name") final String uniqueName, - @JsonProperty("attributes") final String attributes, - @JsonProperty("type") final Channel.ChannelType type, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("created_by") final String createdBy, - @JsonProperty("members_count") final Integer membersCount, - @JsonProperty("messages_count") final Integer messagesCount, - @JsonProperty("url") final URI url, - @JsonProperty("links") final Map links + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("attributes") final String attributes, + @JsonProperty("created_by") final String createdBy, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("links") final Map links, + @JsonProperty("members_count") final Integer membersCount, + @JsonProperty("messages_count") final Integer messagesCount, + @JsonProperty("service_sid") final String serviceSid, + @JsonProperty("sid") final String sid, + @JsonProperty("type") final Channel.ChannelType type, + @JsonProperty("unique_name") final String uniqueName, + @JsonProperty("url") final URI url ) { - this.sid = sid; this.accountSid = accountSid; - this.serviceSid = serviceSid; - this.friendlyName = friendlyName; - this.uniqueName = uniqueName; this.attributes = attributes; - this.type = type; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); this.createdBy = createdBy; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; + this.friendlyName = friendlyName; + this.links = links; this.membersCount = membersCount; this.messagesCount = messagesCount; + this.serviceSid = serviceSid; + this.sid = sid; + this.type = type; + this.uniqueName = uniqueName; this.url = url; - this.links = links; - } - - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getServiceSid() { - return this.serviceSid; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final String getUniqueName() { - return this.uniqueName; - } - - public final String getAttributes() { - return this.attributes; - } - - public final Channel.ChannelType getType() { - return this.type; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final String getCreatedBy() { - return this.createdBy; - } - - public final Integer getMembersCount() { - return this.membersCount; - } - - public final Integer getMessagesCount() { - return this.messagesCount; - } - - public final URI getUrl() { - return this.url; - } - - public final Map getLinks() { - return this.links; } @Override @@ -228,82 +242,44 @@ public boolean equals(final Object o) { } Channel other = (Channel) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(serviceSid, other.serviceSid) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(uniqueName, other.uniqueName) && - Objects.equals(attributes, other.attributes) && - Objects.equals(type, other.type) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(createdBy, other.createdBy) && - Objects.equals(membersCount, other.membersCount) && - Objects.equals(messagesCount, other.messagesCount) && - Objects.equals(url, other.url) && - Objects.equals(links, other.links) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(attributes, other.attributes) && + Objects.equals(createdBy, other.createdBy) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(links, other.links) && + Objects.equals(membersCount, other.membersCount) && + Objects.equals(messagesCount, other.messagesCount) && + Objects.equals(serviceSid, other.serviceSid) && + Objects.equals(sid, other.sid) && + Objects.equals(type, other.type) && + Objects.equals(uniqueName, other.uniqueName) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - sid, - accountSid, - serviceSid, - friendlyName, - uniqueName, - attributes, - type, - dateCreated, - dateUpdated, - createdBy, - membersCount, - messagesCount, - url, - links + accountSid, + attributes, + createdBy, + dateCreated, + dateUpdated, + friendlyName, + links, + membersCount, + messagesCount, + serviceSid, + sid, + type, + uniqueName, + url ); } - public enum ChannelType { - PUBLIC("public"), - PRIVATE("private"); - - private final String value; - - private ChannelType(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static ChannelType forValue(final String value) { - return Promoter.enumFromString(value, ChannelType.values()); - } - } - public enum WebhookEnabledType { - TRUE("true"), - FALSE("false"); - - private final String value; - - private WebhookEnabledType(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static WebhookEnabledType forValue(final String value) { - return Promoter.enumFromString(value, WebhookEnabledType.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/ipmessaging/v2/service/ChannelCreator.java b/src/main/java/com/twilio/rest/ipmessaging/v2/service/ChannelCreator.java index 66d49f7bd2..a43df25663 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v2/service/ChannelCreator.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v2/service/ChannelCreator.java @@ -14,8 +14,11 @@ package com.twilio.rest.ipmessaging.v2.service; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -24,11 +27,12 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.time.ZonedDateTime; public class ChannelCreator extends Creator { - private String pathServiceSid; + private String pathserviceSid; private Channel.WebhookEnabledType xTwilioWebhookEnabled; private String friendlyName; private String uniqueName; @@ -38,85 +42,87 @@ public class ChannelCreator extends Creator { private ZonedDateTime dateUpdated; private String createdBy; - public ChannelCreator(final String pathServiceSid) { - this.pathServiceSid = pathServiceSid; + public ChannelCreator(final String pathserviceSid) { + this.pathserviceSid = pathserviceSid; } - public ChannelCreator setXTwilioWebhookEnabled( - final Channel.WebhookEnabledType xTwilioWebhookEnabled - ) { - this.xTwilioWebhookEnabled = xTwilioWebhookEnabled; - return this; - } public ChannelCreator setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + public ChannelCreator setUniqueName(final String uniqueName) { this.uniqueName = uniqueName; return this; } + public ChannelCreator setAttributes(final String attributes) { this.attributes = attributes; return this; } + public ChannelCreator setType(final Channel.ChannelType type) { this.type = type; return this; } + public ChannelCreator setDateCreated(final ZonedDateTime dateCreated) { this.dateCreated = dateCreated; return this; } + public ChannelCreator setDateUpdated(final ZonedDateTime dateUpdated) { this.dateUpdated = dateUpdated; return this; } + public ChannelCreator setCreatedBy(final String createdBy) { this.createdBy = createdBy; return this; } + + public ChannelCreator setXTwilioWebhookEnabled(final Channel.WebhookEnabledType xTwilioWebhookEnabled) { + this.xTwilioWebhookEnabled = xTwilioWebhookEnabled; + return this; + } + + @Override public Channel create(final TwilioRestClient client) { + String path = "/v2/Services/{ServiceSid}/Channels"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.IPMESSAGING.toString(), - path + HttpMethod.POST, + Domains.IPMESSAGING.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); - addPostParams(request); addHeaderParams(request); + addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Channel creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("Channel creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -125,41 +131,49 @@ public Channel create(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + if (uniqueName != null) { - request.addPostParam("UniqueName", uniqueName); + Serializer.toString(request, "UniqueName", uniqueName, ParameterType.URLENCODED); } + + if (attributes != null) { - request.addPostParam("Attributes", attributes); + Serializer.toString(request, "Attributes", attributes, ParameterType.URLENCODED); } + + if (type != null) { - request.addPostParam("Type", type.toString()); + Serializer.toString(request, "Type", type, ParameterType.URLENCODED); } + + if (dateCreated != null) { - request.addPostParam( - "DateCreated", - dateCreated.toInstant().toString() - ); + Serializer.toString(request, "DateCreated", dateCreated, ParameterType.URLENCODED); } + + if (dateUpdated != null) { - request.addPostParam( - "DateUpdated", - dateUpdated.toInstant().toString() - ); + Serializer.toString(request, "DateUpdated", dateUpdated, ParameterType.URLENCODED); } + + if (createdBy != null) { - request.addPostParam("CreatedBy", createdBy); + Serializer.toString(request, "CreatedBy", createdBy, ParameterType.URLENCODED); } + + } private void addHeaderParams(final Request request) { + if (xTwilioWebhookEnabled != null) { - request.addHeaderParam( - "X-Twilio-Webhook-Enabled", - xTwilioWebhookEnabled.toString() - ); + Serializer.toString(request, "X-Twilio-Webhook-Enabled", xTwilioWebhookEnabled, ParameterType.HEADER); } + } } diff --git a/src/main/java/com/twilio/rest/ipmessaging/v2/service/ChannelDeleter.java b/src/main/java/com/twilio/rest/ipmessaging/v2/service/ChannelDeleter.java index 4a5ac2c908..ca67dbecd8 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v2/service/ChannelDeleter.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v2/service/ChannelDeleter.java @@ -15,7 +15,8 @@ package com.twilio.rest.ipmessaging.v2.service; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,56 +28,49 @@ public class ChannelDeleter extends Deleter { - private String pathServiceSid; - private String pathSid; + private String pathserviceSid; + private String pathsid; private Channel.WebhookEnabledType xTwilioWebhookEnabled; - public ChannelDeleter(final String pathServiceSid, final String pathSid) { - this.pathServiceSid = pathServiceSid; - this.pathSid = pathSid; + public ChannelDeleter(final String pathserviceSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathsid = pathsid; } - public ChannelDeleter setXTwilioWebhookEnabled( - final Channel.WebhookEnabledType xTwilioWebhookEnabled - ) { + + public ChannelDeleter setXTwilioWebhookEnabled(final Channel.WebhookEnabledType xTwilioWebhookEnabled) { this.xTwilioWebhookEnabled = xTwilioWebhookEnabled; return this; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/v2/Services/{ServiceSid}/Channels/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.IPMESSAGING.toString(), - path + HttpMethod.DELETE, + Domains.IPMESSAGING.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addHeaderParams(request); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Channel delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("Channel delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -84,11 +78,10 @@ public boolean delete(final TwilioRestClient client) { } private void addHeaderParams(final Request request) { + if (xTwilioWebhookEnabled != null) { - request.addHeaderParam( - "X-Twilio-Webhook-Enabled", - xTwilioWebhookEnabled.toString() - ); + Serializer.toString(request, "X-Twilio-Webhook-Enabled", xTwilioWebhookEnabled, ParameterType.HEADER); } + } } diff --git a/src/main/java/com/twilio/rest/ipmessaging/v2/service/ChannelFetcher.java b/src/main/java/com/twilio/rest/ipmessaging/v2/service/ChannelFetcher.java index 4058b5695d..b8f6ff0ca0 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v2/service/ChannelFetcher.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v2/service/ChannelFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.ipmessaging.v2.service; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,51 +26,44 @@ public class ChannelFetcher extends Fetcher { - private String pathServiceSid; - private String pathSid; + private String pathserviceSid; + private String pathsid; - public ChannelFetcher(final String pathServiceSid, final String pathSid) { - this.pathServiceSid = pathServiceSid; - this.pathSid = pathSid; + public ChannelFetcher(final String pathserviceSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathsid = pathsid; } + @Override public Channel fetch(final TwilioRestClient client) { + String path = "/v2/Services/{ServiceSid}/Channels/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.IPMESSAGING.toString(), - path + HttpMethod.GET, + Domains.IPMESSAGING.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Channel fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Channel fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Channel.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/ipmessaging/v2/service/ChannelReader.java b/src/main/java/com/twilio/rest/ipmessaging/v2/service/ChannelReader.java index fdb72d3d11..66e1883920 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v2/service/ChannelReader.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v2/service/ChannelReader.java @@ -17,8 +17,9 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; import com.twilio.converter.Promoter; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,18 +28,20 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.util.List; public class ChannelReader extends Reader { - private String pathServiceSid; + private String pathserviceSid; private List type; private Long pageSize; - public ChannelReader(final String pathServiceSid) { - this.pathServiceSid = pathServiceSid; + public ChannelReader(final String pathserviceSid) { + this.pathserviceSid = pathserviceSid; } + public ChannelReader setType(final List type) { this.type = type; return this; @@ -53,108 +56,82 @@ public ChannelReader setPageSize(final Long pageSize) { return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v2/Services/{ServiceSid}/Channels"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.IPMESSAGING.toString(), - path + HttpMethod.GET, + Domains.IPMESSAGING.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Channel read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Channel read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "channels", - response.getContent(), - Channel.class, - client.getObjectMapper() - ); + "channels", + response.getContent(), + Channel.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.IPMESSAGING.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.IPMESSAGING.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (type != null) { - for (Channel.ChannelType prop : type) { - request.addQueryParam("Type", prop.toString()); + for (Channel.ChannelType param : type) { + Serializer.toString(request, "Type", param, ParameterType.QUERY); } } + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/ipmessaging/v2/service/ChannelUpdater.java b/src/main/java/com/twilio/rest/ipmessaging/v2/service/ChannelUpdater.java index e5e40fc54c..ff9474d97e 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v2/service/ChannelUpdater.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v2/service/ChannelUpdater.java @@ -16,6 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -24,12 +26,12 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.time.ZonedDateTime; public class ChannelUpdater extends Updater { - - private String pathServiceSid; - private String pathSid; + private String pathserviceSid; + private String pathsid; private Channel.WebhookEnabledType xTwilioWebhookEnabled; private String friendlyName; private String uniqueName; @@ -38,82 +40,83 @@ public class ChannelUpdater extends Updater { private ZonedDateTime dateUpdated; private String createdBy; - public ChannelUpdater(final String pathServiceSid, final String pathSid) { - this.pathServiceSid = pathServiceSid; - this.pathSid = pathSid; + public ChannelUpdater(final String pathserviceSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathsid = pathsid; } - public ChannelUpdater setXTwilioWebhookEnabled( - final Channel.WebhookEnabledType xTwilioWebhookEnabled - ) { - this.xTwilioWebhookEnabled = xTwilioWebhookEnabled; - return this; - } public ChannelUpdater setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + public ChannelUpdater setUniqueName(final String uniqueName) { this.uniqueName = uniqueName; return this; } + public ChannelUpdater setAttributes(final String attributes) { this.attributes = attributes; return this; } + public ChannelUpdater setDateCreated(final ZonedDateTime dateCreated) { this.dateCreated = dateCreated; return this; } + public ChannelUpdater setDateUpdated(final ZonedDateTime dateUpdated) { this.dateUpdated = dateUpdated; return this; } + public ChannelUpdater setCreatedBy(final String createdBy) { this.createdBy = createdBy; return this; } + + public ChannelUpdater setXTwilioWebhookEnabled(final Channel.WebhookEnabledType xTwilioWebhookEnabled) { + this.xTwilioWebhookEnabled = xTwilioWebhookEnabled; + return this; + } + + @Override public Channel update(final TwilioRestClient client) { + String path = "/v2/Services/{ServiceSid}/Channels/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.IPMESSAGING.toString(), - path + HttpMethod.POST, + Domains.IPMESSAGING.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); - addPostParams(request); addHeaderParams(request); + addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Channel update failed: Unable to connect to server" - ); + throw new ApiConnectionException("Channel update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -122,38 +125,44 @@ public Channel update(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + if (uniqueName != null) { - request.addPostParam("UniqueName", uniqueName); + Serializer.toString(request, "UniqueName", uniqueName, ParameterType.URLENCODED); } + + if (attributes != null) { - request.addPostParam("Attributes", attributes); + Serializer.toString(request, "Attributes", attributes, ParameterType.URLENCODED); } + + if (dateCreated != null) { - request.addPostParam( - "DateCreated", - dateCreated.toInstant().toString() - ); + Serializer.toString(request, "DateCreated", dateCreated, ParameterType.URLENCODED); } + + if (dateUpdated != null) { - request.addPostParam( - "DateUpdated", - dateUpdated.toInstant().toString() - ); + Serializer.toString(request, "DateUpdated", dateUpdated, ParameterType.URLENCODED); } + + if (createdBy != null) { - request.addPostParam("CreatedBy", createdBy); + Serializer.toString(request, "CreatedBy", createdBy, ParameterType.URLENCODED); } + + } private void addHeaderParams(final Request request) { + if (xTwilioWebhookEnabled != null) { - request.addHeaderParam( - "X-Twilio-Webhook-Enabled", - xTwilioWebhookEnabled.toString() - ); + Serializer.toString(request, "X-Twilio-Webhook-Enabled", xTwilioWebhookEnabled, ParameterType.HEADER); } + } } diff --git a/src/main/java/com/twilio/rest/ipmessaging/v2/service/Role.java b/src/main/java/com/twilio/rest/ipmessaging/v2/service/Role.java index 3f44c5de6f..14f473814f 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v2/service/Role.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v2/service/Role.java @@ -18,74 +18,93 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.List; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Role extends Resource { - private static final long serialVersionUID = 252065084446046L; - public static RoleCreator creator( - final String pathServiceSid, - final String friendlyName, - final Role.RoleType type, - final List permission - ) { - return new RoleCreator(pathServiceSid, friendlyName, type, permission); + public static RoleCreator creator(final String pathserviceSid, final String friendlyName, final Role.RoleType type, final List permission) { + return new RoleCreator( + pathserviceSid, friendlyName, type, permission + ); } - public static RoleDeleter deleter( - final String pathServiceSid, - final String pathSid - ) { - return new RoleDeleter(pathServiceSid, pathSid); + + public static RoleDeleter deleter(final String pathserviceSid, final String pathsid) { + return new RoleDeleter( + pathserviceSid, pathsid + ); } - public static RoleFetcher fetcher( - final String pathServiceSid, - final String pathSid - ) { - return new RoleFetcher(pathServiceSid, pathSid); + + public static RoleFetcher fetcher(final String pathserviceSid, final String pathsid) { + return new RoleFetcher( + pathserviceSid, pathsid + ); + } + + + public static RoleReader reader(final String pathserviceSid) { + return new RoleReader( + pathserviceSid + ); } - public static RoleReader reader(final String pathServiceSid) { - return new RoleReader(pathServiceSid); + + public static RoleUpdater updater(final String pathserviceSid, final String pathsid, final List permission) { + return new RoleUpdater( + pathserviceSid, pathsid, permission + ); } - public static RoleUpdater updater( - final String pathServiceSid, - final String pathSid, - final List permission - ) { - return new RoleUpdater(pathServiceSid, pathSid, permission); + + public enum RoleType { + CHANNEL("channel"), + DEPLOYMENT("deployment"); + + private final String value; + + private RoleType(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static RoleType forValue(final String value) { + return Promoter.enumFromString(value, RoleType.values()); + } } + /** * Converts a JSON String into a Role object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Role object represented by the provided JSON */ - public static Role fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Role fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Role.class); @@ -100,14 +119,11 @@ public static Role fromJson( * Converts a JSON InputStream into a Role object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Role object represented by the provided JSON */ - public static Role fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Role fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Role.class); @@ -118,75 +134,63 @@ public static Role fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String serviceSid; - private final String friendlyName; - private final Role.RoleType type; - private final List permissions; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; + @Getter + private final String friendlyName; + @Getter + private final List permissions; + @Getter + private final String serviceSid; + @Getter + private final String sid; + @Getter + private final Role.RoleType type; + @Getter private final URI url; @JsonCreator private Role( - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("service_sid") final String serviceSid, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("type") final Role.RoleType type, - @JsonProperty("permissions") final List permissions, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("url") final URI url + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("permissions") final List permissions, + @JsonProperty("service_sid") final String serviceSid, + @JsonProperty("sid") final String sid, + @JsonProperty("type") final Role.RoleType type, + @JsonProperty("url") final URI url ) { - this.sid = sid; this.accountSid = accountSid; - this.serviceSid = serviceSid; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.friendlyName = friendlyName; - this.type = type; this.permissions = permissions; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); + this.serviceSid = serviceSid; + this.sid = sid; + this.type = type; this.url = url; } - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getServiceSid() { - return this.serviceSid; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final Role.RoleType getType() { - return this.type; - } - - public final List getPermissions() { - return this.permissions; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final URI getUrl() { - return this.url; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -198,52 +202,34 @@ public boolean equals(final Object o) { } Role other = (Role) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(serviceSid, other.serviceSid) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(type, other.type) && - Objects.equals(permissions, other.permissions) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(url, other.url) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(permissions, other.permissions) && + Objects.equals(serviceSid, other.serviceSid) && + Objects.equals(sid, other.sid) && + Objects.equals(type, other.type) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - sid, - accountSid, - serviceSid, - friendlyName, - type, - permissions, - dateCreated, - dateUpdated, - url + accountSid, + dateCreated, + dateUpdated, + friendlyName, + permissions, + serviceSid, + sid, + type, + url ); } - public enum RoleType { - CHANNEL("channel"), - DEPLOYMENT("deployment"); - - private final String value; - - private RoleType(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - @JsonCreator - public static RoleType forValue(final String value) { - return Promoter.enumFromString(value, RoleType.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/ipmessaging/v2/service/RoleCreator.java b/src/main/java/com/twilio/rest/ipmessaging/v2/service/RoleCreator.java index f837400361..273854a3bc 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v2/service/RoleCreator.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v2/service/RoleCreator.java @@ -14,9 +14,12 @@ package com.twilio.rest.ipmessaging.v2.service; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; import com.twilio.converter.Promoter; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,38 +28,36 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -import java.util.List; + import java.util.List; public class RoleCreator extends Creator { - private String pathServiceSid; + private String pathserviceSid; private String friendlyName; private Role.RoleType type; private List permission; - public RoleCreator( - final String pathServiceSid, - final String friendlyName, - final Role.RoleType type, - final List permission - ) { - this.pathServiceSid = pathServiceSid; + public RoleCreator(final String pathserviceSid, final String friendlyName, final Role.RoleType type, final List permission) { + this.pathserviceSid = pathserviceSid; this.friendlyName = friendlyName; this.type = type; this.permission = permission; } + public RoleCreator setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + public RoleCreator setType(final Role.RoleType type) { this.type = type; return this; } + public RoleCreator setPermission(final List permission) { this.permission = permission; return this; @@ -68,44 +69,31 @@ public RoleCreator setPermission(final String permission) { @Override public Role create(final TwilioRestClient client) { + String path = "/v2/Services/{ServiceSid}/Roles"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = - path.replace( - "{" + "FriendlyName" + "}", - this.friendlyName.toString() - ); - path = path.replace("{" + "Type" + "}", this.type.toString()); - path = - path.replace("{" + "Permission" + "}", this.permission.toString()); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.IPMESSAGING.toString(), - path + HttpMethod.POST, + Domains.IPMESSAGING.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Role creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("Role creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -114,16 +102,22 @@ public Role create(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + if (type != null) { - request.addPostParam("Type", type.toString()); + Serializer.toString(request, "Type", type, ParameterType.URLENCODED); } + + if (permission != null) { - for (String prop : permission) { - request.addPostParam("Permission", prop); + for (String param : permission) { + Serializer.toString(request, "Permission", param, ParameterType.URLENCODED); } } + } } diff --git a/src/main/java/com/twilio/rest/ipmessaging/v2/service/RoleDeleter.java b/src/main/java/com/twilio/rest/ipmessaging/v2/service/RoleDeleter.java index e44294002b..f40bd4a20d 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v2/service/RoleDeleter.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v2/service/RoleDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.ipmessaging.v2.service; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,47 +26,41 @@ public class RoleDeleter extends Deleter { - private String pathServiceSid; - private String pathSid; + private String pathserviceSid; + private String pathsid; - public RoleDeleter(final String pathServiceSid, final String pathSid) { - this.pathServiceSid = pathServiceSid; - this.pathSid = pathSid; + public RoleDeleter(final String pathserviceSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/v2/Services/{ServiceSid}/Roles/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.IPMESSAGING.toString(), - path + HttpMethod.DELETE, + Domains.IPMESSAGING.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Role delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("Role delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/ipmessaging/v2/service/RoleFetcher.java b/src/main/java/com/twilio/rest/ipmessaging/v2/service/RoleFetcher.java index 4dbec712ef..2cfbe59bbf 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v2/service/RoleFetcher.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v2/service/RoleFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.ipmessaging.v2.service; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,51 +26,44 @@ public class RoleFetcher extends Fetcher { - private String pathServiceSid; - private String pathSid; + private String pathserviceSid; + private String pathsid; - public RoleFetcher(final String pathServiceSid, final String pathSid) { - this.pathServiceSid = pathServiceSid; - this.pathSid = pathSid; + public RoleFetcher(final String pathserviceSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathsid = pathsid; } + @Override public Role fetch(final TwilioRestClient client) { + String path = "/v2/Services/{ServiceSid}/Roles/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.IPMESSAGING.toString(), - path + HttpMethod.GET, + Domains.IPMESSAGING.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Role fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Role fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Role.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/ipmessaging/v2/service/RoleReader.java b/src/main/java/com/twilio/rest/ipmessaging/v2/service/RoleReader.java index 817c1c0ad9..289184984a 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v2/service/RoleReader.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v2/service/RoleReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,115 +30,88 @@ public class RoleReader extends Reader { - private String pathServiceSid; + private String pathserviceSid; private Long pageSize; - public RoleReader(final String pathServiceSid) { - this.pathServiceSid = pathServiceSid; + public RoleReader(final String pathserviceSid) { + this.pathserviceSid = pathserviceSid; } + public RoleReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v2/Services/{ServiceSid}/Roles"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.IPMESSAGING.toString(), - path + HttpMethod.GET, + Domains.IPMESSAGING.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Role read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Role read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "roles", - response.getContent(), - Role.class, - client.getObjectMapper() - ); + "roles", + response.getContent(), + Role.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.IPMESSAGING.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.IPMESSAGING.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/ipmessaging/v2/service/RoleUpdater.java b/src/main/java/com/twilio/rest/ipmessaging/v2/service/RoleUpdater.java index 3f91c59de1..1967f6dc31 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v2/service/RoleUpdater.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v2/service/RoleUpdater.java @@ -16,7 +16,9 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; import com.twilio.converter.Promoter; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,24 +27,21 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.util.List; public class RoleUpdater extends Updater { - - private String pathServiceSid; - private String pathSid; + private String pathserviceSid; + private String pathsid; private List permission; - public RoleUpdater( - final String pathServiceSid, - final String pathSid, - final List permission - ) { - this.pathServiceSid = pathServiceSid; - this.pathSid = pathSid; + public RoleUpdater(final String pathserviceSid, final String pathsid, final List permission) { + this.pathserviceSid = pathserviceSid; + this.pathsid = pathsid; this.permission = permission; } + public RoleUpdater setPermission(final List permission) { this.permission = permission; return this; @@ -54,39 +53,32 @@ public RoleUpdater setPermission(final String permission) { @Override public Role update(final TwilioRestClient client) { + String path = "/v2/Services/{ServiceSid}/Roles/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); - path = - path.replace("{" + "Permission" + "}", this.permission.toString()); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.IPMESSAGING.toString(), - path + HttpMethod.POST, + Domains.IPMESSAGING.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Role update failed: Unable to connect to server" - ); + throw new ApiConnectionException("Role update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -95,10 +87,13 @@ public Role update(final TwilioRestClient client) { } private void addPostParams(final Request request) { + + if (permission != null) { - for (String prop : permission) { - request.addPostParam("Permission", prop); + for (String param : permission) { + Serializer.toString(request, "Permission", param, ParameterType.URLENCODED); } } + } } diff --git a/src/main/java/com/twilio/rest/ipmessaging/v2/service/User.java b/src/main/java/com/twilio/rest/ipmessaging/v2/service/User.java index 04650e5825..68e4ad7059 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v2/service/User.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v2/service/User.java @@ -18,72 +18,93 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class User extends Resource { - private static final long serialVersionUID = 136391609300437L; - public static UserCreator creator( - final String pathServiceSid, - final String identity - ) { - return new UserCreator(pathServiceSid, identity); + public static UserCreator creator(final String pathserviceSid, final String identity) { + return new UserCreator( + pathserviceSid, identity + ); } - public static UserDeleter deleter( - final String pathServiceSid, - final String pathSid - ) { - return new UserDeleter(pathServiceSid, pathSid); + + public static UserDeleter deleter(final String pathserviceSid, final String pathsid) { + return new UserDeleter( + pathserviceSid, pathsid + ); } - public static UserFetcher fetcher( - final String pathServiceSid, - final String pathSid - ) { - return new UserFetcher(pathServiceSid, pathSid); + + public static UserFetcher fetcher(final String pathserviceSid, final String pathsid) { + return new UserFetcher( + pathserviceSid, pathsid + ); + } + + + public static UserReader reader(final String pathserviceSid) { + return new UserReader( + pathserviceSid + ); } - public static UserReader reader(final String pathServiceSid) { - return new UserReader(pathServiceSid); + + public static UserUpdater updater(final String pathserviceSid, final String pathsid) { + return new UserUpdater( + pathserviceSid, pathsid + ); } - public static UserUpdater updater( - final String pathServiceSid, - final String pathSid - ) { - return new UserUpdater(pathServiceSid, pathSid); + + public enum WebhookEnabledType { + TRUE("true"), + FALSE("false"); + + private final String value; + + private WebhookEnabledType(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static WebhookEnabledType forValue(final String value) { + return Promoter.enumFromString(value, WebhookEnabledType.values()); + } } + /** * Converts a JSON String into a User object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return User object represented by the provided JSON */ - public static User fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static User fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, User.class); @@ -98,14 +119,11 @@ public static User fromJson( * Converts a JSON InputStream into a User object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return User object represented by the provided JSON */ - public static User fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static User fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, User.class); @@ -116,112 +134,83 @@ public static User fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String serviceSid; + @Getter private final String attributes; + @Getter + private final ZonedDateTime dateCreated; + @Getter + private final ZonedDateTime dateUpdated; + @Getter private final String friendlyName; - private final String roleSid; + @Getter private final String identity; - private final Boolean isOnline; + @Getter private final Boolean isNotifiable; - private final ZonedDateTime dateCreated; - private final ZonedDateTime dateUpdated; + @Getter + private final Boolean isOnline; + @Getter private final Integer joinedChannelsCount; + @Getter private final Map links; + @Getter + private final String roleSid; + @Getter + private final String serviceSid; + @Getter + private final String sid; + @Getter private final URI url; @JsonCreator private User( - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("service_sid") final String serviceSid, - @JsonProperty("attributes") final String attributes, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("role_sid") final String roleSid, - @JsonProperty("identity") final String identity, - @JsonProperty("is_online") final Boolean isOnline, - @JsonProperty("is_notifiable") final Boolean isNotifiable, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty( - "joined_channels_count" - ) final Integer joinedChannelsCount, - @JsonProperty("links") final Map links, - @JsonProperty("url") final URI url + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("attributes") final String attributes, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("identity") final String identity, + @JsonProperty("is_notifiable") final Boolean isNotifiable, + @JsonProperty("is_online") final Boolean isOnline, + @JsonProperty("joined_channels_count") final Integer joinedChannelsCount, + @JsonProperty("links") final Map links, + @JsonProperty("role_sid") final String roleSid, + @JsonProperty("service_sid") final String serviceSid, + @JsonProperty("sid") final String sid, + @JsonProperty("url") final URI url ) { - this.sid = sid; this.accountSid = accountSid; - this.serviceSid = serviceSid; this.attributes = attributes; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.friendlyName = friendlyName; - this.roleSid = roleSid; this.identity = identity; - this.isOnline = isOnline; this.isNotifiable = isNotifiable; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); + this.isOnline = isOnline; this.joinedChannelsCount = joinedChannelsCount; this.links = links; + this.roleSid = roleSid; + this.serviceSid = serviceSid; + this.sid = sid; this.url = url; } - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getServiceSid() { - return this.serviceSid; - } - - public final String getAttributes() { - return this.attributes; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final String getRoleSid() { - return this.roleSid; - } - - public final String getIdentity() { - return this.identity; - } - - public final Boolean getIsOnline() { - return this.isOnline; - } - - public final Boolean getIsNotifiable() { - return this.isNotifiable; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final Integer getJoinedChannelsCount() { - return this.joinedChannelsCount; - } - - public final Map getLinks() { - return this.links; - } - - public final URI getUrl() { - return this.url; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -233,62 +222,44 @@ public boolean equals(final Object o) { } User other = (User) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(serviceSid, other.serviceSid) && - Objects.equals(attributes, other.attributes) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(roleSid, other.roleSid) && - Objects.equals(identity, other.identity) && - Objects.equals(isOnline, other.isOnline) && - Objects.equals(isNotifiable, other.isNotifiable) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(joinedChannelsCount, other.joinedChannelsCount) && - Objects.equals(links, other.links) && - Objects.equals(url, other.url) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(attributes, other.attributes) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(identity, other.identity) && + Objects.equals(isNotifiable, other.isNotifiable) && + Objects.equals(isOnline, other.isOnline) && + Objects.equals(joinedChannelsCount, other.joinedChannelsCount) && + Objects.equals(links, other.links) && + Objects.equals(roleSid, other.roleSid) && + Objects.equals(serviceSid, other.serviceSid) && + Objects.equals(sid, other.sid) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - sid, - accountSid, - serviceSid, - attributes, - friendlyName, - roleSid, - identity, - isOnline, - isNotifiable, - dateCreated, - dateUpdated, - joinedChannelsCount, - links, - url + accountSid, + attributes, + dateCreated, + dateUpdated, + friendlyName, + identity, + isNotifiable, + isOnline, + joinedChannelsCount, + links, + roleSid, + serviceSid, + sid, + url ); } - public enum WebhookEnabledType { - TRUE("true"), - FALSE("false"); - - private final String value; - private WebhookEnabledType(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static WebhookEnabledType forValue(final String value) { - return Promoter.enumFromString(value, WebhookEnabledType.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/ipmessaging/v2/service/UserCreator.java b/src/main/java/com/twilio/rest/ipmessaging/v2/service/UserCreator.java index 667fdaae97..abf26214ca 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v2/service/UserCreator.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v2/service/UserCreator.java @@ -14,8 +14,11 @@ package com.twilio.rest.ipmessaging.v2.service; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,79 +30,77 @@ public class UserCreator extends Creator { - private String pathServiceSid; - private String identity; + private String pathserviceSid; private User.WebhookEnabledType xTwilioWebhookEnabled; + private String identity; private String roleSid; private String attributes; private String friendlyName; - public UserCreator(final String pathServiceSid, final String identity) { - this.pathServiceSid = pathServiceSid; + public UserCreator(final String pathserviceSid, final String identity) { + this.pathserviceSid = pathserviceSid; this.identity = identity; } + public UserCreator setIdentity(final String identity) { this.identity = identity; return this; } - public UserCreator setXTwilioWebhookEnabled( - final User.WebhookEnabledType xTwilioWebhookEnabled - ) { - this.xTwilioWebhookEnabled = xTwilioWebhookEnabled; - return this; - } public UserCreator setRoleSid(final String roleSid) { this.roleSid = roleSid; return this; } + public UserCreator setAttributes(final String attributes) { this.attributes = attributes; return this; } + public UserCreator setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + + public UserCreator setXTwilioWebhookEnabled(final User.WebhookEnabledType xTwilioWebhookEnabled) { + this.xTwilioWebhookEnabled = xTwilioWebhookEnabled; + return this; + } + + @Override public User create(final TwilioRestClient client) { + String path = "/v2/Services/{ServiceSid}/Users"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = path.replace("{" + "Identity" + "}", this.identity.toString()); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.IPMESSAGING.toString(), - path + HttpMethod.POST, + Domains.IPMESSAGING.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); - addPostParams(request); addHeaderParams(request); + addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "User creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("User creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -108,26 +109,34 @@ public User create(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (identity != null) { - request.addPostParam("Identity", identity); + Serializer.toString(request, "Identity", identity, ParameterType.URLENCODED); } + + if (roleSid != null) { - request.addPostParam("RoleSid", roleSid); + Serializer.toString(request, "RoleSid", roleSid, ParameterType.URLENCODED); } + + if (attributes != null) { - request.addPostParam("Attributes", attributes); + Serializer.toString(request, "Attributes", attributes, ParameterType.URLENCODED); } + + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + } private void addHeaderParams(final Request request) { + if (xTwilioWebhookEnabled != null) { - request.addHeaderParam( - "X-Twilio-Webhook-Enabled", - xTwilioWebhookEnabled.toString() - ); + Serializer.toString(request, "X-Twilio-Webhook-Enabled", xTwilioWebhookEnabled, ParameterType.HEADER); } + } } diff --git a/src/main/java/com/twilio/rest/ipmessaging/v2/service/UserDeleter.java b/src/main/java/com/twilio/rest/ipmessaging/v2/service/UserDeleter.java index 51767853cd..977212152f 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v2/service/UserDeleter.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v2/service/UserDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.ipmessaging.v2.service; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,47 +26,41 @@ public class UserDeleter extends Deleter { - private String pathServiceSid; - private String pathSid; + private String pathserviceSid; + private String pathsid; - public UserDeleter(final String pathServiceSid, final String pathSid) { - this.pathServiceSid = pathServiceSid; - this.pathSid = pathSid; + public UserDeleter(final String pathserviceSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/v2/Services/{ServiceSid}/Users/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.IPMESSAGING.toString(), - path + HttpMethod.DELETE, + Domains.IPMESSAGING.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "User delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("User delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/ipmessaging/v2/service/UserFetcher.java b/src/main/java/com/twilio/rest/ipmessaging/v2/service/UserFetcher.java index c0abd740c6..b1424ecc97 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v2/service/UserFetcher.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v2/service/UserFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.ipmessaging.v2.service; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,51 +26,44 @@ public class UserFetcher extends Fetcher { - private String pathServiceSid; - private String pathSid; + private String pathserviceSid; + private String pathsid; - public UserFetcher(final String pathServiceSid, final String pathSid) { - this.pathServiceSid = pathServiceSid; - this.pathSid = pathSid; + public UserFetcher(final String pathserviceSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathsid = pathsid; } + @Override public User fetch(final TwilioRestClient client) { + String path = "/v2/Services/{ServiceSid}/Users/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.IPMESSAGING.toString(), - path + HttpMethod.GET, + Domains.IPMESSAGING.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "User fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("User fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return User.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/ipmessaging/v2/service/UserReader.java b/src/main/java/com/twilio/rest/ipmessaging/v2/service/UserReader.java index 06bc848236..cf9be46427 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v2/service/UserReader.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v2/service/UserReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,115 +30,88 @@ public class UserReader extends Reader { - private String pathServiceSid; + private String pathserviceSid; private Long pageSize; - public UserReader(final String pathServiceSid) { - this.pathServiceSid = pathServiceSid; + public UserReader(final String pathserviceSid) { + this.pathserviceSid = pathserviceSid; } + public UserReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v2/Services/{ServiceSid}/Users"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.IPMESSAGING.toString(), - path + HttpMethod.GET, + Domains.IPMESSAGING.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "User read failed: Unable to connect to server" - ); + throw new ApiConnectionException("User read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "users", - response.getContent(), - User.class, - client.getObjectMapper() - ); + "users", + response.getContent(), + User.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.IPMESSAGING.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.IPMESSAGING.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/ipmessaging/v2/service/UserUpdater.java b/src/main/java/com/twilio/rest/ipmessaging/v2/service/UserUpdater.java index 56e65104cb..b56164d96e 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v2/service/UserUpdater.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v2/service/UserUpdater.java @@ -16,6 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -26,75 +28,72 @@ import com.twilio.rest.Domains; public class UserUpdater extends Updater { - - private String pathServiceSid; - private String pathSid; + private String pathserviceSid; + private String pathsid; private User.WebhookEnabledType xTwilioWebhookEnabled; private String roleSid; private String attributes; private String friendlyName; - public UserUpdater(final String pathServiceSid, final String pathSid) { - this.pathServiceSid = pathServiceSid; - this.pathSid = pathSid; + public UserUpdater(final String pathserviceSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathsid = pathsid; } - public UserUpdater setXTwilioWebhookEnabled( - final User.WebhookEnabledType xTwilioWebhookEnabled - ) { - this.xTwilioWebhookEnabled = xTwilioWebhookEnabled; - return this; - } public UserUpdater setRoleSid(final String roleSid) { this.roleSid = roleSid; return this; } + public UserUpdater setAttributes(final String attributes) { this.attributes = attributes; return this; } + public UserUpdater setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + + public UserUpdater setXTwilioWebhookEnabled(final User.WebhookEnabledType xTwilioWebhookEnabled) { + this.xTwilioWebhookEnabled = xTwilioWebhookEnabled; + return this; + } + + @Override public User update(final TwilioRestClient client) { + String path = "/v2/Services/{ServiceSid}/Users/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.IPMESSAGING.toString(), - path + HttpMethod.POST, + Domains.IPMESSAGING.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); - addPostParams(request); addHeaderParams(request); + addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "User update failed: Unable to connect to server" - ); + throw new ApiConnectionException("User update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -103,23 +102,29 @@ public User update(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (roleSid != null) { - request.addPostParam("RoleSid", roleSid); + Serializer.toString(request, "RoleSid", roleSid, ParameterType.URLENCODED); } + + if (attributes != null) { - request.addPostParam("Attributes", attributes); + Serializer.toString(request, "Attributes", attributes, ParameterType.URLENCODED); } + + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + } private void addHeaderParams(final Request request) { + if (xTwilioWebhookEnabled != null) { - request.addHeaderParam( - "X-Twilio-Webhook-Enabled", - xTwilioWebhookEnabled.toString() - ); + Serializer.toString(request, "X-Twilio-Webhook-Enabled", xTwilioWebhookEnabled, ParameterType.HEADER); } + } } diff --git a/src/main/java/com/twilio/rest/ipmessaging/v2/service/channel/Invite.java b/src/main/java/com/twilio/rest/ipmessaging/v2/service/channel/Invite.java index d9dfb25630..1df1e08d7b 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v2/service/channel/Invite.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v2/service/channel/Invite.java @@ -18,68 +18,63 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Invite extends Resource { - private static final long serialVersionUID = 148273166902210L; - public static InviteCreator creator( - final String pathServiceSid, - final String pathChannelSid, - final String identity - ) { - return new InviteCreator(pathServiceSid, pathChannelSid, identity); + public static InviteCreator creator(final String pathserviceSid, final String pathchannelSid, final String identity) { + return new InviteCreator( + pathserviceSid, pathchannelSid, identity + ); } - public static InviteDeleter deleter( - final String pathServiceSid, - final String pathChannelSid, - final String pathSid - ) { - return new InviteDeleter(pathServiceSid, pathChannelSid, pathSid); + + public static InviteDeleter deleter(final String pathserviceSid, final String pathchannelSid, final String pathsid) { + return new InviteDeleter( + pathserviceSid, pathchannelSid, pathsid + ); } - public static InviteFetcher fetcher( - final String pathServiceSid, - final String pathChannelSid, - final String pathSid - ) { - return new InviteFetcher(pathServiceSid, pathChannelSid, pathSid); + + public static InviteFetcher fetcher(final String pathserviceSid, final String pathchannelSid, final String pathsid) { + return new InviteFetcher( + pathserviceSid, pathchannelSid, pathsid + ); } - public static InviteReader reader( - final String pathServiceSid, - final String pathChannelSid - ) { - return new InviteReader(pathServiceSid, pathChannelSid); + + public static InviteReader reader(final String pathserviceSid, final String pathchannelSid) { + return new InviteReader( + pathserviceSid, pathchannelSid + ); } + /** * Converts a JSON String into a Invite object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Invite object represented by the provided JSON */ - public static Invite fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Invite fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Invite.class); @@ -94,14 +89,11 @@ public static Invite fromJson( * Converts a JSON InputStream into a Invite object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Invite object represented by the provided JSON */ - public static Invite fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Invite fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Invite.class); @@ -112,82 +104,67 @@ public static Invite fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; + @Getter private final String channelSid; - private final String serviceSid; - private final String identity; + @Getter + private final String createdBy; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; + @Getter + private final String identity; + @Getter private final String roleSid; - private final String createdBy; + @Getter + private final String serviceSid; + @Getter + private final String sid; + @Getter private final URI url; @JsonCreator private Invite( - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("channel_sid") final String channelSid, - @JsonProperty("service_sid") final String serviceSid, - @JsonProperty("identity") final String identity, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("role_sid") final String roleSid, - @JsonProperty("created_by") final String createdBy, - @JsonProperty("url") final URI url + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("channel_sid") final String channelSid, + @JsonProperty("created_by") final String createdBy, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("identity") final String identity, + @JsonProperty("role_sid") final String roleSid, + @JsonProperty("service_sid") final String serviceSid, + @JsonProperty("sid") final String sid, + @JsonProperty("url") final URI url ) { - this.sid = sid; this.accountSid = accountSid; this.channelSid = channelSid; - this.serviceSid = serviceSid; + this.createdBy = createdBy; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.identity = identity; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); this.roleSid = roleSid; - this.createdBy = createdBy; + this.serviceSid = serviceSid; + this.sid = sid; this.url = url; } - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getChannelSid() { - return this.channelSid; - } - - public final String getServiceSid() { - return this.serviceSid; - } - - public final String getIdentity() { - return this.identity; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final String getRoleSid() { - return this.roleSid; - } - - public final String getCreatedBy() { - return this.createdBy; - } - - public final URI getUrl() { - return this.url; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -199,34 +176,36 @@ public boolean equals(final Object o) { } Invite other = (Invite) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(channelSid, other.channelSid) && - Objects.equals(serviceSid, other.serviceSid) && - Objects.equals(identity, other.identity) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(roleSid, other.roleSid) && - Objects.equals(createdBy, other.createdBy) && - Objects.equals(url, other.url) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(channelSid, other.channelSid) && + Objects.equals(createdBy, other.createdBy) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(identity, other.identity) && + Objects.equals(roleSid, other.roleSid) && + Objects.equals(serviceSid, other.serviceSid) && + Objects.equals(sid, other.sid) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - sid, - accountSid, - channelSid, - serviceSid, - identity, - dateCreated, - dateUpdated, - roleSid, - createdBy, - url + accountSid, + channelSid, + createdBy, + dateCreated, + dateUpdated, + identity, + roleSid, + serviceSid, + sid, + url ); } + + } + diff --git a/src/main/java/com/twilio/rest/ipmessaging/v2/service/channel/InviteCreator.java b/src/main/java/com/twilio/rest/ipmessaging/v2/service/channel/InviteCreator.java index 40380320aa..4be2bbe5f2 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v2/service/channel/InviteCreator.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v2/service/channel/InviteCreator.java @@ -14,8 +14,11 @@ package com.twilio.rest.ipmessaging.v2.service.channel; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,69 +30,58 @@ public class InviteCreator extends Creator { - private String pathServiceSid; - private String pathChannelSid; + private String pathserviceSid; + private String pathchannelSid; private String identity; private String roleSid; - public InviteCreator( - final String pathServiceSid, - final String pathChannelSid, - final String identity - ) { - this.pathServiceSid = pathServiceSid; - this.pathChannelSid = pathChannelSid; + public InviteCreator(final String pathserviceSid, final String pathchannelSid, final String identity) { + this.pathserviceSid = pathserviceSid; + this.pathchannelSid = pathchannelSid; this.identity = identity; } + public InviteCreator setIdentity(final String identity) { this.identity = identity; return this; } + public InviteCreator setRoleSid(final String roleSid) { this.roleSid = roleSid; return this; } + @Override public Invite create(final TwilioRestClient client) { + String path = "/v2/Services/{ServiceSid}/Channels/{ChannelSid}/Invites"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = - path.replace( - "{" + "ChannelSid" + "}", - this.pathChannelSid.toString() - ); - path = path.replace("{" + "Identity" + "}", this.identity.toString()); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "ChannelSid" + "}", this.pathchannelSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.IPMESSAGING.toString(), - path + HttpMethod.POST, + Domains.IPMESSAGING.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Invite creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("Invite creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -98,11 +90,16 @@ public Invite create(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (identity != null) { - request.addPostParam("Identity", identity); + Serializer.toString(request, "Identity", identity, ParameterType.URLENCODED); } + + if (roleSid != null) { - request.addPostParam("RoleSid", roleSid); + Serializer.toString(request, "RoleSid", roleSid, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/ipmessaging/v2/service/channel/InviteDeleter.java b/src/main/java/com/twilio/rest/ipmessaging/v2/service/channel/InviteDeleter.java index 21a270739a..e445459b18 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v2/service/channel/InviteDeleter.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v2/service/channel/InviteDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.ipmessaging.v2.service.channel; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,59 +26,44 @@ public class InviteDeleter extends Deleter { - private String pathServiceSid; - private String pathChannelSid; - private String pathSid; + private String pathserviceSid; + private String pathchannelSid; + private String pathsid; - public InviteDeleter( - final String pathServiceSid, - final String pathChannelSid, - final String pathSid - ) { - this.pathServiceSid = pathServiceSid; - this.pathChannelSid = pathChannelSid; - this.pathSid = pathSid; + public InviteDeleter(final String pathserviceSid, final String pathchannelSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathchannelSid = pathchannelSid; + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { - String path = - "/v2/Services/{ServiceSid}/Channels/{ChannelSid}/Invites/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = - path.replace( - "{" + "ChannelSid" + "}", - this.pathChannelSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/v2/Services/{ServiceSid}/Channels/{ChannelSid}/Invites/{Sid}"; + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "ChannelSid" + "}", this.pathchannelSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.IPMESSAGING.toString(), - path + HttpMethod.DELETE, + Domains.IPMESSAGING.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Invite delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("Invite delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/ipmessaging/v2/service/channel/InviteFetcher.java b/src/main/java/com/twilio/rest/ipmessaging/v2/service/channel/InviteFetcher.java index 9920e15246..cd1c8a0831 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v2/service/channel/InviteFetcher.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v2/service/channel/InviteFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.ipmessaging.v2.service.channel; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,63 +26,47 @@ public class InviteFetcher extends Fetcher { - private String pathServiceSid; - private String pathChannelSid; - private String pathSid; + private String pathserviceSid; + private String pathchannelSid; + private String pathsid; - public InviteFetcher( - final String pathServiceSid, - final String pathChannelSid, - final String pathSid - ) { - this.pathServiceSid = pathServiceSid; - this.pathChannelSid = pathChannelSid; - this.pathSid = pathSid; + public InviteFetcher(final String pathserviceSid, final String pathchannelSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathchannelSid = pathchannelSid; + this.pathsid = pathsid; } + @Override public Invite fetch(final TwilioRestClient client) { - String path = - "/v2/Services/{ServiceSid}/Channels/{ChannelSid}/Invites/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = - path.replace( - "{" + "ChannelSid" + "}", - this.pathChannelSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/v2/Services/{ServiceSid}/Channels/{ChannelSid}/Invites/{Sid}"; + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "ChannelSid" + "}", this.pathchannelSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.IPMESSAGING.toString(), - path + HttpMethod.GET, + Domains.IPMESSAGING.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Invite fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Invite fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Invite.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/ipmessaging/v2/service/channel/InviteReader.java b/src/main/java/com/twilio/rest/ipmessaging/v2/service/channel/InviteReader.java index 75345668be..f86b2eef0c 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v2/service/channel/InviteReader.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v2/service/channel/InviteReader.java @@ -17,8 +17,9 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; import com.twilio.converter.Promoter; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,23 +28,22 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.util.List; public class InviteReader extends Reader { - private String pathServiceSid; - private String pathChannelSid; + private String pathserviceSid; + private String pathchannelSid; private List identity; private Long pageSize; - public InviteReader( - final String pathServiceSid, - final String pathChannelSid - ) { - this.pathServiceSid = pathServiceSid; - this.pathChannelSid = pathChannelSid; + public InviteReader(final String pathserviceSid, final String pathchannelSid) { + this.pathserviceSid = pathserviceSid; + this.pathchannelSid = pathchannelSid; } + public InviteReader setIdentity(final List identity) { this.identity = identity; return this; @@ -58,113 +58,83 @@ public InviteReader setPageSize(final Long pageSize) { return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v2/Services/{ServiceSid}/Channels/{ChannelSid}/Invites"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = - path.replace( - "{" + "ChannelSid" + "}", - this.pathChannelSid.toString() - ); + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "ChannelSid" + "}", this.pathchannelSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.IPMESSAGING.toString(), - path + HttpMethod.GET, + Domains.IPMESSAGING.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Invite read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Invite read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "invites", - response.getContent(), - Invite.class, - client.getObjectMapper() - ); + "invites", + response.getContent(), + Invite.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.IPMESSAGING.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.IPMESSAGING.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (identity != null) { - for (String prop : identity) { - request.addQueryParam("Identity", prop); + for (String param : identity) { + Serializer.toString(request, "Identity", param, ParameterType.QUERY); } } + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/ipmessaging/v2/service/channel/Member.java b/src/main/java/com/twilio/rest/ipmessaging/v2/service/channel/Member.java index b75e0e0fe5..7972e3ce19 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v2/service/channel/Member.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v2/service/channel/Member.java @@ -18,77 +18,92 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Member extends Resource { - private static final long serialVersionUID = 220317594144302L; - public static MemberCreator creator( - final String pathServiceSid, - final String pathChannelSid, - final String identity - ) { - return new MemberCreator(pathServiceSid, pathChannelSid, identity); + public static MemberCreator creator(final String pathserviceSid, final String pathchannelSid, final String identity) { + return new MemberCreator( + pathserviceSid, pathchannelSid, identity + ); } - public static MemberDeleter deleter( - final String pathServiceSid, - final String pathChannelSid, - final String pathSid - ) { - return new MemberDeleter(pathServiceSid, pathChannelSid, pathSid); + + public static MemberDeleter deleter(final String pathserviceSid, final String pathchannelSid, final String pathsid) { + return new MemberDeleter( + pathserviceSid, pathchannelSid, pathsid + ); } - public static MemberFetcher fetcher( - final String pathServiceSid, - final String pathChannelSid, - final String pathSid - ) { - return new MemberFetcher(pathServiceSid, pathChannelSid, pathSid); + + public static MemberFetcher fetcher(final String pathserviceSid, final String pathchannelSid, final String pathsid) { + return new MemberFetcher( + pathserviceSid, pathchannelSid, pathsid + ); } - public static MemberReader reader( - final String pathServiceSid, - final String pathChannelSid - ) { - return new MemberReader(pathServiceSid, pathChannelSid); + + public static MemberReader reader(final String pathserviceSid, final String pathchannelSid) { + return new MemberReader( + pathserviceSid, pathchannelSid + ); } - public static MemberUpdater updater( - final String pathServiceSid, - final String pathChannelSid, - final String pathSid - ) { - return new MemberUpdater(pathServiceSid, pathChannelSid, pathSid); + + public static MemberUpdater updater(final String pathserviceSid, final String pathchannelSid, final String pathsid) { + return new MemberUpdater( + pathserviceSid, pathchannelSid, pathsid + ); } + + public enum WebhookEnabledType { + TRUE("true"), + FALSE("false"); + + private final String value; + + private WebhookEnabledType(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static WebhookEnabledType forValue(final String value) { + return Promoter.enumFromString(value, WebhookEnabledType.values()); + } + } + + /** * Converts a JSON String into a Member object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Member object represented by the provided JSON */ - public static Member fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Member fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Member.class); @@ -103,14 +118,11 @@ public static Member fromJson( * Converts a JSON InputStream into a Member object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Member object represented by the provided JSON */ - public static Member fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Member fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Member.class); @@ -121,99 +133,74 @@ public static Member fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; + @Getter + private final String attributes; + @Getter private final String channelSid; - private final String serviceSid; - private final String identity; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; - private final String roleSid; + @Getter + private final String identity; + @Getter private final Integer lastConsumedMessageIndex; + @Getter private final ZonedDateTime lastConsumptionTimestamp; + @Getter + private final String roleSid; + @Getter + private final String serviceSid; + @Getter + private final String sid; + @Getter private final URI url; - private final String attributes; @JsonCreator private Member( - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("channel_sid") final String channelSid, - @JsonProperty("service_sid") final String serviceSid, - @JsonProperty("identity") final String identity, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("role_sid") final String roleSid, - @JsonProperty( - "last_consumed_message_index" - ) final Integer lastConsumedMessageIndex, - @JsonProperty( - "last_consumption_timestamp" - ) final String lastConsumptionTimestamp, - @JsonProperty("url") final URI url, - @JsonProperty("attributes") final String attributes + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("attributes") final String attributes, + @JsonProperty("channel_sid") final String channelSid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("identity") final String identity, + @JsonProperty("last_consumed_message_index") final Integer lastConsumedMessageIndex, + @JsonProperty("last_consumption_timestamp") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime lastConsumptionTimestamp, + @JsonProperty("role_sid") final String roleSid, + @JsonProperty("service_sid") final String serviceSid, + @JsonProperty("sid") final String sid, + @JsonProperty("url") final URI url ) { - this.sid = sid; this.accountSid = accountSid; + this.attributes = attributes; this.channelSid = channelSid; - this.serviceSid = serviceSid; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.identity = identity; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); - this.roleSid = roleSid; this.lastConsumedMessageIndex = lastConsumedMessageIndex; - this.lastConsumptionTimestamp = - DateConverter.iso8601DateTimeFromString(lastConsumptionTimestamp); + this.lastConsumptionTimestamp = lastConsumptionTimestamp; + this.roleSid = roleSid; + this.serviceSid = serviceSid; + this.sid = sid; this.url = url; - this.attributes = attributes; - } - - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getChannelSid() { - return this.channelSid; - } - - public final String getServiceSid() { - return this.serviceSid; - } - - public final String getIdentity() { - return this.identity; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final String getRoleSid() { - return this.roleSid; - } - - public final Integer getLastConsumedMessageIndex() { - return this.lastConsumedMessageIndex; - } - - public final ZonedDateTime getLastConsumptionTimestamp() { - return this.lastConsumptionTimestamp; - } - - public final URI getUrl() { - return this.url; - } - - public final String getAttributes() { - return this.attributes; } @Override @@ -227,64 +214,40 @@ public boolean equals(final Object o) { } Member other = (Member) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(channelSid, other.channelSid) && - Objects.equals(serviceSid, other.serviceSid) && - Objects.equals(identity, other.identity) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(roleSid, other.roleSid) && - Objects.equals( - lastConsumedMessageIndex, - other.lastConsumedMessageIndex - ) && - Objects.equals( - lastConsumptionTimestamp, - other.lastConsumptionTimestamp - ) && - Objects.equals(url, other.url) && - Objects.equals(attributes, other.attributes) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(attributes, other.attributes) && + Objects.equals(channelSid, other.channelSid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(identity, other.identity) && + Objects.equals(lastConsumedMessageIndex, other.lastConsumedMessageIndex) && + Objects.equals(lastConsumptionTimestamp, other.lastConsumptionTimestamp) && + Objects.equals(roleSid, other.roleSid) && + Objects.equals(serviceSid, other.serviceSid) && + Objects.equals(sid, other.sid) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - sid, - accountSid, - channelSid, - serviceSid, - identity, - dateCreated, - dateUpdated, - roleSid, - lastConsumedMessageIndex, - lastConsumptionTimestamp, - url, - attributes + accountSid, + attributes, + channelSid, + dateCreated, + dateUpdated, + identity, + lastConsumedMessageIndex, + lastConsumptionTimestamp, + roleSid, + serviceSid, + sid, + url ); } - public enum WebhookEnabledType { - TRUE("true"), - FALSE("false"); - - private final String value; - private WebhookEnabledType(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static WebhookEnabledType forValue(final String value) { - return Promoter.enumFromString(value, WebhookEnabledType.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/ipmessaging/v2/service/channel/MemberCreator.java b/src/main/java/com/twilio/rest/ipmessaging/v2/service/channel/MemberCreator.java index 08faab3d83..73471784e7 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v2/service/channel/MemberCreator.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v2/service/channel/MemberCreator.java @@ -14,8 +14,11 @@ package com.twilio.rest.ipmessaging.v2.service.channel; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -24,14 +27,15 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.time.ZonedDateTime; public class MemberCreator extends Creator { - private String pathServiceSid; - private String pathChannelSid; - private String identity; + private String pathserviceSid; + private String pathchannelSid; private Member.WebhookEnabledType xTwilioWebhookEnabled; + private String identity; private String roleSid; private Integer lastConsumedMessageIndex; private ZonedDateTime lastConsumptionTimestamp; @@ -39,101 +43,90 @@ public class MemberCreator extends Creator { private ZonedDateTime dateUpdated; private String attributes; - public MemberCreator( - final String pathServiceSid, - final String pathChannelSid, - final String identity - ) { - this.pathServiceSid = pathServiceSid; - this.pathChannelSid = pathChannelSid; + public MemberCreator(final String pathserviceSid, final String pathchannelSid, final String identity) { + this.pathserviceSid = pathserviceSid; + this.pathchannelSid = pathchannelSid; this.identity = identity; } + public MemberCreator setIdentity(final String identity) { this.identity = identity; return this; } - public MemberCreator setXTwilioWebhookEnabled( - final Member.WebhookEnabledType xTwilioWebhookEnabled - ) { - this.xTwilioWebhookEnabled = xTwilioWebhookEnabled; - return this; - } public MemberCreator setRoleSid(final String roleSid) { this.roleSid = roleSid; return this; } - public MemberCreator setLastConsumedMessageIndex( - final Integer lastConsumedMessageIndex - ) { + + public MemberCreator setLastConsumedMessageIndex(final Integer lastConsumedMessageIndex) { this.lastConsumedMessageIndex = lastConsumedMessageIndex; return this; } - public MemberCreator setLastConsumptionTimestamp( - final ZonedDateTime lastConsumptionTimestamp - ) { + + public MemberCreator setLastConsumptionTimestamp(final ZonedDateTime lastConsumptionTimestamp) { this.lastConsumptionTimestamp = lastConsumptionTimestamp; return this; } + public MemberCreator setDateCreated(final ZonedDateTime dateCreated) { this.dateCreated = dateCreated; return this; } + public MemberCreator setDateUpdated(final ZonedDateTime dateUpdated) { this.dateUpdated = dateUpdated; return this; } + public MemberCreator setAttributes(final String attributes) { this.attributes = attributes; return this; } + + public MemberCreator setXTwilioWebhookEnabled(final Member.WebhookEnabledType xTwilioWebhookEnabled) { + this.xTwilioWebhookEnabled = xTwilioWebhookEnabled; + return this; + } + + @Override public Member create(final TwilioRestClient client) { + String path = "/v2/Services/{ServiceSid}/Channels/{ChannelSid}/Members"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = - path.replace( - "{" + "ChannelSid" + "}", - this.pathChannelSid.toString() - ); - path = path.replace("{" + "Identity" + "}", this.identity.toString()); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "ChannelSid" + "}", this.pathchannelSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.IPMESSAGING.toString(), - path + HttpMethod.POST, + Domains.IPMESSAGING.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); - addPostParams(request); addHeaderParams(request); + addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Member creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("Member creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -142,47 +135,49 @@ public Member create(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (identity != null) { - request.addPostParam("Identity", identity); + Serializer.toString(request, "Identity", identity, ParameterType.URLENCODED); } + + if (roleSid != null) { - request.addPostParam("RoleSid", roleSid); + Serializer.toString(request, "RoleSid", roleSid, ParameterType.URLENCODED); } + + if (lastConsumedMessageIndex != null) { - request.addPostParam( - "LastConsumedMessageIndex", - lastConsumedMessageIndex.toString() - ); + Serializer.toString(request, "LastConsumedMessageIndex", lastConsumedMessageIndex, ParameterType.URLENCODED); } + + if (lastConsumptionTimestamp != null) { - request.addPostParam( - "LastConsumptionTimestamp", - lastConsumptionTimestamp.toInstant().toString() - ); + Serializer.toString(request, "LastConsumptionTimestamp", lastConsumptionTimestamp, ParameterType.URLENCODED); } + + if (dateCreated != null) { - request.addPostParam( - "DateCreated", - dateCreated.toInstant().toString() - ); + Serializer.toString(request, "DateCreated", dateCreated, ParameterType.URLENCODED); } + + if (dateUpdated != null) { - request.addPostParam( - "DateUpdated", - dateUpdated.toInstant().toString() - ); + Serializer.toString(request, "DateUpdated", dateUpdated, ParameterType.URLENCODED); } + + if (attributes != null) { - request.addPostParam("Attributes", attributes); + Serializer.toString(request, "Attributes", attributes, ParameterType.URLENCODED); } + + } private void addHeaderParams(final Request request) { + if (xTwilioWebhookEnabled != null) { - request.addHeaderParam( - "X-Twilio-Webhook-Enabled", - xTwilioWebhookEnabled.toString() - ); + Serializer.toString(request, "X-Twilio-Webhook-Enabled", xTwilioWebhookEnabled, ParameterType.HEADER); } + } } diff --git a/src/main/java/com/twilio/rest/ipmessaging/v2/service/channel/MemberDeleter.java b/src/main/java/com/twilio/rest/ipmessaging/v2/service/channel/MemberDeleter.java index 77d07e1537..31ad3597b8 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v2/service/channel/MemberDeleter.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v2/service/channel/MemberDeleter.java @@ -15,7 +15,8 @@ package com.twilio.rest.ipmessaging.v2.service.channel; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,68 +28,52 @@ public class MemberDeleter extends Deleter { - private String pathServiceSid; - private String pathChannelSid; - private String pathSid; + private String pathserviceSid; + private String pathchannelSid; + private String pathsid; private Member.WebhookEnabledType xTwilioWebhookEnabled; - public MemberDeleter( - final String pathServiceSid, - final String pathChannelSid, - final String pathSid - ) { - this.pathServiceSid = pathServiceSid; - this.pathChannelSid = pathChannelSid; - this.pathSid = pathSid; + public MemberDeleter(final String pathserviceSid, final String pathchannelSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathchannelSid = pathchannelSid; + this.pathsid = pathsid; } - public MemberDeleter setXTwilioWebhookEnabled( - final Member.WebhookEnabledType xTwilioWebhookEnabled - ) { + + public MemberDeleter setXTwilioWebhookEnabled(final Member.WebhookEnabledType xTwilioWebhookEnabled) { this.xTwilioWebhookEnabled = xTwilioWebhookEnabled; return this; } + @Override public boolean delete(final TwilioRestClient client) { - String path = - "/v2/Services/{ServiceSid}/Channels/{ChannelSid}/Members/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = - path.replace( - "{" + "ChannelSid" + "}", - this.pathChannelSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/v2/Services/{ServiceSid}/Channels/{ChannelSid}/Members/{Sid}"; + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "ChannelSid" + "}", this.pathchannelSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.IPMESSAGING.toString(), - path + HttpMethod.DELETE, + Domains.IPMESSAGING.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addHeaderParams(request); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Member delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("Member delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -96,11 +81,10 @@ public boolean delete(final TwilioRestClient client) { } private void addHeaderParams(final Request request) { + if (xTwilioWebhookEnabled != null) { - request.addHeaderParam( - "X-Twilio-Webhook-Enabled", - xTwilioWebhookEnabled.toString() - ); + Serializer.toString(request, "X-Twilio-Webhook-Enabled", xTwilioWebhookEnabled, ParameterType.HEADER); } + } } diff --git a/src/main/java/com/twilio/rest/ipmessaging/v2/service/channel/MemberFetcher.java b/src/main/java/com/twilio/rest/ipmessaging/v2/service/channel/MemberFetcher.java index bc53086a7b..8a40c14d09 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v2/service/channel/MemberFetcher.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v2/service/channel/MemberFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.ipmessaging.v2.service.channel; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,63 +26,47 @@ public class MemberFetcher extends Fetcher { - private String pathServiceSid; - private String pathChannelSid; - private String pathSid; + private String pathserviceSid; + private String pathchannelSid; + private String pathsid; - public MemberFetcher( - final String pathServiceSid, - final String pathChannelSid, - final String pathSid - ) { - this.pathServiceSid = pathServiceSid; - this.pathChannelSid = pathChannelSid; - this.pathSid = pathSid; + public MemberFetcher(final String pathserviceSid, final String pathchannelSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathchannelSid = pathchannelSid; + this.pathsid = pathsid; } + @Override public Member fetch(final TwilioRestClient client) { - String path = - "/v2/Services/{ServiceSid}/Channels/{ChannelSid}/Members/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = - path.replace( - "{" + "ChannelSid" + "}", - this.pathChannelSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/v2/Services/{ServiceSid}/Channels/{ChannelSid}/Members/{Sid}"; + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "ChannelSid" + "}", this.pathchannelSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.IPMESSAGING.toString(), - path + HttpMethod.GET, + Domains.IPMESSAGING.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Member fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Member fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Member.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/ipmessaging/v2/service/channel/MemberReader.java b/src/main/java/com/twilio/rest/ipmessaging/v2/service/channel/MemberReader.java index 4593252c3b..8cea93f439 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v2/service/channel/MemberReader.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v2/service/channel/MemberReader.java @@ -17,8 +17,9 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; import com.twilio.converter.Promoter; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,23 +28,22 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.util.List; public class MemberReader extends Reader { - private String pathServiceSid; - private String pathChannelSid; + private String pathserviceSid; + private String pathchannelSid; private List identity; private Long pageSize; - public MemberReader( - final String pathServiceSid, - final String pathChannelSid - ) { - this.pathServiceSid = pathServiceSid; - this.pathChannelSid = pathChannelSid; + public MemberReader(final String pathserviceSid, final String pathchannelSid) { + this.pathserviceSid = pathserviceSid; + this.pathchannelSid = pathchannelSid; } + public MemberReader setIdentity(final List identity) { this.identity = identity; return this; @@ -58,113 +58,83 @@ public MemberReader setPageSize(final Long pageSize) { return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v2/Services/{ServiceSid}/Channels/{ChannelSid}/Members"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = - path.replace( - "{" + "ChannelSid" + "}", - this.pathChannelSid.toString() - ); + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "ChannelSid" + "}", this.pathchannelSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.IPMESSAGING.toString(), - path + HttpMethod.GET, + Domains.IPMESSAGING.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Member read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Member read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "members", - response.getContent(), - Member.class, - client.getObjectMapper() - ); + "members", + response.getContent(), + Member.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.IPMESSAGING.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.IPMESSAGING.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (identity != null) { - for (String prop : identity) { - request.addQueryParam("Identity", prop); + for (String param : identity) { + Serializer.toString(request, "Identity", param, ParameterType.QUERY); } } + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/ipmessaging/v2/service/channel/MemberUpdater.java b/src/main/java/com/twilio/rest/ipmessaging/v2/service/channel/MemberUpdater.java index 9f7bc0ece2..cc5bab3432 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v2/service/channel/MemberUpdater.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v2/service/channel/MemberUpdater.java @@ -16,6 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -24,13 +26,13 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.time.ZonedDateTime; public class MemberUpdater extends Updater { - - private String pathServiceSid; - private String pathChannelSid; - private String pathSid; + private String pathserviceSid; + private String pathchannelSid; + private String pathsid; private Member.WebhookEnabledType xTwilioWebhookEnabled; private String roleSid; private Integer lastConsumedMessageIndex; @@ -39,97 +41,85 @@ public class MemberUpdater extends Updater { private ZonedDateTime dateUpdated; private String attributes; - public MemberUpdater( - final String pathServiceSid, - final String pathChannelSid, - final String pathSid - ) { - this.pathServiceSid = pathServiceSid; - this.pathChannelSid = pathChannelSid; - this.pathSid = pathSid; + public MemberUpdater(final String pathserviceSid, final String pathchannelSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathchannelSid = pathchannelSid; + this.pathsid = pathsid; } - public MemberUpdater setXTwilioWebhookEnabled( - final Member.WebhookEnabledType xTwilioWebhookEnabled - ) { - this.xTwilioWebhookEnabled = xTwilioWebhookEnabled; - return this; - } public MemberUpdater setRoleSid(final String roleSid) { this.roleSid = roleSid; return this; } - public MemberUpdater setLastConsumedMessageIndex( - final Integer lastConsumedMessageIndex - ) { + + public MemberUpdater setLastConsumedMessageIndex(final Integer lastConsumedMessageIndex) { this.lastConsumedMessageIndex = lastConsumedMessageIndex; return this; } - public MemberUpdater setLastConsumptionTimestamp( - final ZonedDateTime lastConsumptionTimestamp - ) { + + public MemberUpdater setLastConsumptionTimestamp(final ZonedDateTime lastConsumptionTimestamp) { this.lastConsumptionTimestamp = lastConsumptionTimestamp; return this; } + public MemberUpdater setDateCreated(final ZonedDateTime dateCreated) { this.dateCreated = dateCreated; return this; } + public MemberUpdater setDateUpdated(final ZonedDateTime dateUpdated) { this.dateUpdated = dateUpdated; return this; } + public MemberUpdater setAttributes(final String attributes) { this.attributes = attributes; return this; } + + public MemberUpdater setXTwilioWebhookEnabled(final Member.WebhookEnabledType xTwilioWebhookEnabled) { + this.xTwilioWebhookEnabled = xTwilioWebhookEnabled; + return this; + } + + @Override public Member update(final TwilioRestClient client) { - String path = - "/v2/Services/{ServiceSid}/Channels/{ChannelSid}/Members/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = - path.replace( - "{" + "ChannelSid" + "}", - this.pathChannelSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/v2/Services/{ServiceSid}/Channels/{ChannelSid}/Members/{Sid}"; + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "ChannelSid" + "}", this.pathchannelSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.IPMESSAGING.toString(), - path + HttpMethod.POST, + Domains.IPMESSAGING.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); - addPostParams(request); addHeaderParams(request); + addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Member update failed: Unable to connect to server" - ); + throw new ApiConnectionException("Member update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -138,44 +128,44 @@ public Member update(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (roleSid != null) { - request.addPostParam("RoleSid", roleSid); + Serializer.toString(request, "RoleSid", roleSid, ParameterType.URLENCODED); } + + if (lastConsumedMessageIndex != null) { - request.addPostParam( - "LastConsumedMessageIndex", - lastConsumedMessageIndex.toString() - ); + Serializer.toString(request, "LastConsumedMessageIndex", lastConsumedMessageIndex, ParameterType.URLENCODED); } + + if (lastConsumptionTimestamp != null) { - request.addPostParam( - "LastConsumptionTimestamp", - lastConsumptionTimestamp.toInstant().toString() - ); + Serializer.toString(request, "LastConsumptionTimestamp", lastConsumptionTimestamp, ParameterType.URLENCODED); } + + if (dateCreated != null) { - request.addPostParam( - "DateCreated", - dateCreated.toInstant().toString() - ); + Serializer.toString(request, "DateCreated", dateCreated, ParameterType.URLENCODED); } + + if (dateUpdated != null) { - request.addPostParam( - "DateUpdated", - dateUpdated.toInstant().toString() - ); + Serializer.toString(request, "DateUpdated", dateUpdated, ParameterType.URLENCODED); } + + if (attributes != null) { - request.addPostParam("Attributes", attributes); + Serializer.toString(request, "Attributes", attributes, ParameterType.URLENCODED); } + + } private void addHeaderParams(final Request request) { + if (xTwilioWebhookEnabled != null) { - request.addHeaderParam( - "X-Twilio-Webhook-Enabled", - xTwilioWebhookEnabled.toString() - ); + Serializer.toString(request, "X-Twilio-Webhook-Enabled", xTwilioWebhookEnabled, ParameterType.HEADER); } + } } diff --git a/src/main/java/com/twilio/rest/ipmessaging/v2/service/channel/Message.java b/src/main/java/com/twilio/rest/ipmessaging/v2/service/channel/Message.java index 79f44cd1b7..15b2a09cee 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v2/service/channel/Message.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v2/service/channel/Message.java @@ -18,78 +18,112 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; -import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Message extends Resource { - private static final long serialVersionUID = 210901647084119L; - public static MessageCreator creator( - final String pathServiceSid, - final String pathChannelSid - ) { - return new MessageCreator(pathServiceSid, pathChannelSid); + public static MessageCreator creator(final String pathserviceSid, final String pathchannelSid) { + return new MessageCreator( + pathserviceSid, pathchannelSid + ); } - public static MessageDeleter deleter( - final String pathServiceSid, - final String pathChannelSid, - final String pathSid - ) { - return new MessageDeleter(pathServiceSid, pathChannelSid, pathSid); + + public static MessageDeleter deleter(final String pathserviceSid, final String pathchannelSid, final String pathsid) { + return new MessageDeleter( + pathserviceSid, pathchannelSid, pathsid + ); } - public static MessageFetcher fetcher( - final String pathServiceSid, - final String pathChannelSid, - final String pathSid - ) { - return new MessageFetcher(pathServiceSid, pathChannelSid, pathSid); + + public static MessageFetcher fetcher(final String pathserviceSid, final String pathchannelSid, final String pathsid) { + return new MessageFetcher( + pathserviceSid, pathchannelSid, pathsid + ); } - public static MessageReader reader( - final String pathServiceSid, - final String pathChannelSid - ) { - return new MessageReader(pathServiceSid, pathChannelSid); + + public static MessageReader reader(final String pathserviceSid, final String pathchannelSid) { + return new MessageReader( + pathserviceSid, pathchannelSid + ); } - public static MessageUpdater updater( - final String pathServiceSid, - final String pathChannelSid, - final String pathSid - ) { - return new MessageUpdater(pathServiceSid, pathChannelSid, pathSid); + + public static MessageUpdater updater(final String pathserviceSid, final String pathchannelSid, final String pathsid) { + return new MessageUpdater( + pathserviceSid, pathchannelSid, pathsid + ); } + + public enum WebhookEnabledType { + TRUE("true"), + FALSE("false"); + + private final String value; + + private WebhookEnabledType(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static WebhookEnabledType forValue(final String value) { + return Promoter.enumFromString(value, WebhookEnabledType.values()); + } + } + + public enum OrderType { + ASC("asc"), + DESC("desc"); + + private final String value; + + private OrderType(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static OrderType forValue(final String value) { + return Promoter.enumFromString(value, OrderType.values()); + } + } + + /** * Converts a JSON String into a Message object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Message object represented by the provided JSON */ - public static Message fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Message fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Message.class); @@ -104,14 +138,11 @@ public static Message fromJson( * Converts a JSON InputStream into a Message object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Message object represented by the provided JSON */ - public static Message fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Message fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Message.class); @@ -122,122 +153,89 @@ public static Message fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; + @Getter private final String attributes; - private final String serviceSid; - private final String to; + @Getter + private final String body; + @Getter private final String channelSid; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; - private final String lastUpdatedBy; - private final Boolean wasEdited; + @Getter private final String from; - private final String body; + @Getter private final Integer index; + @Getter + private final String lastUpdatedBy; + @Getter + private final Object media; + @Getter + private final String serviceSid; + @Getter + private final String sid; + @Getter + private final String to; + @Getter private final String type; - private final Map media; + @Getter private final URI url; + @Getter + private final Boolean wasEdited; @JsonCreator private Message( - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("attributes") final String attributes, - @JsonProperty("service_sid") final String serviceSid, - @JsonProperty("to") final String to, - @JsonProperty("channel_sid") final String channelSid, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("last_updated_by") final String lastUpdatedBy, - @JsonProperty("was_edited") final Boolean wasEdited, - @JsonProperty("from") final String from, - @JsonProperty("body") final String body, - @JsonProperty("index") final Integer index, - @JsonProperty("type") final String type, - @JsonProperty("media") final Map media, - @JsonProperty("url") final URI url + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("attributes") final String attributes, + @JsonProperty("body") final String body, + @JsonProperty("channel_sid") final String channelSid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("from") final String from, + @JsonProperty("index") final Integer index, + @JsonProperty("last_updated_by") final String lastUpdatedBy, + @JsonProperty("media") final Object media, + @JsonProperty("service_sid") final String serviceSid, + @JsonProperty("sid") final String sid, + @JsonProperty("to") final String to, + @JsonProperty("type") final String type, + @JsonProperty("url") final URI url, + @JsonProperty("was_edited") final Boolean wasEdited ) { - this.sid = sid; this.accountSid = accountSid; this.attributes = attributes; - this.serviceSid = serviceSid; - this.to = to; + this.body = body; this.channelSid = channelSid; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); - this.lastUpdatedBy = lastUpdatedBy; - this.wasEdited = wasEdited; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.from = from; - this.body = body; this.index = index; - this.type = type; + this.lastUpdatedBy = lastUpdatedBy; this.media = media; + this.serviceSid = serviceSid; + this.sid = sid; + this.to = to; + this.type = type; this.url = url; - } - - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getAttributes() { - return this.attributes; - } - - public final String getServiceSid() { - return this.serviceSid; - } - - public final String getTo() { - return this.to; - } - - public final String getChannelSid() { - return this.channelSid; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final String getLastUpdatedBy() { - return this.lastUpdatedBy; - } - - public final Boolean getWasEdited() { - return this.wasEdited; - } - - public final String getFrom() { - return this.from; - } - - public final String getBody() { - return this.body; - } - - public final Integer getIndex() { - return this.index; - } - - public final String getType() { - return this.type; - } - - public final Map getMedia() { - return this.media; - } - - public final URI getUrl() { - return this.url; + this.wasEdited = wasEdited; } @Override @@ -251,86 +249,48 @@ public boolean equals(final Object o) { } Message other = (Message) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(attributes, other.attributes) && - Objects.equals(serviceSid, other.serviceSid) && - Objects.equals(to, other.to) && - Objects.equals(channelSid, other.channelSid) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(lastUpdatedBy, other.lastUpdatedBy) && - Objects.equals(wasEdited, other.wasEdited) && - Objects.equals(from, other.from) && - Objects.equals(body, other.body) && - Objects.equals(index, other.index) && - Objects.equals(type, other.type) && - Objects.equals(media, other.media) && - Objects.equals(url, other.url) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(attributes, other.attributes) && + Objects.equals(body, other.body) && + Objects.equals(channelSid, other.channelSid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(from, other.from) && + Objects.equals(index, other.index) && + Objects.equals(lastUpdatedBy, other.lastUpdatedBy) && + Objects.equals(media, other.media) && + Objects.equals(serviceSid, other.serviceSid) && + Objects.equals(sid, other.sid) && + Objects.equals(to, other.to) && + Objects.equals(type, other.type) && + Objects.equals(url, other.url) && + Objects.equals(wasEdited, other.wasEdited) ); } @Override public int hashCode() { return Objects.hash( - sid, - accountSid, - attributes, - serviceSid, - to, - channelSid, - dateCreated, - dateUpdated, - lastUpdatedBy, - wasEdited, - from, - body, - index, - type, - media, - url + accountSid, + attributes, + body, + channelSid, + dateCreated, + dateUpdated, + from, + index, + lastUpdatedBy, + media, + serviceSid, + sid, + to, + type, + url, + wasEdited ); } - public enum WebhookEnabledType { - TRUE("true"), - FALSE("false"); - - private final String value; - - private WebhookEnabledType(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static WebhookEnabledType forValue(final String value) { - return Promoter.enumFromString(value, WebhookEnabledType.values()); - } - } - - public enum OrderType { - ASC("asc"), - DESC("desc"); - - private final String value; - - private OrderType(final String value) { - this.value = value; - } - public String toString() { - return value; - } - - @JsonCreator - public static OrderType forValue(final String value) { - return Promoter.enumFromString(value, OrderType.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/ipmessaging/v2/service/channel/MessageCreator.java b/src/main/java/com/twilio/rest/ipmessaging/v2/service/channel/MessageCreator.java index e749a6c842..680b0e7f13 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v2/service/channel/MessageCreator.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v2/service/channel/MessageCreator.java @@ -14,8 +14,11 @@ package com.twilio.rest.ipmessaging.v2.service.channel; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -24,12 +27,13 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.time.ZonedDateTime; public class MessageCreator extends Creator { - private String pathServiceSid; - private String pathChannelSid; + private String pathserviceSid; + private String pathchannelSid; private Message.WebhookEnabledType xTwilioWebhookEnabled; private String from; private String attributes; @@ -39,95 +43,89 @@ public class MessageCreator extends Creator { private String body; private String mediaSid; - public MessageCreator( - final String pathServiceSid, - final String pathChannelSid - ) { - this.pathServiceSid = pathServiceSid; - this.pathChannelSid = pathChannelSid; + public MessageCreator(final String pathserviceSid, final String pathchannelSid) { + this.pathserviceSid = pathserviceSid; + this.pathchannelSid = pathchannelSid; } - public MessageCreator setXTwilioWebhookEnabled( - final Message.WebhookEnabledType xTwilioWebhookEnabled - ) { - this.xTwilioWebhookEnabled = xTwilioWebhookEnabled; - return this; - } public MessageCreator setFrom(final String from) { this.from = from; return this; } + public MessageCreator setAttributes(final String attributes) { this.attributes = attributes; return this; } + public MessageCreator setDateCreated(final ZonedDateTime dateCreated) { this.dateCreated = dateCreated; return this; } + public MessageCreator setDateUpdated(final ZonedDateTime dateUpdated) { this.dateUpdated = dateUpdated; return this; } + public MessageCreator setLastUpdatedBy(final String lastUpdatedBy) { this.lastUpdatedBy = lastUpdatedBy; return this; } + public MessageCreator setBody(final String body) { this.body = body; return this; } + public MessageCreator setMediaSid(final String mediaSid) { this.mediaSid = mediaSid; return this; } + + public MessageCreator setXTwilioWebhookEnabled(final Message.WebhookEnabledType xTwilioWebhookEnabled) { + this.xTwilioWebhookEnabled = xTwilioWebhookEnabled; + return this; + } + + @Override public Message create(final TwilioRestClient client) { - String path = - "/v2/Services/{ServiceSid}/Channels/{ChannelSid}/Messages"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = - path.replace( - "{" + "ChannelSid" + "}", - this.pathChannelSid.toString() - ); + String path = "/v2/Services/{ServiceSid}/Channels/{ChannelSid}/Messages"; + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "ChannelSid" + "}", this.pathchannelSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.IPMESSAGING.toString(), - path + HttpMethod.POST, + Domains.IPMESSAGING.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); - addPostParams(request); addHeaderParams(request); + addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Message creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("Message creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -136,41 +134,49 @@ public Message create(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (from != null) { - request.addPostParam("From", from); + Serializer.toString(request, "From", from, ParameterType.URLENCODED); } + + if (attributes != null) { - request.addPostParam("Attributes", attributes); + Serializer.toString(request, "Attributes", attributes, ParameterType.URLENCODED); } + + if (dateCreated != null) { - request.addPostParam( - "DateCreated", - dateCreated.toInstant().toString() - ); + Serializer.toString(request, "DateCreated", dateCreated, ParameterType.URLENCODED); } + + if (dateUpdated != null) { - request.addPostParam( - "DateUpdated", - dateUpdated.toInstant().toString() - ); + Serializer.toString(request, "DateUpdated", dateUpdated, ParameterType.URLENCODED); } + + if (lastUpdatedBy != null) { - request.addPostParam("LastUpdatedBy", lastUpdatedBy); + Serializer.toString(request, "LastUpdatedBy", lastUpdatedBy, ParameterType.URLENCODED); } + + if (body != null) { - request.addPostParam("Body", body); + Serializer.toString(request, "Body", body, ParameterType.URLENCODED); } + + if (mediaSid != null) { - request.addPostParam("MediaSid", mediaSid); + Serializer.toString(request, "MediaSid", mediaSid, ParameterType.URLENCODED); } + + } private void addHeaderParams(final Request request) { + if (xTwilioWebhookEnabled != null) { - request.addHeaderParam( - "X-Twilio-Webhook-Enabled", - xTwilioWebhookEnabled.toString() - ); + Serializer.toString(request, "X-Twilio-Webhook-Enabled", xTwilioWebhookEnabled, ParameterType.HEADER); } + } } diff --git a/src/main/java/com/twilio/rest/ipmessaging/v2/service/channel/MessageDeleter.java b/src/main/java/com/twilio/rest/ipmessaging/v2/service/channel/MessageDeleter.java index 9fb152954c..1481326071 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v2/service/channel/MessageDeleter.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v2/service/channel/MessageDeleter.java @@ -15,7 +15,8 @@ package com.twilio.rest.ipmessaging.v2.service.channel; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,68 +28,52 @@ public class MessageDeleter extends Deleter { - private String pathServiceSid; - private String pathChannelSid; - private String pathSid; + private String pathserviceSid; + private String pathchannelSid; + private String pathsid; private Message.WebhookEnabledType xTwilioWebhookEnabled; - public MessageDeleter( - final String pathServiceSid, - final String pathChannelSid, - final String pathSid - ) { - this.pathServiceSid = pathServiceSid; - this.pathChannelSid = pathChannelSid; - this.pathSid = pathSid; + public MessageDeleter(final String pathserviceSid, final String pathchannelSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathchannelSid = pathchannelSid; + this.pathsid = pathsid; } - public MessageDeleter setXTwilioWebhookEnabled( - final Message.WebhookEnabledType xTwilioWebhookEnabled - ) { + + public MessageDeleter setXTwilioWebhookEnabled(final Message.WebhookEnabledType xTwilioWebhookEnabled) { this.xTwilioWebhookEnabled = xTwilioWebhookEnabled; return this; } + @Override public boolean delete(final TwilioRestClient client) { - String path = - "/v2/Services/{ServiceSid}/Channels/{ChannelSid}/Messages/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = - path.replace( - "{" + "ChannelSid" + "}", - this.pathChannelSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/v2/Services/{ServiceSid}/Channels/{ChannelSid}/Messages/{Sid}"; + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "ChannelSid" + "}", this.pathchannelSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.IPMESSAGING.toString(), - path + HttpMethod.DELETE, + Domains.IPMESSAGING.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addHeaderParams(request); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Message delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("Message delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -96,11 +81,10 @@ public boolean delete(final TwilioRestClient client) { } private void addHeaderParams(final Request request) { + if (xTwilioWebhookEnabled != null) { - request.addHeaderParam( - "X-Twilio-Webhook-Enabled", - xTwilioWebhookEnabled.toString() - ); + Serializer.toString(request, "X-Twilio-Webhook-Enabled", xTwilioWebhookEnabled, ParameterType.HEADER); } + } } diff --git a/src/main/java/com/twilio/rest/ipmessaging/v2/service/channel/MessageFetcher.java b/src/main/java/com/twilio/rest/ipmessaging/v2/service/channel/MessageFetcher.java index 14d43f743f..16fae789d5 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v2/service/channel/MessageFetcher.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v2/service/channel/MessageFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.ipmessaging.v2.service.channel; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,63 +26,47 @@ public class MessageFetcher extends Fetcher { - private String pathServiceSid; - private String pathChannelSid; - private String pathSid; + private String pathserviceSid; + private String pathchannelSid; + private String pathsid; - public MessageFetcher( - final String pathServiceSid, - final String pathChannelSid, - final String pathSid - ) { - this.pathServiceSid = pathServiceSid; - this.pathChannelSid = pathChannelSid; - this.pathSid = pathSid; + public MessageFetcher(final String pathserviceSid, final String pathchannelSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathchannelSid = pathchannelSid; + this.pathsid = pathsid; } + @Override public Message fetch(final TwilioRestClient client) { - String path = - "/v2/Services/{ServiceSid}/Channels/{ChannelSid}/Messages/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = - path.replace( - "{" + "ChannelSid" + "}", - this.pathChannelSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/v2/Services/{ServiceSid}/Channels/{ChannelSid}/Messages/{Sid}"; + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "ChannelSid" + "}", this.pathchannelSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.IPMESSAGING.toString(), - path + HttpMethod.GET, + Domains.IPMESSAGING.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Message fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Message fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Message.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/ipmessaging/v2/service/channel/MessageReader.java b/src/main/java/com/twilio/rest/ipmessaging/v2/service/channel/MessageReader.java index 8d5d344c89..6c4006a975 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v2/service/channel/MessageReader.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v2/service/channel/MessageReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,135 +30,103 @@ public class MessageReader extends Reader { - private String pathServiceSid; - private String pathChannelSid; + private String pathserviceSid; + private String pathchannelSid; private Message.OrderType order; private Long pageSize; - public MessageReader( - final String pathServiceSid, - final String pathChannelSid - ) { - this.pathServiceSid = pathServiceSid; - this.pathChannelSid = pathChannelSid; + public MessageReader(final String pathserviceSid, final String pathchannelSid) { + this.pathserviceSid = pathserviceSid; + this.pathchannelSid = pathchannelSid; } + public MessageReader setOrder(final Message.OrderType order) { this.order = order; return this; } + public MessageReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { - String path = - "/v2/Services/{ServiceSid}/Channels/{ChannelSid}/Messages"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = - path.replace( - "{" + "ChannelSid" + "}", - this.pathChannelSid.toString() - ); + + String path = "/v2/Services/{ServiceSid}/Channels/{ChannelSid}/Messages"; + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "ChannelSid" + "}", this.pathchannelSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.IPMESSAGING.toString(), - path + HttpMethod.GET, + Domains.IPMESSAGING.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Message read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Message read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "messages", - response.getContent(), - Message.class, - client.getObjectMapper() - ); + "messages", + response.getContent(), + Message.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.IPMESSAGING.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.IPMESSAGING.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (order != null) { - request.addQueryParam("Order", order.toString()); + Serializer.toString(request, "Order", order, ParameterType.QUERY); } + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/ipmessaging/v2/service/channel/MessageUpdater.java b/src/main/java/com/twilio/rest/ipmessaging/v2/service/channel/MessageUpdater.java index 2d8f195a52..4ef5b237c6 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v2/service/channel/MessageUpdater.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v2/service/channel/MessageUpdater.java @@ -16,6 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -24,13 +26,13 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.time.ZonedDateTime; public class MessageUpdater extends Updater { - - private String pathServiceSid; - private String pathChannelSid; - private String pathSid; + private String pathserviceSid; + private String pathchannelSid; + private String pathsid; private Message.WebhookEnabledType xTwilioWebhookEnabled; private String body; private String attributes; @@ -39,93 +41,85 @@ public class MessageUpdater extends Updater { private String lastUpdatedBy; private String from; - public MessageUpdater( - final String pathServiceSid, - final String pathChannelSid, - final String pathSid - ) { - this.pathServiceSid = pathServiceSid; - this.pathChannelSid = pathChannelSid; - this.pathSid = pathSid; + public MessageUpdater(final String pathserviceSid, final String pathchannelSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathchannelSid = pathchannelSid; + this.pathsid = pathsid; } - public MessageUpdater setXTwilioWebhookEnabled( - final Message.WebhookEnabledType xTwilioWebhookEnabled - ) { - this.xTwilioWebhookEnabled = xTwilioWebhookEnabled; - return this; - } public MessageUpdater setBody(final String body) { this.body = body; return this; } + public MessageUpdater setAttributes(final String attributes) { this.attributes = attributes; return this; } + public MessageUpdater setDateCreated(final ZonedDateTime dateCreated) { this.dateCreated = dateCreated; return this; } + public MessageUpdater setDateUpdated(final ZonedDateTime dateUpdated) { this.dateUpdated = dateUpdated; return this; } + public MessageUpdater setLastUpdatedBy(final String lastUpdatedBy) { this.lastUpdatedBy = lastUpdatedBy; return this; } + public MessageUpdater setFrom(final String from) { this.from = from; return this; } + + public MessageUpdater setXTwilioWebhookEnabled(final Message.WebhookEnabledType xTwilioWebhookEnabled) { + this.xTwilioWebhookEnabled = xTwilioWebhookEnabled; + return this; + } + + @Override public Message update(final TwilioRestClient client) { - String path = - "/v2/Services/{ServiceSid}/Channels/{ChannelSid}/Messages/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = - path.replace( - "{" + "ChannelSid" + "}", - this.pathChannelSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/v2/Services/{ServiceSid}/Channels/{ChannelSid}/Messages/{Sid}"; + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "ChannelSid" + "}", this.pathchannelSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.IPMESSAGING.toString(), - path + HttpMethod.POST, + Domains.IPMESSAGING.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); - addPostParams(request); addHeaderParams(request); + addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Message update failed: Unable to connect to server" - ); + throw new ApiConnectionException("Message update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -134,38 +128,44 @@ public Message update(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (body != null) { - request.addPostParam("Body", body); + Serializer.toString(request, "Body", body, ParameterType.URLENCODED); } + + if (attributes != null) { - request.addPostParam("Attributes", attributes); + Serializer.toString(request, "Attributes", attributes, ParameterType.URLENCODED); } + + if (dateCreated != null) { - request.addPostParam( - "DateCreated", - dateCreated.toInstant().toString() - ); + Serializer.toString(request, "DateCreated", dateCreated, ParameterType.URLENCODED); } + + if (dateUpdated != null) { - request.addPostParam( - "DateUpdated", - dateUpdated.toInstant().toString() - ); + Serializer.toString(request, "DateUpdated", dateUpdated, ParameterType.URLENCODED); } + + if (lastUpdatedBy != null) { - request.addPostParam("LastUpdatedBy", lastUpdatedBy); + Serializer.toString(request, "LastUpdatedBy", lastUpdatedBy, ParameterType.URLENCODED); } + + if (from != null) { - request.addPostParam("From", from); + Serializer.toString(request, "From", from, ParameterType.URLENCODED); } + + } private void addHeaderParams(final Request request) { + if (xTwilioWebhookEnabled != null) { - request.addHeaderParam( - "X-Twilio-Webhook-Enabled", - xTwilioWebhookEnabled.toString() - ); + Serializer.toString(request, "X-Twilio-Webhook-Enabled", xTwilioWebhookEnabled, ParameterType.HEADER); } + } } diff --git a/src/main/java/com/twilio/rest/ipmessaging/v2/service/channel/Webhook.java b/src/main/java/com/twilio/rest/ipmessaging/v2/service/channel/Webhook.java index e4202e4268..5b776b4b8f 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v2/service/channel/Webhook.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v2/service/channel/Webhook.java @@ -18,79 +18,113 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; -import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Webhook extends Resource { - private static final long serialVersionUID = 201752828404640L; - public static WebhookCreator creator( - final String pathServiceSid, - final String pathChannelSid, - final Webhook.Type type - ) { - return new WebhookCreator(pathServiceSid, pathChannelSid, type); + public static WebhookCreator creator(final String pathserviceSid, final String pathchannelSid, final Webhook.Type type) { + return new WebhookCreator( + pathserviceSid, pathchannelSid, type + ); } - public static WebhookDeleter deleter( - final String pathServiceSid, - final String pathChannelSid, - final String pathSid - ) { - return new WebhookDeleter(pathServiceSid, pathChannelSid, pathSid); + + public static WebhookDeleter deleter(final String pathserviceSid, final String pathchannelSid, final String pathsid) { + return new WebhookDeleter( + pathserviceSid, pathchannelSid, pathsid + ); } - public static WebhookFetcher fetcher( - final String pathServiceSid, - final String pathChannelSid, - final String pathSid - ) { - return new WebhookFetcher(pathServiceSid, pathChannelSid, pathSid); + + public static WebhookFetcher fetcher(final String pathserviceSid, final String pathchannelSid, final String pathsid) { + return new WebhookFetcher( + pathserviceSid, pathchannelSid, pathsid + ); } - public static WebhookReader reader( - final String pathServiceSid, - final String pathChannelSid - ) { - return new WebhookReader(pathServiceSid, pathChannelSid); + + public static WebhookReader reader(final String pathserviceSid, final String pathchannelSid) { + return new WebhookReader( + pathserviceSid, pathchannelSid + ); } - public static WebhookUpdater updater( - final String pathServiceSid, - final String pathChannelSid, - final String pathSid - ) { - return new WebhookUpdater(pathServiceSid, pathChannelSid, pathSid); + + public static WebhookUpdater updater(final String pathserviceSid, final String pathchannelSid, final String pathsid) { + return new WebhookUpdater( + pathserviceSid, pathchannelSid, pathsid + ); } + + public enum Type { + WEBHOOK("webhook"), + TRIGGER("trigger"), + STUDIO("studio"); + + private final String value; + + private Type(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static Type forValue(final String value) { + return Promoter.enumFromString(value, Type.values()); + } + } + + public enum Method { + GET("GET"), + POST("POST"); + + private final String value; + + private Method(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static Method forValue(final String value) { + return Promoter.enumFromString(value, Method.values()); + } + } + + /** * Converts a JSON String into a Webhook object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Webhook object represented by the provided JSON */ - public static Webhook fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Webhook fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Webhook.class); @@ -105,14 +139,11 @@ public static Webhook fromJson( * Converts a JSON InputStream into a Webhook object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Webhook object represented by the provided JSON */ - public static Webhook fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Webhook fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Webhook.class); @@ -123,73 +154,61 @@ public static Webhook fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String serviceSid; + @Getter private final String channelSid; - private final String type; - private final URI url; - private final Map configuration; + @Getter + private final Object configuration; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; + @Getter + private final String serviceSid; + @Getter + private final String sid; + @Getter + private final String type; + @Getter + private final URI url; @JsonCreator private Webhook( - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("service_sid") final String serviceSid, - @JsonProperty("channel_sid") final String channelSid, - @JsonProperty("type") final String type, - @JsonProperty("url") final URI url, - @JsonProperty("configuration") final Map configuration, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("channel_sid") final String channelSid, + @JsonProperty("configuration") final Object configuration, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("service_sid") final String serviceSid, + @JsonProperty("sid") final String sid, + @JsonProperty("type") final String type, + @JsonProperty("url") final URI url ) { - this.sid = sid; this.accountSid = accountSid; - this.serviceSid = serviceSid; this.channelSid = channelSid; + this.configuration = configuration; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; + this.serviceSid = serviceSid; + this.sid = sid; this.type = type; this.url = url; - this.configuration = configuration; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); - } - - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getServiceSid() { - return this.serviceSid; - } - - public final String getChannelSid() { - return this.channelSid; - } - - public final String getType() { - return this.type; - } - - public final URI getUrl() { - return this.url; - } - - public final Map getConfiguration() { - return this.configuration; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; } @Override @@ -203,73 +222,34 @@ public boolean equals(final Object o) { } Webhook other = (Webhook) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(serviceSid, other.serviceSid) && - Objects.equals(channelSid, other.channelSid) && - Objects.equals(type, other.type) && - Objects.equals(url, other.url) && - Objects.equals(configuration, other.configuration) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(channelSid, other.channelSid) && + Objects.equals(configuration, other.configuration) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(serviceSid, other.serviceSid) && + Objects.equals(sid, other.sid) && + Objects.equals(type, other.type) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - sid, - accountSid, - serviceSid, - channelSid, - type, - url, - configuration, - dateCreated, - dateUpdated + accountSid, + channelSid, + configuration, + dateCreated, + dateUpdated, + serviceSid, + sid, + type, + url ); } - public enum Type { - WEBHOOK("webhook"), - TRIGGER("trigger"), - STUDIO("studio"); - - private final String value; - - private Type(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static Type forValue(final String value) { - return Promoter.enumFromString(value, Type.values()); - } - } - - public enum Method { - GET("GET"), - POST("POST"); - - private final String value; - - private Method(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - @JsonCreator - public static Method forValue(final String value) { - return Promoter.enumFromString(value, Method.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/ipmessaging/v2/service/channel/WebhookCreator.java b/src/main/java/com/twilio/rest/ipmessaging/v2/service/channel/WebhookCreator.java index 4e9943a212..d3ec989976 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v2/service/channel/WebhookCreator.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v2/service/channel/WebhookCreator.java @@ -14,9 +14,12 @@ package com.twilio.rest.ipmessaging.v2.service.channel; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; import com.twilio.converter.Promoter; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,13 +28,13 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -import java.util.List; + import java.util.List; public class WebhookCreator extends Creator { - private String pathServiceSid; - private String pathChannelSid; + private String pathserviceSid; + private String pathchannelSid; private Webhook.Type type; private String configurationUrl; private Webhook.Method configurationMethod; @@ -40,116 +43,89 @@ public class WebhookCreator extends Creator { private String configurationFlowSid; private Integer configurationRetryCount; - public WebhookCreator( - final String pathServiceSid, - final String pathChannelSid, - final Webhook.Type type - ) { - this.pathServiceSid = pathServiceSid; - this.pathChannelSid = pathChannelSid; + public WebhookCreator(final String pathserviceSid, final String pathchannelSid, final Webhook.Type type) { + this.pathserviceSid = pathserviceSid; + this.pathchannelSid = pathchannelSid; this.type = type; } + public WebhookCreator setType(final Webhook.Type type) { this.type = type; return this; } + public WebhookCreator setConfigurationUrl(final String configurationUrl) { this.configurationUrl = configurationUrl; return this; } - public WebhookCreator setConfigurationMethod( - final Webhook.Method configurationMethod - ) { + + public WebhookCreator setConfigurationMethod(final Webhook.Method configurationMethod) { this.configurationMethod = configurationMethod; return this; } - public WebhookCreator setConfigurationFilters( - final List configurationFilters - ) { + + public WebhookCreator setConfigurationFilters(final List configurationFilters) { this.configurationFilters = configurationFilters; return this; } - public WebhookCreator setConfigurationFilters( - final String configurationFilters - ) { - return setConfigurationFilters( - Promoter.listOfOne(configurationFilters) - ); + public WebhookCreator setConfigurationFilters(final String configurationFilters) { + return setConfigurationFilters(Promoter.listOfOne(configurationFilters)); } - public WebhookCreator setConfigurationTriggers( - final List configurationTriggers - ) { + public WebhookCreator setConfigurationTriggers(final List configurationTriggers) { this.configurationTriggers = configurationTriggers; return this; } - public WebhookCreator setConfigurationTriggers( - final String configurationTriggers - ) { - return setConfigurationTriggers( - Promoter.listOfOne(configurationTriggers) - ); + public WebhookCreator setConfigurationTriggers(final String configurationTriggers) { + return setConfigurationTriggers(Promoter.listOfOne(configurationTriggers)); } - public WebhookCreator setConfigurationFlowSid( - final String configurationFlowSid - ) { + public WebhookCreator setConfigurationFlowSid(final String configurationFlowSid) { this.configurationFlowSid = configurationFlowSid; return this; } - public WebhookCreator setConfigurationRetryCount( - final Integer configurationRetryCount - ) { + + public WebhookCreator setConfigurationRetryCount(final Integer configurationRetryCount) { this.configurationRetryCount = configurationRetryCount; return this; } + @Override public Webhook create(final TwilioRestClient client) { - String path = - "/v2/Services/{ServiceSid}/Channels/{ChannelSid}/Webhooks"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = - path.replace( - "{" + "ChannelSid" + "}", - this.pathChannelSid.toString() - ); - path = path.replace("{" + "Type" + "}", this.type.toString()); + String path = "/v2/Services/{ServiceSid}/Channels/{ChannelSid}/Webhooks"; + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "ChannelSid" + "}", this.pathchannelSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.IPMESSAGING.toString(), - path + HttpMethod.POST, + Domains.IPMESSAGING.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Webhook creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("Webhook creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -158,36 +134,45 @@ public Webhook create(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (type != null) { - request.addPostParam("Type", type.toString()); + Serializer.toString(request, "Type", type, ParameterType.URLENCODED); } + + if (configurationUrl != null) { - request.addPostParam("Configuration.Url", configurationUrl); + Serializer.toString(request, "Configuration.Url", configurationUrl, ParameterType.URLENCODED); } + + if (configurationMethod != null) { - request.addPostParam( - "Configuration.Method", - configurationMethod.toString() - ); + Serializer.toString(request, "Configuration.Method", configurationMethod, ParameterType.URLENCODED); } + + if (configurationFilters != null) { - for (String prop : configurationFilters) { - request.addPostParam("Configuration.Filters", prop); + for (String param : configurationFilters) { + Serializer.toString(request, "Configuration.Filters", param, ParameterType.URLENCODED); } } + + if (configurationTriggers != null) { - for (String prop : configurationTriggers) { - request.addPostParam("Configuration.Triggers", prop); + for (String param : configurationTriggers) { + Serializer.toString(request, "Configuration.Triggers", param, ParameterType.URLENCODED); } } + + if (configurationFlowSid != null) { - request.addPostParam("Configuration.FlowSid", configurationFlowSid); + Serializer.toString(request, "Configuration.FlowSid", configurationFlowSid, ParameterType.URLENCODED); } + + if (configurationRetryCount != null) { - request.addPostParam( - "Configuration.RetryCount", - configurationRetryCount.toString() - ); + Serializer.toString(request, "Configuration.RetryCount", configurationRetryCount, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/ipmessaging/v2/service/channel/WebhookDeleter.java b/src/main/java/com/twilio/rest/ipmessaging/v2/service/channel/WebhookDeleter.java index 3e4903649b..1b8c195c68 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v2/service/channel/WebhookDeleter.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v2/service/channel/WebhookDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.ipmessaging.v2.service.channel; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,59 +26,44 @@ public class WebhookDeleter extends Deleter { - private String pathServiceSid; - private String pathChannelSid; - private String pathSid; + private String pathserviceSid; + private String pathchannelSid; + private String pathsid; - public WebhookDeleter( - final String pathServiceSid, - final String pathChannelSid, - final String pathSid - ) { - this.pathServiceSid = pathServiceSid; - this.pathChannelSid = pathChannelSid; - this.pathSid = pathSid; + public WebhookDeleter(final String pathserviceSid, final String pathchannelSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathchannelSid = pathchannelSid; + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { - String path = - "/v2/Services/{ServiceSid}/Channels/{ChannelSid}/Webhooks/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = - path.replace( - "{" + "ChannelSid" + "}", - this.pathChannelSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/v2/Services/{ServiceSid}/Channels/{ChannelSid}/Webhooks/{Sid}"; + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "ChannelSid" + "}", this.pathchannelSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.IPMESSAGING.toString(), - path + HttpMethod.DELETE, + Domains.IPMESSAGING.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Webhook delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("Webhook delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/ipmessaging/v2/service/channel/WebhookFetcher.java b/src/main/java/com/twilio/rest/ipmessaging/v2/service/channel/WebhookFetcher.java index 6a7e6b08db..e61e17b941 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v2/service/channel/WebhookFetcher.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v2/service/channel/WebhookFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.ipmessaging.v2.service.channel; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,63 +26,47 @@ public class WebhookFetcher extends Fetcher { - private String pathServiceSid; - private String pathChannelSid; - private String pathSid; + private String pathserviceSid; + private String pathchannelSid; + private String pathsid; - public WebhookFetcher( - final String pathServiceSid, - final String pathChannelSid, - final String pathSid - ) { - this.pathServiceSid = pathServiceSid; - this.pathChannelSid = pathChannelSid; - this.pathSid = pathSid; + public WebhookFetcher(final String pathserviceSid, final String pathchannelSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathchannelSid = pathchannelSid; + this.pathsid = pathsid; } + @Override public Webhook fetch(final TwilioRestClient client) { - String path = - "/v2/Services/{ServiceSid}/Channels/{ChannelSid}/Webhooks/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = - path.replace( - "{" + "ChannelSid" + "}", - this.pathChannelSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/v2/Services/{ServiceSid}/Channels/{ChannelSid}/Webhooks/{Sid}"; + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "ChannelSid" + "}", this.pathchannelSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.IPMESSAGING.toString(), - path + HttpMethod.GET, + Domains.IPMESSAGING.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Webhook fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Webhook fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Webhook.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/ipmessaging/v2/service/channel/WebhookReader.java b/src/main/java/com/twilio/rest/ipmessaging/v2/service/channel/WebhookReader.java index 9c94300405..14622edfb4 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v2/service/channel/WebhookReader.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v2/service/channel/WebhookReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,126 +30,91 @@ public class WebhookReader extends Reader { - private String pathServiceSid; - private String pathChannelSid; + private String pathserviceSid; + private String pathchannelSid; private Long pageSize; - public WebhookReader( - final String pathServiceSid, - final String pathChannelSid - ) { - this.pathServiceSid = pathServiceSid; - this.pathChannelSid = pathChannelSid; + public WebhookReader(final String pathserviceSid, final String pathchannelSid) { + this.pathserviceSid = pathserviceSid; + this.pathchannelSid = pathchannelSid; } + public WebhookReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { - String path = - "/v2/Services/{ServiceSid}/Channels/{ChannelSid}/Webhooks"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = - path.replace( - "{" + "ChannelSid" + "}", - this.pathChannelSid.toString() - ); + + String path = "/v2/Services/{ServiceSid}/Channels/{ChannelSid}/Webhooks"; + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "ChannelSid" + "}", this.pathchannelSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.IPMESSAGING.toString(), - path + HttpMethod.GET, + Domains.IPMESSAGING.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Webhook read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Webhook read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "webhooks", - response.getContent(), - Webhook.class, - client.getObjectMapper() - ); + "webhooks", + response.getContent(), + Webhook.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.IPMESSAGING.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.IPMESSAGING.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/ipmessaging/v2/service/channel/WebhookUpdater.java b/src/main/java/com/twilio/rest/ipmessaging/v2/service/channel/WebhookUpdater.java index 50ec1d7977..fec4e97509 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v2/service/channel/WebhookUpdater.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v2/service/channel/WebhookUpdater.java @@ -16,7 +16,9 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; import com.twilio.converter.Promoter; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,13 +27,13 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.util.List; public class WebhookUpdater extends Updater { - - private String pathServiceSid; - private String pathChannelSid; - private String pathSid; + private String pathserviceSid; + private String pathchannelSid; + private String pathsid; private String configurationUrl; private Webhook.Method configurationMethod; private List configurationFilters; @@ -39,111 +41,84 @@ public class WebhookUpdater extends Updater { private String configurationFlowSid; private Integer configurationRetryCount; - public WebhookUpdater( - final String pathServiceSid, - final String pathChannelSid, - final String pathSid - ) { - this.pathServiceSid = pathServiceSid; - this.pathChannelSid = pathChannelSid; - this.pathSid = pathSid; + public WebhookUpdater(final String pathserviceSid, final String pathchannelSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathchannelSid = pathchannelSid; + this.pathsid = pathsid; } + public WebhookUpdater setConfigurationUrl(final String configurationUrl) { this.configurationUrl = configurationUrl; return this; } - public WebhookUpdater setConfigurationMethod( - final Webhook.Method configurationMethod - ) { + + public WebhookUpdater setConfigurationMethod(final Webhook.Method configurationMethod) { this.configurationMethod = configurationMethod; return this; } - public WebhookUpdater setConfigurationFilters( - final List configurationFilters - ) { + + public WebhookUpdater setConfigurationFilters(final List configurationFilters) { this.configurationFilters = configurationFilters; return this; } - public WebhookUpdater setConfigurationFilters( - final String configurationFilters - ) { - return setConfigurationFilters( - Promoter.listOfOne(configurationFilters) - ); + public WebhookUpdater setConfigurationFilters(final String configurationFilters) { + return setConfigurationFilters(Promoter.listOfOne(configurationFilters)); } - public WebhookUpdater setConfigurationTriggers( - final List configurationTriggers - ) { + public WebhookUpdater setConfigurationTriggers(final List configurationTriggers) { this.configurationTriggers = configurationTriggers; return this; } - public WebhookUpdater setConfigurationTriggers( - final String configurationTriggers - ) { - return setConfigurationTriggers( - Promoter.listOfOne(configurationTriggers) - ); + public WebhookUpdater setConfigurationTriggers(final String configurationTriggers) { + return setConfigurationTriggers(Promoter.listOfOne(configurationTriggers)); } - public WebhookUpdater setConfigurationFlowSid( - final String configurationFlowSid - ) { + public WebhookUpdater setConfigurationFlowSid(final String configurationFlowSid) { this.configurationFlowSid = configurationFlowSid; return this; } - public WebhookUpdater setConfigurationRetryCount( - final Integer configurationRetryCount - ) { + + public WebhookUpdater setConfigurationRetryCount(final Integer configurationRetryCount) { this.configurationRetryCount = configurationRetryCount; return this; } + @Override public Webhook update(final TwilioRestClient client) { - String path = - "/v2/Services/{ServiceSid}/Channels/{ChannelSid}/Webhooks/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = - path.replace( - "{" + "ChannelSid" + "}", - this.pathChannelSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/v2/Services/{ServiceSid}/Channels/{ChannelSid}/Webhooks/{Sid}"; + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "ChannelSid" + "}", this.pathchannelSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.IPMESSAGING.toString(), - path + HttpMethod.POST, + Domains.IPMESSAGING.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Webhook update failed: Unable to connect to server" - ); + throw new ApiConnectionException("Webhook update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -152,33 +127,40 @@ public Webhook update(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (configurationUrl != null) { - request.addPostParam("Configuration.Url", configurationUrl); + Serializer.toString(request, "Configuration.Url", configurationUrl, ParameterType.URLENCODED); } + + if (configurationMethod != null) { - request.addPostParam( - "Configuration.Method", - configurationMethod.toString() - ); + Serializer.toString(request, "Configuration.Method", configurationMethod, ParameterType.URLENCODED); } + + if (configurationFilters != null) { - for (String prop : configurationFilters) { - request.addPostParam("Configuration.Filters", prop); + for (String param : configurationFilters) { + Serializer.toString(request, "Configuration.Filters", param, ParameterType.URLENCODED); } } + + if (configurationTriggers != null) { - for (String prop : configurationTriggers) { - request.addPostParam("Configuration.Triggers", prop); + for (String param : configurationTriggers) { + Serializer.toString(request, "Configuration.Triggers", param, ParameterType.URLENCODED); } } + + if (configurationFlowSid != null) { - request.addPostParam("Configuration.FlowSid", configurationFlowSid); + Serializer.toString(request, "Configuration.FlowSid", configurationFlowSid, ParameterType.URLENCODED); } + + if (configurationRetryCount != null) { - request.addPostParam( - "Configuration.RetryCount", - configurationRetryCount.toString() - ); + Serializer.toString(request, "Configuration.RetryCount", configurationRetryCount, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/ipmessaging/v2/service/user/UserBinding.java b/src/main/java/com/twilio/rest/ipmessaging/v2/service/user/UserBinding.java index e43512d118..232448c5c1 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v2/service/user/UserBinding.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v2/service/user/UserBinding.java @@ -18,62 +18,80 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.List; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class UserBinding extends Resource { - private static final long serialVersionUID = 252068300768529L; - public static UserBindingDeleter deleter( - final String pathServiceSid, - final String pathUserSid, - final String pathSid - ) { - return new UserBindingDeleter(pathServiceSid, pathUserSid, pathSid); + public static UserBindingDeleter deleter(final String pathserviceSid, final String pathuserSid, final String pathsid) { + return new UserBindingDeleter( + pathserviceSid, pathuserSid, pathsid + ); } - public static UserBindingFetcher fetcher( - final String pathServiceSid, - final String pathUserSid, - final String pathSid - ) { - return new UserBindingFetcher(pathServiceSid, pathUserSid, pathSid); + + public static UserBindingFetcher fetcher(final String pathserviceSid, final String pathuserSid, final String pathsid) { + return new UserBindingFetcher( + pathserviceSid, pathuserSid, pathsid + ); } - public static UserBindingReader reader( - final String pathServiceSid, - final String pathUserSid - ) { - return new UserBindingReader(pathServiceSid, pathUserSid); + + public static UserBindingReader reader(final String pathserviceSid, final String pathuserSid) { + return new UserBindingReader( + pathserviceSid, pathuserSid + ); + } + + + public enum BindingType { + GCM("gcm"), + APN("apn"), + FCM("fcm"); + + private final String value; + + private BindingType(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static BindingType forValue(final String value) { + return Promoter.enumFromString(value, BindingType.values()); + } } + /** * Converts a JSON String into a UserBinding object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return UserBinding object represented by the provided JSON */ - public static UserBinding fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static UserBinding fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, UserBinding.class); @@ -88,14 +106,11 @@ public static UserBinding fromJson( * Converts a JSON InputStream into a UserBinding object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return UserBinding object represented by the provided JSON */ - public static UserBinding fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static UserBinding fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, UserBinding.class); @@ -106,94 +121,73 @@ public static UserBinding fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String serviceSid; + @Getter + private final UserBinding.BindingType bindingType; + @Getter + private final String credentialSid; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; + @Getter private final String endpoint; + @Getter private final String identity; - private final String userSid; - private final String credentialSid; - private final UserBinding.BindingType bindingType; + @Getter private final List messageTypes; + @Getter + private final String serviceSid; + @Getter + private final String sid; + @Getter private final URI url; + @Getter + private final String userSid; @JsonCreator private UserBinding( - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("service_sid") final String serviceSid, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("endpoint") final String endpoint, - @JsonProperty("identity") final String identity, - @JsonProperty("user_sid") final String userSid, - @JsonProperty("credential_sid") final String credentialSid, - @JsonProperty("binding_type") final UserBinding.BindingType bindingType, - @JsonProperty("message_types") final List messageTypes, - @JsonProperty("url") final URI url + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("binding_type") final UserBinding.BindingType bindingType, + @JsonProperty("credential_sid") final String credentialSid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("endpoint") final String endpoint, + @JsonProperty("identity") final String identity, + @JsonProperty("message_types") final List messageTypes, + @JsonProperty("service_sid") final String serviceSid, + @JsonProperty("sid") final String sid, + @JsonProperty("url") final URI url, + @JsonProperty("user_sid") final String userSid ) { - this.sid = sid; this.accountSid = accountSid; - this.serviceSid = serviceSid; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); + this.bindingType = bindingType; + this.credentialSid = credentialSid; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.endpoint = endpoint; this.identity = identity; - this.userSid = userSid; - this.credentialSid = credentialSid; - this.bindingType = bindingType; this.messageTypes = messageTypes; + this.serviceSid = serviceSid; + this.sid = sid; this.url = url; - } - - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getServiceSid() { - return this.serviceSid; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final String getEndpoint() { - return this.endpoint; - } - - public final String getIdentity() { - return this.identity; - } - - public final String getUserSid() { - return this.userSid; - } - - public final String getCredentialSid() { - return this.credentialSid; - } - - public final UserBinding.BindingType getBindingType() { - return this.bindingType; - } - - public final List getMessageTypes() { - return this.messageTypes; - } - - public final URI getUrl() { - return this.url; + this.userSid = userSid; } @Override @@ -207,59 +201,40 @@ public boolean equals(final Object o) { } UserBinding other = (UserBinding) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(serviceSid, other.serviceSid) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(endpoint, other.endpoint) && - Objects.equals(identity, other.identity) && - Objects.equals(userSid, other.userSid) && - Objects.equals(credentialSid, other.credentialSid) && - Objects.equals(bindingType, other.bindingType) && - Objects.equals(messageTypes, other.messageTypes) && - Objects.equals(url, other.url) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(bindingType, other.bindingType) && + Objects.equals(credentialSid, other.credentialSid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(endpoint, other.endpoint) && + Objects.equals(identity, other.identity) && + Objects.equals(messageTypes, other.messageTypes) && + Objects.equals(serviceSid, other.serviceSid) && + Objects.equals(sid, other.sid) && + Objects.equals(url, other.url) && + Objects.equals(userSid, other.userSid) ); } @Override public int hashCode() { return Objects.hash( - sid, - accountSid, - serviceSid, - dateCreated, - dateUpdated, - endpoint, - identity, - userSid, - credentialSid, - bindingType, - messageTypes, - url + accountSid, + bindingType, + credentialSid, + dateCreated, + dateUpdated, + endpoint, + identity, + messageTypes, + serviceSid, + sid, + url, + userSid ); } - public enum BindingType { - GCM("gcm"), - APN("apn"), - FCM("fcm"); - private final String value; - - private BindingType(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static BindingType forValue(final String value) { - return Promoter.enumFromString(value, BindingType.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/ipmessaging/v2/service/user/UserBindingDeleter.java b/src/main/java/com/twilio/rest/ipmessaging/v2/service/user/UserBindingDeleter.java index 705a0e2fc1..598ad09798 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v2/service/user/UserBindingDeleter.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v2/service/user/UserBindingDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.ipmessaging.v2.service.user; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,55 +26,44 @@ public class UserBindingDeleter extends Deleter { - private String pathServiceSid; - private String pathUserSid; - private String pathSid; + private String pathserviceSid; + private String pathuserSid; + private String pathsid; - public UserBindingDeleter( - final String pathServiceSid, - final String pathUserSid, - final String pathSid - ) { - this.pathServiceSid = pathServiceSid; - this.pathUserSid = pathUserSid; - this.pathSid = pathSid; + public UserBindingDeleter(final String pathserviceSid, final String pathuserSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathuserSid = pathuserSid; + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { - String path = - "/v2/Services/{ServiceSid}/Users/{UserSid}/Bindings/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = path.replace("{" + "UserSid" + "}", this.pathUserSid.toString()); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/v2/Services/{ServiceSid}/Users/{UserSid}/Bindings/{Sid}"; + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "UserSid" + "}", this.pathuserSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.IPMESSAGING.toString(), - path + HttpMethod.DELETE, + Domains.IPMESSAGING.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "UserBinding delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("UserBinding delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/ipmessaging/v2/service/user/UserBindingFetcher.java b/src/main/java/com/twilio/rest/ipmessaging/v2/service/user/UserBindingFetcher.java index 87bb6ca826..fcadef4dde 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v2/service/user/UserBindingFetcher.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v2/service/user/UserBindingFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.ipmessaging.v2.service.user; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,62 +26,47 @@ public class UserBindingFetcher extends Fetcher { - private String pathServiceSid; - private String pathUserSid; - private String pathSid; + private String pathserviceSid; + private String pathuserSid; + private String pathsid; - public UserBindingFetcher( - final String pathServiceSid, - final String pathUserSid, - final String pathSid - ) { - this.pathServiceSid = pathServiceSid; - this.pathUserSid = pathUserSid; - this.pathSid = pathSid; + public UserBindingFetcher(final String pathserviceSid, final String pathuserSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathuserSid = pathuserSid; + this.pathsid = pathsid; } + @Override public UserBinding fetch(final TwilioRestClient client) { - String path = - "/v2/Services/{ServiceSid}/Users/{UserSid}/Bindings/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = path.replace("{" + "UserSid" + "}", this.pathUserSid.toString()); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/v2/Services/{ServiceSid}/Users/{UserSid}/Bindings/{Sid}"; + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "UserSid" + "}", this.pathuserSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.IPMESSAGING.toString(), - path + HttpMethod.GET, + Domains.IPMESSAGING.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "UserBinding fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("UserBinding fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return UserBinding.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return UserBinding.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/ipmessaging/v2/service/user/UserBindingReader.java b/src/main/java/com/twilio/rest/ipmessaging/v2/service/user/UserBindingReader.java index 98a6bef7ad..f13ef2f52a 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v2/service/user/UserBindingReader.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v2/service/user/UserBindingReader.java @@ -17,8 +17,9 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; import com.twilio.converter.Promoter; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,33 +28,28 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.util.List; public class UserBindingReader extends Reader { - private String pathServiceSid; - private String pathUserSid; + private String pathserviceSid; + private String pathuserSid; private List bindingType; private Long pageSize; - public UserBindingReader( - final String pathServiceSid, - final String pathUserSid - ) { - this.pathServiceSid = pathServiceSid; - this.pathUserSid = pathUserSid; + public UserBindingReader(final String pathserviceSid, final String pathuserSid) { + this.pathserviceSid = pathserviceSid; + this.pathuserSid = pathuserSid; } - public UserBindingReader setBindingType( - final List bindingType - ) { + + public UserBindingReader setBindingType(final List bindingType) { this.bindingType = bindingType; return this; } - public UserBindingReader setBindingType( - final UserBinding.BindingType bindingType - ) { + public UserBindingReader setBindingType(final UserBinding.BindingType bindingType) { return setBindingType(Promoter.listOfOne(bindingType)); } @@ -62,109 +58,83 @@ public UserBindingReader setPageSize(final Long pageSize) { return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v2/Services/{ServiceSid}/Users/{UserSid}/Bindings"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = path.replace("{" + "UserSid" + "}", this.pathUserSid.toString()); + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "UserSid" + "}", this.pathuserSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.IPMESSAGING.toString(), - path + HttpMethod.GET, + Domains.IPMESSAGING.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "UserBinding read failed: Unable to connect to server" - ); + throw new ApiConnectionException("UserBinding read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "bindings", - response.getContent(), - UserBinding.class, - client.getObjectMapper() - ); + "bindings", + response.getContent(), + UserBinding.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.IPMESSAGING.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.IPMESSAGING.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (bindingType != null) { - for (UserBinding.BindingType prop : bindingType) { - request.addQueryParam("BindingType", prop.toString()); + for (UserBinding.BindingType param : bindingType) { + Serializer.toString(request, "BindingType", param, ParameterType.QUERY); } } + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/ipmessaging/v2/service/user/UserChannel.java b/src/main/java/com/twilio/rest/ipmessaging/v2/service/user/UserChannel.java index 780eca1a29..fee1c5f140 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v2/service/user/UserChannel.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v2/service/user/UserChannel.java @@ -18,81 +18,105 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class UserChannel extends Resource { - private static final long serialVersionUID = 104594062960806L; - public static UserChannelDeleter deleter( - final String pathServiceSid, - final String pathUserSid, - final String pathChannelSid - ) { + public static UserChannelDeleter deleter(final String pathserviceSid, final String pathuserSid, final String pathchannelSid) { return new UserChannelDeleter( - pathServiceSid, - pathUserSid, - pathChannelSid + pathserviceSid, pathuserSid, pathchannelSid ); } - public static UserChannelFetcher fetcher( - final String pathServiceSid, - final String pathUserSid, - final String pathChannelSid - ) { + + public static UserChannelFetcher fetcher(final String pathserviceSid, final String pathuserSid, final String pathchannelSid) { return new UserChannelFetcher( - pathServiceSid, - pathUserSid, - pathChannelSid + pathserviceSid, pathuserSid, pathchannelSid ); } - public static UserChannelReader reader( - final String pathServiceSid, - final String pathUserSid - ) { - return new UserChannelReader(pathServiceSid, pathUserSid); + + public static UserChannelReader reader(final String pathserviceSid, final String pathuserSid) { + return new UserChannelReader( + pathserviceSid, pathuserSid + ); } - public static UserChannelUpdater updater( - final String pathServiceSid, - final String pathUserSid, - final String pathChannelSid - ) { + + public static UserChannelUpdater updater(final String pathserviceSid, final String pathuserSid, final String pathchannelSid) { return new UserChannelUpdater( - pathServiceSid, - pathUserSid, - pathChannelSid + pathserviceSid, pathuserSid, pathchannelSid ); } + + public enum NotificationLevel { + DEFAULT("default"), + MUTED("muted"); + + private final String value; + + private NotificationLevel(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static NotificationLevel forValue(final String value) { + return Promoter.enumFromString(value, NotificationLevel.values()); + } + } + + public enum ChannelStatus { + JOINED("joined"), + INVITED("invited"), + NOT_PARTICIPATING("not_participating"); + + private final String value; + + private ChannelStatus(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static ChannelStatus forValue(final String value) { + return Promoter.enumFromString(value, ChannelStatus.values()); + } + } + + /** * Converts a JSON String into a UserChannel object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return UserChannel object represented by the provided JSON */ - public static UserChannel fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static UserChannel fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, UserChannel.class); @@ -107,14 +131,11 @@ public static UserChannel fromJson( * Converts a JSON InputStream into a UserChannel object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return UserChannel object represented by the provided JSON */ - public static UserChannel fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static UserChannel fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, UserChannel.class); @@ -125,93 +146,67 @@ public static UserChannel fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String serviceSid; + @Getter private final String channelSid; - private final String userSid; + @Getter + private final Integer lastConsumedMessageIndex; + @Getter + private final Map links; + @Getter private final String memberSid; + @Getter + private final UserChannel.NotificationLevel notificationLevel; + @Getter + private final String serviceSid; + @Getter private final UserChannel.ChannelStatus status; - private final Integer lastConsumedMessageIndex; + @Getter private final Integer unreadMessagesCount; - private final Map links; + @Getter private final URI url; - private final UserChannel.NotificationLevel notificationLevel; + @Getter + private final String userSid; @JsonCreator private UserChannel( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("service_sid") final String serviceSid, - @JsonProperty("channel_sid") final String channelSid, - @JsonProperty("user_sid") final String userSid, - @JsonProperty("member_sid") final String memberSid, - @JsonProperty("status") final UserChannel.ChannelStatus status, - @JsonProperty( - "last_consumed_message_index" - ) final Integer lastConsumedMessageIndex, - @JsonProperty( - "unread_messages_count" - ) final Integer unreadMessagesCount, - @JsonProperty("links") final Map links, - @JsonProperty("url") final URI url, - @JsonProperty( - "notification_level" - ) final UserChannel.NotificationLevel notificationLevel + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("channel_sid") final String channelSid, + @JsonProperty("last_consumed_message_index") final Integer lastConsumedMessageIndex, + @JsonProperty("links") final Map links, + @JsonProperty("member_sid") final String memberSid, + @JsonProperty("notification_level") final UserChannel.NotificationLevel notificationLevel, + @JsonProperty("service_sid") final String serviceSid, + @JsonProperty("status") final UserChannel.ChannelStatus status, + @JsonProperty("unread_messages_count") final Integer unreadMessagesCount, + @JsonProperty("url") final URI url, + @JsonProperty("user_sid") final String userSid ) { this.accountSid = accountSid; - this.serviceSid = serviceSid; this.channelSid = channelSid; - this.userSid = userSid; + this.lastConsumedMessageIndex = lastConsumedMessageIndex; + this.links = links; this.memberSid = memberSid; + this.notificationLevel = notificationLevel; + this.serviceSid = serviceSid; this.status = status; - this.lastConsumedMessageIndex = lastConsumedMessageIndex; this.unreadMessagesCount = unreadMessagesCount; - this.links = links; this.url = url; - this.notificationLevel = notificationLevel; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getServiceSid() { - return this.serviceSid; - } - - public final String getChannelSid() { - return this.channelSid; - } - - public final String getUserSid() { - return this.userSid; - } - - public final String getMemberSid() { - return this.memberSid; - } - - public final UserChannel.ChannelStatus getStatus() { - return this.status; - } - - public final Integer getLastConsumedMessageIndex() { - return this.lastConsumedMessageIndex; - } - - public final Integer getUnreadMessagesCount() { - return this.unreadMessagesCount; - } - - public final Map getLinks() { - return this.links; - } - - public final URI getUrl() { - return this.url; - } - - public final UserChannel.NotificationLevel getNotificationLevel() { - return this.notificationLevel; + this.userSid = userSid; } @Override @@ -225,80 +220,38 @@ public boolean equals(final Object o) { } UserChannel other = (UserChannel) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(serviceSid, other.serviceSid) && - Objects.equals(channelSid, other.channelSid) && - Objects.equals(userSid, other.userSid) && - Objects.equals(memberSid, other.memberSid) && - Objects.equals(status, other.status) && - Objects.equals( - lastConsumedMessageIndex, - other.lastConsumedMessageIndex - ) && - Objects.equals(unreadMessagesCount, other.unreadMessagesCount) && - Objects.equals(links, other.links) && - Objects.equals(url, other.url) && - Objects.equals(notificationLevel, other.notificationLevel) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(channelSid, other.channelSid) && + Objects.equals(lastConsumedMessageIndex, other.lastConsumedMessageIndex) && + Objects.equals(links, other.links) && + Objects.equals(memberSid, other.memberSid) && + Objects.equals(notificationLevel, other.notificationLevel) && + Objects.equals(serviceSid, other.serviceSid) && + Objects.equals(status, other.status) && + Objects.equals(unreadMessagesCount, other.unreadMessagesCount) && + Objects.equals(url, other.url) && + Objects.equals(userSid, other.userSid) ); } @Override public int hashCode() { return Objects.hash( - accountSid, - serviceSid, - channelSid, - userSid, - memberSid, - status, - lastConsumedMessageIndex, - unreadMessagesCount, - links, - url, - notificationLevel + accountSid, + channelSid, + lastConsumedMessageIndex, + links, + memberSid, + notificationLevel, + serviceSid, + status, + unreadMessagesCount, + url, + userSid ); } - public enum ChannelStatus { - JOINED("joined"), - INVITED("invited"), - NOT_PARTICIPATING("not_participating"); - - private final String value; - - private ChannelStatus(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static ChannelStatus forValue(final String value) { - return Promoter.enumFromString(value, ChannelStatus.values()); - } - } - - public enum NotificationLevel { - DEFAULT("default"), - MUTED("muted"); - - private final String value; - private NotificationLevel(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static NotificationLevel forValue(final String value) { - return Promoter.enumFromString(value, NotificationLevel.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/ipmessaging/v2/service/user/UserChannelDeleter.java b/src/main/java/com/twilio/rest/ipmessaging/v2/service/user/UserChannelDeleter.java index 104378d7bf..d861e8c21b 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v2/service/user/UserChannelDeleter.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v2/service/user/UserChannelDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.ipmessaging.v2.service.user; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,59 +26,44 @@ public class UserChannelDeleter extends Deleter { - private String pathServiceSid; - private String pathUserSid; - private String pathChannelSid; + private String pathserviceSid; + private String pathuserSid; + private String pathchannelSid; - public UserChannelDeleter( - final String pathServiceSid, - final String pathUserSid, - final String pathChannelSid - ) { - this.pathServiceSid = pathServiceSid; - this.pathUserSid = pathUserSid; - this.pathChannelSid = pathChannelSid; + public UserChannelDeleter(final String pathserviceSid, final String pathuserSid, final String pathchannelSid) { + this.pathserviceSid = pathserviceSid; + this.pathuserSid = pathuserSid; + this.pathchannelSid = pathchannelSid; } + @Override public boolean delete(final TwilioRestClient client) { - String path = - "/v2/Services/{ServiceSid}/Users/{UserSid}/Channels/{ChannelSid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = path.replace("{" + "UserSid" + "}", this.pathUserSid.toString()); - path = - path.replace( - "{" + "ChannelSid" + "}", - this.pathChannelSid.toString() - ); + String path = "/v2/Services/{ServiceSid}/Users/{UserSid}/Channels/{ChannelSid}"; + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "UserSid" + "}", this.pathuserSid.toString()); + path = path.replace("{" + "ChannelSid" + "}", this.pathchannelSid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.IPMESSAGING.toString(), - path + HttpMethod.DELETE, + Domains.IPMESSAGING.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "UserChannel delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("UserChannel delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/ipmessaging/v2/service/user/UserChannelFetcher.java b/src/main/java/com/twilio/rest/ipmessaging/v2/service/user/UserChannelFetcher.java index 2b4e826e31..8b1574c1ca 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v2/service/user/UserChannelFetcher.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v2/service/user/UserChannelFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.ipmessaging.v2.service.user; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,66 +26,47 @@ public class UserChannelFetcher extends Fetcher { - private String pathServiceSid; - private String pathUserSid; - private String pathChannelSid; + private String pathserviceSid; + private String pathuserSid; + private String pathchannelSid; - public UserChannelFetcher( - final String pathServiceSid, - final String pathUserSid, - final String pathChannelSid - ) { - this.pathServiceSid = pathServiceSid; - this.pathUserSid = pathUserSid; - this.pathChannelSid = pathChannelSid; + public UserChannelFetcher(final String pathserviceSid, final String pathuserSid, final String pathchannelSid) { + this.pathserviceSid = pathserviceSid; + this.pathuserSid = pathuserSid; + this.pathchannelSid = pathchannelSid; } + @Override public UserChannel fetch(final TwilioRestClient client) { - String path = - "/v2/Services/{ServiceSid}/Users/{UserSid}/Channels/{ChannelSid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = path.replace("{" + "UserSid" + "}", this.pathUserSid.toString()); - path = - path.replace( - "{" + "ChannelSid" + "}", - this.pathChannelSid.toString() - ); + String path = "/v2/Services/{ServiceSid}/Users/{UserSid}/Channels/{ChannelSid}"; + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "UserSid" + "}", this.pathuserSid.toString()); + path = path.replace("{" + "ChannelSid" + "}", this.pathchannelSid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.IPMESSAGING.toString(), - path + HttpMethod.GET, + Domains.IPMESSAGING.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "UserChannel fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("UserChannel fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return UserChannel.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return UserChannel.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/ipmessaging/v2/service/user/UserChannelReader.java b/src/main/java/com/twilio/rest/ipmessaging/v2/service/user/UserChannelReader.java index 870d8c5dd3..053def8a43 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v2/service/user/UserChannelReader.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v2/service/user/UserChannelReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,121 +30,91 @@ public class UserChannelReader extends Reader { - private String pathServiceSid; - private String pathUserSid; + private String pathserviceSid; + private String pathuserSid; private Long pageSize; - public UserChannelReader( - final String pathServiceSid, - final String pathUserSid - ) { - this.pathServiceSid = pathServiceSid; - this.pathUserSid = pathUserSid; + public UserChannelReader(final String pathserviceSid, final String pathuserSid) { + this.pathserviceSid = pathserviceSid; + this.pathuserSid = pathuserSid; } + public UserChannelReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v2/Services/{ServiceSid}/Users/{UserSid}/Channels"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = path.replace("{" + "UserSid" + "}", this.pathUserSid.toString()); + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "UserSid" + "}", this.pathuserSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.IPMESSAGING.toString(), - path + HttpMethod.GET, + Domains.IPMESSAGING.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "UserChannel read failed: Unable to connect to server" - ); + throw new ApiConnectionException("UserChannel read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "channels", - response.getContent(), - UserChannel.class, - client.getObjectMapper() - ); + "channels", + response.getContent(), + UserChannel.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.IPMESSAGING.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.IPMESSAGING.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/ipmessaging/v2/service/user/UserChannelUpdater.java b/src/main/java/com/twilio/rest/ipmessaging/v2/service/user/UserChannelUpdater.java index 9360069c62..365606ad47 100644 --- a/src/main/java/com/twilio/rest/ipmessaging/v2/service/user/UserChannelUpdater.java +++ b/src/main/java/com/twilio/rest/ipmessaging/v2/service/user/UserChannelUpdater.java @@ -16,6 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -24,115 +26,94 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.time.ZonedDateTime; public class UserChannelUpdater extends Updater { - - private String pathServiceSid; - private String pathUserSid; - private String pathChannelSid; + private String pathserviceSid; + private String pathuserSid; + private String pathchannelSid; private UserChannel.NotificationLevel notificationLevel; private Integer lastConsumedMessageIndex; private ZonedDateTime lastConsumptionTimestamp; - public UserChannelUpdater( - final String pathServiceSid, - final String pathUserSid, - final String pathChannelSid - ) { - this.pathServiceSid = pathServiceSid; - this.pathUserSid = pathUserSid; - this.pathChannelSid = pathChannelSid; + public UserChannelUpdater(final String pathserviceSid, final String pathuserSid, final String pathchannelSid) { + this.pathserviceSid = pathserviceSid; + this.pathuserSid = pathuserSid; + this.pathchannelSid = pathchannelSid; } - public UserChannelUpdater setNotificationLevel( - final UserChannel.NotificationLevel notificationLevel - ) { + + public UserChannelUpdater setNotificationLevel(final UserChannel.NotificationLevel notificationLevel) { this.notificationLevel = notificationLevel; return this; } - public UserChannelUpdater setLastConsumedMessageIndex( - final Integer lastConsumedMessageIndex - ) { + + public UserChannelUpdater setLastConsumedMessageIndex(final Integer lastConsumedMessageIndex) { this.lastConsumedMessageIndex = lastConsumedMessageIndex; return this; } - public UserChannelUpdater setLastConsumptionTimestamp( - final ZonedDateTime lastConsumptionTimestamp - ) { + + public UserChannelUpdater setLastConsumptionTimestamp(final ZonedDateTime lastConsumptionTimestamp) { this.lastConsumptionTimestamp = lastConsumptionTimestamp; return this; } + @Override public UserChannel update(final TwilioRestClient client) { - String path = - "/v2/Services/{ServiceSid}/Users/{UserSid}/Channels/{ChannelSid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = path.replace("{" + "UserSid" + "}", this.pathUserSid.toString()); - path = - path.replace( - "{" + "ChannelSid" + "}", - this.pathChannelSid.toString() - ); + String path = "/v2/Services/{ServiceSid}/Users/{UserSid}/Channels/{ChannelSid}"; + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "UserSid" + "}", this.pathuserSid.toString()); + path = path.replace("{" + "ChannelSid" + "}", this.pathchannelSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.IPMESSAGING.toString(), - path + HttpMethod.POST, + Domains.IPMESSAGING.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "UserChannel update failed: Unable to connect to server" - ); + throw new ApiConnectionException("UserChannel update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return UserChannel.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return UserChannel.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (notificationLevel != null) { - request.addPostParam( - "NotificationLevel", - notificationLevel.toString() - ); + Serializer.toString(request, "NotificationLevel", notificationLevel, ParameterType.URLENCODED); } + + if (lastConsumedMessageIndex != null) { - request.addPostParam( - "LastConsumedMessageIndex", - lastConsumedMessageIndex.toString() - ); + Serializer.toString(request, "LastConsumedMessageIndex", lastConsumedMessageIndex, ParameterType.URLENCODED); } + + if (lastConsumptionTimestamp != null) { - request.addPostParam( - "LastConsumptionTimestamp", - lastConsumptionTimestamp.toInstant().toString() - ); + Serializer.toString(request, "LastConsumptionTimestamp", lastConsumptionTimestamp, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/lookups/v1/PhoneNumber.java b/src/main/java/com/twilio/rest/lookups/v1/PhoneNumber.java index 29770ce206..3d158fbf11 100644 --- a/src/main/java/com/twilio/rest/lookups/v1/PhoneNumber.java +++ b/src/main/java/com/twilio/rest/lookups/v1/PhoneNumber.java @@ -18,41 +18,40 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; -import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class PhoneNumber extends Resource { - private static final long serialVersionUID = 141589309941045L; - public static PhoneNumberFetcher fetcher(final String pathPhoneNumber) { - return new PhoneNumberFetcher(pathPhoneNumber); + public static PhoneNumberFetcher fetcher(final String pathphoneNumber) { + return new PhoneNumberFetcher( + pathphoneNumber + ); } + /** * Converts a JSON String into a PhoneNumber object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return PhoneNumber object represented by the provided JSON */ - public static PhoneNumber fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static PhoneNumber fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, PhoneNumber.class); @@ -67,14 +66,11 @@ public static PhoneNumber fromJson( * Converts a JSON InputStream into a PhoneNumber object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return PhoneNumber object represented by the provided JSON */ - public static PhoneNumber fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static PhoneNumber fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, PhoneNumber.class); @@ -85,63 +81,53 @@ public static PhoneNumber fromJson( } } - private final Map callerName; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter + private final Object addOns; + @Getter + private final Object callerName; + @Getter + private final Object carrier; + @Getter private final String countryCode; - private final com.twilio.type.PhoneNumber phoneNumber; + @Getter private final String nationalFormat; - private final Map carrier; - private final Map addOns; + @Getter + private final com.twilio.type.PhoneNumber phoneNumber; + @Getter private final URI url; @JsonCreator private PhoneNumber( - @JsonProperty("caller_name") final Map callerName, - @JsonProperty("country_code") final String countryCode, - @JsonProperty( - "phone_number" - ) final com.twilio.type.PhoneNumber phoneNumber, - @JsonProperty("national_format") final String nationalFormat, - @JsonProperty("carrier") final Map carrier, - @JsonProperty("add_ons") final Map addOns, - @JsonProperty("url") final URI url + @JsonProperty("add_ons") final Object addOns, + @JsonProperty("caller_name") final Object callerName, + @JsonProperty("carrier") final Object carrier, + @JsonProperty("country_code") final String countryCode, + @JsonProperty("national_format") final String nationalFormat, + @JsonProperty("phone_number") final com.twilio.type.PhoneNumber phoneNumber, + @JsonProperty("url") final URI url ) { + this.addOns = addOns; this.callerName = callerName; + this.carrier = carrier; this.countryCode = countryCode; - this.phoneNumber = phoneNumber; this.nationalFormat = nationalFormat; - this.carrier = carrier; - this.addOns = addOns; + this.phoneNumber = phoneNumber; this.url = url; } - public final Map getCallerName() { - return this.callerName; - } - - public final String getCountryCode() { - return this.countryCode; - } - - public final com.twilio.type.PhoneNumber getPhoneNumber() { - return this.phoneNumber; - } - - public final String getNationalFormat() { - return this.nationalFormat; - } - - public final Map getCarrier() { - return this.carrier; - } - - public final Map getAddOns() { - return this.addOns; - } - - public final URI getUrl() { - return this.url; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -153,28 +139,30 @@ public boolean equals(final Object o) { } PhoneNumber other = (PhoneNumber) o; - return ( - Objects.equals(callerName, other.callerName) && - Objects.equals(countryCode, other.countryCode) && - Objects.equals(phoneNumber, other.phoneNumber) && - Objects.equals(nationalFormat, other.nationalFormat) && - Objects.equals(carrier, other.carrier) && - Objects.equals(addOns, other.addOns) && - Objects.equals(url, other.url) + Objects.equals(addOns, other.addOns) && + Objects.equals(callerName, other.callerName) && + Objects.equals(carrier, other.carrier) && + Objects.equals(countryCode, other.countryCode) && + Objects.equals(nationalFormat, other.nationalFormat) && + Objects.equals(phoneNumber, other.phoneNumber) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - callerName, - countryCode, - phoneNumber, - nationalFormat, - carrier, - addOns, - url + addOns, + callerName, + carrier, + countryCode, + nationalFormat, + phoneNumber, + url ); } + + } + diff --git a/src/main/java/com/twilio/rest/lookups/v1/PhoneNumberFetcher.java b/src/main/java/com/twilio/rest/lookups/v1/PhoneNumberFetcher.java index 16736af4d5..348c4fa1ca 100644 --- a/src/main/java/com/twilio/rest/lookups/v1/PhoneNumberFetcher.java +++ b/src/main/java/com/twilio/rest/lookups/v1/PhoneNumberFetcher.java @@ -15,9 +15,9 @@ package com.twilio.rest.lookups.v1; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; -import com.twilio.converter.PrefixedCollapsibleMap; +import com.twilio.constant.EnumConstants.ParameterType; import com.twilio.converter.Promoter; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -26,26 +26,29 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.util.List; import java.util.Map; public class PhoneNumberFetcher extends Fetcher { - private String pathPhoneNumber; + private String pathphoneNumber; private String countryCode; private List type; private List addOns; private Map addOnsData; - public PhoneNumberFetcher(final String pathPhoneNumber) { - this.pathPhoneNumber = pathPhoneNumber; + public PhoneNumberFetcher(final String pathphoneNumber) { + this.pathphoneNumber = pathphoneNumber; } + public PhoneNumberFetcher setCountryCode(final String countryCode) { this.countryCode = countryCode; return this; } + public PhoneNumberFetcher setType(final List type) { this.type = type; return this; @@ -64,78 +67,70 @@ public PhoneNumberFetcher setAddOns(final String addOns) { return setAddOns(Promoter.listOfOne(addOns)); } - public PhoneNumberFetcher setAddOnsData( - final Map addOnsData - ) { + public PhoneNumberFetcher setAddOnsData(final Map addOnsData) { this.addOnsData = addOnsData; return this; } + @Override public PhoneNumber fetch(final TwilioRestClient client) { + String path = "/v1/PhoneNumbers/{PhoneNumber}"; - path = - path.replace( - "{" + "PhoneNumber" + "}", - this.pathPhoneNumber.toString() - ); + path = path.replace("{" + "PhoneNumber" + "}", this.pathphoneNumber.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.LOOKUPS.toString(), - path + HttpMethod.GET, + Domains.LOOKUPS.toString(), + path ); addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "PhoneNumber fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("PhoneNumber fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return PhoneNumber.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return PhoneNumber.fromJson(response.getStream(), client.getObjectMapper()); } private void addQueryParams(final Request request) { + + if (countryCode != null) { - request.addQueryParam("CountryCode", countryCode); + Serializer.toString(request, "CountryCode", countryCode, ParameterType.QUERY); } + + if (type != null) { - for (String prop : type) { - request.addQueryParam("Type", prop); + for (String param : type) { + Serializer.toString(request, "Type", param, ParameterType.QUERY); } } + + if (addOns != null) { - for (String prop : addOns) { - request.addQueryParam("AddOns", prop); + for (String param : addOns) { + Serializer.toString(request, "AddOns", param, ParameterType.QUERY); } } + + if (addOnsData != null) { - Map params = PrefixedCollapsibleMap.serialize( - addOnsData, - "AddOns" - ); - for (Map.Entry entry : params.entrySet()) { - request.addQueryParam(entry.getKey(), entry.getValue()); - } + Serializer.toString(request, "AddOnsData", addOnsData, ParameterType.QUERY); } + + } } diff --git a/src/main/java/com/twilio/rest/lookups/v2/Bucket.java b/src/main/java/com/twilio/rest/lookups/v2/Bucket.java index 221da7456a..acf5db0dbc 100644 --- a/src/main/java/com/twilio/rest/lookups/v2/Bucket.java +++ b/src/main/java/com/twilio/rest/lookups/v2/Bucket.java @@ -25,20 +25,42 @@ import com.twilio.base.Resource; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; -import java.io.IOException; -import java.io.InputStream; -import java.util.Objects; import lombok.Getter; import lombok.Setter; import lombok.ToString; -import lombok.ToString; + +import java.io.IOException; +import java.io.InputStream; +import java.util.Objects; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Bucket extends Resource { - private static final long serialVersionUID = 277677635778369L; + public static BucketDeleter deleter(final String pathfield, final String pathbucket) { + return new BucketDeleter( + pathfield, pathbucket + ); + } + + + public static BucketFetcher fetcher(final String pathfield, final String pathbucket) { + return new BucketFetcher( + pathfield, pathbucket + ); + } + + + public static BucketUpdater updater(final String pathfield, final String pathbucket) { + return new BucketUpdater( + pathfield, pathbucket + ); + } + + + //@JsonDeserialize(builder = RateLimitRequest.Builder.class) + @JsonInclude(JsonInclude.Include.NON_EMPTY) @ToString public static class RateLimitRequest { @@ -54,48 +76,16 @@ public static class RateLimitRequest { @Setter private Integer ttl; - public RateLimitRequest() {} - - public static RateLimitRequest fromJson( - String jsonString, - ObjectMapper mapper - ) throws IOException { - return mapper.readValue(jsonString, RateLimitRequest.class); - } - } - - public static BucketDeleter deleter( - final String pathField, - final String pathBucket - ) { - return new BucketDeleter(pathField, pathBucket); - } - - public static BucketFetcher fetcher( - final String pathField, - final String pathBucket - ) { - return new BucketFetcher(pathField, pathBucket); - } - - public static BucketUpdater updater( - final String pathField, - final String pathBucket - ) { - return new BucketUpdater(pathField, pathBucket); } /** * Converts a JSON String into a Bucket object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Bucket object represented by the provided JSON */ - public static Bucket fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Bucket fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Bucket.class); @@ -110,14 +100,11 @@ public static Bucket fromJson( * Converts a JSON InputStream into a Bucket object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Bucket object represented by the provided JSON */ - public static Bucket fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Bucket fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Bucket.class); @@ -140,47 +127,33 @@ public static String toJson(Object object, ObjectMapper mapper) { } } + + @Getter + private final String bucket; + @Getter private final String field; + @Getter private final Integer limit; - private final String bucket; + @Getter private final String owner; + @Getter private final Integer ttl; @JsonCreator private Bucket( - @JsonProperty("field") final String field, - @JsonProperty("limit") final Integer limit, - @JsonProperty("bucket") final String bucket, - @JsonProperty("owner") final String owner, - @JsonProperty("ttl") final Integer ttl + @JsonProperty("bucket") final String bucket, + @JsonProperty("field") final String field, + @JsonProperty("limit") final Integer limit, + @JsonProperty("owner") final String owner, + @JsonProperty("ttl") final Integer ttl ) { + this.bucket = bucket; this.field = field; this.limit = limit; - this.bucket = bucket; this.owner = owner; this.ttl = ttl; } - public final String getField() { - return this.field; - } - - public final Integer getLimit() { - return this.limit; - } - - public final String getBucket() { - return this.bucket; - } - - public final String getOwner() { - return this.owner; - } - - public final Integer getTtl() { - return this.ttl; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -192,18 +165,26 @@ public boolean equals(final Object o) { } Bucket other = (Bucket) o; - return ( - Objects.equals(field, other.field) && - Objects.equals(limit, other.limit) && - Objects.equals(bucket, other.bucket) && - Objects.equals(owner, other.owner) && - Objects.equals(ttl, other.ttl) + Objects.equals(bucket, other.bucket) && + Objects.equals(field, other.field) && + Objects.equals(limit, other.limit) && + Objects.equals(owner, other.owner) && + Objects.equals(ttl, other.ttl) ); } @Override public int hashCode() { - return Objects.hash(field, limit, bucket, owner, ttl); + return Objects.hash( + bucket, + field, + limit, + owner, + ttl + ); } + + } + diff --git a/src/main/java/com/twilio/rest/lookups/v2/BucketDeleter.java b/src/main/java/com/twilio/rest/lookups/v2/BucketDeleter.java index 511751bad2..a05e2895f4 100644 --- a/src/main/java/com/twilio/rest/lookups/v2/BucketDeleter.java +++ b/src/main/java/com/twilio/rest/lookups/v2/BucketDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.lookups.v2; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,43 +26,41 @@ public class BucketDeleter extends Deleter { - private String pathField; - private String pathBucket; + private String pathfield; + private String pathbucket; - public BucketDeleter(final String pathField, final String pathBucket) { - this.pathField = pathField; - this.pathBucket = pathBucket; + public BucketDeleter(final String pathfield, final String pathbucket) { + this.pathfield = pathfield; + this.pathbucket = pathbucket; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/v2/RateLimits/Fields/{Field}/Bucket/{Bucket}"; - path = path.replace("{" + "Field" + "}", this.pathField.toString()); - path = path.replace("{" + "Bucket" + "}", this.pathBucket.toString()); + path = path.replace("{" + "Field" + "}", this.pathfield.toString()); + path = path.replace("{" + "Bucket" + "}", this.pathbucket.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.LOOKUPS.toString(), - path + HttpMethod.DELETE, + Domains.LOOKUPS.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Bucket delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("Bucket delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/lookups/v2/BucketFetcher.java b/src/main/java/com/twilio/rest/lookups/v2/BucketFetcher.java index c73c369da4..9157a7b504 100644 --- a/src/main/java/com/twilio/rest/lookups/v2/BucketFetcher.java +++ b/src/main/java/com/twilio/rest/lookups/v2/BucketFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.lookups.v2; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,47 +26,44 @@ public class BucketFetcher extends Fetcher { - private String pathField; - private String pathBucket; + private String pathfield; + private String pathbucket; - public BucketFetcher(final String pathField, final String pathBucket) { - this.pathField = pathField; - this.pathBucket = pathBucket; + public BucketFetcher(final String pathfield, final String pathbucket) { + this.pathfield = pathfield; + this.pathbucket = pathbucket; } + @Override public Bucket fetch(final TwilioRestClient client) { + String path = "/v2/RateLimits/Fields/{Field}/Bucket/{Bucket}"; - path = path.replace("{" + "Field" + "}", this.pathField.toString()); - path = path.replace("{" + "Bucket" + "}", this.pathBucket.toString()); + path = path.replace("{" + "Field" + "}", this.pathfield.toString()); + path = path.replace("{" + "Bucket" + "}", this.pathbucket.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.LOOKUPS.toString(), - path + HttpMethod.GET, + Domains.LOOKUPS.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Bucket fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Bucket fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Bucket.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/lookups/v2/BucketUpdater.java b/src/main/java/com/twilio/rest/lookups/v2/BucketUpdater.java index ebb98856f1..68a68c5e9c 100644 --- a/src/main/java/com/twilio/rest/lookups/v2/BucketUpdater.java +++ b/src/main/java/com/twilio/rest/lookups/v2/BucketUpdater.java @@ -27,52 +27,50 @@ import com.twilio.rest.Domains; public class BucketUpdater extends Updater { - - private String pathField; - private String pathBucket; + private String pathfield; + private String pathbucket; private Bucket.RateLimitRequest rateLimitRequest; - public BucketUpdater(final String pathField, final String pathBucket) { - this.pathField = pathField; - this.pathBucket = pathBucket; + public BucketUpdater(final String pathfield, final String pathbucket) { + this.pathfield = pathfield; + this.pathbucket = pathbucket; } - public BucketUpdater setRateLimitRequest( - final Bucket.RateLimitRequest rateLimitRequest - ) { + + public BucketUpdater setRateLimitRequest(final Bucket.RateLimitRequest rateLimitRequest) { this.rateLimitRequest = rateLimitRequest; return this; } + @Override public Bucket update(final TwilioRestClient client) { + String path = "/v2/RateLimits/Fields/{Field}/Bucket/{Bucket}"; - path = path.replace("{" + "Field" + "}", this.pathField.toString()); - path = path.replace("{" + "Bucket" + "}", this.pathBucket.toString()); + path = path.replace("{" + "Field" + "}", this.pathfield.toString()); + path = path.replace("{" + "Bucket" + "}", this.pathbucket.toString()); + Request request = new Request( - HttpMethod.PUT, - Domains.LOOKUPS.toString(), - path + HttpMethod.PUT, + Domains.LOOKUPS.toString(), + path ); request.setContentType(EnumConstants.ContentType.JSON); addPostParams(request, client); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Bucket update failed: Unable to connect to server" - ); + throw new ApiConnectionException("Bucket update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/lookups/v2/LookupOverride.java b/src/main/java/com/twilio/rest/lookups/v2/LookupOverride.java index 69b4c42558..75007d9dc3 100644 --- a/src/main/java/com/twilio/rest/lookups/v2/LookupOverride.java +++ b/src/main/java/com/twilio/rest/lookups/v2/LookupOverride.java @@ -22,26 +22,146 @@ import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.time.ZonedDateTime; import java.util.Objects; -import lombok.Getter; -import lombok.Setter; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class LookupOverride extends Resource { - private static final long serialVersionUID = 147188354779019L; + public static LookupOverrideCreator creator(final String pathfield, final String pathphoneNumber) { + return new LookupOverrideCreator( + pathfield, pathphoneNumber + ); + } + + + public static LookupOverrideDeleter deleter(final String pathfield, final String pathphoneNumber) { + return new LookupOverrideDeleter( + pathfield, pathphoneNumber + ); + } + + + public static LookupOverrideFetcher fetcher(final String pathfield, final String pathphoneNumber) { + return new LookupOverrideFetcher( + pathfield, pathphoneNumber + ); + } + + + public static LookupOverrideUpdater updater(final String pathfield, final String pathphoneNumber) { + return new LookupOverrideUpdater( + pathfield, pathphoneNumber + ); + } + + + public enum OverriddenLineType { + MOBILE("mobile"), + LANDLINE("landline"), + TOLL_FREE("tollFree"), + FIXED_VOIP("fixedVoip"), + NON_FIXED_VOIP("nonFixedVoip"), + PERSONAL("personal"), + PREMIUM("premium"), + VOICEMAIL("voicemail"), + SHARED_COST("sharedCost"), + UAN("uan"), + PAGER("pager"), + UNKNOWN("unknown"); + + private final String value; + + private OverriddenLineType(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static OverriddenLineType forValue(final String value) { + return Promoter.enumFromString(value, OverriddenLineType.values()); + } + } + + public enum LineType { + MOBILE("mobile"), + LANDLINE("landline"), + TOLL_FREE("tollFree"), + FIXED_VOIP("fixedVoip"), + NON_FIXED_VOIP("nonFixedVoip"), + PERSONAL("personal"), + PREMIUM("premium"), + VOICEMAIL("voicemail"), + SHARED_COST("sharedCost"), + UAN("uan"), + PAGER("pager"), + UNKNOWN("unknown"); + + private final String value; + + private LineType(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static LineType forValue(final String value) { + return Promoter.enumFromString(value, LineType.values()); + } + } + + public enum OriginalLineType { + MOBILE("mobile"), + LANDLINE("landline"), + TOLL_FREE("tollFree"), + FIXED_VOIP("fixedVoip"), + NON_FIXED_VOIP("nonFixedVoip"), + PERSONAL("personal"), + PREMIUM("premium"), + VOICEMAIL("voicemail"), + SHARED_COST("sharedCost"), + UAN("uan"), + PAGER("pager"), + UNKNOWN("unknown"); + + private final String value; + + private OriginalLineType(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static OriginalLineType forValue(final String value) { + return Promoter.enumFromString(value, OriginalLineType.values()); + } + } + + + //@JsonDeserialize(builder = OverridesRequest.Builder.class) + @JsonInclude(JsonInclude.Include.NON_EMPTY) @ToString public static class OverridesRequest { @@ -49,7 +169,7 @@ public static class OverridesRequest { @JsonProperty("line_type") @Getter @Setter - private LineTypeEnum lineType; + private LookupOverride.LineType lineType; @JsonInclude(JsonInclude.Include.NON_EMPTY) @JsonProperty("reason") @@ -57,55 +177,16 @@ public static class OverridesRequest { @Setter private String reason; - public OverridesRequest() {} - - public static OverridesRequest fromJson( - String jsonString, - ObjectMapper mapper - ) throws IOException { - return mapper.readValue(jsonString, OverridesRequest.class); - } - } - - public static LookupOverrideCreator creator( - final String pathField, - final String pathPhoneNumber - ) { - return new LookupOverrideCreator(pathField, pathPhoneNumber); - } - - public static LookupOverrideDeleter deleter( - final String pathField, - final String pathPhoneNumber - ) { - return new LookupOverrideDeleter(pathField, pathPhoneNumber); - } - - public static LookupOverrideFetcher fetcher( - final String pathField, - final String pathPhoneNumber - ) { - return new LookupOverrideFetcher(pathField, pathPhoneNumber); - } - - public static LookupOverrideUpdater updater( - final String pathField, - final String pathPhoneNumber - ) { - return new LookupOverrideUpdater(pathField, pathPhoneNumber); } /** * Converts a JSON String into a LookupOverride object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return LookupOverride object represented by the provided JSON */ - public static LookupOverride fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static LookupOverride fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, LookupOverride.class); @@ -120,14 +201,11 @@ public static LookupOverride fromJson( * Converts a JSON InputStream into a LookupOverride object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return LookupOverride object represented by the provided JSON */ - public static LookupOverride fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static LookupOverride fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, LookupOverride.class); @@ -150,59 +228,36 @@ public static String toJson(Object object, ObjectMapper mapper) { } } - private final String phoneNumber; - private final LookupOverride.OriginalLineTypeEnum originalLineType; - private final LookupOverride.OverriddenLineTypeEnum overriddenLineType; + + @Getter + private final LookupOverride.OriginalLineType originalLineType; + @Getter + private final String overriddenByAccountSid; + @Getter + private final LookupOverride.OverriddenLineType overriddenLineType; + @Getter private final String overrideReason; + @Getter private final ZonedDateTime overrideTimestamp; - private final String overriddenByAccountSid; + @Getter + private final String phoneNumber; @JsonCreator private LookupOverride( - @JsonProperty("phone_number") final String phoneNumber, - @JsonProperty( - "original_line_type" - ) final LookupOverride.OriginalLineTypeEnum originalLineType, - @JsonProperty( - "overridden_line_type" - ) final LookupOverride.OverriddenLineTypeEnum overriddenLineType, - @JsonProperty("override_reason") final String overrideReason, - @JsonProperty("override_timestamp") final String overrideTimestamp, - @JsonProperty( - "overridden_by_account_sid" - ) final String overriddenByAccountSid + @JsonProperty("original_line_type") final LookupOverride.OriginalLineType originalLineType, + @JsonProperty("overridden_by_account_sid") final String overriddenByAccountSid, + @JsonProperty("overridden_line_type") final LookupOverride.OverriddenLineType overriddenLineType, + @JsonProperty("override_reason") final String overrideReason, + @JsonProperty("override_timestamp") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime overrideTimestamp, + @JsonProperty("phone_number") final String phoneNumber ) { - this.phoneNumber = phoneNumber; this.originalLineType = originalLineType; + this.overriddenByAccountSid = overriddenByAccountSid; this.overriddenLineType = overriddenLineType; this.overrideReason = overrideReason; - this.overrideTimestamp = - DateConverter.iso8601DateTimeFromString(overrideTimestamp); - this.overriddenByAccountSid = overriddenByAccountSid; - } - - public final String getPhoneNumber() { - return this.phoneNumber; - } - - public final LookupOverride.OriginalLineTypeEnum getOriginalLineType() { - return this.originalLineType; - } - - public final LookupOverride.OverriddenLineTypeEnum getOverriddenLineType() { - return this.overriddenLineType; - } - - public final String getOverrideReason() { - return this.overrideReason; - } - - public final ZonedDateTime getOverrideTimestamp() { - return this.overrideTimestamp; - } - - public final String getOverriddenByAccountSid() { - return this.overriddenByAccountSid; + this.overrideTimestamp = overrideTimestamp; + this.phoneNumber = phoneNumber; } @Override @@ -216,122 +271,28 @@ public boolean equals(final Object o) { } LookupOverride other = (LookupOverride) o; - return ( - Objects.equals(phoneNumber, other.phoneNumber) && - Objects.equals(originalLineType, other.originalLineType) && - Objects.equals(overriddenLineType, other.overriddenLineType) && - Objects.equals(overrideReason, other.overrideReason) && - Objects.equals(overrideTimestamp, other.overrideTimestamp) && - Objects.equals(overriddenByAccountSid, other.overriddenByAccountSid) + Objects.equals(originalLineType, other.originalLineType) && + Objects.equals(overriddenByAccountSid, other.overriddenByAccountSid) && + Objects.equals(overriddenLineType, other.overriddenLineType) && + Objects.equals(overrideReason, other.overrideReason) && + Objects.equals(overrideTimestamp, other.overrideTimestamp) && + Objects.equals(phoneNumber, other.phoneNumber) ); } @Override public int hashCode() { return Objects.hash( - phoneNumber, - originalLineType, - overriddenLineType, - overrideReason, - overrideTimestamp, - overriddenByAccountSid + originalLineType, + overriddenByAccountSid, + overriddenLineType, + overrideReason, + overrideTimestamp, + phoneNumber ); } - public enum OverriddenLineTypeEnum { - MOBILE("mobile"), - LANDLINE("landline"), - TOLLFREE("tollFree"), - FIXEDVOIP("fixedVoip"), - NONFIXEDVOIP("nonFixedVoip"), - PERSONAL("personal"), - PREMIUM("premium"), - VOICEMAIL("voicemail"), - SHAREDCOST("sharedCost"), - UAN("uan"), - PAGER("pager"), - UNKNOWN("unknown"); - - private final String value; - - private OverriddenLineTypeEnum(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - @JsonCreator - public static OverriddenLineTypeEnum forValue(final String value) { - return Promoter.enumFromString( - value, - OverriddenLineTypeEnum.values() - ); - } - } - - public enum LineTypeEnum { - MOBILE("mobile"), - LANDLINE("landline"), - TOLLFREE("tollFree"), - FIXEDVOIP("fixedVoip"), - NONFIXEDVOIP("nonFixedVoip"), - PERSONAL("personal"), - PREMIUM("premium"), - VOICEMAIL("voicemail"), - SHAREDCOST("sharedCost"), - UAN("uan"), - PAGER("pager"), - UNKNOWN("unknown"); - - private final String value; - - private LineTypeEnum(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static LineTypeEnum forValue(final String value) { - return Promoter.enumFromString(value, LineTypeEnum.values()); - } - } - - public enum OriginalLineTypeEnum { - MOBILE("mobile"), - LANDLINE("landline"), - TOLLFREE("tollFree"), - FIXEDVOIP("fixedVoip"), - NONFIXEDVOIP("nonFixedVoip"), - PERSONAL("personal"), - PREMIUM("premium"), - VOICEMAIL("voicemail"), - SHAREDCOST("sharedCost"), - UAN("uan"), - PAGER("pager"), - UNKNOWN("unknown"); - - private final String value; - - private OriginalLineTypeEnum(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static OriginalLineTypeEnum forValue(final String value) { - return Promoter.enumFromString( - value, - OriginalLineTypeEnum.values() - ); - } - } } + diff --git a/src/main/java/com/twilio/rest/lookups/v2/LookupOverrideCreator.java b/src/main/java/com/twilio/rest/lookups/v2/LookupOverrideCreator.java index bdc0dc5304..095b0056aa 100644 --- a/src/main/java/com/twilio/rest/lookups/v2/LookupOverrideCreator.java +++ b/src/main/java/com/twilio/rest/lookups/v2/LookupOverrideCreator.java @@ -28,74 +28,61 @@ public class LookupOverrideCreator extends Creator { - private String pathField; - private String pathPhoneNumber; + private String pathfield; + private String pathphoneNumber; private LookupOverride.OverridesRequest overridesRequest; - public LookupOverrideCreator( - final String pathField, - final String pathPhoneNumber - ) { - this.pathField = pathField; - this.pathPhoneNumber = pathPhoneNumber; + public LookupOverrideCreator(final String pathfield, final String pathphoneNumber) { + this.pathfield = pathfield; + this.pathphoneNumber = pathphoneNumber; } - public LookupOverrideCreator setOverridesRequest( - final LookupOverride.OverridesRequest overridesRequest - ) { + + public LookupOverrideCreator setOverridesRequest(final LookupOverride.OverridesRequest overridesRequest) { this.overridesRequest = overridesRequest; return this; } + @Override public LookupOverride create(final TwilioRestClient client) { + String path = "/v2/PhoneNumbers/{PhoneNumber}/Overrides/{Field}"; - path = path.replace("{" + "Field" + "}", this.pathField.toString()); - path = - path.replace( - "{" + "PhoneNumber" + "}", - this.pathPhoneNumber.toString() - ); + path = path.replace("{" + "Field" + "}", this.pathfield.toString()); + path = path.replace("{" + "PhoneNumber" + "}", this.pathphoneNumber.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.LOOKUPS.toString(), - path + HttpMethod.POST, + Domains.LOOKUPS.toString(), + path ); request.setContentType(EnumConstants.ContentType.JSON); addPostParams(request, client); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "LookupOverride creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("LookupOverride creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return LookupOverride.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return LookupOverride.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request, TwilioRestClient client) { ObjectMapper objectMapper = client.getObjectMapper(); if (overridesRequest != null) { - request.setBody( - LookupOverride.toJson(overridesRequest, objectMapper) - ); + request.setBody(LookupOverride.toJson(overridesRequest, objectMapper)); } } } diff --git a/src/main/java/com/twilio/rest/lookups/v2/LookupOverrideDeleter.java b/src/main/java/com/twilio/rest/lookups/v2/LookupOverrideDeleter.java index 7a13b9fcf0..78eb0fdb10 100644 --- a/src/main/java/com/twilio/rest/lookups/v2/LookupOverrideDeleter.java +++ b/src/main/java/com/twilio/rest/lookups/v2/LookupOverrideDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.lookups.v2; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,50 +26,41 @@ public class LookupOverrideDeleter extends Deleter { - private String pathField; - private String pathPhoneNumber; + private String pathfield; + private String pathphoneNumber; - public LookupOverrideDeleter( - final String pathField, - final String pathPhoneNumber - ) { - this.pathField = pathField; - this.pathPhoneNumber = pathPhoneNumber; + public LookupOverrideDeleter(final String pathfield, final String pathphoneNumber) { + this.pathfield = pathfield; + this.pathphoneNumber = pathphoneNumber; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/v2/PhoneNumbers/{PhoneNumber}/Overrides/{Field}"; - path = path.replace("{" + "Field" + "}", this.pathField.toString()); - path = - path.replace( - "{" + "PhoneNumber" + "}", - this.pathPhoneNumber.toString() - ); + path = path.replace("{" + "Field" + "}", this.pathfield.toString()); + path = path.replace("{" + "PhoneNumber" + "}", this.pathphoneNumber.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.LOOKUPS.toString(), - path + HttpMethod.DELETE, + Domains.LOOKUPS.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "LookupOverride delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("LookupOverride delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/lookups/v2/LookupOverrideFetcher.java b/src/main/java/com/twilio/rest/lookups/v2/LookupOverrideFetcher.java index f345b4a4e4..1ff5f78452 100644 --- a/src/main/java/com/twilio/rest/lookups/v2/LookupOverrideFetcher.java +++ b/src/main/java/com/twilio/rest/lookups/v2/LookupOverrideFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.lookups.v2; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,57 +26,44 @@ public class LookupOverrideFetcher extends Fetcher { - private String pathField; - private String pathPhoneNumber; + private String pathfield; + private String pathphoneNumber; - public LookupOverrideFetcher( - final String pathField, - final String pathPhoneNumber - ) { - this.pathField = pathField; - this.pathPhoneNumber = pathPhoneNumber; + public LookupOverrideFetcher(final String pathfield, final String pathphoneNumber) { + this.pathfield = pathfield; + this.pathphoneNumber = pathphoneNumber; } + @Override public LookupOverride fetch(final TwilioRestClient client) { + String path = "/v2/PhoneNumbers/{PhoneNumber}/Overrides/{Field}"; - path = path.replace("{" + "Field" + "}", this.pathField.toString()); - path = - path.replace( - "{" + "PhoneNumber" + "}", - this.pathPhoneNumber.toString() - ); + path = path.replace("{" + "Field" + "}", this.pathfield.toString()); + path = path.replace("{" + "PhoneNumber" + "}", this.pathphoneNumber.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.LOOKUPS.toString(), - path + HttpMethod.GET, + Domains.LOOKUPS.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "LookupOverride fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("LookupOverride fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return LookupOverride.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return LookupOverride.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/lookups/v2/LookupOverrideUpdater.java b/src/main/java/com/twilio/rest/lookups/v2/LookupOverrideUpdater.java index 5674e6110a..da7416753b 100644 --- a/src/main/java/com/twilio/rest/lookups/v2/LookupOverrideUpdater.java +++ b/src/main/java/com/twilio/rest/lookups/v2/LookupOverrideUpdater.java @@ -27,75 +27,61 @@ import com.twilio.rest.Domains; public class LookupOverrideUpdater extends Updater { - - private String pathField; - private String pathPhoneNumber; + private String pathfield; + private String pathphoneNumber; private LookupOverride.OverridesRequest overridesRequest; - public LookupOverrideUpdater( - final String pathField, - final String pathPhoneNumber - ) { - this.pathField = pathField; - this.pathPhoneNumber = pathPhoneNumber; + public LookupOverrideUpdater(final String pathfield, final String pathphoneNumber) { + this.pathfield = pathfield; + this.pathphoneNumber = pathphoneNumber; } - public LookupOverrideUpdater setOverridesRequest( - final LookupOverride.OverridesRequest overridesRequest - ) { + + public LookupOverrideUpdater setOverridesRequest(final LookupOverride.OverridesRequest overridesRequest) { this.overridesRequest = overridesRequest; return this; } + @Override public LookupOverride update(final TwilioRestClient client) { + String path = "/v2/PhoneNumbers/{PhoneNumber}/Overrides/{Field}"; - path = path.replace("{" + "Field" + "}", this.pathField.toString()); - path = - path.replace( - "{" + "PhoneNumber" + "}", - this.pathPhoneNumber.toString() - ); + path = path.replace("{" + "Field" + "}", this.pathfield.toString()); + path = path.replace("{" + "PhoneNumber" + "}", this.pathphoneNumber.toString()); + Request request = new Request( - HttpMethod.PUT, - Domains.LOOKUPS.toString(), - path + HttpMethod.PUT, + Domains.LOOKUPS.toString(), + path ); request.setContentType(EnumConstants.ContentType.JSON); addPostParams(request, client); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "LookupOverride update failed: Unable to connect to server" - ); + throw new ApiConnectionException("LookupOverride update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return LookupOverride.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return LookupOverride.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request, TwilioRestClient client) { ObjectMapper objectMapper = client.getObjectMapper(); if (overridesRequest != null) { - request.setBody( - LookupOverride.toJson(overridesRequest, objectMapper) - ); + request.setBody(LookupOverride.toJson(overridesRequest, objectMapper)); } } } diff --git a/src/main/java/com/twilio/rest/lookups/v2/PhoneNumber.java b/src/main/java/com/twilio/rest/lookups/v2/PhoneNumber.java index 0bed3d57d4..27c04ae665 100644 --- a/src/main/java/com/twilio/rest/lookups/v2/PhoneNumber.java +++ b/src/main/java/com/twilio/rest/lookups/v2/PhoneNumber.java @@ -18,43 +18,91 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.util.List; -import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class PhoneNumber extends Resource { - private static final long serialVersionUID = 129217577072488L; - public static PhoneNumberFetcher fetcher(final String pathPhoneNumber) { - return new PhoneNumberFetcher(pathPhoneNumber); + public static PhoneNumberFetcher fetcher(final String pathphoneNumber) { + return new PhoneNumberFetcher( + pathphoneNumber + ); } + + public enum PhoneNumberValidationError { + TOO_SHORT("TOO_SHORT"), + TOO_LONG("TOO_LONG"), + INVALID_BUT_POSSIBLE("INVALID_BUT_POSSIBLE"), + INVALID_COUNTRY_CODE("INVALID_COUNTRY_CODE"), + INVALID_LENGTH("INVALID_LENGTH"), + NOT_A_NUMBER("NOT_A_NUMBER"); + + private final String value; + + private PhoneNumberValidationError(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static PhoneNumberValidationError forValue(final String value) { + return Promoter.enumFromString(value, PhoneNumberValidationError.values()); + } + } + + public enum ValidationError { + TOO_SHORT("TOO_SHORT"), + TOO_LONG("TOO_LONG"), + INVALID_BUT_POSSIBLE("INVALID_BUT_POSSIBLE"), + INVALID_COUNTRY_CODE("INVALID_COUNTRY_CODE"), + INVALID_LENGTH("INVALID_LENGTH"), + NOT_A_NUMBER("NOT_A_NUMBER"); + + private final String value; + + private ValidationError(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static ValidationError forValue(final String value) { + return Promoter.enumFromString(value, ValidationError.values()); + } + } + + /** * Converts a JSON String into a PhoneNumber object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return PhoneNumber object represented by the provided JSON */ - public static PhoneNumber fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static PhoneNumber fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, PhoneNumber.class); @@ -69,14 +117,11 @@ public static PhoneNumber fromJson( * Converts a JSON InputStream into a PhoneNumber object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return PhoneNumber object represented by the provided JSON */ - public static PhoneNumber fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static PhoneNumber fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, PhoneNumber.class); @@ -87,148 +132,91 @@ public static PhoneNumber fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter + private final Object callForwarding; + @Getter + private final Object callerName; + @Getter private final String callingCountryCode; + @Getter private final String countryCode; - private final com.twilio.type.PhoneNumber phoneNumber; + @Getter + private final Object identityMatch; + @Getter + private final Object lineStatus; + @Getter + private final Object lineTypeIntelligence; + @Getter private final String nationalFormat; - private final Boolean valid; - private final List validationErrors; - private final Map callerName; - private final Map simSwap; - private final Map callForwarding; - private final Map lineStatus; - private final Map lineTypeIntelligence; - private final Map identityMatch; - private final Map reassignedNumber; - private final Map smsPumpingRisk; - private final Map phoneNumberQualityScore; - private final Map preFill; + @Getter + private final com.twilio.type.PhoneNumber phoneNumber; + @Getter + private final Object phoneNumberQualityScore; + @Getter + private final Object preFill; + @Getter + private final Object reassignedNumber; + @Getter + private final Object simSwap; + @Getter + private final Object smsPumpingRisk; + @Getter private final URI url; + @Getter + private final Boolean valid; + @Getter + private final List validationErrors; @JsonCreator private PhoneNumber( - @JsonProperty("calling_country_code") final String callingCountryCode, - @JsonProperty("country_code") final String countryCode, - @JsonProperty( - "phone_number" - ) final com.twilio.type.PhoneNumber phoneNumber, - @JsonProperty("national_format") final String nationalFormat, - @JsonProperty("valid") final Boolean valid, - @JsonProperty("validation_errors") final List< - PhoneNumber.ValidationError - > validationErrors, - @JsonProperty("caller_name") final Map callerName, - @JsonProperty("sim_swap") final Map simSwap, - @JsonProperty("call_forwarding") final Map< - String, - Object - > callForwarding, - @JsonProperty("line_status") final Map lineStatus, - @JsonProperty("line_type_intelligence") final Map< - String, - Object - > lineTypeIntelligence, - @JsonProperty("identity_match") final Map identityMatch, - @JsonProperty("reassigned_number") final Map< - String, - Object - > reassignedNumber, - @JsonProperty("sms_pumping_risk") final Map< - String, - Object - > smsPumpingRisk, - @JsonProperty("phone_number_quality_score") final Map< - String, - Object - > phoneNumberQualityScore, - @JsonProperty("pre_fill") final Map preFill, - @JsonProperty("url") final URI url + @JsonProperty("call_forwarding") final Object callForwarding, + @JsonProperty("caller_name") final Object callerName, + @JsonProperty("calling_country_code") final String callingCountryCode, + @JsonProperty("country_code") final String countryCode, + @JsonProperty("identity_match") final Object identityMatch, + @JsonProperty("line_status") final Object lineStatus, + @JsonProperty("line_type_intelligence") final Object lineTypeIntelligence, + @JsonProperty("national_format") final String nationalFormat, + @JsonProperty("phone_number") final com.twilio.type.PhoneNumber phoneNumber, + @JsonProperty("phone_number_quality_score") final Object phoneNumberQualityScore, + @JsonProperty("pre_fill") final Object preFill, + @JsonProperty("reassigned_number") final Object reassignedNumber, + @JsonProperty("sim_swap") final Object simSwap, + @JsonProperty("sms_pumping_risk") final Object smsPumpingRisk, + @JsonProperty("url") final URI url, + @JsonProperty("valid") final Boolean valid, + @JsonProperty("validation_errors") final List validationErrors ) { + this.callForwarding = callForwarding; + this.callerName = callerName; this.callingCountryCode = callingCountryCode; this.countryCode = countryCode; - this.phoneNumber = phoneNumber; - this.nationalFormat = nationalFormat; - this.valid = valid; - this.validationErrors = validationErrors; - this.callerName = callerName; - this.simSwap = simSwap; - this.callForwarding = callForwarding; + this.identityMatch = identityMatch; this.lineStatus = lineStatus; this.lineTypeIntelligence = lineTypeIntelligence; - this.identityMatch = identityMatch; - this.reassignedNumber = reassignedNumber; - this.smsPumpingRisk = smsPumpingRisk; + this.nationalFormat = nationalFormat; + this.phoneNumber = phoneNumber; this.phoneNumberQualityScore = phoneNumberQualityScore; this.preFill = preFill; + this.reassignedNumber = reassignedNumber; + this.simSwap = simSwap; + this.smsPumpingRisk = smsPumpingRisk; this.url = url; - } - - public final String getCallingCountryCode() { - return this.callingCountryCode; - } - - public final String getCountryCode() { - return this.countryCode; - } - - public final com.twilio.type.PhoneNumber getPhoneNumber() { - return this.phoneNumber; - } - - public final String getNationalFormat() { - return this.nationalFormat; - } - - public final Boolean getValid() { - return this.valid; - } - - public final List getValidationErrors() { - return this.validationErrors; - } - - public final Map getCallerName() { - return this.callerName; - } - - public final Map getSimSwap() { - return this.simSwap; - } - - public final Map getCallForwarding() { - return this.callForwarding; - } - - public final Map getLineStatus() { - return this.lineStatus; - } - - public final Map getLineTypeIntelligence() { - return this.lineTypeIntelligence; - } - - public final Map getIdentityMatch() { - return this.identityMatch; - } - - public final Map getReassignedNumber() { - return this.reassignedNumber; - } - - public final Map getSmsPumpingRisk() { - return this.smsPumpingRisk; - } - - public final Map getPhoneNumberQualityScore() { - return this.phoneNumberQualityScore; - } - - public final Map getPreFill() { - return this.preFill; - } - - public final URI getUrl() { - return this.url; + this.valid = valid; + this.validationErrors = validationErrors; } @Override @@ -242,75 +230,50 @@ public boolean equals(final Object o) { } PhoneNumber other = (PhoneNumber) o; - return ( - Objects.equals(callingCountryCode, other.callingCountryCode) && - Objects.equals(countryCode, other.countryCode) && - Objects.equals(phoneNumber, other.phoneNumber) && - Objects.equals(nationalFormat, other.nationalFormat) && - Objects.equals(valid, other.valid) && - Objects.equals(validationErrors, other.validationErrors) && - Objects.equals(callerName, other.callerName) && - Objects.equals(simSwap, other.simSwap) && - Objects.equals(callForwarding, other.callForwarding) && - Objects.equals(lineStatus, other.lineStatus) && - Objects.equals(lineTypeIntelligence, other.lineTypeIntelligence) && - Objects.equals(identityMatch, other.identityMatch) && - Objects.equals(reassignedNumber, other.reassignedNumber) && - Objects.equals(smsPumpingRisk, other.smsPumpingRisk) && - Objects.equals( - phoneNumberQualityScore, - other.phoneNumberQualityScore - ) && - Objects.equals(preFill, other.preFill) && - Objects.equals(url, other.url) + Objects.equals(callForwarding, other.callForwarding) && + Objects.equals(callerName, other.callerName) && + Objects.equals(callingCountryCode, other.callingCountryCode) && + Objects.equals(countryCode, other.countryCode) && + Objects.equals(identityMatch, other.identityMatch) && + Objects.equals(lineStatus, other.lineStatus) && + Objects.equals(lineTypeIntelligence, other.lineTypeIntelligence) && + Objects.equals(nationalFormat, other.nationalFormat) && + Objects.equals(phoneNumber, other.phoneNumber) && + Objects.equals(phoneNumberQualityScore, other.phoneNumberQualityScore) && + Objects.equals(preFill, other.preFill) && + Objects.equals(reassignedNumber, other.reassignedNumber) && + Objects.equals(simSwap, other.simSwap) && + Objects.equals(smsPumpingRisk, other.smsPumpingRisk) && + Objects.equals(url, other.url) && + Objects.equals(valid, other.valid) && + Objects.equals(validationErrors, other.validationErrors) ); } @Override public int hashCode() { return Objects.hash( - callingCountryCode, - countryCode, - phoneNumber, - nationalFormat, - valid, - validationErrors, - callerName, - simSwap, - callForwarding, - lineStatus, - lineTypeIntelligence, - identityMatch, - reassignedNumber, - smsPumpingRisk, - phoneNumberQualityScore, - preFill, - url + callForwarding, + callerName, + callingCountryCode, + countryCode, + identityMatch, + lineStatus, + lineTypeIntelligence, + nationalFormat, + phoneNumber, + phoneNumberQualityScore, + preFill, + reassignedNumber, + simSwap, + smsPumpingRisk, + url, + valid, + validationErrors ); } - public enum ValidationError { - TOO_SHORT("TOO_SHORT"), - TOO_LONG("TOO_LONG"), - INVALID_BUT_POSSIBLE("INVALID_BUT_POSSIBLE"), - INVALID_COUNTRY_CODE("INVALID_COUNTRY_CODE"), - INVALID_LENGTH("INVALID_LENGTH"), - NOT_A_NUMBER("NOT_A_NUMBER"); - - private final String value; - - private ValidationError(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - @JsonCreator - public static ValidationError forValue(final String value) { - return Promoter.enumFromString(value, ValidationError.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/lookups/v2/PhoneNumberFetcher.java b/src/main/java/com/twilio/rest/lookups/v2/PhoneNumberFetcher.java index b5060fa7a2..7456756337 100644 --- a/src/main/java/com/twilio/rest/lookups/v2/PhoneNumberFetcher.java +++ b/src/main/java/com/twilio/rest/lookups/v2/PhoneNumberFetcher.java @@ -15,7 +15,8 @@ package com.twilio.rest.lookups.v2; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,7 +28,7 @@ public class PhoneNumberFetcher extends Fetcher { - private String pathPhoneNumber; + private String pathphoneNumber; private String fields; private String countryCode; private String firstName; @@ -44,177 +45,210 @@ public class PhoneNumberFetcher extends Fetcher { private String verificationSid; private String partnerSubId; - public PhoneNumberFetcher(final String pathPhoneNumber) { - this.pathPhoneNumber = pathPhoneNumber; + public PhoneNumberFetcher(final String pathphoneNumber) { + this.pathphoneNumber = pathphoneNumber; } + public PhoneNumberFetcher setFields(final String fields) { this.fields = fields; return this; } + public PhoneNumberFetcher setCountryCode(final String countryCode) { this.countryCode = countryCode; return this; } + public PhoneNumberFetcher setFirstName(final String firstName) { this.firstName = firstName; return this; } + public PhoneNumberFetcher setLastName(final String lastName) { this.lastName = lastName; return this; } + public PhoneNumberFetcher setAddressLine1(final String addressLine1) { this.addressLine1 = addressLine1; return this; } + public PhoneNumberFetcher setAddressLine2(final String addressLine2) { this.addressLine2 = addressLine2; return this; } + public PhoneNumberFetcher setCity(final String city) { this.city = city; return this; } + public PhoneNumberFetcher setState(final String state) { this.state = state; return this; } + public PhoneNumberFetcher setPostalCode(final String postalCode) { this.postalCode = postalCode; return this; } - public PhoneNumberFetcher setAddressCountryCode( - final String addressCountryCode - ) { + + public PhoneNumberFetcher setAddressCountryCode(final String addressCountryCode) { this.addressCountryCode = addressCountryCode; return this; } + public PhoneNumberFetcher setNationalId(final String nationalId) { this.nationalId = nationalId; return this; } + public PhoneNumberFetcher setDateOfBirth(final String dateOfBirth) { this.dateOfBirth = dateOfBirth; return this; } - public PhoneNumberFetcher setLastVerifiedDate( - final String lastVerifiedDate - ) { + + public PhoneNumberFetcher setLastVerifiedDate(final String lastVerifiedDate) { this.lastVerifiedDate = lastVerifiedDate; return this; } + public PhoneNumberFetcher setVerificationSid(final String verificationSid) { this.verificationSid = verificationSid; return this; } + public PhoneNumberFetcher setPartnerSubId(final String partnerSubId) { this.partnerSubId = partnerSubId; return this; } + @Override public PhoneNumber fetch(final TwilioRestClient client) { + String path = "/v2/PhoneNumbers/{PhoneNumber}"; - path = - path.replace( - "{" + "PhoneNumber" + "}", - this.pathPhoneNumber.toString() - ); + path = path.replace("{" + "PhoneNumber" + "}", this.pathphoneNumber.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.LOOKUPS.toString(), - path + HttpMethod.GET, + Domains.LOOKUPS.toString(), + path ); addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "PhoneNumber fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("PhoneNumber fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return PhoneNumber.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return PhoneNumber.fromJson(response.getStream(), client.getObjectMapper()); } private void addQueryParams(final Request request) { + + if (fields != null) { - request.addQueryParam("Fields", fields); + Serializer.toString(request, "Fields", fields, ParameterType.QUERY); } + + if (countryCode != null) { - request.addQueryParam("CountryCode", countryCode); + Serializer.toString(request, "CountryCode", countryCode, ParameterType.QUERY); } + + if (firstName != null) { - request.addQueryParam("FirstName", firstName); + Serializer.toString(request, "FirstName", firstName, ParameterType.QUERY); } + + if (lastName != null) { - request.addQueryParam("LastName", lastName); + Serializer.toString(request, "LastName", lastName, ParameterType.QUERY); } + + if (addressLine1 != null) { - request.addQueryParam("AddressLine1", addressLine1); + Serializer.toString(request, "AddressLine1", addressLine1, ParameterType.QUERY); } + + if (addressLine2 != null) { - request.addQueryParam("AddressLine2", addressLine2); + Serializer.toString(request, "AddressLine2", addressLine2, ParameterType.QUERY); } + + if (city != null) { - request.addQueryParam("City", city); + Serializer.toString(request, "City", city, ParameterType.QUERY); } + + if (state != null) { - request.addQueryParam("State", state); + Serializer.toString(request, "State", state, ParameterType.QUERY); } + + if (postalCode != null) { - request.addQueryParam("PostalCode", postalCode); + Serializer.toString(request, "PostalCode", postalCode, ParameterType.QUERY); } + + if (addressCountryCode != null) { - request.addQueryParam("AddressCountryCode", addressCountryCode); + Serializer.toString(request, "AddressCountryCode", addressCountryCode, ParameterType.QUERY); } + + if (nationalId != null) { - request.addQueryParam("NationalId", nationalId); + Serializer.toString(request, "NationalId", nationalId, ParameterType.QUERY); } + + if (dateOfBirth != null) { - request.addQueryParam("DateOfBirth", dateOfBirth); + Serializer.toString(request, "DateOfBirth", dateOfBirth, ParameterType.QUERY); } + + if (lastVerifiedDate != null) { - request.addQueryParam("LastVerifiedDate", lastVerifiedDate); + Serializer.toString(request, "LastVerifiedDate", lastVerifiedDate, ParameterType.QUERY); } + + if (verificationSid != null) { - request.addQueryParam("VerificationSid", verificationSid); + Serializer.toString(request, "VerificationSid", verificationSid, ParameterType.QUERY); } + + if (partnerSubId != null) { - request.addQueryParam("PartnerSubId", partnerSubId); + Serializer.toString(request, "PartnerSubId", partnerSubId, ParameterType.QUERY); } + + } } diff --git a/src/main/java/com/twilio/rest/lookups/v2/Query.java b/src/main/java/com/twilio/rest/lookups/v2/Query.java index 14e8748259..c9ee538059 100644 --- a/src/main/java/com/twilio/rest/lookups/v2/Query.java +++ b/src/main/java/com/twilio/rest/lookups/v2/Query.java @@ -22,184 +22,216 @@ import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.time.ZonedDateTime; import java.util.List; import java.util.Objects; -import lombok.Getter; -import lombok.Setter; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Query extends Resource { - private static final long serialVersionUID = 115616150775512L; + public static QueryCreator creator() { + return new QueryCreator( + + ); + } + + + public enum Fields { + CALLER_NAME("caller_name"), + SIM_SWAP("sim_swap"), + CALL_FORWARDING("call_forwarding"), + LINE_TYPE_INTELLIGENCE("line_type_intelligence"), + LINE_STATUS("line_status"), + IDENTITY_MATCH("identity_match"), + REASSIGNED_NUMBER("reassigned_number"), + SMS_PUMPING_RISK("sms_pumping_risk"); + + private final String value; + + private Fields(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static Fields forValue(final String value) { + return Promoter.enumFromString(value, Fields.values()); + } + } + + + //@JsonDeserialize(builder = LineTypeIntelligence.Builder.class) + @JsonInclude(JsonInclude.Include.NON_EMPTY) @ToString - public static class IdentityMatchParameters { + public static class LineTypeIntelligence { @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("first_name") + @JsonProperty("type") @Getter @Setter - private String firstName; + private String type; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("last_name") + @JsonProperty("carrier_name") @Getter @Setter - private String lastName; + private String carrierName; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("address_line1") + @JsonProperty("mobile_country_code") @Getter @Setter - private String addressLine1; + private String mobileCountryCode; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("address_line2") + @JsonProperty("mobile_network_code") @Getter @Setter - private String addressLine2; + private String mobileNetworkCode; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("city") + @JsonProperty("error_code") @Getter @Setter - private String city; + private Integer errorCode; + + } + + //@JsonDeserialize(builder = IdentityMatch.Builder.class) + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @ToString + public static class IdentityMatch { @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("state") + @JsonProperty("first_name_match") @Getter @Setter - private String state; + private String firstNameMatch; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("postal_code") + @JsonProperty("last_name_match") @Getter @Setter - private String postalCode; + private String lastNameMatch; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("address_country_code") + @JsonProperty("address_line_match") @Getter @Setter - private String addressCountryCode; + private String addressLineMatch; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("national_id") + @JsonProperty("city_match") @Getter @Setter - private String nationalId; + private String cityMatch; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("date_of_birth") + @JsonProperty("state_match") @Getter @Setter - private String dateOfBirth; - - public static IdentityMatchParameters fromJson( - String jsonString, - ObjectMapper mapper - ) throws IOException { - return mapper.readValue(jsonString, IdentityMatchParameters.class); - } - } - - @ToString - public static class ReassignedNumberRequest { + private String stateMatch; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("last_verified_date") + @JsonProperty("postal_code_match") @Getter @Setter - private String lastVerifiedDate; - - public static ReassignedNumberRequest fromJson( - String jsonString, - ObjectMapper mapper - ) throws IOException { - return mapper.readValue(jsonString, ReassignedNumberRequest.class); - } - } - - @ToString - public static class SmsPumpingRiskParameters { + private String postalCodeMatch; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("partner_sub_id") + @JsonProperty("country_code_match") @Getter @Setter - private String partnerSubId; + private String countryCodeMatch; - public static SmsPumpingRiskParameters fromJson( - String jsonString, - ObjectMapper mapper - ) throws IOException { - return mapper.readValue(jsonString, SmsPumpingRiskParameters.class); - } - } + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("national_id_match") + @Getter + @Setter + private String nationalIdMatch; - @ToString - public static class LookupRequestWithCorId { + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("date_of_birth_match") + @Getter + @Setter + private String dateOfBirthMatch; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("correlation_id") + @JsonProperty("summary_score") @Getter @Setter - private String correlationId; + private Integer summaryScore; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("phone_number") + @JsonProperty("error_code") @Getter @Setter - private String phoneNumber; + private Integer errorCode; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("fields") + @JsonProperty("error_message") @Getter @Setter - private List fields; + private String errorMessage; + + } + + //@JsonDeserialize(builder = ReassignedNumberResponse.Builder.class) + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @ToString + public static class ReassignedNumberResponse { @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("country_code") + @JsonProperty("last_verified_date") @Getter @Setter - private String countryCode; + private String lastVerifiedDate; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("identity_match") + @JsonProperty("is_number_reassigned") @Getter @Setter - private IdentityMatchParameters identityMatch; + private String isNumberReassigned; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("reassigned_number") + @JsonProperty("error_code") @Getter @Setter - private ReassignedNumberRequest reassignedNumber; + private String errorCode; + + } + + //@JsonDeserialize(builder = ReassignedNumberRequest.Builder.class) + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @ToString + public static class ReassignedNumberRequest { @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("sms_pumping_risk") + @JsonProperty("last_verified_date") @Getter @Setter - private SmsPumpingRiskParameters smsPumpingRisk; + private String lastVerifiedDate; - public static LookupRequestWithCorId fromJson( - String jsonString, - ObjectMapper mapper - ) throws IOException { - return mapper.readValue(jsonString, LookupRequestWithCorId.class); - } } + //@JsonDeserialize(builder = LookupRequest1.Builder.class) + @JsonInclude(JsonInclude.Include.NON_EMPTY) @ToString public static class LookupRequest1 { @@ -209,316 +241,275 @@ public static class LookupRequest1 { @Setter private List phoneNumbers; - public LookupRequest1() {} - - public static LookupRequest1 fromJson( - String jsonString, - ObjectMapper mapper - ) throws IOException { - return mapper.readValue(jsonString, LookupRequest1.class); - } } + //@JsonDeserialize(builder = LastSimSwap.Builder.class) + @JsonInclude(JsonInclude.Include.NON_EMPTY) @ToString - public static class CallerName { + public static class LastSimSwap { + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("caller_name") + @JsonProperty("last_sim_swap_date") @Getter @Setter - private String callerName; + private ZonedDateTime lastSimSwapDate; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("caller_type") + @JsonProperty("swapped_period") @Getter @Setter - private String callerType; + private String swappedPeriod; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("error_code") + @JsonProperty("swapped_in_period") @Getter @Setter - private Integer errorCode; + private Boolean swappedInPeriod; - public static CallerName fromJson( - String jsonString, - ObjectMapper mapper - ) throws IOException { - return mapper.readValue(jsonString, CallerName.class); - } } + //@JsonDeserialize(builder = LineStatus.Builder.class) + @JsonInclude(JsonInclude.Include.NON_EMPTY) @ToString - public static class LastSimSwap { + public static class LineStatus { @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("last_sim_swap_date") + @JsonProperty("status") @Getter @Setter - private ZonedDateTime lastSimSwapDate; - - public String getLastSimSwapDate() { - return lastSimSwapDate.toInstant().toString(); - } + private String status; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("swapped_period") + @JsonProperty("error_code") @Getter @Setter - private String swappedPeriod; + private Integer errorCode; + + } + + //@JsonDeserialize(builder = SmsPumpingRiskParameters.Builder.class) + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @ToString + public static class SmsPumpingRiskParameters { @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("swapped_in_period") + @JsonProperty("partner_sub_id") @Getter @Setter - private Boolean swappedInPeriod; + private String partnerSubId; - public static LastSimSwap fromJson( - String jsonString, - ObjectMapper mapper - ) throws IOException { - return mapper.readValue(jsonString, LastSimSwap.class); - } } + //@JsonDeserialize(builder = LookupResponseWithCorId.Builder.class) + @JsonInclude(JsonInclude.Include.NON_EMPTY) @ToString - public static class SimSwap { + public static class LookupResponseWithCorId { @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("last_sim_swap") + @JsonProperty("correlation_id") @Getter @Setter - private LastSimSwap lastSimSwap; + private String correlationId; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("carrier_name") + @JsonProperty("twilio_error_code") @Getter @Setter - private String carrierName; + private Integer twilioErrorCode; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("mobile_country_code") + @JsonProperty("calling_country_code") @Getter @Setter - private String mobileCountryCode; + private String callingCountryCode; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("mobile_network_code") + @JsonProperty("country_code") @Getter @Setter - private String mobileNetworkCode; + private String countryCode; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("error_code") + @JsonProperty("phone_number") @Getter @Setter - private Integer errorCode; - - public static SimSwap fromJson(String jsonString, ObjectMapper mapper) - throws IOException { - return mapper.readValue(jsonString, SimSwap.class); - } - } - - @ToString - public static class CallForwarding { + private String phoneNumber; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("call_forwarding_enabled") + @JsonProperty("national_format") @Getter @Setter - private Boolean callForwardingEnabled; + private String nationalFormat; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("error_code") + @JsonProperty("valid") @Getter @Setter - private Integer errorCode; - - public static CallForwarding fromJson( - String jsonString, - ObjectMapper mapper - ) throws IOException { - return mapper.readValue(jsonString, CallForwarding.class); - } - } - - @ToString - public static class LineTypeIntelligence { + private Boolean valid; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("type") + @JsonProperty("validation_errors") @Getter @Setter - private String type; + private List validationErrors; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("carrier_name") + @JsonProperty("caller_name") @Getter @Setter - private String carrierName; + private CallerName callerName; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("mobile_country_code") + @JsonProperty("sim_swap") @Getter @Setter - private String mobileCountryCode; + private SimSwap simSwap; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("mobile_network_code") + @JsonProperty("call_forwarding") @Getter @Setter - private String mobileNetworkCode; + private CallForwarding callForwarding; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("error_code") + @JsonProperty("line_type_intelligence") @Getter @Setter - private Integer errorCode; + private LineTypeIntelligence lineTypeIntelligence; - public static LineTypeIntelligence fromJson( - String jsonString, - ObjectMapper mapper - ) throws IOException { - return mapper.readValue(jsonString, LineTypeIntelligence.class); - } - } + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("line_status") + @Getter + @Setter + private LineStatus lineStatus; - @ToString - public static class LineStatus { + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("identity_match") + @Getter + @Setter + private IdentityMatch identityMatch; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("status") + @JsonProperty("reassigned_number") @Getter @Setter - private String status; + private ReassignedNumberResponse reassignedNumber; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("error_code") + @JsonProperty("sms_pumping_risk") @Getter @Setter - private Integer errorCode; + private SmsPumpingRisk smsPumpingRisk; - public static LineStatus fromJson( - String jsonString, - ObjectMapper mapper - ) throws IOException { - return mapper.readValue(jsonString, LineStatus.class); - } } + //@JsonDeserialize(builder = SimSwap.Builder.class) + @JsonInclude(JsonInclude.Include.NON_EMPTY) @ToString - public static class IdentityMatch { + public static class SimSwap { @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("first_name_match") + @JsonProperty("last_sim_swap") @Getter @Setter - private String firstNameMatch; + private LastSimSwap lastSimSwap; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("last_name_match") + @JsonProperty("carrier_name") @Getter @Setter - private String lastNameMatch; + private String carrierName; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("address_line_match") + @JsonProperty("mobile_country_code") @Getter @Setter - private String addressLineMatch; + private String mobileCountryCode; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("city_match") + @JsonProperty("mobile_network_code") @Getter @Setter - private String cityMatch; + private String mobileNetworkCode; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("state_match") + @JsonProperty("error_code") @Getter @Setter - private String stateMatch; + private Integer errorCode; + + } + + //@JsonDeserialize(builder = IdentityMatchParameters.Builder.class) + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @ToString + public static class IdentityMatchParameters { @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("postal_code_match") + @JsonProperty("first_name") @Getter @Setter - private String postalCodeMatch; + private String firstName; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("country_code_match") + @JsonProperty("last_name") @Getter @Setter - private String countryCodeMatch; + private String lastName; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("national_id_match") + @JsonProperty("address_line1") @Getter @Setter - private String nationalIdMatch; + private String addressLine1; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("date_of_birth_match") + @JsonProperty("address_line2") @Getter @Setter - private String dateOfBirthMatch; + private String addressLine2; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("summary_score") + @JsonProperty("city") @Getter @Setter - private Integer summaryScore; + private String city; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("error_code") + @JsonProperty("state") @Getter @Setter - private Integer errorCode; + private String state; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("error_message") + @JsonProperty("postal_code") @Getter @Setter - private String errorMessage; - - public static IdentityMatch fromJson( - String jsonString, - ObjectMapper mapper - ) throws IOException { - return mapper.readValue(jsonString, IdentityMatch.class); - } - } - - @ToString - public static class ReassignedNumberResponse { + private String postalCode; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("last_verified_date") + @JsonProperty("address_country_code") @Getter @Setter - private String lastVerifiedDate; + private String addressCountryCode; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("is_number_reassigned") + @JsonProperty("national_id") @Getter @Setter - private String isNumberReassigned; + private String nationalId; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("error_code") + @JsonProperty("date_of_birth") @Getter @Setter - private String errorCode; + private String dateOfBirth; - public static ReassignedNumberResponse fromJson( - String jsonString, - ObjectMapper mapper - ) throws IOException { - return mapper.readValue(jsonString, ReassignedNumberResponse.class); - } } + //@JsonDeserialize(builder = SmsPumpingRisk.Builder.class) + @JsonInclude(JsonInclude.Include.NON_EMPTY) @ToString public static class SmsPumpingRisk { @@ -534,16 +525,13 @@ public static class SmsPumpingRisk { @Setter private Boolean numberBlocked; + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) @JsonInclude(JsonInclude.Include.NON_EMPTY) @JsonProperty("number_blocked_date") @Getter @Setter private ZonedDateTime numberBlockedDate; - public String getNumberBlockedDate() { - return numberBlockedDate.toInstant().toString(); - } - @JsonInclude(JsonInclude.Include.NON_EMPTY) @JsonProperty("number_blocked_last_3_months") @Getter @@ -562,16 +550,15 @@ public String getNumberBlockedDate() { @Setter private Integer errorCode; - public static SmsPumpingRisk fromJson( - String jsonString, - ObjectMapper mapper - ) throws IOException { - return mapper.readValue(jsonString, SmsPumpingRisk.class); - } } + //@JsonDeserialize(builder = LookupRequestWithCorId.Builder.class) + @JsonInclude(JsonInclude.Include.NON_EMPTY) @ToString - public static class LookupResponseWithCorId { + public static class LookupRequestWithCorId { + public LookupRequestWithCorId(final String phoneNumber) { + this.phoneNumber = phoneNumber; + } @JsonInclude(JsonInclude.Include.NON_EMPTY) @JsonProperty("correlation_id") @@ -580,16 +567,16 @@ public static class LookupResponseWithCorId { private String correlationId; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("twilio_error_code") + @JsonProperty("phone_number") @Getter @Setter - private Integer twilioErrorCode; + private String phoneNumber; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("calling_country_code") + @JsonProperty("fields") @Getter @Setter - private String callingCountryCode; + private List fields; @JsonInclude(JsonInclude.Include.NON_EMPTY) @JsonProperty("country_code") @@ -598,100 +585,77 @@ public static class LookupResponseWithCorId { private String countryCode; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("phone_number") + @JsonProperty("identity_match") @Getter @Setter - private String phoneNumber; + private IdentityMatchParameters identityMatch; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("national_format") + @JsonProperty("reassigned_number") @Getter @Setter - private String nationalFormat; + private ReassignedNumberRequest reassignedNumber; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("valid") + @JsonProperty("sms_pumping_risk") @Getter @Setter - private Boolean valid; + private SmsPumpingRiskParameters smsPumpingRisk; - @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("validation_errors") - @Getter - @Setter - private List validationErrors; + } - @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("caller_name") - @Getter - @Setter - private CallerName callerName; + //@JsonDeserialize(builder = CallerName.Builder.class) + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @ToString + public static class CallerName { @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("sim_swap") + @JsonProperty("caller_name") @Getter @Setter - private SimSwap simSwap; + private String callerName; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("call_forwarding") + @JsonProperty("caller_type") @Getter @Setter - private CallForwarding callForwarding; + private String callerType; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("line_type_intelligence") + @JsonProperty("error_code") @Getter @Setter - private LineTypeIntelligence lineTypeIntelligence; + private Integer errorCode; - @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("line_status") - @Getter - @Setter - private LineStatus lineStatus; + } - @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("identity_match") - @Getter - @Setter - private IdentityMatch identityMatch; + //@JsonDeserialize(builder = CallForwarding.Builder.class) + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @ToString + public static class CallForwarding { @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("reassigned_number") + @JsonProperty("call_forwarding_enabled") @Getter @Setter - private ReassignedNumberResponse reassignedNumber; + private Boolean callForwardingEnabled; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("sms_pumping_risk") + @JsonProperty("error_code") @Getter @Setter - private SmsPumpingRisk smsPumpingRisk; - - public static LookupResponseWithCorId fromJson( - String jsonString, - ObjectMapper mapper - ) throws IOException { - return mapper.readValue(jsonString, LookupResponseWithCorId.class); - } - } + private Integer errorCode; - public static QueryCreator creator() { - return new QueryCreator(); } /** * Converts a JSON String into a Query object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Query object represented by the provided JSON */ - public static Query fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Query fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Query.class); @@ -706,14 +670,11 @@ public static Query fromJson( * Converts a JSON InputStream into a Query object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Query object represented by the provided JSON */ - public static Query fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Query fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Query.class); @@ -736,21 +697,17 @@ public static String toJson(Object object, ObjectMapper mapper) { } } + + @Getter private final List phoneNumbers; @JsonCreator private Query( - @JsonProperty("phone_numbers") final List< - LookupResponseWithCorId - > phoneNumbers + @JsonProperty("phone_numbers") final List phoneNumbers ) { this.phoneNumbers = phoneNumbers; } - public final List getPhoneNumbers() { - return this.phoneNumbers; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -762,38 +719,18 @@ public boolean equals(final Object o) { } Query other = (Query) o; - - return Objects.equals(phoneNumbers, other.phoneNumbers); + return ( + Objects.equals(phoneNumbers, other.phoneNumbers) + ); } @Override public int hashCode() { - return Objects.hash(phoneNumbers); + return Objects.hash( + phoneNumbers + ); } - public enum FieldsEnum { - CALLER_NAME("caller_name"), - SIM_SWAP("sim_swap"), - CALL_FORWARDING("call_forwarding"), - LINE_TYPE_INTELLIGENCE("line_type_intelligence"), - LINE_STATUS("line_status"), - IDENTITY_MATCH("identity_match"), - REASSIGNED_NUMBER("reassigned_number"), - SMS_PUMPING_RISK("sms_pumping_risk"); - - private final String value; - - private FieldsEnum(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - @JsonCreator - public static FieldsEnum forValue(final String value) { - return Promoter.enumFromString(value, FieldsEnum.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/lookups/v2/QueryCreator.java b/src/main/java/com/twilio/rest/lookups/v2/QueryCreator.java index e7481c28d8..54070561a1 100644 --- a/src/main/java/com/twilio/rest/lookups/v2/QueryCreator.java +++ b/src/main/java/com/twilio/rest/lookups/v2/QueryCreator.java @@ -30,41 +30,41 @@ public class QueryCreator extends Creator { private Query.LookupRequest1 lookupRequest1; - public QueryCreator() {} + public QueryCreator() { + } + - public QueryCreator setLookupRequest1( - final Query.LookupRequest1 lookupRequest1 - ) { + public QueryCreator setLookupRequest1(final Query.LookupRequest1 lookupRequest1) { this.lookupRequest1 = lookupRequest1; return this; } + @Override public Query create(final TwilioRestClient client) { + String path = "/v2/batch/query"; + Request request = new Request( - HttpMethod.POST, - Domains.LOOKUPS.toString(), - path + HttpMethod.POST, + Domains.LOOKUPS.toString(), + path ); request.setContentType(EnumConstants.ContentType.JSON); addPostParams(request, client); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Query creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("Query creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/lookups/v2/RateLimit.java b/src/main/java/com/twilio/rest/lookups/v2/RateLimit.java index 0551523fd0..563e22a61e 100644 --- a/src/main/java/com/twilio/rest/lookups/v2/RateLimit.java +++ b/src/main/java/com/twilio/rest/lookups/v2/RateLimit.java @@ -19,26 +19,35 @@ import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.util.List; import java.util.Objects; -import lombok.Getter; -import lombok.Setter; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class RateLimit extends Resource { - private static final long serialVersionUID = 36869169584327L; + public static RateLimitFetcher fetcher() { + return new RateLimitFetcher( + + ); + } + + + //@JsonDeserialize(builder = RateLimitResponse.Builder.class) + @JsonInclude(JsonInclude.Include.NON_EMPTY) @ToString public static class RateLimitResponse { @@ -72,29 +81,16 @@ public static class RateLimitResponse { @Setter private Integer ttl; - public static RateLimitResponse fromJson( - String jsonString, - ObjectMapper mapper - ) throws IOException { - return mapper.readValue(jsonString, RateLimitResponse.class); - } - } - - public static RateLimitFetcher fetcher() { - return new RateLimitFetcher(); } /** * Converts a JSON String into a RateLimit object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return RateLimit object represented by the provided JSON */ - public static RateLimit fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static RateLimit fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, RateLimit.class); @@ -109,14 +105,11 @@ public static RateLimit fromJson( * Converts a JSON InputStream into a RateLimit object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return RateLimit object represented by the provided JSON */ - public static RateLimit fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static RateLimit fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, RateLimit.class); @@ -127,19 +120,29 @@ public static RateLimit fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final List rateLimits; @JsonCreator private RateLimit( - @JsonProperty("rate_limits") final List rateLimits + @JsonProperty("rate_limits") final List rateLimits ) { this.rateLimits = rateLimits; } - public final List getRateLimits() { - return this.rateLimits; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -151,12 +154,18 @@ public boolean equals(final Object o) { } RateLimit other = (RateLimit) o; - - return Objects.equals(rateLimits, other.rateLimits); + return ( + Objects.equals(rateLimits, other.rateLimits) + ); } @Override public int hashCode() { - return Objects.hash(rateLimits); + return Objects.hash( + rateLimits + ); } + + } + diff --git a/src/main/java/com/twilio/rest/lookups/v2/RateLimitFetcher.java b/src/main/java/com/twilio/rest/lookups/v2/RateLimitFetcher.java index 8d3e241b82..db6e8f4d80 100644 --- a/src/main/java/com/twilio/rest/lookups/v2/RateLimitFetcher.java +++ b/src/main/java/com/twilio/rest/lookups/v2/RateLimitFetcher.java @@ -15,8 +15,9 @@ package com.twilio.rest.lookups.v2; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; import com.twilio.converter.Promoter; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,13 +26,16 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.util.List; public class RateLimitFetcher extends Fetcher { private List fields; - public RateLimitFetcher() {} + public RateLimitFetcher() { + } + public RateLimitFetcher setFields(final List fields) { this.fields = fields; @@ -44,46 +48,42 @@ public RateLimitFetcher setFields(final String fields) { @Override public RateLimit fetch(final TwilioRestClient client) { + String path = "/v2/RateLimits"; + Request request = new Request( - HttpMethod.GET, - Domains.LOOKUPS.toString(), - path + HttpMethod.GET, + Domains.LOOKUPS.toString(), + path ); addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "RateLimit fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("RateLimit fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return RateLimit.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return RateLimit.fromJson(response.getStream(), client.getObjectMapper()); } private void addQueryParams(final Request request) { + + if (fields != null) { - for (String prop : fields) { - request.addQueryParam("Fields", prop); + for (String param : fields) { + Serializer.toString(request, "Fields", param, ParameterType.QUERY); } } + } } diff --git a/src/main/java/com/twilio/rest/marketplace/v1/AvailableAddOn.java b/src/main/java/com/twilio/rest/marketplace/v1/AvailableAddOn.java index 415f190f8b..bf11358c68 100644 --- a/src/main/java/com/twilio/rest/marketplace/v1/AvailableAddOn.java +++ b/src/main/java/com/twilio/rest/marketplace/v1/AvailableAddOn.java @@ -18,45 +18,48 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class AvailableAddOn extends Resource { - private static final long serialVersionUID = 265387241353044L; - public static AvailableAddOnFetcher fetcher(final String pathSid) { - return new AvailableAddOnFetcher(pathSid); + public static AvailableAddOnFetcher fetcher(final String pathsid) { + return new AvailableAddOnFetcher( + pathsid + ); } + public static AvailableAddOnReader reader() { - return new AvailableAddOnReader(); + return new AvailableAddOnReader( + + ); } + /** * Converts a JSON String into a AvailableAddOn object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return AvailableAddOn object represented by the provided JSON */ - public static AvailableAddOn fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static AvailableAddOn fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, AvailableAddOn.class); @@ -71,14 +74,11 @@ public static AvailableAddOn fromJson( * Converts a JSON InputStream into a AvailableAddOn object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return AvailableAddOn object represented by the provided JSON */ - public static AvailableAddOn fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static AvailableAddOn fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, AvailableAddOn.class); @@ -89,62 +89,51 @@ public static AvailableAddOn fromJson( } } - private final String sid; - private final String friendlyName; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter + private final Object configurationSchema; + @Getter private final String description; + @Getter + private final String friendlyName; + @Getter + private final Map links; + @Getter private final String pricingType; - private final Map configurationSchema; + @Getter + private final String sid; + @Getter private final URI url; - private final Map links; @JsonCreator private AvailableAddOn( - @JsonProperty("sid") final String sid, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("description") final String description, - @JsonProperty("pricing_type") final String pricingType, - @JsonProperty("configuration_schema") final Map< - String, - Object - > configurationSchema, - @JsonProperty("url") final URI url, - @JsonProperty("links") final Map links + @JsonProperty("configuration_schema") final Object configurationSchema, + @JsonProperty("description") final String description, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("links") final Map links, + @JsonProperty("pricing_type") final String pricingType, + @JsonProperty("sid") final String sid, + @JsonProperty("url") final URI url ) { - this.sid = sid; - this.friendlyName = friendlyName; + this.configurationSchema = configurationSchema; this.description = description; + this.friendlyName = friendlyName; + this.links = links; this.pricingType = pricingType; - this.configurationSchema = configurationSchema; + this.sid = sid; this.url = url; - this.links = links; - } - - public final String getSid() { - return this.sid; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final String getDescription() { - return this.description; - } - - public final String getPricingType() { - return this.pricingType; - } - - public final Map getConfigurationSchema() { - return this.configurationSchema; - } - - public final URI getUrl() { - return this.url; - } - - public final Map getLinks() { - return this.links; } @Override @@ -158,28 +147,30 @@ public boolean equals(final Object o) { } AvailableAddOn other = (AvailableAddOn) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(description, other.description) && - Objects.equals(pricingType, other.pricingType) && - Objects.equals(configurationSchema, other.configurationSchema) && - Objects.equals(url, other.url) && - Objects.equals(links, other.links) + Objects.equals(configurationSchema, other.configurationSchema) && + Objects.equals(description, other.description) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(links, other.links) && + Objects.equals(pricingType, other.pricingType) && + Objects.equals(sid, other.sid) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - sid, - friendlyName, - description, - pricingType, - configurationSchema, - url, - links + configurationSchema, + description, + friendlyName, + links, + pricingType, + sid, + url ); } + + } + diff --git a/src/main/java/com/twilio/rest/marketplace/v1/AvailableAddOnFetcher.java b/src/main/java/com/twilio/rest/marketplace/v1/AvailableAddOnFetcher.java index c2146d280e..edd635a8bc 100644 --- a/src/main/java/com/twilio/rest/marketplace/v1/AvailableAddOnFetcher.java +++ b/src/main/java/com/twilio/rest/marketplace/v1/AvailableAddOnFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.marketplace.v1; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,47 +26,41 @@ public class AvailableAddOnFetcher extends Fetcher { - private String pathSid; + private String pathsid; - public AvailableAddOnFetcher(final String pathSid) { - this.pathSid = pathSid; + public AvailableAddOnFetcher(final String pathsid) { + this.pathsid = pathsid; } + @Override public AvailableAddOn fetch(final TwilioRestClient client) { + String path = "/v1/AvailableAddOns/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.MARKETPLACE.toString(), - path + HttpMethod.GET, + Domains.MARKETPLACE.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "AvailableAddOn fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("AvailableAddOn fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return AvailableAddOn.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return AvailableAddOn.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/marketplace/v1/AvailableAddOnReader.java b/src/main/java/com/twilio/rest/marketplace/v1/AvailableAddOnReader.java index 8c46f9e43e..007acaa5ab 100644 --- a/src/main/java/com/twilio/rest/marketplace/v1/AvailableAddOnReader.java +++ b/src/main/java/com/twilio/rest/marketplace/v1/AvailableAddOnReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -31,105 +32,83 @@ public class AvailableAddOnReader extends Reader { private Integer pageSize; - public AvailableAddOnReader() {} + public AvailableAddOnReader() { + } + public AvailableAddOnReader setPageSize(final Integer pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/AvailableAddOns"; + Request request = new Request( - HttpMethod.GET, - Domains.MARKETPLACE.toString(), - path + HttpMethod.GET, + Domains.MARKETPLACE.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "AvailableAddOn read failed: Unable to connect to server" - ); + throw new ApiConnectionException("AvailableAddOn read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "available_add_ons", - response.getContent(), - AvailableAddOn.class, - client.getObjectMapper() - ); + "available_add_ons", + response.getContent(), + AvailableAddOn.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.MARKETPLACE.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.MARKETPLACE.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/marketplace/v1/InstalledAddOn.java b/src/main/java/com/twilio/rest/marketplace/v1/InstalledAddOn.java index 801aa781b7..ec5caccf1e 100644 --- a/src/main/java/com/twilio/rest/marketplace/v1/InstalledAddOn.java +++ b/src/main/java/com/twilio/rest/marketplace/v1/InstalledAddOn.java @@ -18,65 +18,71 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class InstalledAddOn extends Resource { - private static final long serialVersionUID = 250400645130930L; - public static InstalledAddOnCreator creator( - final String availableAddOnSid, - final Boolean acceptTermsOfService - ) { + public static InstalledAddOnCreator creator(final String availableAddOnSid, final Boolean acceptTermsOfService) { return new InstalledAddOnCreator( - availableAddOnSid, - acceptTermsOfService + availableAddOnSid, acceptTermsOfService ); } - public static InstalledAddOnDeleter deleter(final String pathSid) { - return new InstalledAddOnDeleter(pathSid); + + public static InstalledAddOnDeleter deleter(final String pathsid) { + return new InstalledAddOnDeleter( + pathsid + ); } - public static InstalledAddOnFetcher fetcher(final String pathSid) { - return new InstalledAddOnFetcher(pathSid); + + public static InstalledAddOnFetcher fetcher(final String pathsid) { + return new InstalledAddOnFetcher( + pathsid + ); } + public static InstalledAddOnReader reader() { - return new InstalledAddOnReader(); + return new InstalledAddOnReader( + + ); } - public static InstalledAddOnUpdater updater(final String pathSid) { - return new InstalledAddOnUpdater(pathSid); + + public static InstalledAddOnUpdater updater(final String pathsid) { + return new InstalledAddOnUpdater( + pathsid + ); } + /** * Converts a JSON String into a InstalledAddOn object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return InstalledAddOn object represented by the provided JSON */ - public static InstalledAddOn fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static InstalledAddOn fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, InstalledAddOn.class); @@ -91,14 +97,11 @@ public static InstalledAddOn fromJson( * Converts a JSON InputStream into a InstalledAddOn object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return InstalledAddOn object represented by the provided JSON */ - public static InstalledAddOn fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static InstalledAddOn fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, InstalledAddOn.class); @@ -109,80 +112,65 @@ public static InstalledAddOn fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String friendlyName; - private final String description; - private final Map configuration; - private final String uniqueName; + @Getter + private final Object configuration; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; - private final URI url; + @Getter + private final String description; + @Getter + private final String friendlyName; + @Getter private final Map links; + @Getter + private final String sid; + @Getter + private final String uniqueName; + @Getter + private final URI url; @JsonCreator private InstalledAddOn( - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("description") final String description, - @JsonProperty("configuration") final Map configuration, - @JsonProperty("unique_name") final String uniqueName, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("url") final URI url, - @JsonProperty("links") final Map links + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("configuration") final Object configuration, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("description") final String description, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("links") final Map links, + @JsonProperty("sid") final String sid, + @JsonProperty("unique_name") final String uniqueName, + @JsonProperty("url") final URI url ) { - this.sid = sid; this.accountSid = accountSid; - this.friendlyName = friendlyName; - this.description = description; this.configuration = configuration; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; + this.description = description; + this.friendlyName = friendlyName; + this.links = links; + this.sid = sid; this.uniqueName = uniqueName; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); this.url = url; - this.links = links; - } - - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final String getDescription() { - return this.description; - } - - public final Map getConfiguration() { - return this.configuration; - } - - public final String getUniqueName() { - return this.uniqueName; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final URI getUrl() { - return this.url; - } - - public final Map getLinks() { - return this.links; } @Override @@ -196,34 +184,36 @@ public boolean equals(final Object o) { } InstalledAddOn other = (InstalledAddOn) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(description, other.description) && - Objects.equals(configuration, other.configuration) && - Objects.equals(uniqueName, other.uniqueName) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(url, other.url) && - Objects.equals(links, other.links) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(configuration, other.configuration) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(description, other.description) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(links, other.links) && + Objects.equals(sid, other.sid) && + Objects.equals(uniqueName, other.uniqueName) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - sid, - accountSid, - friendlyName, - description, - configuration, - uniqueName, - dateCreated, - dateUpdated, - url, - links + accountSid, + configuration, + dateCreated, + dateUpdated, + description, + friendlyName, + links, + sid, + uniqueName, + url ); } + + } + diff --git a/src/main/java/com/twilio/rest/marketplace/v1/InstalledAddOnCreator.java b/src/main/java/com/twilio/rest/marketplace/v1/InstalledAddOnCreator.java index daafa5c509..846ecb6848 100644 --- a/src/main/java/com/twilio/rest/marketplace/v1/InstalledAddOnCreator.java +++ b/src/main/java/com/twilio/rest/marketplace/v1/InstalledAddOnCreator.java @@ -14,10 +14,11 @@ package com.twilio.rest.marketplace.v1; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; -import com.twilio.converter.Converter; -import com.twilio.converter.Converter; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -34,103 +35,89 @@ public class InstalledAddOnCreator extends Creator { private Object configuration; private String uniqueName; - public InstalledAddOnCreator( - final String availableAddOnSid, - final Boolean acceptTermsOfService - ) { + public InstalledAddOnCreator(final String availableAddOnSid, final Boolean acceptTermsOfService) { this.availableAddOnSid = availableAddOnSid; this.acceptTermsOfService = acceptTermsOfService; } - public InstalledAddOnCreator setAvailableAddOnSid( - final String availableAddOnSid - ) { + + public InstalledAddOnCreator setAvailableAddOnSid(final String availableAddOnSid) { this.availableAddOnSid = availableAddOnSid; return this; } - public InstalledAddOnCreator setAcceptTermsOfService( - final Boolean acceptTermsOfService - ) { + + public InstalledAddOnCreator setAcceptTermsOfService(final Boolean acceptTermsOfService) { this.acceptTermsOfService = acceptTermsOfService; return this; } + public InstalledAddOnCreator setConfiguration(final Object configuration) { this.configuration = configuration; return this; } + public InstalledAddOnCreator setUniqueName(final String uniqueName) { this.uniqueName = uniqueName; return this; } + @Override public InstalledAddOn create(final TwilioRestClient client) { + String path = "/v1/InstalledAddOns"; - path = - path.replace( - "{" + "AvailableAddOnSid" + "}", - this.availableAddOnSid.toString() - ); - path = - path.replace( - "{" + "AcceptTermsOfService" + "}", - this.acceptTermsOfService.toString() - ); Request request = new Request( - HttpMethod.POST, - Domains.MARKETPLACE.toString(), - path + HttpMethod.POST, + Domains.MARKETPLACE.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "InstalledAddOn creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("InstalledAddOn creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return InstalledAddOn.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return InstalledAddOn.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (availableAddOnSid != null) { - request.addPostParam("AvailableAddOnSid", availableAddOnSid); + Serializer.toString(request, "AvailableAddOnSid", availableAddOnSid, ParameterType.URLENCODED); } + + if (acceptTermsOfService != null) { - request.addPostParam( - "AcceptTermsOfService", - acceptTermsOfService.toString() - ); + Serializer.toString(request, "AcceptTermsOfService", acceptTermsOfService, ParameterType.URLENCODED); } + + if (configuration != null) { - request.addPostParam( - "Configuration", - Converter.objectToJson(configuration) - ); + Serializer.toString(request, "Configuration", configuration, ParameterType.URLENCODED); } + + if (uniqueName != null) { - request.addPostParam("UniqueName", uniqueName); + Serializer.toString(request, "UniqueName", uniqueName, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/marketplace/v1/InstalledAddOnDeleter.java b/src/main/java/com/twilio/rest/marketplace/v1/InstalledAddOnDeleter.java index f282cbcb30..2c897bad38 100644 --- a/src/main/java/com/twilio/rest/marketplace/v1/InstalledAddOnDeleter.java +++ b/src/main/java/com/twilio/rest/marketplace/v1/InstalledAddOnDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.marketplace.v1; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,40 +26,38 @@ public class InstalledAddOnDeleter extends Deleter { - private String pathSid; + private String pathsid; - public InstalledAddOnDeleter(final String pathSid) { - this.pathSid = pathSid; + public InstalledAddOnDeleter(final String pathsid) { + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/v1/InstalledAddOns/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.MARKETPLACE.toString(), - path + HttpMethod.DELETE, + Domains.MARKETPLACE.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "InstalledAddOn delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("InstalledAddOn delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/marketplace/v1/InstalledAddOnFetcher.java b/src/main/java/com/twilio/rest/marketplace/v1/InstalledAddOnFetcher.java index f1cc561538..d3c054e650 100644 --- a/src/main/java/com/twilio/rest/marketplace/v1/InstalledAddOnFetcher.java +++ b/src/main/java/com/twilio/rest/marketplace/v1/InstalledAddOnFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.marketplace.v1; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,47 +26,41 @@ public class InstalledAddOnFetcher extends Fetcher { - private String pathSid; + private String pathsid; - public InstalledAddOnFetcher(final String pathSid) { - this.pathSid = pathSid; + public InstalledAddOnFetcher(final String pathsid) { + this.pathsid = pathsid; } + @Override public InstalledAddOn fetch(final TwilioRestClient client) { + String path = "/v1/InstalledAddOns/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.MARKETPLACE.toString(), - path + HttpMethod.GET, + Domains.MARKETPLACE.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "InstalledAddOn fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("InstalledAddOn fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return InstalledAddOn.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return InstalledAddOn.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/marketplace/v1/InstalledAddOnReader.java b/src/main/java/com/twilio/rest/marketplace/v1/InstalledAddOnReader.java index b63b2fb040..4d48a42d14 100644 --- a/src/main/java/com/twilio/rest/marketplace/v1/InstalledAddOnReader.java +++ b/src/main/java/com/twilio/rest/marketplace/v1/InstalledAddOnReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -31,105 +32,83 @@ public class InstalledAddOnReader extends Reader { private Integer pageSize; - public InstalledAddOnReader() {} + public InstalledAddOnReader() { + } + public InstalledAddOnReader setPageSize(final Integer pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/InstalledAddOns"; + Request request = new Request( - HttpMethod.GET, - Domains.MARKETPLACE.toString(), - path + HttpMethod.GET, + Domains.MARKETPLACE.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "InstalledAddOn read failed: Unable to connect to server" - ); + throw new ApiConnectionException("InstalledAddOn read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "installed_add_ons", - response.getContent(), - InstalledAddOn.class, - client.getObjectMapper() - ); + "installed_add_ons", + response.getContent(), + InstalledAddOn.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.MARKETPLACE.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.MARKETPLACE.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/marketplace/v1/InstalledAddOnUpdater.java b/src/main/java/com/twilio/rest/marketplace/v1/InstalledAddOnUpdater.java index 4863943fb4..f77ebdfb96 100644 --- a/src/main/java/com/twilio/rest/marketplace/v1/InstalledAddOnUpdater.java +++ b/src/main/java/com/twilio/rest/marketplace/v1/InstalledAddOnUpdater.java @@ -16,7 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; -import com.twilio.converter.Converter; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,72 +28,72 @@ import com.twilio.rest.Domains; public class InstalledAddOnUpdater extends Updater { - - private String pathSid; + private String pathsid; private Object configuration; private String uniqueName; - public InstalledAddOnUpdater(final String pathSid) { - this.pathSid = pathSid; + public InstalledAddOnUpdater(final String pathsid) { + this.pathsid = pathsid; } + public InstalledAddOnUpdater setConfiguration(final Object configuration) { this.configuration = configuration; return this; } + public InstalledAddOnUpdater setUniqueName(final String uniqueName) { this.uniqueName = uniqueName; return this; } + @Override public InstalledAddOn update(final TwilioRestClient client) { + String path = "/v1/InstalledAddOns/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.MARKETPLACE.toString(), - path + HttpMethod.POST, + Domains.MARKETPLACE.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "InstalledAddOn update failed: Unable to connect to server" - ); + throw new ApiConnectionException("InstalledAddOn update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return InstalledAddOn.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return InstalledAddOn.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (configuration != null) { - request.addPostParam( - "Configuration", - Converter.objectToJson(configuration) - ); + Serializer.toString(request, "Configuration", configuration, ParameterType.URLENCODED); } + + if (uniqueName != null) { - request.addPostParam("UniqueName", uniqueName); + Serializer.toString(request, "UniqueName", uniqueName, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/marketplace/v1/ModuleData.java b/src/main/java/com/twilio/rest/marketplace/v1/ModuleData.java index f76398f843..c11dbfb298 100644 --- a/src/main/java/com/twilio/rest/marketplace/v1/ModuleData.java +++ b/src/main/java/com/twilio/rest/marketplace/v1/ModuleData.java @@ -18,46 +18,48 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.util.List; -import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class ModuleData extends Resource { - private static final long serialVersionUID = 132859226086963L; public static ModuleDataCreator creator() { - return new ModuleDataCreator(); + return new ModuleDataCreator( + + ); } + public static ModuleDataFetcher fetcher() { - return new ModuleDataFetcher(); + return new ModuleDataFetcher( + + ); } + /** * Converts a JSON String into a ModuleData object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return ModuleData object represented by the provided JSON */ - public static ModuleData fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static ModuleData fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, ModuleData.class); @@ -72,14 +74,11 @@ public static ModuleData fromJson( * Converts a JSON InputStream into a ModuleData object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return ModuleData object represented by the provided JSON */ - public static ModuleData fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static ModuleData fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, ModuleData.class); @@ -90,80 +89,63 @@ public static ModuleData fromJson( } } - private final URI url; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter + private final Object configuration; + @Getter + private final Object description; + @Getter + private final Object documentation; + @Getter + private final List listings; + @Getter + private final Object moduleInfo; + @Getter + private final Object policies; + @Getter + private final Object pricing; + @Getter private final String sid; - private final Map description; - private final Map support; - private final Map policies; - private final Map moduleInfo; - private final Map documentation; - private final Map configuration; - private final Map pricing; - private final List> listings; + @Getter + private final Object support; + @Getter + private final URI url; @JsonCreator private ModuleData( - @JsonProperty("url") final URI url, - @JsonProperty("sid") final String sid, - @JsonProperty("description") final Map description, - @JsonProperty("support") final Map support, - @JsonProperty("policies") final Map policies, - @JsonProperty("module_info") final Map moduleInfo, - @JsonProperty("documentation") final Map documentation, - @JsonProperty("configuration") final Map configuration, - @JsonProperty("pricing") final Map pricing, - @JsonProperty("listings") final List> listings + @JsonProperty("configuration") final Object configuration, + @JsonProperty("description") final Object description, + @JsonProperty("documentation") final Object documentation, + @JsonProperty("listings") final List listings, + @JsonProperty("module_info") final Object moduleInfo, + @JsonProperty("policies") final Object policies, + @JsonProperty("pricing") final Object pricing, + @JsonProperty("sid") final String sid, + @JsonProperty("support") final Object support, + @JsonProperty("url") final URI url ) { - this.url = url; - this.sid = sid; + this.configuration = configuration; this.description = description; - this.support = support; - this.policies = policies; - this.moduleInfo = moduleInfo; this.documentation = documentation; - this.configuration = configuration; - this.pricing = pricing; this.listings = listings; - } - - public final URI getUrl() { - return this.url; - } - - public final String getSid() { - return this.sid; - } - - public final Map getDescription() { - return this.description; - } - - public final Map getSupport() { - return this.support; - } - - public final Map getPolicies() { - return this.policies; - } - - public final Map getModuleInfo() { - return this.moduleInfo; - } - - public final Map getDocumentation() { - return this.documentation; - } - - public final Map getConfiguration() { - return this.configuration; - } - - public final Map getPricing() { - return this.pricing; - } - - public final List> getListings() { - return this.listings; + this.moduleInfo = moduleInfo; + this.policies = policies; + this.pricing = pricing; + this.sid = sid; + this.support = support; + this.url = url; } @Override @@ -177,34 +159,36 @@ public boolean equals(final Object o) { } ModuleData other = (ModuleData) o; - return ( - Objects.equals(url, other.url) && - Objects.equals(sid, other.sid) && - Objects.equals(description, other.description) && - Objects.equals(support, other.support) && - Objects.equals(policies, other.policies) && - Objects.equals(moduleInfo, other.moduleInfo) && - Objects.equals(documentation, other.documentation) && - Objects.equals(configuration, other.configuration) && - Objects.equals(pricing, other.pricing) && - Objects.equals(listings, other.listings) + Objects.equals(configuration, other.configuration) && + Objects.equals(description, other.description) && + Objects.equals(documentation, other.documentation) && + Objects.equals(listings, other.listings) && + Objects.equals(moduleInfo, other.moduleInfo) && + Objects.equals(policies, other.policies) && + Objects.equals(pricing, other.pricing) && + Objects.equals(sid, other.sid) && + Objects.equals(support, other.support) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - url, - sid, - description, - support, - policies, - moduleInfo, - documentation, - configuration, - pricing, - listings + configuration, + description, + documentation, + listings, + moduleInfo, + policies, + pricing, + sid, + support, + url ); } + + } + diff --git a/src/main/java/com/twilio/rest/marketplace/v1/ModuleDataCreator.java b/src/main/java/com/twilio/rest/marketplace/v1/ModuleDataCreator.java index 08bd2419af..4e0b7373d2 100644 --- a/src/main/java/com/twilio/rest/marketplace/v1/ModuleDataCreator.java +++ b/src/main/java/com/twilio/rest/marketplace/v1/ModuleDataCreator.java @@ -14,8 +14,11 @@ package com.twilio.rest.marketplace.v1; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -30,60 +33,65 @@ public class ModuleDataCreator extends Creator { private String moduleInfo; private String configuration; - public ModuleDataCreator() {} + public ModuleDataCreator() { + } + public ModuleDataCreator setModuleInfo(final String moduleInfo) { this.moduleInfo = moduleInfo; return this; } + public ModuleDataCreator setConfiguration(final String configuration) { this.configuration = configuration; return this; } + @Override public ModuleData create(final TwilioRestClient client) { + String path = "/v1/Listings"; + Request request = new Request( - HttpMethod.POST, - Domains.MARKETPLACE.toString(), - path + HttpMethod.POST, + Domains.MARKETPLACE.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "ModuleData creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("ModuleData creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return ModuleData.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return ModuleData.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (moduleInfo != null) { - request.addPostParam("ModuleInfo", moduleInfo); + Serializer.toString(request, "ModuleInfo", moduleInfo, ParameterType.URLENCODED); } + + if (configuration != null) { - request.addPostParam("Configuration", configuration); + Serializer.toString(request, "Configuration", configuration, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/marketplace/v1/ModuleDataFetcher.java b/src/main/java/com/twilio/rest/marketplace/v1/ModuleDataFetcher.java index e5772cd653..8e8f6723cc 100644 --- a/src/main/java/com/twilio/rest/marketplace/v1/ModuleDataFetcher.java +++ b/src/main/java/com/twilio/rest/marketplace/v1/ModuleDataFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.marketplace.v1; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,41 +26,37 @@ public class ModuleDataFetcher extends Fetcher { - public ModuleDataFetcher() {} + + public ModuleDataFetcher() { + } + @Override public ModuleData fetch(final TwilioRestClient client) { + String path = "/v1/Listings"; + Request request = new Request( - HttpMethod.GET, - Domains.MARKETPLACE.toString(), - path + HttpMethod.GET, + Domains.MARKETPLACE.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "ModuleData fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("ModuleData fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return ModuleData.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return ModuleData.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/marketplace/v1/ModuleDataManagement.java b/src/main/java/com/twilio/rest/marketplace/v1/ModuleDataManagement.java index 4030edb955..f2b4037190 100644 --- a/src/main/java/com/twilio/rest/marketplace/v1/ModuleDataManagement.java +++ b/src/main/java/com/twilio/rest/marketplace/v1/ModuleDataManagement.java @@ -18,45 +18,47 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; -import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class ModuleDataManagement extends Resource { - private static final long serialVersionUID = 28686366019019L; - public static ModuleDataManagementFetcher fetcher(final String pathSid) { - return new ModuleDataManagementFetcher(pathSid); + public static ModuleDataManagementFetcher fetcher(final String pathsid) { + return new ModuleDataManagementFetcher( + pathsid + ); } - public static ModuleDataManagementUpdater updater(final String pathSid) { - return new ModuleDataManagementUpdater(pathSid); + + public static ModuleDataManagementUpdater updater(final String pathsid) { + return new ModuleDataManagementUpdater( + pathsid + ); } + /** * Converts a JSON String into a ModuleDataManagement object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return ModuleDataManagement object represented by the provided JSON */ - public static ModuleDataManagement fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static ModuleDataManagement fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, ModuleDataManagement.class); @@ -71,14 +73,11 @@ public static ModuleDataManagement fromJson( * Converts a JSON InputStream into a ModuleDataManagement object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return ModuleDataManagement object represented by the provided JSON */ - public static ModuleDataManagement fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static ModuleDataManagement fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, ModuleDataManagement.class); @@ -89,73 +88,59 @@ public static ModuleDataManagement fromJson( } } - private final URI url; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter + private final Object configuration; + @Getter + private final Object description; + @Getter + private final Object documentation; + @Getter + private final Object moduleInfo; + @Getter + private final Object policies; + @Getter + private final Object pricing; + @Getter private final String sid; - private final Map description; - private final Map support; - private final Map policies; - private final Map moduleInfo; - private final Map documentation; - private final Map configuration; - private final Map pricing; + @Getter + private final Object support; + @Getter + private final URI url; @JsonCreator private ModuleDataManagement( - @JsonProperty("url") final URI url, - @JsonProperty("sid") final String sid, - @JsonProperty("description") final Map description, - @JsonProperty("support") final Map support, - @JsonProperty("policies") final Map policies, - @JsonProperty("module_info") final Map moduleInfo, - @JsonProperty("documentation") final Map documentation, - @JsonProperty("configuration") final Map configuration, - @JsonProperty("pricing") final Map pricing + @JsonProperty("configuration") final Object configuration, + @JsonProperty("description") final Object description, + @JsonProperty("documentation") final Object documentation, + @JsonProperty("module_info") final Object moduleInfo, + @JsonProperty("policies") final Object policies, + @JsonProperty("pricing") final Object pricing, + @JsonProperty("sid") final String sid, + @JsonProperty("support") final Object support, + @JsonProperty("url") final URI url ) { - this.url = url; - this.sid = sid; + this.configuration = configuration; this.description = description; - this.support = support; - this.policies = policies; - this.moduleInfo = moduleInfo; this.documentation = documentation; - this.configuration = configuration; + this.moduleInfo = moduleInfo; + this.policies = policies; this.pricing = pricing; - } - - public final URI getUrl() { - return this.url; - } - - public final String getSid() { - return this.sid; - } - - public final Map getDescription() { - return this.description; - } - - public final Map getSupport() { - return this.support; - } - - public final Map getPolicies() { - return this.policies; - } - - public final Map getModuleInfo() { - return this.moduleInfo; - } - - public final Map getDocumentation() { - return this.documentation; - } - - public final Map getConfiguration() { - return this.configuration; - } - - public final Map getPricing() { - return this.pricing; + this.sid = sid; + this.support = support; + this.url = url; } @Override @@ -169,32 +154,34 @@ public boolean equals(final Object o) { } ModuleDataManagement other = (ModuleDataManagement) o; - return ( - Objects.equals(url, other.url) && - Objects.equals(sid, other.sid) && - Objects.equals(description, other.description) && - Objects.equals(support, other.support) && - Objects.equals(policies, other.policies) && - Objects.equals(moduleInfo, other.moduleInfo) && - Objects.equals(documentation, other.documentation) && - Objects.equals(configuration, other.configuration) && - Objects.equals(pricing, other.pricing) + Objects.equals(configuration, other.configuration) && + Objects.equals(description, other.description) && + Objects.equals(documentation, other.documentation) && + Objects.equals(moduleInfo, other.moduleInfo) && + Objects.equals(policies, other.policies) && + Objects.equals(pricing, other.pricing) && + Objects.equals(sid, other.sid) && + Objects.equals(support, other.support) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - url, - sid, - description, - support, - policies, - moduleInfo, - documentation, - configuration, - pricing + configuration, + description, + documentation, + moduleInfo, + policies, + pricing, + sid, + support, + url ); } + + } + diff --git a/src/main/java/com/twilio/rest/marketplace/v1/ModuleDataManagementFetcher.java b/src/main/java/com/twilio/rest/marketplace/v1/ModuleDataManagementFetcher.java index e908370c4b..ce9e98eac9 100644 --- a/src/main/java/com/twilio/rest/marketplace/v1/ModuleDataManagementFetcher.java +++ b/src/main/java/com/twilio/rest/marketplace/v1/ModuleDataManagementFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.marketplace.v1; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,47 +26,41 @@ public class ModuleDataManagementFetcher extends Fetcher { - private String pathSid; + private String pathsid; - public ModuleDataManagementFetcher(final String pathSid) { - this.pathSid = pathSid; + public ModuleDataManagementFetcher(final String pathsid) { + this.pathsid = pathsid; } + @Override public ModuleDataManagement fetch(final TwilioRestClient client) { + String path = "/v1/Listing/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.MARKETPLACE.toString(), - path + HttpMethod.GET, + Domains.MARKETPLACE.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "ModuleDataManagement fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("ModuleDataManagement fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return ModuleDataManagement.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return ModuleDataManagement.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/marketplace/v1/ModuleDataManagementUpdater.java b/src/main/java/com/twilio/rest/marketplace/v1/ModuleDataManagementUpdater.java index 98a678bc01..01d7e035cc 100644 --- a/src/main/java/com/twilio/rest/marketplace/v1/ModuleDataManagementUpdater.java +++ b/src/main/java/com/twilio/rest/marketplace/v1/ModuleDataManagementUpdater.java @@ -16,6 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -26,8 +28,7 @@ import com.twilio.rest.Domains; public class ModuleDataManagementUpdater extends Updater { - - private String pathSid; + private String pathsid; private String moduleInfo; private String description; private String documentation; @@ -36,110 +37,123 @@ public class ModuleDataManagementUpdater extends Updater { private String configuration; private String pricing; - public ModuleDataManagementUpdater(final String pathSid) { - this.pathSid = pathSid; + public ModuleDataManagementUpdater(final String pathsid) { + this.pathsid = pathsid; } + public ModuleDataManagementUpdater setModuleInfo(final String moduleInfo) { this.moduleInfo = moduleInfo; return this; } - public ModuleDataManagementUpdater setDescription( - final String description - ) { + + public ModuleDataManagementUpdater setDescription(final String description) { this.description = description; return this; } - public ModuleDataManagementUpdater setDocumentation( - final String documentation - ) { + + public ModuleDataManagementUpdater setDocumentation(final String documentation) { this.documentation = documentation; return this; } + public ModuleDataManagementUpdater setPolicies(final String policies) { this.policies = policies; return this; } + public ModuleDataManagementUpdater setSupport(final String support) { this.support = support; return this; } - public ModuleDataManagementUpdater setConfiguration( - final String configuration - ) { + + public ModuleDataManagementUpdater setConfiguration(final String configuration) { this.configuration = configuration; return this; } + public ModuleDataManagementUpdater setPricing(final String pricing) { this.pricing = pricing; return this; } + @Override public ModuleDataManagement update(final TwilioRestClient client) { + String path = "/v1/Listing/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.MARKETPLACE.toString(), - path + HttpMethod.POST, + Domains.MARKETPLACE.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "ModuleDataManagement update failed: Unable to connect to server" - ); + throw new ApiConnectionException("ModuleDataManagement update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return ModuleDataManagement.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return ModuleDataManagement.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (moduleInfo != null) { - request.addPostParam("ModuleInfo", moduleInfo); + Serializer.toString(request, "ModuleInfo", moduleInfo, ParameterType.URLENCODED); } + + if (description != null) { - request.addPostParam("Description", description); + Serializer.toString(request, "Description", description, ParameterType.URLENCODED); } + + if (documentation != null) { - request.addPostParam("Documentation", documentation); + Serializer.toString(request, "Documentation", documentation, ParameterType.URLENCODED); } + + if (policies != null) { - request.addPostParam("Policies", policies); + Serializer.toString(request, "Policies", policies, ParameterType.URLENCODED); } + + if (support != null) { - request.addPostParam("Support", support); + Serializer.toString(request, "Support", support, ParameterType.URLENCODED); } + + if (configuration != null) { - request.addPostParam("Configuration", configuration); + Serializer.toString(request, "Configuration", configuration, ParameterType.URLENCODED); } + + if (pricing != null) { - request.addPostParam("Pricing", pricing); + Serializer.toString(request, "Pricing", pricing, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/marketplace/v1/ReferralConversion.java b/src/main/java/com/twilio/rest/marketplace/v1/ReferralConversion.java index 2981e42916..8929979385 100644 --- a/src/main/java/com/twilio/rest/marketplace/v1/ReferralConversion.java +++ b/src/main/java/com/twilio/rest/marketplace/v1/ReferralConversion.java @@ -25,20 +25,28 @@ import com.twilio.base.Resource; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; -import java.io.IOException; -import java.io.InputStream; -import java.util.Objects; import lombok.Getter; import lombok.Setter; import lombok.ToString; -import lombok.ToString; + +import java.io.IOException; +import java.io.InputStream; +import java.util.Objects; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class ReferralConversion extends Resource { - private static final long serialVersionUID = 67114907443655L; + public static ReferralConversionCreator creator(final ReferralConversion.CreateReferralConversionRequest createReferralConversionRequest) { + return new ReferralConversionCreator( + createReferralConversionRequest + ); + } + + + //@JsonDeserialize(builder = CreateReferralConversionRequest.Builder.class) + @JsonInclude(JsonInclude.Include.NON_EMPTY) @ToString public static class CreateReferralConversionRequest { @@ -48,36 +56,16 @@ public static class CreateReferralConversionRequest { @Setter private String referralAccountSid; - public CreateReferralConversionRequest() {} - - public static CreateReferralConversionRequest fromJson( - String jsonString, - ObjectMapper mapper - ) throws IOException { - return mapper.readValue( - jsonString, - CreateReferralConversionRequest.class - ); - } - } - - public static ReferralConversionCreator creator( - final ReferralConversion.CreateReferralConversionRequest createReferralConversionRequest - ) { - return new ReferralConversionCreator(createReferralConversionRequest); } /** * Converts a JSON String into a ReferralConversion object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return ReferralConversion object represented by the provided JSON */ - public static ReferralConversion fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static ReferralConversion fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, ReferralConversion.class); @@ -92,14 +80,11 @@ public static ReferralConversion fromJson( * Converts a JSON InputStream into a ReferralConversion object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return ReferralConversion object represented by the provided JSON */ - public static ReferralConversion fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static ReferralConversion fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, ReferralConversion.class); @@ -122,19 +107,17 @@ public static String toJson(Object object, ObjectMapper mapper) { } } + + @Getter private final String convertedAccountSid; @JsonCreator private ReferralConversion( - @JsonProperty("converted_account_sid") final String convertedAccountSid + @JsonProperty("converted_account_sid") final String convertedAccountSid ) { this.convertedAccountSid = convertedAccountSid; } - public final String getConvertedAccountSid() { - return this.convertedAccountSid; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -146,12 +129,18 @@ public boolean equals(final Object o) { } ReferralConversion other = (ReferralConversion) o; - - return Objects.equals(convertedAccountSid, other.convertedAccountSid); + return ( + Objects.equals(convertedAccountSid, other.convertedAccountSid) + ); } @Override public int hashCode() { - return Objects.hash(convertedAccountSid); + return Objects.hash( + convertedAccountSid + ); } + + } + diff --git a/src/main/java/com/twilio/rest/marketplace/v1/ReferralConversionCreator.java b/src/main/java/com/twilio/rest/marketplace/v1/ReferralConversionCreator.java index 3af0d6b48f..df17bf30b7 100644 --- a/src/main/java/com/twilio/rest/marketplace/v1/ReferralConversionCreator.java +++ b/src/main/java/com/twilio/rest/marketplace/v1/ReferralConversionCreator.java @@ -30,70 +30,53 @@ public class ReferralConversionCreator extends Creator { private ReferralConversion.CreateReferralConversionRequest createReferralConversionRequest; - public ReferralConversionCreator( - final ReferralConversion.CreateReferralConversionRequest createReferralConversionRequest - ) { + public ReferralConversionCreator(final ReferralConversion.CreateReferralConversionRequest createReferralConversionRequest) { this.createReferralConversionRequest = createReferralConversionRequest; } - public ReferralConversionCreator setCreateReferralConversionRequest( - final ReferralConversion.CreateReferralConversionRequest createReferralConversionRequest - ) { + + public ReferralConversionCreator setCreateReferralConversionRequest(final ReferralConversion.CreateReferralConversionRequest createReferralConversionRequest) { this.createReferralConversionRequest = createReferralConversionRequest; return this; } + @Override public ReferralConversion create(final TwilioRestClient client) { + String path = "/v1/ReferralConversion"; - path = - path.replace( - "{" + "CreateReferralConversionRequest" + "}", - this.createReferralConversionRequest.toString() - ); Request request = new Request( - HttpMethod.POST, - Domains.MARKETPLACE.toString(), - path + HttpMethod.POST, + Domains.MARKETPLACE.toString(), + path ); request.setContentType(EnumConstants.ContentType.JSON); addPostParams(request, client); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "ReferralConversion creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("ReferralConversion creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return ReferralConversion.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return ReferralConversion.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request, TwilioRestClient client) { ObjectMapper objectMapper = client.getObjectMapper(); if (createReferralConversionRequest != null) { - request.setBody( - ReferralConversion.toJson( - createReferralConversionRequest, - objectMapper - ) - ); + request.setBody(ReferralConversion.toJson(createReferralConversionRequest, objectMapper)); } } } diff --git a/src/main/java/com/twilio/rest/marketplace/v1/availableaddon/AvailableAddOnExtension.java b/src/main/java/com/twilio/rest/marketplace/v1/availableaddon/AvailableAddOnExtension.java index 2fe77de077..b38fc4c668 100644 --- a/src/main/java/com/twilio/rest/marketplace/v1/availableaddon/AvailableAddOnExtension.java +++ b/src/main/java/com/twilio/rest/marketplace/v1/availableaddon/AvailableAddOnExtension.java @@ -18,51 +18,47 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class AvailableAddOnExtension extends Resource { - private static final long serialVersionUID = 15009232316880L; - public static AvailableAddOnExtensionFetcher fetcher( - final String pathAvailableAddOnSid, - final String pathSid - ) { + public static AvailableAddOnExtensionFetcher fetcher(final String pathavailableAddOnSid, final String pathsid) { return new AvailableAddOnExtensionFetcher( - pathAvailableAddOnSid, - pathSid + pathavailableAddOnSid, pathsid ); } - public static AvailableAddOnExtensionReader reader( - final String pathAvailableAddOnSid - ) { - return new AvailableAddOnExtensionReader(pathAvailableAddOnSid); + + public static AvailableAddOnExtensionReader reader(final String pathavailableAddOnSid) { + return new AvailableAddOnExtensionReader( + pathavailableAddOnSid + ); } + /** * Converts a JSON String into a AvailableAddOnExtension object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return AvailableAddOnExtension object represented by the provided JSON */ - public static AvailableAddOnExtension fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static AvailableAddOnExtension fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, AvailableAddOnExtension.class); @@ -77,14 +73,11 @@ public static AvailableAddOnExtension fromJson( * Converts a JSON InputStream into a AvailableAddOnExtension object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return AvailableAddOnExtension object represented by the provided JSON */ - public static AvailableAddOnExtension fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static AvailableAddOnExtension fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, AvailableAddOnExtension.class); @@ -95,54 +88,49 @@ public static AvailableAddOnExtension fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String availableAddOnSid; + @Getter private final String friendlyName; + @Getter private final String productName; + @Getter + private final String sid; + @Getter private final String uniqueName; + @Getter private final URI url; @JsonCreator private AvailableAddOnExtension( - @JsonProperty("sid") final String sid, - @JsonProperty("available_add_on_sid") final String availableAddOnSid, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("product_name") final String productName, - @JsonProperty("unique_name") final String uniqueName, - @JsonProperty("url") final URI url + @JsonProperty("available_add_on_sid") final String availableAddOnSid, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("product_name") final String productName, + @JsonProperty("sid") final String sid, + @JsonProperty("unique_name") final String uniqueName, + @JsonProperty("url") final URI url ) { - this.sid = sid; this.availableAddOnSid = availableAddOnSid; this.friendlyName = friendlyName; this.productName = productName; + this.sid = sid; this.uniqueName = uniqueName; this.url = url; } - public final String getSid() { - return this.sid; - } - - public final String getAvailableAddOnSid() { - return this.availableAddOnSid; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final String getProductName() { - return this.productName; - } - - public final String getUniqueName() { - return this.uniqueName; - } - - public final URI getUrl() { - return this.url; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -154,26 +142,28 @@ public boolean equals(final Object o) { } AvailableAddOnExtension other = (AvailableAddOnExtension) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(availableAddOnSid, other.availableAddOnSid) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(productName, other.productName) && - Objects.equals(uniqueName, other.uniqueName) && - Objects.equals(url, other.url) + Objects.equals(availableAddOnSid, other.availableAddOnSid) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(productName, other.productName) && + Objects.equals(sid, other.sid) && + Objects.equals(uniqueName, other.uniqueName) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - sid, - availableAddOnSid, - friendlyName, - productName, - uniqueName, - url + availableAddOnSid, + friendlyName, + productName, + sid, + uniqueName, + url ); } + + } + diff --git a/src/main/java/com/twilio/rest/marketplace/v1/availableaddon/AvailableAddOnExtensionFetcher.java b/src/main/java/com/twilio/rest/marketplace/v1/availableaddon/AvailableAddOnExtensionFetcher.java index 1fdb3258ab..7abe3750cc 100644 --- a/src/main/java/com/twilio/rest/marketplace/v1/availableaddon/AvailableAddOnExtensionFetcher.java +++ b/src/main/java/com/twilio/rest/marketplace/v1/availableaddon/AvailableAddOnExtensionFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.marketplace.v1.availableaddon; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,61 +24,46 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class AvailableAddOnExtensionFetcher - extends Fetcher { +public class AvailableAddOnExtensionFetcher extends Fetcher { - private String pathAvailableAddOnSid; - private String pathSid; + private String pathavailableAddOnSid; + private String pathsid; - public AvailableAddOnExtensionFetcher( - final String pathAvailableAddOnSid, - final String pathSid - ) { - this.pathAvailableAddOnSid = pathAvailableAddOnSid; - this.pathSid = pathSid; + public AvailableAddOnExtensionFetcher(final String pathavailableAddOnSid, final String pathsid) { + this.pathavailableAddOnSid = pathavailableAddOnSid; + this.pathsid = pathsid; } + @Override public AvailableAddOnExtension fetch(final TwilioRestClient client) { - String path = - "/v1/AvailableAddOns/{AvailableAddOnSid}/Extensions/{Sid}"; - path = - path.replace( - "{" + "AvailableAddOnSid" + "}", - this.pathAvailableAddOnSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/v1/AvailableAddOns/{AvailableAddOnSid}/Extensions/{Sid}"; + + path = path.replace("{" + "AvailableAddOnSid" + "}", this.pathavailableAddOnSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.MARKETPLACE.toString(), - path + HttpMethod.GET, + Domains.MARKETPLACE.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "AvailableAddOnExtension fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("AvailableAddOnExtension fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return AvailableAddOnExtension.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return AvailableAddOnExtension.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/marketplace/v1/availableaddon/AvailableAddOnExtensionReader.java b/src/main/java/com/twilio/rest/marketplace/v1/availableaddon/AvailableAddOnExtensionReader.java index 92b2757d8c..2562498921 100644 --- a/src/main/java/com/twilio/rest/marketplace/v1/availableaddon/AvailableAddOnExtensionReader.java +++ b/src/main/java/com/twilio/rest/marketplace/v1/availableaddon/AvailableAddOnExtensionReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,122 +28,90 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class AvailableAddOnExtensionReader - extends Reader { +public class AvailableAddOnExtensionReader extends Reader { - private String pathAvailableAddOnSid; + private String pathavailableAddOnSid; private Integer pageSize; - public AvailableAddOnExtensionReader(final String pathAvailableAddOnSid) { - this.pathAvailableAddOnSid = pathAvailableAddOnSid; + public AvailableAddOnExtensionReader(final String pathavailableAddOnSid) { + this.pathavailableAddOnSid = pathavailableAddOnSid; } + public AvailableAddOnExtensionReader setPageSize(final Integer pageSize) { this.pageSize = pageSize; return this; } + @Override - public ResourceSet read( - final TwilioRestClient client - ) { + public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } - public Page firstPage( - final TwilioRestClient client - ) { + public Page firstPage(final TwilioRestClient client) { + String path = "/v1/AvailableAddOns/{AvailableAddOnSid}/Extensions"; - path = - path.replace( - "{" + "AvailableAddOnSid" + "}", - this.pathAvailableAddOnSid.toString() - ); + + path = path.replace("{" + "AvailableAddOnSid" + "}", this.pathavailableAddOnSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.MARKETPLACE.toString(), - path + HttpMethod.GET, + Domains.MARKETPLACE.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "AvailableAddOnExtension read failed: Unable to connect to server" - ); + throw new ApiConnectionException("AvailableAddOnExtension read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "extensions", - response.getContent(), - AvailableAddOnExtension.class, - client.getObjectMapper() - ); + "extensions", + response.getContent(), + AvailableAddOnExtension.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.MARKETPLACE.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.MARKETPLACE.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/marketplace/v1/installedaddon/InstalledAddOnExtension.java b/src/main/java/com/twilio/rest/marketplace/v1/installedaddon/InstalledAddOnExtension.java index 827e62c6e8..83bf2cef8c 100644 --- a/src/main/java/com/twilio/rest/marketplace/v1/installedaddon/InstalledAddOnExtension.java +++ b/src/main/java/com/twilio/rest/marketplace/v1/installedaddon/InstalledAddOnExtension.java @@ -18,63 +18,54 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class InstalledAddOnExtension extends Resource { - private static final long serialVersionUID = 244872409958696L; - public static InstalledAddOnExtensionFetcher fetcher( - final String pathInstalledAddOnSid, - final String pathSid - ) { + public static InstalledAddOnExtensionFetcher fetcher(final String pathinstalledAddOnSid, final String pathsid) { return new InstalledAddOnExtensionFetcher( - pathInstalledAddOnSid, - pathSid + pathinstalledAddOnSid, pathsid ); } - public static InstalledAddOnExtensionReader reader( - final String pathInstalledAddOnSid - ) { - return new InstalledAddOnExtensionReader(pathInstalledAddOnSid); + + public static InstalledAddOnExtensionReader reader(final String pathinstalledAddOnSid) { + return new InstalledAddOnExtensionReader( + pathinstalledAddOnSid + ); } - public static InstalledAddOnExtensionUpdater updater( - final String pathInstalledAddOnSid, - final String pathSid, - final Boolean enabled - ) { + + public static InstalledAddOnExtensionUpdater updater(final String pathinstalledAddOnSid, final String pathsid, final Boolean enabled) { return new InstalledAddOnExtensionUpdater( - pathInstalledAddOnSid, - pathSid, - enabled + pathinstalledAddOnSid, pathsid, enabled ); } + /** * Converts a JSON String into a InstalledAddOnExtension object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return InstalledAddOnExtension object represented by the provided JSON */ - public static InstalledAddOnExtension fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static InstalledAddOnExtension fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, InstalledAddOnExtension.class); @@ -89,14 +80,11 @@ public static InstalledAddOnExtension fromJson( * Converts a JSON InputStream into a InstalledAddOnExtension object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return InstalledAddOnExtension object represented by the provided JSON */ - public static InstalledAddOnExtension fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static InstalledAddOnExtension fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, InstalledAddOnExtension.class); @@ -107,61 +95,53 @@ public static InstalledAddOnExtension fromJson( } } - private final String sid; - private final String installedAddOnSid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter + private final Boolean enabled; + @Getter private final String friendlyName; + @Getter + private final String installedAddOnSid; + @Getter private final String productName; + @Getter + private final String sid; + @Getter private final String uniqueName; - private final Boolean enabled; + @Getter private final URI url; @JsonCreator private InstalledAddOnExtension( - @JsonProperty("sid") final String sid, - @JsonProperty("installed_add_on_sid") final String installedAddOnSid, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("product_name") final String productName, - @JsonProperty("unique_name") final String uniqueName, - @JsonProperty("enabled") final Boolean enabled, - @JsonProperty("url") final URI url + @JsonProperty("enabled") final Boolean enabled, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("installed_add_on_sid") final String installedAddOnSid, + @JsonProperty("product_name") final String productName, + @JsonProperty("sid") final String sid, + @JsonProperty("unique_name") final String uniqueName, + @JsonProperty("url") final URI url ) { - this.sid = sid; - this.installedAddOnSid = installedAddOnSid; + this.enabled = enabled; this.friendlyName = friendlyName; + this.installedAddOnSid = installedAddOnSid; this.productName = productName; + this.sid = sid; this.uniqueName = uniqueName; - this.enabled = enabled; this.url = url; } - public final String getSid() { - return this.sid; - } - - public final String getInstalledAddOnSid() { - return this.installedAddOnSid; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final String getProductName() { - return this.productName; - } - - public final String getUniqueName() { - return this.uniqueName; - } - - public final Boolean getEnabled() { - return this.enabled; - } - - public final URI getUrl() { - return this.url; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -173,28 +153,30 @@ public boolean equals(final Object o) { } InstalledAddOnExtension other = (InstalledAddOnExtension) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(installedAddOnSid, other.installedAddOnSid) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(productName, other.productName) && - Objects.equals(uniqueName, other.uniqueName) && - Objects.equals(enabled, other.enabled) && - Objects.equals(url, other.url) + Objects.equals(enabled, other.enabled) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(installedAddOnSid, other.installedAddOnSid) && + Objects.equals(productName, other.productName) && + Objects.equals(sid, other.sid) && + Objects.equals(uniqueName, other.uniqueName) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - sid, - installedAddOnSid, - friendlyName, - productName, - uniqueName, - enabled, - url + enabled, + friendlyName, + installedAddOnSid, + productName, + sid, + uniqueName, + url ); } + + } + diff --git a/src/main/java/com/twilio/rest/marketplace/v1/installedaddon/InstalledAddOnExtensionFetcher.java b/src/main/java/com/twilio/rest/marketplace/v1/installedaddon/InstalledAddOnExtensionFetcher.java index e502bf19ba..8b2f090a3e 100644 --- a/src/main/java/com/twilio/rest/marketplace/v1/installedaddon/InstalledAddOnExtensionFetcher.java +++ b/src/main/java/com/twilio/rest/marketplace/v1/installedaddon/InstalledAddOnExtensionFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.marketplace.v1.installedaddon; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,61 +24,46 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class InstalledAddOnExtensionFetcher - extends Fetcher { +public class InstalledAddOnExtensionFetcher extends Fetcher { - private String pathInstalledAddOnSid; - private String pathSid; + private String pathinstalledAddOnSid; + private String pathsid; - public InstalledAddOnExtensionFetcher( - final String pathInstalledAddOnSid, - final String pathSid - ) { - this.pathInstalledAddOnSid = pathInstalledAddOnSid; - this.pathSid = pathSid; + public InstalledAddOnExtensionFetcher(final String pathinstalledAddOnSid, final String pathsid) { + this.pathinstalledAddOnSid = pathinstalledAddOnSid; + this.pathsid = pathsid; } + @Override public InstalledAddOnExtension fetch(final TwilioRestClient client) { - String path = - "/v1/InstalledAddOns/{InstalledAddOnSid}/Extensions/{Sid}"; - path = - path.replace( - "{" + "InstalledAddOnSid" + "}", - this.pathInstalledAddOnSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/v1/InstalledAddOns/{InstalledAddOnSid}/Extensions/{Sid}"; + + path = path.replace("{" + "InstalledAddOnSid" + "}", this.pathinstalledAddOnSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.MARKETPLACE.toString(), - path + HttpMethod.GET, + Domains.MARKETPLACE.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "InstalledAddOnExtension fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("InstalledAddOnExtension fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return InstalledAddOnExtension.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return InstalledAddOnExtension.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/marketplace/v1/installedaddon/InstalledAddOnExtensionReader.java b/src/main/java/com/twilio/rest/marketplace/v1/installedaddon/InstalledAddOnExtensionReader.java index 9c34614755..7ebc61248b 100644 --- a/src/main/java/com/twilio/rest/marketplace/v1/installedaddon/InstalledAddOnExtensionReader.java +++ b/src/main/java/com/twilio/rest/marketplace/v1/installedaddon/InstalledAddOnExtensionReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,122 +28,90 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class InstalledAddOnExtensionReader - extends Reader { +public class InstalledAddOnExtensionReader extends Reader { - private String pathInstalledAddOnSid; + private String pathinstalledAddOnSid; private Integer pageSize; - public InstalledAddOnExtensionReader(final String pathInstalledAddOnSid) { - this.pathInstalledAddOnSid = pathInstalledAddOnSid; + public InstalledAddOnExtensionReader(final String pathinstalledAddOnSid) { + this.pathinstalledAddOnSid = pathinstalledAddOnSid; } + public InstalledAddOnExtensionReader setPageSize(final Integer pageSize) { this.pageSize = pageSize; return this; } + @Override - public ResourceSet read( - final TwilioRestClient client - ) { + public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } - public Page firstPage( - final TwilioRestClient client - ) { + public Page firstPage(final TwilioRestClient client) { + String path = "/v1/InstalledAddOns/{InstalledAddOnSid}/Extensions"; - path = - path.replace( - "{" + "InstalledAddOnSid" + "}", - this.pathInstalledAddOnSid.toString() - ); + + path = path.replace("{" + "InstalledAddOnSid" + "}", this.pathinstalledAddOnSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.MARKETPLACE.toString(), - path + HttpMethod.GET, + Domains.MARKETPLACE.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "InstalledAddOnExtension read failed: Unable to connect to server" - ); + throw new ApiConnectionException("InstalledAddOnExtension read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "extensions", - response.getContent(), - InstalledAddOnExtension.class, - client.getObjectMapper() - ); + "extensions", + response.getContent(), + InstalledAddOnExtension.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.MARKETPLACE.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.MARKETPLACE.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/marketplace/v1/installedaddon/InstalledAddOnExtensionUpdater.java b/src/main/java/com/twilio/rest/marketplace/v1/installedaddon/InstalledAddOnExtensionUpdater.java index ddece99a56..8b8ea8f6c8 100644 --- a/src/main/java/com/twilio/rest/marketplace/v1/installedaddon/InstalledAddOnExtensionUpdater.java +++ b/src/main/java/com/twilio/rest/marketplace/v1/installedaddon/InstalledAddOnExtensionUpdater.java @@ -16,6 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,76 +27,65 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class InstalledAddOnExtensionUpdater - extends Updater { - - private String pathInstalledAddOnSid; - private String pathSid; +public class InstalledAddOnExtensionUpdater extends Updater { + private String pathinstalledAddOnSid; + private String pathsid; private Boolean enabled; - public InstalledAddOnExtensionUpdater( - final String pathInstalledAddOnSid, - final String pathSid, - final Boolean enabled - ) { - this.pathInstalledAddOnSid = pathInstalledAddOnSid; - this.pathSid = pathSid; + public InstalledAddOnExtensionUpdater(final String pathinstalledAddOnSid, final String pathsid, final Boolean enabled) { + this.pathinstalledAddOnSid = pathinstalledAddOnSid; + this.pathsid = pathsid; this.enabled = enabled; } + public InstalledAddOnExtensionUpdater setEnabled(final Boolean enabled) { this.enabled = enabled; return this; } + @Override public InstalledAddOnExtension update(final TwilioRestClient client) { - String path = - "/v1/InstalledAddOns/{InstalledAddOnSid}/Extensions/{Sid}"; - path = - path.replace( - "{" + "InstalledAddOnSid" + "}", - this.pathInstalledAddOnSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); - path = path.replace("{" + "Enabled" + "}", this.enabled.toString()); + String path = "/v1/InstalledAddOns/{InstalledAddOnSid}/Extensions/{Sid}"; + + path = path.replace("{" + "InstalledAddOnSid" + "}", this.pathinstalledAddOnSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.MARKETPLACE.toString(), - path + HttpMethod.POST, + Domains.MARKETPLACE.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "InstalledAddOnExtension update failed: Unable to connect to server" - ); + throw new ApiConnectionException("InstalledAddOnExtension update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return InstalledAddOnExtension.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return InstalledAddOnExtension.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (enabled != null) { - request.addPostParam("Enabled", enabled.toString()); + Serializer.toString(request, "Enabled", enabled, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/marketplace/v1/installedaddon/InstalledAddOnUsage.java b/src/main/java/com/twilio/rest/marketplace/v1/installedaddon/InstalledAddOnUsage.java index 26949939ae..7ca2edede3 100644 --- a/src/main/java/com/twilio/rest/marketplace/v1/installedaddon/InstalledAddOnUsage.java +++ b/src/main/java/com/twilio/rest/marketplace/v1/installedaddon/InstalledAddOnUsage.java @@ -25,111 +25,87 @@ import com.twilio.base.Resource; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.math.BigDecimal; import java.util.List; import java.util.Objects; -import lombok.Getter; -import lombok.Setter; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class InstalledAddOnUsage extends Resource { - private static final long serialVersionUID = 201246203121312L; - @ToString - public static class MarketplaceV1InstalledAddOnInstalledAddOnUsageBillableItems { + public static InstalledAddOnUsageCreator creator(final String pathinstalledAddOnSid, final InstalledAddOnUsage.MarketplaceV1InstalledAddOnInstalledAddOnUsage marketplaceV1InstalledAddOnInstalledAddOnUsage) { + return new InstalledAddOnUsageCreator( + pathinstalledAddOnSid, marketplaceV1InstalledAddOnInstalledAddOnUsage + ); + } - @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("quantity") - @Getter - @Setter - private BigDecimal quantity; + + //@JsonDeserialize(builder = MarketplaceV1InstalledAddOnInstalledAddOnUsage.Builder.class) + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @ToString + public static class MarketplaceV1InstalledAddOnInstalledAddOnUsage { + public MarketplaceV1InstalledAddOnInstalledAddOnUsage(final List billableItems) { + this.billableItems = billableItems; + } @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("sid") + @JsonProperty("total_submitted") @Getter @Setter - private String sid; + private BigDecimal totalSubmitted; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("submitted") + @JsonProperty("billable_items") @Getter @Setter - private Boolean submitted; + private List billableItems; - public static MarketplaceV1InstalledAddOnInstalledAddOnUsageBillableItems fromJson( - String jsonString, - ObjectMapper mapper - ) throws IOException { - return mapper.readValue( - jsonString, - MarketplaceV1InstalledAddOnInstalledAddOnUsageBillableItems.class - ); - } } + //@JsonDeserialize(builder = MarketplaceV1InstalledAddOnInstalledAddOnUsageBillableItemsInner.Builder.class) + @JsonInclude(JsonInclude.Include.NON_EMPTY) @ToString - public static class MarketplaceV1InstalledAddOnInstalledAddOnUsage { + public static class MarketplaceV1InstalledAddOnInstalledAddOnUsageBillableItemsInner { + public MarketplaceV1InstalledAddOnInstalledAddOnUsageBillableItemsInner(final BigDecimal quantity, final String sid) { + this.quantity = quantity; + this.sid = sid; + } @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("totalSubmitted") + @JsonProperty("quantity") @Getter @Setter - private BigDecimal totalSubmitted; + private BigDecimal quantity; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("billableItems") + @JsonProperty("sid") @Getter @Setter - private List< - MarketplaceV1InstalledAddOnInstalledAddOnUsageBillableItems - > billableItems; - - public MarketplaceV1InstalledAddOnInstalledAddOnUsage( - final List< - MarketplaceV1InstalledAddOnInstalledAddOnUsageBillableItems - > billableItems - ) { - this.billableItems = billableItems; - } + private String sid; - public static MarketplaceV1InstalledAddOnInstalledAddOnUsage fromJson( - String jsonString, - ObjectMapper mapper - ) throws IOException { - return mapper.readValue( - jsonString, - MarketplaceV1InstalledAddOnInstalledAddOnUsage.class - ); - } - } + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("submitted") + @Getter + @Setter + private Boolean submitted; - public static InstalledAddOnUsageCreator creator( - final String pathInstalledAddOnSid, - final InstalledAddOnUsage.MarketplaceV1InstalledAddOnInstalledAddOnUsage marketplaceV1InstalledAddOnInstalledAddOnUsage - ) { - return new InstalledAddOnUsageCreator( - pathInstalledAddOnSid, - marketplaceV1InstalledAddOnInstalledAddOnUsage - ); } /** * Converts a JSON String into a InstalledAddOnUsage object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return InstalledAddOnUsage object represented by the provided JSON */ - public static InstalledAddOnUsage fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static InstalledAddOnUsage fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, InstalledAddOnUsage.class); @@ -144,14 +120,11 @@ public static InstalledAddOnUsage fromJson( * Converts a JSON InputStream into a InstalledAddOnUsage object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return InstalledAddOnUsage object represented by the provided JSON */ - public static InstalledAddOnUsage fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static InstalledAddOnUsage fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, InstalledAddOnUsage.class); @@ -174,30 +147,19 @@ public static String toJson(Object object, ObjectMapper mapper) { } } + + @Getter + private final List billableItems; + @Getter private final BigDecimal totalSubmitted; - private final List< - MarketplaceV1InstalledAddOnInstalledAddOnUsageBillableItems - > billableItems; @JsonCreator private InstalledAddOnUsage( - @JsonProperty("total_submitted") final BigDecimal totalSubmitted, - @JsonProperty("billable_items") final List< - MarketplaceV1InstalledAddOnInstalledAddOnUsageBillableItems - > billableItems + @JsonProperty("billable_items") final List billableItems, + @JsonProperty("total_submitted") final BigDecimal totalSubmitted ) { - this.totalSubmitted = totalSubmitted; this.billableItems = billableItems; - } - - public final BigDecimal getTotalSubmitted() { - return this.totalSubmitted; - } - - public final List< - MarketplaceV1InstalledAddOnInstalledAddOnUsageBillableItems - > getBillableItems() { - return this.billableItems; + this.totalSubmitted = totalSubmitted; } @Override @@ -211,15 +173,20 @@ public boolean equals(final Object o) { } InstalledAddOnUsage other = (InstalledAddOnUsage) o; - return ( - Objects.equals(totalSubmitted, other.totalSubmitted) && - Objects.equals(billableItems, other.billableItems) + Objects.equals(billableItems, other.billableItems) && + Objects.equals(totalSubmitted, other.totalSubmitted) ); } @Override public int hashCode() { - return Objects.hash(totalSubmitted, billableItems); + return Objects.hash( + billableItems, + totalSubmitted + ); } + + } + diff --git a/src/main/java/com/twilio/rest/marketplace/v1/installedaddon/InstalledAddOnUsageCreator.java b/src/main/java/com/twilio/rest/marketplace/v1/installedaddon/InstalledAddOnUsageCreator.java index ec10495e56..8239a7d379 100644 --- a/src/main/java/com/twilio/rest/marketplace/v1/installedaddon/InstalledAddOnUsageCreator.java +++ b/src/main/java/com/twilio/rest/marketplace/v1/installedaddon/InstalledAddOnUsageCreator.java @@ -28,82 +28,59 @@ public class InstalledAddOnUsageCreator extends Creator { - private String pathInstalledAddOnSid; + private String pathinstalledAddOnSid; private InstalledAddOnUsage.MarketplaceV1InstalledAddOnInstalledAddOnUsage marketplaceV1InstalledAddOnInstalledAddOnUsage; - public InstalledAddOnUsageCreator( - final String pathInstalledAddOnSid, - final InstalledAddOnUsage.MarketplaceV1InstalledAddOnInstalledAddOnUsage marketplaceV1InstalledAddOnInstalledAddOnUsage - ) { - this.pathInstalledAddOnSid = pathInstalledAddOnSid; - this.marketplaceV1InstalledAddOnInstalledAddOnUsage = - marketplaceV1InstalledAddOnInstalledAddOnUsage; + public InstalledAddOnUsageCreator(final String pathinstalledAddOnSid, final InstalledAddOnUsage.MarketplaceV1InstalledAddOnInstalledAddOnUsage marketplaceV1InstalledAddOnInstalledAddOnUsage) { + this.pathinstalledAddOnSid = pathinstalledAddOnSid; + this.marketplaceV1InstalledAddOnInstalledAddOnUsage = marketplaceV1InstalledAddOnInstalledAddOnUsage; } - public InstalledAddOnUsageCreator setMarketplaceV1InstalledAddOnInstalledAddOnUsage( - final InstalledAddOnUsage.MarketplaceV1InstalledAddOnInstalledAddOnUsage marketplaceV1InstalledAddOnInstalledAddOnUsage - ) { - this.marketplaceV1InstalledAddOnInstalledAddOnUsage = - marketplaceV1InstalledAddOnInstalledAddOnUsage; + + public InstalledAddOnUsageCreator setMarketplaceV1InstalledAddOnInstalledAddOnUsage(final InstalledAddOnUsage.MarketplaceV1InstalledAddOnInstalledAddOnUsage marketplaceV1InstalledAddOnInstalledAddOnUsage) { + this.marketplaceV1InstalledAddOnInstalledAddOnUsage = marketplaceV1InstalledAddOnInstalledAddOnUsage; return this; } + @Override public InstalledAddOnUsage create(final TwilioRestClient client) { + String path = "/v1/InstalledAddOns/{InstalledAddOnSid}/Usage"; - path = - path.replace( - "{" + "InstalledAddOnSid" + "}", - this.pathInstalledAddOnSid.toString() - ); - path = - path.replace( - "{" + "MarketplaceV1InstalledAddOnInstalledAddOnUsage" + "}", - this.marketplaceV1InstalledAddOnInstalledAddOnUsage.toString() - ); + path = path.replace("{" + "InstalledAddOnSid" + "}", this.pathinstalledAddOnSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.MARKETPLACE.toString(), - path + HttpMethod.POST, + Domains.MARKETPLACE.toString(), + path ); request.setContentType(EnumConstants.ContentType.JSON); addPostParams(request, client); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "InstalledAddOnUsage creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("InstalledAddOnUsage creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return InstalledAddOnUsage.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return InstalledAddOnUsage.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request, TwilioRestClient client) { ObjectMapper objectMapper = client.getObjectMapper(); if (marketplaceV1InstalledAddOnInstalledAddOnUsage != null) { - request.setBody( - InstalledAddOnUsage.toJson( - marketplaceV1InstalledAddOnInstalledAddOnUsage, - objectMapper - ) - ); + request.setBody(InstalledAddOnUsage.toJson(marketplaceV1InstalledAddOnInstalledAddOnUsage, objectMapper)); } } } diff --git a/src/main/java/com/twilio/rest/messaging/v1/BrandRegistration.java b/src/main/java/com/twilio/rest/messaging/v1/BrandRegistration.java index 1f04545099..43f7a520cf 100644 --- a/src/main/java/com/twilio/rest/messaging/v1/BrandRegistration.java +++ b/src/main/java/com/twilio/rest/messaging/v1/BrandRegistration.java @@ -18,323 +18,173 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.List; import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class BrandRegistration extends Resource { - private static final long serialVersionUID = 138336370956862L; - public static BrandRegistrationCreator creator( - final String customerProfileBundleSid, - final String a2PProfileBundleSid - ) { + public static BrandRegistrationCreator creator(final String customerProfileBundleSid, final String a2PProfileBundleSid) { return new BrandRegistrationCreator( - customerProfileBundleSid, - a2PProfileBundleSid + customerProfileBundleSid, a2PProfileBundleSid ); } - public static BrandRegistrationFetcher fetcher(final String pathSid) { - return new BrandRegistrationFetcher(pathSid); + + public static BrandRegistrationFetcher fetcher(final String pathsid) { + return new BrandRegistrationFetcher( + pathsid + ); } + public static BrandRegistrationReader reader() { - return new BrandRegistrationReader(); - } + return new BrandRegistrationReader( - public static BrandRegistrationUpdater updater(final String pathSid) { - return new BrandRegistrationUpdater(pathSid); + ); } - /** - * Converts a JSON String into a BrandRegistration object using the provided ObjectMapper. - * - * @param json Raw JSON String - * @param objectMapper Jackson ObjectMapper - * @return BrandRegistration object represented by the provided JSON - */ - public static BrandRegistration fromJson( - final String json, - final ObjectMapper objectMapper - ) { - // Convert all checked exceptions to Runtime - try { - return objectMapper.readValue(json, BrandRegistration.class); - } catch (final JsonMappingException | JsonParseException e) { - throw new ApiException(e.getMessage(), e); - } catch (final IOException e) { - throw new ApiConnectionException(e.getMessage(), e); - } - } - /** - * Converts a JSON InputStream into a BrandRegistration object using the provided - * ObjectMapper. - * - * @param json Raw JSON InputStream - * @param objectMapper Jackson ObjectMapper - * @return BrandRegistration object represented by the provided JSON - */ - public static BrandRegistration fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { - // Convert all checked exceptions to Runtime - try { - return objectMapper.readValue(json, BrandRegistration.class); - } catch (final JsonMappingException | JsonParseException e) { - throw new ApiException(e.getMessage(), e); - } catch (final IOException e) { - throw new ApiConnectionException(e.getMessage(), e); - } + public static BrandRegistrationUpdater updater(final String pathsid) { + return new BrandRegistrationUpdater( + pathsid + ); } - private final String sid; - private final String accountSid; - private final String customerProfileBundleSid; - private final String a2pProfileBundleSid; - private final ZonedDateTime dateCreated; - private final ZonedDateTime dateUpdated; - private final String brandType; - private final BrandRegistration.Status status; - private final String tcrId; - private final String failureReason; - private final List> errors; - private final URI url; - private final Integer brandScore; - private final List brandFeedback; - private final BrandRegistration.IdentityStatus identityStatus; - private final Boolean russell3000; - private final Boolean governmentEntity; - private final String taxExemptStatus; - private final Boolean skipAutomaticSecVet; - private final Boolean mock; - private final Map links; - @JsonCreator - private BrandRegistration( - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty( - "customer_profile_bundle_sid" - ) final String customerProfileBundleSid, - @JsonProperty( - "a2p_profile_bundle_sid" - ) final String a2pProfileBundleSid, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("brand_type") final String brandType, - @JsonProperty("status") final BrandRegistration.Status status, - @JsonProperty("tcr_id") final String tcrId, - @JsonProperty("failure_reason") final String failureReason, - @JsonProperty("errors") final List> errors, - @JsonProperty("url") final URI url, - @JsonProperty("brand_score") final Integer brandScore, - @JsonProperty("brand_feedback") final List< - BrandRegistration.BrandFeedback - > brandFeedback, - @JsonProperty( - "identity_status" - ) final BrandRegistration.IdentityStatus identityStatus, - @JsonProperty("russell3000") final Boolean russell3000, - @JsonProperty("government_entity") final Boolean governmentEntity, - @JsonProperty("tax_exempt_status") final String taxExemptStatus, - @JsonProperty( - "skip_automatic_sec_vet" - ) final Boolean skipAutomaticSecVet, - @JsonProperty("mock") final Boolean mock, - @JsonProperty("links") final Map links - ) { - this.sid = sid; - this.accountSid = accountSid; - this.customerProfileBundleSid = customerProfileBundleSid; - this.a2pProfileBundleSid = a2pProfileBundleSid; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); - this.brandType = brandType; - this.status = status; - this.tcrId = tcrId; - this.failureReason = failureReason; - this.errors = errors; - this.url = url; - this.brandScore = brandScore; - this.brandFeedback = brandFeedback; - this.identityStatus = identityStatus; - this.russell3000 = russell3000; - this.governmentEntity = governmentEntity; - this.taxExemptStatus = taxExemptStatus; - this.skipAutomaticSecVet = skipAutomaticSecVet; - this.mock = mock; - this.links = links; - } + public enum Status { + PENDING("PENDING"), + APPROVED("APPROVED"), + FAILED("FAILED"), + IN_REVIEW("IN_REVIEW"), + DELETION_PENDING("DELETION_PENDING"), + DELETION_FAILED("DELETION_FAILED"), + SUSPENDED("SUSPENDED"); - public final String getSid() { - return this.sid; - } + private final String value; - public final String getAccountSid() { - return this.accountSid; - } + private Status(final String value) { + this.value = value; + } - public final String getCustomerProfileBundleSid() { - return this.customerProfileBundleSid; - } + public String toString() { + return value; + } - public final String getA2pProfileBundleSid() { - return this.a2pProfileBundleSid; + @JsonCreator + public static Status forValue(final String value) { + return Promoter.enumFromString(value, Status.values()); + } } - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } + public enum BrandRegistrationBrandFeedback { + TAX_ID("TAX_ID"), + STOCK_SYMBOL("STOCK_SYMBOL"), + NONPROFIT("NONPROFIT"), + GOVERNMENT_ENTITY("GOVERNMENT_ENTITY"), + OTHERS("OTHERS"); - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } + private final String value; - public final String getBrandType() { - return this.brandType; - } + private BrandRegistrationBrandFeedback(final String value) { + this.value = value; + } - public final BrandRegistration.Status getStatus() { - return this.status; - } + public String toString() { + return value; + } - public final String getTcrId() { - return this.tcrId; + @JsonCreator + public static BrandRegistrationBrandFeedback forValue(final String value) { + return Promoter.enumFromString(value, BrandRegistrationBrandFeedback.values()); + } } - public final String getFailureReason() { - return this.failureReason; - } + public enum BrandRegistrationBrandRegistrationBrandRegistrationBrandRegistrationBrandRegistrationBrandFeedback { + TAX_ID("TAX_ID"), + STOCK_SYMBOL("STOCK_SYMBOL"), + NONPROFIT("NONPROFIT"), + GOVERNMENT_ENTITY("GOVERNMENT_ENTITY"), + OTHERS("OTHERS"); - public final List> getErrors() { - return this.errors; - } + private final String value; - public final URI getUrl() { - return this.url; - } + private BrandRegistrationBrandRegistrationBrandRegistrationBrandRegistrationBrandRegistrationBrandFeedback(final String value) { + this.value = value; + } - public final Integer getBrandScore() { - return this.brandScore; - } + public String toString() { + return value; + } - public final List getBrandFeedback() { - return this.brandFeedback; + @JsonCreator + public static BrandRegistrationBrandRegistrationBrandRegistrationBrandRegistrationBrandRegistrationBrandFeedback forValue(final String value) { + return Promoter.enumFromString(value, BrandRegistrationBrandRegistrationBrandRegistrationBrandRegistrationBrandRegistrationBrandFeedback.values()); + } } - public final BrandRegistration.IdentityStatus getIdentityStatus() { - return this.identityStatus; - } + public enum BrandRegistrationBrandRegistrationBrandRegistrationBrandRegistrationBrandRegistrationBrandRegistrationBrandRegistrationBrandFeedback { + TAX_ID("TAX_ID"), + STOCK_SYMBOL("STOCK_SYMBOL"), + NONPROFIT("NONPROFIT"), + GOVERNMENT_ENTITY("GOVERNMENT_ENTITY"), + OTHERS("OTHERS"); - public final Boolean getRussell3000() { - return this.russell3000; - } + private final String value; - public final Boolean getGovernmentEntity() { - return this.governmentEntity; - } + private BrandRegistrationBrandRegistrationBrandRegistrationBrandRegistrationBrandRegistrationBrandRegistrationBrandRegistrationBrandFeedback(final String value) { + this.value = value; + } - public final String getTaxExemptStatus() { - return this.taxExemptStatus; - } + public String toString() { + return value; + } - public final Boolean getSkipAutomaticSecVet() { - return this.skipAutomaticSecVet; + @JsonCreator + public static BrandRegistrationBrandRegistrationBrandRegistrationBrandRegistrationBrandRegistrationBrandRegistrationBrandRegistrationBrandFeedback forValue(final String value) { + return Promoter.enumFromString(value, BrandRegistrationBrandRegistrationBrandRegistrationBrandRegistrationBrandRegistrationBrandRegistrationBrandRegistrationBrandFeedback.values()); + } } - public final Boolean getMock() { - return this.mock; - } + public enum BrandRegistrationBrandRegistrationBrandRegistrationBrandRegistrationBrandFeedback { + TAX_ID("TAX_ID"), + STOCK_SYMBOL("STOCK_SYMBOL"), + NONPROFIT("NONPROFIT"), + GOVERNMENT_ENTITY("GOVERNMENT_ENTITY"), + OTHERS("OTHERS"); - public final Map getLinks() { - return this.links; - } + private final String value; - @Override - public boolean equals(final Object o) { - if (this == o) { - return true; + private BrandRegistrationBrandRegistrationBrandRegistrationBrandRegistrationBrandFeedback(final String value) { + this.value = value; } - if (o == null || getClass() != o.getClass()) { - return false; + public String toString() { + return value; } - BrandRegistration other = (BrandRegistration) o; - - return ( - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals( - customerProfileBundleSid, - other.customerProfileBundleSid - ) && - Objects.equals(a2pProfileBundleSid, other.a2pProfileBundleSid) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(brandType, other.brandType) && - Objects.equals(status, other.status) && - Objects.equals(tcrId, other.tcrId) && - Objects.equals(failureReason, other.failureReason) && - Objects.equals(errors, other.errors) && - Objects.equals(url, other.url) && - Objects.equals(brandScore, other.brandScore) && - Objects.equals(brandFeedback, other.brandFeedback) && - Objects.equals(identityStatus, other.identityStatus) && - Objects.equals(russell3000, other.russell3000) && - Objects.equals(governmentEntity, other.governmentEntity) && - Objects.equals(taxExemptStatus, other.taxExemptStatus) && - Objects.equals(skipAutomaticSecVet, other.skipAutomaticSecVet) && - Objects.equals(mock, other.mock) && - Objects.equals(links, other.links) - ); - } - - @Override - public int hashCode() { - return Objects.hash( - sid, - accountSid, - customerProfileBundleSid, - a2pProfileBundleSid, - dateCreated, - dateUpdated, - brandType, - status, - tcrId, - failureReason, - errors, - url, - brandScore, - brandFeedback, - identityStatus, - russell3000, - governmentEntity, - taxExemptStatus, - skipAutomaticSecVet, - mock, - links - ); + @JsonCreator + public static BrandRegistrationBrandRegistrationBrandRegistrationBrandRegistrationBrandFeedback forValue(final String value) { + return Promoter.enumFromString(value, BrandRegistrationBrandRegistrationBrandRegistrationBrandRegistrationBrandFeedback.values()); + } } public enum BrandFeedback { @@ -360,18 +210,16 @@ public static BrandFeedback forValue(final String value) { } } - public enum Status { - PENDING("PENDING"), - APPROVED("APPROVED"), - FAILED("FAILED"), - IN_REVIEW("IN_REVIEW"), - DELETION_PENDING("DELETION_PENDING"), - DELETION_FAILED("DELETION_FAILED"), - SUSPENDED("SUSPENDED"); + public enum BrandRegistrationBrandRegistrationBrandRegistrationBrandFeedback { + TAX_ID("TAX_ID"), + STOCK_SYMBOL("STOCK_SYMBOL"), + NONPROFIT("NONPROFIT"), + GOVERNMENT_ENTITY("GOVERNMENT_ENTITY"), + OTHERS("OTHERS"); private final String value; - private Status(final String value) { + private BrandRegistrationBrandRegistrationBrandRegistrationBrandFeedback(final String value) { this.value = value; } @@ -380,8 +228,31 @@ public String toString() { } @JsonCreator - public static Status forValue(final String value) { - return Promoter.enumFromString(value, Status.values()); + public static BrandRegistrationBrandRegistrationBrandRegistrationBrandFeedback forValue(final String value) { + return Promoter.enumFromString(value, BrandRegistrationBrandRegistrationBrandRegistrationBrandFeedback.values()); + } + } + + public enum BrandRegistrationBrandRegistrationBrandFeedback { + TAX_ID("TAX_ID"), + STOCK_SYMBOL("STOCK_SYMBOL"), + NONPROFIT("NONPROFIT"), + GOVERNMENT_ENTITY("GOVERNMENT_ENTITY"), + OTHERS("OTHERS"); + + private final String value; + + private BrandRegistrationBrandRegistrationBrandFeedback(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static BrandRegistrationBrandRegistrationBrandFeedback forValue(final String value) { + return Promoter.enumFromString(value, BrandRegistrationBrandRegistrationBrandFeedback.values()); } } @@ -406,4 +277,236 @@ public static IdentityStatus forValue(final String value) { return Promoter.enumFromString(value, IdentityStatus.values()); } } + + public enum BrandRegistrationBrandRegistrationBrandRegistrationBrandRegistrationBrandRegistrationBrandRegistrationBrandFeedback { + TAX_ID("TAX_ID"), + STOCK_SYMBOL("STOCK_SYMBOL"), + NONPROFIT("NONPROFIT"), + GOVERNMENT_ENTITY("GOVERNMENT_ENTITY"), + OTHERS("OTHERS"); + + private final String value; + + private BrandRegistrationBrandRegistrationBrandRegistrationBrandRegistrationBrandRegistrationBrandRegistrationBrandFeedback(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static BrandRegistrationBrandRegistrationBrandRegistrationBrandRegistrationBrandRegistrationBrandRegistrationBrandFeedback forValue(final String value) { + return Promoter.enumFromString(value, BrandRegistrationBrandRegistrationBrandRegistrationBrandRegistrationBrandRegistrationBrandRegistrationBrandFeedback.values()); + } + } + + + /** + * Converts a JSON String into a BrandRegistration object using the provided ObjectMapper. + * + * @param json Raw JSON String + * @param objectMapper Jackson ObjectMapper + * @return BrandRegistration object represented by the provided JSON + */ + public static BrandRegistration fromJson(final String json, final ObjectMapper objectMapper) { + // Convert all checked exceptions to Runtime + try { + return objectMapper.readValue(json, BrandRegistration.class); + } catch (final JsonMappingException | JsonParseException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + /** + * Converts a JSON InputStream into a BrandRegistration object using the provided + * ObjectMapper. + * + * @param json Raw JSON InputStream + * @param objectMapper Jackson ObjectMapper + * @return BrandRegistration object represented by the provided JSON + */ + public static BrandRegistration fromJson(final InputStream json, final ObjectMapper objectMapper) { + // Convert all checked exceptions to Runtime + try { + return objectMapper.readValue(json, BrandRegistration.class); + } catch (final JsonMappingException | JsonParseException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter + private final String a2pProfileBundleSid; + @Getter + private final String accountSid; + @Getter + private final List brandFeedback; + @Getter + private final Integer brandScore; + @Getter + private final String brandType; + @Getter + private final String customerProfileBundleSid; + @Getter + private final ZonedDateTime dateCreated; + @Getter + private final ZonedDateTime dateUpdated; + @Getter + private final List errors; + @Getter + private final String failureReason; + @Getter + private final Boolean governmentEntity; + @Getter + private final BrandRegistration.IdentityStatus identityStatus; + @Getter + private final Map links; + @Getter + private final Boolean mock; + @Getter + private final Boolean russell3000; + @Getter + private final String sid; + @Getter + private final Boolean skipAutomaticSecVet; + @Getter + private final BrandRegistration.Status status; + @Getter + private final String taxExemptStatus; + @Getter + private final String tcrId; + @Getter + private final URI url; + + @JsonCreator + private BrandRegistration( + @JsonProperty("a2p_profile_bundle_sid") final String a2pProfileBundleSid, + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("brand_feedback") final List brandFeedback, + @JsonProperty("brand_score") final Integer brandScore, + @JsonProperty("brand_type") final String brandType, + @JsonProperty("customer_profile_bundle_sid") final String customerProfileBundleSid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("errors") final List errors, + @JsonProperty("failure_reason") final String failureReason, + @JsonProperty("government_entity") final Boolean governmentEntity, + @JsonProperty("identity_status") final BrandRegistration.IdentityStatus identityStatus, + @JsonProperty("links") final Map links, + @JsonProperty("mock") final Boolean mock, + @JsonProperty("russell_3000") final Boolean russell3000, + @JsonProperty("sid") final String sid, + @JsonProperty("skip_automatic_sec_vet") final Boolean skipAutomaticSecVet, + @JsonProperty("status") final BrandRegistration.Status status, + @JsonProperty("tax_exempt_status") final String taxExemptStatus, + @JsonProperty("tcr_id") final String tcrId, + @JsonProperty("url") final URI url + ) { + this.a2pProfileBundleSid = a2pProfileBundleSid; + this.accountSid = accountSid; + this.brandFeedback = brandFeedback; + this.brandScore = brandScore; + this.brandType = brandType; + this.customerProfileBundleSid = customerProfileBundleSid; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; + this.errors = errors; + this.failureReason = failureReason; + this.governmentEntity = governmentEntity; + this.identityStatus = identityStatus; + this.links = links; + this.mock = mock; + this.russell3000 = russell3000; + this.sid = sid; + this.skipAutomaticSecVet = skipAutomaticSecVet; + this.status = status; + this.taxExemptStatus = taxExemptStatus; + this.tcrId = tcrId; + this.url = url; + } + + @Override + public boolean equals(final Object o) { + if (this == o) { + return true; + } + + if (o == null || getClass() != o.getClass()) { + return false; + } + + BrandRegistration other = (BrandRegistration) o; + return ( + Objects.equals(a2pProfileBundleSid, other.a2pProfileBundleSid) && + Objects.equals(accountSid, other.accountSid) && + Objects.equals(brandFeedback, other.brandFeedback) && + Objects.equals(brandScore, other.brandScore) && + Objects.equals(brandType, other.brandType) && + Objects.equals(customerProfileBundleSid, other.customerProfileBundleSid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(errors, other.errors) && + Objects.equals(failureReason, other.failureReason) && + Objects.equals(governmentEntity, other.governmentEntity) && + Objects.equals(identityStatus, other.identityStatus) && + Objects.equals(links, other.links) && + Objects.equals(mock, other.mock) && + Objects.equals(russell3000, other.russell3000) && + Objects.equals(sid, other.sid) && + Objects.equals(skipAutomaticSecVet, other.skipAutomaticSecVet) && + Objects.equals(status, other.status) && + Objects.equals(taxExemptStatus, other.taxExemptStatus) && + Objects.equals(tcrId, other.tcrId) && + Objects.equals(url, other.url) + ); + } + + @Override + public int hashCode() { + return Objects.hash( + a2pProfileBundleSid, + accountSid, + brandFeedback, + brandScore, + brandType, + customerProfileBundleSid, + dateCreated, + dateUpdated, + errors, + failureReason, + governmentEntity, + identityStatus, + links, + mock, + russell3000, + sid, + skipAutomaticSecVet, + status, + taxExemptStatus, + tcrId, + url + ); + } + + } + diff --git a/src/main/java/com/twilio/rest/messaging/v1/BrandRegistrationCreator.java b/src/main/java/com/twilio/rest/messaging/v1/BrandRegistrationCreator.java index 5321b7e896..4f66094fec 100644 --- a/src/main/java/com/twilio/rest/messaging/v1/BrandRegistrationCreator.java +++ b/src/main/java/com/twilio/rest/messaging/v1/BrandRegistrationCreator.java @@ -14,8 +14,11 @@ package com.twilio.rest.messaging.v1; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -33,113 +36,100 @@ public class BrandRegistrationCreator extends Creator { private Boolean mock; private Boolean skipAutomaticSecVet; - public BrandRegistrationCreator( - final String customerProfileBundleSid, - final String a2PProfileBundleSid - ) { + public BrandRegistrationCreator(final String customerProfileBundleSid, final String a2PProfileBundleSid) { this.customerProfileBundleSid = customerProfileBundleSid; this.a2PProfileBundleSid = a2PProfileBundleSid; } - public BrandRegistrationCreator setCustomerProfileBundleSid( - final String customerProfileBundleSid - ) { + + public BrandRegistrationCreator setCustomerProfileBundleSid(final String customerProfileBundleSid) { this.customerProfileBundleSid = customerProfileBundleSid; return this; } - public BrandRegistrationCreator setA2PProfileBundleSid( - final String a2PProfileBundleSid - ) { + + public BrandRegistrationCreator setA2PProfileBundleSid(final String a2PProfileBundleSid) { this.a2PProfileBundleSid = a2PProfileBundleSid; return this; } + public BrandRegistrationCreator setBrandType(final String brandType) { this.brandType = brandType; return this; } + public BrandRegistrationCreator setMock(final Boolean mock) { this.mock = mock; return this; } - public BrandRegistrationCreator setSkipAutomaticSecVet( - final Boolean skipAutomaticSecVet - ) { + + public BrandRegistrationCreator setSkipAutomaticSecVet(final Boolean skipAutomaticSecVet) { this.skipAutomaticSecVet = skipAutomaticSecVet; return this; } + @Override public BrandRegistration create(final TwilioRestClient client) { + String path = "/v1/a2p/BrandRegistrations"; - path = - path.replace( - "{" + "CustomerProfileBundleSid" + "}", - this.customerProfileBundleSid.toString() - ); - path = - path.replace( - "{" + "A2PProfileBundleSid" + "}", - this.a2PProfileBundleSid.toString() - ); Request request = new Request( - HttpMethod.POST, - Domains.MESSAGING.toString(), - path + HttpMethod.POST, + Domains.MESSAGING.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "BrandRegistration creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("BrandRegistration creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return BrandRegistration.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return BrandRegistration.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (customerProfileBundleSid != null) { - request.addPostParam( - "CustomerProfileBundleSid", - customerProfileBundleSid - ); + Serializer.toString(request, "CustomerProfileBundleSid", customerProfileBundleSid, ParameterType.URLENCODED); } + + if (a2PProfileBundleSid != null) { - request.addPostParam("A2PProfileBundleSid", a2PProfileBundleSid); + Serializer.toString(request, "A2PProfileBundleSid", a2PProfileBundleSid, ParameterType.URLENCODED); } + + if (brandType != null) { - request.addPostParam("BrandType", brandType); + Serializer.toString(request, "BrandType", brandType, ParameterType.URLENCODED); } + + if (mock != null) { - request.addPostParam("Mock", mock.toString()); + Serializer.toString(request, "Mock", mock, ParameterType.URLENCODED); } + + if (skipAutomaticSecVet != null) { - request.addPostParam( - "SkipAutomaticSecVet", - skipAutomaticSecVet.toString() - ); + Serializer.toString(request, "SkipAutomaticSecVet", skipAutomaticSecVet, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/messaging/v1/BrandRegistrationFetcher.java b/src/main/java/com/twilio/rest/messaging/v1/BrandRegistrationFetcher.java index 73db21b8a1..31df5d7555 100644 --- a/src/main/java/com/twilio/rest/messaging/v1/BrandRegistrationFetcher.java +++ b/src/main/java/com/twilio/rest/messaging/v1/BrandRegistrationFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.messaging.v1; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,47 +26,41 @@ public class BrandRegistrationFetcher extends Fetcher { - private String pathSid; + private String pathsid; - public BrandRegistrationFetcher(final String pathSid) { - this.pathSid = pathSid; + public BrandRegistrationFetcher(final String pathsid) { + this.pathsid = pathsid; } + @Override public BrandRegistration fetch(final TwilioRestClient client) { + String path = "/v1/a2p/BrandRegistrations/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.MESSAGING.toString(), - path + HttpMethod.GET, + Domains.MESSAGING.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "BrandRegistration fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("BrandRegistration fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return BrandRegistration.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return BrandRegistration.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/messaging/v1/BrandRegistrationReader.java b/src/main/java/com/twilio/rest/messaging/v1/BrandRegistrationReader.java index 499be3bf66..0e7c2ad9fe 100644 --- a/src/main/java/com/twilio/rest/messaging/v1/BrandRegistrationReader.java +++ b/src/main/java/com/twilio/rest/messaging/v1/BrandRegistrationReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -31,105 +32,83 @@ public class BrandRegistrationReader extends Reader { private Long pageSize; - public BrandRegistrationReader() {} + public BrandRegistrationReader() { + } + public BrandRegistrationReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/a2p/BrandRegistrations"; + Request request = new Request( - HttpMethod.GET, - Domains.MESSAGING.toString(), - path + HttpMethod.GET, + Domains.MESSAGING.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "BrandRegistration read failed: Unable to connect to server" - ); + throw new ApiConnectionException("BrandRegistration read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "data", - response.getContent(), - BrandRegistration.class, - client.getObjectMapper() - ); + "data", + response.getContent(), + BrandRegistration.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.MESSAGING.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.MESSAGING.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/messaging/v1/BrandRegistrationUpdater.java b/src/main/java/com/twilio/rest/messaging/v1/BrandRegistrationUpdater.java index ecf874faf4..5181d8de89 100644 --- a/src/main/java/com/twilio/rest/messaging/v1/BrandRegistrationUpdater.java +++ b/src/main/java/com/twilio/rest/messaging/v1/BrandRegistrationUpdater.java @@ -15,7 +15,6 @@ package com.twilio.rest.messaging.v1; import com.twilio.base.Updater; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -26,47 +25,42 @@ import com.twilio.rest.Domains; public class BrandRegistrationUpdater extends Updater { + private String pathsid; - private String pathSid; - - public BrandRegistrationUpdater(final String pathSid) { - this.pathSid = pathSid; + public BrandRegistrationUpdater(final String pathsid) { + this.pathsid = pathsid; } + @Override public BrandRegistration update(final TwilioRestClient client) { + String path = "/v1/a2p/BrandRegistrations/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.MESSAGING.toString(), - path + HttpMethod.POST, + Domains.MESSAGING.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "BrandRegistration update failed: Unable to connect to server" - ); + throw new ApiConnectionException("BrandRegistration update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return BrandRegistration.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return BrandRegistration.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/messaging/v1/Deactivations.java b/src/main/java/com/twilio/rest/messaging/v1/Deactivations.java index 791de912cc..e9e8b03e34 100644 --- a/src/main/java/com/twilio/rest/messaging/v1/Deactivations.java +++ b/src/main/java/com/twilio/rest/messaging/v1/Deactivations.java @@ -18,39 +18,40 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Deactivations extends Resource { - private static final long serialVersionUID = 245900587626041L; public static DeactivationsFetcher fetcher() { - return new DeactivationsFetcher(); + return new DeactivationsFetcher( + + ); } + /** * Converts a JSON String into a Deactivations object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Deactivations object represented by the provided JSON */ - public static Deactivations fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Deactivations fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Deactivations.class); @@ -65,14 +66,11 @@ public static Deactivations fromJson( * Converts a JSON InputStream into a Deactivations object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Deactivations object represented by the provided JSON */ - public static Deactivations fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Deactivations fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Deactivations.class); @@ -83,17 +81,29 @@ public static Deactivations fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final URI redirectTo; @JsonCreator - private Deactivations(@JsonProperty("redirect_to") final URI redirectTo) { + private Deactivations( + @JsonProperty("redirect_to") final URI redirectTo + ) { this.redirectTo = redirectTo; } - public final URI getRedirectTo() { - return this.redirectTo; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -105,12 +115,18 @@ public boolean equals(final Object o) { } Deactivations other = (Deactivations) o; - - return Objects.equals(redirectTo, other.redirectTo); + return ( + Objects.equals(redirectTo, other.redirectTo) + ); } @Override public int hashCode() { - return Objects.hash(redirectTo); + return Objects.hash( + redirectTo + ); } + + } + diff --git a/src/main/java/com/twilio/rest/messaging/v1/DeactivationsFetcher.java b/src/main/java/com/twilio/rest/messaging/v1/DeactivationsFetcher.java index 6e3b1c206e..d29dfa6180 100644 --- a/src/main/java/com/twilio/rest/messaging/v1/DeactivationsFetcher.java +++ b/src/main/java/com/twilio/rest/messaging/v1/DeactivationsFetcher.java @@ -15,8 +15,8 @@ package com.twilio.rest.messaging.v1; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; -import com.twilio.converter.DateConverter; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,62 +25,60 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.time.LocalDate; public class DeactivationsFetcher extends Fetcher { private LocalDate date; - public DeactivationsFetcher() {} + public DeactivationsFetcher() { + } + public DeactivationsFetcher setDate(final LocalDate date) { this.date = date; return this; } + @Override public Deactivations fetch(final TwilioRestClient client) { + String path = "/v1/Deactivations"; + Request request = new Request( - HttpMethod.GET, - Domains.MESSAGING.toString(), - path + HttpMethod.GET, + Domains.MESSAGING.toString(), + path ); addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Deactivations fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Deactivations fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return Deactivations.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Deactivations.fromJson(response.getStream(), client.getObjectMapper()); } private void addQueryParams(final Request request) { + + if (date != null) { - request.addQueryParam( - "Date", - DateConverter.dateStringFromLocalDate(date) - ); + Serializer.toString(request, "Date", date, ParameterType.QUERY); } + + } } diff --git a/src/main/java/com/twilio/rest/messaging/v1/DomainCerts.java b/src/main/java/com/twilio/rest/messaging/v1/DomainCerts.java index af2becdd8f..857324283a 100644 --- a/src/main/java/com/twilio/rest/messaging/v1/DomainCerts.java +++ b/src/main/java/com/twilio/rest/messaging/v1/DomainCerts.java @@ -18,54 +18,56 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; -import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class DomainCerts extends Resource { - private static final long serialVersionUID = 200335100401859L; - public static DomainCertsDeleter deleter(final String pathDomainSid) { - return new DomainCertsDeleter(pathDomainSid); + public static DomainCertsDeleter deleter(final String pathdomainSid) { + return new DomainCertsDeleter( + pathdomainSid + ); } - public static DomainCertsFetcher fetcher(final String pathDomainSid) { - return new DomainCertsFetcher(pathDomainSid); + + public static DomainCertsFetcher fetcher(final String pathdomainSid) { + return new DomainCertsFetcher( + pathdomainSid + ); } - public static DomainCertsUpdater updater( - final String pathDomainSid, - final String tlsCert - ) { - return new DomainCertsUpdater(pathDomainSid, tlsCert); + + public static DomainCertsUpdater updater(final String pathdomainSid, final String tlsCert) { + return new DomainCertsUpdater( + pathdomainSid, tlsCert + ); } + /** * Converts a JSON String into a DomainCerts object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return DomainCerts object represented by the provided JSON */ - public static DomainCerts fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static DomainCerts fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, DomainCerts.class); @@ -80,14 +82,11 @@ public static DomainCerts fromJson( * Converts a JSON InputStream into a DomainCerts object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return DomainCerts object represented by the provided JSON */ - public static DomainCerts fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static DomainCerts fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, DomainCerts.class); @@ -98,69 +97,58 @@ public static DomainCerts fromJson( } } - private final String domainSid; - private final ZonedDateTime dateUpdated; - private final ZonedDateTime dateExpires; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter + private final Object certInValidation; + @Getter + private final String certificateSid; + @Getter private final ZonedDateTime dateCreated; + @Getter + private final ZonedDateTime dateExpires; + @Getter + private final ZonedDateTime dateUpdated; + @Getter private final URI domainName; - private final String certificateSid; + @Getter + private final String domainSid; + @Getter private final URI url; - private final Map certInValidation; @JsonCreator private DomainCerts( - @JsonProperty("domain_sid") final String domainSid, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("date_expires") final String dateExpires, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("domain_name") final URI domainName, - @JsonProperty("certificate_sid") final String certificateSid, - @JsonProperty("url") final URI url, - @JsonProperty("cert_in_validation") final Map< - String, - Object - > certInValidation + @JsonProperty("cert_in_validation") final Object certInValidation, + @JsonProperty("certificate_sid") final String certificateSid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_expires") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateExpires, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("domain_name") final URI domainName, + @JsonProperty("domain_sid") final String domainSid, + @JsonProperty("url") final URI url ) { - this.domainSid = domainSid; - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); - this.dateExpires = DateConverter.iso8601DateTimeFromString(dateExpires); - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.domainName = domainName; + this.certInValidation = certInValidation; this.certificateSid = certificateSid; + this.dateCreated = dateCreated; + this.dateExpires = dateExpires; + this.dateUpdated = dateUpdated; + this.domainName = domainName; + this.domainSid = domainSid; this.url = url; - this.certInValidation = certInValidation; - } - - public final String getDomainSid() { - return this.domainSid; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final ZonedDateTime getDateExpires() { - return this.dateExpires; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final URI getDomainName() { - return this.domainName; - } - - public final String getCertificateSid() { - return this.certificateSid; - } - - public final URI getUrl() { - return this.url; - } - - public final Map getCertInValidation() { - return this.certInValidation; } @Override @@ -174,30 +162,32 @@ public boolean equals(final Object o) { } DomainCerts other = (DomainCerts) o; - return ( - Objects.equals(domainSid, other.domainSid) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(dateExpires, other.dateExpires) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(domainName, other.domainName) && - Objects.equals(certificateSid, other.certificateSid) && - Objects.equals(url, other.url) && - Objects.equals(certInValidation, other.certInValidation) + Objects.equals(certInValidation, other.certInValidation) && + Objects.equals(certificateSid, other.certificateSid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateExpires, other.dateExpires) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(domainName, other.domainName) && + Objects.equals(domainSid, other.domainSid) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - domainSid, - dateUpdated, - dateExpires, - dateCreated, - domainName, - certificateSid, - url, - certInValidation + certInValidation, + certificateSid, + dateCreated, + dateExpires, + dateUpdated, + domainName, + domainSid, + url ); } + + } + diff --git a/src/main/java/com/twilio/rest/messaging/v1/DomainCertsDeleter.java b/src/main/java/com/twilio/rest/messaging/v1/DomainCertsDeleter.java index 267602a342..049d83dc47 100644 --- a/src/main/java/com/twilio/rest/messaging/v1/DomainCertsDeleter.java +++ b/src/main/java/com/twilio/rest/messaging/v1/DomainCertsDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.messaging.v1; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,44 +26,38 @@ public class DomainCertsDeleter extends Deleter { - private String pathDomainSid; + private String pathdomainSid; - public DomainCertsDeleter(final String pathDomainSid) { - this.pathDomainSid = pathDomainSid; + public DomainCertsDeleter(final String pathdomainSid) { + this.pathdomainSid = pathdomainSid; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/v1/LinkShortening/Domains/{DomainSid}/Certificate"; - path = - path.replace( - "{" + "DomainSid" + "}", - this.pathDomainSid.toString() - ); + path = path.replace("{" + "DomainSid" + "}", this.pathdomainSid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.MESSAGING.toString(), - path + HttpMethod.DELETE, + Domains.MESSAGING.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "DomainCerts delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("DomainCerts delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/messaging/v1/DomainCertsFetcher.java b/src/main/java/com/twilio/rest/messaging/v1/DomainCertsFetcher.java index 39de560d42..dce0f03bed 100644 --- a/src/main/java/com/twilio/rest/messaging/v1/DomainCertsFetcher.java +++ b/src/main/java/com/twilio/rest/messaging/v1/DomainCertsFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.messaging.v1; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,51 +26,41 @@ public class DomainCertsFetcher extends Fetcher { - private String pathDomainSid; + private String pathdomainSid; - public DomainCertsFetcher(final String pathDomainSid) { - this.pathDomainSid = pathDomainSid; + public DomainCertsFetcher(final String pathdomainSid) { + this.pathdomainSid = pathdomainSid; } + @Override public DomainCerts fetch(final TwilioRestClient client) { + String path = "/v1/LinkShortening/Domains/{DomainSid}/Certificate"; - path = - path.replace( - "{" + "DomainSid" + "}", - this.pathDomainSid.toString() - ); + path = path.replace("{" + "DomainSid" + "}", this.pathdomainSid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.MESSAGING.toString(), - path + HttpMethod.GET, + Domains.MESSAGING.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "DomainCerts fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("DomainCerts fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return DomainCerts.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return DomainCerts.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/messaging/v1/DomainCertsUpdater.java b/src/main/java/com/twilio/rest/messaging/v1/DomainCertsUpdater.java index 596cde1a50..4e43e05201 100644 --- a/src/main/java/com/twilio/rest/messaging/v1/DomainCertsUpdater.java +++ b/src/main/java/com/twilio/rest/messaging/v1/DomainCertsUpdater.java @@ -16,6 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -26,69 +28,61 @@ import com.twilio.rest.Domains; public class DomainCertsUpdater extends Updater { - - private String pathDomainSid; + private String pathdomainSid; private String tlsCert; - public DomainCertsUpdater( - final String pathDomainSid, - final String tlsCert - ) { - this.pathDomainSid = pathDomainSid; + public DomainCertsUpdater(final String pathdomainSid, final String tlsCert) { + this.pathdomainSid = pathdomainSid; this.tlsCert = tlsCert; } + public DomainCertsUpdater setTlsCert(final String tlsCert) { this.tlsCert = tlsCert; return this; } + @Override public DomainCerts update(final TwilioRestClient client) { + String path = "/v1/LinkShortening/Domains/{DomainSid}/Certificate"; - path = - path.replace( - "{" + "DomainSid" + "}", - this.pathDomainSid.toString() - ); - path = path.replace("{" + "TlsCert" + "}", this.tlsCert.toString()); + path = path.replace("{" + "DomainSid" + "}", this.pathdomainSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.MESSAGING.toString(), - path + HttpMethod.POST, + Domains.MESSAGING.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "DomainCerts update failed: Unable to connect to server" - ); + throw new ApiConnectionException("DomainCerts update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return DomainCerts.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return DomainCerts.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (tlsCert != null) { - request.addPostParam("TlsCert", tlsCert); + Serializer.toString(request, "TlsCert", tlsCert, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/messaging/v1/DomainConfig.java b/src/main/java/com/twilio/rest/messaging/v1/DomainConfig.java index e9243efa90..84f005d770 100644 --- a/src/main/java/com/twilio/rest/messaging/v1/DomainConfig.java +++ b/src/main/java/com/twilio/rest/messaging/v1/DomainConfig.java @@ -18,45 +18,49 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class DomainConfig extends Resource { - private static final long serialVersionUID = 278004827100918L; - public static DomainConfigFetcher fetcher(final String pathDomainSid) { - return new DomainConfigFetcher(pathDomainSid); + public static DomainConfigFetcher fetcher(final String pathdomainSid) { + return new DomainConfigFetcher( + pathdomainSid + ); } - public static DomainConfigUpdater updater(final String pathDomainSid) { - return new DomainConfigUpdater(pathDomainSid); + + public static DomainConfigUpdater updater(final String pathdomainSid) { + return new DomainConfigUpdater( + pathdomainSid + ); } + /** * Converts a JSON String into a DomainConfig object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return DomainConfig object represented by the provided JSON */ - public static DomainConfig fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static DomainConfig fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, DomainConfig.class); @@ -71,14 +75,11 @@ public static DomainConfig fromJson( * Converts a JSON InputStream into a DomainConfig object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return DomainConfig object represented by the provided JSON */ - public static DomainConfig fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static DomainConfig fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, DomainConfig.class); @@ -89,73 +90,61 @@ public static DomainConfig fromJson( } } - private final String domainSid; - private final String configSid; - private final URI fallbackUrl; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final URI callbackUrl; + @Getter + private final String configSid; + @Getter private final Boolean continueOnFailure; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; - private final URI url; + @Getter private final Boolean disableHttps; + @Getter + private final String domainSid; + @Getter + private final URI fallbackUrl; + @Getter + private final URI url; @JsonCreator private DomainConfig( - @JsonProperty("domain_sid") final String domainSid, - @JsonProperty("config_sid") final String configSid, - @JsonProperty("fallback_url") final URI fallbackUrl, - @JsonProperty("callback_url") final URI callbackUrl, - @JsonProperty("continue_on_failure") final Boolean continueOnFailure, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("url") final URI url, - @JsonProperty("disable_https") final Boolean disableHttps + @JsonProperty("callback_url") final URI callbackUrl, + @JsonProperty("config_sid") final String configSid, + @JsonProperty("continue_on_failure") final Boolean continueOnFailure, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("disable_https") final Boolean disableHttps, + @JsonProperty("domain_sid") final String domainSid, + @JsonProperty("fallback_url") final URI fallbackUrl, + @JsonProperty("url") final URI url ) { - this.domainSid = domainSid; - this.configSid = configSid; - this.fallbackUrl = fallbackUrl; this.callbackUrl = callbackUrl; + this.configSid = configSid; this.continueOnFailure = continueOnFailure; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); - this.url = url; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.disableHttps = disableHttps; - } - - public final String getDomainSid() { - return this.domainSid; - } - - public final String getConfigSid() { - return this.configSid; - } - - public final URI getFallbackUrl() { - return this.fallbackUrl; - } - - public final URI getCallbackUrl() { - return this.callbackUrl; - } - - public final Boolean getContinueOnFailure() { - return this.continueOnFailure; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final URI getUrl() { - return this.url; - } - - public final Boolean getDisableHttps() { - return this.disableHttps; + this.domainSid = domainSid; + this.fallbackUrl = fallbackUrl; + this.url = url; } @Override @@ -169,32 +158,34 @@ public boolean equals(final Object o) { } DomainConfig other = (DomainConfig) o; - return ( - Objects.equals(domainSid, other.domainSid) && - Objects.equals(configSid, other.configSid) && - Objects.equals(fallbackUrl, other.fallbackUrl) && - Objects.equals(callbackUrl, other.callbackUrl) && - Objects.equals(continueOnFailure, other.continueOnFailure) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(url, other.url) && - Objects.equals(disableHttps, other.disableHttps) + Objects.equals(callbackUrl, other.callbackUrl) && + Objects.equals(configSid, other.configSid) && + Objects.equals(continueOnFailure, other.continueOnFailure) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(disableHttps, other.disableHttps) && + Objects.equals(domainSid, other.domainSid) && + Objects.equals(fallbackUrl, other.fallbackUrl) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - domainSid, - configSid, - fallbackUrl, - callbackUrl, - continueOnFailure, - dateCreated, - dateUpdated, - url, - disableHttps + callbackUrl, + configSid, + continueOnFailure, + dateCreated, + dateUpdated, + disableHttps, + domainSid, + fallbackUrl, + url ); } + + } + diff --git a/src/main/java/com/twilio/rest/messaging/v1/DomainConfigFetcher.java b/src/main/java/com/twilio/rest/messaging/v1/DomainConfigFetcher.java index 96d07292ed..20a86f6b74 100644 --- a/src/main/java/com/twilio/rest/messaging/v1/DomainConfigFetcher.java +++ b/src/main/java/com/twilio/rest/messaging/v1/DomainConfigFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.messaging.v1; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,51 +26,41 @@ public class DomainConfigFetcher extends Fetcher { - private String pathDomainSid; + private String pathdomainSid; - public DomainConfigFetcher(final String pathDomainSid) { - this.pathDomainSid = pathDomainSid; + public DomainConfigFetcher(final String pathdomainSid) { + this.pathdomainSid = pathdomainSid; } + @Override public DomainConfig fetch(final TwilioRestClient client) { + String path = "/v1/LinkShortening/Domains/{DomainSid}/Config"; - path = - path.replace( - "{" + "DomainSid" + "}", - this.pathDomainSid.toString() - ); + path = path.replace("{" + "DomainSid" + "}", this.pathdomainSid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.MESSAGING.toString(), - path + HttpMethod.GET, + Domains.MESSAGING.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "DomainConfig fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("DomainConfig fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return DomainConfig.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return DomainConfig.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/messaging/v1/DomainConfigMessagingService.java b/src/main/java/com/twilio/rest/messaging/v1/DomainConfigMessagingService.java index 0fd4766e6a..f4993485a8 100644 --- a/src/main/java/com/twilio/rest/messaging/v1/DomainConfigMessagingService.java +++ b/src/main/java/com/twilio/rest/messaging/v1/DomainConfigMessagingService.java @@ -18,49 +18,45 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class DomainConfigMessagingService extends Resource { - private static final long serialVersionUID = 37164874125386L; - public static DomainConfigMessagingServiceFetcher fetcher( - final String pathMessagingServiceSid - ) { - return new DomainConfigMessagingServiceFetcher(pathMessagingServiceSid); + public static DomainConfigMessagingServiceFetcher fetcher(final String pathmessagingServiceSid) { + return new DomainConfigMessagingServiceFetcher( + pathmessagingServiceSid + ); } + /** * Converts a JSON String into a DomainConfigMessagingService object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return DomainConfigMessagingService object represented by the provided JSON */ - public static DomainConfigMessagingService fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static DomainConfigMessagingService fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { - return objectMapper.readValue( - json, - DomainConfigMessagingService.class - ); + return objectMapper.readValue(json, DomainConfigMessagingService.class); } catch (final JsonMappingException | JsonParseException e) { throw new ApiException(e.getMessage(), e); } catch (final IOException e) { @@ -72,20 +68,14 @@ public static DomainConfigMessagingService fromJson( * Converts a JSON InputStream into a DomainConfigMessagingService object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return DomainConfigMessagingService object represented by the provided JSON */ - public static DomainConfigMessagingService fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static DomainConfigMessagingService fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { - return objectMapper.readValue( - json, - DomainConfigMessagingService.class - ); + return objectMapper.readValue(json, DomainConfigMessagingService.class); } catch (final JsonMappingException | JsonParseException e) { throw new ApiException(e.getMessage(), e); } catch (final IOException e) { @@ -93,75 +83,63 @@ public static DomainConfigMessagingService fromJson( } } - private final String domainSid; - private final String configSid; - private final String messagingServiceSid; - private final URI fallbackUrl; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final URI callbackUrl; + @Getter + private final String configSid; + @Getter private final Boolean continueOnFailure; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; + @Getter + private final String domainSid; + @Getter + private final URI fallbackUrl; + @Getter + private final String messagingServiceSid; + @Getter private final URI url; @JsonCreator private DomainConfigMessagingService( - @JsonProperty("domain_sid") final String domainSid, - @JsonProperty("config_sid") final String configSid, - @JsonProperty("messaging_service_sid") final String messagingServiceSid, - @JsonProperty("fallback_url") final URI fallbackUrl, - @JsonProperty("callback_url") final URI callbackUrl, - @JsonProperty("continue_on_failure") final Boolean continueOnFailure, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("url") final URI url + @JsonProperty("callback_url") final URI callbackUrl, + @JsonProperty("config_sid") final String configSid, + @JsonProperty("continue_on_failure") final Boolean continueOnFailure, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("domain_sid") final String domainSid, + @JsonProperty("fallback_url") final URI fallbackUrl, + @JsonProperty("messaging_service_sid") final String messagingServiceSid, + @JsonProperty("url") final URI url ) { - this.domainSid = domainSid; - this.configSid = configSid; - this.messagingServiceSid = messagingServiceSid; - this.fallbackUrl = fallbackUrl; this.callbackUrl = callbackUrl; + this.configSid = configSid; this.continueOnFailure = continueOnFailure; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; + this.domainSid = domainSid; + this.fallbackUrl = fallbackUrl; + this.messagingServiceSid = messagingServiceSid; this.url = url; } - public final String getDomainSid() { - return this.domainSid; - } - - public final String getConfigSid() { - return this.configSid; - } - - public final String getMessagingServiceSid() { - return this.messagingServiceSid; - } - - public final URI getFallbackUrl() { - return this.fallbackUrl; - } - - public final URI getCallbackUrl() { - return this.callbackUrl; - } - - public final Boolean getContinueOnFailure() { - return this.continueOnFailure; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final URI getUrl() { - return this.url; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -173,32 +151,34 @@ public boolean equals(final Object o) { } DomainConfigMessagingService other = (DomainConfigMessagingService) o; - return ( - Objects.equals(domainSid, other.domainSid) && - Objects.equals(configSid, other.configSid) && - Objects.equals(messagingServiceSid, other.messagingServiceSid) && - Objects.equals(fallbackUrl, other.fallbackUrl) && - Objects.equals(callbackUrl, other.callbackUrl) && - Objects.equals(continueOnFailure, other.continueOnFailure) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(url, other.url) + Objects.equals(callbackUrl, other.callbackUrl) && + Objects.equals(configSid, other.configSid) && + Objects.equals(continueOnFailure, other.continueOnFailure) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(domainSid, other.domainSid) && + Objects.equals(fallbackUrl, other.fallbackUrl) && + Objects.equals(messagingServiceSid, other.messagingServiceSid) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - domainSid, - configSid, - messagingServiceSid, - fallbackUrl, - callbackUrl, - continueOnFailure, - dateCreated, - dateUpdated, - url + callbackUrl, + configSid, + continueOnFailure, + dateCreated, + dateUpdated, + domainSid, + fallbackUrl, + messagingServiceSid, + url ); } + + } + diff --git a/src/main/java/com/twilio/rest/messaging/v1/DomainConfigMessagingServiceFetcher.java b/src/main/java/com/twilio/rest/messaging/v1/DomainConfigMessagingServiceFetcher.java index 6b36fd5588..a9295e70e8 100644 --- a/src/main/java/com/twilio/rest/messaging/v1/DomainConfigMessagingServiceFetcher.java +++ b/src/main/java/com/twilio/rest/messaging/v1/DomainConfigMessagingServiceFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.messaging.v1; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,57 +24,43 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class DomainConfigMessagingServiceFetcher - extends Fetcher { +public class DomainConfigMessagingServiceFetcher extends Fetcher { - private String pathMessagingServiceSid; + private String pathmessagingServiceSid; - public DomainConfigMessagingServiceFetcher( - final String pathMessagingServiceSid - ) { - this.pathMessagingServiceSid = pathMessagingServiceSid; + public DomainConfigMessagingServiceFetcher(final String pathmessagingServiceSid) { + this.pathmessagingServiceSid = pathmessagingServiceSid; } + @Override public DomainConfigMessagingService fetch(final TwilioRestClient client) { - String path = - "/v1/LinkShortening/MessagingService/{MessagingServiceSid}/DomainConfig"; - path = - path.replace( - "{" + "MessagingServiceSid" + "}", - this.pathMessagingServiceSid.toString() - ); + String path = "/v1/LinkShortening/MessagingService/{MessagingServiceSid}/DomainConfig"; + + path = path.replace("{" + "MessagingServiceSid" + "}", this.pathmessagingServiceSid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.MESSAGING.toString(), - path + HttpMethod.GET, + Domains.MESSAGING.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "DomainConfigMessagingService fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("DomainConfigMessagingService fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return DomainConfigMessagingService.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return DomainConfigMessagingService.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/messaging/v1/DomainConfigUpdater.java b/src/main/java/com/twilio/rest/messaging/v1/DomainConfigUpdater.java index 1ccceb0a7b..d4d42f9ba5 100644 --- a/src/main/java/com/twilio/rest/messaging/v1/DomainConfigUpdater.java +++ b/src/main/java/com/twilio/rest/messaging/v1/DomainConfigUpdater.java @@ -16,7 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; -import com.twilio.converter.Promoter; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,107 +26,100 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.net.URI; public class DomainConfigUpdater extends Updater { - - private String pathDomainSid; + private String pathdomainSid; private URI fallbackUrl; private URI callbackUrl; private Boolean continueOnFailure; private Boolean disableHttps; - public DomainConfigUpdater(final String pathDomainSid) { - this.pathDomainSid = pathDomainSid; + public DomainConfigUpdater(final String pathdomainSid) { + this.pathdomainSid = pathdomainSid; } + public DomainConfigUpdater setFallbackUrl(final URI fallbackUrl) { this.fallbackUrl = fallbackUrl; return this; } - public DomainConfigUpdater setFallbackUrl(final String fallbackUrl) { - return setFallbackUrl(Promoter.uriFromString(fallbackUrl)); - } public DomainConfigUpdater setCallbackUrl(final URI callbackUrl) { this.callbackUrl = callbackUrl; return this; } - public DomainConfigUpdater setCallbackUrl(final String callbackUrl) { - return setCallbackUrl(Promoter.uriFromString(callbackUrl)); - } - public DomainConfigUpdater setContinueOnFailure( - final Boolean continueOnFailure - ) { + public DomainConfigUpdater setContinueOnFailure(final Boolean continueOnFailure) { this.continueOnFailure = continueOnFailure; return this; } + public DomainConfigUpdater setDisableHttps(final Boolean disableHttps) { this.disableHttps = disableHttps; return this; } + @Override public DomainConfig update(final TwilioRestClient client) { + String path = "/v1/LinkShortening/Domains/{DomainSid}/Config"; - path = - path.replace( - "{" + "DomainSid" + "}", - this.pathDomainSid.toString() - ); + path = path.replace("{" + "DomainSid" + "}", this.pathdomainSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.MESSAGING.toString(), - path + HttpMethod.POST, + Domains.MESSAGING.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "DomainConfig update failed: Unable to connect to server" - ); + throw new ApiConnectionException("DomainConfig update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return DomainConfig.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return DomainConfig.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (fallbackUrl != null) { - request.addPostParam("FallbackUrl", fallbackUrl.toString()); + Serializer.toString(request, "FallbackUrl", fallbackUrl, ParameterType.URLENCODED); } + + if (callbackUrl != null) { - request.addPostParam("CallbackUrl", callbackUrl.toString()); + Serializer.toString(request, "CallbackUrl", callbackUrl, ParameterType.URLENCODED); } + + if (continueOnFailure != null) { - request.addPostParam( - "ContinueOnFailure", - continueOnFailure.toString() - ); + Serializer.toString(request, "ContinueOnFailure", continueOnFailure, ParameterType.URLENCODED); } + + if (disableHttps != null) { - request.addPostParam("DisableHttps", disableHttps.toString()); + Serializer.toString(request, "DisableHttps", disableHttps, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/messaging/v1/ExternalCampaign.java b/src/main/java/com/twilio/rest/messaging/v1/ExternalCampaign.java index f892c314da..d81d74ace7 100644 --- a/src/main/java/com/twilio/rest/messaging/v1/ExternalCampaign.java +++ b/src/main/java/com/twilio/rest/messaging/v1/ExternalCampaign.java @@ -18,43 +18,41 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.time.ZonedDateTime; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class ExternalCampaign extends Resource { - private static final long serialVersionUID = 211920409391157L; - public static ExternalCampaignCreator creator( - final String campaignId, - final String messagingServiceSid - ) { - return new ExternalCampaignCreator(campaignId, messagingServiceSid); + public static ExternalCampaignCreator creator(final String campaignId, final String messagingServiceSid) { + return new ExternalCampaignCreator( + campaignId, messagingServiceSid + ); } + /** * Converts a JSON String into a ExternalCampaign object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return ExternalCampaign object represented by the provided JSON */ - public static ExternalCampaign fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static ExternalCampaign fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, ExternalCampaign.class); @@ -69,14 +67,11 @@ public static ExternalCampaign fromJson( * Converts a JSON InputStream into a ExternalCampaign object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return ExternalCampaign object represented by the provided JSON */ - public static ExternalCampaign fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static ExternalCampaign fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, ExternalCampaign.class); @@ -87,45 +82,44 @@ public static ExternalCampaign fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; + @Getter private final String campaignId; - private final String messagingServiceSid; + @Getter private final ZonedDateTime dateCreated; + @Getter + private final String messagingServiceSid; + @Getter + private final String sid; @JsonCreator private ExternalCampaign( - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("campaign_id") final String campaignId, - @JsonProperty("messaging_service_sid") final String messagingServiceSid, - @JsonProperty("date_created") final String dateCreated + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("campaign_id") final String campaignId, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("messaging_service_sid") final String messagingServiceSid, + @JsonProperty("sid") final String sid ) { - this.sid = sid; this.accountSid = accountSid; this.campaignId = campaignId; + this.dateCreated = dateCreated; this.messagingServiceSid = messagingServiceSid; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - } - - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getCampaignId() { - return this.campaignId; - } - - public final String getMessagingServiceSid() { - return this.messagingServiceSid; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; + this.sid = sid; } @Override @@ -139,24 +133,26 @@ public boolean equals(final Object o) { } ExternalCampaign other = (ExternalCampaign) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(campaignId, other.campaignId) && - Objects.equals(messagingServiceSid, other.messagingServiceSid) && - Objects.equals(dateCreated, other.dateCreated) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(campaignId, other.campaignId) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(messagingServiceSid, other.messagingServiceSid) && + Objects.equals(sid, other.sid) ); } @Override public int hashCode() { return Objects.hash( - sid, - accountSid, - campaignId, - messagingServiceSid, - dateCreated + accountSid, + campaignId, + dateCreated, + messagingServiceSid, + sid ); } + + } + diff --git a/src/main/java/com/twilio/rest/messaging/v1/ExternalCampaignCreator.java b/src/main/java/com/twilio/rest/messaging/v1/ExternalCampaignCreator.java index 7748f64da4..472fe46a82 100644 --- a/src/main/java/com/twilio/rest/messaging/v1/ExternalCampaignCreator.java +++ b/src/main/java/com/twilio/rest/messaging/v1/ExternalCampaignCreator.java @@ -14,8 +14,11 @@ package com.twilio.rest.messaging.v1; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -31,84 +34,78 @@ public class ExternalCampaignCreator extends Creator { private String messagingServiceSid; private Boolean cnpMigration; - public ExternalCampaignCreator( - final String campaignId, - final String messagingServiceSid - ) { + public ExternalCampaignCreator(final String campaignId, final String messagingServiceSid) { this.campaignId = campaignId; this.messagingServiceSid = messagingServiceSid; } + public ExternalCampaignCreator setCampaignId(final String campaignId) { this.campaignId = campaignId; return this; } - public ExternalCampaignCreator setMessagingServiceSid( - final String messagingServiceSid - ) { + + public ExternalCampaignCreator setMessagingServiceSid(final String messagingServiceSid) { this.messagingServiceSid = messagingServiceSid; return this; } + public ExternalCampaignCreator setCnpMigration(final Boolean cnpMigration) { this.cnpMigration = cnpMigration; return this; } + @Override public ExternalCampaign create(final TwilioRestClient client) { + String path = "/v1/Services/PreregisteredUsa2p"; - path = - path.replace("{" + "CampaignId" + "}", this.campaignId.toString()); - path = - path.replace( - "{" + "MessagingServiceSid" + "}", - this.messagingServiceSid.toString() - ); Request request = new Request( - HttpMethod.POST, - Domains.MESSAGING.toString(), - path + HttpMethod.POST, + Domains.MESSAGING.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "ExternalCampaign creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("ExternalCampaign creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return ExternalCampaign.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return ExternalCampaign.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (campaignId != null) { - request.addPostParam("CampaignId", campaignId); + Serializer.toString(request, "CampaignId", campaignId, ParameterType.URLENCODED); } + + if (messagingServiceSid != null) { - request.addPostParam("MessagingServiceSid", messagingServiceSid); + Serializer.toString(request, "MessagingServiceSid", messagingServiceSid, ParameterType.URLENCODED); } + + if (cnpMigration != null) { - request.addPostParam("CnpMigration", cnpMigration.toString()); + Serializer.toString(request, "CnpMigration", cnpMigration, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/messaging/v1/LinkshorteningMessagingService.java b/src/main/java/com/twilio/rest/messaging/v1/LinkshorteningMessagingService.java index 1193f3f6f1..d128881fee 100644 --- a/src/main/java/com/twilio/rest/messaging/v1/LinkshorteningMessagingService.java +++ b/src/main/java/com/twilio/rest/messaging/v1/LinkshorteningMessagingService.java @@ -18,61 +18,50 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class LinkshorteningMessagingService extends Resource { - private static final long serialVersionUID = 242981332247911L; - public static LinkshorteningMessagingServiceCreator creator( - final String pathDomainSid, - final String pathMessagingServiceSid - ) { + public static LinkshorteningMessagingServiceCreator creator(final String pathdomainSid, final String pathmessagingServiceSid) { return new LinkshorteningMessagingServiceCreator( - pathDomainSid, - pathMessagingServiceSid + pathdomainSid, pathmessagingServiceSid ); } - public static LinkshorteningMessagingServiceDeleter deleter( - final String pathDomainSid, - final String pathMessagingServiceSid - ) { + + public static LinkshorteningMessagingServiceDeleter deleter(final String pathdomainSid, final String pathmessagingServiceSid) { return new LinkshorteningMessagingServiceDeleter( - pathDomainSid, - pathMessagingServiceSid + pathdomainSid, pathmessagingServiceSid ); } + /** * Converts a JSON String into a LinkshorteningMessagingService object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return LinkshorteningMessagingService object represented by the provided JSON */ - public static LinkshorteningMessagingService fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static LinkshorteningMessagingService fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { - return objectMapper.readValue( - json, - LinkshorteningMessagingService.class - ); + return objectMapper.readValue(json, LinkshorteningMessagingService.class); } catch (final JsonMappingException | JsonParseException e) { throw new ApiException(e.getMessage(), e); } catch (final IOException e) { @@ -84,20 +73,14 @@ public static LinkshorteningMessagingService fromJson( * Converts a JSON InputStream into a LinkshorteningMessagingService object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return LinkshorteningMessagingService object represented by the provided JSON */ - public static LinkshorteningMessagingService fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static LinkshorteningMessagingService fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { - return objectMapper.readValue( - json, - LinkshorteningMessagingService.class - ); + return objectMapper.readValue(json, LinkshorteningMessagingService.class); } catch (final JsonMappingException | JsonParseException e) { throw new ApiException(e.getMessage(), e); } catch (final IOException e) { @@ -105,33 +88,37 @@ public static LinkshorteningMessagingService fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String domainSid; + @Getter private final String messagingServiceSid; + @Getter private final URI url; @JsonCreator private LinkshorteningMessagingService( - @JsonProperty("domain_sid") final String domainSid, - @JsonProperty("messaging_service_sid") final String messagingServiceSid, - @JsonProperty("url") final URI url + @JsonProperty("domain_sid") final String domainSid, + @JsonProperty("messaging_service_sid") final String messagingServiceSid, + @JsonProperty("url") final URI url ) { this.domainSid = domainSid; this.messagingServiceSid = messagingServiceSid; this.url = url; } - public final String getDomainSid() { - return this.domainSid; - } - - public final String getMessagingServiceSid() { - return this.messagingServiceSid; - } - - public final URI getUrl() { - return this.url; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -142,18 +129,23 @@ public boolean equals(final Object o) { return false; } - LinkshorteningMessagingService other = - (LinkshorteningMessagingService) o; - + LinkshorteningMessagingService other = (LinkshorteningMessagingService) o; return ( - Objects.equals(domainSid, other.domainSid) && - Objects.equals(messagingServiceSid, other.messagingServiceSid) && - Objects.equals(url, other.url) + Objects.equals(domainSid, other.domainSid) && + Objects.equals(messagingServiceSid, other.messagingServiceSid) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { - return Objects.hash(domainSid, messagingServiceSid, url); + return Objects.hash( + domainSid, + messagingServiceSid, + url + ); } + + } + diff --git a/src/main/java/com/twilio/rest/messaging/v1/LinkshorteningMessagingServiceCreator.java b/src/main/java/com/twilio/rest/messaging/v1/LinkshorteningMessagingServiceCreator.java index c385bc9402..5cf07eec72 100644 --- a/src/main/java/com/twilio/rest/messaging/v1/LinkshorteningMessagingServiceCreator.java +++ b/src/main/java/com/twilio/rest/messaging/v1/LinkshorteningMessagingServiceCreator.java @@ -14,8 +14,8 @@ package com.twilio.rest.messaging.v1; + import com.twilio.base.Creator; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,66 +25,47 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class LinkshorteningMessagingServiceCreator - extends Creator { +public class LinkshorteningMessagingServiceCreator extends Creator { - private String pathDomainSid; - private String pathMessagingServiceSid; + private String pathdomainSid; + private String pathmessagingServiceSid; - public LinkshorteningMessagingServiceCreator( - final String pathDomainSid, - final String pathMessagingServiceSid - ) { - this.pathDomainSid = pathDomainSid; - this.pathMessagingServiceSid = pathMessagingServiceSid; + public LinkshorteningMessagingServiceCreator(final String pathdomainSid, final String pathmessagingServiceSid) { + this.pathdomainSid = pathdomainSid; + this.pathmessagingServiceSid = pathmessagingServiceSid; } + @Override - public LinkshorteningMessagingService create( - final TwilioRestClient client - ) { - String path = - "/v1/LinkShortening/Domains/{DomainSid}/MessagingServices/{MessagingServiceSid}"; + public LinkshorteningMessagingService create(final TwilioRestClient client) { + + String path = "/v1/LinkShortening/Domains/{DomainSid}/MessagingServices/{MessagingServiceSid}"; + + path = path.replace("{" + "DomainSid" + "}", this.pathdomainSid.toString()); + path = path.replace("{" + "MessagingServiceSid" + "}", this.pathmessagingServiceSid.toString()); - path = - path.replace( - "{" + "DomainSid" + "}", - this.pathDomainSid.toString() - ); - path = - path.replace( - "{" + "MessagingServiceSid" + "}", - this.pathMessagingServiceSid.toString() - ); Request request = new Request( - HttpMethod.POST, - Domains.MESSAGING.toString(), - path + HttpMethod.POST, + Domains.MESSAGING.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "LinkshorteningMessagingService creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("LinkshorteningMessagingService creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return LinkshorteningMessagingService.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return LinkshorteningMessagingService.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/messaging/v1/LinkshorteningMessagingServiceDeleter.java b/src/main/java/com/twilio/rest/messaging/v1/LinkshorteningMessagingServiceDeleter.java index e26fe24c5a..0d75017407 100644 --- a/src/main/java/com/twilio/rest/messaging/v1/LinkshorteningMessagingServiceDeleter.java +++ b/src/main/java/com/twilio/rest/messaging/v1/LinkshorteningMessagingServiceDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.messaging.v1; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,58 +24,43 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class LinkshorteningMessagingServiceDeleter - extends Deleter { +public class LinkshorteningMessagingServiceDeleter extends Deleter { - private String pathDomainSid; - private String pathMessagingServiceSid; + private String pathdomainSid; + private String pathmessagingServiceSid; - public LinkshorteningMessagingServiceDeleter( - final String pathDomainSid, - final String pathMessagingServiceSid - ) { - this.pathDomainSid = pathDomainSid; - this.pathMessagingServiceSid = pathMessagingServiceSid; + public LinkshorteningMessagingServiceDeleter(final String pathdomainSid, final String pathmessagingServiceSid) { + this.pathdomainSid = pathdomainSid; + this.pathmessagingServiceSid = pathmessagingServiceSid; } + @Override public boolean delete(final TwilioRestClient client) { - String path = - "/v1/LinkShortening/Domains/{DomainSid}/MessagingServices/{MessagingServiceSid}"; - path = - path.replace( - "{" + "DomainSid" + "}", - this.pathDomainSid.toString() - ); - path = - path.replace( - "{" + "MessagingServiceSid" + "}", - this.pathMessagingServiceSid.toString() - ); + String path = "/v1/LinkShortening/Domains/{DomainSid}/MessagingServices/{MessagingServiceSid}"; + + path = path.replace("{" + "DomainSid" + "}", this.pathdomainSid.toString()); + path = path.replace("{" + "MessagingServiceSid" + "}", this.pathmessagingServiceSid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.MESSAGING.toString(), - path + HttpMethod.DELETE, + Domains.MESSAGING.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "LinkshorteningMessagingService delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("LinkshorteningMessagingService delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/messaging/v1/LinkshorteningMessagingServiceDomainAssociation.java b/src/main/java/com/twilio/rest/messaging/v1/LinkshorteningMessagingServiceDomainAssociation.java index a187053131..12e20d4780 100644 --- a/src/main/java/com/twilio/rest/messaging/v1/LinkshorteningMessagingServiceDomainAssociation.java +++ b/src/main/java/com/twilio/rest/messaging/v1/LinkshorteningMessagingServiceDomainAssociation.java @@ -18,49 +18,43 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class LinkshorteningMessagingServiceDomainAssociation extends Resource { - private static final long serialVersionUID = 242981332247911L; - public static LinkshorteningMessagingServiceDomainAssociationFetcher fetcher( - final String pathMessagingServiceSid - ) { + public static LinkshorteningMessagingServiceDomainAssociationFetcher fetcher(final String pathmessagingServiceSid) { return new LinkshorteningMessagingServiceDomainAssociationFetcher( - pathMessagingServiceSid + pathmessagingServiceSid ); } + /** * Converts a JSON String into a LinkshorteningMessagingServiceDomainAssociation object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return LinkshorteningMessagingServiceDomainAssociation object represented by the provided JSON */ - public static LinkshorteningMessagingServiceDomainAssociation fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static LinkshorteningMessagingServiceDomainAssociation fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { - return objectMapper.readValue( - json, - LinkshorteningMessagingServiceDomainAssociation.class - ); + return objectMapper.readValue(json, LinkshorteningMessagingServiceDomainAssociation.class); } catch (final JsonMappingException | JsonParseException e) { throw new ApiException(e.getMessage(), e); } catch (final IOException e) { @@ -72,20 +66,14 @@ public static LinkshorteningMessagingServiceDomainAssociation fromJson( * Converts a JSON InputStream into a LinkshorteningMessagingServiceDomainAssociation object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return LinkshorteningMessagingServiceDomainAssociation object represented by the provided JSON */ - public static LinkshorteningMessagingServiceDomainAssociation fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static LinkshorteningMessagingServiceDomainAssociation fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { - return objectMapper.readValue( - json, - LinkshorteningMessagingServiceDomainAssociation.class - ); + return objectMapper.readValue(json, LinkshorteningMessagingServiceDomainAssociation.class); } catch (final JsonMappingException | JsonParseException e) { throw new ApiException(e.getMessage(), e); } catch (final IOException e) { @@ -93,33 +81,37 @@ public static LinkshorteningMessagingServiceDomainAssociation fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String domainSid; + @Getter private final String messagingServiceSid; + @Getter private final URI url; @JsonCreator private LinkshorteningMessagingServiceDomainAssociation( - @JsonProperty("domain_sid") final String domainSid, - @JsonProperty("messaging_service_sid") final String messagingServiceSid, - @JsonProperty("url") final URI url + @JsonProperty("domain_sid") final String domainSid, + @JsonProperty("messaging_service_sid") final String messagingServiceSid, + @JsonProperty("url") final URI url ) { this.domainSid = domainSid; this.messagingServiceSid = messagingServiceSid; this.url = url; } - public final String getDomainSid() { - return this.domainSid; - } - - public final String getMessagingServiceSid() { - return this.messagingServiceSid; - } - - public final URI getUrl() { - return this.url; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -130,18 +122,23 @@ public boolean equals(final Object o) { return false; } - LinkshorteningMessagingServiceDomainAssociation other = - (LinkshorteningMessagingServiceDomainAssociation) o; - + LinkshorteningMessagingServiceDomainAssociation other = (LinkshorteningMessagingServiceDomainAssociation) o; return ( - Objects.equals(domainSid, other.domainSid) && - Objects.equals(messagingServiceSid, other.messagingServiceSid) && - Objects.equals(url, other.url) + Objects.equals(domainSid, other.domainSid) && + Objects.equals(messagingServiceSid, other.messagingServiceSid) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { - return Objects.hash(domainSid, messagingServiceSid, url); + return Objects.hash( + domainSid, + messagingServiceSid, + url + ); } + + } + diff --git a/src/main/java/com/twilio/rest/messaging/v1/LinkshorteningMessagingServiceDomainAssociationFetcher.java b/src/main/java/com/twilio/rest/messaging/v1/LinkshorteningMessagingServiceDomainAssociationFetcher.java index 4e19b90d94..c3bf554851 100644 --- a/src/main/java/com/twilio/rest/messaging/v1/LinkshorteningMessagingServiceDomainAssociationFetcher.java +++ b/src/main/java/com/twilio/rest/messaging/v1/LinkshorteningMessagingServiceDomainAssociationFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.messaging.v1; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,59 +24,43 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class LinkshorteningMessagingServiceDomainAssociationFetcher - extends Fetcher { +public class LinkshorteningMessagingServiceDomainAssociationFetcher extends Fetcher { - private String pathMessagingServiceSid; + private String pathmessagingServiceSid; - public LinkshorteningMessagingServiceDomainAssociationFetcher( - final String pathMessagingServiceSid - ) { - this.pathMessagingServiceSid = pathMessagingServiceSid; + public LinkshorteningMessagingServiceDomainAssociationFetcher(final String pathmessagingServiceSid) { + this.pathmessagingServiceSid = pathmessagingServiceSid; } + @Override - public LinkshorteningMessagingServiceDomainAssociation fetch( - final TwilioRestClient client - ) { - String path = - "/v1/LinkShortening/MessagingServices/{MessagingServiceSid}/Domain"; + public LinkshorteningMessagingServiceDomainAssociation fetch(final TwilioRestClient client) { + + String path = "/v1/LinkShortening/MessagingServices/{MessagingServiceSid}/Domain"; + + path = path.replace("{" + "MessagingServiceSid" + "}", this.pathmessagingServiceSid.toString()); - path = - path.replace( - "{" + "MessagingServiceSid" + "}", - this.pathMessagingServiceSid.toString() - ); Request request = new Request( - HttpMethod.GET, - Domains.MESSAGING.toString(), - path + HttpMethod.GET, + Domains.MESSAGING.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "LinkshorteningMessagingServiceDomainAssociation fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("LinkshorteningMessagingServiceDomainAssociation fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return LinkshorteningMessagingServiceDomainAssociation.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return LinkshorteningMessagingServiceDomainAssociation.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/messaging/v1/RequestManagedCert.java b/src/main/java/com/twilio/rest/messaging/v1/RequestManagedCert.java index 1f3075e35b..36df48cbfe 100644 --- a/src/main/java/com/twilio/rest/messaging/v1/RequestManagedCert.java +++ b/src/main/java/com/twilio/rest/messaging/v1/RequestManagedCert.java @@ -18,43 +18,42 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class RequestManagedCert extends Resource { - private static final long serialVersionUID = 86009690306630L; - public static RequestManagedCertUpdater updater( - final String pathDomainSid - ) { - return new RequestManagedCertUpdater(pathDomainSid); + public static RequestManagedCertUpdater updater(final String pathdomainSid) { + return new RequestManagedCertUpdater( + pathdomainSid + ); } + /** * Converts a JSON String into a RequestManagedCert object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return RequestManagedCert object represented by the provided JSON */ - public static RequestManagedCert fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static RequestManagedCert fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, RequestManagedCert.class); @@ -69,14 +68,11 @@ public static RequestManagedCert fromJson( * Converts a JSON InputStream into a RequestManagedCert object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return RequestManagedCert object represented by the provided JSON */ - public static RequestManagedCert fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static RequestManagedCert fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, RequestManagedCert.class); @@ -87,73 +83,62 @@ public static RequestManagedCert fromJson( } } - private final String domainSid; - private final ZonedDateTime dateUpdated; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter + private final String certificateSid; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateExpires; + @Getter + private final ZonedDateTime dateUpdated; + @Getter private final URI domainName; - private final String certificateSid; - private final URI url; + @Getter + private final String domainSid; + @Getter private final Boolean managed; + @Getter private final Boolean requesting; + @Getter + private final URI url; @JsonCreator private RequestManagedCert( - @JsonProperty("domain_sid") final String domainSid, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_expires") final String dateExpires, - @JsonProperty("domain_name") final URI domainName, - @JsonProperty("certificate_sid") final String certificateSid, - @JsonProperty("url") final URI url, - @JsonProperty("managed") final Boolean managed, - @JsonProperty("requesting") final Boolean requesting + @JsonProperty("certificate_sid") final String certificateSid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_expires") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateExpires, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("domain_name") final URI domainName, + @JsonProperty("domain_sid") final String domainSid, + @JsonProperty("managed") final Boolean managed, + @JsonProperty("requesting") final Boolean requesting, + @JsonProperty("url") final URI url ) { - this.domainSid = domainSid; - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateExpires = DateConverter.iso8601DateTimeFromString(dateExpires); - this.domainName = domainName; this.certificateSid = certificateSid; - this.url = url; + this.dateCreated = dateCreated; + this.dateExpires = dateExpires; + this.dateUpdated = dateUpdated; + this.domainName = domainName; + this.domainSid = domainSid; this.managed = managed; this.requesting = requesting; - } - - public final String getDomainSid() { - return this.domainSid; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateExpires() { - return this.dateExpires; - } - - public final URI getDomainName() { - return this.domainName; - } - - public final String getCertificateSid() { - return this.certificateSid; - } - - public final URI getUrl() { - return this.url; - } - - public final Boolean getManaged() { - return this.managed; - } - - public final Boolean getRequesting() { - return this.requesting; + this.url = url; } @Override @@ -167,32 +152,34 @@ public boolean equals(final Object o) { } RequestManagedCert other = (RequestManagedCert) o; - return ( - Objects.equals(domainSid, other.domainSid) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateExpires, other.dateExpires) && - Objects.equals(domainName, other.domainName) && - Objects.equals(certificateSid, other.certificateSid) && - Objects.equals(url, other.url) && - Objects.equals(managed, other.managed) && - Objects.equals(requesting, other.requesting) + Objects.equals(certificateSid, other.certificateSid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateExpires, other.dateExpires) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(domainName, other.domainName) && + Objects.equals(domainSid, other.domainSid) && + Objects.equals(managed, other.managed) && + Objects.equals(requesting, other.requesting) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - domainSid, - dateUpdated, - dateCreated, - dateExpires, - domainName, - certificateSid, - url, - managed, - requesting + certificateSid, + dateCreated, + dateExpires, + dateUpdated, + domainName, + domainSid, + managed, + requesting, + url ); } + + } + diff --git a/src/main/java/com/twilio/rest/messaging/v1/RequestManagedCertUpdater.java b/src/main/java/com/twilio/rest/messaging/v1/RequestManagedCertUpdater.java index 6f62086240..3807e36d4a 100644 --- a/src/main/java/com/twilio/rest/messaging/v1/RequestManagedCertUpdater.java +++ b/src/main/java/com/twilio/rest/messaging/v1/RequestManagedCertUpdater.java @@ -15,7 +15,6 @@ package com.twilio.rest.messaging.v1; import com.twilio.base.Updater; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -26,52 +25,42 @@ import com.twilio.rest.Domains; public class RequestManagedCertUpdater extends Updater { + private String pathdomainSid; - private String pathDomainSid; - - public RequestManagedCertUpdater(final String pathDomainSid) { - this.pathDomainSid = pathDomainSid; + public RequestManagedCertUpdater(final String pathdomainSid) { + this.pathdomainSid = pathdomainSid; } + @Override public RequestManagedCert update(final TwilioRestClient client) { - String path = - "/v1/LinkShortening/Domains/{DomainSid}/RequestManagedCert"; - path = - path.replace( - "{" + "DomainSid" + "}", - this.pathDomainSid.toString() - ); + String path = "/v1/LinkShortening/Domains/{DomainSid}/RequestManagedCert"; + + path = path.replace("{" + "DomainSid" + "}", this.pathdomainSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.MESSAGING.toString(), - path + HttpMethod.POST, + Domains.MESSAGING.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "RequestManagedCert update failed: Unable to connect to server" - ); + throw new ApiConnectionException("RequestManagedCert update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return RequestManagedCert.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return RequestManagedCert.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/messaging/v1/Service.java b/src/main/java/com/twilio/rest/messaging/v1/Service.java index 3775bf4572..fa0f9deb52 100644 --- a/src/main/java/com/twilio/rest/messaging/v1/Service.java +++ b/src/main/java/com/twilio/rest/messaging/v1/Service.java @@ -18,61 +18,95 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.http.HttpMethod; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Service extends Resource { - private static final long serialVersionUID = 59018314319448L; public static ServiceCreator creator(final String friendlyName) { - return new ServiceCreator(friendlyName); + return new ServiceCreator( + friendlyName + ); } - public static ServiceDeleter deleter(final String pathSid) { - return new ServiceDeleter(pathSid); + + public static ServiceDeleter deleter(final String pathsid) { + return new ServiceDeleter( + pathsid + ); } - public static ServiceFetcher fetcher(final String pathSid) { - return new ServiceFetcher(pathSid); + + public static ServiceFetcher fetcher(final String pathsid) { + return new ServiceFetcher( + pathsid + ); } + public static ServiceReader reader() { - return new ServiceReader(); + return new ServiceReader( + + ); } - public static ServiceUpdater updater(final String pathSid) { - return new ServiceUpdater(pathSid); + + public static ServiceUpdater updater(final String pathsid) { + return new ServiceUpdater( + pathsid + ); } + + public enum ScanMessageContent { + INHERIT("inherit"), + ENABLE("enable"), + DISABLE("disable"); + + private final String value; + + private ScanMessageContent(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static ScanMessageContent forValue(final String value) { + return Promoter.enumFromString(value, ScanMessageContent.values()); + } + } + + /** * Converts a JSON String into a Service object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Service object represented by the provided JSON */ - public static Service fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Service fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Service.class); @@ -87,14 +121,11 @@ public static Service fromJson( * Converts a JSON InputStream into a Service object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Service object represented by the provided JSON */ - public static Service fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Service fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Service.class); @@ -105,179 +136,117 @@ public static Service fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String friendlyName; + @Getter + private final Boolean areaCodeGeomatch; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; - private final URI inboundRequestUrl; - private final HttpMethod inboundMethod; - private final URI fallbackUrl; + @Getter private final HttpMethod fallbackMethod; - private final URI statusCallback; - private final Boolean stickySender; + @Getter + private final Boolean fallbackToLongCode; + @Getter + private final URI fallbackUrl; + @Getter + private final String friendlyName; + @Getter + private final HttpMethod inboundMethod; + @Getter + private final URI inboundRequestUrl; + @Getter + private final Map links; + @Getter private final Boolean mmsConverter; - private final Boolean smartEncoding; + @Getter private final Service.ScanMessageContent scanMessageContent; - private final Boolean fallbackToLongCode; - private final Boolean areaCodeGeomatch; + @Getter + private final String sid; + @Getter + private final Boolean smartEncoding; + @Getter + private final URI statusCallback; + @Getter + private final Boolean stickySender; + @Getter private final Boolean synchronousValidation; - private final Integer validityPeriod; + @Getter private final URI url; - private final Map links; - private final String usecase; + @Getter private final Boolean usAppToPersonRegistered; + @Getter private final Boolean useInboundWebhookOnNumber; + @Getter + private final String usecase; + @Getter + private final Integer validityPeriod; @JsonCreator private Service( - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("inbound_request_url") final URI inboundRequestUrl, - @JsonProperty("inbound_method") final HttpMethod inboundMethod, - @JsonProperty("fallback_url") final URI fallbackUrl, - @JsonProperty("fallback_method") final HttpMethod fallbackMethod, - @JsonProperty("status_callback") final URI statusCallback, - @JsonProperty("sticky_sender") final Boolean stickySender, - @JsonProperty("mms_converter") final Boolean mmsConverter, - @JsonProperty("smart_encoding") final Boolean smartEncoding, - @JsonProperty( - "scan_message_content" - ) final Service.ScanMessageContent scanMessageContent, - @JsonProperty("fallback_to_long_code") final Boolean fallbackToLongCode, - @JsonProperty("area_code_geomatch") final Boolean areaCodeGeomatch, - @JsonProperty( - "synchronous_validation" - ) final Boolean synchronousValidation, - @JsonProperty("validity_period") final Integer validityPeriod, - @JsonProperty("url") final URI url, - @JsonProperty("links") final Map links, - @JsonProperty("usecase") final String usecase, - @JsonProperty( - "us_app_to_person_registered" - ) final Boolean usAppToPersonRegistered, - @JsonProperty( - "use_inbound_webhook_on_number" - ) final Boolean useInboundWebhookOnNumber + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("area_code_geomatch") final Boolean areaCodeGeomatch, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("fallback_method") final HttpMethod fallbackMethod, + @JsonProperty("fallback_to_long_code") final Boolean fallbackToLongCode, + @JsonProperty("fallback_url") final URI fallbackUrl, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("inbound_method") final HttpMethod inboundMethod, + @JsonProperty("inbound_request_url") final URI inboundRequestUrl, + @JsonProperty("links") final Map links, + @JsonProperty("mms_converter") final Boolean mmsConverter, + @JsonProperty("scan_message_content") final Service.ScanMessageContent scanMessageContent, + @JsonProperty("sid") final String sid, + @JsonProperty("smart_encoding") final Boolean smartEncoding, + @JsonProperty("status_callback") final URI statusCallback, + @JsonProperty("sticky_sender") final Boolean stickySender, + @JsonProperty("synchronous_validation") final Boolean synchronousValidation, + @JsonProperty("url") final URI url, + @JsonProperty("us_app_to_person_registered") final Boolean usAppToPersonRegistered, + @JsonProperty("use_inbound_webhook_on_number") final Boolean useInboundWebhookOnNumber, + @JsonProperty("usecase") final String usecase, + @JsonProperty("validity_period") final Integer validityPeriod ) { - this.sid = sid; this.accountSid = accountSid; + this.areaCodeGeomatch = areaCodeGeomatch; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; + this.fallbackMethod = fallbackMethod; + this.fallbackToLongCode = fallbackToLongCode; + this.fallbackUrl = fallbackUrl; this.friendlyName = friendlyName; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); - this.inboundRequestUrl = inboundRequestUrl; this.inboundMethod = inboundMethod; - this.fallbackUrl = fallbackUrl; - this.fallbackMethod = fallbackMethod; - this.statusCallback = statusCallback; - this.stickySender = stickySender; + this.inboundRequestUrl = inboundRequestUrl; + this.links = links; this.mmsConverter = mmsConverter; - this.smartEncoding = smartEncoding; this.scanMessageContent = scanMessageContent; - this.fallbackToLongCode = fallbackToLongCode; - this.areaCodeGeomatch = areaCodeGeomatch; + this.sid = sid; + this.smartEncoding = smartEncoding; + this.statusCallback = statusCallback; + this.stickySender = stickySender; this.synchronousValidation = synchronousValidation; - this.validityPeriod = validityPeriod; this.url = url; - this.links = links; - this.usecase = usecase; this.usAppToPersonRegistered = usAppToPersonRegistered; this.useInboundWebhookOnNumber = useInboundWebhookOnNumber; - } - - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final URI getInboundRequestUrl() { - return this.inboundRequestUrl; - } - - public final HttpMethod getInboundMethod() { - return this.inboundMethod; - } - - public final URI getFallbackUrl() { - return this.fallbackUrl; - } - - public final HttpMethod getFallbackMethod() { - return this.fallbackMethod; - } - - public final URI getStatusCallback() { - return this.statusCallback; - } - - public final Boolean getStickySender() { - return this.stickySender; - } - - public final Boolean getMmsConverter() { - return this.mmsConverter; - } - - public final Boolean getSmartEncoding() { - return this.smartEncoding; - } - - public final Service.ScanMessageContent getScanMessageContent() { - return this.scanMessageContent; - } - - public final Boolean getFallbackToLongCode() { - return this.fallbackToLongCode; - } - - public final Boolean getAreaCodeGeomatch() { - return this.areaCodeGeomatch; - } - - public final Boolean getSynchronousValidation() { - return this.synchronousValidation; - } - - public final Integer getValidityPeriod() { - return this.validityPeriod; - } - - public final URI getUrl() { - return this.url; - } - - public final Map getLinks() { - return this.links; - } - - public final String getUsecase() { - return this.usecase; - } - - public final Boolean getUsAppToPersonRegistered() { - return this.usAppToPersonRegistered; - } - - public final Boolean getUseInboundWebhookOnNumber() { - return this.useInboundWebhookOnNumber; + this.usecase = usecase; + this.validityPeriod = validityPeriod; } @Override @@ -291,90 +260,62 @@ public boolean equals(final Object o) { } Service other = (Service) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(inboundRequestUrl, other.inboundRequestUrl) && - Objects.equals(inboundMethod, other.inboundMethod) && - Objects.equals(fallbackUrl, other.fallbackUrl) && - Objects.equals(fallbackMethod, other.fallbackMethod) && - Objects.equals(statusCallback, other.statusCallback) && - Objects.equals(stickySender, other.stickySender) && - Objects.equals(mmsConverter, other.mmsConverter) && - Objects.equals(smartEncoding, other.smartEncoding) && - Objects.equals(scanMessageContent, other.scanMessageContent) && - Objects.equals(fallbackToLongCode, other.fallbackToLongCode) && - Objects.equals(areaCodeGeomatch, other.areaCodeGeomatch) && - Objects.equals( - synchronousValidation, - other.synchronousValidation - ) && - Objects.equals(validityPeriod, other.validityPeriod) && - Objects.equals(url, other.url) && - Objects.equals(links, other.links) && - Objects.equals(usecase, other.usecase) && - Objects.equals( - usAppToPersonRegistered, - other.usAppToPersonRegistered - ) && - Objects.equals( - useInboundWebhookOnNumber, - other.useInboundWebhookOnNumber - ) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(areaCodeGeomatch, other.areaCodeGeomatch) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(fallbackMethod, other.fallbackMethod) && + Objects.equals(fallbackToLongCode, other.fallbackToLongCode) && + Objects.equals(fallbackUrl, other.fallbackUrl) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(inboundMethod, other.inboundMethod) && + Objects.equals(inboundRequestUrl, other.inboundRequestUrl) && + Objects.equals(links, other.links) && + Objects.equals(mmsConverter, other.mmsConverter) && + Objects.equals(scanMessageContent, other.scanMessageContent) && + Objects.equals(sid, other.sid) && + Objects.equals(smartEncoding, other.smartEncoding) && + Objects.equals(statusCallback, other.statusCallback) && + Objects.equals(stickySender, other.stickySender) && + Objects.equals(synchronousValidation, other.synchronousValidation) && + Objects.equals(url, other.url) && + Objects.equals(usAppToPersonRegistered, other.usAppToPersonRegistered) && + Objects.equals(useInboundWebhookOnNumber, other.useInboundWebhookOnNumber) && + Objects.equals(usecase, other.usecase) && + Objects.equals(validityPeriod, other.validityPeriod) ); } @Override public int hashCode() { return Objects.hash( - sid, - accountSid, - friendlyName, - dateCreated, - dateUpdated, - inboundRequestUrl, - inboundMethod, - fallbackUrl, - fallbackMethod, - statusCallback, - stickySender, - mmsConverter, - smartEncoding, - scanMessageContent, - fallbackToLongCode, - areaCodeGeomatch, - synchronousValidation, - validityPeriod, - url, - links, - usecase, - usAppToPersonRegistered, - useInboundWebhookOnNumber + accountSid, + areaCodeGeomatch, + dateCreated, + dateUpdated, + fallbackMethod, + fallbackToLongCode, + fallbackUrl, + friendlyName, + inboundMethod, + inboundRequestUrl, + links, + mmsConverter, + scanMessageContent, + sid, + smartEncoding, + statusCallback, + stickySender, + synchronousValidation, + url, + usAppToPersonRegistered, + useInboundWebhookOnNumber, + usecase, + validityPeriod ); } - public enum ScanMessageContent { - INHERIT("inherit"), - ENABLE("enable"), - DISABLE("disable"); - - private final String value; - - private ScanMessageContent(final String value) { - this.value = value; - } - public String toString() { - return value; - } - - @JsonCreator - public static ScanMessageContent forValue(final String value) { - return Promoter.enumFromString(value, ScanMessageContent.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/messaging/v1/ServiceCreator.java b/src/main/java/com/twilio/rest/messaging/v1/ServiceCreator.java index b212f813ad..e8543e4f8f 100644 --- a/src/main/java/com/twilio/rest/messaging/v1/ServiceCreator.java +++ b/src/main/java/com/twilio/rest/messaging/v1/ServiceCreator.java @@ -14,9 +14,11 @@ package com.twilio.rest.messaging.v1; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; -import com.twilio.converter.Promoter; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,7 +27,7 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -import java.net.URI; + import java.net.URI; public class ServiceCreator extends Creator { @@ -51,138 +53,128 @@ public ServiceCreator(final String friendlyName) { this.friendlyName = friendlyName; } + public ServiceCreator setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + public ServiceCreator setInboundRequestUrl(final URI inboundRequestUrl) { this.inboundRequestUrl = inboundRequestUrl; return this; } - public ServiceCreator setInboundRequestUrl(final String inboundRequestUrl) { - return setInboundRequestUrl(Promoter.uriFromString(inboundRequestUrl)); - } public ServiceCreator setInboundMethod(final HttpMethod inboundMethod) { this.inboundMethod = inboundMethod; return this; } + public ServiceCreator setFallbackUrl(final URI fallbackUrl) { this.fallbackUrl = fallbackUrl; return this; } - public ServiceCreator setFallbackUrl(final String fallbackUrl) { - return setFallbackUrl(Promoter.uriFromString(fallbackUrl)); - } public ServiceCreator setFallbackMethod(final HttpMethod fallbackMethod) { this.fallbackMethod = fallbackMethod; return this; } + public ServiceCreator setStatusCallback(final URI statusCallback) { this.statusCallback = statusCallback; return this; } - public ServiceCreator setStatusCallback(final String statusCallback) { - return setStatusCallback(Promoter.uriFromString(statusCallback)); - } public ServiceCreator setStickySender(final Boolean stickySender) { this.stickySender = stickySender; return this; } + public ServiceCreator setMmsConverter(final Boolean mmsConverter) { this.mmsConverter = mmsConverter; return this; } + public ServiceCreator setSmartEncoding(final Boolean smartEncoding) { this.smartEncoding = smartEncoding; return this; } - public ServiceCreator setScanMessageContent( - final Service.ScanMessageContent scanMessageContent - ) { + + public ServiceCreator setScanMessageContent(final Service.ScanMessageContent scanMessageContent) { this.scanMessageContent = scanMessageContent; return this; } - public ServiceCreator setFallbackToLongCode( - final Boolean fallbackToLongCode - ) { + + public ServiceCreator setFallbackToLongCode(final Boolean fallbackToLongCode) { this.fallbackToLongCode = fallbackToLongCode; return this; } + public ServiceCreator setAreaCodeGeomatch(final Boolean areaCodeGeomatch) { this.areaCodeGeomatch = areaCodeGeomatch; return this; } + public ServiceCreator setValidityPeriod(final Integer validityPeriod) { this.validityPeriod = validityPeriod; return this; } - public ServiceCreator setSynchronousValidation( - final Boolean synchronousValidation - ) { + + public ServiceCreator setSynchronousValidation(final Boolean synchronousValidation) { this.synchronousValidation = synchronousValidation; return this; } + public ServiceCreator setUsecase(final String usecase) { this.usecase = usecase; return this; } - public ServiceCreator setUseInboundWebhookOnNumber( - final Boolean useInboundWebhookOnNumber - ) { + + public ServiceCreator setUseInboundWebhookOnNumber(final Boolean useInboundWebhookOnNumber) { this.useInboundWebhookOnNumber = useInboundWebhookOnNumber; return this; } + @Override public Service create(final TwilioRestClient client) { + String path = "/v1/Services"; - path = - path.replace( - "{" + "FriendlyName" + "}", - this.friendlyName.toString() - ); Request request = new Request( - HttpMethod.POST, - Domains.MESSAGING.toString(), - path + HttpMethod.POST, + Domains.MESSAGING.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Service creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("Service creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -191,71 +183,86 @@ public Service create(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + if (inboundRequestUrl != null) { - request.addPostParam( - "InboundRequestUrl", - inboundRequestUrl.toString() - ); + Serializer.toString(request, "InboundRequestUrl", inboundRequestUrl, ParameterType.URLENCODED); } + + if (inboundMethod != null) { - request.addPostParam("InboundMethod", inboundMethod.toString()); + Serializer.toString(request, "InboundMethod", inboundMethod, ParameterType.URLENCODED); } + + if (fallbackUrl != null) { - request.addPostParam("FallbackUrl", fallbackUrl.toString()); + Serializer.toString(request, "FallbackUrl", fallbackUrl, ParameterType.URLENCODED); } + + if (fallbackMethod != null) { - request.addPostParam("FallbackMethod", fallbackMethod.toString()); + Serializer.toString(request, "FallbackMethod", fallbackMethod, ParameterType.URLENCODED); } + + if (statusCallback != null) { - request.addPostParam("StatusCallback", statusCallback.toString()); + Serializer.toString(request, "StatusCallback", statusCallback, ParameterType.URLENCODED); } + + if (stickySender != null) { - request.addPostParam("StickySender", stickySender.toString()); + Serializer.toString(request, "StickySender", stickySender, ParameterType.URLENCODED); } + + if (mmsConverter != null) { - request.addPostParam("MmsConverter", mmsConverter.toString()); + Serializer.toString(request, "MmsConverter", mmsConverter, ParameterType.URLENCODED); } + + if (smartEncoding != null) { - request.addPostParam("SmartEncoding", smartEncoding.toString()); + Serializer.toString(request, "SmartEncoding", smartEncoding, ParameterType.URLENCODED); } + + if (scanMessageContent != null) { - request.addPostParam( - "ScanMessageContent", - scanMessageContent.toString() - ); + Serializer.toString(request, "ScanMessageContent", scanMessageContent, ParameterType.URLENCODED); } + + if (fallbackToLongCode != null) { - request.addPostParam( - "FallbackToLongCode", - fallbackToLongCode.toString() - ); + Serializer.toString(request, "FallbackToLongCode", fallbackToLongCode, ParameterType.URLENCODED); } + + if (areaCodeGeomatch != null) { - request.addPostParam( - "AreaCodeGeomatch", - areaCodeGeomatch.toString() - ); + Serializer.toString(request, "AreaCodeGeomatch", areaCodeGeomatch, ParameterType.URLENCODED); } + + if (validityPeriod != null) { - request.addPostParam("ValidityPeriod", validityPeriod.toString()); + Serializer.toString(request, "ValidityPeriod", validityPeriod, ParameterType.URLENCODED); } + + if (synchronousValidation != null) { - request.addPostParam( - "SynchronousValidation", - synchronousValidation.toString() - ); + Serializer.toString(request, "SynchronousValidation", synchronousValidation, ParameterType.URLENCODED); } + + if (usecase != null) { - request.addPostParam("Usecase", usecase); + Serializer.toString(request, "Usecase", usecase, ParameterType.URLENCODED); } + + if (useInboundWebhookOnNumber != null) { - request.addPostParam( - "UseInboundWebhookOnNumber", - useInboundWebhookOnNumber.toString() - ); + Serializer.toString(request, "UseInboundWebhookOnNumber", useInboundWebhookOnNumber, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/messaging/v1/ServiceDeleter.java b/src/main/java/com/twilio/rest/messaging/v1/ServiceDeleter.java index 54c1faf1c6..e94297498d 100644 --- a/src/main/java/com/twilio/rest/messaging/v1/ServiceDeleter.java +++ b/src/main/java/com/twilio/rest/messaging/v1/ServiceDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.messaging.v1; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,40 +26,38 @@ public class ServiceDeleter extends Deleter { - private String pathSid; + private String pathsid; - public ServiceDeleter(final String pathSid) { - this.pathSid = pathSid; + public ServiceDeleter(final String pathsid) { + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/v1/Services/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.MESSAGING.toString(), - path + HttpMethod.DELETE, + Domains.MESSAGING.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Service delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("Service delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/messaging/v1/ServiceFetcher.java b/src/main/java/com/twilio/rest/messaging/v1/ServiceFetcher.java index 7b589e7a0d..d58e46c898 100644 --- a/src/main/java/com/twilio/rest/messaging/v1/ServiceFetcher.java +++ b/src/main/java/com/twilio/rest/messaging/v1/ServiceFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.messaging.v1; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,44 +26,41 @@ public class ServiceFetcher extends Fetcher { - private String pathSid; + private String pathsid; - public ServiceFetcher(final String pathSid) { - this.pathSid = pathSid; + public ServiceFetcher(final String pathsid) { + this.pathsid = pathsid; } + @Override public Service fetch(final TwilioRestClient client) { + String path = "/v1/Services/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.MESSAGING.toString(), - path + HttpMethod.GET, + Domains.MESSAGING.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Service fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Service fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Service.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/messaging/v1/ServiceReader.java b/src/main/java/com/twilio/rest/messaging/v1/ServiceReader.java index bb1ec849fa..b143c915d0 100644 --- a/src/main/java/com/twilio/rest/messaging/v1/ServiceReader.java +++ b/src/main/java/com/twilio/rest/messaging/v1/ServiceReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -31,105 +32,83 @@ public class ServiceReader extends Reader { private Long pageSize; - public ServiceReader() {} + public ServiceReader() { + } + public ServiceReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/Services"; + Request request = new Request( - HttpMethod.GET, - Domains.MESSAGING.toString(), - path + HttpMethod.GET, + Domains.MESSAGING.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Service read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Service read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "services", - response.getContent(), - Service.class, - client.getObjectMapper() - ); + "services", + response.getContent(), + Service.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.MESSAGING.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.MESSAGING.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/messaging/v1/ServiceUpdater.java b/src/main/java/com/twilio/rest/messaging/v1/ServiceUpdater.java index bff592d09b..f351d3c8df 100644 --- a/src/main/java/com/twilio/rest/messaging/v1/ServiceUpdater.java +++ b/src/main/java/com/twilio/rest/messaging/v1/ServiceUpdater.java @@ -16,7 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; -import com.twilio.converter.Promoter; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,11 +26,11 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.net.URI; public class ServiceUpdater extends Updater { - - private String pathSid; + private String pathsid; private String friendlyName; private URI inboundRequestUrl; private HttpMethod inboundMethod; @@ -47,138 +48,134 @@ public class ServiceUpdater extends Updater { private String usecase; private Boolean useInboundWebhookOnNumber; - public ServiceUpdater(final String pathSid) { - this.pathSid = pathSid; + public ServiceUpdater(final String pathsid) { + this.pathsid = pathsid; } + public ServiceUpdater setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + public ServiceUpdater setInboundRequestUrl(final URI inboundRequestUrl) { this.inboundRequestUrl = inboundRequestUrl; return this; } - public ServiceUpdater setInboundRequestUrl(final String inboundRequestUrl) { - return setInboundRequestUrl(Promoter.uriFromString(inboundRequestUrl)); - } public ServiceUpdater setInboundMethod(final HttpMethod inboundMethod) { this.inboundMethod = inboundMethod; return this; } + public ServiceUpdater setFallbackUrl(final URI fallbackUrl) { this.fallbackUrl = fallbackUrl; return this; } - public ServiceUpdater setFallbackUrl(final String fallbackUrl) { - return setFallbackUrl(Promoter.uriFromString(fallbackUrl)); - } public ServiceUpdater setFallbackMethod(final HttpMethod fallbackMethod) { this.fallbackMethod = fallbackMethod; return this; } + public ServiceUpdater setStatusCallback(final URI statusCallback) { this.statusCallback = statusCallback; return this; } - public ServiceUpdater setStatusCallback(final String statusCallback) { - return setStatusCallback(Promoter.uriFromString(statusCallback)); - } public ServiceUpdater setStickySender(final Boolean stickySender) { this.stickySender = stickySender; return this; } + public ServiceUpdater setMmsConverter(final Boolean mmsConverter) { this.mmsConverter = mmsConverter; return this; } + public ServiceUpdater setSmartEncoding(final Boolean smartEncoding) { this.smartEncoding = smartEncoding; return this; } - public ServiceUpdater setScanMessageContent( - final Service.ScanMessageContent scanMessageContent - ) { + + public ServiceUpdater setScanMessageContent(final Service.ScanMessageContent scanMessageContent) { this.scanMessageContent = scanMessageContent; return this; } - public ServiceUpdater setFallbackToLongCode( - final Boolean fallbackToLongCode - ) { + + public ServiceUpdater setFallbackToLongCode(final Boolean fallbackToLongCode) { this.fallbackToLongCode = fallbackToLongCode; return this; } + public ServiceUpdater setAreaCodeGeomatch(final Boolean areaCodeGeomatch) { this.areaCodeGeomatch = areaCodeGeomatch; return this; } + public ServiceUpdater setValidityPeriod(final Integer validityPeriod) { this.validityPeriod = validityPeriod; return this; } - public ServiceUpdater setSynchronousValidation( - final Boolean synchronousValidation - ) { + + public ServiceUpdater setSynchronousValidation(final Boolean synchronousValidation) { this.synchronousValidation = synchronousValidation; return this; } + public ServiceUpdater setUsecase(final String usecase) { this.usecase = usecase; return this; } - public ServiceUpdater setUseInboundWebhookOnNumber( - final Boolean useInboundWebhookOnNumber - ) { + + public ServiceUpdater setUseInboundWebhookOnNumber(final Boolean useInboundWebhookOnNumber) { this.useInboundWebhookOnNumber = useInboundWebhookOnNumber; return this; } + @Override public Service update(final TwilioRestClient client) { + String path = "/v1/Services/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.MESSAGING.toString(), - path + HttpMethod.POST, + Domains.MESSAGING.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Service update failed: Unable to connect to server" - ); + throw new ApiConnectionException("Service update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -187,71 +184,86 @@ public Service update(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + if (inboundRequestUrl != null) { - request.addPostParam( - "InboundRequestUrl", - inboundRequestUrl.toString() - ); + Serializer.toString(request, "InboundRequestUrl", inboundRequestUrl, ParameterType.URLENCODED); } + + if (inboundMethod != null) { - request.addPostParam("InboundMethod", inboundMethod.toString()); + Serializer.toString(request, "InboundMethod", inboundMethod, ParameterType.URLENCODED); } + + if (fallbackUrl != null) { - request.addPostParam("FallbackUrl", fallbackUrl.toString()); + Serializer.toString(request, "FallbackUrl", fallbackUrl, ParameterType.URLENCODED); } + + if (fallbackMethod != null) { - request.addPostParam("FallbackMethod", fallbackMethod.toString()); + Serializer.toString(request, "FallbackMethod", fallbackMethod, ParameterType.URLENCODED); } + + if (statusCallback != null) { - request.addPostParam("StatusCallback", statusCallback.toString()); + Serializer.toString(request, "StatusCallback", statusCallback, ParameterType.URLENCODED); } + + if (stickySender != null) { - request.addPostParam("StickySender", stickySender.toString()); + Serializer.toString(request, "StickySender", stickySender, ParameterType.URLENCODED); } + + if (mmsConverter != null) { - request.addPostParam("MmsConverter", mmsConverter.toString()); + Serializer.toString(request, "MmsConverter", mmsConverter, ParameterType.URLENCODED); } + + if (smartEncoding != null) { - request.addPostParam("SmartEncoding", smartEncoding.toString()); + Serializer.toString(request, "SmartEncoding", smartEncoding, ParameterType.URLENCODED); } + + if (scanMessageContent != null) { - request.addPostParam( - "ScanMessageContent", - scanMessageContent.toString() - ); + Serializer.toString(request, "ScanMessageContent", scanMessageContent, ParameterType.URLENCODED); } + + if (fallbackToLongCode != null) { - request.addPostParam( - "FallbackToLongCode", - fallbackToLongCode.toString() - ); + Serializer.toString(request, "FallbackToLongCode", fallbackToLongCode, ParameterType.URLENCODED); } + + if (areaCodeGeomatch != null) { - request.addPostParam( - "AreaCodeGeomatch", - areaCodeGeomatch.toString() - ); + Serializer.toString(request, "AreaCodeGeomatch", areaCodeGeomatch, ParameterType.URLENCODED); } + + if (validityPeriod != null) { - request.addPostParam("ValidityPeriod", validityPeriod.toString()); + Serializer.toString(request, "ValidityPeriod", validityPeriod, ParameterType.URLENCODED); } + + if (synchronousValidation != null) { - request.addPostParam( - "SynchronousValidation", - synchronousValidation.toString() - ); + Serializer.toString(request, "SynchronousValidation", synchronousValidation, ParameterType.URLENCODED); } + + if (usecase != null) { - request.addPostParam("Usecase", usecase); + Serializer.toString(request, "Usecase", usecase, ParameterType.URLENCODED); } + + if (useInboundWebhookOnNumber != null) { - request.addPostParam( - "UseInboundWebhookOnNumber", - useInboundWebhookOnNumber.toString() - ); + Serializer.toString(request, "UseInboundWebhookOnNumber", useInboundWebhookOnNumber, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/messaging/v1/TollfreeVerification.java b/src/main/java/com/twilio/rest/messaging/v1/TollfreeVerification.java index da3ddb6f84..395f10c6ab 100644 --- a/src/main/java/com/twilio/rest/messaging/v1/TollfreeVerification.java +++ b/src/main/java/com/twilio/rest/messaging/v1/TollfreeVerification.java @@ -18,83 +18,120 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.List; -import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class TollfreeVerification extends Resource { - private static final long serialVersionUID = 271545419096190L; - - public static TollfreeVerificationCreator creator( - final String businessName, - final String businessWebsite, - final String notificationEmail, - final List useCaseCategories, - final String useCaseSummary, - final String productionMessageSample, - final List optInImageUrls, - final TollfreeVerification.OptInType optInType, - final String messageVolume, - final String tollfreePhoneNumberSid - ) { + + public static TollfreeVerificationCreator creator(final String businessName, final String businessWebsite, final String notificationEmail, final List useCaseCategories, final String useCaseSummary, final String productionMessageSample, final List optInImageUrls, final TollfreeVerification.OptInType optInType, final String messageVolume, final String tollfreePhoneNumberSid) { return new TollfreeVerificationCreator( - businessName, - businessWebsite, - notificationEmail, - useCaseCategories, - useCaseSummary, - productionMessageSample, - optInImageUrls, - optInType, - messageVolume, - tollfreePhoneNumberSid + businessName, businessWebsite, notificationEmail, useCaseCategories, useCaseSummary, productionMessageSample, optInImageUrls, optInType, messageVolume, tollfreePhoneNumberSid ); } - public static TollfreeVerificationDeleter deleter(final String pathSid) { - return new TollfreeVerificationDeleter(pathSid); + + public static TollfreeVerificationDeleter deleter(final String pathsid) { + return new TollfreeVerificationDeleter( + pathsid + ); } - public static TollfreeVerificationFetcher fetcher(final String pathSid) { - return new TollfreeVerificationFetcher(pathSid); + + public static TollfreeVerificationFetcher fetcher(final String pathsid) { + return new TollfreeVerificationFetcher( + pathsid + ); } + public static TollfreeVerificationReader reader() { - return new TollfreeVerificationReader(); + return new TollfreeVerificationReader( + + ); } - public static TollfreeVerificationUpdater updater(final String pathSid) { - return new TollfreeVerificationUpdater(pathSid); + + public static TollfreeVerificationUpdater updater(final String pathsid) { + return new TollfreeVerificationUpdater( + pathsid + ); } + + public enum Status { + PENDING_REVIEW("PENDING_REVIEW"), + IN_REVIEW("IN_REVIEW"), + TWILIO_APPROVED("TWILIO_APPROVED"), + TWILIO_REJECTED("TWILIO_REJECTED"); + + private final String value; + + private Status(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static Status forValue(final String value) { + return Promoter.enumFromString(value, Status.values()); + } + } + + public enum OptInType { + VERBAL("VERBAL"), + WEB_FORM("WEB_FORM"), + PAPER_FORM("PAPER_FORM"), + VIA_TEXT("VIA_TEXT"), + MOBILE_QR_CODE("MOBILE_QR_CODE"), + IMPORT("IMPORT"), + IMPORT_PLEASE_REPLACE("IMPORT_PLEASE_REPLACE"); + + private final String value; + + private OptInType(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static OptInType forValue(final String value) { + return Promoter.enumFromString(value, OptInType.values()); + } + } + + /** * Converts a JSON String into a TollfreeVerification object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return TollfreeVerification object represented by the provided JSON */ - public static TollfreeVerification fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static TollfreeVerification fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, TollfreeVerification.class); @@ -109,14 +146,11 @@ public static TollfreeVerification fromJson( * Converts a JSON InputStream into a TollfreeVerification object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return TollfreeVerification object represented by the provided JSON */ - public static TollfreeVerification fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static TollfreeVerification fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, TollfreeVerification.class); @@ -127,296 +161,174 @@ public static TollfreeVerification fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String customerProfileSid; - private final String trustProductSid; - private final ZonedDateTime dateCreated; - private final ZonedDateTime dateUpdated; - private final String regulatedItemSid; - private final String businessName; - private final String businessStreetAddress; - private final String businessStreetAddress2; + @Getter + private final String additionalInformation; + @Getter private final String businessCity; - private final String businessStateProvinceRegion; - private final String businessPostalCode; - private final String businessCountry; - private final String businessWebsite; + @Getter + private final String businessContactEmail; + @Getter private final String businessContactFirstName; + @Getter private final String businessContactLastName; - private final String businessContactEmail; + @Getter private final com.twilio.type.PhoneNumber businessContactPhone; + @Getter + private final String businessCountry; + @Getter + private final String businessName; + @Getter + private final String businessPostalCode; + @Getter + private final String businessStateProvinceRegion; + @Getter + private final String businessStreetAddress; + @Getter + private final String businessStreetAddress2; + @Getter + private final String businessWebsite; + @Getter + private final String customerProfileSid; + @Getter + private final ZonedDateTime dateCreated; + @Getter + private final ZonedDateTime dateUpdated; + @Getter + private final Boolean editAllowed; + @Getter + private final ZonedDateTime editExpiration; + @Getter + private final Integer errorCode; + @Getter + private final String externalReferenceId; + @Getter + private final String messageVolume; + @Getter private final String notificationEmail; - private final List useCaseCategories; - private final String useCaseSummary; - private final String productionMessageSample; + @Getter private final List optInImageUrls; + @Getter private final TollfreeVerification.OptInType optInType; - private final String messageVolume; - private final String additionalInformation; - private final String tollfreePhoneNumberSid; + @Getter + private final String productionMessageSample; + @Getter + private final String regulatedItemSid; + @Getter + private final String rejectionReason; + @Getter + private final List rejectionReasons; + @Getter + private final Object resourceLinks; + @Getter + private final String sid; + @Getter private final TollfreeVerification.Status status; + @Getter + private final String tollfreePhoneNumberSid; + @Getter + private final String trustProductSid; + @Getter private final URI url; - private final String rejectionReason; - private final Integer errorCode; - private final ZonedDateTime editExpiration; - private final Boolean editAllowed; - private final List> rejectionReasons; - private final Map resourceLinks; - private final String externalReferenceId; + @Getter + private final List useCaseCategories; + @Getter + private final String useCaseSummary; @JsonCreator private TollfreeVerification( - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("customer_profile_sid") final String customerProfileSid, - @JsonProperty("trust_product_sid") final String trustProductSid, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("regulated_item_sid") final String regulatedItemSid, - @JsonProperty("business_name") final String businessName, - @JsonProperty( - "business_street_address" - ) final String businessStreetAddress, - @JsonProperty( - "business_street_address2" - ) final String businessStreetAddress2, - @JsonProperty("business_city") final String businessCity, - @JsonProperty( - "business_state_province_region" - ) final String businessStateProvinceRegion, - @JsonProperty("business_postal_code") final String businessPostalCode, - @JsonProperty("business_country") final String businessCountry, - @JsonProperty("business_website") final String businessWebsite, - @JsonProperty( - "business_contact_first_name" - ) final String businessContactFirstName, - @JsonProperty( - "business_contact_last_name" - ) final String businessContactLastName, - @JsonProperty( - "business_contact_email" - ) final String businessContactEmail, - @JsonProperty( - "business_contact_phone" - ) final com.twilio.type.PhoneNumber businessContactPhone, - @JsonProperty("notification_email") final String notificationEmail, - @JsonProperty("use_case_categories") final List< - String - > useCaseCategories, - @JsonProperty("use_case_summary") final String useCaseSummary, - @JsonProperty( - "production_message_sample" - ) final String productionMessageSample, - @JsonProperty("opt_in_image_urls") final List optInImageUrls, - @JsonProperty( - "opt_in_type" - ) final TollfreeVerification.OptInType optInType, - @JsonProperty("message_volume") final String messageVolume, - @JsonProperty( - "additional_information" - ) final String additionalInformation, - @JsonProperty( - "tollfree_phone_number_sid" - ) final String tollfreePhoneNumberSid, - @JsonProperty("status") final TollfreeVerification.Status status, - @JsonProperty("url") final URI url, - @JsonProperty("rejection_reason") final String rejectionReason, - @JsonProperty("error_code") final Integer errorCode, - @JsonProperty("edit_expiration") final String editExpiration, - @JsonProperty("edit_allowed") final Boolean editAllowed, - @JsonProperty("rejection_reasons") final List< - Map - > rejectionReasons, - @JsonProperty("resource_links") final Map resourceLinks, - @JsonProperty("external_reference_id") final String externalReferenceId + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("additional_information") final String additionalInformation, + @JsonProperty("business_city") final String businessCity, + @JsonProperty("business_contact_email") final String businessContactEmail, + @JsonProperty("business_contact_first_name") final String businessContactFirstName, + @JsonProperty("business_contact_last_name") final String businessContactLastName, + @JsonProperty("business_contact_phone") final com.twilio.type.PhoneNumber businessContactPhone, + @JsonProperty("business_country") final String businessCountry, + @JsonProperty("business_name") final String businessName, + @JsonProperty("business_postal_code") final String businessPostalCode, + @JsonProperty("business_state_province_region") final String businessStateProvinceRegion, + @JsonProperty("business_street_address") final String businessStreetAddress, + @JsonProperty("business_street_address2") final String businessStreetAddress2, + @JsonProperty("business_website") final String businessWebsite, + @JsonProperty("customer_profile_sid") final String customerProfileSid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("edit_allowed") final Boolean editAllowed, + @JsonProperty("edit_expiration") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime editExpiration, + @JsonProperty("error_code") final Integer errorCode, + @JsonProperty("external_reference_id") final String externalReferenceId, + @JsonProperty("message_volume") final String messageVolume, + @JsonProperty("notification_email") final String notificationEmail, + @JsonProperty("opt_in_image_urls") final List optInImageUrls, + @JsonProperty("opt_in_type") final TollfreeVerification.OptInType optInType, + @JsonProperty("production_message_sample") final String productionMessageSample, + @JsonProperty("regulated_item_sid") final String regulatedItemSid, + @JsonProperty("rejection_reason") final String rejectionReason, + @JsonProperty("rejection_reasons") final List rejectionReasons, + @JsonProperty("resource_links") final Object resourceLinks, + @JsonProperty("sid") final String sid, + @JsonProperty("status") final TollfreeVerification.Status status, + @JsonProperty("tollfree_phone_number_sid") final String tollfreePhoneNumberSid, + @JsonProperty("trust_product_sid") final String trustProductSid, + @JsonProperty("url") final URI url, + @JsonProperty("use_case_categories") final List useCaseCategories, + @JsonProperty("use_case_summary") final String useCaseSummary ) { - this.sid = sid; this.accountSid = accountSid; - this.customerProfileSid = customerProfileSid; - this.trustProductSid = trustProductSid; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); - this.regulatedItemSid = regulatedItemSid; - this.businessName = businessName; - this.businessStreetAddress = businessStreetAddress; - this.businessStreetAddress2 = businessStreetAddress2; + this.additionalInformation = additionalInformation; this.businessCity = businessCity; - this.businessStateProvinceRegion = businessStateProvinceRegion; - this.businessPostalCode = businessPostalCode; - this.businessCountry = businessCountry; - this.businessWebsite = businessWebsite; + this.businessContactEmail = businessContactEmail; this.businessContactFirstName = businessContactFirstName; this.businessContactLastName = businessContactLastName; - this.businessContactEmail = businessContactEmail; this.businessContactPhone = businessContactPhone; + this.businessCountry = businessCountry; + this.businessName = businessName; + this.businessPostalCode = businessPostalCode; + this.businessStateProvinceRegion = businessStateProvinceRegion; + this.businessStreetAddress = businessStreetAddress; + this.businessStreetAddress2 = businessStreetAddress2; + this.businessWebsite = businessWebsite; + this.customerProfileSid = customerProfileSid; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; + this.editAllowed = editAllowed; + this.editExpiration = editExpiration; + this.errorCode = errorCode; + this.externalReferenceId = externalReferenceId; + this.messageVolume = messageVolume; this.notificationEmail = notificationEmail; - this.useCaseCategories = useCaseCategories; - this.useCaseSummary = useCaseSummary; - this.productionMessageSample = productionMessageSample; this.optInImageUrls = optInImageUrls; this.optInType = optInType; - this.messageVolume = messageVolume; - this.additionalInformation = additionalInformation; - this.tollfreePhoneNumberSid = tollfreePhoneNumberSid; - this.status = status; - this.url = url; + this.productionMessageSample = productionMessageSample; + this.regulatedItemSid = regulatedItemSid; this.rejectionReason = rejectionReason; - this.errorCode = errorCode; - this.editExpiration = - DateConverter.iso8601DateTimeFromString(editExpiration); - this.editAllowed = editAllowed; this.rejectionReasons = rejectionReasons; this.resourceLinks = resourceLinks; - this.externalReferenceId = externalReferenceId; - } - - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getCustomerProfileSid() { - return this.customerProfileSid; - } - - public final String getTrustProductSid() { - return this.trustProductSid; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final String getRegulatedItemSid() { - return this.regulatedItemSid; - } - - public final String getBusinessName() { - return this.businessName; - } - - public final String getBusinessStreetAddress() { - return this.businessStreetAddress; - } - - public final String getBusinessStreetAddress2() { - return this.businessStreetAddress2; - } - - public final String getBusinessCity() { - return this.businessCity; - } - - public final String getBusinessStateProvinceRegion() { - return this.businessStateProvinceRegion; - } - - public final String getBusinessPostalCode() { - return this.businessPostalCode; - } - - public final String getBusinessCountry() { - return this.businessCountry; - } - - public final String getBusinessWebsite() { - return this.businessWebsite; - } - - public final String getBusinessContactFirstName() { - return this.businessContactFirstName; - } - - public final String getBusinessContactLastName() { - return this.businessContactLastName; - } - - public final String getBusinessContactEmail() { - return this.businessContactEmail; - } - - public final com.twilio.type.PhoneNumber getBusinessContactPhone() { - return this.businessContactPhone; - } - - public final String getNotificationEmail() { - return this.notificationEmail; - } - - public final List getUseCaseCategories() { - return this.useCaseCategories; - } - - public final String getUseCaseSummary() { - return this.useCaseSummary; - } - - public final String getProductionMessageSample() { - return this.productionMessageSample; - } - - public final List getOptInImageUrls() { - return this.optInImageUrls; - } - - public final TollfreeVerification.OptInType getOptInType() { - return this.optInType; - } - - public final String getMessageVolume() { - return this.messageVolume; - } - - public final String getAdditionalInformation() { - return this.additionalInformation; - } - - public final String getTollfreePhoneNumberSid() { - return this.tollfreePhoneNumberSid; - } - - public final TollfreeVerification.Status getStatus() { - return this.status; - } - - public final URI getUrl() { - return this.url; - } - - public final String getRejectionReason() { - return this.rejectionReason; - } - - public final Integer getErrorCode() { - return this.errorCode; - } - - public final ZonedDateTime getEditExpiration() { - return this.editExpiration; - } - - public final Boolean getEditAllowed() { - return this.editAllowed; - } - - public final List> getRejectionReasons() { - return this.rejectionReasons; - } - - public final Map getResourceLinks() { - return this.resourceLinks; - } - - public final String getExternalReferenceId() { - return this.externalReferenceId; + this.sid = sid; + this.status = status; + this.tollfreePhoneNumberSid = tollfreePhoneNumberSid; + this.trustProductSid = trustProductSid; + this.url = url; + this.useCaseCategories = useCaseCategories; + this.useCaseSummary = useCaseSummary; } @Override @@ -430,159 +342,90 @@ public boolean equals(final Object o) { } TollfreeVerification other = (TollfreeVerification) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(customerProfileSid, other.customerProfileSid) && - Objects.equals(trustProductSid, other.trustProductSid) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(regulatedItemSid, other.regulatedItemSid) && - Objects.equals(businessName, other.businessName) && - Objects.equals( - businessStreetAddress, - other.businessStreetAddress - ) && - Objects.equals( - businessStreetAddress2, - other.businessStreetAddress2 - ) && - Objects.equals(businessCity, other.businessCity) && - Objects.equals( - businessStateProvinceRegion, - other.businessStateProvinceRegion - ) && - Objects.equals(businessPostalCode, other.businessPostalCode) && - Objects.equals(businessCountry, other.businessCountry) && - Objects.equals(businessWebsite, other.businessWebsite) && - Objects.equals( - businessContactFirstName, - other.businessContactFirstName - ) && - Objects.equals( - businessContactLastName, - other.businessContactLastName - ) && - Objects.equals(businessContactEmail, other.businessContactEmail) && - Objects.equals(businessContactPhone, other.businessContactPhone) && - Objects.equals(notificationEmail, other.notificationEmail) && - Objects.equals(useCaseCategories, other.useCaseCategories) && - Objects.equals(useCaseSummary, other.useCaseSummary) && - Objects.equals( - productionMessageSample, - other.productionMessageSample - ) && - Objects.equals(optInImageUrls, other.optInImageUrls) && - Objects.equals(optInType, other.optInType) && - Objects.equals(messageVolume, other.messageVolume) && - Objects.equals( - additionalInformation, - other.additionalInformation - ) && - Objects.equals( - tollfreePhoneNumberSid, - other.tollfreePhoneNumberSid - ) && - Objects.equals(status, other.status) && - Objects.equals(url, other.url) && - Objects.equals(rejectionReason, other.rejectionReason) && - Objects.equals(errorCode, other.errorCode) && - Objects.equals(editExpiration, other.editExpiration) && - Objects.equals(editAllowed, other.editAllowed) && - Objects.equals(rejectionReasons, other.rejectionReasons) && - Objects.equals(resourceLinks, other.resourceLinks) && - Objects.equals(externalReferenceId, other.externalReferenceId) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(additionalInformation, other.additionalInformation) && + Objects.equals(businessCity, other.businessCity) && + Objects.equals(businessContactEmail, other.businessContactEmail) && + Objects.equals(businessContactFirstName, other.businessContactFirstName) && + Objects.equals(businessContactLastName, other.businessContactLastName) && + Objects.equals(businessContactPhone, other.businessContactPhone) && + Objects.equals(businessCountry, other.businessCountry) && + Objects.equals(businessName, other.businessName) && + Objects.equals(businessPostalCode, other.businessPostalCode) && + Objects.equals(businessStateProvinceRegion, other.businessStateProvinceRegion) && + Objects.equals(businessStreetAddress, other.businessStreetAddress) && + Objects.equals(businessStreetAddress2, other.businessStreetAddress2) && + Objects.equals(businessWebsite, other.businessWebsite) && + Objects.equals(customerProfileSid, other.customerProfileSid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(editAllowed, other.editAllowed) && + Objects.equals(editExpiration, other.editExpiration) && + Objects.equals(errorCode, other.errorCode) && + Objects.equals(externalReferenceId, other.externalReferenceId) && + Objects.equals(messageVolume, other.messageVolume) && + Objects.equals(notificationEmail, other.notificationEmail) && + Objects.equals(optInImageUrls, other.optInImageUrls) && + Objects.equals(optInType, other.optInType) && + Objects.equals(productionMessageSample, other.productionMessageSample) && + Objects.equals(regulatedItemSid, other.regulatedItemSid) && + Objects.equals(rejectionReason, other.rejectionReason) && + Objects.equals(rejectionReasons, other.rejectionReasons) && + Objects.equals(resourceLinks, other.resourceLinks) && + Objects.equals(sid, other.sid) && + Objects.equals(status, other.status) && + Objects.equals(tollfreePhoneNumberSid, other.tollfreePhoneNumberSid) && + Objects.equals(trustProductSid, other.trustProductSid) && + Objects.equals(url, other.url) && + Objects.equals(useCaseCategories, other.useCaseCategories) && + Objects.equals(useCaseSummary, other.useCaseSummary) ); } @Override public int hashCode() { return Objects.hash( - sid, - accountSid, - customerProfileSid, - trustProductSid, - dateCreated, - dateUpdated, - regulatedItemSid, - businessName, - businessStreetAddress, - businessStreetAddress2, - businessCity, - businessStateProvinceRegion, - businessPostalCode, - businessCountry, - businessWebsite, - businessContactFirstName, - businessContactLastName, - businessContactEmail, - businessContactPhone, - notificationEmail, - useCaseCategories, - useCaseSummary, - productionMessageSample, - optInImageUrls, - optInType, - messageVolume, - additionalInformation, - tollfreePhoneNumberSid, - status, - url, - rejectionReason, - errorCode, - editExpiration, - editAllowed, - rejectionReasons, - resourceLinks, - externalReferenceId + accountSid, + additionalInformation, + businessCity, + businessContactEmail, + businessContactFirstName, + businessContactLastName, + businessContactPhone, + businessCountry, + businessName, + businessPostalCode, + businessStateProvinceRegion, + businessStreetAddress, + businessStreetAddress2, + businessWebsite, + customerProfileSid, + dateCreated, + dateUpdated, + editAllowed, + editExpiration, + errorCode, + externalReferenceId, + messageVolume, + notificationEmail, + optInImageUrls, + optInType, + productionMessageSample, + regulatedItemSid, + rejectionReason, + rejectionReasons, + resourceLinks, + sid, + status, + tollfreePhoneNumberSid, + trustProductSid, + url, + useCaseCategories, + useCaseSummary ); } - public enum OptInType { - VERBAL("VERBAL"), - WEB_FORM("WEB_FORM"), - PAPER_FORM("PAPER_FORM"), - VIA_TEXT("VIA_TEXT"), - MOBILE_QR_CODE("MOBILE_QR_CODE"), - IMPORT("IMPORT"), - IMPORT_PLEASE_REPLACE("IMPORT_PLEASE_REPLACE"); - private final String value; - - private OptInType(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static OptInType forValue(final String value) { - return Promoter.enumFromString(value, OptInType.values()); - } - } - - public enum Status { - PENDING_REVIEW("PENDING_REVIEW"), - IN_REVIEW("IN_REVIEW"), - TWILIO_APPROVED("TWILIO_APPROVED"), - TWILIO_REJECTED("TWILIO_REJECTED"); - - private final String value; - - private Status(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static Status forValue(final String value) { - return Promoter.enumFromString(value, Status.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/messaging/v1/TollfreeVerificationCreator.java b/src/main/java/com/twilio/rest/messaging/v1/TollfreeVerificationCreator.java index 0de99a0d1f..cacdcf772d 100644 --- a/src/main/java/com/twilio/rest/messaging/v1/TollfreeVerificationCreator.java +++ b/src/main/java/com/twilio/rest/messaging/v1/TollfreeVerificationCreator.java @@ -14,9 +14,12 @@ package com.twilio.rest.messaging.v1; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; import com.twilio.converter.Promoter; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,7 +28,7 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -import java.util.List; + import java.util.List; public class TollfreeVerificationCreator extends Creator { @@ -54,18 +57,7 @@ public class TollfreeVerificationCreator extends Creator { private com.twilio.type.PhoneNumber businessContactPhone; private String externalReferenceId; - public TollfreeVerificationCreator( - final String businessName, - final String businessWebsite, - final String notificationEmail, - final List useCaseCategories, - final String useCaseSummary, - final String productionMessageSample, - final List optInImageUrls, - final TollfreeVerification.OptInType optInType, - final String messageVolume, - final String tollfreePhoneNumberSid - ) { + public TollfreeVerificationCreator(final String businessName, final String businessWebsite, final String notificationEmail, final List useCaseCategories, final String useCaseSummary, final String productionMessageSample, final List optInImageUrls, final TollfreeVerification.OptInType optInType, final String messageVolume, final String tollfreePhoneNumberSid) { this.businessName = businessName; this.businessWebsite = businessWebsite; this.notificationEmail = notificationEmail; @@ -78,370 +70,306 @@ public TollfreeVerificationCreator( this.tollfreePhoneNumberSid = tollfreePhoneNumberSid; } - public TollfreeVerificationCreator setBusinessName( - final String businessName - ) { + + public TollfreeVerificationCreator setBusinessName(final String businessName) { this.businessName = businessName; return this; } - public TollfreeVerificationCreator setBusinessWebsite( - final String businessWebsite - ) { + + public TollfreeVerificationCreator setBusinessWebsite(final String businessWebsite) { this.businessWebsite = businessWebsite; return this; } - public TollfreeVerificationCreator setNotificationEmail( - final String notificationEmail - ) { + + public TollfreeVerificationCreator setNotificationEmail(final String notificationEmail) { this.notificationEmail = notificationEmail; return this; } - public TollfreeVerificationCreator setUseCaseCategories( - final List useCaseCategories - ) { + + public TollfreeVerificationCreator setUseCaseCategories(final List useCaseCategories) { this.useCaseCategories = useCaseCategories; return this; } - public TollfreeVerificationCreator setUseCaseCategories( - final String useCaseCategories - ) { + public TollfreeVerificationCreator setUseCaseCategories(final String useCaseCategories) { return setUseCaseCategories(Promoter.listOfOne(useCaseCategories)); } - public TollfreeVerificationCreator setUseCaseSummary( - final String useCaseSummary - ) { + public TollfreeVerificationCreator setUseCaseSummary(final String useCaseSummary) { this.useCaseSummary = useCaseSummary; return this; } - public TollfreeVerificationCreator setProductionMessageSample( - final String productionMessageSample - ) { + + public TollfreeVerificationCreator setProductionMessageSample(final String productionMessageSample) { this.productionMessageSample = productionMessageSample; return this; } - public TollfreeVerificationCreator setOptInImageUrls( - final List optInImageUrls - ) { + + public TollfreeVerificationCreator setOptInImageUrls(final List optInImageUrls) { this.optInImageUrls = optInImageUrls; return this; } - public TollfreeVerificationCreator setOptInImageUrls( - final String optInImageUrls - ) { + public TollfreeVerificationCreator setOptInImageUrls(final String optInImageUrls) { return setOptInImageUrls(Promoter.listOfOne(optInImageUrls)); } - public TollfreeVerificationCreator setOptInType( - final TollfreeVerification.OptInType optInType - ) { + public TollfreeVerificationCreator setOptInType(final TollfreeVerification.OptInType optInType) { this.optInType = optInType; return this; } - public TollfreeVerificationCreator setMessageVolume( - final String messageVolume - ) { + + public TollfreeVerificationCreator setMessageVolume(final String messageVolume) { this.messageVolume = messageVolume; return this; } - public TollfreeVerificationCreator setTollfreePhoneNumberSid( - final String tollfreePhoneNumberSid - ) { + + public TollfreeVerificationCreator setTollfreePhoneNumberSid(final String tollfreePhoneNumberSid) { this.tollfreePhoneNumberSid = tollfreePhoneNumberSid; return this; } - public TollfreeVerificationCreator setCustomerProfileSid( - final String customerProfileSid - ) { + + public TollfreeVerificationCreator setCustomerProfileSid(final String customerProfileSid) { this.customerProfileSid = customerProfileSid; return this; } - public TollfreeVerificationCreator setBusinessStreetAddress( - final String businessStreetAddress - ) { + + public TollfreeVerificationCreator setBusinessStreetAddress(final String businessStreetAddress) { this.businessStreetAddress = businessStreetAddress; return this; } - public TollfreeVerificationCreator setBusinessStreetAddress2( - final String businessStreetAddress2 - ) { + + public TollfreeVerificationCreator setBusinessStreetAddress2(final String businessStreetAddress2) { this.businessStreetAddress2 = businessStreetAddress2; return this; } - public TollfreeVerificationCreator setBusinessCity( - final String businessCity - ) { + + public TollfreeVerificationCreator setBusinessCity(final String businessCity) { this.businessCity = businessCity; return this; } - public TollfreeVerificationCreator setBusinessStateProvinceRegion( - final String businessStateProvinceRegion - ) { + + public TollfreeVerificationCreator setBusinessStateProvinceRegion(final String businessStateProvinceRegion) { this.businessStateProvinceRegion = businessStateProvinceRegion; return this; } - public TollfreeVerificationCreator setBusinessPostalCode( - final String businessPostalCode - ) { + + public TollfreeVerificationCreator setBusinessPostalCode(final String businessPostalCode) { this.businessPostalCode = businessPostalCode; return this; } - public TollfreeVerificationCreator setBusinessCountry( - final String businessCountry - ) { + + public TollfreeVerificationCreator setBusinessCountry(final String businessCountry) { this.businessCountry = businessCountry; return this; } - public TollfreeVerificationCreator setAdditionalInformation( - final String additionalInformation - ) { + + public TollfreeVerificationCreator setAdditionalInformation(final String additionalInformation) { this.additionalInformation = additionalInformation; return this; } - public TollfreeVerificationCreator setBusinessContactFirstName( - final String businessContactFirstName - ) { + + public TollfreeVerificationCreator setBusinessContactFirstName(final String businessContactFirstName) { this.businessContactFirstName = businessContactFirstName; return this; } - public TollfreeVerificationCreator setBusinessContactLastName( - final String businessContactLastName - ) { + + public TollfreeVerificationCreator setBusinessContactLastName(final String businessContactLastName) { this.businessContactLastName = businessContactLastName; return this; } - public TollfreeVerificationCreator setBusinessContactEmail( - final String businessContactEmail - ) { + + public TollfreeVerificationCreator setBusinessContactEmail(final String businessContactEmail) { this.businessContactEmail = businessContactEmail; return this; } - public TollfreeVerificationCreator setBusinessContactPhone( - final com.twilio.type.PhoneNumber businessContactPhone - ) { + + public TollfreeVerificationCreator setBusinessContactPhone(final com.twilio.type.PhoneNumber businessContactPhone) { this.businessContactPhone = businessContactPhone; return this; } - public TollfreeVerificationCreator setBusinessContactPhone( - final String businessContactPhone - ) { - return setBusinessContactPhone( - Promoter.phoneNumberFromString(businessContactPhone) - ); + public TollfreeVerificationCreator setBusinessContactPhone(final String businessContactPhone) { + return setBusinessContactPhone(Promoter.phoneNumberFromString(businessContactPhone)); } - public TollfreeVerificationCreator setExternalReferenceId( - final String externalReferenceId - ) { + public TollfreeVerificationCreator setExternalReferenceId(final String externalReferenceId) { this.externalReferenceId = externalReferenceId; return this; } + @Override public TollfreeVerification create(final TwilioRestClient client) { + String path = "/v1/Tollfree/Verifications"; - path = - path.replace( - "{" + "BusinessName" + "}", - this.businessName.toString() - ); - path = - path.replace( - "{" + "BusinessWebsite" + "}", - this.businessWebsite.toString() - ); - path = - path.replace( - "{" + "NotificationEmail" + "}", - this.notificationEmail.toString() - ); - path = - path.replace( - "{" + "UseCaseCategories" + "}", - this.useCaseCategories.toString() - ); - path = - path.replace( - "{" + "UseCaseSummary" + "}", - this.useCaseSummary.toString() - ); - path = - path.replace( - "{" + "ProductionMessageSample" + "}", - this.productionMessageSample.toString() - ); - path = - path.replace( - "{" + "OptInImageUrls" + "}", - this.optInImageUrls.toString() - ); - path = path.replace("{" + "OptInType" + "}", this.optInType.toString()); - path = - path.replace( - "{" + "MessageVolume" + "}", - this.messageVolume.toString() - ); - path = - path.replace( - "{" + "TollfreePhoneNumberSid" + "}", - this.tollfreePhoneNumberSid.toString() - ); Request request = new Request( - HttpMethod.POST, - Domains.MESSAGING.toString(), - path + HttpMethod.POST, + Domains.MESSAGING.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "TollfreeVerification creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("TollfreeVerification creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return TollfreeVerification.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return TollfreeVerification.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (businessName != null) { - request.addPostParam("BusinessName", businessName); + Serializer.toString(request, "BusinessName", businessName, ParameterType.URLENCODED); } + + if (businessWebsite != null) { - request.addPostParam("BusinessWebsite", businessWebsite); + Serializer.toString(request, "BusinessWebsite", businessWebsite, ParameterType.URLENCODED); } + + if (notificationEmail != null) { - request.addPostParam("NotificationEmail", notificationEmail); + Serializer.toString(request, "NotificationEmail", notificationEmail, ParameterType.URLENCODED); } + + if (useCaseCategories != null) { - for (String prop : useCaseCategories) { - request.addPostParam("UseCaseCategories", prop); + for (String param : useCaseCategories) { + Serializer.toString(request, "UseCaseCategories", param, ParameterType.URLENCODED); } } + + if (useCaseSummary != null) { - request.addPostParam("UseCaseSummary", useCaseSummary); + Serializer.toString(request, "UseCaseSummary", useCaseSummary, ParameterType.URLENCODED); } + + if (productionMessageSample != null) { - request.addPostParam( - "ProductionMessageSample", - productionMessageSample - ); + Serializer.toString(request, "ProductionMessageSample", productionMessageSample, ParameterType.URLENCODED); } + + if (optInImageUrls != null) { - for (String prop : optInImageUrls) { - request.addPostParam("OptInImageUrls", prop); + for (String param : optInImageUrls) { + Serializer.toString(request, "OptInImageUrls", param, ParameterType.URLENCODED); } } + + if (optInType != null) { - request.addPostParam("OptInType", optInType.toString()); + Serializer.toString(request, "OptInType", optInType, ParameterType.URLENCODED); } + + if (messageVolume != null) { - request.addPostParam("MessageVolume", messageVolume); + Serializer.toString(request, "MessageVolume", messageVolume, ParameterType.URLENCODED); } + + if (tollfreePhoneNumberSid != null) { - request.addPostParam( - "TollfreePhoneNumberSid", - tollfreePhoneNumberSid - ); + Serializer.toString(request, "TollfreePhoneNumberSid", tollfreePhoneNumberSid, ParameterType.URLENCODED); } + + if (customerProfileSid != null) { - request.addPostParam("CustomerProfileSid", customerProfileSid); + Serializer.toString(request, "CustomerProfileSid", customerProfileSid, ParameterType.URLENCODED); } + + if (businessStreetAddress != null) { - request.addPostParam( - "BusinessStreetAddress", - businessStreetAddress - ); + Serializer.toString(request, "BusinessStreetAddress", businessStreetAddress, ParameterType.URLENCODED); } + + if (businessStreetAddress2 != null) { - request.addPostParam( - "BusinessStreetAddress2", - businessStreetAddress2 - ); + Serializer.toString(request, "BusinessStreetAddress2", businessStreetAddress2, ParameterType.URLENCODED); } + + if (businessCity != null) { - request.addPostParam("BusinessCity", businessCity); + Serializer.toString(request, "BusinessCity", businessCity, ParameterType.URLENCODED); } + + if (businessStateProvinceRegion != null) { - request.addPostParam( - "BusinessStateProvinceRegion", - businessStateProvinceRegion - ); + Serializer.toString(request, "BusinessStateProvinceRegion", businessStateProvinceRegion, ParameterType.URLENCODED); } + + if (businessPostalCode != null) { - request.addPostParam("BusinessPostalCode", businessPostalCode); + Serializer.toString(request, "BusinessPostalCode", businessPostalCode, ParameterType.URLENCODED); } + + if (businessCountry != null) { - request.addPostParam("BusinessCountry", businessCountry); + Serializer.toString(request, "BusinessCountry", businessCountry, ParameterType.URLENCODED); } + + if (additionalInformation != null) { - request.addPostParam( - "AdditionalInformation", - additionalInformation - ); + Serializer.toString(request, "AdditionalInformation", additionalInformation, ParameterType.URLENCODED); } + + if (businessContactFirstName != null) { - request.addPostParam( - "BusinessContactFirstName", - businessContactFirstName - ); + Serializer.toString(request, "BusinessContactFirstName", businessContactFirstName, ParameterType.URLENCODED); } + + if (businessContactLastName != null) { - request.addPostParam( - "BusinessContactLastName", - businessContactLastName - ); + Serializer.toString(request, "BusinessContactLastName", businessContactLastName, ParameterType.URLENCODED); } + + if (businessContactEmail != null) { - request.addPostParam("BusinessContactEmail", businessContactEmail); + Serializer.toString(request, "BusinessContactEmail", businessContactEmail, ParameterType.URLENCODED); } + + if (businessContactPhone != null) { - request.addPostParam( - "BusinessContactPhone", - businessContactPhone.toString() - ); + Serializer.toString(request, "BusinessContactPhone", businessContactPhone, ParameterType.URLENCODED); } + + if (externalReferenceId != null) { - request.addPostParam("ExternalReferenceId", externalReferenceId); + Serializer.toString(request, "ExternalReferenceId", externalReferenceId, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/messaging/v1/TollfreeVerificationDeleter.java b/src/main/java/com/twilio/rest/messaging/v1/TollfreeVerificationDeleter.java index a59328ac78..2ba69d6c0e 100644 --- a/src/main/java/com/twilio/rest/messaging/v1/TollfreeVerificationDeleter.java +++ b/src/main/java/com/twilio/rest/messaging/v1/TollfreeVerificationDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.messaging.v1; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,40 +26,38 @@ public class TollfreeVerificationDeleter extends Deleter { - private String pathSid; + private String pathsid; - public TollfreeVerificationDeleter(final String pathSid) { - this.pathSid = pathSid; + public TollfreeVerificationDeleter(final String pathsid) { + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/v1/Tollfree/Verifications/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.MESSAGING.toString(), - path + HttpMethod.DELETE, + Domains.MESSAGING.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "TollfreeVerification delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("TollfreeVerification delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/messaging/v1/TollfreeVerificationFetcher.java b/src/main/java/com/twilio/rest/messaging/v1/TollfreeVerificationFetcher.java index 9f074fa7f7..07016851ba 100644 --- a/src/main/java/com/twilio/rest/messaging/v1/TollfreeVerificationFetcher.java +++ b/src/main/java/com/twilio/rest/messaging/v1/TollfreeVerificationFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.messaging.v1; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,47 +26,41 @@ public class TollfreeVerificationFetcher extends Fetcher { - private String pathSid; + private String pathsid; - public TollfreeVerificationFetcher(final String pathSid) { - this.pathSid = pathSid; + public TollfreeVerificationFetcher(final String pathsid) { + this.pathsid = pathsid; } + @Override public TollfreeVerification fetch(final TwilioRestClient client) { + String path = "/v1/Tollfree/Verifications/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.MESSAGING.toString(), - path + HttpMethod.GET, + Domains.MESSAGING.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "TollfreeVerification fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("TollfreeVerification fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return TollfreeVerification.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return TollfreeVerification.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/messaging/v1/TollfreeVerificationReader.java b/src/main/java/com/twilio/rest/messaging/v1/TollfreeVerificationReader.java index dceec62f82..370731c288 100644 --- a/src/main/java/com/twilio/rest/messaging/v1/TollfreeVerificationReader.java +++ b/src/main/java/com/twilio/rest/messaging/v1/TollfreeVerificationReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -35,153 +36,127 @@ public class TollfreeVerificationReader extends Reader { private Boolean includeSubAccounts; private Long pageSize; - public TollfreeVerificationReader() {} + public TollfreeVerificationReader() { + } + - public TollfreeVerificationReader setTollfreePhoneNumberSid( - final String tollfreePhoneNumberSid - ) { + public TollfreeVerificationReader setTollfreePhoneNumberSid(final String tollfreePhoneNumberSid) { this.tollfreePhoneNumberSid = tollfreePhoneNumberSid; return this; } - public TollfreeVerificationReader setStatus( - final TollfreeVerification.Status status - ) { + + public TollfreeVerificationReader setStatus(final TollfreeVerification.Status status) { this.status = status; return this; } - public TollfreeVerificationReader setExternalReferenceId( - final String externalReferenceId - ) { + + public TollfreeVerificationReader setExternalReferenceId(final String externalReferenceId) { this.externalReferenceId = externalReferenceId; return this; } - public TollfreeVerificationReader setIncludeSubAccounts( - final Boolean includeSubAccounts - ) { + + public TollfreeVerificationReader setIncludeSubAccounts(final Boolean includeSubAccounts) { this.includeSubAccounts = includeSubAccounts; return this; } + public TollfreeVerificationReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override - public ResourceSet read( - final TwilioRestClient client - ) { + public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/Tollfree/Verifications"; + Request request = new Request( - HttpMethod.GET, - Domains.MESSAGING.toString(), - path + HttpMethod.GET, + Domains.MESSAGING.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "TollfreeVerification read failed: Unable to connect to server" - ); + throw new ApiConnectionException("TollfreeVerification read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "verifications", - response.getContent(), - TollfreeVerification.class, - client.getObjectMapper() - ); + "verifications", + response.getContent(), + TollfreeVerification.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.MESSAGING.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.MESSAGING.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (tollfreePhoneNumberSid != null) { - request.addQueryParam( - "TollfreePhoneNumberSid", - tollfreePhoneNumberSid - ); + Serializer.toString(request, "TollfreePhoneNumberSid", tollfreePhoneNumberSid, ParameterType.QUERY); } + + if (status != null) { - request.addQueryParam("Status", status.toString()); + Serializer.toString(request, "Status", status, ParameterType.QUERY); } + + if (externalReferenceId != null) { - request.addQueryParam("ExternalReferenceId", externalReferenceId); + Serializer.toString(request, "ExternalReferenceId", externalReferenceId, ParameterType.QUERY); } + + if (includeSubAccounts != null) { - request.addQueryParam( - "IncludeSubAccounts", - includeSubAccounts.toString() - ); + Serializer.toString(request, "IncludeSubAccounts", includeSubAccounts, ParameterType.QUERY); } + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/messaging/v1/TollfreeVerificationUpdater.java b/src/main/java/com/twilio/rest/messaging/v1/TollfreeVerificationUpdater.java index 212cb9f085..af5c442d8f 100644 --- a/src/main/java/com/twilio/rest/messaging/v1/TollfreeVerificationUpdater.java +++ b/src/main/java/com/twilio/rest/messaging/v1/TollfreeVerificationUpdater.java @@ -16,7 +16,9 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; import com.twilio.converter.Promoter; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,11 +27,11 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.util.List; public class TollfreeVerificationUpdater extends Updater { - - private String pathSid; + private String pathsid; private String businessName; private String businessWebsite; private String notificationEmail; @@ -52,168 +54,138 @@ public class TollfreeVerificationUpdater extends Updater { private com.twilio.type.PhoneNumber businessContactPhone; private String editReason; - public TollfreeVerificationUpdater(final String pathSid) { - this.pathSid = pathSid; + public TollfreeVerificationUpdater(final String pathsid) { + this.pathsid = pathsid; } - public TollfreeVerificationUpdater setBusinessName( - final String businessName - ) { + + public TollfreeVerificationUpdater setBusinessName(final String businessName) { this.businessName = businessName; return this; } - public TollfreeVerificationUpdater setBusinessWebsite( - final String businessWebsite - ) { + + public TollfreeVerificationUpdater setBusinessWebsite(final String businessWebsite) { this.businessWebsite = businessWebsite; return this; } - public TollfreeVerificationUpdater setNotificationEmail( - final String notificationEmail - ) { + + public TollfreeVerificationUpdater setNotificationEmail(final String notificationEmail) { this.notificationEmail = notificationEmail; return this; } - public TollfreeVerificationUpdater setUseCaseCategories( - final List useCaseCategories - ) { + + public TollfreeVerificationUpdater setUseCaseCategories(final List useCaseCategories) { this.useCaseCategories = useCaseCategories; return this; } - public TollfreeVerificationUpdater setUseCaseCategories( - final String useCaseCategories - ) { + public TollfreeVerificationUpdater setUseCaseCategories(final String useCaseCategories) { return setUseCaseCategories(Promoter.listOfOne(useCaseCategories)); } - public TollfreeVerificationUpdater setUseCaseSummary( - final String useCaseSummary - ) { + public TollfreeVerificationUpdater setUseCaseSummary(final String useCaseSummary) { this.useCaseSummary = useCaseSummary; return this; } - public TollfreeVerificationUpdater setProductionMessageSample( - final String productionMessageSample - ) { + + public TollfreeVerificationUpdater setProductionMessageSample(final String productionMessageSample) { this.productionMessageSample = productionMessageSample; return this; } - public TollfreeVerificationUpdater setOptInImageUrls( - final List optInImageUrls - ) { + + public TollfreeVerificationUpdater setOptInImageUrls(final List optInImageUrls) { this.optInImageUrls = optInImageUrls; return this; } - public TollfreeVerificationUpdater setOptInImageUrls( - final String optInImageUrls - ) { + public TollfreeVerificationUpdater setOptInImageUrls(final String optInImageUrls) { return setOptInImageUrls(Promoter.listOfOne(optInImageUrls)); } - public TollfreeVerificationUpdater setOptInType( - final TollfreeVerification.OptInType optInType - ) { + public TollfreeVerificationUpdater setOptInType(final TollfreeVerification.OptInType optInType) { this.optInType = optInType; return this; } - public TollfreeVerificationUpdater setMessageVolume( - final String messageVolume - ) { + + public TollfreeVerificationUpdater setMessageVolume(final String messageVolume) { this.messageVolume = messageVolume; return this; } - public TollfreeVerificationUpdater setBusinessStreetAddress( - final String businessStreetAddress - ) { + + public TollfreeVerificationUpdater setBusinessStreetAddress(final String businessStreetAddress) { this.businessStreetAddress = businessStreetAddress; return this; } - public TollfreeVerificationUpdater setBusinessStreetAddress2( - final String businessStreetAddress2 - ) { + + public TollfreeVerificationUpdater setBusinessStreetAddress2(final String businessStreetAddress2) { this.businessStreetAddress2 = businessStreetAddress2; return this; } - public TollfreeVerificationUpdater setBusinessCity( - final String businessCity - ) { + + public TollfreeVerificationUpdater setBusinessCity(final String businessCity) { this.businessCity = businessCity; return this; } - public TollfreeVerificationUpdater setBusinessStateProvinceRegion( - final String businessStateProvinceRegion - ) { + + public TollfreeVerificationUpdater setBusinessStateProvinceRegion(final String businessStateProvinceRegion) { this.businessStateProvinceRegion = businessStateProvinceRegion; return this; } - public TollfreeVerificationUpdater setBusinessPostalCode( - final String businessPostalCode - ) { + + public TollfreeVerificationUpdater setBusinessPostalCode(final String businessPostalCode) { this.businessPostalCode = businessPostalCode; return this; } - public TollfreeVerificationUpdater setBusinessCountry( - final String businessCountry - ) { + + public TollfreeVerificationUpdater setBusinessCountry(final String businessCountry) { this.businessCountry = businessCountry; return this; } - public TollfreeVerificationUpdater setAdditionalInformation( - final String additionalInformation - ) { + + public TollfreeVerificationUpdater setAdditionalInformation(final String additionalInformation) { this.additionalInformation = additionalInformation; return this; } - public TollfreeVerificationUpdater setBusinessContactFirstName( - final String businessContactFirstName - ) { + + public TollfreeVerificationUpdater setBusinessContactFirstName(final String businessContactFirstName) { this.businessContactFirstName = businessContactFirstName; return this; } - public TollfreeVerificationUpdater setBusinessContactLastName( - final String businessContactLastName - ) { + + public TollfreeVerificationUpdater setBusinessContactLastName(final String businessContactLastName) { this.businessContactLastName = businessContactLastName; return this; } - public TollfreeVerificationUpdater setBusinessContactEmail( - final String businessContactEmail - ) { + + public TollfreeVerificationUpdater setBusinessContactEmail(final String businessContactEmail) { this.businessContactEmail = businessContactEmail; return this; } - public TollfreeVerificationUpdater setBusinessContactPhone( - final com.twilio.type.PhoneNumber businessContactPhone - ) { + + public TollfreeVerificationUpdater setBusinessContactPhone(final com.twilio.type.PhoneNumber businessContactPhone) { this.businessContactPhone = businessContactPhone; return this; } - public TollfreeVerificationUpdater setBusinessContactPhone( - final String businessContactPhone - ) { - return setBusinessContactPhone( - Promoter.phoneNumberFromString(businessContactPhone) - ); + public TollfreeVerificationUpdater setBusinessContactPhone(final String businessContactPhone) { + return setBusinessContactPhone(Promoter.phoneNumberFromString(businessContactPhone)); } public TollfreeVerificationUpdater setEditReason(final String editReason) { @@ -221,135 +193,151 @@ public TollfreeVerificationUpdater setEditReason(final String editReason) { return this; } + @Override public TollfreeVerification update(final TwilioRestClient client) { + String path = "/v1/Tollfree/Verifications/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.MESSAGING.toString(), - path + HttpMethod.POST, + Domains.MESSAGING.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "TollfreeVerification update failed: Unable to connect to server" - ); + throw new ApiConnectionException("TollfreeVerification update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return TollfreeVerification.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return TollfreeVerification.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (businessName != null) { - request.addPostParam("BusinessName", businessName); + Serializer.toString(request, "BusinessName", businessName, ParameterType.URLENCODED); } + + if (businessWebsite != null) { - request.addPostParam("BusinessWebsite", businessWebsite); + Serializer.toString(request, "BusinessWebsite", businessWebsite, ParameterType.URLENCODED); } + + if (notificationEmail != null) { - request.addPostParam("NotificationEmail", notificationEmail); + Serializer.toString(request, "NotificationEmail", notificationEmail, ParameterType.URLENCODED); } + + if (useCaseCategories != null) { - for (String prop : useCaseCategories) { - request.addPostParam("UseCaseCategories", prop); + for (String param : useCaseCategories) { + Serializer.toString(request, "UseCaseCategories", param, ParameterType.URLENCODED); } } + + if (useCaseSummary != null) { - request.addPostParam("UseCaseSummary", useCaseSummary); + Serializer.toString(request, "UseCaseSummary", useCaseSummary, ParameterType.URLENCODED); } + + if (productionMessageSample != null) { - request.addPostParam( - "ProductionMessageSample", - productionMessageSample - ); + Serializer.toString(request, "ProductionMessageSample", productionMessageSample, ParameterType.URLENCODED); } + + if (optInImageUrls != null) { - for (String prop : optInImageUrls) { - request.addPostParam("OptInImageUrls", prop); + for (String param : optInImageUrls) { + Serializer.toString(request, "OptInImageUrls", param, ParameterType.URLENCODED); } } + + if (optInType != null) { - request.addPostParam("OptInType", optInType.toString()); + Serializer.toString(request, "OptInType", optInType, ParameterType.URLENCODED); } + + if (messageVolume != null) { - request.addPostParam("MessageVolume", messageVolume); + Serializer.toString(request, "MessageVolume", messageVolume, ParameterType.URLENCODED); } + + if (businessStreetAddress != null) { - request.addPostParam( - "BusinessStreetAddress", - businessStreetAddress - ); + Serializer.toString(request, "BusinessStreetAddress", businessStreetAddress, ParameterType.URLENCODED); } + + if (businessStreetAddress2 != null) { - request.addPostParam( - "BusinessStreetAddress2", - businessStreetAddress2 - ); + Serializer.toString(request, "BusinessStreetAddress2", businessStreetAddress2, ParameterType.URLENCODED); } + + if (businessCity != null) { - request.addPostParam("BusinessCity", businessCity); + Serializer.toString(request, "BusinessCity", businessCity, ParameterType.URLENCODED); } + + if (businessStateProvinceRegion != null) { - request.addPostParam( - "BusinessStateProvinceRegion", - businessStateProvinceRegion - ); + Serializer.toString(request, "BusinessStateProvinceRegion", businessStateProvinceRegion, ParameterType.URLENCODED); } + + if (businessPostalCode != null) { - request.addPostParam("BusinessPostalCode", businessPostalCode); + Serializer.toString(request, "BusinessPostalCode", businessPostalCode, ParameterType.URLENCODED); } + + if (businessCountry != null) { - request.addPostParam("BusinessCountry", businessCountry); + Serializer.toString(request, "BusinessCountry", businessCountry, ParameterType.URLENCODED); } + + if (additionalInformation != null) { - request.addPostParam( - "AdditionalInformation", - additionalInformation - ); + Serializer.toString(request, "AdditionalInformation", additionalInformation, ParameterType.URLENCODED); } + + if (businessContactFirstName != null) { - request.addPostParam( - "BusinessContactFirstName", - businessContactFirstName - ); + Serializer.toString(request, "BusinessContactFirstName", businessContactFirstName, ParameterType.URLENCODED); } + + if (businessContactLastName != null) { - request.addPostParam( - "BusinessContactLastName", - businessContactLastName - ); + Serializer.toString(request, "BusinessContactLastName", businessContactLastName, ParameterType.URLENCODED); } + + if (businessContactEmail != null) { - request.addPostParam("BusinessContactEmail", businessContactEmail); + Serializer.toString(request, "BusinessContactEmail", businessContactEmail, ParameterType.URLENCODED); } + + if (businessContactPhone != null) { - request.addPostParam( - "BusinessContactPhone", - businessContactPhone.toString() - ); + Serializer.toString(request, "BusinessContactPhone", businessContactPhone, ParameterType.URLENCODED); } + + if (editReason != null) { - request.addPostParam("EditReason", editReason); + Serializer.toString(request, "EditReason", editReason, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/messaging/v1/Usecase.java b/src/main/java/com/twilio/rest/messaging/v1/Usecase.java index 292cfb83b1..8f528b1625 100644 --- a/src/main/java/com/twilio/rest/messaging/v1/Usecase.java +++ b/src/main/java/com/twilio/rest/messaging/v1/Usecase.java @@ -18,41 +18,40 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.util.List; -import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Usecase extends Resource { - private static final long serialVersionUID = 232787447190817L; public static UsecaseFetcher fetcher() { - return new UsecaseFetcher(); + return new UsecaseFetcher( + + ); } + /** * Converts a JSON String into a Usecase object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Usecase object represented by the provided JSON */ - public static Usecase fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Usecase fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Usecase.class); @@ -67,14 +66,11 @@ public static Usecase fromJson( * Converts a JSON InputStream into a Usecase object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Usecase object represented by the provided JSON */ - public static Usecase fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Usecase fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Usecase.class); @@ -85,19 +81,29 @@ public static Usecase fromJson( } } - private final List> usecases; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter + private final List usecases; @JsonCreator private Usecase( - @JsonProperty("usecases") final List> usecases + @JsonProperty("usecases") final List usecases ) { this.usecases = usecases; } - public final List> getUsecases() { - return this.usecases; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -109,12 +115,18 @@ public boolean equals(final Object o) { } Usecase other = (Usecase) o; - - return Objects.equals(usecases, other.usecases); + return ( + Objects.equals(usecases, other.usecases) + ); } @Override public int hashCode() { - return Objects.hash(usecases); + return Objects.hash( + usecases + ); } + + } + diff --git a/src/main/java/com/twilio/rest/messaging/v1/UsecaseFetcher.java b/src/main/java/com/twilio/rest/messaging/v1/UsecaseFetcher.java index f166b496d4..d53d8e03a5 100644 --- a/src/main/java/com/twilio/rest/messaging/v1/UsecaseFetcher.java +++ b/src/main/java/com/twilio/rest/messaging/v1/UsecaseFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.messaging.v1; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,38 +26,37 @@ public class UsecaseFetcher extends Fetcher { - public UsecaseFetcher() {} + + public UsecaseFetcher() { + } + @Override public Usecase fetch(final TwilioRestClient client) { + String path = "/v1/Services/Usecases"; + Request request = new Request( - HttpMethod.GET, - Domains.MESSAGING.toString(), - path + HttpMethod.GET, + Domains.MESSAGING.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Usecase fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Usecase fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Usecase.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/messaging/v1/brandregistration/BrandRegistrationOtp.java b/src/main/java/com/twilio/rest/messaging/v1/brandregistration/BrandRegistrationOtp.java index 165f5acc23..c880408902 100644 --- a/src/main/java/com/twilio/rest/messaging/v1/brandregistration/BrandRegistrationOtp.java +++ b/src/main/java/com/twilio/rest/messaging/v1/brandregistration/BrandRegistrationOtp.java @@ -18,40 +18,39 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class BrandRegistrationOtp extends Resource { - private static final long serialVersionUID = 131615733171627L; - public static BrandRegistrationOtpCreator creator( - final String pathBrandRegistrationSid - ) { - return new BrandRegistrationOtpCreator(pathBrandRegistrationSid); + public static BrandRegistrationOtpCreator creator(final String pathbrandRegistrationSid) { + return new BrandRegistrationOtpCreator( + pathbrandRegistrationSid + ); } + /** * Converts a JSON String into a BrandRegistrationOtp object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return BrandRegistrationOtp object represented by the provided JSON */ - public static BrandRegistrationOtp fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static BrandRegistrationOtp fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, BrandRegistrationOtp.class); @@ -66,14 +65,11 @@ public static BrandRegistrationOtp fromJson( * Converts a JSON InputStream into a BrandRegistrationOtp object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return BrandRegistrationOtp object represented by the provided JSON */ - public static BrandRegistrationOtp fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static BrandRegistrationOtp fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, BrandRegistrationOtp.class); @@ -84,28 +80,33 @@ public static BrandRegistrationOtp fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; + @Getter private final String brandRegistrationSid; @JsonCreator private BrandRegistrationOtp( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty( - "brand_registration_sid" - ) final String brandRegistrationSid + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("brand_registration_sid") final String brandRegistrationSid ) { this.accountSid = accountSid; this.brandRegistrationSid = brandRegistrationSid; } - public final String getAccountSid() { - return this.accountSid; - } - - public final String getBrandRegistrationSid() { - return this.brandRegistrationSid; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -117,15 +118,20 @@ public boolean equals(final Object o) { } BrandRegistrationOtp other = (BrandRegistrationOtp) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(brandRegistrationSid, other.brandRegistrationSid) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(brandRegistrationSid, other.brandRegistrationSid) ); } @Override public int hashCode() { - return Objects.hash(accountSid, brandRegistrationSid); + return Objects.hash( + accountSid, + brandRegistrationSid + ); } + + } + diff --git a/src/main/java/com/twilio/rest/messaging/v1/brandregistration/BrandRegistrationOtpCreator.java b/src/main/java/com/twilio/rest/messaging/v1/brandregistration/BrandRegistrationOtpCreator.java index 989a50313c..60770e5796 100644 --- a/src/main/java/com/twilio/rest/messaging/v1/brandregistration/BrandRegistrationOtpCreator.java +++ b/src/main/java/com/twilio/rest/messaging/v1/brandregistration/BrandRegistrationOtpCreator.java @@ -14,8 +14,8 @@ package com.twilio.rest.messaging.v1.brandregistration; + import com.twilio.base.Creator; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,51 +27,42 @@ public class BrandRegistrationOtpCreator extends Creator { - private String pathBrandRegistrationSid; + private String pathbrandRegistrationSid; - public BrandRegistrationOtpCreator(final String pathBrandRegistrationSid) { - this.pathBrandRegistrationSid = pathBrandRegistrationSid; + public BrandRegistrationOtpCreator(final String pathbrandRegistrationSid) { + this.pathbrandRegistrationSid = pathbrandRegistrationSid; } + @Override public BrandRegistrationOtp create(final TwilioRestClient client) { - String path = - "/v1/a2p/BrandRegistrations/{BrandRegistrationSid}/SmsOtp"; - path = - path.replace( - "{" + "BrandRegistrationSid" + "}", - this.pathBrandRegistrationSid.toString() - ); + String path = "/v1/a2p/BrandRegistrations/{BrandRegistrationSid}/SmsOtp"; + + path = path.replace("{" + "BrandRegistrationSid" + "}", this.pathbrandRegistrationSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.MESSAGING.toString(), - path + HttpMethod.POST, + Domains.MESSAGING.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "BrandRegistrationOtp creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("BrandRegistrationOtp creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return BrandRegistrationOtp.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return BrandRegistrationOtp.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/messaging/v1/brandregistration/BrandVetting.java b/src/main/java/com/twilio/rest/messaging/v1/brandregistration/BrandVetting.java index 7d7f8526b5..a8ce388ff0 100644 --- a/src/main/java/com/twilio/rest/messaging/v1/brandregistration/BrandVetting.java +++ b/src/main/java/com/twilio/rest/messaging/v1/brandregistration/BrandVetting.java @@ -18,56 +18,78 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class BrandVetting extends Resource { - private static final long serialVersionUID = 122020517475795L; - public static BrandVettingCreator creator( - final String pathBrandSid, - final BrandVetting.VettingProvider vettingProvider - ) { - return new BrandVettingCreator(pathBrandSid, vettingProvider); + public static BrandVettingCreator creator(final String pathbrandSid, final BrandVetting.VettingProvider vettingProvider) { + return new BrandVettingCreator( + pathbrandSid, vettingProvider + ); } - public static BrandVettingFetcher fetcher( - final String pathBrandSid, - final String pathBrandVettingSid - ) { - return new BrandVettingFetcher(pathBrandSid, pathBrandVettingSid); + + public static BrandVettingFetcher fetcher(final String pathbrandSid, final String pathbrandVettingSid) { + return new BrandVettingFetcher( + pathbrandSid, pathbrandVettingSid + ); } - public static BrandVettingReader reader(final String pathBrandSid) { - return new BrandVettingReader(pathBrandSid); + + public static BrandVettingReader reader(final String pathbrandSid) { + return new BrandVettingReader( + pathbrandSid + ); } + + public enum VettingProvider { + CAMPAIGN_VERIFY("campaign-verify"), + AEGIS("aegis"); + + private final String value; + + private VettingProvider(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static VettingProvider forValue(final String value) { + return Promoter.enumFromString(value, VettingProvider.values()); + } + } + + /** * Converts a JSON String into a BrandVetting object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return BrandVetting object represented by the provided JSON */ - public static BrandVetting fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static BrandVetting fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, BrandVetting.class); @@ -82,14 +104,11 @@ public static BrandVetting fromJson( * Converts a JSON InputStream into a BrandVetting object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return BrandVetting object represented by the provided JSON */ - public static BrandVetting fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static BrandVetting fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, BrandVetting.class); @@ -100,82 +119,65 @@ public static BrandVetting fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; + @Getter private final String brandSid; + @Getter private final String brandVettingSid; - private final ZonedDateTime dateUpdated; + @Getter private final ZonedDateTime dateCreated; - private final String vettingId; + @Getter + private final ZonedDateTime dateUpdated; + @Getter + private final URI url; + @Getter private final String vettingClass; - private final String vettingStatus; + @Getter + private final String vettingId; + @Getter private final BrandVetting.VettingProvider vettingProvider; - private final URI url; + @Getter + private final String vettingStatus; @JsonCreator private BrandVetting( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("brand_sid") final String brandSid, - @JsonProperty("brand_vetting_sid") final String brandVettingSid, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("vetting_id") final String vettingId, - @JsonProperty("vetting_class") final String vettingClass, - @JsonProperty("vetting_status") final String vettingStatus, - @JsonProperty( - "vetting_provider" - ) final BrandVetting.VettingProvider vettingProvider, - @JsonProperty("url") final URI url + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("brand_sid") final String brandSid, + @JsonProperty("brand_vetting_sid") final String brandVettingSid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("url") final URI url, + @JsonProperty("vetting_class") final String vettingClass, + @JsonProperty("vetting_id") final String vettingId, + @JsonProperty("vetting_provider") final BrandVetting.VettingProvider vettingProvider, + @JsonProperty("vetting_status") final String vettingStatus ) { this.accountSid = accountSid; this.brandSid = brandSid; this.brandVettingSid = brandVettingSid; - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.vettingId = vettingId; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; + this.url = url; this.vettingClass = vettingClass; - this.vettingStatus = vettingStatus; + this.vettingId = vettingId; this.vettingProvider = vettingProvider; - this.url = url; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getBrandSid() { - return this.brandSid; - } - - public final String getBrandVettingSid() { - return this.brandVettingSid; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final String getVettingId() { - return this.vettingId; - } - - public final String getVettingClass() { - return this.vettingClass; - } - - public final String getVettingStatus() { - return this.vettingStatus; - } - - public final BrandVetting.VettingProvider getVettingProvider() { - return this.vettingProvider; - } - - public final URI getUrl() { - return this.url; + this.vettingStatus = vettingStatus; } @Override @@ -189,54 +191,36 @@ public boolean equals(final Object o) { } BrandVetting other = (BrandVetting) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(brandSid, other.brandSid) && - Objects.equals(brandVettingSid, other.brandVettingSid) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(vettingId, other.vettingId) && - Objects.equals(vettingClass, other.vettingClass) && - Objects.equals(vettingStatus, other.vettingStatus) && - Objects.equals(vettingProvider, other.vettingProvider) && - Objects.equals(url, other.url) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(brandSid, other.brandSid) && + Objects.equals(brandVettingSid, other.brandVettingSid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(url, other.url) && + Objects.equals(vettingClass, other.vettingClass) && + Objects.equals(vettingId, other.vettingId) && + Objects.equals(vettingProvider, other.vettingProvider) && + Objects.equals(vettingStatus, other.vettingStatus) ); } @Override public int hashCode() { return Objects.hash( - accountSid, - brandSid, - brandVettingSid, - dateUpdated, - dateCreated, - vettingId, - vettingClass, - vettingStatus, - vettingProvider, - url + accountSid, + brandSid, + brandVettingSid, + dateCreated, + dateUpdated, + url, + vettingClass, + vettingId, + vettingProvider, + vettingStatus ); } - public enum VettingProvider { - CAMPAIGN_VERIFY("campaign-verify"), - AEGIS("aegis"); - - private final String value; - - private VettingProvider(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - @JsonCreator - public static VettingProvider forValue(final String value) { - return Promoter.enumFromString(value, VettingProvider.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/messaging/v1/brandregistration/BrandVettingCreator.java b/src/main/java/com/twilio/rest/messaging/v1/brandregistration/BrandVettingCreator.java index 07a4f7d954..3b3bfbdcea 100644 --- a/src/main/java/com/twilio/rest/messaging/v1/brandregistration/BrandVettingCreator.java +++ b/src/main/java/com/twilio/rest/messaging/v1/brandregistration/BrandVettingCreator.java @@ -14,8 +14,11 @@ package com.twilio.rest.messaging.v1.brandregistration; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,80 +30,73 @@ public class BrandVettingCreator extends Creator { - private String pathBrandSid; + private String pathbrandSid; private BrandVetting.VettingProvider vettingProvider; private String vettingId; - public BrandVettingCreator( - final String pathBrandSid, - final BrandVetting.VettingProvider vettingProvider - ) { - this.pathBrandSid = pathBrandSid; + public BrandVettingCreator(final String pathbrandSid, final BrandVetting.VettingProvider vettingProvider) { + this.pathbrandSid = pathbrandSid; this.vettingProvider = vettingProvider; } - public BrandVettingCreator setVettingProvider( - final BrandVetting.VettingProvider vettingProvider - ) { + + public BrandVettingCreator setVettingProvider(final BrandVetting.VettingProvider vettingProvider) { this.vettingProvider = vettingProvider; return this; } + public BrandVettingCreator setVettingId(final String vettingId) { this.vettingId = vettingId; return this; } + @Override public BrandVetting create(final TwilioRestClient client) { + String path = "/v1/a2p/BrandRegistrations/{BrandSid}/Vettings"; - path = - path.replace("{" + "BrandSid" + "}", this.pathBrandSid.toString()); - path = - path.replace( - "{" + "VettingProvider" + "}", - this.vettingProvider.toString() - ); + path = path.replace("{" + "BrandSid" + "}", this.pathbrandSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.MESSAGING.toString(), - path + HttpMethod.POST, + Domains.MESSAGING.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "BrandVetting creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("BrandVetting creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return BrandVetting.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return BrandVetting.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (vettingProvider != null) { - request.addPostParam("VettingProvider", vettingProvider.toString()); + Serializer.toString(request, "VettingProvider", vettingProvider, ParameterType.URLENCODED); } + + if (vettingId != null) { - request.addPostParam("VettingId", vettingId); + Serializer.toString(request, "VettingId", vettingId, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/messaging/v1/brandregistration/BrandVettingFetcher.java b/src/main/java/com/twilio/rest/messaging/v1/brandregistration/BrandVettingFetcher.java index 482aeddcc5..3a69f72e87 100644 --- a/src/main/java/com/twilio/rest/messaging/v1/brandregistration/BrandVettingFetcher.java +++ b/src/main/java/com/twilio/rest/messaging/v1/brandregistration/BrandVettingFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.messaging.v1.brandregistration; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,59 +26,44 @@ public class BrandVettingFetcher extends Fetcher { - private String pathBrandSid; - private String pathBrandVettingSid; + private String pathbrandSid; + private String pathbrandVettingSid; - public BrandVettingFetcher( - final String pathBrandSid, - final String pathBrandVettingSid - ) { - this.pathBrandSid = pathBrandSid; - this.pathBrandVettingSid = pathBrandVettingSid; + public BrandVettingFetcher(final String pathbrandSid, final String pathbrandVettingSid) { + this.pathbrandSid = pathbrandSid; + this.pathbrandVettingSid = pathbrandVettingSid; } + @Override public BrandVetting fetch(final TwilioRestClient client) { - String path = - "/v1/a2p/BrandRegistrations/{BrandSid}/Vettings/{BrandVettingSid}"; - path = - path.replace("{" + "BrandSid" + "}", this.pathBrandSid.toString()); - path = - path.replace( - "{" + "BrandVettingSid" + "}", - this.pathBrandVettingSid.toString() - ); + String path = "/v1/a2p/BrandRegistrations/{BrandSid}/Vettings/{BrandVettingSid}"; + + path = path.replace("{" + "BrandSid" + "}", this.pathbrandSid.toString()); + path = path.replace("{" + "BrandVettingSid" + "}", this.pathbrandVettingSid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.MESSAGING.toString(), - path + HttpMethod.GET, + Domains.MESSAGING.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "BrandVetting fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("BrandVetting fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return BrandVetting.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return BrandVetting.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/messaging/v1/brandregistration/BrandVettingReader.java b/src/main/java/com/twilio/rest/messaging/v1/brandregistration/BrandVettingReader.java index db8f3b9487..ac27ca535d 100644 --- a/src/main/java/com/twilio/rest/messaging/v1/brandregistration/BrandVettingReader.java +++ b/src/main/java/com/twilio/rest/messaging/v1/brandregistration/BrandVettingReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,117 +30,88 @@ public class BrandVettingReader extends Reader { - private String pathBrandSid; + private String pathbrandSid; private BrandVetting.VettingProvider vettingProvider; - public BrandVettingReader(final String pathBrandSid) { - this.pathBrandSid = pathBrandSid; + public BrandVettingReader(final String pathbrandSid) { + this.pathbrandSid = pathbrandSid; } - public BrandVettingReader setVettingProvider( - final BrandVetting.VettingProvider vettingProvider - ) { + + public BrandVettingReader setVettingProvider(final BrandVetting.VettingProvider vettingProvider) { this.vettingProvider = vettingProvider; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/a2p/BrandRegistrations/{BrandSid}/Vettings"; - path = - path.replace("{" + "BrandSid" + "}", this.pathBrandSid.toString()); + + path = path.replace("{" + "BrandSid" + "}", this.pathbrandSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.MESSAGING.toString(), - path + HttpMethod.GET, + Domains.MESSAGING.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "BrandVetting read failed: Unable to connect to server" - ); + throw new ApiConnectionException("BrandVetting read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "data", - response.getContent(), - BrandVetting.class, - client.getObjectMapper() - ); + "data", + response.getContent(), + BrandVetting.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.MESSAGING.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.MESSAGING.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (vettingProvider != null) { - request.addQueryParam( - "VettingProvider", - vettingProvider.toString() - ); + Serializer.toString(request, "VettingProvider", vettingProvider, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/messaging/v1/service/AlphaSender.java b/src/main/java/com/twilio/rest/messaging/v1/service/AlphaSender.java index d13ad27315..9978e0a5b4 100644 --- a/src/main/java/com/twilio/rest/messaging/v1/service/AlphaSender.java +++ b/src/main/java/com/twilio/rest/messaging/v1/service/AlphaSender.java @@ -18,63 +18,64 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.List; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class AlphaSender extends Resource { - private static final long serialVersionUID = 147044042659249L; - public static AlphaSenderCreator creator( - final String pathServiceSid, - final String alphaSender - ) { - return new AlphaSenderCreator(pathServiceSid, alphaSender); + public static AlphaSenderCreator creator(final String pathserviceSid, final String alphaSender) { + return new AlphaSenderCreator( + pathserviceSid, alphaSender + ); } - public static AlphaSenderDeleter deleter( - final String pathServiceSid, - final String pathSid - ) { - return new AlphaSenderDeleter(pathServiceSid, pathSid); + + public static AlphaSenderDeleter deleter(final String pathserviceSid, final String pathsid) { + return new AlphaSenderDeleter( + pathserviceSid, pathsid + ); } - public static AlphaSenderFetcher fetcher( - final String pathServiceSid, - final String pathSid - ) { - return new AlphaSenderFetcher(pathServiceSid, pathSid); + + public static AlphaSenderFetcher fetcher(final String pathserviceSid, final String pathsid) { + return new AlphaSenderFetcher( + pathserviceSid, pathsid + ); } - public static AlphaSenderReader reader(final String pathServiceSid) { - return new AlphaSenderReader(pathServiceSid); + + public static AlphaSenderReader reader(final String pathserviceSid) { + return new AlphaSenderReader( + pathserviceSid + ); } + /** * Converts a JSON String into a AlphaSender object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return AlphaSender object represented by the provided JSON */ - public static AlphaSender fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static AlphaSender fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, AlphaSender.class); @@ -89,14 +90,11 @@ public static AlphaSender fromJson( * Converts a JSON InputStream into a AlphaSender object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return AlphaSender object represented by the provided JSON */ - public static AlphaSender fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static AlphaSender fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, AlphaSender.class); @@ -107,68 +105,59 @@ public static AlphaSender fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String serviceSid; - private final ZonedDateTime dateCreated; - private final ZonedDateTime dateUpdated; + @Getter private final String alphaSender; + @Getter private final List capabilities; + @Getter + private final ZonedDateTime dateCreated; + @Getter + private final ZonedDateTime dateUpdated; + @Getter + private final String serviceSid; + @Getter + private final String sid; + @Getter private final URI url; @JsonCreator private AlphaSender( - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("service_sid") final String serviceSid, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("alpha_sender") final String alphaSender, - @JsonProperty("capabilities") final List capabilities, - @JsonProperty("url") final URI url + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("alpha_sender") final String alphaSender, + @JsonProperty("capabilities") final List capabilities, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("service_sid") final String serviceSid, + @JsonProperty("sid") final String sid, + @JsonProperty("url") final URI url ) { - this.sid = sid; this.accountSid = accountSid; - this.serviceSid = serviceSid; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); this.alphaSender = alphaSender; this.capabilities = capabilities; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; + this.serviceSid = serviceSid; + this.sid = sid; this.url = url; } - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getServiceSid() { - return this.serviceSid; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final String getAlphaSender() { - return this.alphaSender; - } - - public final List getCapabilities() { - return this.capabilities; - } - - public final URI getUrl() { - return this.url; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -180,30 +169,32 @@ public boolean equals(final Object o) { } AlphaSender other = (AlphaSender) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(serviceSid, other.serviceSid) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(alphaSender, other.alphaSender) && - Objects.equals(capabilities, other.capabilities) && - Objects.equals(url, other.url) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(alphaSender, other.alphaSender) && + Objects.equals(capabilities, other.capabilities) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(serviceSid, other.serviceSid) && + Objects.equals(sid, other.sid) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - sid, - accountSid, - serviceSid, - dateCreated, - dateUpdated, - alphaSender, - capabilities, - url + accountSid, + alphaSender, + capabilities, + dateCreated, + dateUpdated, + serviceSid, + sid, + url ); } + + } + diff --git a/src/main/java/com/twilio/rest/messaging/v1/service/AlphaSenderCreator.java b/src/main/java/com/twilio/rest/messaging/v1/service/AlphaSenderCreator.java index f2f46637b1..dc463f42f2 100644 --- a/src/main/java/com/twilio/rest/messaging/v1/service/AlphaSenderCreator.java +++ b/src/main/java/com/twilio/rest/messaging/v1/service/AlphaSenderCreator.java @@ -14,8 +14,11 @@ package com.twilio.rest.messaging.v1.service; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,72 +30,61 @@ public class AlphaSenderCreator extends Creator { - private String pathServiceSid; + private String pathserviceSid; private String alphaSender; - public AlphaSenderCreator( - final String pathServiceSid, - final String alphaSender - ) { - this.pathServiceSid = pathServiceSid; + public AlphaSenderCreator(final String pathserviceSid, final String alphaSender) { + this.pathserviceSid = pathserviceSid; this.alphaSender = alphaSender; } + public AlphaSenderCreator setAlphaSender(final String alphaSender) { this.alphaSender = alphaSender; return this; } + @Override public AlphaSender create(final TwilioRestClient client) { + String path = "/v1/Services/{ServiceSid}/AlphaSenders"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = - path.replace( - "{" + "AlphaSender" + "}", - this.alphaSender.toString() - ); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.MESSAGING.toString(), - path + HttpMethod.POST, + Domains.MESSAGING.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "AlphaSender creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("AlphaSender creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return AlphaSender.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return AlphaSender.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (alphaSender != null) { - request.addPostParam("AlphaSender", alphaSender); + Serializer.toString(request, "AlphaSender", alphaSender, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/messaging/v1/service/AlphaSenderDeleter.java b/src/main/java/com/twilio/rest/messaging/v1/service/AlphaSenderDeleter.java index c596fc6ccc..690b7924ac 100644 --- a/src/main/java/com/twilio/rest/messaging/v1/service/AlphaSenderDeleter.java +++ b/src/main/java/com/twilio/rest/messaging/v1/service/AlphaSenderDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.messaging.v1.service; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,50 +26,41 @@ public class AlphaSenderDeleter extends Deleter { - private String pathServiceSid; - private String pathSid; + private String pathserviceSid; + private String pathsid; - public AlphaSenderDeleter( - final String pathServiceSid, - final String pathSid - ) { - this.pathServiceSid = pathServiceSid; - this.pathSid = pathSid; + public AlphaSenderDeleter(final String pathserviceSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/v1/Services/{ServiceSid}/AlphaSenders/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.MESSAGING.toString(), - path + HttpMethod.DELETE, + Domains.MESSAGING.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "AlphaSender delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("AlphaSender delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/messaging/v1/service/AlphaSenderFetcher.java b/src/main/java/com/twilio/rest/messaging/v1/service/AlphaSenderFetcher.java index a24e33fded..183700b62b 100644 --- a/src/main/java/com/twilio/rest/messaging/v1/service/AlphaSenderFetcher.java +++ b/src/main/java/com/twilio/rest/messaging/v1/service/AlphaSenderFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.messaging.v1.service; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,57 +26,44 @@ public class AlphaSenderFetcher extends Fetcher { - private String pathServiceSid; - private String pathSid; + private String pathserviceSid; + private String pathsid; - public AlphaSenderFetcher( - final String pathServiceSid, - final String pathSid - ) { - this.pathServiceSid = pathServiceSid; - this.pathSid = pathSid; + public AlphaSenderFetcher(final String pathserviceSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathsid = pathsid; } + @Override public AlphaSender fetch(final TwilioRestClient client) { + String path = "/v1/Services/{ServiceSid}/AlphaSenders/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.MESSAGING.toString(), - path + HttpMethod.GET, + Domains.MESSAGING.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "AlphaSender fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("AlphaSender fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return AlphaSender.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return AlphaSender.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/messaging/v1/service/AlphaSenderReader.java b/src/main/java/com/twilio/rest/messaging/v1/service/AlphaSenderReader.java index f20e3870f3..bc0bb0ed14 100644 --- a/src/main/java/com/twilio/rest/messaging/v1/service/AlphaSenderReader.java +++ b/src/main/java/com/twilio/rest/messaging/v1/service/AlphaSenderReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,115 +30,88 @@ public class AlphaSenderReader extends Reader { - private String pathServiceSid; + private String pathserviceSid; private Long pageSize; - public AlphaSenderReader(final String pathServiceSid) { - this.pathServiceSid = pathServiceSid; + public AlphaSenderReader(final String pathserviceSid) { + this.pathserviceSid = pathserviceSid; } + public AlphaSenderReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/Services/{ServiceSid}/AlphaSenders"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.MESSAGING.toString(), - path + HttpMethod.GET, + Domains.MESSAGING.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "AlphaSender read failed: Unable to connect to server" - ); + throw new ApiConnectionException("AlphaSender read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "alpha_senders", - response.getContent(), - AlphaSender.class, - client.getObjectMapper() - ); + "alpha_senders", + response.getContent(), + AlphaSender.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.MESSAGING.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.MESSAGING.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/messaging/v1/service/ChannelSender.java b/src/main/java/com/twilio/rest/messaging/v1/service/ChannelSender.java index fe8266c690..fc075c772f 100644 --- a/src/main/java/com/twilio/rest/messaging/v1/service/ChannelSender.java +++ b/src/main/java/com/twilio/rest/messaging/v1/service/ChannelSender.java @@ -18,64 +18,63 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class ChannelSender extends Resource { - private static final long serialVersionUID = 32697428616380L; - public static ChannelSenderCreator creator( - final String pathMessagingServiceSid, - final String sid - ) { - return new ChannelSenderCreator(pathMessagingServiceSid, sid); + public static ChannelSenderCreator creator(final String pathmessagingServiceSid, final String sid) { + return new ChannelSenderCreator( + pathmessagingServiceSid, sid + ); } - public static ChannelSenderDeleter deleter( - final String pathMessagingServiceSid, - final String pathSid - ) { - return new ChannelSenderDeleter(pathMessagingServiceSid, pathSid); + + public static ChannelSenderDeleter deleter(final String pathmessagingServiceSid, final String pathsid) { + return new ChannelSenderDeleter( + pathmessagingServiceSid, pathsid + ); } - public static ChannelSenderFetcher fetcher( - final String pathMessagingServiceSid, - final String pathSid - ) { - return new ChannelSenderFetcher(pathMessagingServiceSid, pathSid); + + public static ChannelSenderFetcher fetcher(final String pathmessagingServiceSid, final String pathsid) { + return new ChannelSenderFetcher( + pathmessagingServiceSid, pathsid + ); } - public static ChannelSenderReader reader( - final String pathMessagingServiceSid - ) { - return new ChannelSenderReader(pathMessagingServiceSid); + + public static ChannelSenderReader reader(final String pathmessagingServiceSid) { + return new ChannelSenderReader( + pathmessagingServiceSid + ); } + /** * Converts a JSON String into a ChannelSender object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return ChannelSender object represented by the provided JSON */ - public static ChannelSender fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static ChannelSender fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, ChannelSender.class); @@ -90,14 +89,11 @@ public static ChannelSender fromJson( * Converts a JSON InputStream into a ChannelSender object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return ChannelSender object represented by the provided JSON */ - public static ChannelSender fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static ChannelSender fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, ChannelSender.class); @@ -108,75 +104,63 @@ public static ChannelSender fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String messagingServiceSid; - private final String sid; - private final String sender; - private final String senderType; + @Getter private final String countryCode; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; + @Getter + private final String messagingServiceSid; + @Getter + private final String sender; + @Getter + private final String senderType; + @Getter + private final String sid; + @Getter private final URI url; @JsonCreator private ChannelSender( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("messaging_service_sid") final String messagingServiceSid, - @JsonProperty("sid") final String sid, - @JsonProperty("sender") final String sender, - @JsonProperty("sender_type") final String senderType, - @JsonProperty("country_code") final String countryCode, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("url") final URI url + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("country_code") final String countryCode, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("messaging_service_sid") final String messagingServiceSid, + @JsonProperty("sender") final String sender, + @JsonProperty("sender_type") final String senderType, + @JsonProperty("sid") final String sid, + @JsonProperty("url") final URI url ) { this.accountSid = accountSid; + this.countryCode = countryCode; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.messagingServiceSid = messagingServiceSid; - this.sid = sid; this.sender = sender; this.senderType = senderType; - this.countryCode = countryCode; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); + this.sid = sid; this.url = url; } - public final String getAccountSid() { - return this.accountSid; - } - - public final String getMessagingServiceSid() { - return this.messagingServiceSid; - } - - public final String getSid() { - return this.sid; - } - - public final String getSender() { - return this.sender; - } - - public final String getSenderType() { - return this.senderType; - } - - public final String getCountryCode() { - return this.countryCode; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final URI getUrl() { - return this.url; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -188,32 +172,34 @@ public boolean equals(final Object o) { } ChannelSender other = (ChannelSender) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(messagingServiceSid, other.messagingServiceSid) && - Objects.equals(sid, other.sid) && - Objects.equals(sender, other.sender) && - Objects.equals(senderType, other.senderType) && - Objects.equals(countryCode, other.countryCode) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(url, other.url) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(countryCode, other.countryCode) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(messagingServiceSid, other.messagingServiceSid) && + Objects.equals(sender, other.sender) && + Objects.equals(senderType, other.senderType) && + Objects.equals(sid, other.sid) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - accountSid, - messagingServiceSid, - sid, - sender, - senderType, - countryCode, - dateCreated, - dateUpdated, - url + accountSid, + countryCode, + dateCreated, + dateUpdated, + messagingServiceSid, + sender, + senderType, + sid, + url ); } + + } + diff --git a/src/main/java/com/twilio/rest/messaging/v1/service/ChannelSenderCreator.java b/src/main/java/com/twilio/rest/messaging/v1/service/ChannelSenderCreator.java index e492a10cbe..432e9965cf 100644 --- a/src/main/java/com/twilio/rest/messaging/v1/service/ChannelSenderCreator.java +++ b/src/main/java/com/twilio/rest/messaging/v1/service/ChannelSenderCreator.java @@ -14,8 +14,11 @@ package com.twilio.rest.messaging.v1.service; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,68 +30,61 @@ public class ChannelSenderCreator extends Creator { - private String pathMessagingServiceSid; + private String pathmessagingServiceSid; private String sid; - public ChannelSenderCreator( - final String pathMessagingServiceSid, - final String sid - ) { - this.pathMessagingServiceSid = pathMessagingServiceSid; + public ChannelSenderCreator(final String pathmessagingServiceSid, final String sid) { + this.pathmessagingServiceSid = pathmessagingServiceSid; this.sid = sid; } + public ChannelSenderCreator setSid(final String sid) { this.sid = sid; return this; } + @Override public ChannelSender create(final TwilioRestClient client) { + String path = "/v1/Services/{MessagingServiceSid}/ChannelSenders"; - path = - path.replace( - "{" + "MessagingServiceSid" + "}", - this.pathMessagingServiceSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.sid.toString()); + path = path.replace("{" + "MessagingServiceSid" + "}", this.pathmessagingServiceSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.MESSAGING.toString(), - path + HttpMethod.POST, + Domains.MESSAGING.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "ChannelSender creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("ChannelSender creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return ChannelSender.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return ChannelSender.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (sid != null) { - request.addPostParam("Sid", sid); + Serializer.toString(request, "Sid", sid, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/messaging/v1/service/ChannelSenderDeleter.java b/src/main/java/com/twilio/rest/messaging/v1/service/ChannelSenderDeleter.java index f5d6f15a2a..7487c7088a 100644 --- a/src/main/java/com/twilio/rest/messaging/v1/service/ChannelSenderDeleter.java +++ b/src/main/java/com/twilio/rest/messaging/v1/service/ChannelSenderDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.messaging.v1.service; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,50 +26,41 @@ public class ChannelSenderDeleter extends Deleter { - private String pathMessagingServiceSid; - private String pathSid; + private String pathmessagingServiceSid; + private String pathsid; - public ChannelSenderDeleter( - final String pathMessagingServiceSid, - final String pathSid - ) { - this.pathMessagingServiceSid = pathMessagingServiceSid; - this.pathSid = pathSid; + public ChannelSenderDeleter(final String pathmessagingServiceSid, final String pathsid) { + this.pathmessagingServiceSid = pathmessagingServiceSid; + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/v1/Services/{MessagingServiceSid}/ChannelSenders/{Sid}"; - path = - path.replace( - "{" + "MessagingServiceSid" + "}", - this.pathMessagingServiceSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "MessagingServiceSid" + "}", this.pathmessagingServiceSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.MESSAGING.toString(), - path + HttpMethod.DELETE, + Domains.MESSAGING.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "ChannelSender delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("ChannelSender delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/messaging/v1/service/ChannelSenderFetcher.java b/src/main/java/com/twilio/rest/messaging/v1/service/ChannelSenderFetcher.java index a28798ec6f..5739c0dcbb 100644 --- a/src/main/java/com/twilio/rest/messaging/v1/service/ChannelSenderFetcher.java +++ b/src/main/java/com/twilio/rest/messaging/v1/service/ChannelSenderFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.messaging.v1.service; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,57 +26,44 @@ public class ChannelSenderFetcher extends Fetcher { - private String pathMessagingServiceSid; - private String pathSid; + private String pathmessagingServiceSid; + private String pathsid; - public ChannelSenderFetcher( - final String pathMessagingServiceSid, - final String pathSid - ) { - this.pathMessagingServiceSid = pathMessagingServiceSid; - this.pathSid = pathSid; + public ChannelSenderFetcher(final String pathmessagingServiceSid, final String pathsid) { + this.pathmessagingServiceSid = pathmessagingServiceSid; + this.pathsid = pathsid; } + @Override public ChannelSender fetch(final TwilioRestClient client) { + String path = "/v1/Services/{MessagingServiceSid}/ChannelSenders/{Sid}"; - path = - path.replace( - "{" + "MessagingServiceSid" + "}", - this.pathMessagingServiceSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "MessagingServiceSid" + "}", this.pathmessagingServiceSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.MESSAGING.toString(), - path + HttpMethod.GET, + Domains.MESSAGING.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "ChannelSender fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("ChannelSender fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return ChannelSender.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return ChannelSender.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/messaging/v1/service/ChannelSenderReader.java b/src/main/java/com/twilio/rest/messaging/v1/service/ChannelSenderReader.java index 4dab8836fe..6052bb746f 100644 --- a/src/main/java/com/twilio/rest/messaging/v1/service/ChannelSenderReader.java +++ b/src/main/java/com/twilio/rest/messaging/v1/service/ChannelSenderReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,115 +30,88 @@ public class ChannelSenderReader extends Reader { - private String pathMessagingServiceSid; + private String pathmessagingServiceSid; private Long pageSize; - public ChannelSenderReader(final String pathMessagingServiceSid) { - this.pathMessagingServiceSid = pathMessagingServiceSid; + public ChannelSenderReader(final String pathmessagingServiceSid) { + this.pathmessagingServiceSid = pathmessagingServiceSid; } + public ChannelSenderReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/Services/{MessagingServiceSid}/ChannelSenders"; - path = - path.replace( - "{" + "MessagingServiceSid" + "}", - this.pathMessagingServiceSid.toString() - ); + + path = path.replace("{" + "MessagingServiceSid" + "}", this.pathmessagingServiceSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.MESSAGING.toString(), - path + HttpMethod.GET, + Domains.MESSAGING.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "ChannelSender read failed: Unable to connect to server" - ); + throw new ApiConnectionException("ChannelSender read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "senders", - response.getContent(), - ChannelSender.class, - client.getObjectMapper() - ); + "senders", + response.getContent(), + ChannelSender.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.MESSAGING.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.MESSAGING.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/messaging/v1/service/DestinationAlphaSender.java b/src/main/java/com/twilio/rest/messaging/v1/service/DestinationAlphaSender.java index 3d56268c4c..71ee803068 100644 --- a/src/main/java/com/twilio/rest/messaging/v1/service/DestinationAlphaSender.java +++ b/src/main/java/com/twilio/rest/messaging/v1/service/DestinationAlphaSender.java @@ -18,65 +18,64 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.List; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class DestinationAlphaSender extends Resource { - private static final long serialVersionUID = 148729356404048L; - public static DestinationAlphaSenderCreator creator( - final String pathServiceSid, - final String alphaSender - ) { - return new DestinationAlphaSenderCreator(pathServiceSid, alphaSender); + public static DestinationAlphaSenderCreator creator(final String pathserviceSid, final String alphaSender) { + return new DestinationAlphaSenderCreator( + pathserviceSid, alphaSender + ); } - public static DestinationAlphaSenderDeleter deleter( - final String pathServiceSid, - final String pathSid - ) { - return new DestinationAlphaSenderDeleter(pathServiceSid, pathSid); + + public static DestinationAlphaSenderDeleter deleter(final String pathserviceSid, final String pathsid) { + return new DestinationAlphaSenderDeleter( + pathserviceSid, pathsid + ); } - public static DestinationAlphaSenderFetcher fetcher( - final String pathServiceSid, - final String pathSid - ) { - return new DestinationAlphaSenderFetcher(pathServiceSid, pathSid); + + public static DestinationAlphaSenderFetcher fetcher(final String pathserviceSid, final String pathsid) { + return new DestinationAlphaSenderFetcher( + pathserviceSid, pathsid + ); } - public static DestinationAlphaSenderReader reader( - final String pathServiceSid - ) { - return new DestinationAlphaSenderReader(pathServiceSid); + + public static DestinationAlphaSenderReader reader(final String pathserviceSid) { + return new DestinationAlphaSenderReader( + pathserviceSid + ); } + /** * Converts a JSON String into a DestinationAlphaSender object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return DestinationAlphaSender object represented by the provided JSON */ - public static DestinationAlphaSender fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static DestinationAlphaSender fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, DestinationAlphaSender.class); @@ -91,14 +90,11 @@ public static DestinationAlphaSender fromJson( * Converts a JSON InputStream into a DestinationAlphaSender object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return DestinationAlphaSender object represented by the provided JSON */ - public static DestinationAlphaSender fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static DestinationAlphaSender fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, DestinationAlphaSender.class); @@ -109,73 +105,61 @@ public static DestinationAlphaSender fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String serviceSid; - private final ZonedDateTime dateCreated; - private final ZonedDateTime dateUpdated; + @Getter private final String alphaSender; + @Getter private final List capabilities; - private final URI url; + @Getter + private final ZonedDateTime dateCreated; + @Getter + private final ZonedDateTime dateUpdated; + @Getter private final String isoCountryCode; + @Getter + private final String serviceSid; + @Getter + private final String sid; + @Getter + private final URI url; @JsonCreator private DestinationAlphaSender( - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("service_sid") final String serviceSid, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("alpha_sender") final String alphaSender, - @JsonProperty("capabilities") final List capabilities, - @JsonProperty("url") final URI url, - @JsonProperty("iso_country_code") final String isoCountryCode + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("alpha_sender") final String alphaSender, + @JsonProperty("capabilities") final List capabilities, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("iso_country_code") final String isoCountryCode, + @JsonProperty("service_sid") final String serviceSid, + @JsonProperty("sid") final String sid, + @JsonProperty("url") final URI url ) { - this.sid = sid; this.accountSid = accountSid; - this.serviceSid = serviceSid; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); this.alphaSender = alphaSender; this.capabilities = capabilities; - this.url = url; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.isoCountryCode = isoCountryCode; - } - - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getServiceSid() { - return this.serviceSid; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final String getAlphaSender() { - return this.alphaSender; - } - - public final List getCapabilities() { - return this.capabilities; - } - - public final URI getUrl() { - return this.url; - } - - public final String getIsoCountryCode() { - return this.isoCountryCode; + this.serviceSid = serviceSid; + this.sid = sid; + this.url = url; } @Override @@ -189,32 +173,34 @@ public boolean equals(final Object o) { } DestinationAlphaSender other = (DestinationAlphaSender) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(serviceSid, other.serviceSid) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(alphaSender, other.alphaSender) && - Objects.equals(capabilities, other.capabilities) && - Objects.equals(url, other.url) && - Objects.equals(isoCountryCode, other.isoCountryCode) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(alphaSender, other.alphaSender) && + Objects.equals(capabilities, other.capabilities) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(isoCountryCode, other.isoCountryCode) && + Objects.equals(serviceSid, other.serviceSid) && + Objects.equals(sid, other.sid) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - sid, - accountSid, - serviceSid, - dateCreated, - dateUpdated, - alphaSender, - capabilities, - url, - isoCountryCode + accountSid, + alphaSender, + capabilities, + dateCreated, + dateUpdated, + isoCountryCode, + serviceSid, + sid, + url ); } + + } + diff --git a/src/main/java/com/twilio/rest/messaging/v1/service/DestinationAlphaSenderCreator.java b/src/main/java/com/twilio/rest/messaging/v1/service/DestinationAlphaSenderCreator.java index 0ea7c1ffed..2fdce55f15 100644 --- a/src/main/java/com/twilio/rest/messaging/v1/service/DestinationAlphaSenderCreator.java +++ b/src/main/java/com/twilio/rest/messaging/v1/service/DestinationAlphaSenderCreator.java @@ -14,8 +14,11 @@ package com.twilio.rest.messaging.v1.service; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,88 +28,75 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class DestinationAlphaSenderCreator - extends Creator { +public class DestinationAlphaSenderCreator extends Creator { - private String pathServiceSid; + private String pathserviceSid; private String alphaSender; private String isoCountryCode; - public DestinationAlphaSenderCreator( - final String pathServiceSid, - final String alphaSender - ) { - this.pathServiceSid = pathServiceSid; + public DestinationAlphaSenderCreator(final String pathserviceSid, final String alphaSender) { + this.pathserviceSid = pathserviceSid; this.alphaSender = alphaSender; } - public DestinationAlphaSenderCreator setAlphaSender( - final String alphaSender - ) { + + public DestinationAlphaSenderCreator setAlphaSender(final String alphaSender) { this.alphaSender = alphaSender; return this; } - public DestinationAlphaSenderCreator setIsoCountryCode( - final String isoCountryCode - ) { + + public DestinationAlphaSenderCreator setIsoCountryCode(final String isoCountryCode) { this.isoCountryCode = isoCountryCode; return this; } + @Override public DestinationAlphaSender create(final TwilioRestClient client) { + String path = "/v1/Services/{ServiceSid}/DestinationAlphaSenders"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = - path.replace( - "{" + "AlphaSender" + "}", - this.alphaSender.toString() - ); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.MESSAGING.toString(), - path + HttpMethod.POST, + Domains.MESSAGING.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "DestinationAlphaSender creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("DestinationAlphaSender creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return DestinationAlphaSender.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return DestinationAlphaSender.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (alphaSender != null) { - request.addPostParam("AlphaSender", alphaSender); + Serializer.toString(request, "AlphaSender", alphaSender, ParameterType.URLENCODED); } + + if (isoCountryCode != null) { - request.addPostParam("IsoCountryCode", isoCountryCode); + Serializer.toString(request, "IsoCountryCode", isoCountryCode, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/messaging/v1/service/DestinationAlphaSenderDeleter.java b/src/main/java/com/twilio/rest/messaging/v1/service/DestinationAlphaSenderDeleter.java index 2fe7b9fbb3..75cbacd650 100644 --- a/src/main/java/com/twilio/rest/messaging/v1/service/DestinationAlphaSenderDeleter.java +++ b/src/main/java/com/twilio/rest/messaging/v1/service/DestinationAlphaSenderDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.messaging.v1.service; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,53 +24,43 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class DestinationAlphaSenderDeleter - extends Deleter { +public class DestinationAlphaSenderDeleter extends Deleter { - private String pathServiceSid; - private String pathSid; + private String pathserviceSid; + private String pathsid; - public DestinationAlphaSenderDeleter( - final String pathServiceSid, - final String pathSid - ) { - this.pathServiceSid = pathServiceSid; - this.pathSid = pathSid; + public DestinationAlphaSenderDeleter(final String pathserviceSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/v1/Services/{ServiceSid}/DestinationAlphaSenders/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.MESSAGING.toString(), - path + HttpMethod.DELETE, + Domains.MESSAGING.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "DestinationAlphaSender delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("DestinationAlphaSender delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/messaging/v1/service/DestinationAlphaSenderFetcher.java b/src/main/java/com/twilio/rest/messaging/v1/service/DestinationAlphaSenderFetcher.java index e54f63702b..b332c93d1c 100644 --- a/src/main/java/com/twilio/rest/messaging/v1/service/DestinationAlphaSenderFetcher.java +++ b/src/main/java/com/twilio/rest/messaging/v1/service/DestinationAlphaSenderFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.messaging.v1.service; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,60 +24,46 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class DestinationAlphaSenderFetcher - extends Fetcher { +public class DestinationAlphaSenderFetcher extends Fetcher { - private String pathServiceSid; - private String pathSid; + private String pathserviceSid; + private String pathsid; - public DestinationAlphaSenderFetcher( - final String pathServiceSid, - final String pathSid - ) { - this.pathServiceSid = pathServiceSid; - this.pathSid = pathSid; + public DestinationAlphaSenderFetcher(final String pathserviceSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathsid = pathsid; } + @Override public DestinationAlphaSender fetch(final TwilioRestClient client) { + String path = "/v1/Services/{ServiceSid}/DestinationAlphaSenders/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.MESSAGING.toString(), - path + HttpMethod.GET, + Domains.MESSAGING.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "DestinationAlphaSender fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("DestinationAlphaSender fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return DestinationAlphaSender.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return DestinationAlphaSender.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/messaging/v1/service/DestinationAlphaSenderReader.java b/src/main/java/com/twilio/rest/messaging/v1/service/DestinationAlphaSenderReader.java index c521f523ca..8cff692198 100644 --- a/src/main/java/com/twilio/rest/messaging/v1/service/DestinationAlphaSenderReader.java +++ b/src/main/java/com/twilio/rest/messaging/v1/service/DestinationAlphaSenderReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,133 +28,102 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class DestinationAlphaSenderReader - extends Reader { +public class DestinationAlphaSenderReader extends Reader { - private String pathServiceSid; + private String pathserviceSid; private String isoCountryCode; private Long pageSize; - public DestinationAlphaSenderReader(final String pathServiceSid) { - this.pathServiceSid = pathServiceSid; + public DestinationAlphaSenderReader(final String pathserviceSid) { + this.pathserviceSid = pathserviceSid; } - public DestinationAlphaSenderReader setIsoCountryCode( - final String isoCountryCode - ) { + + public DestinationAlphaSenderReader setIsoCountryCode(final String isoCountryCode) { this.isoCountryCode = isoCountryCode; return this; } + public DestinationAlphaSenderReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override - public ResourceSet read( - final TwilioRestClient client - ) { + public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } - public Page firstPage( - final TwilioRestClient client - ) { + public Page firstPage(final TwilioRestClient client) { + String path = "/v1/Services/{ServiceSid}/DestinationAlphaSenders"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.MESSAGING.toString(), - path + HttpMethod.GET, + Domains.MESSAGING.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "DestinationAlphaSender read failed: Unable to connect to server" - ); + throw new ApiConnectionException("DestinationAlphaSender read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "alpha_senders", - response.getContent(), - DestinationAlphaSender.class, - client.getObjectMapper() - ); + "alpha_senders", + response.getContent(), + DestinationAlphaSender.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.MESSAGING.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.MESSAGING.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (isoCountryCode != null) { - request.addQueryParam("IsoCountryCode", isoCountryCode); + Serializer.toString(request, "IsoCountryCode", isoCountryCode, ParameterType.QUERY); } + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/messaging/v1/service/PhoneNumber.java b/src/main/java/com/twilio/rest/messaging/v1/service/PhoneNumber.java index 453f546a87..acb896ba75 100644 --- a/src/main/java/com/twilio/rest/messaging/v1/service/PhoneNumber.java +++ b/src/main/java/com/twilio/rest/messaging/v1/service/PhoneNumber.java @@ -18,63 +18,64 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.List; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class PhoneNumber extends Resource { - private static final long serialVersionUID = 272509077394294L; - public static PhoneNumberCreator creator( - final String pathServiceSid, - final String phoneNumberSid - ) { - return new PhoneNumberCreator(pathServiceSid, phoneNumberSid); + public static PhoneNumberCreator creator(final String pathserviceSid, final String phoneNumberSid) { + return new PhoneNumberCreator( + pathserviceSid, phoneNumberSid + ); } - public static PhoneNumberDeleter deleter( - final String pathServiceSid, - final String pathSid - ) { - return new PhoneNumberDeleter(pathServiceSid, pathSid); + + public static PhoneNumberDeleter deleter(final String pathserviceSid, final String pathsid) { + return new PhoneNumberDeleter( + pathserviceSid, pathsid + ); } - public static PhoneNumberFetcher fetcher( - final String pathServiceSid, - final String pathSid - ) { - return new PhoneNumberFetcher(pathServiceSid, pathSid); + + public static PhoneNumberFetcher fetcher(final String pathserviceSid, final String pathsid) { + return new PhoneNumberFetcher( + pathserviceSid, pathsid + ); } - public static PhoneNumberReader reader(final String pathServiceSid) { - return new PhoneNumberReader(pathServiceSid); + + public static PhoneNumberReader reader(final String pathserviceSid) { + return new PhoneNumberReader( + pathserviceSid + ); } + /** * Converts a JSON String into a PhoneNumber object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return PhoneNumber object represented by the provided JSON */ - public static PhoneNumber fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static PhoneNumber fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, PhoneNumber.class); @@ -89,14 +90,11 @@ public static PhoneNumber fromJson( * Converts a JSON InputStream into a PhoneNumber object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return PhoneNumber object represented by the provided JSON */ - public static PhoneNumber fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static PhoneNumber fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, PhoneNumber.class); @@ -107,77 +105,63 @@ public static PhoneNumber fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String serviceSid; + @Getter + private final List capabilities; + @Getter + private final String countryCode; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; + @Getter private final com.twilio.type.PhoneNumber phoneNumber; - private final String countryCode; - private final List capabilities; + @Getter + private final String serviceSid; + @Getter + private final String sid; + @Getter private final URI url; @JsonCreator private PhoneNumber( - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("service_sid") final String serviceSid, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty( - "phone_number" - ) final com.twilio.type.PhoneNumber phoneNumber, - @JsonProperty("country_code") final String countryCode, - @JsonProperty("capabilities") final List capabilities, - @JsonProperty("url") final URI url + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("capabilities") final List capabilities, + @JsonProperty("country_code") final String countryCode, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("phone_number") final com.twilio.type.PhoneNumber phoneNumber, + @JsonProperty("service_sid") final String serviceSid, + @JsonProperty("sid") final String sid, + @JsonProperty("url") final URI url ) { - this.sid = sid; this.accountSid = accountSid; - this.serviceSid = serviceSid; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); - this.phoneNumber = phoneNumber; - this.countryCode = countryCode; this.capabilities = capabilities; + this.countryCode = countryCode; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; + this.phoneNumber = phoneNumber; + this.serviceSid = serviceSid; + this.sid = sid; this.url = url; } - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getServiceSid() { - return this.serviceSid; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final com.twilio.type.PhoneNumber getPhoneNumber() { - return this.phoneNumber; - } - - public final String getCountryCode() { - return this.countryCode; - } - - public final List getCapabilities() { - return this.capabilities; - } - - public final URI getUrl() { - return this.url; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -189,32 +173,34 @@ public boolean equals(final Object o) { } PhoneNumber other = (PhoneNumber) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(serviceSid, other.serviceSid) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(phoneNumber, other.phoneNumber) && - Objects.equals(countryCode, other.countryCode) && - Objects.equals(capabilities, other.capabilities) && - Objects.equals(url, other.url) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(capabilities, other.capabilities) && + Objects.equals(countryCode, other.countryCode) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(phoneNumber, other.phoneNumber) && + Objects.equals(serviceSid, other.serviceSid) && + Objects.equals(sid, other.sid) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - sid, - accountSid, - serviceSid, - dateCreated, - dateUpdated, - phoneNumber, - countryCode, - capabilities, - url + accountSid, + capabilities, + countryCode, + dateCreated, + dateUpdated, + phoneNumber, + serviceSid, + sid, + url ); } + + } + diff --git a/src/main/java/com/twilio/rest/messaging/v1/service/PhoneNumberCreator.java b/src/main/java/com/twilio/rest/messaging/v1/service/PhoneNumberCreator.java index 53f905a1a3..25a4a6a5e1 100644 --- a/src/main/java/com/twilio/rest/messaging/v1/service/PhoneNumberCreator.java +++ b/src/main/java/com/twilio/rest/messaging/v1/service/PhoneNumberCreator.java @@ -14,8 +14,11 @@ package com.twilio.rest.messaging.v1.service; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,72 +30,61 @@ public class PhoneNumberCreator extends Creator { - private String pathServiceSid; + private String pathserviceSid; private String phoneNumberSid; - public PhoneNumberCreator( - final String pathServiceSid, - final String phoneNumberSid - ) { - this.pathServiceSid = pathServiceSid; + public PhoneNumberCreator(final String pathserviceSid, final String phoneNumberSid) { + this.pathserviceSid = pathserviceSid; this.phoneNumberSid = phoneNumberSid; } + public PhoneNumberCreator setPhoneNumberSid(final String phoneNumberSid) { this.phoneNumberSid = phoneNumberSid; return this; } + @Override public PhoneNumber create(final TwilioRestClient client) { + String path = "/v1/Services/{ServiceSid}/PhoneNumbers"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = - path.replace( - "{" + "PhoneNumberSid" + "}", - this.phoneNumberSid.toString() - ); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.MESSAGING.toString(), - path + HttpMethod.POST, + Domains.MESSAGING.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "PhoneNumber creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("PhoneNumber creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return PhoneNumber.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return PhoneNumber.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (phoneNumberSid != null) { - request.addPostParam("PhoneNumberSid", phoneNumberSid); + Serializer.toString(request, "PhoneNumberSid", phoneNumberSid, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/messaging/v1/service/PhoneNumberDeleter.java b/src/main/java/com/twilio/rest/messaging/v1/service/PhoneNumberDeleter.java index 51a0ae7586..51906fb7f4 100644 --- a/src/main/java/com/twilio/rest/messaging/v1/service/PhoneNumberDeleter.java +++ b/src/main/java/com/twilio/rest/messaging/v1/service/PhoneNumberDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.messaging.v1.service; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,50 +26,41 @@ public class PhoneNumberDeleter extends Deleter { - private String pathServiceSid; - private String pathSid; + private String pathserviceSid; + private String pathsid; - public PhoneNumberDeleter( - final String pathServiceSid, - final String pathSid - ) { - this.pathServiceSid = pathServiceSid; - this.pathSid = pathSid; + public PhoneNumberDeleter(final String pathserviceSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/v1/Services/{ServiceSid}/PhoneNumbers/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.MESSAGING.toString(), - path + HttpMethod.DELETE, + Domains.MESSAGING.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "PhoneNumber delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("PhoneNumber delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/messaging/v1/service/PhoneNumberFetcher.java b/src/main/java/com/twilio/rest/messaging/v1/service/PhoneNumberFetcher.java index 8aabedeb0e..40a5b58348 100644 --- a/src/main/java/com/twilio/rest/messaging/v1/service/PhoneNumberFetcher.java +++ b/src/main/java/com/twilio/rest/messaging/v1/service/PhoneNumberFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.messaging.v1.service; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,57 +26,44 @@ public class PhoneNumberFetcher extends Fetcher { - private String pathServiceSid; - private String pathSid; + private String pathserviceSid; + private String pathsid; - public PhoneNumberFetcher( - final String pathServiceSid, - final String pathSid - ) { - this.pathServiceSid = pathServiceSid; - this.pathSid = pathSid; + public PhoneNumberFetcher(final String pathserviceSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathsid = pathsid; } + @Override public PhoneNumber fetch(final TwilioRestClient client) { + String path = "/v1/Services/{ServiceSid}/PhoneNumbers/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.MESSAGING.toString(), - path + HttpMethod.GET, + Domains.MESSAGING.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "PhoneNumber fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("PhoneNumber fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return PhoneNumber.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return PhoneNumber.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/messaging/v1/service/PhoneNumberReader.java b/src/main/java/com/twilio/rest/messaging/v1/service/PhoneNumberReader.java index 0a3230f0e7..80163970c7 100644 --- a/src/main/java/com/twilio/rest/messaging/v1/service/PhoneNumberReader.java +++ b/src/main/java/com/twilio/rest/messaging/v1/service/PhoneNumberReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,115 +30,88 @@ public class PhoneNumberReader extends Reader { - private String pathServiceSid; + private String pathserviceSid; private Long pageSize; - public PhoneNumberReader(final String pathServiceSid) { - this.pathServiceSid = pathServiceSid; + public PhoneNumberReader(final String pathserviceSid) { + this.pathserviceSid = pathserviceSid; } + public PhoneNumberReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/Services/{ServiceSid}/PhoneNumbers"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.MESSAGING.toString(), - path + HttpMethod.GET, + Domains.MESSAGING.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "PhoneNumber read failed: Unable to connect to server" - ); + throw new ApiConnectionException("PhoneNumber read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "phone_numbers", - response.getContent(), - PhoneNumber.class, - client.getObjectMapper() - ); + "phone_numbers", + response.getContent(), + PhoneNumber.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.MESSAGING.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.MESSAGING.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/messaging/v1/service/ShortCode.java b/src/main/java/com/twilio/rest/messaging/v1/service/ShortCode.java index bafe69a882..c2fa794b84 100644 --- a/src/main/java/com/twilio/rest/messaging/v1/service/ShortCode.java +++ b/src/main/java/com/twilio/rest/messaging/v1/service/ShortCode.java @@ -18,63 +18,64 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.List; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class ShortCode extends Resource { - private static final long serialVersionUID = 25601319717810L; - public static ShortCodeCreator creator( - final String pathServiceSid, - final String shortCodeSid - ) { - return new ShortCodeCreator(pathServiceSid, shortCodeSid); + public static ShortCodeCreator creator(final String pathserviceSid, final String shortCodeSid) { + return new ShortCodeCreator( + pathserviceSid, shortCodeSid + ); } - public static ShortCodeDeleter deleter( - final String pathServiceSid, - final String pathSid - ) { - return new ShortCodeDeleter(pathServiceSid, pathSid); + + public static ShortCodeDeleter deleter(final String pathserviceSid, final String pathsid) { + return new ShortCodeDeleter( + pathserviceSid, pathsid + ); } - public static ShortCodeFetcher fetcher( - final String pathServiceSid, - final String pathSid - ) { - return new ShortCodeFetcher(pathServiceSid, pathSid); + + public static ShortCodeFetcher fetcher(final String pathserviceSid, final String pathsid) { + return new ShortCodeFetcher( + pathserviceSid, pathsid + ); } - public static ShortCodeReader reader(final String pathServiceSid) { - return new ShortCodeReader(pathServiceSid); + + public static ShortCodeReader reader(final String pathserviceSid) { + return new ShortCodeReader( + pathserviceSid + ); } + /** * Converts a JSON String into a ShortCode object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return ShortCode object represented by the provided JSON */ - public static ShortCode fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static ShortCode fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, ShortCode.class); @@ -89,14 +90,11 @@ public static ShortCode fromJson( * Converts a JSON InputStream into a ShortCode object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return ShortCode object represented by the provided JSON */ - public static ShortCode fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static ShortCode fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, ShortCode.class); @@ -107,75 +105,63 @@ public static ShortCode fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String serviceSid; + @Getter + private final List capabilities; + @Getter + private final String countryCode; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; + @Getter + private final String serviceSid; + @Getter private final String shortCode; - private final String countryCode; - private final List capabilities; + @Getter + private final String sid; + @Getter private final URI url; @JsonCreator private ShortCode( - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("service_sid") final String serviceSid, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("short_code") final String shortCode, - @JsonProperty("country_code") final String countryCode, - @JsonProperty("capabilities") final List capabilities, - @JsonProperty("url") final URI url + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("capabilities") final List capabilities, + @JsonProperty("country_code") final String countryCode, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("service_sid") final String serviceSid, + @JsonProperty("short_code") final String shortCode, + @JsonProperty("sid") final String sid, + @JsonProperty("url") final URI url ) { - this.sid = sid; this.accountSid = accountSid; + this.capabilities = capabilities; + this.countryCode = countryCode; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.serviceSid = serviceSid; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); this.shortCode = shortCode; - this.countryCode = countryCode; - this.capabilities = capabilities; + this.sid = sid; this.url = url; } - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getServiceSid() { - return this.serviceSid; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final String getShortCode() { - return this.shortCode; - } - - public final String getCountryCode() { - return this.countryCode; - } - - public final List getCapabilities() { - return this.capabilities; - } - - public final URI getUrl() { - return this.url; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -187,32 +173,34 @@ public boolean equals(final Object o) { } ShortCode other = (ShortCode) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(serviceSid, other.serviceSid) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(shortCode, other.shortCode) && - Objects.equals(countryCode, other.countryCode) && - Objects.equals(capabilities, other.capabilities) && - Objects.equals(url, other.url) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(capabilities, other.capabilities) && + Objects.equals(countryCode, other.countryCode) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(serviceSid, other.serviceSid) && + Objects.equals(shortCode, other.shortCode) && + Objects.equals(sid, other.sid) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - sid, - accountSid, - serviceSid, - dateCreated, - dateUpdated, - shortCode, - countryCode, - capabilities, - url + accountSid, + capabilities, + countryCode, + dateCreated, + dateUpdated, + serviceSid, + shortCode, + sid, + url ); } + + } + diff --git a/src/main/java/com/twilio/rest/messaging/v1/service/ShortCodeCreator.java b/src/main/java/com/twilio/rest/messaging/v1/service/ShortCodeCreator.java index aa07b830c1..081b577546 100644 --- a/src/main/java/com/twilio/rest/messaging/v1/service/ShortCodeCreator.java +++ b/src/main/java/com/twilio/rest/messaging/v1/service/ShortCodeCreator.java @@ -14,8 +14,11 @@ package com.twilio.rest.messaging.v1.service; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,72 +30,61 @@ public class ShortCodeCreator extends Creator { - private String pathServiceSid; + private String pathserviceSid; private String shortCodeSid; - public ShortCodeCreator( - final String pathServiceSid, - final String shortCodeSid - ) { - this.pathServiceSid = pathServiceSid; + public ShortCodeCreator(final String pathserviceSid, final String shortCodeSid) { + this.pathserviceSid = pathserviceSid; this.shortCodeSid = shortCodeSid; } + public ShortCodeCreator setShortCodeSid(final String shortCodeSid) { this.shortCodeSid = shortCodeSid; return this; } + @Override public ShortCode create(final TwilioRestClient client) { + String path = "/v1/Services/{ServiceSid}/ShortCodes"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = - path.replace( - "{" + "ShortCodeSid" + "}", - this.shortCodeSid.toString() - ); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.MESSAGING.toString(), - path + HttpMethod.POST, + Domains.MESSAGING.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "ShortCode creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("ShortCode creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return ShortCode.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return ShortCode.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (shortCodeSid != null) { - request.addPostParam("ShortCodeSid", shortCodeSid); + Serializer.toString(request, "ShortCodeSid", shortCodeSid, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/messaging/v1/service/ShortCodeDeleter.java b/src/main/java/com/twilio/rest/messaging/v1/service/ShortCodeDeleter.java index d9eaa42e39..5c7cab1d8d 100644 --- a/src/main/java/com/twilio/rest/messaging/v1/service/ShortCodeDeleter.java +++ b/src/main/java/com/twilio/rest/messaging/v1/service/ShortCodeDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.messaging.v1.service; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,47 +26,41 @@ public class ShortCodeDeleter extends Deleter { - private String pathServiceSid; - private String pathSid; + private String pathserviceSid; + private String pathsid; - public ShortCodeDeleter(final String pathServiceSid, final String pathSid) { - this.pathServiceSid = pathServiceSid; - this.pathSid = pathSid; + public ShortCodeDeleter(final String pathserviceSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/v1/Services/{ServiceSid}/ShortCodes/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.MESSAGING.toString(), - path + HttpMethod.DELETE, + Domains.MESSAGING.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "ShortCode delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("ShortCode delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/messaging/v1/service/ShortCodeFetcher.java b/src/main/java/com/twilio/rest/messaging/v1/service/ShortCodeFetcher.java index 4c9c354aa3..fbea83fdde 100644 --- a/src/main/java/com/twilio/rest/messaging/v1/service/ShortCodeFetcher.java +++ b/src/main/java/com/twilio/rest/messaging/v1/service/ShortCodeFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.messaging.v1.service; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,54 +26,44 @@ public class ShortCodeFetcher extends Fetcher { - private String pathServiceSid; - private String pathSid; + private String pathserviceSid; + private String pathsid; - public ShortCodeFetcher(final String pathServiceSid, final String pathSid) { - this.pathServiceSid = pathServiceSid; - this.pathSid = pathSid; + public ShortCodeFetcher(final String pathserviceSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathsid = pathsid; } + @Override public ShortCode fetch(final TwilioRestClient client) { + String path = "/v1/Services/{ServiceSid}/ShortCodes/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.MESSAGING.toString(), - path + HttpMethod.GET, + Domains.MESSAGING.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "ShortCode fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("ShortCode fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return ShortCode.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return ShortCode.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/messaging/v1/service/ShortCodeReader.java b/src/main/java/com/twilio/rest/messaging/v1/service/ShortCodeReader.java index e110c66384..fc5ae67b5a 100644 --- a/src/main/java/com/twilio/rest/messaging/v1/service/ShortCodeReader.java +++ b/src/main/java/com/twilio/rest/messaging/v1/service/ShortCodeReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,115 +30,88 @@ public class ShortCodeReader extends Reader { - private String pathServiceSid; + private String pathserviceSid; private Long pageSize; - public ShortCodeReader(final String pathServiceSid) { - this.pathServiceSid = pathServiceSid; + public ShortCodeReader(final String pathserviceSid) { + this.pathserviceSid = pathserviceSid; } + public ShortCodeReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/Services/{ServiceSid}/ShortCodes"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.MESSAGING.toString(), - path + HttpMethod.GET, + Domains.MESSAGING.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "ShortCode read failed: Unable to connect to server" - ); + throw new ApiConnectionException("ShortCode read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "short_codes", - response.getContent(), - ShortCode.class, - client.getObjectMapper() - ); + "short_codes", + response.getContent(), + ShortCode.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.MESSAGING.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.MESSAGING.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/messaging/v1/service/UsAppToPerson.java b/src/main/java/com/twilio/rest/messaging/v1/service/UsAppToPerson.java index 6fda592d0e..38d0993704 100644 --- a/src/main/java/com/twilio/rest/messaging/v1/service/UsAppToPerson.java +++ b/src/main/java/com/twilio/rest/messaging/v1/service/UsAppToPerson.java @@ -18,106 +18,71 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.List; -import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class UsAppToPerson extends Resource { - private static final long serialVersionUID = 1672467414686L; - public static UsAppToPersonCreator creator( - final String pathMessagingServiceSid, - final String brandRegistrationSid, - final String description, - final String messageFlow, - final List messageSamples, - final String usAppToPersonUsecase, - final Boolean hasEmbeddedLinks, - final Boolean hasEmbeddedPhone - ) { + public static UsAppToPersonCreator creator(final String pathmessagingServiceSid, final String brandRegistrationSid, final String description, final String messageFlow, final List messageSamples, final String usAppToPersonUsecase, final Boolean hasEmbeddedLinks, final Boolean hasEmbeddedPhone) { return new UsAppToPersonCreator( - pathMessagingServiceSid, - brandRegistrationSid, - description, - messageFlow, - messageSamples, - usAppToPersonUsecase, - hasEmbeddedLinks, - hasEmbeddedPhone + pathmessagingServiceSid, brandRegistrationSid, description, messageFlow, messageSamples, usAppToPersonUsecase, hasEmbeddedLinks, hasEmbeddedPhone ); } - public static UsAppToPersonDeleter deleter( - final String pathMessagingServiceSid, - final String pathSid - ) { - return new UsAppToPersonDeleter(pathMessagingServiceSid, pathSid); + + public static UsAppToPersonDeleter deleter(final String pathmessagingServiceSid, final String pathsid) { + return new UsAppToPersonDeleter( + pathmessagingServiceSid, pathsid + ); } - public static UsAppToPersonFetcher fetcher( - final String pathMessagingServiceSid, - final String pathSid - ) { - return new UsAppToPersonFetcher(pathMessagingServiceSid, pathSid); + + public static UsAppToPersonFetcher fetcher(final String pathmessagingServiceSid, final String pathsid) { + return new UsAppToPersonFetcher( + pathmessagingServiceSid, pathsid + ); } - public static UsAppToPersonReader reader( - final String pathMessagingServiceSid - ) { - return new UsAppToPersonReader(pathMessagingServiceSid); + + public static UsAppToPersonReader reader(final String pathmessagingServiceSid) { + return new UsAppToPersonReader( + pathmessagingServiceSid + ); } - public static UsAppToPersonUpdater updater( - final String pathMessagingServiceSid, - final String pathSid, - final Boolean hasEmbeddedLinks, - final Boolean hasEmbeddedPhone, - final List messageSamples, - final String messageFlow, - final String description, - final Boolean ageGated, - final Boolean directLending - ) { + + public static UsAppToPersonUpdater updater(final String pathmessagingServiceSid, final String pathsid, final Boolean hasEmbeddedLinks, final Boolean hasEmbeddedPhone, final List messageSamples, final String messageFlow, final String description, final Boolean ageGated, final Boolean directLending) { return new UsAppToPersonUpdater( - pathMessagingServiceSid, - pathSid, - hasEmbeddedLinks, - hasEmbeddedPhone, - messageSamples, - messageFlow, - description, - ageGated, - directLending + pathmessagingServiceSid, pathsid, hasEmbeddedLinks, hasEmbeddedPhone, messageSamples, messageFlow, description, ageGated, directLending ); } + /** * Converts a JSON String into a UsAppToPerson object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return UsAppToPerson object represented by the provided JSON */ - public static UsAppToPerson fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static UsAppToPerson fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, UsAppToPerson.class); @@ -132,14 +97,11 @@ public static UsAppToPerson fromJson( * Converts a JSON InputStream into a UsAppToPerson object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return UsAppToPerson object represented by the provided JSON */ - public static UsAppToPerson fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static UsAppToPerson fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, UsAppToPerson.class); @@ -150,212 +112,137 @@ public static UsAppToPerson fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; + @Getter + private final Boolean ageGated; + @Getter private final String brandRegistrationSid; - private final String messagingServiceSid; + @Getter + private final String campaignId; + @Getter + private final String campaignStatus; + @Getter + private final ZonedDateTime dateCreated; + @Getter + private final ZonedDateTime dateUpdated; + @Getter private final String description; - private final List messageSamples; - private final String usAppToPersonUsecase; + @Getter + private final Boolean directLending; + @Getter + private final List errors; + @Getter private final Boolean hasEmbeddedLinks; + @Getter private final Boolean hasEmbeddedPhone; - private final Boolean subscriberOptIn; - private final Boolean ageGated; - private final Boolean directLending; - private final String campaignStatus; - private final String campaignId; + @Getter + private final List helpKeywords; + @Getter + private final String helpMessage; + @Getter private final Boolean isExternallyRegistered; - private final Map rateLimits; + @Getter private final String messageFlow; - private final String optInMessage; - private final String optOutMessage; - private final String helpMessage; + @Getter + private final List messageSamples; + @Getter + private final String messagingServiceSid; + @Getter + private final Boolean mock; + @Getter private final List optInKeywords; + @Getter + private final String optInMessage; + @Getter private final List optOutKeywords; - private final List helpKeywords; - private final ZonedDateTime dateCreated; - private final ZonedDateTime dateUpdated; + @Getter + private final String optOutMessage; + @Getter + private final Object rateLimits; + @Getter + private final String sid; + @Getter + private final Boolean subscriberOptIn; + @Getter private final URI url; - private final Boolean mock; - private final List> errors; + @Getter + private final String usAppToPersonUsecase; @JsonCreator private UsAppToPerson( - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty( - "brand_registration_sid" - ) final String brandRegistrationSid, - @JsonProperty("messaging_service_sid") final String messagingServiceSid, - @JsonProperty("description") final String description, - @JsonProperty("message_samples") final List messageSamples, - @JsonProperty( - "us_app_to_person_usecase" - ) final String usAppToPersonUsecase, - @JsonProperty("has_embedded_links") final Boolean hasEmbeddedLinks, - @JsonProperty("has_embedded_phone") final Boolean hasEmbeddedPhone, - @JsonProperty("subscriber_opt_in") final Boolean subscriberOptIn, - @JsonProperty("age_gated") final Boolean ageGated, - @JsonProperty("direct_lending") final Boolean directLending, - @JsonProperty("campaign_status") final String campaignStatus, - @JsonProperty("campaign_id") final String campaignId, - @JsonProperty( - "is_externally_registered" - ) final Boolean isExternallyRegistered, - @JsonProperty("rate_limits") final Map rateLimits, - @JsonProperty("message_flow") final String messageFlow, - @JsonProperty("opt_in_message") final String optInMessage, - @JsonProperty("opt_out_message") final String optOutMessage, - @JsonProperty("help_message") final String helpMessage, - @JsonProperty("opt_in_keywords") final List optInKeywords, - @JsonProperty("opt_out_keywords") final List optOutKeywords, - @JsonProperty("help_keywords") final List helpKeywords, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("url") final URI url, - @JsonProperty("mock") final Boolean mock, - @JsonProperty("errors") final List> errors + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("age_gated") final Boolean ageGated, + @JsonProperty("brand_registration_sid") final String brandRegistrationSid, + @JsonProperty("campaign_id") final String campaignId, + @JsonProperty("campaign_status") final String campaignStatus, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("description") final String description, + @JsonProperty("direct_lending") final Boolean directLending, + @JsonProperty("errors") final List errors, + @JsonProperty("has_embedded_links") final Boolean hasEmbeddedLinks, + @JsonProperty("has_embedded_phone") final Boolean hasEmbeddedPhone, + @JsonProperty("help_keywords") final List helpKeywords, + @JsonProperty("help_message") final String helpMessage, + @JsonProperty("is_externally_registered") final Boolean isExternallyRegistered, + @JsonProperty("message_flow") final String messageFlow, + @JsonProperty("message_samples") final List messageSamples, + @JsonProperty("messaging_service_sid") final String messagingServiceSid, + @JsonProperty("mock") final Boolean mock, + @JsonProperty("opt_in_keywords") final List optInKeywords, + @JsonProperty("opt_in_message") final String optInMessage, + @JsonProperty("opt_out_keywords") final List optOutKeywords, + @JsonProperty("opt_out_message") final String optOutMessage, + @JsonProperty("rate_limits") final Object rateLimits, + @JsonProperty("sid") final String sid, + @JsonProperty("subscriber_opt_in") final Boolean subscriberOptIn, + @JsonProperty("url") final URI url, + @JsonProperty("us_app_to_person_usecase") final String usAppToPersonUsecase ) { - this.sid = sid; this.accountSid = accountSid; + this.ageGated = ageGated; this.brandRegistrationSid = brandRegistrationSid; - this.messagingServiceSid = messagingServiceSid; + this.campaignId = campaignId; + this.campaignStatus = campaignStatus; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.description = description; - this.messageSamples = messageSamples; - this.usAppToPersonUsecase = usAppToPersonUsecase; + this.directLending = directLending; + this.errors = errors; this.hasEmbeddedLinks = hasEmbeddedLinks; this.hasEmbeddedPhone = hasEmbeddedPhone; - this.subscriberOptIn = subscriberOptIn; - this.ageGated = ageGated; - this.directLending = directLending; - this.campaignStatus = campaignStatus; - this.campaignId = campaignId; + this.helpKeywords = helpKeywords; + this.helpMessage = helpMessage; this.isExternallyRegistered = isExternallyRegistered; - this.rateLimits = rateLimits; this.messageFlow = messageFlow; - this.optInMessage = optInMessage; - this.optOutMessage = optOutMessage; - this.helpMessage = helpMessage; + this.messageSamples = messageSamples; + this.messagingServiceSid = messagingServiceSid; + this.mock = mock; this.optInKeywords = optInKeywords; + this.optInMessage = optInMessage; this.optOutKeywords = optOutKeywords; - this.helpKeywords = helpKeywords; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); + this.optOutMessage = optOutMessage; + this.rateLimits = rateLimits; + this.sid = sid; + this.subscriberOptIn = subscriberOptIn; this.url = url; - this.mock = mock; - this.errors = errors; - } - - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getBrandRegistrationSid() { - return this.brandRegistrationSid; - } - - public final String getMessagingServiceSid() { - return this.messagingServiceSid; - } - - public final String getDescription() { - return this.description; - } - - public final List getMessageSamples() { - return this.messageSamples; - } - - public final String getUsAppToPersonUsecase() { - return this.usAppToPersonUsecase; - } - - public final Boolean getHasEmbeddedLinks() { - return this.hasEmbeddedLinks; - } - - public final Boolean getHasEmbeddedPhone() { - return this.hasEmbeddedPhone; - } - - public final Boolean getSubscriberOptIn() { - return this.subscriberOptIn; - } - - public final Boolean getAgeGated() { - return this.ageGated; - } - - public final Boolean getDirectLending() { - return this.directLending; - } - - public final String getCampaignStatus() { - return this.campaignStatus; - } - - public final String getCampaignId() { - return this.campaignId; - } - - public final Boolean getIsExternallyRegistered() { - return this.isExternallyRegistered; - } - - public final Map getRateLimits() { - return this.rateLimits; - } - - public final String getMessageFlow() { - return this.messageFlow; - } - - public final String getOptInMessage() { - return this.optInMessage; - } - - public final String getOptOutMessage() { - return this.optOutMessage; - } - - public final String getHelpMessage() { - return this.helpMessage; - } - - public final List getOptInKeywords() { - return this.optInKeywords; - } - - public final List getOptOutKeywords() { - return this.optOutKeywords; - } - - public final List getHelpKeywords() { - return this.helpKeywords; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final URI getUrl() { - return this.url; - } - - public final Boolean getMock() { - return this.mock; - } - - public final List> getErrors() { - return this.errors; + this.usAppToPersonUsecase = usAppToPersonUsecase; } @Override @@ -369,73 +256,72 @@ public boolean equals(final Object o) { } UsAppToPerson other = (UsAppToPerson) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(brandRegistrationSid, other.brandRegistrationSid) && - Objects.equals(messagingServiceSid, other.messagingServiceSid) && - Objects.equals(description, other.description) && - Objects.equals(messageSamples, other.messageSamples) && - Objects.equals(usAppToPersonUsecase, other.usAppToPersonUsecase) && - Objects.equals(hasEmbeddedLinks, other.hasEmbeddedLinks) && - Objects.equals(hasEmbeddedPhone, other.hasEmbeddedPhone) && - Objects.equals(subscriberOptIn, other.subscriberOptIn) && - Objects.equals(ageGated, other.ageGated) && - Objects.equals(directLending, other.directLending) && - Objects.equals(campaignStatus, other.campaignStatus) && - Objects.equals(campaignId, other.campaignId) && - Objects.equals( - isExternallyRegistered, - other.isExternallyRegistered - ) && - Objects.equals(rateLimits, other.rateLimits) && - Objects.equals(messageFlow, other.messageFlow) && - Objects.equals(optInMessage, other.optInMessage) && - Objects.equals(optOutMessage, other.optOutMessage) && - Objects.equals(helpMessage, other.helpMessage) && - Objects.equals(optInKeywords, other.optInKeywords) && - Objects.equals(optOutKeywords, other.optOutKeywords) && - Objects.equals(helpKeywords, other.helpKeywords) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(url, other.url) && - Objects.equals(mock, other.mock) && - Objects.equals(errors, other.errors) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(ageGated, other.ageGated) && + Objects.equals(brandRegistrationSid, other.brandRegistrationSid) && + Objects.equals(campaignId, other.campaignId) && + Objects.equals(campaignStatus, other.campaignStatus) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(description, other.description) && + Objects.equals(directLending, other.directLending) && + Objects.equals(errors, other.errors) && + Objects.equals(hasEmbeddedLinks, other.hasEmbeddedLinks) && + Objects.equals(hasEmbeddedPhone, other.hasEmbeddedPhone) && + Objects.equals(helpKeywords, other.helpKeywords) && + Objects.equals(helpMessage, other.helpMessage) && + Objects.equals(isExternallyRegistered, other.isExternallyRegistered) && + Objects.equals(messageFlow, other.messageFlow) && + Objects.equals(messageSamples, other.messageSamples) && + Objects.equals(messagingServiceSid, other.messagingServiceSid) && + Objects.equals(mock, other.mock) && + Objects.equals(optInKeywords, other.optInKeywords) && + Objects.equals(optInMessage, other.optInMessage) && + Objects.equals(optOutKeywords, other.optOutKeywords) && + Objects.equals(optOutMessage, other.optOutMessage) && + Objects.equals(rateLimits, other.rateLimits) && + Objects.equals(sid, other.sid) && + Objects.equals(subscriberOptIn, other.subscriberOptIn) && + Objects.equals(url, other.url) && + Objects.equals(usAppToPersonUsecase, other.usAppToPersonUsecase) ); } @Override public int hashCode() { return Objects.hash( - sid, - accountSid, - brandRegistrationSid, - messagingServiceSid, - description, - messageSamples, - usAppToPersonUsecase, - hasEmbeddedLinks, - hasEmbeddedPhone, - subscriberOptIn, - ageGated, - directLending, - campaignStatus, - campaignId, - isExternallyRegistered, - rateLimits, - messageFlow, - optInMessage, - optOutMessage, - helpMessage, - optInKeywords, - optOutKeywords, - helpKeywords, - dateCreated, - dateUpdated, - url, - mock, - errors + accountSid, + ageGated, + brandRegistrationSid, + campaignId, + campaignStatus, + dateCreated, + dateUpdated, + description, + directLending, + errors, + hasEmbeddedLinks, + hasEmbeddedPhone, + helpKeywords, + helpMessage, + isExternallyRegistered, + messageFlow, + messageSamples, + messagingServiceSid, + mock, + optInKeywords, + optInMessage, + optOutKeywords, + optOutMessage, + rateLimits, + sid, + subscriberOptIn, + url, + usAppToPersonUsecase ); } + + } + diff --git a/src/main/java/com/twilio/rest/messaging/v1/service/UsAppToPersonCreator.java b/src/main/java/com/twilio/rest/messaging/v1/service/UsAppToPersonCreator.java index 487b107a33..80d6d94f98 100644 --- a/src/main/java/com/twilio/rest/messaging/v1/service/UsAppToPersonCreator.java +++ b/src/main/java/com/twilio/rest/messaging/v1/service/UsAppToPersonCreator.java @@ -14,9 +14,12 @@ package com.twilio.rest.messaging.v1.service; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; import com.twilio.converter.Promoter; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,12 +28,12 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -import java.util.List; + import java.util.List; public class UsAppToPersonCreator extends Creator { - private String pathMessagingServiceSid; + private String pathmessagingServiceSid; private String brandRegistrationSid; private String description; private String messageFlow; @@ -48,17 +51,8 @@ public class UsAppToPersonCreator extends Creator { private Boolean ageGated; private Boolean directLending; - public UsAppToPersonCreator( - final String pathMessagingServiceSid, - final String brandRegistrationSid, - final String description, - final String messageFlow, - final List messageSamples, - final String usAppToPersonUsecase, - final Boolean hasEmbeddedLinks, - final Boolean hasEmbeddedPhone - ) { - this.pathMessagingServiceSid = pathMessagingServiceSid; + public UsAppToPersonCreator(final String pathmessagingServiceSid, final String brandRegistrationSid, final String description, final String messageFlow, final List messageSamples, final String usAppToPersonUsecase, final Boolean hasEmbeddedLinks, final Boolean hasEmbeddedPhone) { + this.pathmessagingServiceSid = pathmessagingServiceSid; this.brandRegistrationSid = brandRegistrationSid; this.description = description; this.messageFlow = messageFlow; @@ -68,26 +62,26 @@ public UsAppToPersonCreator( this.hasEmbeddedPhone = hasEmbeddedPhone; } - public UsAppToPersonCreator setBrandRegistrationSid( - final String brandRegistrationSid - ) { + + public UsAppToPersonCreator setBrandRegistrationSid(final String brandRegistrationSid) { this.brandRegistrationSid = brandRegistrationSid; return this; } + public UsAppToPersonCreator setDescription(final String description) { this.description = description; return this; } + public UsAppToPersonCreator setMessageFlow(final String messageFlow) { this.messageFlow = messageFlow; return this; } - public UsAppToPersonCreator setMessageSamples( - final List messageSamples - ) { + + public UsAppToPersonCreator setMessageSamples(final List messageSamples) { this.messageSamples = messageSamples; return this; } @@ -96,45 +90,43 @@ public UsAppToPersonCreator setMessageSamples(final String messageSamples) { return setMessageSamples(Promoter.listOfOne(messageSamples)); } - public UsAppToPersonCreator setUsAppToPersonUsecase( - final String usAppToPersonUsecase - ) { + public UsAppToPersonCreator setUsAppToPersonUsecase(final String usAppToPersonUsecase) { this.usAppToPersonUsecase = usAppToPersonUsecase; return this; } - public UsAppToPersonCreator setHasEmbeddedLinks( - final Boolean hasEmbeddedLinks - ) { + + public UsAppToPersonCreator setHasEmbeddedLinks(final Boolean hasEmbeddedLinks) { this.hasEmbeddedLinks = hasEmbeddedLinks; return this; } - public UsAppToPersonCreator setHasEmbeddedPhone( - final Boolean hasEmbeddedPhone - ) { + + public UsAppToPersonCreator setHasEmbeddedPhone(final Boolean hasEmbeddedPhone) { this.hasEmbeddedPhone = hasEmbeddedPhone; return this; } + public UsAppToPersonCreator setOptInMessage(final String optInMessage) { this.optInMessage = optInMessage; return this; } + public UsAppToPersonCreator setOptOutMessage(final String optOutMessage) { this.optOutMessage = optOutMessage; return this; } + public UsAppToPersonCreator setHelpMessage(final String helpMessage) { this.helpMessage = helpMessage; return this; } - public UsAppToPersonCreator setOptInKeywords( - final List optInKeywords - ) { + + public UsAppToPersonCreator setOptInKeywords(final List optInKeywords) { this.optInKeywords = optInKeywords; return this; } @@ -143,9 +135,7 @@ public UsAppToPersonCreator setOptInKeywords(final String optInKeywords) { return setOptInKeywords(Promoter.listOfOne(optInKeywords)); } - public UsAppToPersonCreator setOptOutKeywords( - final List optOutKeywords - ) { + public UsAppToPersonCreator setOptOutKeywords(final List optOutKeywords) { this.optOutKeywords = optOutKeywords; return this; } @@ -154,9 +144,7 @@ public UsAppToPersonCreator setOptOutKeywords(final String optOutKeywords) { return setOptOutKeywords(Promoter.listOfOne(optOutKeywords)); } - public UsAppToPersonCreator setHelpKeywords( - final List helpKeywords - ) { + public UsAppToPersonCreator setHelpKeywords(final List helpKeywords) { this.helpKeywords = helpKeywords; return this; } @@ -165,162 +153,147 @@ public UsAppToPersonCreator setHelpKeywords(final String helpKeywords) { return setHelpKeywords(Promoter.listOfOne(helpKeywords)); } - public UsAppToPersonCreator setSubscriberOptIn( - final Boolean subscriberOptIn - ) { + public UsAppToPersonCreator setSubscriberOptIn(final Boolean subscriberOptIn) { this.subscriberOptIn = subscriberOptIn; return this; } + public UsAppToPersonCreator setAgeGated(final Boolean ageGated) { this.ageGated = ageGated; return this; } + public UsAppToPersonCreator setDirectLending(final Boolean directLending) { this.directLending = directLending; return this; } + @Override public UsAppToPerson create(final TwilioRestClient client) { + String path = "/v1/Services/{MessagingServiceSid}/Compliance/Usa2p"; - path = - path.replace( - "{" + "MessagingServiceSid" + "}", - this.pathMessagingServiceSid.toString() - ); - path = - path.replace( - "{" + "BrandRegistrationSid" + "}", - this.brandRegistrationSid.toString() - ); - path = - path.replace( - "{" + "Description" + "}", - this.description.toString() - ); - path = - path.replace( - "{" + "MessageFlow" + "}", - this.messageFlow.toString() - ); - path = - path.replace( - "{" + "MessageSamples" + "}", - this.messageSamples.toString() - ); - path = - path.replace( - "{" + "UsAppToPersonUsecase" + "}", - this.usAppToPersonUsecase.toString() - ); - path = - path.replace( - "{" + "HasEmbeddedLinks" + "}", - this.hasEmbeddedLinks.toString() - ); - path = - path.replace( - "{" + "HasEmbeddedPhone" + "}", - this.hasEmbeddedPhone.toString() - ); + path = path.replace("{" + "MessagingServiceSid" + "}", this.pathmessagingServiceSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.MESSAGING.toString(), - path + HttpMethod.POST, + Domains.MESSAGING.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "UsAppToPerson creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("UsAppToPerson creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return UsAppToPerson.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return UsAppToPerson.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (brandRegistrationSid != null) { - request.addPostParam("BrandRegistrationSid", brandRegistrationSid); + Serializer.toString(request, "BrandRegistrationSid", brandRegistrationSid, ParameterType.URLENCODED); } + + if (description != null) { - request.addPostParam("Description", description); + Serializer.toString(request, "Description", description, ParameterType.URLENCODED); } + + if (messageFlow != null) { - request.addPostParam("MessageFlow", messageFlow); + Serializer.toString(request, "MessageFlow", messageFlow, ParameterType.URLENCODED); } + + if (messageSamples != null) { - for (String prop : messageSamples) { - request.addPostParam("MessageSamples", prop); + for (String param : messageSamples) { + Serializer.toString(request, "MessageSamples", param, ParameterType.URLENCODED); } } + + if (usAppToPersonUsecase != null) { - request.addPostParam("UsAppToPersonUsecase", usAppToPersonUsecase); + Serializer.toString(request, "UsAppToPersonUsecase", usAppToPersonUsecase, ParameterType.URLENCODED); } + + if (hasEmbeddedLinks != null) { - request.addPostParam( - "HasEmbeddedLinks", - hasEmbeddedLinks.toString() - ); + Serializer.toString(request, "HasEmbeddedLinks", hasEmbeddedLinks, ParameterType.URLENCODED); } + + if (hasEmbeddedPhone != null) { - request.addPostParam( - "HasEmbeddedPhone", - hasEmbeddedPhone.toString() - ); + Serializer.toString(request, "HasEmbeddedPhone", hasEmbeddedPhone, ParameterType.URLENCODED); } + + if (optInMessage != null) { - request.addPostParam("OptInMessage", optInMessage); + Serializer.toString(request, "OptInMessage", optInMessage, ParameterType.URLENCODED); } + + if (optOutMessage != null) { - request.addPostParam("OptOutMessage", optOutMessage); + Serializer.toString(request, "OptOutMessage", optOutMessage, ParameterType.URLENCODED); } + + if (helpMessage != null) { - request.addPostParam("HelpMessage", helpMessage); + Serializer.toString(request, "HelpMessage", helpMessage, ParameterType.URLENCODED); } + + if (optInKeywords != null) { - for (String prop : optInKeywords) { - request.addPostParam("OptInKeywords", prop); + for (String param : optInKeywords) { + Serializer.toString(request, "OptInKeywords", param, ParameterType.URLENCODED); } } + + if (optOutKeywords != null) { - for (String prop : optOutKeywords) { - request.addPostParam("OptOutKeywords", prop); + for (String param : optOutKeywords) { + Serializer.toString(request, "OptOutKeywords", param, ParameterType.URLENCODED); } } + + if (helpKeywords != null) { - for (String prop : helpKeywords) { - request.addPostParam("HelpKeywords", prop); + for (String param : helpKeywords) { + Serializer.toString(request, "HelpKeywords", param, ParameterType.URLENCODED); } } + + if (subscriberOptIn != null) { - request.addPostParam("SubscriberOptIn", subscriberOptIn.toString()); + Serializer.toString(request, "SubscriberOptIn", subscriberOptIn, ParameterType.URLENCODED); } + + if (ageGated != null) { - request.addPostParam("AgeGated", ageGated.toString()); + Serializer.toString(request, "AgeGated", ageGated, ParameterType.URLENCODED); } + + if (directLending != null) { - request.addPostParam("DirectLending", directLending.toString()); + Serializer.toString(request, "DirectLending", directLending, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/messaging/v1/service/UsAppToPersonDeleter.java b/src/main/java/com/twilio/rest/messaging/v1/service/UsAppToPersonDeleter.java index f1a91ef543..84cc933497 100644 --- a/src/main/java/com/twilio/rest/messaging/v1/service/UsAppToPersonDeleter.java +++ b/src/main/java/com/twilio/rest/messaging/v1/service/UsAppToPersonDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.messaging.v1.service; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,51 +26,41 @@ public class UsAppToPersonDeleter extends Deleter { - private String pathMessagingServiceSid; - private String pathSid; + private String pathmessagingServiceSid; + private String pathsid; - public UsAppToPersonDeleter( - final String pathMessagingServiceSid, - final String pathSid - ) { - this.pathMessagingServiceSid = pathMessagingServiceSid; - this.pathSid = pathSid; + public UsAppToPersonDeleter(final String pathmessagingServiceSid, final String pathsid) { + this.pathmessagingServiceSid = pathmessagingServiceSid; + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { - String path = - "/v1/Services/{MessagingServiceSid}/Compliance/Usa2p/{Sid}"; - path = - path.replace( - "{" + "MessagingServiceSid" + "}", - this.pathMessagingServiceSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/v1/Services/{MessagingServiceSid}/Compliance/Usa2p/{Sid}"; + + path = path.replace("{" + "MessagingServiceSid" + "}", this.pathmessagingServiceSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.MESSAGING.toString(), - path + HttpMethod.DELETE, + Domains.MESSAGING.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "UsAppToPerson delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("UsAppToPerson delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/messaging/v1/service/UsAppToPersonFetcher.java b/src/main/java/com/twilio/rest/messaging/v1/service/UsAppToPersonFetcher.java index d69404db17..1caf2c41c2 100644 --- a/src/main/java/com/twilio/rest/messaging/v1/service/UsAppToPersonFetcher.java +++ b/src/main/java/com/twilio/rest/messaging/v1/service/UsAppToPersonFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.messaging.v1.service; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,58 +26,44 @@ public class UsAppToPersonFetcher extends Fetcher { - private String pathMessagingServiceSid; - private String pathSid; + private String pathmessagingServiceSid; + private String pathsid; - public UsAppToPersonFetcher( - final String pathMessagingServiceSid, - final String pathSid - ) { - this.pathMessagingServiceSid = pathMessagingServiceSid; - this.pathSid = pathSid; + public UsAppToPersonFetcher(final String pathmessagingServiceSid, final String pathsid) { + this.pathmessagingServiceSid = pathmessagingServiceSid; + this.pathsid = pathsid; } + @Override public UsAppToPerson fetch(final TwilioRestClient client) { - String path = - "/v1/Services/{MessagingServiceSid}/Compliance/Usa2p/{Sid}"; - path = - path.replace( - "{" + "MessagingServiceSid" + "}", - this.pathMessagingServiceSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/v1/Services/{MessagingServiceSid}/Compliance/Usa2p/{Sid}"; + + path = path.replace("{" + "MessagingServiceSid" + "}", this.pathmessagingServiceSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.MESSAGING.toString(), - path + HttpMethod.GET, + Domains.MESSAGING.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "UsAppToPerson fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("UsAppToPerson fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return UsAppToPerson.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return UsAppToPerson.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/messaging/v1/service/UsAppToPersonReader.java b/src/main/java/com/twilio/rest/messaging/v1/service/UsAppToPersonReader.java index 98c0dddad2..6bce6289f5 100644 --- a/src/main/java/com/twilio/rest/messaging/v1/service/UsAppToPersonReader.java +++ b/src/main/java/com/twilio/rest/messaging/v1/service/UsAppToPersonReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,115 +30,88 @@ public class UsAppToPersonReader extends Reader { - private String pathMessagingServiceSid; + private String pathmessagingServiceSid; private Long pageSize; - public UsAppToPersonReader(final String pathMessagingServiceSid) { - this.pathMessagingServiceSid = pathMessagingServiceSid; + public UsAppToPersonReader(final String pathmessagingServiceSid) { + this.pathmessagingServiceSid = pathmessagingServiceSid; } + public UsAppToPersonReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/Services/{MessagingServiceSid}/Compliance/Usa2p"; - path = - path.replace( - "{" + "MessagingServiceSid" + "}", - this.pathMessagingServiceSid.toString() - ); + + path = path.replace("{" + "MessagingServiceSid" + "}", this.pathmessagingServiceSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.MESSAGING.toString(), - path + HttpMethod.GET, + Domains.MESSAGING.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "UsAppToPerson read failed: Unable to connect to server" - ); + throw new ApiConnectionException("UsAppToPerson read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "compliance", - response.getContent(), - UsAppToPerson.class, - client.getObjectMapper() - ); + "compliance", + response.getContent(), + UsAppToPerson.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.MESSAGING.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.MESSAGING.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/messaging/v1/service/UsAppToPersonUpdater.java b/src/main/java/com/twilio/rest/messaging/v1/service/UsAppToPersonUpdater.java index 60de932a12..12236c484c 100644 --- a/src/main/java/com/twilio/rest/messaging/v1/service/UsAppToPersonUpdater.java +++ b/src/main/java/com/twilio/rest/messaging/v1/service/UsAppToPersonUpdater.java @@ -16,7 +16,9 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; import com.twilio.converter.Promoter; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,12 +27,12 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.util.List; public class UsAppToPersonUpdater extends Updater { - - private String pathMessagingServiceSid; - private String pathSid; + private String pathmessagingServiceSid; + private String pathsid; private Boolean hasEmbeddedLinks; private Boolean hasEmbeddedPhone; private List messageSamples; @@ -39,19 +41,9 @@ public class UsAppToPersonUpdater extends Updater { private Boolean ageGated; private Boolean directLending; - public UsAppToPersonUpdater( - final String pathMessagingServiceSid, - final String pathSid, - final Boolean hasEmbeddedLinks, - final Boolean hasEmbeddedPhone, - final List messageSamples, - final String messageFlow, - final String description, - final Boolean ageGated, - final Boolean directLending - ) { - this.pathMessagingServiceSid = pathMessagingServiceSid; - this.pathSid = pathSid; + public UsAppToPersonUpdater(final String pathmessagingServiceSid, final String pathsid, final Boolean hasEmbeddedLinks, final Boolean hasEmbeddedPhone, final List messageSamples, final String messageFlow, final String description, final Boolean ageGated, final Boolean directLending) { + this.pathmessagingServiceSid = pathmessagingServiceSid; + this.pathsid = pathsid; this.hasEmbeddedLinks = hasEmbeddedLinks; this.hasEmbeddedPhone = hasEmbeddedPhone; this.messageSamples = messageSamples; @@ -61,23 +53,20 @@ public UsAppToPersonUpdater( this.directLending = directLending; } - public UsAppToPersonUpdater setHasEmbeddedLinks( - final Boolean hasEmbeddedLinks - ) { + + public UsAppToPersonUpdater setHasEmbeddedLinks(final Boolean hasEmbeddedLinks) { this.hasEmbeddedLinks = hasEmbeddedLinks; return this; } - public UsAppToPersonUpdater setHasEmbeddedPhone( - final Boolean hasEmbeddedPhone - ) { + + public UsAppToPersonUpdater setHasEmbeddedPhone(final Boolean hasEmbeddedPhone) { this.hasEmbeddedPhone = hasEmbeddedPhone; return this; } - public UsAppToPersonUpdater setMessageSamples( - final List messageSamples - ) { + + public UsAppToPersonUpdater setMessageSamples(final List messageSamples) { this.messageSamples = messageSamples; return this; } @@ -91,125 +80,98 @@ public UsAppToPersonUpdater setMessageFlow(final String messageFlow) { return this; } + public UsAppToPersonUpdater setDescription(final String description) { this.description = description; return this; } + public UsAppToPersonUpdater setAgeGated(final Boolean ageGated) { this.ageGated = ageGated; return this; } + public UsAppToPersonUpdater setDirectLending(final Boolean directLending) { this.directLending = directLending; return this; } + @Override public UsAppToPerson update(final TwilioRestClient client) { - String path = - "/v1/Services/{MessagingServiceSid}/Compliance/Usa2p/{Sid}"; - path = - path.replace( - "{" + "MessagingServiceSid" + "}", - this.pathMessagingServiceSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); - path = - path.replace( - "{" + "HasEmbeddedLinks" + "}", - this.hasEmbeddedLinks.toString() - ); - path = - path.replace( - "{" + "HasEmbeddedPhone" + "}", - this.hasEmbeddedPhone.toString() - ); - path = - path.replace( - "{" + "MessageSamples" + "}", - this.messageSamples.toString() - ); - path = - path.replace( - "{" + "MessageFlow" + "}", - this.messageFlow.toString() - ); - path = - path.replace( - "{" + "Description" + "}", - this.description.toString() - ); - path = path.replace("{" + "AgeGated" + "}", this.ageGated.toString()); - path = - path.replace( - "{" + "DirectLending" + "}", - this.directLending.toString() - ); + String path = "/v1/Services/{MessagingServiceSid}/Compliance/Usa2p/{Sid}"; + + path = path.replace("{" + "MessagingServiceSid" + "}", this.pathmessagingServiceSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.MESSAGING.toString(), - path + HttpMethod.POST, + Domains.MESSAGING.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "UsAppToPerson update failed: Unable to connect to server" - ); + throw new ApiConnectionException("UsAppToPerson update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return UsAppToPerson.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return UsAppToPerson.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (hasEmbeddedLinks != null) { - request.addPostParam( - "HasEmbeddedLinks", - hasEmbeddedLinks.toString() - ); + Serializer.toString(request, "HasEmbeddedLinks", hasEmbeddedLinks, ParameterType.URLENCODED); } + + if (hasEmbeddedPhone != null) { - request.addPostParam( - "HasEmbeddedPhone", - hasEmbeddedPhone.toString() - ); + Serializer.toString(request, "HasEmbeddedPhone", hasEmbeddedPhone, ParameterType.URLENCODED); } + + if (messageSamples != null) { - for (String prop : messageSamples) { - request.addPostParam("MessageSamples", prop); + for (String param : messageSamples) { + Serializer.toString(request, "MessageSamples", param, ParameterType.URLENCODED); } } + + if (messageFlow != null) { - request.addPostParam("MessageFlow", messageFlow); + Serializer.toString(request, "MessageFlow", messageFlow, ParameterType.URLENCODED); } + + if (description != null) { - request.addPostParam("Description", description); + Serializer.toString(request, "Description", description, ParameterType.URLENCODED); } + + if (ageGated != null) { - request.addPostParam("AgeGated", ageGated.toString()); + Serializer.toString(request, "AgeGated", ageGated, ParameterType.URLENCODED); } + + if (directLending != null) { - request.addPostParam("DirectLending", directLending.toString()); + Serializer.toString(request, "DirectLending", directLending, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/messaging/v1/service/UsAppToPersonUsecase.java b/src/main/java/com/twilio/rest/messaging/v1/service/UsAppToPersonUsecase.java index 19d433f3be..56cdcbd4c1 100644 --- a/src/main/java/com/twilio/rest/messaging/v1/service/UsAppToPersonUsecase.java +++ b/src/main/java/com/twilio/rest/messaging/v1/service/UsAppToPersonUsecase.java @@ -18,43 +18,40 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.util.List; -import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class UsAppToPersonUsecase extends Resource { - private static final long serialVersionUID = 181251380697241L; - public static UsAppToPersonUsecaseFetcher fetcher( - final String pathMessagingServiceSid - ) { - return new UsAppToPersonUsecaseFetcher(pathMessagingServiceSid); + public static UsAppToPersonUsecaseFetcher fetcher(final String pathmessagingServiceSid) { + return new UsAppToPersonUsecaseFetcher( + pathmessagingServiceSid + ); } + /** * Converts a JSON String into a UsAppToPersonUsecase object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return UsAppToPersonUsecase object represented by the provided JSON */ - public static UsAppToPersonUsecase fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static UsAppToPersonUsecase fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, UsAppToPersonUsecase.class); @@ -69,14 +66,11 @@ public static UsAppToPersonUsecase fromJson( * Converts a JSON InputStream into a UsAppToPersonUsecase object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return UsAppToPersonUsecase object represented by the provided JSON */ - public static UsAppToPersonUsecase fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static UsAppToPersonUsecase fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, UsAppToPersonUsecase.class); @@ -87,21 +81,29 @@ public static UsAppToPersonUsecase fromJson( } } - private final List> usAppToPersonUsecases; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter + private final List usAppToPersonUsecases; @JsonCreator private UsAppToPersonUsecase( - @JsonProperty("us_app_to_person_usecases") final List< - Map - > usAppToPersonUsecases + @JsonProperty("us_app_to_person_usecases") final List usAppToPersonUsecases ) { this.usAppToPersonUsecases = usAppToPersonUsecases; } - public final List> getUsAppToPersonUsecases() { - return this.usAppToPersonUsecases; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -113,15 +115,18 @@ public boolean equals(final Object o) { } UsAppToPersonUsecase other = (UsAppToPersonUsecase) o; - - return Objects.equals( - usAppToPersonUsecases, - other.usAppToPersonUsecases + return ( + Objects.equals(usAppToPersonUsecases, other.usAppToPersonUsecases) ); } @Override public int hashCode() { - return Objects.hash(usAppToPersonUsecases); + return Objects.hash( + usAppToPersonUsecases + ); } + + } + diff --git a/src/main/java/com/twilio/rest/messaging/v1/service/UsAppToPersonUsecaseFetcher.java b/src/main/java/com/twilio/rest/messaging/v1/service/UsAppToPersonUsecaseFetcher.java index 7e68d3f101..82e91a69f2 100644 --- a/src/main/java/com/twilio/rest/messaging/v1/service/UsAppToPersonUsecaseFetcher.java +++ b/src/main/java/com/twilio/rest/messaging/v1/service/UsAppToPersonUsecaseFetcher.java @@ -15,7 +15,8 @@ package com.twilio.rest.messaging.v1.service; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,67 +28,59 @@ public class UsAppToPersonUsecaseFetcher extends Fetcher { - private String pathMessagingServiceSid; + private String pathmessagingServiceSid; private String brandRegistrationSid; - public UsAppToPersonUsecaseFetcher(final String pathMessagingServiceSid) { - this.pathMessagingServiceSid = pathMessagingServiceSid; + public UsAppToPersonUsecaseFetcher(final String pathmessagingServiceSid) { + this.pathmessagingServiceSid = pathmessagingServiceSid; } - public UsAppToPersonUsecaseFetcher setBrandRegistrationSid( - final String brandRegistrationSid - ) { + + public UsAppToPersonUsecaseFetcher setBrandRegistrationSid(final String brandRegistrationSid) { this.brandRegistrationSid = brandRegistrationSid; return this; } + @Override public UsAppToPersonUsecase fetch(final TwilioRestClient client) { - String path = - "/v1/Services/{MessagingServiceSid}/Compliance/Usa2p/Usecases"; - path = - path.replace( - "{" + "MessagingServiceSid" + "}", - this.pathMessagingServiceSid.toString() - ); + String path = "/v1/Services/{MessagingServiceSid}/Compliance/Usa2p/Usecases"; + + path = path.replace("{" + "MessagingServiceSid" + "}", this.pathmessagingServiceSid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.MESSAGING.toString(), - path + HttpMethod.GET, + Domains.MESSAGING.toString(), + path ); addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "UsAppToPersonUsecase fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("UsAppToPersonUsecase fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return UsAppToPersonUsecase.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return UsAppToPersonUsecase.fromJson(response.getStream(), client.getObjectMapper()); } private void addQueryParams(final Request request) { + + if (brandRegistrationSid != null) { - request.addQueryParam("BrandRegistrationSid", brandRegistrationSid); + Serializer.toString(request, "BrandRegistrationSid", brandRegistrationSid, ParameterType.QUERY); } + + } } diff --git a/src/main/java/com/twilio/rest/messaging/v2/ChannelsSender.java b/src/main/java/com/twilio/rest/messaging/v2/ChannelsSender.java index 457b66eaf8..bd15a6b9c0 100644 --- a/src/main/java/com/twilio/rest/messaging/v2/ChannelsSender.java +++ b/src/main/java/com/twilio/rest/messaging/v2/ChannelsSender.java @@ -26,110 +26,192 @@ import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.util.List; import java.util.Objects; -import lombok.Getter; -import lombok.Setter; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class ChannelsSender extends Resource { - private static final long serialVersionUID = 140943943425747L; - @ToString - public static class MessagingV2ChannelsSenderConfiguration { + public static ChannelsSenderCreator creator(final ChannelsSender.MessagingV2ChannelsSenderRequestsCreate messagingV2ChannelsSenderRequestsCreate) { + return new ChannelsSenderCreator( + messagingV2ChannelsSenderRequestsCreate + ); + } - @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("waba_id") - @Getter - @Setter - private String wabaId; - @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("verification_method") - @Getter - @Setter - private VerificationMethodEnum verificationMethod; + public static ChannelsSenderDeleter deleter(final String pathsid) { + return new ChannelsSenderDeleter( + pathsid + ); + } - @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("verification_code") - @Getter - @Setter - private String verificationCode; - @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("voice_application_sid") - @Getter - @Setter - private String voiceApplicationSid; + public static ChannelsSenderFetcher fetcher(final String pathsid) { + return new ChannelsSenderFetcher( + pathsid + ); + } + + + public static ChannelsSenderReader reader(final String channel) { + return new ChannelsSenderReader( + channel + ); + } + + + public static ChannelsSenderUpdater updater(final String pathsid) { + return new ChannelsSenderUpdater( + pathsid + ); + } + + + public enum Status { + CREATING("CREATING"), + ONLINE("ONLINE"), + OFFLINE("OFFLINE"), + PENDING_VERIFICATION("PENDING_VERIFICATION"), + VERIFYING("VERIFYING"), + ONLINE_UPDATING("ONLINE:UPDATING"), + TWILIO_REVIEW("TWILIO_REVIEW"), + DRAFT("DRAFT"), + STUBBED("STUBBED"); + + private final String value; + + private Status(final String value) { + this.value = value; + } + + public String toString() { + return value; + } - public static MessagingV2ChannelsSenderConfiguration fromJson( - String jsonString, - ObjectMapper mapper - ) throws IOException { - return mapper.readValue( - jsonString, - MessagingV2ChannelsSenderConfiguration.class - ); + @JsonCreator + public static Status forValue(final String value) { + return Promoter.enumFromString(value, Status.values()); } } - @ToString - public static class MessagingV2ChannelsSenderWebhook { + public enum CallbackMethod { + POST("POST"), + PUT("PUT"); - @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("callback_url") - @Getter - @Setter - private String callbackUrl; + private final String value; - @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("callback_method") - @Getter - @Setter - private CallbackMethodEnum callbackMethod; + private CallbackMethod(final String value) { + this.value = value; + } - @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("fallback_url") - @Getter - @Setter - private String fallbackUrl; + public String toString() { + return value; + } - @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("fallback_method") - @Getter - @Setter - private FallbackMethodEnum fallbackMethod; + @JsonCreator + public static CallbackMethod forValue(final String value) { + return Promoter.enumFromString(value, CallbackMethod.values()); + } + } - @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("status_callback_url") - @Getter - @Setter - private String statusCallbackUrl; + public enum MessagingVRcsCountryStatus { + ONLINE("ONLINE"), + OFFLINE("OFFLINE"), + TWILIO_REVIEW("TWILIO_REVIEW"), + PENDING_VERIFICATION("PENDING_VERIFICATION"); - @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("status_callback_method") - @Getter - @Setter - private String statusCallbackMethod; + private final String value; + + private MessagingVRcsCountryStatus(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static MessagingVRcsCountryStatus forValue(final String value) { + return Promoter.enumFromString(value, MessagingVRcsCountryStatus.values()); + } + } + + public enum VerificationMethod { + SMS("sms"), + VOICE("voice"); - public static MessagingV2ChannelsSenderWebhook fromJson( - String jsonString, - ObjectMapper mapper - ) throws IOException { - return mapper.readValue( - jsonString, - MessagingV2ChannelsSenderWebhook.class - ); + private final String value; + + private VerificationMethod(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static VerificationMethod forValue(final String value) { + return Promoter.enumFromString(value, VerificationMethod.values()); + } + } + + public enum MessagingVRcsCarrierStatus { + UNKNOWN("UNKNOWN"), + UNLAUNCHED("UNLAUNCHED"), + CARRIER_REVIEW("CARRIER_REVIEW"), + APPROVED("APPROVED"), + REJECTED("REJECTED"), + SUSPENDED("SUSPENDED"); + + private final String value; + + private MessagingVRcsCarrierStatus(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static MessagingVRcsCarrierStatus forValue(final String value) { + return Promoter.enumFromString(value, MessagingVRcsCarrierStatus.values()); + } + } + + public enum FallbackMethod { + POST("POST"), + PUT("PUT"); + + private final String value; + + private FallbackMethod(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static FallbackMethod forValue(final String value) { + return Promoter.enumFromString(value, FallbackMethod.values()); } } + + //@JsonDeserialize(builder = MessagingV2ChannelsSenderProfile.Builder.class) + @JsonInclude(JsonInclude.Include.NON_EMPTY) @ToString public static class MessagingV2ChannelsSenderProfile { @@ -211,61 +293,82 @@ public static class MessagingV2ChannelsSenderProfile { @Setter private Object phoneNumbers; - public static MessagingV2ChannelsSenderProfile fromJson( - String jsonString, - ObjectMapper mapper - ) throws IOException { - return mapper.readValue( - jsonString, - MessagingV2ChannelsSenderProfile.class - ); - } } + //@JsonDeserialize(builder = MessagingV2ChannelsSenderProfileGenericResponseWebsitesInner.Builder.class) + @JsonInclude(JsonInclude.Include.NON_EMPTY) @ToString - public static class MessagingV2ChannelsSenderRequestsCreate { + public static class MessagingV2ChannelsSenderProfileGenericResponseWebsitesInner { @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("sender_id") + @JsonProperty("website") @Getter @Setter - private String senderId; + private String website; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("configuration") + @JsonProperty("label") @Getter @Setter - private MessagingV2ChannelsSenderConfiguration configuration; + private String label; + + } + + //@JsonDeserialize(builder = MessagingV2RcsComplianceResponse.Builder.class) + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @ToString + public static class MessagingV2RcsComplianceResponse { + public MessagingV2RcsComplianceResponse(final String registrationSid, final List countries) { + this.registrationSid = registrationSid; + this.countries = countries; + } @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("webhook") + @JsonProperty("registration_sid") @Getter @Setter - private MessagingV2ChannelsSenderWebhook webhook; + private String registrationSid; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("profile") + @JsonProperty("countries") @Getter @Setter - private MessagingV2ChannelsSenderProfile profile; + private List countries; - public MessagingV2ChannelsSenderRequestsCreate(final String senderId) { - this.senderId = senderId; - } + } + + //@JsonDeserialize(builder = MessagingV2RcsCarrier.Builder.class) + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @ToString + public static class MessagingV2RcsCarrier { + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("name") + @Getter + @Setter + private String name; + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("status") + @Getter + @Setter + private ChannelsSender.MessagingVRcsCarrierStatus status; - public static MessagingV2ChannelsSenderRequestsCreate fromJson( - String jsonString, - ObjectMapper mapper - ) throws IOException { - return mapper.readValue( - jsonString, - MessagingV2ChannelsSenderRequestsCreate.class - ); - } } + //@JsonDeserialize(builder = MessagingV2ChannelsSenderRequestsCreate.Builder.class) + @JsonInclude(JsonInclude.Include.NON_EMPTY) @ToString - public static class MessagingV2ChannelsSenderRequestsUpdate { + public static class MessagingV2ChannelsSenderRequestsCreate { + public MessagingV2ChannelsSenderRequestsCreate(final String senderId) { + this.senderId = senderId; + } + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("sender_id") + @Getter + @Setter + private String senderId; @JsonInclude(JsonInclude.Include.NON_EMPTY) @JsonProperty("configuration") @@ -285,27 +388,18 @@ public static class MessagingV2ChannelsSenderRequestsUpdate { @Setter private MessagingV2ChannelsSenderProfile profile; - public MessagingV2ChannelsSenderRequestsUpdate() {} - - public static MessagingV2ChannelsSenderRequestsUpdate fromJson( - String jsonString, - ObjectMapper mapper - ) throws IOException { - return mapper.readValue( - jsonString, - MessagingV2ChannelsSenderRequestsUpdate.class - ); - } } + //@JsonDeserialize(builder = MessagingV2ChannelsSenderProfileGenericResponsePhoneNumbersInner.Builder.class) + @JsonInclude(JsonInclude.Include.NON_EMPTY) @ToString - public static class MessagingV2ChannelsSenderProfileGenericResponseWebsites { + public static class MessagingV2ChannelsSenderProfileGenericResponsePhoneNumbersInner { @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("website") + @JsonProperty("phone_number") @Getter @Setter - private String website; + private String phoneNumber; @JsonInclude(JsonInclude.Include.NON_EMPTY) @JsonProperty("label") @@ -313,347 +407,299 @@ public static class MessagingV2ChannelsSenderProfileGenericResponseWebsites { @Setter private String label; - public static MessagingV2ChannelsSenderProfileGenericResponseWebsites fromJson( - String jsonString, - ObjectMapper mapper - ) throws IOException { - return mapper.readValue( - jsonString, - MessagingV2ChannelsSenderProfileGenericResponseWebsites.class - ); - } } + //@JsonDeserialize(builder = MessagingV2ChannelsSenderProperties.Builder.class) + @JsonInclude(JsonInclude.Include.NON_EMPTY) @ToString - public static class MessagingV2ChannelsSenderProfileGenericResponseEmails { + public static class MessagingV2ChannelsSenderProperties { @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("email") + @JsonProperty("quality_rating") @Getter @Setter - private String email; + private String qualityRating; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("label") + @JsonProperty("messaging_limit") @Getter @Setter - private String label; + private String messagingLimit; - public static MessagingV2ChannelsSenderProfileGenericResponseEmails fromJson( - String jsonString, - ObjectMapper mapper - ) throws IOException { - return mapper.readValue( - jsonString, - MessagingV2ChannelsSenderProfileGenericResponseEmails.class - ); - } } + //@JsonDeserialize(builder = MessagingV2ChannelsSenderOfflineReasonsItems.Builder.class) + @JsonInclude(JsonInclude.Include.NON_EMPTY) @ToString - public static class MessagingV2ChannelsSenderProfileGenericResponsePhoneNumbers { + public static class MessagingV2ChannelsSenderOfflineReasonsItems { @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("phone_number") + @JsonProperty("code") @Getter @Setter - private String phoneNumber; + private String code; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("label") + @JsonProperty("message") @Getter @Setter - private String label; + private String message; + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("more_info") + @Getter + @Setter + private URI moreInfo; - public static MessagingV2ChannelsSenderProfileGenericResponsePhoneNumbers fromJson( - String jsonString, - ObjectMapper mapper - ) throws IOException { - return mapper.readValue( - jsonString, - MessagingV2ChannelsSenderProfileGenericResponsePhoneNumbers.class - ); - } } + //@JsonDeserialize(builder = MessagingV2ChannelsSenderProfileGenericResponseEmailsInner.Builder.class) + @JsonInclude(JsonInclude.Include.NON_EMPTY) @ToString - public static class MessagingV2ChannelsSenderProfileGenericResponse { + public static class MessagingV2ChannelsSenderProfileGenericResponseEmailsInner { @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("name") + @JsonProperty("email") @Getter @Setter - private String name; + private String email; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("about") + @JsonProperty("label") @Getter @Setter - private String about; + private String label; + + } + + //@JsonDeserialize(builder = MessagingV2ChannelsSenderRequestsUpdate.Builder.class) + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @ToString + public static class MessagingV2ChannelsSenderRequestsUpdate { @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("address") + @JsonProperty("configuration") @Getter @Setter - private String address; + private MessagingV2ChannelsSenderConfiguration configuration; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("description") + @JsonProperty("webhook") @Getter @Setter - private String description; + private MessagingV2ChannelsSenderWebhook webhook; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("logo_url") + @JsonProperty("profile") @Getter @Setter - private String logoUrl; + private MessagingV2ChannelsSenderProfile profile; + + } + + //@JsonDeserialize(builder = MessagingV2RcsComplianceCountryResponse.Builder.class) + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @ToString + public static class MessagingV2RcsComplianceCountryResponse { + public MessagingV2RcsComplianceCountryResponse(final String country, final String registrationSid, final ChannelsSender.MessagingVRcsCountryStatus status) { + this.country = country; + this.registrationSid = registrationSid; + this.status = status; + } @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("banner_url") + @JsonProperty("country") @Getter @Setter - private String bannerUrl; + private String country; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("privacy_url") + @JsonProperty("registration_sid") @Getter @Setter - private String privacyUrl; + private String registrationSid; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("terms_of_service_url") + @JsonProperty("status") @Getter @Setter - private String termsOfServiceUrl; + private ChannelsSender.MessagingVRcsCountryStatus status; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("accent_color") + @JsonProperty("carriers") @Getter @Setter - private String accentColor; + private List carriers; + + } + + //@JsonDeserialize(builder = MessagingV2ChannelsSenderWebhook.Builder.class) + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @ToString + public static class MessagingV2ChannelsSenderWebhook { @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("vertical") + @JsonProperty("callback_url") @Getter @Setter - private String vertical; + private String callbackUrl; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("websites") + @JsonProperty("callback_method") @Getter @Setter - private List< - MessagingV2ChannelsSenderProfileGenericResponseWebsites - > websites; + private ChannelsSender.CallbackMethod callbackMethod; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("emails") + @JsonProperty("fallback_url") @Getter @Setter - private List< - MessagingV2ChannelsSenderProfileGenericResponseEmails - > emails; + private String fallbackUrl; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("phone_numbers") + @JsonProperty("fallback_method") @Getter @Setter - private List< - MessagingV2ChannelsSenderProfileGenericResponsePhoneNumbers - > phoneNumbers; - - public static MessagingV2ChannelsSenderProfileGenericResponse fromJson( - String jsonString, - ObjectMapper mapper - ) throws IOException { - return mapper.readValue( - jsonString, - MessagingV2ChannelsSenderProfileGenericResponse.class - ); - } - } - - @ToString - public static class MessagingV2ChannelsSenderProperties { + private ChannelsSender.FallbackMethod fallbackMethod; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("quality_rating") + @JsonProperty("status_callback_url") @Getter @Setter - private String qualityRating; + private String statusCallbackUrl; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("messaging_limit") + @JsonProperty("status_callback_method") @Getter @Setter - private String messagingLimit; + private String statusCallbackMethod; - public static MessagingV2ChannelsSenderProperties fromJson( - String jsonString, - ObjectMapper mapper - ) throws IOException { - return mapper.readValue( - jsonString, - MessagingV2ChannelsSenderProperties.class - ); - } } + //@JsonDeserialize(builder = MessagingV2ChannelsSenderProfileGenericResponse.Builder.class) + @JsonInclude(JsonInclude.Include.NON_EMPTY) @ToString - public static class MessagingV2ChannelsSenderOfflineReasonsItems { + public static class MessagingV2ChannelsSenderProfileGenericResponse { @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("code") + @JsonProperty("name") @Getter @Setter - private String code; + private String name; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("message") + @JsonProperty("about") @Getter @Setter - private String message; + private String about; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("more_info") + @JsonProperty("address") @Getter @Setter - private URI moreInfo; + private String address; - public static MessagingV2ChannelsSenderOfflineReasonsItems fromJson( - String jsonString, - ObjectMapper mapper - ) throws IOException { - return mapper.readValue( - jsonString, - MessagingV2ChannelsSenderOfflineReasonsItems.class - ); - } - } + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("description") + @Getter + @Setter + private String description; - @ToString - public static class MessagingV2RcsCarrier { + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("logo_url") + @Getter + @Setter + private String logoUrl; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("name") + @JsonProperty("banner_url") @Getter @Setter - private String name; + private String bannerUrl; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("status") + @JsonProperty("privacy_url") @Getter @Setter - private MessagingV2RcsCarrierStatus status; + private String privacyUrl; - public static MessagingV2RcsCarrier fromJson( - String jsonString, - ObjectMapper mapper - ) throws IOException { - return mapper.readValue(jsonString, MessagingV2RcsCarrier.class); - } - } + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("terms_of_service_url") + @Getter + @Setter + private String termsOfServiceUrl; - @ToString - public static class MessagingV2RcsComplianceCountryResponse { + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("accent_color") + @Getter + @Setter + private String accentColor; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("country") + @JsonProperty("vertical") @Getter @Setter - private String country; + private String vertical; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("registration_sid") + @JsonProperty("websites") @Getter @Setter - private String registrationSid; + private List websites; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("status") + @JsonProperty("emails") @Getter @Setter - private MessagingV2RcsCountryStatus status; + private List emails; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("carriers") + @JsonProperty("phone_numbers") @Getter @Setter - private List carriers; + private List phoneNumbers; - public static MessagingV2RcsComplianceCountryResponse fromJson( - String jsonString, - ObjectMapper mapper - ) throws IOException { - return mapper.readValue( - jsonString, - MessagingV2RcsComplianceCountryResponse.class - ); - } } + //@JsonDeserialize(builder = MessagingV2ChannelsSenderConfiguration.Builder.class) + @JsonInclude(JsonInclude.Include.NON_EMPTY) @ToString - public static class MessagingV2RcsComplianceResponse { + public static class MessagingV2ChannelsSenderConfiguration { @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("registration_sid") + @JsonProperty("waba_id") @Getter @Setter - private String registrationSid; + private String wabaId; @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("countries") + @JsonProperty("verification_method") @Getter @Setter - private List countries; - - public static MessagingV2RcsComplianceResponse fromJson( - String jsonString, - ObjectMapper mapper - ) throws IOException { - return mapper.readValue( - jsonString, - MessagingV2RcsComplianceResponse.class - ); - } - } - - public static ChannelsSenderCreator creator( - final ChannelsSender.MessagingV2ChannelsSenderRequestsCreate messagingV2ChannelsSenderRequestsCreate - ) { - return new ChannelsSenderCreator( - messagingV2ChannelsSenderRequestsCreate - ); - } - - public static ChannelsSenderDeleter deleter(final String pathSid) { - return new ChannelsSenderDeleter(pathSid); - } + private ChannelsSender.VerificationMethod verificationMethod; - public static ChannelsSenderFetcher fetcher(final String pathSid) { - return new ChannelsSenderFetcher(pathSid); - } + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("verification_code") + @Getter + @Setter + private String verificationCode; - public static ChannelsSenderReader reader(final String channel) { - return new ChannelsSenderReader(channel); - } + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("voice_application_sid") + @Getter + @Setter + private String voiceApplicationSid; - public static ChannelsSenderUpdater updater(final String pathSid) { - return new ChannelsSenderUpdater(pathSid); } /** * Converts a JSON String into a ChannelsSender object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return ChannelsSender object represented by the provided JSON */ - public static ChannelsSender fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static ChannelsSender fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, ChannelsSender.class); @@ -668,14 +714,11 @@ public static ChannelsSender fromJson( * Converts a JSON InputStream into a ChannelsSender object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return ChannelsSender object represented by the provided JSON */ - public static ChannelsSender fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static ChannelsSender fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, ChannelsSender.class); @@ -698,94 +741,51 @@ public static String toJson(Object object, ObjectMapper mapper) { } } - private final String sid; - private final ChannelsSender.Status status; - private final String senderId; + + @Getter + private final MessagingV2RcsComplianceResponse compliance; + @Getter private final MessagingV2ChannelsSenderConfiguration configuration; - private final MessagingV2ChannelsSenderWebhook webhook; + @Getter + private final List offlineReasons; + @Getter private final MessagingV2ChannelsSenderProfileGenericResponse profile; + @Getter private final MessagingV2ChannelsSenderProperties properties; - private final List< - MessagingV2ChannelsSenderOfflineReasonsItems - > offlineReasons; - private final MessagingV2RcsComplianceResponse compliance; + @Getter + private final String senderId; + @Getter + private final String sid; + @Getter + private final ChannelsSender.Status status; + @Getter private final URI url; + @Getter + private final MessagingV2ChannelsSenderWebhook webhook; @JsonCreator private ChannelsSender( - @JsonProperty("sid") final String sid, - @JsonProperty("status") final ChannelsSender.Status status, - @JsonProperty("sender_id") final String senderId, - @JsonProperty( - "configuration" - ) final MessagingV2ChannelsSenderConfiguration configuration, - @JsonProperty("webhook") final MessagingV2ChannelsSenderWebhook webhook, - @JsonProperty( - "profile" - ) final MessagingV2ChannelsSenderProfileGenericResponse profile, - @JsonProperty( - "properties" - ) final MessagingV2ChannelsSenderProperties properties, - @JsonProperty("offline_reasons") final List< - MessagingV2ChannelsSenderOfflineReasonsItems - > offlineReasons, - @JsonProperty( - "compliance" - ) final MessagingV2RcsComplianceResponse compliance, - @JsonProperty("url") final URI url + @JsonProperty("compliance") final MessagingV2RcsComplianceResponse compliance, + @JsonProperty("configuration") final MessagingV2ChannelsSenderConfiguration configuration, + @JsonProperty("offline_reasons") final List offlineReasons, + @JsonProperty("profile") final MessagingV2ChannelsSenderProfileGenericResponse profile, + @JsonProperty("properties") final MessagingV2ChannelsSenderProperties properties, + @JsonProperty("sender_id") final String senderId, + @JsonProperty("sid") final String sid, + @JsonProperty("status") final ChannelsSender.Status status, + @JsonProperty("url") final URI url, + @JsonProperty("webhook") final MessagingV2ChannelsSenderWebhook webhook ) { - this.sid = sid; - this.status = status; - this.senderId = senderId; + this.compliance = compliance; this.configuration = configuration; - this.webhook = webhook; + this.offlineReasons = offlineReasons; this.profile = profile; this.properties = properties; - this.offlineReasons = offlineReasons; - this.compliance = compliance; + this.senderId = senderId; + this.sid = sid; + this.status = status; this.url = url; - } - - public final String getSid() { - return this.sid; - } - - public final ChannelsSender.Status getStatus() { - return this.status; - } - - public final String getSenderId() { - return this.senderId; - } - - public final MessagingV2ChannelsSenderConfiguration getConfiguration() { - return this.configuration; - } - - public final MessagingV2ChannelsSenderWebhook getWebhook() { - return this.webhook; - } - - public final MessagingV2ChannelsSenderProfileGenericResponse getProfile() { - return this.profile; - } - - public final MessagingV2ChannelsSenderProperties getProperties() { - return this.properties; - } - - public final List< - MessagingV2ChannelsSenderOfflineReasonsItems - > getOfflineReasons() { - return this.offlineReasons; - } - - public final MessagingV2RcsComplianceResponse getCompliance() { - return this.compliance; - } - - public final URI getUrl() { - return this.url; + this.webhook = webhook; } @Override @@ -799,175 +799,36 @@ public boolean equals(final Object o) { } ChannelsSender other = (ChannelsSender) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(status, other.status) && - Objects.equals(senderId, other.senderId) && - Objects.equals(configuration, other.configuration) && - Objects.equals(webhook, other.webhook) && - Objects.equals(profile, other.profile) && - Objects.equals(properties, other.properties) && - Objects.equals(offlineReasons, other.offlineReasons) && - Objects.equals(compliance, other.compliance) && - Objects.equals(url, other.url) + Objects.equals(compliance, other.compliance) && + Objects.equals(configuration, other.configuration) && + Objects.equals(offlineReasons, other.offlineReasons) && + Objects.equals(profile, other.profile) && + Objects.equals(properties, other.properties) && + Objects.equals(senderId, other.senderId) && + Objects.equals(sid, other.sid) && + Objects.equals(status, other.status) && + Objects.equals(url, other.url) && + Objects.equals(webhook, other.webhook) ); } @Override public int hashCode() { return Objects.hash( - sid, - status, - senderId, - configuration, - webhook, - profile, - properties, - offlineReasons, - compliance, - url + compliance, + configuration, + offlineReasons, + profile, + properties, + senderId, + sid, + status, + url, + webhook ); } - public enum MessagingV2RcsCountryStatus { - ONLINE("ONLINE"), - OFFLINE("OFFLINE"), - TWILIO_REVIEW("TWILIO_REVIEW"), - PENDING_VERIFICATION("PENDING_VERIFICATION"); - - private final String value; - - private MessagingV2RcsCountryStatus(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static MessagingV2RcsCountryStatus forValue(final String value) { - return Promoter.enumFromString( - value, - MessagingV2RcsCountryStatus.values() - ); - } - } - - public enum MessagingV2RcsCarrierStatus { - UNKNOWN("UNKNOWN"), - UNLAUNCHED("UNLAUNCHED"), - CARRIER_REVIEW("CARRIER_REVIEW"), - APPROVED("APPROVED"), - REJECTED("REJECTED"), - SUSPENDED("SUSPENDED"); - - private final String value; - private MessagingV2RcsCarrierStatus(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static MessagingV2RcsCarrierStatus forValue(final String value) { - return Promoter.enumFromString( - value, - MessagingV2RcsCarrierStatus.values() - ); - } - } - - public enum CallbackMethodEnum { - POST("POST"), - PUT("PUT"); - - private final String value; - - private CallbackMethodEnum(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static CallbackMethodEnum forValue(final String value) { - return Promoter.enumFromString(value, CallbackMethodEnum.values()); - } - } - - public enum FallbackMethodEnum { - POST("POST"), - PUT("PUT"); - - private final String value; - - private FallbackMethodEnum(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static FallbackMethodEnum forValue(final String value) { - return Promoter.enumFromString(value, FallbackMethodEnum.values()); - } - } - - public enum VerificationMethodEnum { - SMS("sms"), - VOICE("voice"); - - private final String value; - - private VerificationMethodEnum(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static VerificationMethodEnum forValue(final String value) { - return Promoter.enumFromString( - value, - VerificationMethodEnum.values() - ); - } - } - - public enum Status { - CREATING("CREATING"), - ONLINE("ONLINE"), - OFFLINE("OFFLINE"), - PENDING_VERIFICATION("PENDING_VERIFICATION"), - VERIFYING("VERIFYING"), - ONLINE_UPDATING("ONLINE:UPDATING"), - TWILIO_REVIEW("TWILIO_REVIEW"), - DRAFT("DRAFT"); - - private final String value; - - private Status(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static Status forValue(final String value) { - return Promoter.enumFromString(value, Status.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/messaging/v2/ChannelsSenderCreator.java b/src/main/java/com/twilio/rest/messaging/v2/ChannelsSenderCreator.java index f63eac8ede..3aa40b9766 100644 --- a/src/main/java/com/twilio/rest/messaging/v2/ChannelsSenderCreator.java +++ b/src/main/java/com/twilio/rest/messaging/v2/ChannelsSenderCreator.java @@ -30,72 +30,53 @@ public class ChannelsSenderCreator extends Creator { private ChannelsSender.MessagingV2ChannelsSenderRequestsCreate messagingV2ChannelsSenderRequestsCreate; - public ChannelsSenderCreator( - final ChannelsSender.MessagingV2ChannelsSenderRequestsCreate messagingV2ChannelsSenderRequestsCreate - ) { - this.messagingV2ChannelsSenderRequestsCreate = - messagingV2ChannelsSenderRequestsCreate; + public ChannelsSenderCreator(final ChannelsSender.MessagingV2ChannelsSenderRequestsCreate messagingV2ChannelsSenderRequestsCreate) { + this.messagingV2ChannelsSenderRequestsCreate = messagingV2ChannelsSenderRequestsCreate; } - public ChannelsSenderCreator setMessagingV2ChannelsSenderRequestsCreate( - final ChannelsSender.MessagingV2ChannelsSenderRequestsCreate messagingV2ChannelsSenderRequestsCreate - ) { - this.messagingV2ChannelsSenderRequestsCreate = - messagingV2ChannelsSenderRequestsCreate; + + public ChannelsSenderCreator setMessagingV2ChannelsSenderRequestsCreate(final ChannelsSender.MessagingV2ChannelsSenderRequestsCreate messagingV2ChannelsSenderRequestsCreate) { + this.messagingV2ChannelsSenderRequestsCreate = messagingV2ChannelsSenderRequestsCreate; return this; } + @Override public ChannelsSender create(final TwilioRestClient client) { + String path = "/v2/Channels/Senders"; - path = - path.replace( - "{" + "MessagingV2ChannelsSenderRequestsCreate" + "}", - this.messagingV2ChannelsSenderRequestsCreate.toString() - ); Request request = new Request( - HttpMethod.POST, - Domains.MESSAGING.toString(), - path + HttpMethod.POST, + Domains.MESSAGING.toString(), + path ); request.setContentType(EnumConstants.ContentType.JSON); addPostParams(request, client); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "ChannelsSender creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("ChannelsSender creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return ChannelsSender.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return ChannelsSender.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request, TwilioRestClient client) { ObjectMapper objectMapper = client.getObjectMapper(); if (messagingV2ChannelsSenderRequestsCreate != null) { - request.setBody( - ChannelsSender.toJson( - messagingV2ChannelsSenderRequestsCreate, - objectMapper - ) - ); + request.setBody(ChannelsSender.toJson(messagingV2ChannelsSenderRequestsCreate, objectMapper)); } } } diff --git a/src/main/java/com/twilio/rest/messaging/v2/ChannelsSenderDeleter.java b/src/main/java/com/twilio/rest/messaging/v2/ChannelsSenderDeleter.java index 7b6870d0df..c355287d9a 100644 --- a/src/main/java/com/twilio/rest/messaging/v2/ChannelsSenderDeleter.java +++ b/src/main/java/com/twilio/rest/messaging/v2/ChannelsSenderDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.messaging.v2; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,40 +26,38 @@ public class ChannelsSenderDeleter extends Deleter { - private String pathSid; + private String pathsid; - public ChannelsSenderDeleter(final String pathSid) { - this.pathSid = pathSid; + public ChannelsSenderDeleter(final String pathsid) { + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/v2/Channels/Senders/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.MESSAGING.toString(), - path + HttpMethod.DELETE, + Domains.MESSAGING.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "ChannelsSender delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("ChannelsSender delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/messaging/v2/ChannelsSenderFetcher.java b/src/main/java/com/twilio/rest/messaging/v2/ChannelsSenderFetcher.java index 7b17d3c38e..9cefa061b7 100644 --- a/src/main/java/com/twilio/rest/messaging/v2/ChannelsSenderFetcher.java +++ b/src/main/java/com/twilio/rest/messaging/v2/ChannelsSenderFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.messaging.v2; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,47 +26,41 @@ public class ChannelsSenderFetcher extends Fetcher { - private String pathSid; + private String pathsid; - public ChannelsSenderFetcher(final String pathSid) { - this.pathSid = pathSid; + public ChannelsSenderFetcher(final String pathsid) { + this.pathsid = pathsid; } + @Override public ChannelsSender fetch(final TwilioRestClient client) { + String path = "/v2/Channels/Senders/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.MESSAGING.toString(), - path + HttpMethod.GET, + Domains.MESSAGING.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "ChannelsSender fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("ChannelsSender fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return ChannelsSender.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return ChannelsSender.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/messaging/v2/ChannelsSenderReader.java b/src/main/java/com/twilio/rest/messaging/v2/ChannelsSenderReader.java index 1a316d899d..cf4cc049e8 100644 --- a/src/main/java/com/twilio/rest/messaging/v2/ChannelsSenderReader.java +++ b/src/main/java/com/twilio/rest/messaging/v2/ChannelsSenderReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -36,112 +37,91 @@ public ChannelsSenderReader(final String channel) { this.channel = channel; } + public ChannelsSenderReader setChannel(final String channel) { this.channel = channel; return this; } + public ChannelsSenderReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v2/Channels/Senders"; - path = path.replace("{" + "Channel" + "}", this.channel.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.MESSAGING.toString(), - path + HttpMethod.GET, + Domains.MESSAGING.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "ChannelsSender read failed: Unable to connect to server" - ); + throw new ApiConnectionException("ChannelsSender read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "senders", - response.getContent(), - ChannelsSender.class, - client.getObjectMapper() - ); + "senders", + response.getContent(), + ChannelsSender.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.MESSAGING.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.MESSAGING.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (channel != null) { - request.addQueryParam("Channel", channel); + Serializer.toString(request, "Channel", channel, ParameterType.QUERY); } + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/messaging/v2/ChannelsSenderUpdater.java b/src/main/java/com/twilio/rest/messaging/v2/ChannelsSenderUpdater.java index 27315f96ae..669227730d 100644 --- a/src/main/java/com/twilio/rest/messaging/v2/ChannelsSenderUpdater.java +++ b/src/main/java/com/twilio/rest/messaging/v2/ChannelsSenderUpdater.java @@ -27,69 +27,58 @@ import com.twilio.rest.Domains; public class ChannelsSenderUpdater extends Updater { - - private String pathSid; + private String pathsid; private ChannelsSender.MessagingV2ChannelsSenderRequestsUpdate messagingV2ChannelsSenderRequestsUpdate; - public ChannelsSenderUpdater(final String pathSid) { - this.pathSid = pathSid; + public ChannelsSenderUpdater(final String pathsid) { + this.pathsid = pathsid; } - public ChannelsSenderUpdater setMessagingV2ChannelsSenderRequestsUpdate( - final ChannelsSender.MessagingV2ChannelsSenderRequestsUpdate messagingV2ChannelsSenderRequestsUpdate - ) { - this.messagingV2ChannelsSenderRequestsUpdate = - messagingV2ChannelsSenderRequestsUpdate; + + public ChannelsSenderUpdater setMessagingV2ChannelsSenderRequestsUpdate(final ChannelsSender.MessagingV2ChannelsSenderRequestsUpdate messagingV2ChannelsSenderRequestsUpdate) { + this.messagingV2ChannelsSenderRequestsUpdate = messagingV2ChannelsSenderRequestsUpdate; return this; } + @Override public ChannelsSender update(final TwilioRestClient client) { + String path = "/v2/Channels/Senders/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.MESSAGING.toString(), - path + HttpMethod.POST, + Domains.MESSAGING.toString(), + path ); request.setContentType(EnumConstants.ContentType.JSON); addPostParams(request, client); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "ChannelsSender update failed: Unable to connect to server" - ); + throw new ApiConnectionException("ChannelsSender update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return ChannelsSender.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return ChannelsSender.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request, TwilioRestClient client) { ObjectMapper objectMapper = client.getObjectMapper(); if (messagingV2ChannelsSenderRequestsUpdate != null) { - request.setBody( - ChannelsSender.toJson( - messagingV2ChannelsSenderRequestsUpdate, - objectMapper - ) - ); + request.setBody(ChannelsSender.toJson(messagingV2ChannelsSenderRequestsUpdate, objectMapper)); } } } diff --git a/src/main/java/com/twilio/rest/monitor/v1/Alert.java b/src/main/java/com/twilio/rest/monitor/v1/Alert.java index b716f30f62..4d8b490774 100644 --- a/src/main/java/com/twilio/rest/monitor/v1/Alert.java +++ b/src/main/java/com/twilio/rest/monitor/v1/Alert.java @@ -18,46 +18,50 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.http.HttpMethod; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Alert extends Resource { - private static final long serialVersionUID = 14184743930644L; - public static AlertFetcher fetcher(final String pathSid) { - return new AlertFetcher(pathSid); + public static AlertFetcher fetcher(final String pathsid) { + return new AlertFetcher( + pathsid + ); } + public static AlertReader reader() { - return new AlertReader(); + return new AlertReader( + + ); } + /** * Converts a JSON String into a Alert object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Alert object represented by the provided JSON */ - public static Alert fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Alert fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Alert.class); @@ -72,14 +76,11 @@ public static Alert fromJson( * Converts a JSON InputStream into a Alert object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Alert object represented by the provided JSON */ - public static Alert fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Alert fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Alert.class); @@ -90,144 +91,102 @@ public static Alert fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; + @Getter private final String alertText; + @Getter private final String apiVersion; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateGenerated; + @Getter private final ZonedDateTime dateUpdated; + @Getter private final String errorCode; + @Getter private final String logLevel; + @Getter private final String moreInfo; + @Getter + private final String requestHeaders; + @Getter private final HttpMethod requestMethod; + @Getter private final String requestUrl; + @Getter private final String requestVariables; + @Getter private final String resourceSid; + @Getter private final String responseBody; + @Getter private final String responseHeaders; + @Getter + private final String serviceSid; + @Getter private final String sid; + @Getter private final URI url; - private final String requestHeaders; - private final String serviceSid; @JsonCreator private Alert( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("alert_text") final String alertText, - @JsonProperty("api_version") final String apiVersion, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_generated") final String dateGenerated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("error_code") final String errorCode, - @JsonProperty("log_level") final String logLevel, - @JsonProperty("more_info") final String moreInfo, - @JsonProperty("request_method") final HttpMethod requestMethod, - @JsonProperty("request_url") final String requestUrl, - @JsonProperty("request_variables") final String requestVariables, - @JsonProperty("resource_sid") final String resourceSid, - @JsonProperty("response_body") final String responseBody, - @JsonProperty("response_headers") final String responseHeaders, - @JsonProperty("sid") final String sid, - @JsonProperty("url") final URI url, - @JsonProperty("request_headers") final String requestHeaders, - @JsonProperty("service_sid") final String serviceSid + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("alert_text") final String alertText, + @JsonProperty("api_version") final String apiVersion, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_generated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateGenerated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("error_code") final String errorCode, + @JsonProperty("log_level") final String logLevel, + @JsonProperty("more_info") final String moreInfo, + @JsonProperty("request_headers") final String requestHeaders, + @JsonProperty("request_method") final HttpMethod requestMethod, + @JsonProperty("request_url") final String requestUrl, + @JsonProperty("request_variables") final String requestVariables, + @JsonProperty("resource_sid") final String resourceSid, + @JsonProperty("response_body") final String responseBody, + @JsonProperty("response_headers") final String responseHeaders, + @JsonProperty("service_sid") final String serviceSid, + @JsonProperty("sid") final String sid, + @JsonProperty("url") final URI url ) { this.accountSid = accountSid; this.alertText = alertText; this.apiVersion = apiVersion; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateGenerated = - DateConverter.iso8601DateTimeFromString(dateGenerated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); + this.dateCreated = dateCreated; + this.dateGenerated = dateGenerated; + this.dateUpdated = dateUpdated; this.errorCode = errorCode; this.logLevel = logLevel; this.moreInfo = moreInfo; + this.requestHeaders = requestHeaders; this.requestMethod = requestMethod; this.requestUrl = requestUrl; this.requestVariables = requestVariables; this.resourceSid = resourceSid; this.responseBody = responseBody; this.responseHeaders = responseHeaders; + this.serviceSid = serviceSid; this.sid = sid; this.url = url; - this.requestHeaders = requestHeaders; - this.serviceSid = serviceSid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getAlertText() { - return this.alertText; - } - - public final String getApiVersion() { - return this.apiVersion; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateGenerated() { - return this.dateGenerated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final String getErrorCode() { - return this.errorCode; - } - - public final String getLogLevel() { - return this.logLevel; - } - - public final String getMoreInfo() { - return this.moreInfo; - } - - public final HttpMethod getRequestMethod() { - return this.requestMethod; - } - - public final String getRequestUrl() { - return this.requestUrl; - } - - public final String getRequestVariables() { - return this.requestVariables; - } - - public final String getResourceSid() { - return this.resourceSid; - } - - public final String getResponseBody() { - return this.responseBody; - } - - public final String getResponseHeaders() { - return this.responseHeaders; - } - - public final String getSid() { - return this.sid; - } - - public final URI getUrl() { - return this.url; - } - - public final String getRequestHeaders() { - return this.requestHeaders; - } - - public final String getServiceSid() { - return this.serviceSid; } @Override @@ -241,52 +200,54 @@ public boolean equals(final Object o) { } Alert other = (Alert) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(alertText, other.alertText) && - Objects.equals(apiVersion, other.apiVersion) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateGenerated, other.dateGenerated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(errorCode, other.errorCode) && - Objects.equals(logLevel, other.logLevel) && - Objects.equals(moreInfo, other.moreInfo) && - Objects.equals(requestMethod, other.requestMethod) && - Objects.equals(requestUrl, other.requestUrl) && - Objects.equals(requestVariables, other.requestVariables) && - Objects.equals(resourceSid, other.resourceSid) && - Objects.equals(responseBody, other.responseBody) && - Objects.equals(responseHeaders, other.responseHeaders) && - Objects.equals(sid, other.sid) && - Objects.equals(url, other.url) && - Objects.equals(requestHeaders, other.requestHeaders) && - Objects.equals(serviceSid, other.serviceSid) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(alertText, other.alertText) && + Objects.equals(apiVersion, other.apiVersion) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateGenerated, other.dateGenerated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(errorCode, other.errorCode) && + Objects.equals(logLevel, other.logLevel) && + Objects.equals(moreInfo, other.moreInfo) && + Objects.equals(requestHeaders, other.requestHeaders) && + Objects.equals(requestMethod, other.requestMethod) && + Objects.equals(requestUrl, other.requestUrl) && + Objects.equals(requestVariables, other.requestVariables) && + Objects.equals(resourceSid, other.resourceSid) && + Objects.equals(responseBody, other.responseBody) && + Objects.equals(responseHeaders, other.responseHeaders) && + Objects.equals(serviceSid, other.serviceSid) && + Objects.equals(sid, other.sid) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - accountSid, - alertText, - apiVersion, - dateCreated, - dateGenerated, - dateUpdated, - errorCode, - logLevel, - moreInfo, - requestMethod, - requestUrl, - requestVariables, - resourceSid, - responseBody, - responseHeaders, - sid, - url, - requestHeaders, - serviceSid + accountSid, + alertText, + apiVersion, + dateCreated, + dateGenerated, + dateUpdated, + errorCode, + logLevel, + moreInfo, + requestHeaders, + requestMethod, + requestUrl, + requestVariables, + resourceSid, + responseBody, + responseHeaders, + serviceSid, + sid, + url ); } + + } + diff --git a/src/main/java/com/twilio/rest/monitor/v1/AlertFetcher.java b/src/main/java/com/twilio/rest/monitor/v1/AlertFetcher.java index adb4a74c60..127b1e667f 100644 --- a/src/main/java/com/twilio/rest/monitor/v1/AlertFetcher.java +++ b/src/main/java/com/twilio/rest/monitor/v1/AlertFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.monitor.v1; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,44 +26,41 @@ public class AlertFetcher extends Fetcher { - private String pathSid; + private String pathsid; - public AlertFetcher(final String pathSid) { - this.pathSid = pathSid; + public AlertFetcher(final String pathsid) { + this.pathsid = pathsid; } + @Override public Alert fetch(final TwilioRestClient client) { + String path = "/v1/Alerts/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.MONITOR.toString(), - path + HttpMethod.GET, + Domains.MONITOR.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Alert fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Alert fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Alert.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/monitor/v1/AlertReader.java b/src/main/java/com/twilio/rest/monitor/v1/AlertReader.java index aebca18c6e..dc9916ea7b 100644 --- a/src/main/java/com/twilio/rest/monitor/v1/AlertReader.java +++ b/src/main/java/com/twilio/rest/monitor/v1/AlertReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -26,6 +27,7 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.time.ZonedDateTime; public class AlertReader extends Reader { @@ -35,134 +37,116 @@ public class AlertReader extends Reader { private ZonedDateTime endDate; private Long pageSize; - public AlertReader() {} + public AlertReader() { + } + public AlertReader setLogLevel(final String logLevel) { this.logLevel = logLevel; return this; } + public AlertReader setStartDate(final ZonedDateTime startDate) { this.startDate = startDate; return this; } + public AlertReader setEndDate(final ZonedDateTime endDate) { this.endDate = endDate; return this; } + public AlertReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/Alerts"; + Request request = new Request( - HttpMethod.GET, - Domains.MONITOR.toString(), - path + HttpMethod.GET, + Domains.MONITOR.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Alert read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Alert read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "alerts", - response.getContent(), - Alert.class, - client.getObjectMapper() - ); + "alerts", + response.getContent(), + Alert.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.MONITOR.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.MONITOR.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (logLevel != null) { - request.addQueryParam("LogLevel", logLevel); + Serializer.toString(request, "LogLevel", logLevel, ParameterType.QUERY); } + + if (startDate != null) { - request.addQueryParam( - "StartDate", - startDate.toInstant().toString() - ); + Serializer.toString(request, "StartDate", startDate, ParameterType.QUERY); } + if (endDate != null) { - request.addQueryParam("EndDate", endDate.toInstant().toString()); + Serializer.toString(request, "EndDate", endDate, ParameterType.QUERY); } + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/monitor/v1/Event.java b/src/main/java/com/twilio/rest/monitor/v1/Event.java index fdac28b2c2..667565a348 100644 --- a/src/main/java/com/twilio/rest/monitor/v1/Event.java +++ b/src/main/java/com/twilio/rest/monitor/v1/Event.java @@ -18,47 +18,50 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Event extends Resource { - private static final long serialVersionUID = 206221188315695L; - public static EventFetcher fetcher(final String pathSid) { - return new EventFetcher(pathSid); + public static EventFetcher fetcher(final String pathsid) { + return new EventFetcher( + pathsid + ); } + public static EventReader reader() { - return new EventReader(); + return new EventReader( + + ); } + /** * Converts a JSON String into a Event object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Event object represented by the provided JSON */ - public static Event fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Event fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Event.class); @@ -73,14 +76,11 @@ public static Event fromJson( * Converts a JSON InputStream into a Event object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Event object represented by the provided JSON */ - public static Event fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Event fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Event.class); @@ -91,108 +91,80 @@ public static Event fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; + @Getter private final String actorSid; + @Getter private final String actorType; + @Getter private final String description; - private final Map eventData; + @Getter + private final Object eventData; + @Getter private final ZonedDateTime eventDate; + @Getter private final String eventType; + @Getter + private final Map links; + @Getter private final String resourceSid; + @Getter private final String resourceType; + @Getter private final String sid; + @Getter private final String source; + @Getter private final String sourceIpAddress; + @Getter private final URI url; - private final Map links; @JsonCreator private Event( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("actor_sid") final String actorSid, - @JsonProperty("actor_type") final String actorType, - @JsonProperty("description") final String description, - @JsonProperty("event_data") final Map eventData, - @JsonProperty("event_date") final String eventDate, - @JsonProperty("event_type") final String eventType, - @JsonProperty("resource_sid") final String resourceSid, - @JsonProperty("resource_type") final String resourceType, - @JsonProperty("sid") final String sid, - @JsonProperty("source") final String source, - @JsonProperty("source_ip_address") final String sourceIpAddress, - @JsonProperty("url") final URI url, - @JsonProperty("links") final Map links + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("actor_sid") final String actorSid, + @JsonProperty("actor_type") final String actorType, + @JsonProperty("description") final String description, + @JsonProperty("event_data") final Object eventData, + @JsonProperty("event_date") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime eventDate, + @JsonProperty("event_type") final String eventType, + @JsonProperty("links") final Map links, + @JsonProperty("resource_sid") final String resourceSid, + @JsonProperty("resource_type") final String resourceType, + @JsonProperty("sid") final String sid, + @JsonProperty("source") final String source, + @JsonProperty("source_ip_address") final String sourceIpAddress, + @JsonProperty("url") final URI url ) { this.accountSid = accountSid; this.actorSid = actorSid; this.actorType = actorType; this.description = description; this.eventData = eventData; - this.eventDate = DateConverter.iso8601DateTimeFromString(eventDate); + this.eventDate = eventDate; this.eventType = eventType; + this.links = links; this.resourceSid = resourceSid; this.resourceType = resourceType; this.sid = sid; this.source = source; this.sourceIpAddress = sourceIpAddress; this.url = url; - this.links = links; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getActorSid() { - return this.actorSid; - } - - public final String getActorType() { - return this.actorType; - } - - public final String getDescription() { - return this.description; - } - - public final Map getEventData() { - return this.eventData; - } - - public final ZonedDateTime getEventDate() { - return this.eventDate; - } - - public final String getEventType() { - return this.eventType; - } - - public final String getResourceSid() { - return this.resourceSid; - } - - public final String getResourceType() { - return this.resourceType; - } - - public final String getSid() { - return this.sid; - } - - public final String getSource() { - return this.source; - } - - public final String getSourceIpAddress() { - return this.sourceIpAddress; - } - - public final URI getUrl() { - return this.url; - } - - public final Map getLinks() { - return this.links; } @Override @@ -206,42 +178,44 @@ public boolean equals(final Object o) { } Event other = (Event) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(actorSid, other.actorSid) && - Objects.equals(actorType, other.actorType) && - Objects.equals(description, other.description) && - Objects.equals(eventData, other.eventData) && - Objects.equals(eventDate, other.eventDate) && - Objects.equals(eventType, other.eventType) && - Objects.equals(resourceSid, other.resourceSid) && - Objects.equals(resourceType, other.resourceType) && - Objects.equals(sid, other.sid) && - Objects.equals(source, other.source) && - Objects.equals(sourceIpAddress, other.sourceIpAddress) && - Objects.equals(url, other.url) && - Objects.equals(links, other.links) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(actorSid, other.actorSid) && + Objects.equals(actorType, other.actorType) && + Objects.equals(description, other.description) && + Objects.equals(eventData, other.eventData) && + Objects.equals(eventDate, other.eventDate) && + Objects.equals(eventType, other.eventType) && + Objects.equals(links, other.links) && + Objects.equals(resourceSid, other.resourceSid) && + Objects.equals(resourceType, other.resourceType) && + Objects.equals(sid, other.sid) && + Objects.equals(source, other.source) && + Objects.equals(sourceIpAddress, other.sourceIpAddress) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - accountSid, - actorSid, - actorType, - description, - eventData, - eventDate, - eventType, - resourceSid, - resourceType, - sid, - source, - sourceIpAddress, - url, - links + accountSid, + actorSid, + actorType, + description, + eventData, + eventDate, + eventType, + links, + resourceSid, + resourceType, + sid, + source, + sourceIpAddress, + url ); } + + } + diff --git a/src/main/java/com/twilio/rest/monitor/v1/EventFetcher.java b/src/main/java/com/twilio/rest/monitor/v1/EventFetcher.java index 7399afd304..9abd6a072f 100644 --- a/src/main/java/com/twilio/rest/monitor/v1/EventFetcher.java +++ b/src/main/java/com/twilio/rest/monitor/v1/EventFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.monitor.v1; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,44 +26,41 @@ public class EventFetcher extends Fetcher { - private String pathSid; + private String pathsid; - public EventFetcher(final String pathSid) { - this.pathSid = pathSid; + public EventFetcher(final String pathsid) { + this.pathsid = pathsid; } + @Override public Event fetch(final TwilioRestClient client) { + String path = "/v1/Events/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.MONITOR.toString(), - path + HttpMethod.GET, + Domains.MONITOR.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Event fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Event fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Event.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/monitor/v1/EventReader.java b/src/main/java/com/twilio/rest/monitor/v1/EventReader.java index c24298908a..ad5adbc29a 100644 --- a/src/main/java/com/twilio/rest/monitor/v1/EventReader.java +++ b/src/main/java/com/twilio/rest/monitor/v1/EventReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -26,6 +27,7 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.time.ZonedDateTime; public class EventReader extends Reader { @@ -38,158 +40,149 @@ public class EventReader extends Reader { private ZonedDateTime endDate; private Long pageSize; - public EventReader() {} + public EventReader() { + } + public EventReader setActorSid(final String actorSid) { this.actorSid = actorSid; return this; } + public EventReader setEventType(final String eventType) { this.eventType = eventType; return this; } + public EventReader setResourceSid(final String resourceSid) { this.resourceSid = resourceSid; return this; } + public EventReader setSourceIpAddress(final String sourceIpAddress) { this.sourceIpAddress = sourceIpAddress; return this; } + public EventReader setStartDate(final ZonedDateTime startDate) { this.startDate = startDate; return this; } + public EventReader setEndDate(final ZonedDateTime endDate) { this.endDate = endDate; return this; } + public EventReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/Events"; + Request request = new Request( - HttpMethod.GET, - Domains.MONITOR.toString(), - path + HttpMethod.GET, + Domains.MONITOR.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Event read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Event read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "events", - response.getContent(), - Event.class, - client.getObjectMapper() - ); + "events", + response.getContent(), + Event.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.MONITOR.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.MONITOR.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (actorSid != null) { - request.addQueryParam("ActorSid", actorSid); + Serializer.toString(request, "ActorSid", actorSid, ParameterType.QUERY); } + + if (eventType != null) { - request.addQueryParam("EventType", eventType); + Serializer.toString(request, "EventType", eventType, ParameterType.QUERY); } + + if (resourceSid != null) { - request.addQueryParam("ResourceSid", resourceSid); + Serializer.toString(request, "ResourceSid", resourceSid, ParameterType.QUERY); } + + if (sourceIpAddress != null) { - request.addQueryParam("SourceIpAddress", sourceIpAddress); + Serializer.toString(request, "SourceIpAddress", sourceIpAddress, ParameterType.QUERY); } + + if (startDate != null) { - request.addQueryParam( - "StartDate", - startDate.toInstant().toString() - ); + Serializer.toString(request, "StartDate", startDate, ParameterType.QUERY); } + if (endDate != null) { - request.addQueryParam("EndDate", endDate.toInstant().toString()); + Serializer.toString(request, "EndDate", endDate, ParameterType.QUERY); } + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/notify/v1/Credential.java b/src/main/java/com/twilio/rest/notify/v1/Credential.java index 316599eb29..db764ceb30 100644 --- a/src/main/java/com/twilio/rest/notify/v1/Credential.java +++ b/src/main/java/com/twilio/rest/notify/v1/Credential.java @@ -18,58 +18,93 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Credential extends Resource { - private static final long serialVersionUID = 161183169234848L; public static CredentialCreator creator(final Credential.PushService type) { - return new CredentialCreator(type); + return new CredentialCreator( + type + ); } - public static CredentialDeleter deleter(final String pathSid) { - return new CredentialDeleter(pathSid); + + public static CredentialDeleter deleter(final String pathsid) { + return new CredentialDeleter( + pathsid + ); } - public static CredentialFetcher fetcher(final String pathSid) { - return new CredentialFetcher(pathSid); + + public static CredentialFetcher fetcher(final String pathsid) { + return new CredentialFetcher( + pathsid + ); } + public static CredentialReader reader() { - return new CredentialReader(); + return new CredentialReader( + + ); } - public static CredentialUpdater updater(final String pathSid) { - return new CredentialUpdater(pathSid); + + public static CredentialUpdater updater(final String pathsid) { + return new CredentialUpdater( + pathsid + ); } + + public enum PushService { + GCM("gcm"), + APN("apn"), + FCM("fcm"); + + private final String value; + + private PushService(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static PushService forValue(final String value) { + return Promoter.enumFromString(value, PushService.values()); + } + } + + /** * Converts a JSON String into a Credential object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Credential object represented by the provided JSON */ - public static Credential fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Credential fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Credential.class); @@ -84,14 +119,11 @@ public static Credential fromJson( * Converts a JSON InputStream into a Credential object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Credential object represented by the provided JSON */ - public static Credential fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Credential fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Credential.class); @@ -102,68 +134,59 @@ public static Credential fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String friendlyName; - private final Credential.PushService type; - private final String sandbox; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; + @Getter + private final String friendlyName; + @Getter + private final String sandbox; + @Getter + private final String sid; + @Getter + private final Credential.PushService type; + @Getter private final URI url; @JsonCreator private Credential( - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("type") final Credential.PushService type, - @JsonProperty("sandbox") final String sandbox, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("url") final URI url + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("sandbox") final String sandbox, + @JsonProperty("sid") final String sid, + @JsonProperty("type") final Credential.PushService type, + @JsonProperty("url") final URI url ) { - this.sid = sid; this.accountSid = accountSid; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.friendlyName = friendlyName; - this.type = type; this.sandbox = sandbox; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); + this.sid = sid; + this.type = type; this.url = url; } - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final Credential.PushService getType() { - return this.type; - } - - public final String getSandbox() { - return this.sandbox; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final URI getUrl() { - return this.url; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -175,51 +198,32 @@ public boolean equals(final Object o) { } Credential other = (Credential) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(type, other.type) && - Objects.equals(sandbox, other.sandbox) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(url, other.url) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(sandbox, other.sandbox) && + Objects.equals(sid, other.sid) && + Objects.equals(type, other.type) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - sid, - accountSid, - friendlyName, - type, - sandbox, - dateCreated, - dateUpdated, - url + accountSid, + dateCreated, + dateUpdated, + friendlyName, + sandbox, + sid, + type, + url ); } - public enum PushService { - GCM("gcm"), - APN("apn"), - FCM("fcm"); - - private final String value; - - private PushService(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - @JsonCreator - public static PushService forValue(final String value) { - return Promoter.enumFromString(value, PushService.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/notify/v1/CredentialCreator.java b/src/main/java/com/twilio/rest/notify/v1/CredentialCreator.java index e7f1cf5ec4..d2b61d952d 100644 --- a/src/main/java/com/twilio/rest/notify/v1/CredentialCreator.java +++ b/src/main/java/com/twilio/rest/notify/v1/CredentialCreator.java @@ -14,8 +14,11 @@ package com.twilio.rest.notify.v1; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -39,100 +42,117 @@ public CredentialCreator(final Credential.PushService type) { this.type = type; } + public CredentialCreator setType(final Credential.PushService type) { this.type = type; return this; } + public CredentialCreator setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + public CredentialCreator setCertificate(final String certificate) { this.certificate = certificate; return this; } + public CredentialCreator setPrivateKey(final String privateKey) { this.privateKey = privateKey; return this; } + public CredentialCreator setSandbox(final Boolean sandbox) { this.sandbox = sandbox; return this; } + public CredentialCreator setApiKey(final String apiKey) { this.apiKey = apiKey; return this; } + public CredentialCreator setSecret(final String secret) { this.secret = secret; return this; } + @Override public Credential create(final TwilioRestClient client) { + String path = "/v1/Credentials"; - path = path.replace("{" + "Type" + "}", this.type.toString()); Request request = new Request( - HttpMethod.POST, - Domains.NOTIFY.toString(), - path + HttpMethod.POST, + Domains.NOTIFY.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Credential creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("Credential creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Credential.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Credential.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (type != null) { - request.addPostParam("Type", type.toString()); + Serializer.toString(request, "Type", type, ParameterType.URLENCODED); } + + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + if (certificate != null) { - request.addPostParam("Certificate", certificate); + Serializer.toString(request, "Certificate", certificate, ParameterType.URLENCODED); } + + if (privateKey != null) { - request.addPostParam("PrivateKey", privateKey); + Serializer.toString(request, "PrivateKey", privateKey, ParameterType.URLENCODED); } + + if (sandbox != null) { - request.addPostParam("Sandbox", sandbox.toString()); + Serializer.toString(request, "Sandbox", sandbox, ParameterType.URLENCODED); } + + if (apiKey != null) { - request.addPostParam("ApiKey", apiKey); + Serializer.toString(request, "ApiKey", apiKey, ParameterType.URLENCODED); } + + if (secret != null) { - request.addPostParam("Secret", secret); + Serializer.toString(request, "Secret", secret, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/notify/v1/CredentialDeleter.java b/src/main/java/com/twilio/rest/notify/v1/CredentialDeleter.java index 85102c0c0a..5522b936f7 100644 --- a/src/main/java/com/twilio/rest/notify/v1/CredentialDeleter.java +++ b/src/main/java/com/twilio/rest/notify/v1/CredentialDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.notify.v1; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,40 +26,38 @@ public class CredentialDeleter extends Deleter { - private String pathSid; + private String pathsid; - public CredentialDeleter(final String pathSid) { - this.pathSid = pathSid; + public CredentialDeleter(final String pathsid) { + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/v1/Credentials/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.NOTIFY.toString(), - path + HttpMethod.DELETE, + Domains.NOTIFY.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Credential delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("Credential delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/notify/v1/CredentialFetcher.java b/src/main/java/com/twilio/rest/notify/v1/CredentialFetcher.java index a5ea066624..572b74e531 100644 --- a/src/main/java/com/twilio/rest/notify/v1/CredentialFetcher.java +++ b/src/main/java/com/twilio/rest/notify/v1/CredentialFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.notify.v1; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,47 +26,41 @@ public class CredentialFetcher extends Fetcher { - private String pathSid; + private String pathsid; - public CredentialFetcher(final String pathSid) { - this.pathSid = pathSid; + public CredentialFetcher(final String pathsid) { + this.pathsid = pathsid; } + @Override public Credential fetch(final TwilioRestClient client) { + String path = "/v1/Credentials/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.NOTIFY.toString(), - path + HttpMethod.GET, + Domains.NOTIFY.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Credential fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Credential fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return Credential.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Credential.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/notify/v1/CredentialReader.java b/src/main/java/com/twilio/rest/notify/v1/CredentialReader.java index d281257cd0..ad9970bd82 100644 --- a/src/main/java/com/twilio/rest/notify/v1/CredentialReader.java +++ b/src/main/java/com/twilio/rest/notify/v1/CredentialReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -31,105 +32,83 @@ public class CredentialReader extends Reader { private Long pageSize; - public CredentialReader() {} + public CredentialReader() { + } + public CredentialReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/Credentials"; + Request request = new Request( - HttpMethod.GET, - Domains.NOTIFY.toString(), - path + HttpMethod.GET, + Domains.NOTIFY.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Credential read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Credential read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "credentials", - response.getContent(), - Credential.class, - client.getObjectMapper() - ); + "credentials", + response.getContent(), + Credential.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.NOTIFY.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.NOTIFY.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/notify/v1/CredentialUpdater.java b/src/main/java/com/twilio/rest/notify/v1/CredentialUpdater.java index 3ff1e068c9..c941c41c56 100644 --- a/src/main/java/com/twilio/rest/notify/v1/CredentialUpdater.java +++ b/src/main/java/com/twilio/rest/notify/v1/CredentialUpdater.java @@ -16,6 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -26,8 +28,7 @@ import com.twilio.rest.Domains; public class CredentialUpdater extends Updater { - - private String pathSid; + private String pathsid; private String friendlyName; private String certificate; private String privateKey; @@ -35,96 +36,112 @@ public class CredentialUpdater extends Updater { private String apiKey; private String secret; - public CredentialUpdater(final String pathSid) { - this.pathSid = pathSid; + public CredentialUpdater(final String pathsid) { + this.pathsid = pathsid; } + public CredentialUpdater setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + public CredentialUpdater setCertificate(final String certificate) { this.certificate = certificate; return this; } + public CredentialUpdater setPrivateKey(final String privateKey) { this.privateKey = privateKey; return this; } + public CredentialUpdater setSandbox(final Boolean sandbox) { this.sandbox = sandbox; return this; } + public CredentialUpdater setApiKey(final String apiKey) { this.apiKey = apiKey; return this; } + public CredentialUpdater setSecret(final String secret) { this.secret = secret; return this; } + @Override public Credential update(final TwilioRestClient client) { + String path = "/v1/Credentials/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.NOTIFY.toString(), - path + HttpMethod.POST, + Domains.NOTIFY.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Credential update failed: Unable to connect to server" - ); + throw new ApiConnectionException("Credential update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Credential.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Credential.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + if (certificate != null) { - request.addPostParam("Certificate", certificate); + Serializer.toString(request, "Certificate", certificate, ParameterType.URLENCODED); } + + if (privateKey != null) { - request.addPostParam("PrivateKey", privateKey); + Serializer.toString(request, "PrivateKey", privateKey, ParameterType.URLENCODED); } + + if (sandbox != null) { - request.addPostParam("Sandbox", sandbox.toString()); + Serializer.toString(request, "Sandbox", sandbox, ParameterType.URLENCODED); } + + if (apiKey != null) { - request.addPostParam("ApiKey", apiKey); + Serializer.toString(request, "ApiKey", apiKey, ParameterType.URLENCODED); } + + if (secret != null) { - request.addPostParam("Secret", secret); + Serializer.toString(request, "Secret", secret, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/notify/v1/Service.java b/src/main/java/com/twilio/rest/notify/v1/Service.java index d051e43198..1b722e3d02 100644 --- a/src/main/java/com/twilio/rest/notify/v1/Service.java +++ b/src/main/java/com/twilio/rest/notify/v1/Service.java @@ -18,59 +18,71 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Service extends Resource { - private static final long serialVersionUID = 212409990270052L; public static ServiceCreator creator() { - return new ServiceCreator(); + return new ServiceCreator( + + ); } - public static ServiceDeleter deleter(final String pathSid) { - return new ServiceDeleter(pathSid); + + public static ServiceDeleter deleter(final String pathsid) { + return new ServiceDeleter( + pathsid + ); } - public static ServiceFetcher fetcher(final String pathSid) { - return new ServiceFetcher(pathSid); + + public static ServiceFetcher fetcher(final String pathsid) { + return new ServiceFetcher( + pathsid + ); } + public static ServiceReader reader() { - return new ServiceReader(); + return new ServiceReader( + + ); } - public static ServiceUpdater updater(final String pathSid) { - return new ServiceUpdater(pathSid); + + public static ServiceUpdater updater(final String pathsid) { + return new ServiceUpdater( + pathsid + ); } + /** * Converts a JSON String into a Service object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Service object represented by the provided JSON */ - public static Service fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Service fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Service.class); @@ -85,14 +97,11 @@ public static Service fromJson( * Converts a JSON InputStream into a Service object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Service object represented by the provided JSON */ - public static Service fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Service fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Service.class); @@ -103,166 +112,105 @@ public static Service fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String friendlyName; + @Getter + private final String alexaSkillId; + @Getter + private final String apnCredentialSid; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; - private final String apnCredentialSid; - private final String gcmCredentialSid; - private final String fcmCredentialSid; - private final String messagingServiceSid; - private final String facebookMessengerPageId; + @Getter + private final String defaultAlexaNotificationProtocolVersion; + @Getter private final String defaultApnNotificationProtocolVersion; - private final String defaultGcmNotificationProtocolVersion; + @Getter private final String defaultFcmNotificationProtocolVersion; + @Getter + private final String defaultGcmNotificationProtocolVersion; + @Getter + private final Boolean deliveryCallbackEnabled; + @Getter + private final String deliveryCallbackUrl; + @Getter + private final String facebookMessengerPageId; + @Getter + private final String fcmCredentialSid; + @Getter + private final String friendlyName; + @Getter + private final String gcmCredentialSid; + @Getter + private final Map links; + @Getter private final Boolean logEnabled; + @Getter + private final String messagingServiceSid; + @Getter + private final String sid; + @Getter private final URI url; - private final Map links; - private final String alexaSkillId; - private final String defaultAlexaNotificationProtocolVersion; - private final String deliveryCallbackUrl; - private final Boolean deliveryCallbackEnabled; @JsonCreator private Service( - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("apn_credential_sid") final String apnCredentialSid, - @JsonProperty("gcm_credential_sid") final String gcmCredentialSid, - @JsonProperty("fcm_credential_sid") final String fcmCredentialSid, - @JsonProperty("messaging_service_sid") final String messagingServiceSid, - @JsonProperty( - "facebook_messenger_page_id" - ) final String facebookMessengerPageId, - @JsonProperty( - "default_apn_notification_protocol_version" - ) final String defaultApnNotificationProtocolVersion, - @JsonProperty( - "default_gcm_notification_protocol_version" - ) final String defaultGcmNotificationProtocolVersion, - @JsonProperty( - "default_fcm_notification_protocol_version" - ) final String defaultFcmNotificationProtocolVersion, - @JsonProperty("log_enabled") final Boolean logEnabled, - @JsonProperty("url") final URI url, - @JsonProperty("links") final Map links, - @JsonProperty("alexa_skill_id") final String alexaSkillId, - @JsonProperty( - "default_alexa_notification_protocol_version" - ) final String defaultAlexaNotificationProtocolVersion, - @JsonProperty("delivery_callback_url") final String deliveryCallbackUrl, - @JsonProperty( - "delivery_callback_enabled" - ) final Boolean deliveryCallbackEnabled + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("alexa_skill_id") final String alexaSkillId, + @JsonProperty("apn_credential_sid") final String apnCredentialSid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("default_alexa_notification_protocol_version") final String defaultAlexaNotificationProtocolVersion, + @JsonProperty("default_apn_notification_protocol_version") final String defaultApnNotificationProtocolVersion, + @JsonProperty("default_fcm_notification_protocol_version") final String defaultFcmNotificationProtocolVersion, + @JsonProperty("default_gcm_notification_protocol_version") final String defaultGcmNotificationProtocolVersion, + @JsonProperty("delivery_callback_enabled") final Boolean deliveryCallbackEnabled, + @JsonProperty("delivery_callback_url") final String deliveryCallbackUrl, + @JsonProperty("facebook_messenger_page_id") final String facebookMessengerPageId, + @JsonProperty("fcm_credential_sid") final String fcmCredentialSid, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("gcm_credential_sid") final String gcmCredentialSid, + @JsonProperty("links") final Map links, + @JsonProperty("log_enabled") final Boolean logEnabled, + @JsonProperty("messaging_service_sid") final String messagingServiceSid, + @JsonProperty("sid") final String sid, + @JsonProperty("url") final URI url ) { - this.sid = sid; this.accountSid = accountSid; - this.friendlyName = friendlyName; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); + this.alexaSkillId = alexaSkillId; this.apnCredentialSid = apnCredentialSid; - this.gcmCredentialSid = gcmCredentialSid; - this.fcmCredentialSid = fcmCredentialSid; - this.messagingServiceSid = messagingServiceSid; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; + this.defaultAlexaNotificationProtocolVersion = defaultAlexaNotificationProtocolVersion; + this.defaultApnNotificationProtocolVersion = defaultApnNotificationProtocolVersion; + this.defaultFcmNotificationProtocolVersion = defaultFcmNotificationProtocolVersion; + this.defaultGcmNotificationProtocolVersion = defaultGcmNotificationProtocolVersion; + this.deliveryCallbackEnabled = deliveryCallbackEnabled; + this.deliveryCallbackUrl = deliveryCallbackUrl; this.facebookMessengerPageId = facebookMessengerPageId; - this.defaultApnNotificationProtocolVersion = - defaultApnNotificationProtocolVersion; - this.defaultGcmNotificationProtocolVersion = - defaultGcmNotificationProtocolVersion; - this.defaultFcmNotificationProtocolVersion = - defaultFcmNotificationProtocolVersion; + this.fcmCredentialSid = fcmCredentialSid; + this.friendlyName = friendlyName; + this.gcmCredentialSid = gcmCredentialSid; + this.links = links; this.logEnabled = logEnabled; + this.messagingServiceSid = messagingServiceSid; + this.sid = sid; this.url = url; - this.links = links; - this.alexaSkillId = alexaSkillId; - this.defaultAlexaNotificationProtocolVersion = - defaultAlexaNotificationProtocolVersion; - this.deliveryCallbackUrl = deliveryCallbackUrl; - this.deliveryCallbackEnabled = deliveryCallbackEnabled; - } - - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final String getApnCredentialSid() { - return this.apnCredentialSid; - } - - public final String getGcmCredentialSid() { - return this.gcmCredentialSid; - } - - public final String getFcmCredentialSid() { - return this.fcmCredentialSid; - } - - public final String getMessagingServiceSid() { - return this.messagingServiceSid; - } - - public final String getFacebookMessengerPageId() { - return this.facebookMessengerPageId; - } - - public final String getDefaultApnNotificationProtocolVersion() { - return this.defaultApnNotificationProtocolVersion; - } - - public final String getDefaultGcmNotificationProtocolVersion() { - return this.defaultGcmNotificationProtocolVersion; - } - - public final String getDefaultFcmNotificationProtocolVersion() { - return this.defaultFcmNotificationProtocolVersion; - } - - public final Boolean getLogEnabled() { - return this.logEnabled; - } - - public final URI getUrl() { - return this.url; - } - - public final Map getLinks() { - return this.links; - } - - public final String getAlexaSkillId() { - return this.alexaSkillId; - } - - public final String getDefaultAlexaNotificationProtocolVersion() { - return this.defaultAlexaNotificationProtocolVersion; - } - - public final String getDeliveryCallbackUrl() { - return this.deliveryCallbackUrl; - } - - public final Boolean getDeliveryCallbackEnabled() { - return this.deliveryCallbackEnabled; } @Override @@ -276,72 +224,56 @@ public boolean equals(final Object o) { } Service other = (Service) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(apnCredentialSid, other.apnCredentialSid) && - Objects.equals(gcmCredentialSid, other.gcmCredentialSid) && - Objects.equals(fcmCredentialSid, other.fcmCredentialSid) && - Objects.equals(messagingServiceSid, other.messagingServiceSid) && - Objects.equals( - facebookMessengerPageId, - other.facebookMessengerPageId - ) && - Objects.equals( - defaultApnNotificationProtocolVersion, - other.defaultApnNotificationProtocolVersion - ) && - Objects.equals( - defaultGcmNotificationProtocolVersion, - other.defaultGcmNotificationProtocolVersion - ) && - Objects.equals( - defaultFcmNotificationProtocolVersion, - other.defaultFcmNotificationProtocolVersion - ) && - Objects.equals(logEnabled, other.logEnabled) && - Objects.equals(url, other.url) && - Objects.equals(links, other.links) && - Objects.equals(alexaSkillId, other.alexaSkillId) && - Objects.equals( - defaultAlexaNotificationProtocolVersion, - other.defaultAlexaNotificationProtocolVersion - ) && - Objects.equals(deliveryCallbackUrl, other.deliveryCallbackUrl) && - Objects.equals( - deliveryCallbackEnabled, - other.deliveryCallbackEnabled - ) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(alexaSkillId, other.alexaSkillId) && + Objects.equals(apnCredentialSid, other.apnCredentialSid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(defaultAlexaNotificationProtocolVersion, other.defaultAlexaNotificationProtocolVersion) && + Objects.equals(defaultApnNotificationProtocolVersion, other.defaultApnNotificationProtocolVersion) && + Objects.equals(defaultFcmNotificationProtocolVersion, other.defaultFcmNotificationProtocolVersion) && + Objects.equals(defaultGcmNotificationProtocolVersion, other.defaultGcmNotificationProtocolVersion) && + Objects.equals(deliveryCallbackEnabled, other.deliveryCallbackEnabled) && + Objects.equals(deliveryCallbackUrl, other.deliveryCallbackUrl) && + Objects.equals(facebookMessengerPageId, other.facebookMessengerPageId) && + Objects.equals(fcmCredentialSid, other.fcmCredentialSid) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(gcmCredentialSid, other.gcmCredentialSid) && + Objects.equals(links, other.links) && + Objects.equals(logEnabled, other.logEnabled) && + Objects.equals(messagingServiceSid, other.messagingServiceSid) && + Objects.equals(sid, other.sid) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - sid, - accountSid, - friendlyName, - dateCreated, - dateUpdated, - apnCredentialSid, - gcmCredentialSid, - fcmCredentialSid, - messagingServiceSid, - facebookMessengerPageId, - defaultApnNotificationProtocolVersion, - defaultGcmNotificationProtocolVersion, - defaultFcmNotificationProtocolVersion, - logEnabled, - url, - links, - alexaSkillId, - defaultAlexaNotificationProtocolVersion, - deliveryCallbackUrl, - deliveryCallbackEnabled + accountSid, + alexaSkillId, + apnCredentialSid, + dateCreated, + dateUpdated, + defaultAlexaNotificationProtocolVersion, + defaultApnNotificationProtocolVersion, + defaultFcmNotificationProtocolVersion, + defaultGcmNotificationProtocolVersion, + deliveryCallbackEnabled, + deliveryCallbackUrl, + facebookMessengerPageId, + fcmCredentialSid, + friendlyName, + gcmCredentialSid, + links, + logEnabled, + messagingServiceSid, + sid, + url ); } + + } + diff --git a/src/main/java/com/twilio/rest/notify/v1/ServiceCreator.java b/src/main/java/com/twilio/rest/notify/v1/ServiceCreator.java index 5abcfa01f6..93341dba91 100644 --- a/src/main/java/com/twilio/rest/notify/v1/ServiceCreator.java +++ b/src/main/java/com/twilio/rest/notify/v1/ServiceCreator.java @@ -14,8 +14,11 @@ package com.twilio.rest.notify.v1; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -42,124 +45,119 @@ public class ServiceCreator extends Creator { private String deliveryCallbackUrl; private Boolean deliveryCallbackEnabled; - public ServiceCreator() {} + public ServiceCreator() { + } + public ServiceCreator setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + public ServiceCreator setApnCredentialSid(final String apnCredentialSid) { this.apnCredentialSid = apnCredentialSid; return this; } + public ServiceCreator setGcmCredentialSid(final String gcmCredentialSid) { this.gcmCredentialSid = gcmCredentialSid; return this; } - public ServiceCreator setMessagingServiceSid( - final String messagingServiceSid - ) { + + public ServiceCreator setMessagingServiceSid(final String messagingServiceSid) { this.messagingServiceSid = messagingServiceSid; return this; } - public ServiceCreator setFacebookMessengerPageId( - final String facebookMessengerPageId - ) { + + public ServiceCreator setFacebookMessengerPageId(final String facebookMessengerPageId) { this.facebookMessengerPageId = facebookMessengerPageId; return this; } - public ServiceCreator setDefaultApnNotificationProtocolVersion( - final String defaultApnNotificationProtocolVersion - ) { - this.defaultApnNotificationProtocolVersion = - defaultApnNotificationProtocolVersion; + + public ServiceCreator setDefaultApnNotificationProtocolVersion(final String defaultApnNotificationProtocolVersion) { + this.defaultApnNotificationProtocolVersion = defaultApnNotificationProtocolVersion; return this; } - public ServiceCreator setDefaultGcmNotificationProtocolVersion( - final String defaultGcmNotificationProtocolVersion - ) { - this.defaultGcmNotificationProtocolVersion = - defaultGcmNotificationProtocolVersion; + + public ServiceCreator setDefaultGcmNotificationProtocolVersion(final String defaultGcmNotificationProtocolVersion) { + this.defaultGcmNotificationProtocolVersion = defaultGcmNotificationProtocolVersion; return this; } + public ServiceCreator setFcmCredentialSid(final String fcmCredentialSid) { this.fcmCredentialSid = fcmCredentialSid; return this; } - public ServiceCreator setDefaultFcmNotificationProtocolVersion( - final String defaultFcmNotificationProtocolVersion - ) { - this.defaultFcmNotificationProtocolVersion = - defaultFcmNotificationProtocolVersion; + + public ServiceCreator setDefaultFcmNotificationProtocolVersion(final String defaultFcmNotificationProtocolVersion) { + this.defaultFcmNotificationProtocolVersion = defaultFcmNotificationProtocolVersion; return this; } + public ServiceCreator setLogEnabled(final Boolean logEnabled) { this.logEnabled = logEnabled; return this; } + public ServiceCreator setAlexaSkillId(final String alexaSkillId) { this.alexaSkillId = alexaSkillId; return this; } - public ServiceCreator setDefaultAlexaNotificationProtocolVersion( - final String defaultAlexaNotificationProtocolVersion - ) { - this.defaultAlexaNotificationProtocolVersion = - defaultAlexaNotificationProtocolVersion; + + public ServiceCreator setDefaultAlexaNotificationProtocolVersion(final String defaultAlexaNotificationProtocolVersion) { + this.defaultAlexaNotificationProtocolVersion = defaultAlexaNotificationProtocolVersion; return this; } - public ServiceCreator setDeliveryCallbackUrl( - final String deliveryCallbackUrl - ) { + + public ServiceCreator setDeliveryCallbackUrl(final String deliveryCallbackUrl) { this.deliveryCallbackUrl = deliveryCallbackUrl; return this; } - public ServiceCreator setDeliveryCallbackEnabled( - final Boolean deliveryCallbackEnabled - ) { + + public ServiceCreator setDeliveryCallbackEnabled(final Boolean deliveryCallbackEnabled) { this.deliveryCallbackEnabled = deliveryCallbackEnabled; return this; } + @Override public Service create(final TwilioRestClient client) { + String path = "/v1/Services"; + Request request = new Request( - HttpMethod.POST, - Domains.NOTIFY.toString(), - path + HttpMethod.POST, + Domains.NOTIFY.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Service creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("Service creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -168,65 +166,76 @@ public Service create(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + if (apnCredentialSid != null) { - request.addPostParam("ApnCredentialSid", apnCredentialSid); + Serializer.toString(request, "ApnCredentialSid", apnCredentialSid, ParameterType.URLENCODED); } + + if (gcmCredentialSid != null) { - request.addPostParam("GcmCredentialSid", gcmCredentialSid); + Serializer.toString(request, "GcmCredentialSid", gcmCredentialSid, ParameterType.URLENCODED); } + + if (messagingServiceSid != null) { - request.addPostParam("MessagingServiceSid", messagingServiceSid); + Serializer.toString(request, "MessagingServiceSid", messagingServiceSid, ParameterType.URLENCODED); } + + if (facebookMessengerPageId != null) { - request.addPostParam( - "FacebookMessengerPageId", - facebookMessengerPageId - ); + Serializer.toString(request, "FacebookMessengerPageId", facebookMessengerPageId, ParameterType.URLENCODED); } + + if (defaultApnNotificationProtocolVersion != null) { - request.addPostParam( - "DefaultApnNotificationProtocolVersion", - defaultApnNotificationProtocolVersion - ); + Serializer.toString(request, "DefaultApnNotificationProtocolVersion", defaultApnNotificationProtocolVersion, ParameterType.URLENCODED); } + + if (defaultGcmNotificationProtocolVersion != null) { - request.addPostParam( - "DefaultGcmNotificationProtocolVersion", - defaultGcmNotificationProtocolVersion - ); + Serializer.toString(request, "DefaultGcmNotificationProtocolVersion", defaultGcmNotificationProtocolVersion, ParameterType.URLENCODED); } + + if (fcmCredentialSid != null) { - request.addPostParam("FcmCredentialSid", fcmCredentialSid); + Serializer.toString(request, "FcmCredentialSid", fcmCredentialSid, ParameterType.URLENCODED); } + + if (defaultFcmNotificationProtocolVersion != null) { - request.addPostParam( - "DefaultFcmNotificationProtocolVersion", - defaultFcmNotificationProtocolVersion - ); + Serializer.toString(request, "DefaultFcmNotificationProtocolVersion", defaultFcmNotificationProtocolVersion, ParameterType.URLENCODED); } + + if (logEnabled != null) { - request.addPostParam("LogEnabled", logEnabled.toString()); + Serializer.toString(request, "LogEnabled", logEnabled, ParameterType.URLENCODED); } + + if (alexaSkillId != null) { - request.addPostParam("AlexaSkillId", alexaSkillId); + Serializer.toString(request, "AlexaSkillId", alexaSkillId, ParameterType.URLENCODED); } + + if (defaultAlexaNotificationProtocolVersion != null) { - request.addPostParam( - "DefaultAlexaNotificationProtocolVersion", - defaultAlexaNotificationProtocolVersion - ); + Serializer.toString(request, "DefaultAlexaNotificationProtocolVersion", defaultAlexaNotificationProtocolVersion, ParameterType.URLENCODED); } + + if (deliveryCallbackUrl != null) { - request.addPostParam("DeliveryCallbackUrl", deliveryCallbackUrl); + Serializer.toString(request, "DeliveryCallbackUrl", deliveryCallbackUrl, ParameterType.URLENCODED); } + + if (deliveryCallbackEnabled != null) { - request.addPostParam( - "DeliveryCallbackEnabled", - deliveryCallbackEnabled.toString() - ); + Serializer.toString(request, "DeliveryCallbackEnabled", deliveryCallbackEnabled, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/notify/v1/ServiceDeleter.java b/src/main/java/com/twilio/rest/notify/v1/ServiceDeleter.java index 47243575b9..740436652b 100644 --- a/src/main/java/com/twilio/rest/notify/v1/ServiceDeleter.java +++ b/src/main/java/com/twilio/rest/notify/v1/ServiceDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.notify.v1; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,40 +26,38 @@ public class ServiceDeleter extends Deleter { - private String pathSid; + private String pathsid; - public ServiceDeleter(final String pathSid) { - this.pathSid = pathSid; + public ServiceDeleter(final String pathsid) { + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/v1/Services/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.NOTIFY.toString(), - path + HttpMethod.DELETE, + Domains.NOTIFY.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Service delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("Service delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/notify/v1/ServiceFetcher.java b/src/main/java/com/twilio/rest/notify/v1/ServiceFetcher.java index 9c6d391e2d..bab0f9fb3e 100644 --- a/src/main/java/com/twilio/rest/notify/v1/ServiceFetcher.java +++ b/src/main/java/com/twilio/rest/notify/v1/ServiceFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.notify.v1; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,44 +26,41 @@ public class ServiceFetcher extends Fetcher { - private String pathSid; + private String pathsid; - public ServiceFetcher(final String pathSid) { - this.pathSid = pathSid; + public ServiceFetcher(final String pathsid) { + this.pathsid = pathsid; } + @Override public Service fetch(final TwilioRestClient client) { + String path = "/v1/Services/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.NOTIFY.toString(), - path + HttpMethod.GET, + Domains.NOTIFY.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Service fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Service fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Service.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/notify/v1/ServiceReader.java b/src/main/java/com/twilio/rest/notify/v1/ServiceReader.java index 6b99081307..562ddfa7e9 100644 --- a/src/main/java/com/twilio/rest/notify/v1/ServiceReader.java +++ b/src/main/java/com/twilio/rest/notify/v1/ServiceReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -32,113 +33,94 @@ public class ServiceReader extends Reader { private String friendlyName; private Long pageSize; - public ServiceReader() {} + public ServiceReader() { + } + public ServiceReader setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + public ServiceReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/Services"; + Request request = new Request( - HttpMethod.GET, - Domains.NOTIFY.toString(), - path + HttpMethod.GET, + Domains.NOTIFY.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Service read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Service read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "services", - response.getContent(), - Service.class, - client.getObjectMapper() - ); + "services", + response.getContent(), + Service.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.NOTIFY.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.NOTIFY.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (friendlyName != null) { - request.addQueryParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.QUERY); } + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/notify/v1/ServiceUpdater.java b/src/main/java/com/twilio/rest/notify/v1/ServiceUpdater.java index 2a44b867c6..95fbc50fcf 100644 --- a/src/main/java/com/twilio/rest/notify/v1/ServiceUpdater.java +++ b/src/main/java/com/twilio/rest/notify/v1/ServiceUpdater.java @@ -16,6 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -26,8 +28,7 @@ import com.twilio.rest.Domains; public class ServiceUpdater extends Updater { - - private String pathSid; + private String pathsid; private String friendlyName; private String apnCredentialSid; private String gcmCredentialSid; @@ -43,128 +44,122 @@ public class ServiceUpdater extends Updater { private String deliveryCallbackUrl; private Boolean deliveryCallbackEnabled; - public ServiceUpdater(final String pathSid) { - this.pathSid = pathSid; + public ServiceUpdater(final String pathsid) { + this.pathsid = pathsid; } + public ServiceUpdater setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + public ServiceUpdater setApnCredentialSid(final String apnCredentialSid) { this.apnCredentialSid = apnCredentialSid; return this; } + public ServiceUpdater setGcmCredentialSid(final String gcmCredentialSid) { this.gcmCredentialSid = gcmCredentialSid; return this; } - public ServiceUpdater setMessagingServiceSid( - final String messagingServiceSid - ) { + + public ServiceUpdater setMessagingServiceSid(final String messagingServiceSid) { this.messagingServiceSid = messagingServiceSid; return this; } - public ServiceUpdater setFacebookMessengerPageId( - final String facebookMessengerPageId - ) { + + public ServiceUpdater setFacebookMessengerPageId(final String facebookMessengerPageId) { this.facebookMessengerPageId = facebookMessengerPageId; return this; } - public ServiceUpdater setDefaultApnNotificationProtocolVersion( - final String defaultApnNotificationProtocolVersion - ) { - this.defaultApnNotificationProtocolVersion = - defaultApnNotificationProtocolVersion; + + public ServiceUpdater setDefaultApnNotificationProtocolVersion(final String defaultApnNotificationProtocolVersion) { + this.defaultApnNotificationProtocolVersion = defaultApnNotificationProtocolVersion; return this; } - public ServiceUpdater setDefaultGcmNotificationProtocolVersion( - final String defaultGcmNotificationProtocolVersion - ) { - this.defaultGcmNotificationProtocolVersion = - defaultGcmNotificationProtocolVersion; + + public ServiceUpdater setDefaultGcmNotificationProtocolVersion(final String defaultGcmNotificationProtocolVersion) { + this.defaultGcmNotificationProtocolVersion = defaultGcmNotificationProtocolVersion; return this; } + public ServiceUpdater setFcmCredentialSid(final String fcmCredentialSid) { this.fcmCredentialSid = fcmCredentialSid; return this; } - public ServiceUpdater setDefaultFcmNotificationProtocolVersion( - final String defaultFcmNotificationProtocolVersion - ) { - this.defaultFcmNotificationProtocolVersion = - defaultFcmNotificationProtocolVersion; + + public ServiceUpdater setDefaultFcmNotificationProtocolVersion(final String defaultFcmNotificationProtocolVersion) { + this.defaultFcmNotificationProtocolVersion = defaultFcmNotificationProtocolVersion; return this; } + public ServiceUpdater setLogEnabled(final Boolean logEnabled) { this.logEnabled = logEnabled; return this; } + public ServiceUpdater setAlexaSkillId(final String alexaSkillId) { this.alexaSkillId = alexaSkillId; return this; } - public ServiceUpdater setDefaultAlexaNotificationProtocolVersion( - final String defaultAlexaNotificationProtocolVersion - ) { - this.defaultAlexaNotificationProtocolVersion = - defaultAlexaNotificationProtocolVersion; + + public ServiceUpdater setDefaultAlexaNotificationProtocolVersion(final String defaultAlexaNotificationProtocolVersion) { + this.defaultAlexaNotificationProtocolVersion = defaultAlexaNotificationProtocolVersion; return this; } - public ServiceUpdater setDeliveryCallbackUrl( - final String deliveryCallbackUrl - ) { + + public ServiceUpdater setDeliveryCallbackUrl(final String deliveryCallbackUrl) { this.deliveryCallbackUrl = deliveryCallbackUrl; return this; } - public ServiceUpdater setDeliveryCallbackEnabled( - final Boolean deliveryCallbackEnabled - ) { + + public ServiceUpdater setDeliveryCallbackEnabled(final Boolean deliveryCallbackEnabled) { this.deliveryCallbackEnabled = deliveryCallbackEnabled; return this; } + @Override public Service update(final TwilioRestClient client) { + String path = "/v1/Services/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.NOTIFY.toString(), - path + HttpMethod.POST, + Domains.NOTIFY.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Service update failed: Unable to connect to server" - ); + throw new ApiConnectionException("Service update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -173,65 +168,76 @@ public Service update(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + if (apnCredentialSid != null) { - request.addPostParam("ApnCredentialSid", apnCredentialSid); + Serializer.toString(request, "ApnCredentialSid", apnCredentialSid, ParameterType.URLENCODED); } + + if (gcmCredentialSid != null) { - request.addPostParam("GcmCredentialSid", gcmCredentialSid); + Serializer.toString(request, "GcmCredentialSid", gcmCredentialSid, ParameterType.URLENCODED); } + + if (messagingServiceSid != null) { - request.addPostParam("MessagingServiceSid", messagingServiceSid); + Serializer.toString(request, "MessagingServiceSid", messagingServiceSid, ParameterType.URLENCODED); } + + if (facebookMessengerPageId != null) { - request.addPostParam( - "FacebookMessengerPageId", - facebookMessengerPageId - ); + Serializer.toString(request, "FacebookMessengerPageId", facebookMessengerPageId, ParameterType.URLENCODED); } + + if (defaultApnNotificationProtocolVersion != null) { - request.addPostParam( - "DefaultApnNotificationProtocolVersion", - defaultApnNotificationProtocolVersion - ); + Serializer.toString(request, "DefaultApnNotificationProtocolVersion", defaultApnNotificationProtocolVersion, ParameterType.URLENCODED); } + + if (defaultGcmNotificationProtocolVersion != null) { - request.addPostParam( - "DefaultGcmNotificationProtocolVersion", - defaultGcmNotificationProtocolVersion - ); + Serializer.toString(request, "DefaultGcmNotificationProtocolVersion", defaultGcmNotificationProtocolVersion, ParameterType.URLENCODED); } + + if (fcmCredentialSid != null) { - request.addPostParam("FcmCredentialSid", fcmCredentialSid); + Serializer.toString(request, "FcmCredentialSid", fcmCredentialSid, ParameterType.URLENCODED); } + + if (defaultFcmNotificationProtocolVersion != null) { - request.addPostParam( - "DefaultFcmNotificationProtocolVersion", - defaultFcmNotificationProtocolVersion - ); + Serializer.toString(request, "DefaultFcmNotificationProtocolVersion", defaultFcmNotificationProtocolVersion, ParameterType.URLENCODED); } + + if (logEnabled != null) { - request.addPostParam("LogEnabled", logEnabled.toString()); + Serializer.toString(request, "LogEnabled", logEnabled, ParameterType.URLENCODED); } + + if (alexaSkillId != null) { - request.addPostParam("AlexaSkillId", alexaSkillId); + Serializer.toString(request, "AlexaSkillId", alexaSkillId, ParameterType.URLENCODED); } + + if (defaultAlexaNotificationProtocolVersion != null) { - request.addPostParam( - "DefaultAlexaNotificationProtocolVersion", - defaultAlexaNotificationProtocolVersion - ); + Serializer.toString(request, "DefaultAlexaNotificationProtocolVersion", defaultAlexaNotificationProtocolVersion, ParameterType.URLENCODED); } + + if (deliveryCallbackUrl != null) { - request.addPostParam("DeliveryCallbackUrl", deliveryCallbackUrl); + Serializer.toString(request, "DeliveryCallbackUrl", deliveryCallbackUrl, ParameterType.URLENCODED); } + + if (deliveryCallbackEnabled != null) { - request.addPostParam( - "DeliveryCallbackEnabled", - deliveryCallbackEnabled.toString() - ); + Serializer.toString(request, "DeliveryCallbackEnabled", deliveryCallbackEnabled, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/notify/v1/service/Binding.java b/src/main/java/com/twilio/rest/notify/v1/service/Binding.java index a61e6c16e0..ebf40df41c 100644 --- a/src/main/java/com/twilio/rest/notify/v1/service/Binding.java +++ b/src/main/java/com/twilio/rest/notify/v1/service/Binding.java @@ -18,73 +18,91 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.List; import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Binding extends Resource { - private static final long serialVersionUID = 204710880064403L; - public static BindingCreator creator( - final String pathServiceSid, - final String identity, - final Binding.BindingType bindingType, - final String address - ) { + public static BindingCreator creator(final String pathserviceSid, final String identity, final Binding.BindingType bindingType, final String address) { return new BindingCreator( - pathServiceSid, - identity, - bindingType, - address + pathserviceSid, identity, bindingType, address ); } - public static BindingDeleter deleter( - final String pathServiceSid, - final String pathSid - ) { - return new BindingDeleter(pathServiceSid, pathSid); + + public static BindingDeleter deleter(final String pathserviceSid, final String pathsid) { + return new BindingDeleter( + pathserviceSid, pathsid + ); } - public static BindingFetcher fetcher( - final String pathServiceSid, - final String pathSid - ) { - return new BindingFetcher(pathServiceSid, pathSid); + + public static BindingFetcher fetcher(final String pathserviceSid, final String pathsid) { + return new BindingFetcher( + pathserviceSid, pathsid + ); } - public static BindingReader reader(final String pathServiceSid) { - return new BindingReader(pathServiceSid); + + public static BindingReader reader(final String pathserviceSid) { + return new BindingReader( + pathserviceSid + ); } + + public enum BindingType { + APN("apn"), + GCM("gcm"), + SMS("sms"), + FCM("fcm"), + FACEBOOK_MESSENGER("facebook-messenger"), + ALEXA("alexa"); + + private final String value; + + private BindingType(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static BindingType forValue(final String value) { + return Promoter.enumFromString(value, BindingType.values()); + } + } + + /** * Converts a JSON String into a Binding object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Binding object represented by the provided JSON */ - public static Binding fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Binding fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Binding.class); @@ -99,14 +117,11 @@ public static Binding fromJson( * Converts a JSON InputStream into a Binding object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Binding object represented by the provided JSON */ - public static Binding fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Binding fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Binding.class); @@ -117,110 +132,81 @@ public static Binding fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String serviceSid; + @Getter + private final String address; + @Getter + private final String bindingType; + @Getter private final String credentialSid; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; - private final String notificationProtocolVersion; + @Getter private final String endpoint; + @Getter private final String identity; - private final String bindingType; - private final String address; + @Getter + private final Map links; + @Getter + private final String notificationProtocolVersion; + @Getter + private final String serviceSid; + @Getter + private final String sid; + @Getter private final List tags; + @Getter private final URI url; - private final Map links; @JsonCreator private Binding( - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("service_sid") final String serviceSid, - @JsonProperty("credential_sid") final String credentialSid, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty( - "notification_protocol_version" - ) final String notificationProtocolVersion, - @JsonProperty("endpoint") final String endpoint, - @JsonProperty("identity") final String identity, - @JsonProperty("binding_type") final String bindingType, - @JsonProperty("address") final String address, - @JsonProperty("tags") final List tags, - @JsonProperty("url") final URI url, - @JsonProperty("links") final Map links + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("address") final String address, + @JsonProperty("binding_type") final String bindingType, + @JsonProperty("credential_sid") final String credentialSid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("endpoint") final String endpoint, + @JsonProperty("identity") final String identity, + @JsonProperty("links") final Map links, + @JsonProperty("notification_protocol_version") final String notificationProtocolVersion, + @JsonProperty("service_sid") final String serviceSid, + @JsonProperty("sid") final String sid, + @JsonProperty("tags") final List tags, + @JsonProperty("url") final URI url ) { - this.sid = sid; this.accountSid = accountSid; - this.serviceSid = serviceSid; + this.address = address; + this.bindingType = bindingType; this.credentialSid = credentialSid; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); - this.notificationProtocolVersion = notificationProtocolVersion; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.endpoint = endpoint; this.identity = identity; - this.bindingType = bindingType; - this.address = address; + this.links = links; + this.notificationProtocolVersion = notificationProtocolVersion; + this.serviceSid = serviceSid; + this.sid = sid; this.tags = tags; this.url = url; - this.links = links; - } - - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getServiceSid() { - return this.serviceSid; - } - - public final String getCredentialSid() { - return this.credentialSid; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final String getNotificationProtocolVersion() { - return this.notificationProtocolVersion; - } - - public final String getEndpoint() { - return this.endpoint; - } - - public final String getIdentity() { - return this.identity; - } - - public final String getBindingType() { - return this.bindingType; - } - - public final String getAddress() { - return this.address; - } - - public final List getTags() { - return this.tags; - } - - public final URI getUrl() { - return this.url; - } - - public final Map getLinks() { - return this.links; } @Override @@ -234,69 +220,44 @@ public boolean equals(final Object o) { } Binding other = (Binding) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(serviceSid, other.serviceSid) && - Objects.equals(credentialSid, other.credentialSid) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals( - notificationProtocolVersion, - other.notificationProtocolVersion - ) && - Objects.equals(endpoint, other.endpoint) && - Objects.equals(identity, other.identity) && - Objects.equals(bindingType, other.bindingType) && - Objects.equals(address, other.address) && - Objects.equals(tags, other.tags) && - Objects.equals(url, other.url) && - Objects.equals(links, other.links) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(address, other.address) && + Objects.equals(bindingType, other.bindingType) && + Objects.equals(credentialSid, other.credentialSid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(endpoint, other.endpoint) && + Objects.equals(identity, other.identity) && + Objects.equals(links, other.links) && + Objects.equals(notificationProtocolVersion, other.notificationProtocolVersion) && + Objects.equals(serviceSid, other.serviceSid) && + Objects.equals(sid, other.sid) && + Objects.equals(tags, other.tags) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - sid, - accountSid, - serviceSid, - credentialSid, - dateCreated, - dateUpdated, - notificationProtocolVersion, - endpoint, - identity, - bindingType, - address, - tags, - url, - links + accountSid, + address, + bindingType, + credentialSid, + dateCreated, + dateUpdated, + endpoint, + identity, + links, + notificationProtocolVersion, + serviceSid, + sid, + tags, + url ); } - public enum BindingType { - APN("apn"), - GCM("gcm"), - SMS("sms"), - FCM("fcm"), - FACEBOOK_MESSENGER("facebook-messenger"), - ALEXA("alexa"); - - private final String value; - - private BindingType(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - @JsonCreator - public static BindingType forValue(final String value) { - return Promoter.enumFromString(value, BindingType.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/notify/v1/service/BindingCreator.java b/src/main/java/com/twilio/rest/notify/v1/service/BindingCreator.java index fd4d9aa671..bd970d1843 100644 --- a/src/main/java/com/twilio/rest/notify/v1/service/BindingCreator.java +++ b/src/main/java/com/twilio/rest/notify/v1/service/BindingCreator.java @@ -14,9 +14,12 @@ package com.twilio.rest.notify.v1.service; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; import com.twilio.converter.Promoter; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,12 +28,12 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -import java.util.List; + import java.util.List; public class BindingCreator extends Creator { - private String pathServiceSid; + private String pathserviceSid; private String identity; private Binding.BindingType bindingType; private String address; @@ -39,35 +42,32 @@ public class BindingCreator extends Creator { private String credentialSid; private String endpoint; - public BindingCreator( - final String pathServiceSid, - final String identity, - final Binding.BindingType bindingType, - final String address - ) { - this.pathServiceSid = pathServiceSid; + public BindingCreator(final String pathserviceSid, final String identity, final Binding.BindingType bindingType, final String address) { + this.pathserviceSid = pathserviceSid; this.identity = identity; this.bindingType = bindingType; this.address = address; } + public BindingCreator setIdentity(final String identity) { this.identity = identity; return this; } - public BindingCreator setBindingType( - final Binding.BindingType bindingType - ) { + + public BindingCreator setBindingType(final Binding.BindingType bindingType) { this.bindingType = bindingType; return this; } + public BindingCreator setAddress(final String address) { this.address = address; return this; } + public BindingCreator setTag(final List tag) { this.tag = tag; return this; @@ -77,62 +77,51 @@ public BindingCreator setTag(final String tag) { return setTag(Promoter.listOfOne(tag)); } - public BindingCreator setNotificationProtocolVersion( - final String notificationProtocolVersion - ) { + public BindingCreator setNotificationProtocolVersion(final String notificationProtocolVersion) { this.notificationProtocolVersion = notificationProtocolVersion; return this; } + public BindingCreator setCredentialSid(final String credentialSid) { this.credentialSid = credentialSid; return this; } + public BindingCreator setEndpoint(final String endpoint) { this.endpoint = endpoint; return this; } + @Override public Binding create(final TwilioRestClient client) { + String path = "/v1/Services/{ServiceSid}/Bindings"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = path.replace("{" + "Identity" + "}", this.identity.toString()); - path = - path.replace( - "{" + "BindingType" + "}", - this.bindingType.toString() - ); - path = path.replace("{" + "Address" + "}", this.address.toString()); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.NOTIFY.toString(), - path + HttpMethod.POST, + Domains.NOTIFY.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Binding creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("Binding creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -141,31 +130,43 @@ public Binding create(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (identity != null) { - request.addPostParam("Identity", identity); + Serializer.toString(request, "Identity", identity, ParameterType.URLENCODED); } + + if (bindingType != null) { - request.addPostParam("BindingType", bindingType.toString()); + Serializer.toString(request, "BindingType", bindingType, ParameterType.URLENCODED); } + + if (address != null) { - request.addPostParam("Address", address); + Serializer.toString(request, "Address", address, ParameterType.URLENCODED); } + + if (tag != null) { - for (String prop : tag) { - request.addPostParam("Tag", prop); + for (String param : tag) { + Serializer.toString(request, "Tag", param, ParameterType.URLENCODED); } } + + if (notificationProtocolVersion != null) { - request.addPostParam( - "NotificationProtocolVersion", - notificationProtocolVersion - ); + Serializer.toString(request, "NotificationProtocolVersion", notificationProtocolVersion, ParameterType.URLENCODED); } + + if (credentialSid != null) { - request.addPostParam("CredentialSid", credentialSid); + Serializer.toString(request, "CredentialSid", credentialSid, ParameterType.URLENCODED); } + + if (endpoint != null) { - request.addPostParam("Endpoint", endpoint); + Serializer.toString(request, "Endpoint", endpoint, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/notify/v1/service/BindingDeleter.java b/src/main/java/com/twilio/rest/notify/v1/service/BindingDeleter.java index 5257f5e50c..841ce9d4ba 100644 --- a/src/main/java/com/twilio/rest/notify/v1/service/BindingDeleter.java +++ b/src/main/java/com/twilio/rest/notify/v1/service/BindingDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.notify.v1.service; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,47 +26,41 @@ public class BindingDeleter extends Deleter { - private String pathServiceSid; - private String pathSid; + private String pathserviceSid; + private String pathsid; - public BindingDeleter(final String pathServiceSid, final String pathSid) { - this.pathServiceSid = pathServiceSid; - this.pathSid = pathSid; + public BindingDeleter(final String pathserviceSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/v1/Services/{ServiceSid}/Bindings/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.NOTIFY.toString(), - path + HttpMethod.DELETE, + Domains.NOTIFY.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Binding delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("Binding delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/notify/v1/service/BindingFetcher.java b/src/main/java/com/twilio/rest/notify/v1/service/BindingFetcher.java index ef3d17b718..cb44c4b12a 100644 --- a/src/main/java/com/twilio/rest/notify/v1/service/BindingFetcher.java +++ b/src/main/java/com/twilio/rest/notify/v1/service/BindingFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.notify.v1.service; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,51 +26,44 @@ public class BindingFetcher extends Fetcher { - private String pathServiceSid; - private String pathSid; + private String pathserviceSid; + private String pathsid; - public BindingFetcher(final String pathServiceSid, final String pathSid) { - this.pathServiceSid = pathServiceSid; - this.pathSid = pathSid; + public BindingFetcher(final String pathserviceSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathsid = pathsid; } + @Override public Binding fetch(final TwilioRestClient client) { + String path = "/v1/Services/{ServiceSid}/Bindings/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.NOTIFY.toString(), - path + HttpMethod.GET, + Domains.NOTIFY.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Binding fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Binding fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Binding.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/notify/v1/service/BindingReader.java b/src/main/java/com/twilio/rest/notify/v1/service/BindingReader.java index b05d07150b..e081eee49d 100644 --- a/src/main/java/com/twilio/rest/notify/v1/service/BindingReader.java +++ b/src/main/java/com/twilio/rest/notify/v1/service/BindingReader.java @@ -17,9 +17,9 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; -import com.twilio.converter.DateConverter; +import com.twilio.constant.EnumConstants.ParameterType; import com.twilio.converter.Promoter; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -28,32 +28,36 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.time.LocalDate; import java.util.List; public class BindingReader extends Reader { - private String pathServiceSid; + private String pathserviceSid; private LocalDate startDate; private LocalDate endDate; private List identity; private List tag; private Long pageSize; - public BindingReader(final String pathServiceSid) { - this.pathServiceSid = pathServiceSid; + public BindingReader(final String pathserviceSid) { + this.pathserviceSid = pathserviceSid; } + public BindingReader setStartDate(final LocalDate startDate) { this.startDate = startDate; return this; } + public BindingReader setEndDate(final LocalDate endDate) { this.endDate = endDate; return this; } + public BindingReader setIdentity(final List identity) { this.identity = identity; return this; @@ -77,127 +81,99 @@ public BindingReader setPageSize(final Long pageSize) { return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/Services/{ServiceSid}/Bindings"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.NOTIFY.toString(), - path + HttpMethod.GET, + Domains.NOTIFY.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Binding read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Binding read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "bindings", - response.getContent(), - Binding.class, - client.getObjectMapper() - ); + "bindings", + response.getContent(), + Binding.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.NOTIFY.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.NOTIFY.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (startDate != null) { - request.addQueryParam( - "StartDate", - DateConverter.dateStringFromLocalDate(startDate) - ); + Serializer.toString(request, "StartDate", startDate, ParameterType.QUERY); } + if (endDate != null) { - request.addQueryParam( - "EndDate", - DateConverter.dateStringFromLocalDate(endDate) - ); + Serializer.toString(request, "EndDate", endDate, ParameterType.QUERY); } + if (identity != null) { - for (String prop : identity) { - request.addQueryParam("Identity", prop); + for (String param : identity) { + Serializer.toString(request, "Identity", param, ParameterType.QUERY); } } + + if (tag != null) { - for (String prop : tag) { - request.addQueryParam("Tag", prop); + for (String param : tag) { + Serializer.toString(request, "Tag", param, ParameterType.QUERY); } } + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/notify/v1/service/Notification.java b/src/main/java/com/twilio/rest/notify/v1/service/Notification.java index 432641c6cb..1f66a0b5f3 100644 --- a/src/main/java/com/twilio/rest/notify/v1/service/Notification.java +++ b/src/main/java/com/twilio/rest/notify/v1/service/Notification.java @@ -18,44 +18,64 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.time.ZonedDateTime; import java.util.List; -import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Notification extends Resource { - private static final long serialVersionUID = 129411229878484L; - public static NotificationCreator creator(final String pathServiceSid) { - return new NotificationCreator(pathServiceSid); + public static NotificationCreator creator(final String pathserviceSid) { + return new NotificationCreator( + pathserviceSid + ); + } + + + public enum Priority { + HIGH("high"), + LOW("low"); + + private final String value; + + private Priority(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static Priority forValue(final String value) { + return Promoter.enumFromString(value, Priority.values()); + } } + /** * Converts a JSON String into a Notification object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Notification object represented by the provided JSON */ - public static Notification fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Notification fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Notification.class); @@ -70,14 +90,11 @@ public static Notification fromJson( * Converts a JSON InputStream into a Notification object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Notification object represented by the provided JSON */ - public static Notification fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Notification fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Notification.class); @@ -88,153 +105,104 @@ public static Notification fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String serviceSid; + @Getter + private final String action; + @Getter + private final Object alexa; + @Getter + private final Object apn; + @Getter + private final String body; + @Getter + private final Object data; + @Getter private final ZonedDateTime dateCreated; + @Getter + private final Object facebookMessenger; + @Getter + private final Object fcm; + @Getter + private final Object gcm; + @Getter private final List identities; - private final List tags; - private final List segments; + @Getter private final Notification.Priority priority; - private final Integer ttl; - private final String title; - private final String body; + @Getter + private final List segments; + @Getter + private final String serviceSid; + @Getter + private final String sid; + @Getter + private final Object sms; + @Getter private final String sound; - private final String action; - private final Map data; - private final Map apn; - private final Map gcm; - private final Map fcm; - private final Map sms; - private final Map facebookMessenger; - private final Map alexa; + @Getter + private final List tags; + @Getter + private final String title; + @Getter + private final Integer ttl; @JsonCreator private Notification( - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("service_sid") final String serviceSid, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("identities") final List identities, - @JsonProperty("tags") final List tags, - @JsonProperty("segments") final List segments, - @JsonProperty("priority") final Notification.Priority priority, - @JsonProperty("ttl") final Integer ttl, - @JsonProperty("title") final String title, - @JsonProperty("body") final String body, - @JsonProperty("sound") final String sound, - @JsonProperty("action") final String action, - @JsonProperty("data") final Map data, - @JsonProperty("apn") final Map apn, - @JsonProperty("gcm") final Map gcm, - @JsonProperty("fcm") final Map fcm, - @JsonProperty("sms") final Map sms, - @JsonProperty("facebook_messenger") final Map< - String, - Object - > facebookMessenger, - @JsonProperty("alexa") final Map alexa + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("action") final String action, + @JsonProperty("alexa") final Object alexa, + @JsonProperty("apn") final Object apn, + @JsonProperty("body") final String body, + @JsonProperty("data") final Object data, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("facebook_messenger") final Object facebookMessenger, + @JsonProperty("fcm") final Object fcm, + @JsonProperty("gcm") final Object gcm, + @JsonProperty("identities") final List identities, + @JsonProperty("priority") final Notification.Priority priority, + @JsonProperty("segments") final List segments, + @JsonProperty("service_sid") final String serviceSid, + @JsonProperty("sid") final String sid, + @JsonProperty("sms") final Object sms, + @JsonProperty("sound") final String sound, + @JsonProperty("tags") final List tags, + @JsonProperty("title") final String title, + @JsonProperty("ttl") final Integer ttl ) { - this.sid = sid; this.accountSid = accountSid; - this.serviceSid = serviceSid; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.identities = identities; - this.tags = tags; - this.segments = segments; - this.priority = priority; - this.ttl = ttl; - this.title = title; - this.body = body; - this.sound = sound; this.action = action; - this.data = data; + this.alexa = alexa; this.apn = apn; - this.gcm = gcm; + this.body = body; + this.data = data; + this.dateCreated = dateCreated; + this.facebookMessenger = facebookMessenger; this.fcm = fcm; + this.gcm = gcm; + this.identities = identities; + this.priority = priority; + this.segments = segments; + this.serviceSid = serviceSid; + this.sid = sid; this.sms = sms; - this.facebookMessenger = facebookMessenger; - this.alexa = alexa; - } - - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getServiceSid() { - return this.serviceSid; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final List getIdentities() { - return this.identities; - } - - public final List getTags() { - return this.tags; - } - - public final List getSegments() { - return this.segments; - } - - public final Notification.Priority getPriority() { - return this.priority; - } - - public final Integer getTtl() { - return this.ttl; - } - - public final String getTitle() { - return this.title; - } - - public final String getBody() { - return this.body; - } - - public final String getSound() { - return this.sound; - } - - public final String getAction() { - return this.action; - } - - public final Map getData() { - return this.data; - } - - public final Map getApn() { - return this.apn; - } - - public final Map getGcm() { - return this.gcm; - } - - public final Map getFcm() { - return this.fcm; - } - - public final Map getSms() { - return this.sms; - } - - public final Map getFacebookMessenger() { - return this.facebookMessenger; - } - - public final Map getAlexa() { - return this.alexa; + this.sound = sound; + this.tags = tags; + this.title = title; + this.ttl = ttl; } @Override @@ -248,74 +216,56 @@ public boolean equals(final Object o) { } Notification other = (Notification) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(serviceSid, other.serviceSid) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(identities, other.identities) && - Objects.equals(tags, other.tags) && - Objects.equals(segments, other.segments) && - Objects.equals(priority, other.priority) && - Objects.equals(ttl, other.ttl) && - Objects.equals(title, other.title) && - Objects.equals(body, other.body) && - Objects.equals(sound, other.sound) && - Objects.equals(action, other.action) && - Objects.equals(data, other.data) && - Objects.equals(apn, other.apn) && - Objects.equals(gcm, other.gcm) && - Objects.equals(fcm, other.fcm) && - Objects.equals(sms, other.sms) && - Objects.equals(facebookMessenger, other.facebookMessenger) && - Objects.equals(alexa, other.alexa) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(action, other.action) && + Objects.equals(alexa, other.alexa) && + Objects.equals(apn, other.apn) && + Objects.equals(body, other.body) && + Objects.equals(data, other.data) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(facebookMessenger, other.facebookMessenger) && + Objects.equals(fcm, other.fcm) && + Objects.equals(gcm, other.gcm) && + Objects.equals(identities, other.identities) && + Objects.equals(priority, other.priority) && + Objects.equals(segments, other.segments) && + Objects.equals(serviceSid, other.serviceSid) && + Objects.equals(sid, other.sid) && + Objects.equals(sms, other.sms) && + Objects.equals(sound, other.sound) && + Objects.equals(tags, other.tags) && + Objects.equals(title, other.title) && + Objects.equals(ttl, other.ttl) ); } @Override public int hashCode() { return Objects.hash( - sid, - accountSid, - serviceSid, - dateCreated, - identities, - tags, - segments, - priority, - ttl, - title, - body, - sound, - action, - data, - apn, - gcm, - fcm, - sms, - facebookMessenger, - alexa + accountSid, + action, + alexa, + apn, + body, + data, + dateCreated, + facebookMessenger, + fcm, + gcm, + identities, + priority, + segments, + serviceSid, + sid, + sms, + sound, + tags, + title, + ttl ); } - public enum Priority { - HIGH("high"), - LOW("low"); - - private final String value; - private Priority(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static Priority forValue(final String value) { - return Promoter.enumFromString(value, Priority.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/notify/v1/service/NotificationCreator.java b/src/main/java/com/twilio/rest/notify/v1/service/NotificationCreator.java index 249e0f9685..dda31b2171 100644 --- a/src/main/java/com/twilio/rest/notify/v1/service/NotificationCreator.java +++ b/src/main/java/com/twilio/rest/notify/v1/service/NotificationCreator.java @@ -14,11 +14,12 @@ package com.twilio.rest.notify.v1.service; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; -import com.twilio.converter.Converter; -import com.twilio.converter.Converter; +import com.twilio.constant.EnumConstants.ParameterType; import com.twilio.converter.Promoter; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,12 +28,12 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -import java.util.List; + import java.util.List; public class NotificationCreator extends Creator { - private String pathServiceSid; + private String pathserviceSid; private String body; private Notification.Priority priority; private Integer ttl; @@ -52,74 +53,83 @@ public class NotificationCreator extends Creator { private List identity; private List tag; - public NotificationCreator(final String pathServiceSid) { - this.pathServiceSid = pathServiceSid; + public NotificationCreator(final String pathserviceSid) { + this.pathserviceSid = pathserviceSid; } + public NotificationCreator setBody(final String body) { this.body = body; return this; } - public NotificationCreator setPriority( - final Notification.Priority priority - ) { + + public NotificationCreator setPriority(final Notification.Priority priority) { this.priority = priority; return this; } + public NotificationCreator setTtl(final Integer ttl) { this.ttl = ttl; return this; } + public NotificationCreator setTitle(final String title) { this.title = title; return this; } + public NotificationCreator setSound(final String sound) { this.sound = sound; return this; } + public NotificationCreator setAction(final String action) { this.action = action; return this; } + public NotificationCreator setData(final Object data) { this.data = data; return this; } + public NotificationCreator setApn(final Object apn) { this.apn = apn; return this; } + public NotificationCreator setGcm(final Object gcm) { this.gcm = gcm; return this; } + public NotificationCreator setSms(final Object sms) { this.sms = sms; return this; } - public NotificationCreator setFacebookMessenger( - final Object facebookMessenger - ) { + + public NotificationCreator setFacebookMessenger(final Object facebookMessenger) { this.facebookMessenger = facebookMessenger; return this; } + public NotificationCreator setFcm(final Object fcm) { this.fcm = fcm; return this; } + public NotificationCreator setSegment(final List segment) { this.segment = segment; return this; @@ -134,6 +144,7 @@ public NotificationCreator setAlexa(final Object alexa) { return this; } + public NotificationCreator setToBinding(final List toBinding) { this.toBinding = toBinding; return this; @@ -143,13 +154,12 @@ public NotificationCreator setToBinding(final String toBinding) { return setToBinding(Promoter.listOfOne(toBinding)); } - public NotificationCreator setDeliveryCallbackUrl( - final String deliveryCallbackUrl - ) { + public NotificationCreator setDeliveryCallbackUrl(final String deliveryCallbackUrl) { this.deliveryCallbackUrl = deliveryCallbackUrl; return this; } + public NotificationCreator setIdentity(final List identity) { this.identity = identity; return this; @@ -170,111 +180,136 @@ public NotificationCreator setTag(final String tag) { @Override public Notification create(final TwilioRestClient client) { + String path = "/v1/Services/{ServiceSid}/Notifications"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.NOTIFY.toString(), - path + HttpMethod.POST, + Domains.NOTIFY.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Notification creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("Notification creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Notification.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Notification.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (body != null) { - request.addPostParam("Body", body); + Serializer.toString(request, "Body", body, ParameterType.URLENCODED); } + + if (priority != null) { - request.addPostParam("Priority", priority.toString()); + Serializer.toString(request, "Priority", priority, ParameterType.URLENCODED); } + + if (ttl != null) { - request.addPostParam("Ttl", ttl.toString()); + Serializer.toString(request, "Ttl", ttl, ParameterType.URLENCODED); } + + if (title != null) { - request.addPostParam("Title", title); + Serializer.toString(request, "Title", title, ParameterType.URLENCODED); } + + if (sound != null) { - request.addPostParam("Sound", sound); + Serializer.toString(request, "Sound", sound, ParameterType.URLENCODED); } + + if (action != null) { - request.addPostParam("Action", action); + Serializer.toString(request, "Action", action, ParameterType.URLENCODED); } + + if (data != null) { - request.addPostParam("Data", Converter.objectToJson(data)); + Serializer.toString(request, "Data", data, ParameterType.URLENCODED); } + + if (apn != null) { - request.addPostParam("Apn", Converter.objectToJson(apn)); + Serializer.toString(request, "Apn", apn, ParameterType.URLENCODED); } + + if (gcm != null) { - request.addPostParam("Gcm", Converter.objectToJson(gcm)); + Serializer.toString(request, "Gcm", gcm, ParameterType.URLENCODED); } + + if (sms != null) { - request.addPostParam("Sms", Converter.objectToJson(sms)); + Serializer.toString(request, "Sms", sms, ParameterType.URLENCODED); } + + if (facebookMessenger != null) { - request.addPostParam( - "FacebookMessenger", - Converter.objectToJson(facebookMessenger) - ); + Serializer.toString(request, "FacebookMessenger", facebookMessenger, ParameterType.URLENCODED); } + + if (fcm != null) { - request.addPostParam("Fcm", Converter.objectToJson(fcm)); + Serializer.toString(request, "Fcm", fcm, ParameterType.URLENCODED); } + + if (segment != null) { - for (String prop : segment) { - request.addPostParam("Segment", prop); + for (String param : segment) { + Serializer.toString(request, "Segment", param, ParameterType.URLENCODED); } } + + if (alexa != null) { - request.addPostParam("Alexa", Converter.objectToJson(alexa)); + Serializer.toString(request, "Alexa", alexa, ParameterType.URLENCODED); } + + if (toBinding != null) { - for (String prop : toBinding) { - request.addPostParam("ToBinding", prop); + for (String param : toBinding) { + Serializer.toString(request, "ToBinding", param, ParameterType.URLENCODED); } } + + if (deliveryCallbackUrl != null) { - request.addPostParam("DeliveryCallbackUrl", deliveryCallbackUrl); + Serializer.toString(request, "DeliveryCallbackUrl", deliveryCallbackUrl, ParameterType.URLENCODED); } + + if (identity != null) { - for (String prop : identity) { - request.addPostParam("Identity", prop); + for (String param : identity) { + Serializer.toString(request, "Identity", param, ParameterType.URLENCODED); } } + + if (tag != null) { - for (String prop : tag) { - request.addPostParam("Tag", prop); + for (String param : tag) { + Serializer.toString(request, "Tag", param, ParameterType.URLENCODED); } } + } } diff --git a/src/main/java/com/twilio/rest/numbers/v1/BulkEligibility.java b/src/main/java/com/twilio/rest/numbers/v1/BulkEligibility.java index d9007ef8c7..a21f36d70f 100644 --- a/src/main/java/com/twilio/rest/numbers/v1/BulkEligibility.java +++ b/src/main/java/com/twilio/rest/numbers/v1/BulkEligibility.java @@ -21,46 +21,47 @@ import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.List; -import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class BulkEligibility extends Resource { - private static final long serialVersionUID = 38354491175250L; public static BulkEligibilityCreator creator() { - return new BulkEligibilityCreator(); + return new BulkEligibilityCreator( + + ); } - public static BulkEligibilityFetcher fetcher(final String pathRequestId) { - return new BulkEligibilityFetcher(pathRequestId); + + public static BulkEligibilityFetcher fetcher(final String pathrequestId) { + return new BulkEligibilityFetcher( + pathrequestId + ); } + /** * Converts a JSON String into a BulkEligibility object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return BulkEligibility object represented by the provided JSON */ - public static BulkEligibility fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static BulkEligibility fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, BulkEligibility.class); @@ -75,14 +76,11 @@ public static BulkEligibility fromJson( * Converts a JSON InputStream into a BulkEligibility object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return BulkEligibility object represented by the provided JSON */ - public static BulkEligibility fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static BulkEligibility fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, BulkEligibility.class); @@ -105,60 +103,41 @@ public static String toJson(Object object, ObjectMapper mapper) { } } - private final String requestId; - private final URI url; - private final List> results; + + @Getter + private final ZonedDateTime dateCompleted; + @Getter + private final ZonedDateTime dateCreated; + @Getter private final String friendlyName; + @Getter + private final String requestId; + @Getter + private final List results; + @Getter private final String status; - private final ZonedDateTime dateCreated; - private final ZonedDateTime dateCompleted; + @Getter + private final URI url; @JsonCreator private BulkEligibility( - @JsonProperty("request_id") final String requestId, - @JsonProperty("url") final URI url, - @JsonProperty("results") final List> results, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("status") final String status, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_completed") final String dateCompleted + @JsonProperty("date_completed") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCompleted, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("request_id") final String requestId, + @JsonProperty("results") final List results, + @JsonProperty("status") final String status, + @JsonProperty("url") final URI url ) { + this.dateCompleted = dateCompleted; + this.dateCreated = dateCreated; + this.friendlyName = friendlyName; this.requestId = requestId; - this.url = url; this.results = results; - this.friendlyName = friendlyName; this.status = status; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateCompleted = - DateConverter.iso8601DateTimeFromString(dateCompleted); - } - - public final String getRequestId() { - return this.requestId; - } - - public final URI getUrl() { - return this.url; - } - - public final List> getResults() { - return this.results; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final String getStatus() { - return this.status; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateCompleted() { - return this.dateCompleted; + this.url = url; } @Override @@ -172,28 +151,30 @@ public boolean equals(final Object o) { } BulkEligibility other = (BulkEligibility) o; - return ( - Objects.equals(requestId, other.requestId) && - Objects.equals(url, other.url) && - Objects.equals(results, other.results) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(status, other.status) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateCompleted, other.dateCompleted) + Objects.equals(dateCompleted, other.dateCompleted) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(requestId, other.requestId) && + Objects.equals(results, other.results) && + Objects.equals(status, other.status) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - requestId, - url, - results, - friendlyName, - status, - dateCreated, - dateCompleted + dateCompleted, + dateCreated, + friendlyName, + requestId, + results, + status, + url ); } + + } + diff --git a/src/main/java/com/twilio/rest/numbers/v1/BulkEligibilityCreator.java b/src/main/java/com/twilio/rest/numbers/v1/BulkEligibilityCreator.java index 24167a030f..f59754656d 100644 --- a/src/main/java/com/twilio/rest/numbers/v1/BulkEligibilityCreator.java +++ b/src/main/java/com/twilio/rest/numbers/v1/BulkEligibilityCreator.java @@ -30,47 +30,46 @@ public class BulkEligibilityCreator extends Creator { private Object body; - public BulkEligibilityCreator() {} + public BulkEligibilityCreator() { + } + public BulkEligibilityCreator setBody(final Object body) { this.body = body; return this; } + @Override public BulkEligibility create(final TwilioRestClient client) { + String path = "/v1/HostedNumber/Eligibility/Bulk"; + Request request = new Request( - HttpMethod.POST, - Domains.NUMBERS.toString(), - path + HttpMethod.POST, + Domains.NUMBERS.toString(), + path ); request.setContentType(EnumConstants.ContentType.JSON); addPostParams(request, client); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "BulkEligibility creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("BulkEligibility creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return BulkEligibility.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return BulkEligibility.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request, TwilioRestClient client) { diff --git a/src/main/java/com/twilio/rest/numbers/v1/BulkEligibilityFetcher.java b/src/main/java/com/twilio/rest/numbers/v1/BulkEligibilityFetcher.java index 7ab7ee8f65..9e4270f22b 100644 --- a/src/main/java/com/twilio/rest/numbers/v1/BulkEligibilityFetcher.java +++ b/src/main/java/com/twilio/rest/numbers/v1/BulkEligibilityFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.numbers.v1; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,51 +26,41 @@ public class BulkEligibilityFetcher extends Fetcher { - private String pathRequestId; + private String pathrequestId; - public BulkEligibilityFetcher(final String pathRequestId) { - this.pathRequestId = pathRequestId; + public BulkEligibilityFetcher(final String pathrequestId) { + this.pathrequestId = pathrequestId; } + @Override public BulkEligibility fetch(final TwilioRestClient client) { + String path = "/v1/HostedNumber/Eligibility/Bulk/{RequestId}"; - path = - path.replace( - "{" + "RequestId" + "}", - this.pathRequestId.toString() - ); + path = path.replace("{" + "RequestId" + "}", this.pathrequestId.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.NUMBERS.toString(), - path + HttpMethod.GET, + Domains.NUMBERS.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "BulkEligibility fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("BulkEligibility fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return BulkEligibility.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return BulkEligibility.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/numbers/v1/Eligibility.java b/src/main/java/com/twilio/rest/numbers/v1/Eligibility.java index c37aabdd86..1bc04828cc 100644 --- a/src/main/java/com/twilio/rest/numbers/v1/Eligibility.java +++ b/src/main/java/com/twilio/rest/numbers/v1/Eligibility.java @@ -24,36 +24,34 @@ import com.twilio.base.Resource; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.util.List; -import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Eligibility extends Resource { - private static final long serialVersionUID = 222327706675602L; public static EligibilityCreator creator() { - return new EligibilityCreator(); + return new EligibilityCreator( + + ); } + /** * Converts a JSON String into a Eligibility object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Eligibility object represented by the provided JSON */ - public static Eligibility fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Eligibility fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Eligibility.class); @@ -68,14 +66,11 @@ public static Eligibility fromJson( * Converts a JSON InputStream into a Eligibility object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Eligibility object represented by the provided JSON */ - public static Eligibility fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Eligibility fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Eligibility.class); @@ -98,19 +93,17 @@ public static String toJson(Object object, ObjectMapper mapper) { } } - private final List> results; + + @Getter + private final List results; @JsonCreator private Eligibility( - @JsonProperty("results") final List> results + @JsonProperty("results") final List results ) { this.results = results; } - public final List> getResults() { - return this.results; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -122,12 +115,18 @@ public boolean equals(final Object o) { } Eligibility other = (Eligibility) o; - - return Objects.equals(results, other.results); + return ( + Objects.equals(results, other.results) + ); } @Override public int hashCode() { - return Objects.hash(results); + return Objects.hash( + results + ); } + + } + diff --git a/src/main/java/com/twilio/rest/numbers/v1/EligibilityCreator.java b/src/main/java/com/twilio/rest/numbers/v1/EligibilityCreator.java index dd8ffb4bee..b091e7287c 100644 --- a/src/main/java/com/twilio/rest/numbers/v1/EligibilityCreator.java +++ b/src/main/java/com/twilio/rest/numbers/v1/EligibilityCreator.java @@ -30,47 +30,46 @@ public class EligibilityCreator extends Creator { private Object body; - public EligibilityCreator() {} + public EligibilityCreator() { + } + public EligibilityCreator setBody(final Object body) { this.body = body; return this; } + @Override public Eligibility create(final TwilioRestClient client) { + String path = "/v1/HostedNumber/Eligibility"; + Request request = new Request( - HttpMethod.POST, - Domains.NUMBERS.toString(), - path + HttpMethod.POST, + Domains.NUMBERS.toString(), + path ); request.setContentType(EnumConstants.ContentType.JSON); addPostParams(request, client); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Eligibility creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("Eligibility creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Eligibility.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Eligibility.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request, TwilioRestClient client) { diff --git a/src/main/java/com/twilio/rest/numbers/v1/PortingPortIn.java b/src/main/java/com/twilio/rest/numbers/v1/PortingPortIn.java index d3fc89c41a..a517d4c746 100644 --- a/src/main/java/com/twilio/rest/numbers/v1/PortingPortIn.java +++ b/src/main/java/com/twilio/rest/numbers/v1/PortingPortIn.java @@ -21,55 +21,55 @@ import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.LocalDate; import java.time.ZonedDateTime; import java.util.List; -import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class PortingPortIn extends Resource { - private static final long serialVersionUID = 109031413524724L; public static PortingPortInCreator creator() { - return new PortingPortInCreator(); + return new PortingPortInCreator( + + ); } - public static PortingPortInDeleter deleter( - final String pathPortInRequestSid - ) { - return new PortingPortInDeleter(pathPortInRequestSid); + + public static PortingPortInDeleter deleter(final String pathportInRequestSid) { + return new PortingPortInDeleter( + pathportInRequestSid + ); } - public static PortingPortInFetcher fetcher( - final String pathPortInRequestSid - ) { - return new PortingPortInFetcher(pathPortInRequestSid); + + public static PortingPortInFetcher fetcher(final String pathportInRequestSid) { + return new PortingPortInFetcher( + pathportInRequestSid + ); } + /** * Converts a JSON String into a PortingPortIn object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return PortingPortIn object represented by the provided JSON */ - public static PortingPortIn fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static PortingPortIn fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, PortingPortIn.class); @@ -84,14 +84,11 @@ public static PortingPortIn fromJson( * Converts a JSON InputStream into a PortingPortIn object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return PortingPortIn object represented by the provided JSON */ - public static PortingPortIn fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static PortingPortIn fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, PortingPortIn.class); @@ -114,133 +111,73 @@ public static String toJson(Object object, ObjectMapper mapper) { } } - private final String portInRequestSid; - private final URI url; + + @Getter private final String accountSid; + @Getter + private final String autoCancelApprovalNumbers; + @Getter + private final String bundleSid; + @Getter + private final ZonedDateTime dateCreated; + @Getter + private final List documents; + @Getter + private final Object losingCarrierInformation; + @Getter private final List notificationEmails; - private final LocalDate targetPortInDate; - private final String targetPortInTimeRangeStart; - private final String targetPortInTimeRangeEnd; + @Getter + private final List phoneNumbers; + @Getter + private final String portInRequestSid; + @Getter private final String portInRequestStatus; - private final Map losingCarrierInformation; - private final List> phoneNumbers; - private final String bundleSid; + @Getter private final String portabilityAdvanceCarrier; - private final String autoCancelApprovalNumbers; - private final List documents; - private final ZonedDateTime dateCreated; + @Getter + private final LocalDate targetPortInDate; + @Getter + private final String targetPortInTimeRangeEnd; + @Getter + private final String targetPortInTimeRangeStart; + @Getter + private final URI url; @JsonCreator private PortingPortIn( - @JsonProperty("port_in_request_sid") final String portInRequestSid, - @JsonProperty("url") final URI url, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("notification_emails") final List< - String - > notificationEmails, - @JsonProperty("target_port_in_date") final String targetPortInDate, - @JsonProperty( - "target_port_in_time_range_start" - ) final String targetPortInTimeRangeStart, - @JsonProperty( - "target_port_in_time_range_end" - ) final String targetPortInTimeRangeEnd, - @JsonProperty( - "port_in_request_status" - ) final String portInRequestStatus, - @JsonProperty("losing_carrier_information") final Map< - String, - Object - > losingCarrierInformation, - @JsonProperty("phone_numbers") final List< - Map - > phoneNumbers, - @JsonProperty("bundle_sid") final String bundleSid, - @JsonProperty( - "portability_advance_carrier" - ) final String portabilityAdvanceCarrier, - @JsonProperty( - "auto_cancel_approval_numbers" - ) final String autoCancelApprovalNumbers, - @JsonProperty("documents") final List documents, - @JsonProperty("date_created") final String dateCreated + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("auto_cancel_approval_numbers") final String autoCancelApprovalNumbers, + @JsonProperty("bundle_sid") final String bundleSid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("documents") final List documents, + @JsonProperty("losing_carrier_information") final Object losingCarrierInformation, + @JsonProperty("notification_emails") final List notificationEmails, + @JsonProperty("phone_numbers") final List phoneNumbers, + @JsonProperty("port_in_request_sid") final String portInRequestSid, + @JsonProperty("port_in_request_status") final String portInRequestStatus, + @JsonProperty("portability_advance_carrier") final String portabilityAdvanceCarrier, + @JsonProperty("target_port_in_date") + @JsonDeserialize(using = com.twilio.converter.LocalDateDeserializer.class) final LocalDate targetPortInDate, + @JsonProperty("target_port_in_time_range_end") final String targetPortInTimeRangeEnd, + @JsonProperty("target_port_in_time_range_start") final String targetPortInTimeRangeStart, + @JsonProperty("url") final URI url ) { - this.portInRequestSid = portInRequestSid; - this.url = url; this.accountSid = accountSid; - this.notificationEmails = notificationEmails; - this.targetPortInDate = - DateConverter.localDateFromString(targetPortInDate); - this.targetPortInTimeRangeStart = targetPortInTimeRangeStart; - this.targetPortInTimeRangeEnd = targetPortInTimeRangeEnd; - this.portInRequestStatus = portInRequestStatus; + this.autoCancelApprovalNumbers = autoCancelApprovalNumbers; + this.bundleSid = bundleSid; + this.dateCreated = dateCreated; + this.documents = documents; this.losingCarrierInformation = losingCarrierInformation; + this.notificationEmails = notificationEmails; this.phoneNumbers = phoneNumbers; - this.bundleSid = bundleSid; + this.portInRequestSid = portInRequestSid; + this.portInRequestStatus = portInRequestStatus; this.portabilityAdvanceCarrier = portabilityAdvanceCarrier; - this.autoCancelApprovalNumbers = autoCancelApprovalNumbers; - this.documents = documents; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - } - - public final String getPortInRequestSid() { - return this.portInRequestSid; - } - - public final URI getUrl() { - return this.url; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final List getNotificationEmails() { - return this.notificationEmails; - } - - public final LocalDate getTargetPortInDate() { - return this.targetPortInDate; - } - - public final String getTargetPortInTimeRangeStart() { - return this.targetPortInTimeRangeStart; - } - - public final String getTargetPortInTimeRangeEnd() { - return this.targetPortInTimeRangeEnd; - } - - public final String getPortInRequestStatus() { - return this.portInRequestStatus; - } - - public final Map getLosingCarrierInformation() { - return this.losingCarrierInformation; - } - - public final List> getPhoneNumbers() { - return this.phoneNumbers; - } - - public final String getBundleSid() { - return this.bundleSid; - } - - public final String getPortabilityAdvanceCarrier() { - return this.portabilityAdvanceCarrier; - } - - public final String getAutoCancelApprovalNumbers() { - return this.autoCancelApprovalNumbers; - } - - public final List getDocuments() { - return this.documents; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; + this.targetPortInDate = targetPortInDate; + this.targetPortInTimeRangeEnd = targetPortInTimeRangeEnd; + this.targetPortInTimeRangeStart = targetPortInTimeRangeStart; + this.url = url; } @Override @@ -254,59 +191,46 @@ public boolean equals(final Object o) { } PortingPortIn other = (PortingPortIn) o; - return ( - Objects.equals(portInRequestSid, other.portInRequestSid) && - Objects.equals(url, other.url) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(notificationEmails, other.notificationEmails) && - Objects.equals(targetPortInDate, other.targetPortInDate) && - Objects.equals( - targetPortInTimeRangeStart, - other.targetPortInTimeRangeStart - ) && - Objects.equals( - targetPortInTimeRangeEnd, - other.targetPortInTimeRangeEnd - ) && - Objects.equals(portInRequestStatus, other.portInRequestStatus) && - Objects.equals( - losingCarrierInformation, - other.losingCarrierInformation - ) && - Objects.equals(phoneNumbers, other.phoneNumbers) && - Objects.equals(bundleSid, other.bundleSid) && - Objects.equals( - portabilityAdvanceCarrier, - other.portabilityAdvanceCarrier - ) && - Objects.equals( - autoCancelApprovalNumbers, - other.autoCancelApprovalNumbers - ) && - Objects.equals(documents, other.documents) && - Objects.equals(dateCreated, other.dateCreated) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(autoCancelApprovalNumbers, other.autoCancelApprovalNumbers) && + Objects.equals(bundleSid, other.bundleSid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(documents, other.documents) && + Objects.equals(losingCarrierInformation, other.losingCarrierInformation) && + Objects.equals(notificationEmails, other.notificationEmails) && + Objects.equals(phoneNumbers, other.phoneNumbers) && + Objects.equals(portInRequestSid, other.portInRequestSid) && + Objects.equals(portInRequestStatus, other.portInRequestStatus) && + Objects.equals(portabilityAdvanceCarrier, other.portabilityAdvanceCarrier) && + Objects.equals(targetPortInDate, other.targetPortInDate) && + Objects.equals(targetPortInTimeRangeEnd, other.targetPortInTimeRangeEnd) && + Objects.equals(targetPortInTimeRangeStart, other.targetPortInTimeRangeStart) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - portInRequestSid, - url, - accountSid, - notificationEmails, - targetPortInDate, - targetPortInTimeRangeStart, - targetPortInTimeRangeEnd, - portInRequestStatus, - losingCarrierInformation, - phoneNumbers, - bundleSid, - portabilityAdvanceCarrier, - autoCancelApprovalNumbers, - documents, - dateCreated + accountSid, + autoCancelApprovalNumbers, + bundleSid, + dateCreated, + documents, + losingCarrierInformation, + notificationEmails, + phoneNumbers, + portInRequestSid, + portInRequestStatus, + portabilityAdvanceCarrier, + targetPortInDate, + targetPortInTimeRangeEnd, + targetPortInTimeRangeStart, + url ); } + + } + diff --git a/src/main/java/com/twilio/rest/numbers/v1/PortingPortInCreator.java b/src/main/java/com/twilio/rest/numbers/v1/PortingPortInCreator.java index b7f5282ac3..39206213c4 100644 --- a/src/main/java/com/twilio/rest/numbers/v1/PortingPortInCreator.java +++ b/src/main/java/com/twilio/rest/numbers/v1/PortingPortInCreator.java @@ -30,47 +30,46 @@ public class PortingPortInCreator extends Creator { private Object body; - public PortingPortInCreator() {} + public PortingPortInCreator() { + } + public PortingPortInCreator setBody(final Object body) { this.body = body; return this; } + @Override public PortingPortIn create(final TwilioRestClient client) { + String path = "/v1/Porting/PortIn"; + Request request = new Request( - HttpMethod.POST, - Domains.NUMBERS.toString(), - path + HttpMethod.POST, + Domains.NUMBERS.toString(), + path ); request.setContentType(EnumConstants.ContentType.JSON); addPostParams(request, client); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "PortingPortIn creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("PortingPortIn creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return PortingPortIn.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return PortingPortIn.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request, TwilioRestClient client) { diff --git a/src/main/java/com/twilio/rest/numbers/v1/PortingPortInDeleter.java b/src/main/java/com/twilio/rest/numbers/v1/PortingPortInDeleter.java index 6a07fa03ba..db2a2935af 100644 --- a/src/main/java/com/twilio/rest/numbers/v1/PortingPortInDeleter.java +++ b/src/main/java/com/twilio/rest/numbers/v1/PortingPortInDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.numbers.v1; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,44 +26,38 @@ public class PortingPortInDeleter extends Deleter { - private String pathPortInRequestSid; + private String pathportInRequestSid; - public PortingPortInDeleter(final String pathPortInRequestSid) { - this.pathPortInRequestSid = pathPortInRequestSid; + public PortingPortInDeleter(final String pathportInRequestSid) { + this.pathportInRequestSid = pathportInRequestSid; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/v1/Porting/PortIn/{PortInRequestSid}"; - path = - path.replace( - "{" + "PortInRequestSid" + "}", - this.pathPortInRequestSid.toString() - ); + path = path.replace("{" + "PortInRequestSid" + "}", this.pathportInRequestSid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.NUMBERS.toString(), - path + HttpMethod.DELETE, + Domains.NUMBERS.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "PortingPortIn delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("PortingPortIn delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/numbers/v1/PortingPortInFetcher.java b/src/main/java/com/twilio/rest/numbers/v1/PortingPortInFetcher.java index 2075c7b195..b31f2120c4 100644 --- a/src/main/java/com/twilio/rest/numbers/v1/PortingPortInFetcher.java +++ b/src/main/java/com/twilio/rest/numbers/v1/PortingPortInFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.numbers.v1; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,51 +26,41 @@ public class PortingPortInFetcher extends Fetcher { - private String pathPortInRequestSid; + private String pathportInRequestSid; - public PortingPortInFetcher(final String pathPortInRequestSid) { - this.pathPortInRequestSid = pathPortInRequestSid; + public PortingPortInFetcher(final String pathportInRequestSid) { + this.pathportInRequestSid = pathportInRequestSid; } + @Override public PortingPortIn fetch(final TwilioRestClient client) { + String path = "/v1/Porting/PortIn/{PortInRequestSid}"; - path = - path.replace( - "{" + "PortInRequestSid" + "}", - this.pathPortInRequestSid.toString() - ); + path = path.replace("{" + "PortInRequestSid" + "}", this.pathportInRequestSid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.NUMBERS.toString(), - path + HttpMethod.GET, + Domains.NUMBERS.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "PortingPortIn fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("PortingPortIn fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return PortingPortIn.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return PortingPortIn.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/numbers/v1/PortingPortInPhoneNumber.java b/src/main/java/com/twilio/rest/numbers/v1/PortingPortInPhoneNumber.java index 1274dc801c..c31d1b442e 100644 --- a/src/main/java/com/twilio/rest/numbers/v1/PortingPortInPhoneNumber.java +++ b/src/main/java/com/twilio/rest/numbers/v1/PortingPortInPhoneNumber.java @@ -18,57 +18,49 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class PortingPortInPhoneNumber extends Resource { - private static final long serialVersionUID = 167748348431012L; - public static PortingPortInPhoneNumberDeleter deleter( - final String pathPortInRequestSid, - final String pathPhoneNumberSid - ) { + public static PortingPortInPhoneNumberDeleter deleter(final String pathportInRequestSid, final String pathphoneNumberSid) { return new PortingPortInPhoneNumberDeleter( - pathPortInRequestSid, - pathPhoneNumberSid + pathportInRequestSid, pathphoneNumberSid ); } - public static PortingPortInPhoneNumberFetcher fetcher( - final String pathPortInRequestSid, - final String pathPhoneNumberSid - ) { + + public static PortingPortInPhoneNumberFetcher fetcher(final String pathportInRequestSid, final String pathphoneNumberSid) { return new PortingPortInPhoneNumberFetcher( - pathPortInRequestSid, - pathPhoneNumberSid + pathportInRequestSid, pathphoneNumberSid ); } + /** * Converts a JSON String into a PortingPortInPhoneNumber object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return PortingPortInPhoneNumber object represented by the provided JSON */ - public static PortingPortInPhoneNumber fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static PortingPortInPhoneNumber fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, PortingPortInPhoneNumber.class); @@ -83,14 +75,11 @@ public static PortingPortInPhoneNumber fromJson( * Converts a JSON InputStream into a PortingPortInPhoneNumber object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return PortingPortInPhoneNumber object represented by the provided JSON */ - public static PortingPortInPhoneNumber fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static PortingPortInPhoneNumber fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, PortingPortInPhoneNumber.class); @@ -101,148 +90,98 @@ public static PortingPortInPhoneNumber fromJson( } } - private final String portInRequestSid; - private final String phoneNumberSid; - private final URI url; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String phoneNumberType; - private final ZonedDateTime dateCreated; + @Getter private final String country; - private final Boolean missingRequiredFields; + @Getter + private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime lastUpdated; - private final com.twilio.type.PhoneNumber phoneNumber; - private final Boolean portable; + @Getter + private final Boolean missingRequiredFields; + @Getter private final String notPortabilityReason; + @Getter private final Integer notPortabilityReasonCode; + @Getter + private final com.twilio.type.PhoneNumber phoneNumber; + @Getter + private final String phoneNumberSid; + @Getter + private final String phoneNumberType; + @Getter + private final ZonedDateTime portDate; + @Getter private final String portInPhoneNumberStatus; + @Getter + private final String portInRequestSid; + @Getter private final Integer portOutPin; + @Getter + private final Boolean portable; + @Getter private final String rejectionReason; + @Getter private final Integer rejectionReasonCode; - private final ZonedDateTime portDate; + @Getter + private final URI url; @JsonCreator private PortingPortInPhoneNumber( - @JsonProperty("port_in_request_sid") final String portInRequestSid, - @JsonProperty("phone_number_sid") final String phoneNumberSid, - @JsonProperty("url") final URI url, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("phone_number_type") final String phoneNumberType, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("country") final String country, - @JsonProperty( - "missing_required_fields" - ) final Boolean missingRequiredFields, - @JsonProperty("last_updated") final String lastUpdated, - @JsonProperty( - "phone_number" - ) final com.twilio.type.PhoneNumber phoneNumber, - @JsonProperty("portable") final Boolean portable, - @JsonProperty( - "not_portability_reason" - ) final String notPortabilityReason, - @JsonProperty( - "not_portability_reason_code" - ) final Integer notPortabilityReasonCode, - @JsonProperty( - "port_in_phone_number_status" - ) final String portInPhoneNumberStatus, - @JsonProperty("port_out_pin") final Integer portOutPin, - @JsonProperty("rejection_reason") final String rejectionReason, - @JsonProperty( - "rejection_reason_code" - ) final Integer rejectionReasonCode, - @JsonProperty("port_date") final String portDate + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("country") final String country, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("last_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime lastUpdated, + @JsonProperty("missing_required_fields") final Boolean missingRequiredFields, + @JsonProperty("not_portability_reason") final String notPortabilityReason, + @JsonProperty("not_portability_reason_code") final Integer notPortabilityReasonCode, + @JsonProperty("phone_number") final com.twilio.type.PhoneNumber phoneNumber, + @JsonProperty("phone_number_sid") final String phoneNumberSid, + @JsonProperty("phone_number_type") final String phoneNumberType, + @JsonProperty("port_date") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime portDate, + @JsonProperty("port_in_phone_number_status") final String portInPhoneNumberStatus, + @JsonProperty("port_in_request_sid") final String portInRequestSid, + @JsonProperty("port_out_pin") final Integer portOutPin, + @JsonProperty("portable") final Boolean portable, + @JsonProperty("rejection_reason") final String rejectionReason, + @JsonProperty("rejection_reason_code") final Integer rejectionReasonCode, + @JsonProperty("url") final URI url ) { - this.portInRequestSid = portInRequestSid; - this.phoneNumberSid = phoneNumberSid; - this.url = url; this.accountSid = accountSid; - this.phoneNumberType = phoneNumberType; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); this.country = country; + this.dateCreated = dateCreated; + this.lastUpdated = lastUpdated; this.missingRequiredFields = missingRequiredFields; - this.lastUpdated = DateConverter.iso8601DateTimeFromString(lastUpdated); - this.phoneNumber = phoneNumber; - this.portable = portable; this.notPortabilityReason = notPortabilityReason; this.notPortabilityReasonCode = notPortabilityReasonCode; + this.phoneNumber = phoneNumber; + this.phoneNumberSid = phoneNumberSid; + this.phoneNumberType = phoneNumberType; + this.portDate = portDate; this.portInPhoneNumberStatus = portInPhoneNumberStatus; + this.portInRequestSid = portInRequestSid; this.portOutPin = portOutPin; + this.portable = portable; this.rejectionReason = rejectionReason; this.rejectionReasonCode = rejectionReasonCode; - this.portDate = DateConverter.iso8601DateTimeFromString(portDate); - } - - public final String getPortInRequestSid() { - return this.portInRequestSid; - } - - public final String getPhoneNumberSid() { - return this.phoneNumberSid; - } - - public final URI getUrl() { - return this.url; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getPhoneNumberType() { - return this.phoneNumberType; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final String getCountry() { - return this.country; - } - - public final Boolean getMissingRequiredFields() { - return this.missingRequiredFields; - } - - public final ZonedDateTime getLastUpdated() { - return this.lastUpdated; - } - - public final com.twilio.type.PhoneNumber getPhoneNumber() { - return this.phoneNumber; - } - - public final Boolean getPortable() { - return this.portable; - } - - public final String getNotPortabilityReason() { - return this.notPortabilityReason; - } - - public final Integer getNotPortabilityReasonCode() { - return this.notPortabilityReasonCode; - } - - public final String getPortInPhoneNumberStatus() { - return this.portInPhoneNumberStatus; - } - - public final Integer getPortOutPin() { - return this.portOutPin; - } - - public final String getRejectionReason() { - return this.rejectionReason; - } - - public final Integer getRejectionReasonCode() { - return this.rejectionReasonCode; - } - - public final ZonedDateTime getPortDate() { - return this.portDate; + this.url = url; } @Override @@ -256,59 +195,52 @@ public boolean equals(final Object o) { } PortingPortInPhoneNumber other = (PortingPortInPhoneNumber) o; - return ( - Objects.equals(portInRequestSid, other.portInRequestSid) && - Objects.equals(phoneNumberSid, other.phoneNumberSid) && - Objects.equals(url, other.url) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(phoneNumberType, other.phoneNumberType) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(country, other.country) && - Objects.equals( - missingRequiredFields, - other.missingRequiredFields - ) && - Objects.equals(lastUpdated, other.lastUpdated) && - Objects.equals(phoneNumber, other.phoneNumber) && - Objects.equals(portable, other.portable) && - Objects.equals(notPortabilityReason, other.notPortabilityReason) && - Objects.equals( - notPortabilityReasonCode, - other.notPortabilityReasonCode - ) && - Objects.equals( - portInPhoneNumberStatus, - other.portInPhoneNumberStatus - ) && - Objects.equals(portOutPin, other.portOutPin) && - Objects.equals(rejectionReason, other.rejectionReason) && - Objects.equals(rejectionReasonCode, other.rejectionReasonCode) && - Objects.equals(portDate, other.portDate) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(country, other.country) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(lastUpdated, other.lastUpdated) && + Objects.equals(missingRequiredFields, other.missingRequiredFields) && + Objects.equals(notPortabilityReason, other.notPortabilityReason) && + Objects.equals(notPortabilityReasonCode, other.notPortabilityReasonCode) && + Objects.equals(phoneNumber, other.phoneNumber) && + Objects.equals(phoneNumberSid, other.phoneNumberSid) && + Objects.equals(phoneNumberType, other.phoneNumberType) && + Objects.equals(portDate, other.portDate) && + Objects.equals(portInPhoneNumberStatus, other.portInPhoneNumberStatus) && + Objects.equals(portInRequestSid, other.portInRequestSid) && + Objects.equals(portOutPin, other.portOutPin) && + Objects.equals(portable, other.portable) && + Objects.equals(rejectionReason, other.rejectionReason) && + Objects.equals(rejectionReasonCode, other.rejectionReasonCode) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - portInRequestSid, - phoneNumberSid, - url, - accountSid, - phoneNumberType, - dateCreated, - country, - missingRequiredFields, - lastUpdated, - phoneNumber, - portable, - notPortabilityReason, - notPortabilityReasonCode, - portInPhoneNumberStatus, - portOutPin, - rejectionReason, - rejectionReasonCode, - portDate + accountSid, + country, + dateCreated, + lastUpdated, + missingRequiredFields, + notPortabilityReason, + notPortabilityReasonCode, + phoneNumber, + phoneNumberSid, + phoneNumberType, + portDate, + portInPhoneNumberStatus, + portInRequestSid, + portOutPin, + portable, + rejectionReason, + rejectionReasonCode, + url ); } + + } + diff --git a/src/main/java/com/twilio/rest/numbers/v1/PortingPortInPhoneNumberDeleter.java b/src/main/java/com/twilio/rest/numbers/v1/PortingPortInPhoneNumberDeleter.java index d4342b4def..3b9a2ec439 100644 --- a/src/main/java/com/twilio/rest/numbers/v1/PortingPortInPhoneNumberDeleter.java +++ b/src/main/java/com/twilio/rest/numbers/v1/PortingPortInPhoneNumberDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.numbers.v1; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,58 +24,43 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class PortingPortInPhoneNumberDeleter - extends Deleter { +public class PortingPortInPhoneNumberDeleter extends Deleter { - private String pathPortInRequestSid; - private String pathPhoneNumberSid; + private String pathportInRequestSid; + private String pathphoneNumberSid; - public PortingPortInPhoneNumberDeleter( - final String pathPortInRequestSid, - final String pathPhoneNumberSid - ) { - this.pathPortInRequestSid = pathPortInRequestSid; - this.pathPhoneNumberSid = pathPhoneNumberSid; + public PortingPortInPhoneNumberDeleter(final String pathportInRequestSid, final String pathphoneNumberSid) { + this.pathportInRequestSid = pathportInRequestSid; + this.pathphoneNumberSid = pathphoneNumberSid; } + @Override public boolean delete(final TwilioRestClient client) { - String path = - "/v1/Porting/PortIn/{PortInRequestSid}/PhoneNumber/{PhoneNumberSid}"; - path = - path.replace( - "{" + "PortInRequestSid" + "}", - this.pathPortInRequestSid.toString() - ); - path = - path.replace( - "{" + "PhoneNumberSid" + "}", - this.pathPhoneNumberSid.toString() - ); + String path = "/v1/Porting/PortIn/{PortInRequestSid}/PhoneNumber/{PhoneNumberSid}"; + + path = path.replace("{" + "PortInRequestSid" + "}", this.pathportInRequestSid.toString()); + path = path.replace("{" + "PhoneNumberSid" + "}", this.pathphoneNumberSid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.NUMBERS.toString(), - path + HttpMethod.DELETE, + Domains.NUMBERS.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "PortingPortInPhoneNumber delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("PortingPortInPhoneNumber delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/numbers/v1/PortingPortInPhoneNumberFetcher.java b/src/main/java/com/twilio/rest/numbers/v1/PortingPortInPhoneNumberFetcher.java index 0cf5aa2a2e..071a422723 100644 --- a/src/main/java/com/twilio/rest/numbers/v1/PortingPortInPhoneNumberFetcher.java +++ b/src/main/java/com/twilio/rest/numbers/v1/PortingPortInPhoneNumberFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.numbers.v1; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,65 +24,46 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class PortingPortInPhoneNumberFetcher - extends Fetcher { +public class PortingPortInPhoneNumberFetcher extends Fetcher { - private String pathPortInRequestSid; - private String pathPhoneNumberSid; + private String pathportInRequestSid; + private String pathphoneNumberSid; - public PortingPortInPhoneNumberFetcher( - final String pathPortInRequestSid, - final String pathPhoneNumberSid - ) { - this.pathPortInRequestSid = pathPortInRequestSid; - this.pathPhoneNumberSid = pathPhoneNumberSid; + public PortingPortInPhoneNumberFetcher(final String pathportInRequestSid, final String pathphoneNumberSid) { + this.pathportInRequestSid = pathportInRequestSid; + this.pathphoneNumberSid = pathphoneNumberSid; } + @Override public PortingPortInPhoneNumber fetch(final TwilioRestClient client) { - String path = - "/v1/Porting/PortIn/{PortInRequestSid}/PhoneNumber/{PhoneNumberSid}"; - path = - path.replace( - "{" + "PortInRequestSid" + "}", - this.pathPortInRequestSid.toString() - ); - path = - path.replace( - "{" + "PhoneNumberSid" + "}", - this.pathPhoneNumberSid.toString() - ); + String path = "/v1/Porting/PortIn/{PortInRequestSid}/PhoneNumber/{PhoneNumberSid}"; + + path = path.replace("{" + "PortInRequestSid" + "}", this.pathportInRequestSid.toString()); + path = path.replace("{" + "PhoneNumberSid" + "}", this.pathphoneNumberSid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.NUMBERS.toString(), - path + HttpMethod.GET, + Domains.NUMBERS.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "PortingPortInPhoneNumber fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("PortingPortInPhoneNumber fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return PortingPortInPhoneNumber.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return PortingPortInPhoneNumber.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/numbers/v1/PortingPortability.java b/src/main/java/com/twilio/rest/numbers/v1/PortingPortability.java index f047290739..13c6c71d13 100644 --- a/src/main/java/com/twilio/rest/numbers/v1/PortingPortability.java +++ b/src/main/java/com/twilio/rest/numbers/v1/PortingPortability.java @@ -18,42 +18,64 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class PortingPortability extends Resource { - private static final long serialVersionUID = 123066058600162L; - public static PortingPortabilityFetcher fetcher( - final com.twilio.type.PhoneNumber pathPhoneNumber - ) { - return new PortingPortabilityFetcher(pathPhoneNumber); + public static PortingPortabilityFetcher fetcher(final com.twilio.type.PhoneNumber pathphoneNumber) { + return new PortingPortabilityFetcher( + pathphoneNumber + ); } + + public enum NumberType { + LOCAL("LOCAL"), + UNKNOWN("UNKNOWN"), + MOBILE("MOBILE"), + TOLL_FREE("TOLL-FREE"); + + private final String value; + + private NumberType(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static NumberType forValue(final String value) { + return Promoter.enumFromString(value, NumberType.values()); + } + } + + /** * Converts a JSON String into a PortingPortability object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return PortingPortability object represented by the provided JSON */ - public static PortingPortability fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static PortingPortability fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, PortingPortability.class); @@ -68,14 +90,11 @@ public static PortingPortability fromJson( * Converts a JSON InputStream into a PortingPortability object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return PortingPortability object represented by the provided JSON */ - public static PortingPortability fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static PortingPortability fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, PortingPortability.class); @@ -86,83 +105,61 @@ public static PortingPortability fromJson( } } - private final com.twilio.type.PhoneNumber phoneNumber; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final Boolean portable; - private final Boolean pinAndAccountNumberRequired; + @Getter + private final String country; + @Getter private final String notPortableReason; + @Getter private final Integer notPortableReasonCode; + @Getter private final PortingPortability.NumberType numberType; - private final String country; + @Getter + private final com.twilio.type.PhoneNumber phoneNumber; + @Getter + private final Boolean pinAndAccountNumberRequired; + @Getter + private final Boolean portable; + @Getter private final URI url; @JsonCreator private PortingPortability( - @JsonProperty( - "phone_number" - ) final com.twilio.type.PhoneNumber phoneNumber, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("portable") final Boolean portable, - @JsonProperty( - "pin_and_account_number_required" - ) final Boolean pinAndAccountNumberRequired, - @JsonProperty("not_portable_reason") final String notPortableReason, - @JsonProperty( - "not_portable_reason_code" - ) final Integer notPortableReasonCode, - @JsonProperty( - "number_type" - ) final PortingPortability.NumberType numberType, - @JsonProperty("country") final String country, - @JsonProperty("url") final URI url + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("country") final String country, + @JsonProperty("not_portable_reason") final String notPortableReason, + @JsonProperty("not_portable_reason_code") final Integer notPortableReasonCode, + @JsonProperty("number_type") final PortingPortability.NumberType numberType, + @JsonProperty("phone_number") final com.twilio.type.PhoneNumber phoneNumber, + @JsonProperty("pin_and_account_number_required") final Boolean pinAndAccountNumberRequired, + @JsonProperty("portable") final Boolean portable, + @JsonProperty("url") final URI url ) { - this.phoneNumber = phoneNumber; this.accountSid = accountSid; - this.portable = portable; - this.pinAndAccountNumberRequired = pinAndAccountNumberRequired; + this.country = country; this.notPortableReason = notPortableReason; this.notPortableReasonCode = notPortableReasonCode; this.numberType = numberType; - this.country = country; + this.phoneNumber = phoneNumber; + this.pinAndAccountNumberRequired = pinAndAccountNumberRequired; + this.portable = portable; this.url = url; } - public final com.twilio.type.PhoneNumber getPhoneNumber() { - return this.phoneNumber; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final Boolean getPortable() { - return this.portable; - } - - public final Boolean getPinAndAccountNumberRequired() { - return this.pinAndAccountNumberRequired; - } - - public final String getNotPortableReason() { - return this.notPortableReason; - } - - public final Integer getNotPortableReasonCode() { - return this.notPortableReasonCode; - } - - public final PortingPortability.NumberType getNumberType() { - return this.numberType; - } - - public final String getCountry() { - return this.country; - } - - public final URI getUrl() { - return this.url; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -174,60 +171,34 @@ public boolean equals(final Object o) { } PortingPortability other = (PortingPortability) o; - return ( - Objects.equals(phoneNumber, other.phoneNumber) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(portable, other.portable) && - Objects.equals( - pinAndAccountNumberRequired, - other.pinAndAccountNumberRequired - ) && - Objects.equals(notPortableReason, other.notPortableReason) && - Objects.equals( - notPortableReasonCode, - other.notPortableReasonCode - ) && - Objects.equals(numberType, other.numberType) && - Objects.equals(country, other.country) && - Objects.equals(url, other.url) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(country, other.country) && + Objects.equals(notPortableReason, other.notPortableReason) && + Objects.equals(notPortableReasonCode, other.notPortableReasonCode) && + Objects.equals(numberType, other.numberType) && + Objects.equals(phoneNumber, other.phoneNumber) && + Objects.equals(pinAndAccountNumberRequired, other.pinAndAccountNumberRequired) && + Objects.equals(portable, other.portable) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - phoneNumber, - accountSid, - portable, - pinAndAccountNumberRequired, - notPortableReason, - notPortableReasonCode, - numberType, - country, - url + accountSid, + country, + notPortableReason, + notPortableReasonCode, + numberType, + phoneNumber, + pinAndAccountNumberRequired, + portable, + url ); } - public enum NumberType { - LOCAL("LOCAL"), - UNKNOWN("UNKNOWN"), - MOBILE("MOBILE"), - TOLL_FREE("TOLL-FREE"); - - private final String value; - private NumberType(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static NumberType forValue(final String value) { - return Promoter.enumFromString(value, NumberType.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/numbers/v1/PortingPortabilityFetcher.java b/src/main/java/com/twilio/rest/numbers/v1/PortingPortabilityFetcher.java index 3eec9d2bbe..2776859e85 100644 --- a/src/main/java/com/twilio/rest/numbers/v1/PortingPortabilityFetcher.java +++ b/src/main/java/com/twilio/rest/numbers/v1/PortingPortabilityFetcher.java @@ -15,7 +15,8 @@ package com.twilio.rest.numbers.v1; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,77 +28,71 @@ public class PortingPortabilityFetcher extends Fetcher { - private com.twilio.type.PhoneNumber pathPhoneNumber; + private com.twilio.type.PhoneNumber pathphoneNumber; private String targetAccountSid; private String addressSid; - public PortingPortabilityFetcher( - final com.twilio.type.PhoneNumber pathPhoneNumber - ) { - this.pathPhoneNumber = pathPhoneNumber; + public PortingPortabilityFetcher(final com.twilio.type.PhoneNumber pathphoneNumber) { + this.pathphoneNumber = pathphoneNumber; } - public PortingPortabilityFetcher setTargetAccountSid( - final String targetAccountSid - ) { + + public PortingPortabilityFetcher setTargetAccountSid(final String targetAccountSid) { this.targetAccountSid = targetAccountSid; return this; } + public PortingPortabilityFetcher setAddressSid(final String addressSid) { this.addressSid = addressSid; return this; } + @Override public PortingPortability fetch(final TwilioRestClient client) { + String path = "/v1/Porting/Portability/PhoneNumber/{PhoneNumber}"; - path = - path.replace( - "{" + "PhoneNumber" + "}", - this.pathPhoneNumber.toString() - ); + path = path.replace("{" + "PhoneNumber" + "}", this.pathphoneNumber.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.NUMBERS.toString(), - path + HttpMethod.GET, + Domains.NUMBERS.toString(), + path ); addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "PortingPortability fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("PortingPortability fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return PortingPortability.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return PortingPortability.fromJson(response.getStream(), client.getObjectMapper()); } private void addQueryParams(final Request request) { + + if (targetAccountSid != null) { - request.addQueryParam("TargetAccountSid", targetAccountSid); + Serializer.toString(request, "TargetAccountSid", targetAccountSid, ParameterType.QUERY); } + + if (addressSid != null) { - request.addQueryParam("AddressSid", addressSid); + Serializer.toString(request, "AddressSid", addressSid, ParameterType.QUERY); } + + } } diff --git a/src/main/java/com/twilio/rest/numbers/v1/PortingWebhookConfiguration.java b/src/main/java/com/twilio/rest/numbers/v1/PortingWebhookConfiguration.java index beb7a459c6..bdaf28dc6f 100644 --- a/src/main/java/com/twilio/rest/numbers/v1/PortingWebhookConfiguration.java +++ b/src/main/java/com/twilio/rest/numbers/v1/PortingWebhookConfiguration.java @@ -24,41 +24,38 @@ import com.twilio.base.Resource; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.util.List; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class PortingWebhookConfiguration extends Resource { - private static final long serialVersionUID = 164865478946260L; public static PortingWebhookConfigurationCreator creator() { - return new PortingWebhookConfigurationCreator(); + return new PortingWebhookConfigurationCreator( + + ); } + /** * Converts a JSON String into a PortingWebhookConfiguration object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return PortingWebhookConfiguration object represented by the provided JSON */ - public static PortingWebhookConfiguration fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static PortingWebhookConfiguration fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { - return objectMapper.readValue( - json, - PortingWebhookConfiguration.class - ); + return objectMapper.readValue(json, PortingWebhookConfiguration.class); } catch (final JsonMappingException | JsonParseException e) { throw new ApiException(e.getMessage(), e); } catch (final IOException e) { @@ -70,20 +67,14 @@ public static PortingWebhookConfiguration fromJson( * Converts a JSON InputStream into a PortingWebhookConfiguration object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return PortingWebhookConfiguration object represented by the provided JSON */ - public static PortingWebhookConfiguration fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static PortingWebhookConfiguration fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { - return objectMapper.readValue( - json, - PortingWebhookConfiguration.class - ); + return objectMapper.readValue(json, PortingWebhookConfiguration.class); } catch (final JsonMappingException | JsonParseException e) { throw new ApiException(e.getMessage(), e); } catch (final IOException e) { @@ -103,38 +94,27 @@ public static String toJson(Object object, ObjectMapper mapper) { } } - private final URI url; + + @Getter + private final List notificationsOf; + @Getter private final URI portInTargetUrl; + @Getter private final URI portOutTargetUrl; - private final List notificationsOf; + @Getter + private final URI url; @JsonCreator private PortingWebhookConfiguration( - @JsonProperty("url") final URI url, - @JsonProperty("port_in_target_url") final URI portInTargetUrl, - @JsonProperty("port_out_target_url") final URI portOutTargetUrl, - @JsonProperty("notifications_of") final List notificationsOf + @JsonProperty("notifications_of") final List notificationsOf, + @JsonProperty("port_in_target_url") final URI portInTargetUrl, + @JsonProperty("port_out_target_url") final URI portOutTargetUrl, + @JsonProperty("url") final URI url ) { - this.url = url; + this.notificationsOf = notificationsOf; this.portInTargetUrl = portInTargetUrl; this.portOutTargetUrl = portOutTargetUrl; - this.notificationsOf = notificationsOf; - } - - public final URI getUrl() { - return this.url; - } - - public final URI getPortInTargetUrl() { - return this.portInTargetUrl; - } - - public final URI getPortOutTargetUrl() { - return this.portOutTargetUrl; - } - - public final List getNotificationsOf() { - return this.notificationsOf; + this.url = url; } @Override @@ -148,22 +128,24 @@ public boolean equals(final Object o) { } PortingWebhookConfiguration other = (PortingWebhookConfiguration) o; - return ( - Objects.equals(url, other.url) && - Objects.equals(portInTargetUrl, other.portInTargetUrl) && - Objects.equals(portOutTargetUrl, other.portOutTargetUrl) && - Objects.equals(notificationsOf, other.notificationsOf) + Objects.equals(notificationsOf, other.notificationsOf) && + Objects.equals(portInTargetUrl, other.portInTargetUrl) && + Objects.equals(portOutTargetUrl, other.portOutTargetUrl) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - url, - portInTargetUrl, - portOutTargetUrl, - notificationsOf + notificationsOf, + portInTargetUrl, + portOutTargetUrl, + url ); } + + } + diff --git a/src/main/java/com/twilio/rest/numbers/v1/PortingWebhookConfigurationCreator.java b/src/main/java/com/twilio/rest/numbers/v1/PortingWebhookConfigurationCreator.java index 0129bc86d6..0b8e9903ef 100644 --- a/src/main/java/com/twilio/rest/numbers/v1/PortingWebhookConfigurationCreator.java +++ b/src/main/java/com/twilio/rest/numbers/v1/PortingWebhookConfigurationCreator.java @@ -26,60 +26,56 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class PortingWebhookConfigurationCreator - extends Creator { +public class PortingWebhookConfigurationCreator extends Creator { private Object body; - public PortingWebhookConfigurationCreator() {} + public PortingWebhookConfigurationCreator() { + } + public PortingWebhookConfigurationCreator setBody(final Object body) { this.body = body; return this; } + @Override public PortingWebhookConfiguration create(final TwilioRestClient client) { + String path = "/v1/Porting/Configuration/Webhook"; + Request request = new Request( - HttpMethod.POST, - Domains.NUMBERS.toString(), - path + HttpMethod.POST, + Domains.NUMBERS.toString(), + path ); request.setContentType(EnumConstants.ContentType.JSON); addPostParams(request, client); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "PortingWebhookConfiguration creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("PortingWebhookConfiguration creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return PortingWebhookConfiguration.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return PortingWebhookConfiguration.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request, TwilioRestClient client) { ObjectMapper objectMapper = client.getObjectMapper(); if (body != null) { - request.setBody( - PortingWebhookConfiguration.toJson(body, objectMapper) - ); + request.setBody(PortingWebhookConfiguration.toJson(body, objectMapper)); } } } diff --git a/src/main/java/com/twilio/rest/numbers/v1/PortingWebhookConfigurationDelete.java b/src/main/java/com/twilio/rest/numbers/v1/PortingWebhookConfigurationDelete.java index cec172e3a1..5b27e4f20d 100644 --- a/src/main/java/com/twilio/rest/numbers/v1/PortingWebhookConfigurationDelete.java +++ b/src/main/java/com/twilio/rest/numbers/v1/PortingWebhookConfigurationDelete.java @@ -17,46 +17,62 @@ import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class PortingWebhookConfigurationDelete extends Resource { - private static final long serialVersionUID = 0L; - public static PortingWebhookConfigurationDeleteDeleter deleter( - final PortingWebhookConfigurationDelete.WebhookType webhookType - ) { - return new PortingWebhookConfigurationDeleteDeleter(webhookType); + public static PortingWebhookConfigurationDeleteDeleter deleter(final PortingWebhookConfigurationDelete.WebhookType pathwebhookType) { + return new PortingWebhookConfigurationDeleteDeleter( + pathwebhookType + ); + } + + + public enum WebhookType { + PORT_IN("PORT_IN"), + PORT_OUT("PORT_OUT"); + + private final String value; + + private WebhookType(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static WebhookType forValue(final String value) { + return Promoter.enumFromString(value, WebhookType.values()); + } } + /** * Converts a JSON String into a PortingWebhookConfigurationDelete object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return PortingWebhookConfigurationDelete object represented by the provided JSON */ - public static PortingWebhookConfigurationDelete fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static PortingWebhookConfigurationDelete fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { - return objectMapper.readValue( - json, - PortingWebhookConfigurationDelete.class - ); + return objectMapper.readValue(json, PortingWebhookConfigurationDelete.class); } catch (final JsonMappingException | JsonParseException e) { throw new ApiException(e.getMessage(), e); } catch (final IOException e) { @@ -68,20 +84,14 @@ public static PortingWebhookConfigurationDelete fromJson( * Converts a JSON InputStream into a PortingWebhookConfigurationDelete object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return PortingWebhookConfigurationDelete object represented by the provided JSON */ - public static PortingWebhookConfigurationDelete fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static PortingWebhookConfigurationDelete fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { - return objectMapper.readValue( - json, - PortingWebhookConfigurationDelete.class - ); + return objectMapper.readValue(json, PortingWebhookConfigurationDelete.class); } catch (final JsonMappingException | JsonParseException e) { throw new ApiException(e.getMessage(), e); } catch (final IOException e) { @@ -89,8 +99,21 @@ public static PortingWebhookConfigurationDelete fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + @JsonCreator - private PortingWebhookConfigurationDelete() {} + private PortingWebhookConfigurationDelete() { + } @Override public boolean equals(Object obj) { @@ -102,23 +125,5 @@ public int hashCode() { return 1; } - public enum WebhookType { - PORT_IN("PORT_IN"), - PORT_OUT("PORT_OUT"); - - private final String value; - - private WebhookType(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static WebhookType forValue(final String value) { - return Promoter.enumFromString(value, WebhookType.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/numbers/v1/PortingWebhookConfigurationDeleteDeleter.java b/src/main/java/com/twilio/rest/numbers/v1/PortingWebhookConfigurationDeleteDeleter.java index fd7c1d4338..a050c4831a 100644 --- a/src/main/java/com/twilio/rest/numbers/v1/PortingWebhookConfigurationDeleteDeleter.java +++ b/src/main/java/com/twilio/rest/numbers/v1/PortingWebhookConfigurationDeleteDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.numbers.v1; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,49 +24,40 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class PortingWebhookConfigurationDeleteDeleter - extends Deleter { +public class PortingWebhookConfigurationDeleteDeleter extends Deleter { - private PortingWebhookConfigurationDelete.WebhookType webhookType; + private PortingWebhookConfigurationDelete.WebhookType pathwebhookType; - public PortingWebhookConfigurationDeleteDeleter( - final PortingWebhookConfigurationDelete.WebhookType webhookType - ) { - this.webhookType = webhookType; + public PortingWebhookConfigurationDeleteDeleter(final PortingWebhookConfigurationDelete.WebhookType pathwebhookType) { + this.pathwebhookType = pathwebhookType; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/v1/Porting/Configuration/Webhook/{WebhookType}"; - path = - path.replace( - "{" + "WebhookType" + "}", - this.webhookType.toString() - ); + path = path.replace("{" + "WebhookType" + "}", this.pathwebhookType.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.NUMBERS.toString(), - path + HttpMethod.DELETE, + Domains.NUMBERS.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "PortingWebhookConfigurationDelete delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("PortingWebhookConfigurationDelete delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/numbers/v1/SigningRequestConfiguration.java b/src/main/java/com/twilio/rest/numbers/v1/SigningRequestConfiguration.java index f46de624aa..c33ecb8c52 100644 --- a/src/main/java/com/twilio/rest/numbers/v1/SigningRequestConfiguration.java +++ b/src/main/java/com/twilio/rest/numbers/v1/SigningRequestConfiguration.java @@ -24,44 +24,44 @@ import com.twilio.base.Resource; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class SigningRequestConfiguration extends Resource { - private static final long serialVersionUID = 45135348317638L; public static SigningRequestConfigurationCreator creator() { - return new SigningRequestConfigurationCreator(); + return new SigningRequestConfigurationCreator( + + ); } + public static SigningRequestConfigurationReader reader() { - return new SigningRequestConfigurationReader(); + return new SigningRequestConfigurationReader( + + ); } + /** * Converts a JSON String into a SigningRequestConfiguration object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return SigningRequestConfiguration object represented by the provided JSON */ - public static SigningRequestConfiguration fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static SigningRequestConfiguration fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { - return objectMapper.readValue( - json, - SigningRequestConfiguration.class - ); + return objectMapper.readValue(json, SigningRequestConfiguration.class); } catch (final JsonMappingException | JsonParseException e) { throw new ApiException(e.getMessage(), e); } catch (final IOException e) { @@ -73,20 +73,14 @@ public static SigningRequestConfiguration fromJson( * Converts a JSON InputStream into a SigningRequestConfiguration object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return SigningRequestConfiguration object represented by the provided JSON */ - public static SigningRequestConfiguration fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static SigningRequestConfiguration fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { - return objectMapper.readValue( - json, - SigningRequestConfiguration.class - ); + return objectMapper.readValue(json, SigningRequestConfiguration.class); } catch (final JsonMappingException | JsonParseException e) { throw new ApiException(e.getMessage(), e); } catch (final IOException e) { @@ -106,66 +100,43 @@ public static String toJson(Object object, ObjectMapper mapper) { } } - private final String logoSid; - private final String friendlyName; - private final String product; + + @Getter private final String country; - private final String emailSubject; + @Getter private final String emailMessage; - private final String urlRedirection; + @Getter + private final String emailSubject; + @Getter + private final String friendlyName; + @Getter + private final String logoSid; + @Getter + private final String product; + @Getter private final URI url; + @Getter + private final String urlRedirection; @JsonCreator private SigningRequestConfiguration( - @JsonProperty("logo_sid") final String logoSid, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("product") final String product, - @JsonProperty("country") final String country, - @JsonProperty("email_subject") final String emailSubject, - @JsonProperty("email_message") final String emailMessage, - @JsonProperty("url_redirection") final String urlRedirection, - @JsonProperty("url") final URI url + @JsonProperty("country") final String country, + @JsonProperty("email_message") final String emailMessage, + @JsonProperty("email_subject") final String emailSubject, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("logo_sid") final String logoSid, + @JsonProperty("product") final String product, + @JsonProperty("url") final URI url, + @JsonProperty("url_redirection") final String urlRedirection ) { - this.logoSid = logoSid; - this.friendlyName = friendlyName; - this.product = product; this.country = country; - this.emailSubject = emailSubject; this.emailMessage = emailMessage; - this.urlRedirection = urlRedirection; + this.emailSubject = emailSubject; + this.friendlyName = friendlyName; + this.logoSid = logoSid; + this.product = product; this.url = url; - } - - public final String getLogoSid() { - return this.logoSid; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final String getProduct() { - return this.product; - } - - public final String getCountry() { - return this.country; - } - - public final String getEmailSubject() { - return this.emailSubject; - } - - public final String getEmailMessage() { - return this.emailMessage; - } - - public final String getUrlRedirection() { - return this.urlRedirection; - } - - public final URI getUrl() { - return this.url; + this.urlRedirection = urlRedirection; } @Override @@ -179,30 +150,32 @@ public boolean equals(final Object o) { } SigningRequestConfiguration other = (SigningRequestConfiguration) o; - return ( - Objects.equals(logoSid, other.logoSid) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(product, other.product) && - Objects.equals(country, other.country) && - Objects.equals(emailSubject, other.emailSubject) && - Objects.equals(emailMessage, other.emailMessage) && - Objects.equals(urlRedirection, other.urlRedirection) && - Objects.equals(url, other.url) + Objects.equals(country, other.country) && + Objects.equals(emailMessage, other.emailMessage) && + Objects.equals(emailSubject, other.emailSubject) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(logoSid, other.logoSid) && + Objects.equals(product, other.product) && + Objects.equals(url, other.url) && + Objects.equals(urlRedirection, other.urlRedirection) ); } @Override public int hashCode() { return Objects.hash( - logoSid, - friendlyName, - product, - country, - emailSubject, - emailMessage, - urlRedirection, - url + country, + emailMessage, + emailSubject, + friendlyName, + logoSid, + product, + url, + urlRedirection ); } + + } + diff --git a/src/main/java/com/twilio/rest/numbers/v1/SigningRequestConfigurationCreator.java b/src/main/java/com/twilio/rest/numbers/v1/SigningRequestConfigurationCreator.java index ae315a3bd7..cb60dd62ae 100644 --- a/src/main/java/com/twilio/rest/numbers/v1/SigningRequestConfigurationCreator.java +++ b/src/main/java/com/twilio/rest/numbers/v1/SigningRequestConfigurationCreator.java @@ -26,60 +26,56 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class SigningRequestConfigurationCreator - extends Creator { +public class SigningRequestConfigurationCreator extends Creator { private Object body; - public SigningRequestConfigurationCreator() {} + public SigningRequestConfigurationCreator() { + } + public SigningRequestConfigurationCreator setBody(final Object body) { this.body = body; return this; } + @Override public SigningRequestConfiguration create(final TwilioRestClient client) { + String path = "/v1/SigningRequest/Configuration"; + Request request = new Request( - HttpMethod.POST, - Domains.NUMBERS.toString(), - path + HttpMethod.POST, + Domains.NUMBERS.toString(), + path ); request.setContentType(EnumConstants.ContentType.JSON); addPostParams(request, client); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "SigningRequestConfiguration creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("SigningRequestConfiguration creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return SigningRequestConfiguration.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return SigningRequestConfiguration.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request, TwilioRestClient client) { ObjectMapper objectMapper = client.getObjectMapper(); if (body != null) { - request.setBody( - SigningRequestConfiguration.toJson(body, objectMapper) - ); + request.setBody(SigningRequestConfiguration.toJson(body, objectMapper)); } } } diff --git a/src/main/java/com/twilio/rest/numbers/v1/SigningRequestConfigurationReader.java b/src/main/java/com/twilio/rest/numbers/v1/SigningRequestConfigurationReader.java index 98404085b9..bcd04d4c30 100644 --- a/src/main/java/com/twilio/rest/numbers/v1/SigningRequestConfigurationReader.java +++ b/src/main/java/com/twilio/rest/numbers/v1/SigningRequestConfigurationReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,132 +28,111 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class SigningRequestConfigurationReader - extends Reader { +public class SigningRequestConfigurationReader extends Reader { private String country; private String product; private Long pageSize; - public SigningRequestConfigurationReader() {} + public SigningRequestConfigurationReader() { + } + public SigningRequestConfigurationReader setCountry(final String country) { this.country = country; return this; } + public SigningRequestConfigurationReader setProduct(final String product) { this.product = product; return this; } + public SigningRequestConfigurationReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override - public ResourceSet read( - final TwilioRestClient client - ) { + public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } - public Page firstPage( - final TwilioRestClient client - ) { + public Page firstPage(final TwilioRestClient client) { + String path = "/v1/SigningRequest/Configuration"; + Request request = new Request( - HttpMethod.GET, - Domains.NUMBERS.toString(), - path + HttpMethod.GET, + Domains.NUMBERS.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "SigningRequestConfiguration read failed: Unable to connect to server" - ); + throw new ApiConnectionException("SigningRequestConfiguration read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "configurations", - response.getContent(), - SigningRequestConfiguration.class, - client.getObjectMapper() - ); + "configurations", + response.getContent(), + SigningRequestConfiguration.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.NUMBERS.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.NUMBERS.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (country != null) { - request.addQueryParam("Country", country); + Serializer.toString(request, "Country", country, ParameterType.QUERY); } + + if (product != null) { - request.addQueryParam("Product", product); + Serializer.toString(request, "Product", product, ParameterType.QUERY); } + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/numbers/v1/Webhook.java b/src/main/java/com/twilio/rest/numbers/v1/Webhook.java index 6e9c6921dd..b3093e7b78 100644 --- a/src/main/java/com/twilio/rest/numbers/v1/Webhook.java +++ b/src/main/java/com/twilio/rest/numbers/v1/Webhook.java @@ -18,42 +18,43 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.List; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Webhook extends Resource { - private static final long serialVersionUID = 270526030240961L; public static WebhookFetcher fetcher() { - return new WebhookFetcher(); + return new WebhookFetcher( + + ); } + /** * Converts a JSON String into a Webhook object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Webhook object represented by the provided JSON */ - public static Webhook fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Webhook fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Webhook.class); @@ -68,14 +69,11 @@ public static Webhook fromJson( * Converts a JSON InputStream into a Webhook object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Webhook object represented by the provided JSON */ - public static Webhook fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Webhook fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Webhook.class); @@ -86,58 +84,49 @@ public static Webhook fromJson( } } - private final URI url; - private final URI portInTargetUrl; - private final URI portOutTargetUrl; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final List notificationsOf; + @Getter private final ZonedDateTime portInTargetDateCreated; + @Getter + private final URI portInTargetUrl; + @Getter private final ZonedDateTime portOutTargetDateCreated; + @Getter + private final URI portOutTargetUrl; + @Getter + private final URI url; @JsonCreator private Webhook( - @JsonProperty("url") final URI url, - @JsonProperty("port_in_target_url") final URI portInTargetUrl, - @JsonProperty("port_out_target_url") final URI portOutTargetUrl, - @JsonProperty("notifications_of") final List notificationsOf, - @JsonProperty( - "port_in_target_date_created" - ) final String portInTargetDateCreated, - @JsonProperty( - "port_out_target_date_created" - ) final String portOutTargetDateCreated + @JsonProperty("notifications_of") final List notificationsOf, + @JsonProperty("port_in_target_date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime portInTargetDateCreated, + @JsonProperty("port_in_target_url") final URI portInTargetUrl, + @JsonProperty("port_out_target_date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime portOutTargetDateCreated, + @JsonProperty("port_out_target_url") final URI portOutTargetUrl, + @JsonProperty("url") final URI url ) { - this.url = url; + this.notificationsOf = notificationsOf; + this.portInTargetDateCreated = portInTargetDateCreated; this.portInTargetUrl = portInTargetUrl; + this.portOutTargetDateCreated = portOutTargetDateCreated; this.portOutTargetUrl = portOutTargetUrl; - this.notificationsOf = notificationsOf; - this.portInTargetDateCreated = - DateConverter.iso8601DateTimeFromString(portInTargetDateCreated); - this.portOutTargetDateCreated = - DateConverter.iso8601DateTimeFromString(portOutTargetDateCreated); - } - - public final URI getUrl() { - return this.url; - } - - public final URI getPortInTargetUrl() { - return this.portInTargetUrl; - } - - public final URI getPortOutTargetUrl() { - return this.portOutTargetUrl; - } - - public final List getNotificationsOf() { - return this.notificationsOf; - } - - public final ZonedDateTime getPortInTargetDateCreated() { - return this.portInTargetDateCreated; - } - - public final ZonedDateTime getPortOutTargetDateCreated() { - return this.portOutTargetDateCreated; + this.url = url; } @Override @@ -151,32 +140,28 @@ public boolean equals(final Object o) { } Webhook other = (Webhook) o; - return ( - Objects.equals(url, other.url) && - Objects.equals(portInTargetUrl, other.portInTargetUrl) && - Objects.equals(portOutTargetUrl, other.portOutTargetUrl) && - Objects.equals(notificationsOf, other.notificationsOf) && - Objects.equals( - portInTargetDateCreated, - other.portInTargetDateCreated - ) && - Objects.equals( - portOutTargetDateCreated, - other.portOutTargetDateCreated - ) + Objects.equals(notificationsOf, other.notificationsOf) && + Objects.equals(portInTargetDateCreated, other.portInTargetDateCreated) && + Objects.equals(portInTargetUrl, other.portInTargetUrl) && + Objects.equals(portOutTargetDateCreated, other.portOutTargetDateCreated) && + Objects.equals(portOutTargetUrl, other.portOutTargetUrl) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - url, - portInTargetUrl, - portOutTargetUrl, - notificationsOf, - portInTargetDateCreated, - portOutTargetDateCreated + notificationsOf, + portInTargetDateCreated, + portInTargetUrl, + portOutTargetDateCreated, + portOutTargetUrl, + url ); } + + } + diff --git a/src/main/java/com/twilio/rest/numbers/v1/WebhookFetcher.java b/src/main/java/com/twilio/rest/numbers/v1/WebhookFetcher.java index ccffc00624..fd4efb0e6e 100644 --- a/src/main/java/com/twilio/rest/numbers/v1/WebhookFetcher.java +++ b/src/main/java/com/twilio/rest/numbers/v1/WebhookFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.numbers.v1; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,38 +26,37 @@ public class WebhookFetcher extends Fetcher { - public WebhookFetcher() {} + + public WebhookFetcher() { + } + @Override public Webhook fetch(final TwilioRestClient client) { + String path = "/v1/Porting/Configuration/Webhook"; + Request request = new Request( - HttpMethod.GET, - Domains.NUMBERS.toString(), - path + HttpMethod.GET, + Domains.NUMBERS.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Webhook fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Webhook fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Webhook.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/numbers/v2/AuthorizationDocument.java b/src/main/java/com/twilio/rest/numbers/v2/AuthorizationDocument.java index 0c3aa64569..bb9991f076 100644 --- a/src/main/java/com/twilio/rest/numbers/v2/AuthorizationDocument.java +++ b/src/main/java/com/twilio/rest/numbers/v2/AuthorizationDocument.java @@ -18,67 +18,90 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.List; import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class AuthorizationDocument extends Resource { - private static final long serialVersionUID = 7314983531290L; - public static AuthorizationDocumentCreator creator( - final String addressSid, - final String email, - final com.twilio.type.PhoneNumber contactPhoneNumber, - final List hostedNumberOrderSids - ) { + public static AuthorizationDocumentCreator creator(final String addressSid, final String email, final com.twilio.type.PhoneNumber contactPhoneNumber, final List hostedNumberOrderSids) { return new AuthorizationDocumentCreator( - addressSid, - email, - contactPhoneNumber, - hostedNumberOrderSids + addressSid, email, contactPhoneNumber, hostedNumberOrderSids ); } - public static AuthorizationDocumentDeleter deleter(final String pathSid) { - return new AuthorizationDocumentDeleter(pathSid); + + public static AuthorizationDocumentDeleter deleter(final String pathsid) { + return new AuthorizationDocumentDeleter( + pathsid + ); } - public static AuthorizationDocumentFetcher fetcher(final String pathSid) { - return new AuthorizationDocumentFetcher(pathSid); + + public static AuthorizationDocumentFetcher fetcher(final String pathsid) { + return new AuthorizationDocumentFetcher( + pathsid + ); } + public static AuthorizationDocumentReader reader() { - return new AuthorizationDocumentReader(); + return new AuthorizationDocumentReader( + + ); } + + public enum Status { + OPENED("opened"), + SIGNING("signing"), + SIGNED("signed"), + CANCELED("canceled"), + FAILED("failed"); + + private final String value; + + private Status(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static Status forValue(final String value) { + return Promoter.enumFromString(value, Status.values()); + } + } + + /** * Converts a JSON String into a AuthorizationDocument object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return AuthorizationDocument object represented by the provided JSON */ - public static AuthorizationDocument fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static AuthorizationDocument fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, AuthorizationDocument.class); @@ -93,14 +116,11 @@ public static AuthorizationDocument fromJson( * Converts a JSON InputStream into a AuthorizationDocument object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return AuthorizationDocument object represented by the provided JSON */ - public static AuthorizationDocument fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static AuthorizationDocument fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, AuthorizationDocument.class); @@ -111,73 +131,61 @@ public static AuthorizationDocument fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String addressSid; - private final AuthorizationDocument.Status status; - private final String email; + @Getter private final List ccEmails; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; - private final URI url; + @Getter + private final String email; + @Getter private final Map links; + @Getter + private final String sid; + @Getter + private final AuthorizationDocument.Status status; + @Getter + private final URI url; @JsonCreator private AuthorizationDocument( - @JsonProperty("sid") final String sid, - @JsonProperty("address_sid") final String addressSid, - @JsonProperty("status") final AuthorizationDocument.Status status, - @JsonProperty("email") final String email, - @JsonProperty("cc_emails") final List ccEmails, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("url") final URI url, - @JsonProperty("links") final Map links + @JsonProperty("address_sid") final String addressSid, + @JsonProperty("cc_emails") final List ccEmails, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("email") final String email, + @JsonProperty("links") final Map links, + @JsonProperty("sid") final String sid, + @JsonProperty("status") final AuthorizationDocument.Status status, + @JsonProperty("url") final URI url ) { - this.sid = sid; this.addressSid = addressSid; - this.status = status; - this.email = email; this.ccEmails = ccEmails; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); - this.url = url; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; + this.email = email; this.links = links; - } - - public final String getSid() { - return this.sid; - } - - public final String getAddressSid() { - return this.addressSid; - } - - public final AuthorizationDocument.Status getStatus() { - return this.status; - } - - public final String getEmail() { - return this.email; - } - - public final List getCcEmails() { - return this.ccEmails; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final URI getUrl() { - return this.url; - } - - public final Map getLinks() { - return this.links; + this.sid = sid; + this.status = status; + this.url = url; } @Override @@ -191,55 +199,34 @@ public boolean equals(final Object o) { } AuthorizationDocument other = (AuthorizationDocument) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(addressSid, other.addressSid) && - Objects.equals(status, other.status) && - Objects.equals(email, other.email) && - Objects.equals(ccEmails, other.ccEmails) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(url, other.url) && - Objects.equals(links, other.links) + Objects.equals(addressSid, other.addressSid) && + Objects.equals(ccEmails, other.ccEmails) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(email, other.email) && + Objects.equals(links, other.links) && + Objects.equals(sid, other.sid) && + Objects.equals(status, other.status) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - sid, - addressSid, - status, - email, - ccEmails, - dateCreated, - dateUpdated, - url, - links + addressSid, + ccEmails, + dateCreated, + dateUpdated, + email, + links, + sid, + status, + url ); } - public enum Status { - OPENED("opened"), - SIGNING("signing"), - SIGNED("signed"), - CANCELED("canceled"), - FAILED("failed"); - - private final String value; - - private Status(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - @JsonCreator - public static Status forValue(final String value) { - return Promoter.enumFromString(value, Status.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/numbers/v2/AuthorizationDocumentCreator.java b/src/main/java/com/twilio/rest/numbers/v2/AuthorizationDocumentCreator.java index 3e9f6c5dd8..4664db3547 100644 --- a/src/main/java/com/twilio/rest/numbers/v2/AuthorizationDocumentCreator.java +++ b/src/main/java/com/twilio/rest/numbers/v2/AuthorizationDocumentCreator.java @@ -14,9 +14,12 @@ package com.twilio.rest.numbers.v2; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; import com.twilio.converter.Promoter; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,11 +28,10 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -import java.util.List; + import java.util.List; -public class AuthorizationDocumentCreator - extends Creator { +public class AuthorizationDocumentCreator extends Creator { private String addressSid; private String email; @@ -38,68 +40,51 @@ public class AuthorizationDocumentCreator private String contactTitle; private List ccEmails; - public AuthorizationDocumentCreator( - final String addressSid, - final String email, - final com.twilio.type.PhoneNumber contactPhoneNumber, - final List hostedNumberOrderSids - ) { + public AuthorizationDocumentCreator(final String addressSid, final String email, final com.twilio.type.PhoneNumber contactPhoneNumber, final List hostedNumberOrderSids) { this.addressSid = addressSid; this.email = email; this.contactPhoneNumber = contactPhoneNumber; this.hostedNumberOrderSids = hostedNumberOrderSids; } + public AuthorizationDocumentCreator setAddressSid(final String addressSid) { this.addressSid = addressSid; return this; } + public AuthorizationDocumentCreator setEmail(final String email) { this.email = email; return this; } - public AuthorizationDocumentCreator setContactPhoneNumber( - final com.twilio.type.PhoneNumber contactPhoneNumber - ) { + + public AuthorizationDocumentCreator setContactPhoneNumber(final com.twilio.type.PhoneNumber contactPhoneNumber) { this.contactPhoneNumber = contactPhoneNumber; return this; } - public AuthorizationDocumentCreator setContactPhoneNumber( - final String contactPhoneNumber - ) { - return setContactPhoneNumber( - Promoter.phoneNumberFromString(contactPhoneNumber) - ); + public AuthorizationDocumentCreator setContactPhoneNumber(final String contactPhoneNumber) { + return setContactPhoneNumber(Promoter.phoneNumberFromString(contactPhoneNumber)); } - public AuthorizationDocumentCreator setHostedNumberOrderSids( - final List hostedNumberOrderSids - ) { + public AuthorizationDocumentCreator setHostedNumberOrderSids(final List hostedNumberOrderSids) { this.hostedNumberOrderSids = hostedNumberOrderSids; return this; } - public AuthorizationDocumentCreator setHostedNumberOrderSids( - final String hostedNumberOrderSids - ) { - return setHostedNumberOrderSids( - Promoter.listOfOne(hostedNumberOrderSids) - ); + public AuthorizationDocumentCreator setHostedNumberOrderSids(final String hostedNumberOrderSids) { + return setHostedNumberOrderSids(Promoter.listOfOne(hostedNumberOrderSids)); } - public AuthorizationDocumentCreator setContactTitle( - final String contactTitle - ) { + public AuthorizationDocumentCreator setContactTitle(final String contactTitle) { this.contactTitle = contactTitle; return this; } - public AuthorizationDocumentCreator setCcEmails( - final List ccEmails - ) { + + public AuthorizationDocumentCreator setCcEmails(final List ccEmails) { this.ccEmails = ccEmails; return this; } @@ -110,79 +95,70 @@ public AuthorizationDocumentCreator setCcEmails(final String ccEmails) { @Override public AuthorizationDocument create(final TwilioRestClient client) { + String path = "/v2/HostedNumber/AuthorizationDocuments"; - path = - path.replace("{" + "AddressSid" + "}", this.addressSid.toString()); - path = path.replace("{" + "Email" + "}", this.email.toString()); - path = - path.replace( - "{" + "ContactPhoneNumber" + "}", - this.contactPhoneNumber.toString() - ); - path = - path.replace( - "{" + "HostedNumberOrderSids" + "}", - this.hostedNumberOrderSids.toString() - ); Request request = new Request( - HttpMethod.POST, - Domains.NUMBERS.toString(), - path + HttpMethod.POST, + Domains.NUMBERS.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "AuthorizationDocument creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("AuthorizationDocument creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return AuthorizationDocument.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return AuthorizationDocument.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (addressSid != null) { - request.addPostParam("AddressSid", addressSid); + Serializer.toString(request, "AddressSid", addressSid, ParameterType.URLENCODED); } + + if (email != null) { - request.addPostParam("Email", email); + Serializer.toString(request, "Email", email, ParameterType.URLENCODED); } + + if (contactPhoneNumber != null) { - request.addPostParam( - "ContactPhoneNumber", - contactPhoneNumber.toString() - ); + Serializer.toString(request, "ContactPhoneNumber", contactPhoneNumber, ParameterType.URLENCODED); } + + if (hostedNumberOrderSids != null) { - for (String prop : hostedNumberOrderSids) { - request.addPostParam("HostedNumberOrderSids", prop); + for (String param : hostedNumberOrderSids) { + Serializer.toString(request, "HostedNumberOrderSids", param, ParameterType.URLENCODED); } } + + if (contactTitle != null) { - request.addPostParam("ContactTitle", contactTitle); + Serializer.toString(request, "ContactTitle", contactTitle, ParameterType.URLENCODED); } + + if (ccEmails != null) { - for (String prop : ccEmails) { - request.addPostParam("CcEmails", prop); + for (String param : ccEmails) { + Serializer.toString(request, "CcEmails", param, ParameterType.URLENCODED); } } + } } diff --git a/src/main/java/com/twilio/rest/numbers/v2/AuthorizationDocumentDeleter.java b/src/main/java/com/twilio/rest/numbers/v2/AuthorizationDocumentDeleter.java index f408a110f4..eacae184f1 100644 --- a/src/main/java/com/twilio/rest/numbers/v2/AuthorizationDocumentDeleter.java +++ b/src/main/java/com/twilio/rest/numbers/v2/AuthorizationDocumentDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.numbers.v2; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,43 +24,40 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class AuthorizationDocumentDeleter - extends Deleter { +public class AuthorizationDocumentDeleter extends Deleter { - private String pathSid; + private String pathsid; - public AuthorizationDocumentDeleter(final String pathSid) { - this.pathSid = pathSid; + public AuthorizationDocumentDeleter(final String pathsid) { + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/v2/HostedNumber/AuthorizationDocuments/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.NUMBERS.toString(), - path + HttpMethod.DELETE, + Domains.NUMBERS.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "AuthorizationDocument delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("AuthorizationDocument delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/numbers/v2/AuthorizationDocumentFetcher.java b/src/main/java/com/twilio/rest/numbers/v2/AuthorizationDocumentFetcher.java index bdef150e06..8cc2e6e8dc 100644 --- a/src/main/java/com/twilio/rest/numbers/v2/AuthorizationDocumentFetcher.java +++ b/src/main/java/com/twilio/rest/numbers/v2/AuthorizationDocumentFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.numbers.v2; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,50 +24,43 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class AuthorizationDocumentFetcher - extends Fetcher { +public class AuthorizationDocumentFetcher extends Fetcher { - private String pathSid; + private String pathsid; - public AuthorizationDocumentFetcher(final String pathSid) { - this.pathSid = pathSid; + public AuthorizationDocumentFetcher(final String pathsid) { + this.pathsid = pathsid; } + @Override public AuthorizationDocument fetch(final TwilioRestClient client) { + String path = "/v2/HostedNumber/AuthorizationDocuments/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.NUMBERS.toString(), - path + HttpMethod.GET, + Domains.NUMBERS.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "AuthorizationDocument fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("AuthorizationDocument fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return AuthorizationDocument.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return AuthorizationDocument.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/numbers/v2/AuthorizationDocumentReader.java b/src/main/java/com/twilio/rest/numbers/v2/AuthorizationDocumentReader.java index 74ba8f0425..c064a3bfc8 100644 --- a/src/main/java/com/twilio/rest/numbers/v2/AuthorizationDocumentReader.java +++ b/src/main/java/com/twilio/rest/numbers/v2/AuthorizationDocumentReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -33,127 +34,105 @@ public class AuthorizationDocumentReader extends Reader { private AuthorizationDocument.Status status; private Long pageSize; - public AuthorizationDocumentReader() {} + public AuthorizationDocumentReader() { + } + public AuthorizationDocumentReader setEmail(final String email) { this.email = email; return this; } - public AuthorizationDocumentReader setStatus( - final AuthorizationDocument.Status status - ) { + + public AuthorizationDocumentReader setStatus(final AuthorizationDocument.Status status) { this.status = status; return this; } + public AuthorizationDocumentReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override - public ResourceSet read( - final TwilioRestClient client - ) { + public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } - public Page firstPage( - final TwilioRestClient client - ) { + public Page firstPage(final TwilioRestClient client) { + String path = "/v2/HostedNumber/AuthorizationDocuments"; + Request request = new Request( - HttpMethod.GET, - Domains.NUMBERS.toString(), - path + HttpMethod.GET, + Domains.NUMBERS.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "AuthorizationDocument read failed: Unable to connect to server" - ); + throw new ApiConnectionException("AuthorizationDocument read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "items", - response.getContent(), - AuthorizationDocument.class, - client.getObjectMapper() - ); + "items", + response.getContent(), + AuthorizationDocument.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.NUMBERS.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.NUMBERS.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (email != null) { - request.addQueryParam("Email", email); + Serializer.toString(request, "Email", email, ParameterType.QUERY); } + + if (status != null) { - request.addQueryParam("Status", status.toString()); + Serializer.toString(request, "Status", status, ParameterType.QUERY); } + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/numbers/v2/BulkHostedNumberOrder.java b/src/main/java/com/twilio/rest/numbers/v2/BulkHostedNumberOrder.java index d491067489..ab0aacb106 100644 --- a/src/main/java/com/twilio/rest/numbers/v2/BulkHostedNumberOrder.java +++ b/src/main/java/com/twilio/rest/numbers/v2/BulkHostedNumberOrder.java @@ -21,49 +21,70 @@ import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.List; -import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class BulkHostedNumberOrder extends Resource { - private static final long serialVersionUID = 251635704058877L; public static BulkHostedNumberOrderCreator creator() { - return new BulkHostedNumberOrderCreator(); + return new BulkHostedNumberOrderCreator( + + ); } - public static BulkHostedNumberOrderFetcher fetcher( - final String pathBulkHostingSid - ) { - return new BulkHostedNumberOrderFetcher(pathBulkHostingSid); + + public static BulkHostedNumberOrderFetcher fetcher(final String pathbulkHostingSid) { + return new BulkHostedNumberOrderFetcher( + pathbulkHostingSid + ); + } + + + public enum RequestStatus { + QUEUED("QUEUED"), + IN_PROGRESS("IN_PROGRESS"), + PROCESSED("PROCESSED"); + + private final String value; + + private RequestStatus(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static RequestStatus forValue(final String value) { + return Promoter.enumFromString(value, RequestStatus.values()); + } } + /** * Converts a JSON String into a BulkHostedNumberOrder object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return BulkHostedNumberOrder object represented by the provided JSON */ - public static BulkHostedNumberOrder fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static BulkHostedNumberOrder fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, BulkHostedNumberOrder.class); @@ -78,14 +99,11 @@ public static BulkHostedNumberOrder fromJson( * Converts a JSON InputStream into a BulkHostedNumberOrder object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return BulkHostedNumberOrder object represented by the provided JSON */ - public static BulkHostedNumberOrder fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static BulkHostedNumberOrder fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, BulkHostedNumberOrder.class); @@ -108,76 +126,49 @@ public static String toJson(Object object, ObjectMapper mapper) { } } + + @Getter private final String bulkHostingSid; - private final BulkHostedNumberOrder.RequestStatus requestStatus; + @Getter + private final ZonedDateTime dateCompleted; + @Getter + private final ZonedDateTime dateCreated; + @Getter private final String friendlyName; + @Getter private final String notificationEmail; - private final ZonedDateTime dateCreated; - private final ZonedDateTime dateCompleted; - private final URI url; + @Getter + private final BulkHostedNumberOrder.RequestStatus requestStatus; + @Getter + private final List results; + @Getter private final Integer totalCount; - private final List> results; + @Getter + private final URI url; @JsonCreator private BulkHostedNumberOrder( - @JsonProperty("bulk_hosting_sid") final String bulkHostingSid, - @JsonProperty( - "request_status" - ) final BulkHostedNumberOrder.RequestStatus requestStatus, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("notification_email") final String notificationEmail, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_completed") final String dateCompleted, - @JsonProperty("url") final URI url, - @JsonProperty("total_count") final Integer totalCount, - @JsonProperty("results") final List> results + @JsonProperty("bulk_hosting_sid") final String bulkHostingSid, + @JsonProperty("date_completed") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCompleted, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("notification_email") final String notificationEmail, + @JsonProperty("request_status") final BulkHostedNumberOrder.RequestStatus requestStatus, + @JsonProperty("results") final List results, + @JsonProperty("total_count") final Integer totalCount, + @JsonProperty("url") final URI url ) { this.bulkHostingSid = bulkHostingSid; - this.requestStatus = requestStatus; + this.dateCompleted = dateCompleted; + this.dateCreated = dateCreated; this.friendlyName = friendlyName; this.notificationEmail = notificationEmail; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateCompleted = - DateConverter.iso8601DateTimeFromString(dateCompleted); - this.url = url; - this.totalCount = totalCount; + this.requestStatus = requestStatus; this.results = results; - } - - public final String getBulkHostingSid() { - return this.bulkHostingSid; - } - - public final BulkHostedNumberOrder.RequestStatus getRequestStatus() { - return this.requestStatus; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final String getNotificationEmail() { - return this.notificationEmail; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateCompleted() { - return this.dateCompleted; - } - - public final URI getUrl() { - return this.url; - } - - public final Integer getTotalCount() { - return this.totalCount; - } - - public final List> getResults() { - return this.results; + this.totalCount = totalCount; + this.url = url; } @Override @@ -191,53 +182,34 @@ public boolean equals(final Object o) { } BulkHostedNumberOrder other = (BulkHostedNumberOrder) o; - return ( - Objects.equals(bulkHostingSid, other.bulkHostingSid) && - Objects.equals(requestStatus, other.requestStatus) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(notificationEmail, other.notificationEmail) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateCompleted, other.dateCompleted) && - Objects.equals(url, other.url) && - Objects.equals(totalCount, other.totalCount) && - Objects.equals(results, other.results) + Objects.equals(bulkHostingSid, other.bulkHostingSid) && + Objects.equals(dateCompleted, other.dateCompleted) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(notificationEmail, other.notificationEmail) && + Objects.equals(requestStatus, other.requestStatus) && + Objects.equals(results, other.results) && + Objects.equals(totalCount, other.totalCount) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - bulkHostingSid, - requestStatus, - friendlyName, - notificationEmail, - dateCreated, - dateCompleted, - url, - totalCount, - results + bulkHostingSid, + dateCompleted, + dateCreated, + friendlyName, + notificationEmail, + requestStatus, + results, + totalCount, + url ); } - public enum RequestStatus { - QUEUED("QUEUED"), - IN_PROGRESS("IN_PROGRESS"), - PROCESSED("PROCESSED"); - - private final String value; - - private RequestStatus(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - @JsonCreator - public static RequestStatus forValue(final String value) { - return Promoter.enumFromString(value, RequestStatus.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/numbers/v2/BulkHostedNumberOrderCreator.java b/src/main/java/com/twilio/rest/numbers/v2/BulkHostedNumberOrderCreator.java index 45d5438f36..fed95a1c53 100644 --- a/src/main/java/com/twilio/rest/numbers/v2/BulkHostedNumberOrderCreator.java +++ b/src/main/java/com/twilio/rest/numbers/v2/BulkHostedNumberOrderCreator.java @@ -26,52 +26,50 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class BulkHostedNumberOrderCreator - extends Creator { +public class BulkHostedNumberOrderCreator extends Creator { private Object body; - public BulkHostedNumberOrderCreator() {} + public BulkHostedNumberOrderCreator() { + } + public BulkHostedNumberOrderCreator setBody(final Object body) { this.body = body; return this; } + @Override public BulkHostedNumberOrder create(final TwilioRestClient client) { + String path = "/v2/HostedNumber/Orders/Bulk"; + Request request = new Request( - HttpMethod.POST, - Domains.NUMBERS.toString(), - path + HttpMethod.POST, + Domains.NUMBERS.toString(), + path ); request.setContentType(EnumConstants.ContentType.JSON); addPostParams(request, client); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "BulkHostedNumberOrder creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("BulkHostedNumberOrder creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return BulkHostedNumberOrder.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return BulkHostedNumberOrder.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request, TwilioRestClient client) { diff --git a/src/main/java/com/twilio/rest/numbers/v2/BulkHostedNumberOrderFetcher.java b/src/main/java/com/twilio/rest/numbers/v2/BulkHostedNumberOrderFetcher.java index 03e4c8a701..97e2089d09 100644 --- a/src/main/java/com/twilio/rest/numbers/v2/BulkHostedNumberOrderFetcher.java +++ b/src/main/java/com/twilio/rest/numbers/v2/BulkHostedNumberOrderFetcher.java @@ -15,7 +15,8 @@ package com.twilio.rest.numbers.v2; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,69 +26,61 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class BulkHostedNumberOrderFetcher - extends Fetcher { +public class BulkHostedNumberOrderFetcher extends Fetcher { - private String pathBulkHostingSid; + private String pathbulkHostingSid; private String orderStatus; - public BulkHostedNumberOrderFetcher(final String pathBulkHostingSid) { - this.pathBulkHostingSid = pathBulkHostingSid; + public BulkHostedNumberOrderFetcher(final String pathbulkHostingSid) { + this.pathbulkHostingSid = pathbulkHostingSid; } - public BulkHostedNumberOrderFetcher setOrderStatus( - final String orderStatus - ) { + + public BulkHostedNumberOrderFetcher setOrderStatus(final String orderStatus) { this.orderStatus = orderStatus; return this; } + @Override public BulkHostedNumberOrder fetch(final TwilioRestClient client) { + String path = "/v2/HostedNumber/Orders/Bulk/{BulkHostingSid}"; - path = - path.replace( - "{" + "BulkHostingSid" + "}", - this.pathBulkHostingSid.toString() - ); + path = path.replace("{" + "BulkHostingSid" + "}", this.pathbulkHostingSid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.NUMBERS.toString(), - path + HttpMethod.GET, + Domains.NUMBERS.toString(), + path ); addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "BulkHostedNumberOrder fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("BulkHostedNumberOrder fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return BulkHostedNumberOrder.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return BulkHostedNumberOrder.fromJson(response.getStream(), client.getObjectMapper()); } private void addQueryParams(final Request request) { + + if (orderStatus != null) { - request.addQueryParam("OrderStatus", orderStatus); + Serializer.toString(request, "OrderStatus", orderStatus, ParameterType.QUERY); } + + } } diff --git a/src/main/java/com/twilio/rest/numbers/v2/BundleClone.java b/src/main/java/com/twilio/rest/numbers/v2/BundleClone.java index 8462b057d5..48625ef08b 100644 --- a/src/main/java/com/twilio/rest/numbers/v2/BundleClone.java +++ b/src/main/java/com/twilio/rest/numbers/v2/BundleClone.java @@ -18,45 +18,68 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class BundleClone extends Resource { - private static final long serialVersionUID = 223439984305390L; - public static BundleCloneCreator creator( - final String pathBundleSid, - final String targetAccountSid - ) { - return new BundleCloneCreator(pathBundleSid, targetAccountSid); + public static BundleCloneCreator creator(final String pathbundleSid, final String targetAccountSid) { + return new BundleCloneCreator( + pathbundleSid, targetAccountSid + ); + } + + + public enum Status { + DRAFT("draft"), + PENDING_REVIEW("pending-review"), + IN_REVIEW("in-review"), + TWILIO_REJECTED("twilio-rejected"), + TWILIO_APPROVED("twilio-approved"), + PROVISIONALLY_APPROVED("provisionally-approved"); + + private final String value; + + private Status(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static Status forValue(final String value) { + return Promoter.enumFromString(value, Status.values()); + } } + /** * Converts a JSON String into a BundleClone object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return BundleClone object represented by the provided JSON */ - public static BundleClone fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static BundleClone fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, BundleClone.class); @@ -71,14 +94,11 @@ public static BundleClone fromJson( * Converts a JSON InputStream into a BundleClone object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return BundleClone object represented by the provided JSON */ - public static BundleClone fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static BundleClone fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, BundleClone.class); @@ -89,87 +109,70 @@ public static BundleClone fromJson( } } - private final String bundleSid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String regulationSid; + @Getter + private final String bundleSid; + @Getter + private final ZonedDateTime dateCreated; + @Getter + private final ZonedDateTime dateUpdated; + @Getter + private final String email; + @Getter private final String friendlyName; + @Getter + private final String regulationSid; + @Getter private final BundleClone.Status status; - private final ZonedDateTime validUntil; - private final String email; + @Getter private final URI statusCallback; - private final ZonedDateTime dateCreated; - private final ZonedDateTime dateUpdated; + @Getter private final URI url; + @Getter + private final ZonedDateTime validUntil; @JsonCreator private BundleClone( - @JsonProperty("bundle_sid") final String bundleSid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("regulation_sid") final String regulationSid, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("status") final BundleClone.Status status, - @JsonProperty("valid_until") final String validUntil, - @JsonProperty("email") final String email, - @JsonProperty("status_callback") final URI statusCallback, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("url") final URI url + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("bundle_sid") final String bundleSid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("email") final String email, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("regulation_sid") final String regulationSid, + @JsonProperty("status") final BundleClone.Status status, + @JsonProperty("status_callback") final URI statusCallback, + @JsonProperty("url") final URI url, + @JsonProperty("valid_until") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime validUntil ) { - this.bundleSid = bundleSid; this.accountSid = accountSid; - this.regulationSid = regulationSid; + this.bundleSid = bundleSid; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; + this.email = email; this.friendlyName = friendlyName; + this.regulationSid = regulationSid; this.status = status; - this.validUntil = DateConverter.iso8601DateTimeFromString(validUntil); - this.email = email; this.statusCallback = statusCallback; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); this.url = url; - } - - public final String getBundleSid() { - return this.bundleSid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getRegulationSid() { - return this.regulationSid; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final BundleClone.Status getStatus() { - return this.status; - } - - public final ZonedDateTime getValidUntil() { - return this.validUntil; - } - - public final String getEmail() { - return this.email; - } - - public final URI getStatusCallback() { - return this.statusCallback; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final URI getUrl() { - return this.url; + this.validUntil = validUntil; } @Override @@ -183,60 +186,38 @@ public boolean equals(final Object o) { } BundleClone other = (BundleClone) o; - return ( - Objects.equals(bundleSid, other.bundleSid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(regulationSid, other.regulationSid) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(status, other.status) && - Objects.equals(validUntil, other.validUntil) && - Objects.equals(email, other.email) && - Objects.equals(statusCallback, other.statusCallback) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(url, other.url) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(bundleSid, other.bundleSid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(email, other.email) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(regulationSid, other.regulationSid) && + Objects.equals(status, other.status) && + Objects.equals(statusCallback, other.statusCallback) && + Objects.equals(url, other.url) && + Objects.equals(validUntil, other.validUntil) ); } @Override public int hashCode() { return Objects.hash( - bundleSid, - accountSid, - regulationSid, - friendlyName, - status, - validUntil, - email, - statusCallback, - dateCreated, - dateUpdated, - url + accountSid, + bundleSid, + dateCreated, + dateUpdated, + email, + friendlyName, + regulationSid, + status, + statusCallback, + url, + validUntil ); } - public enum Status { - DRAFT("draft"), - PENDING_REVIEW("pending-review"), - IN_REVIEW("in-review"), - TWILIO_REJECTED("twilio-rejected"), - TWILIO_APPROVED("twilio-approved"), - PROVISIONALLY_APPROVED("provisionally-approved"); - - private final String value; - - private Status(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - @JsonCreator - public static Status forValue(final String value) { - return Promoter.enumFromString(value, Status.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/numbers/v2/BundleCloneCreator.java b/src/main/java/com/twilio/rest/numbers/v2/BundleCloneCreator.java index 023601f553..b2e310a56c 100644 --- a/src/main/java/com/twilio/rest/numbers/v2/BundleCloneCreator.java +++ b/src/main/java/com/twilio/rest/numbers/v2/BundleCloneCreator.java @@ -14,8 +14,11 @@ package com.twilio.rest.numbers.v2; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,92 +30,85 @@ public class BundleCloneCreator extends Creator { - private String pathBundleSid; + private String pathbundleSid; private String targetAccountSid; private Boolean moveToDraft; private String friendlyName; - public BundleCloneCreator( - final String pathBundleSid, - final String targetAccountSid - ) { - this.pathBundleSid = pathBundleSid; + public BundleCloneCreator(final String pathbundleSid, final String targetAccountSid) { + this.pathbundleSid = pathbundleSid; this.targetAccountSid = targetAccountSid; } - public BundleCloneCreator setTargetAccountSid( - final String targetAccountSid - ) { + + public BundleCloneCreator setTargetAccountSid(final String targetAccountSid) { this.targetAccountSid = targetAccountSid; return this; } + public BundleCloneCreator setMoveToDraft(final Boolean moveToDraft) { this.moveToDraft = moveToDraft; return this; } + public BundleCloneCreator setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + @Override public BundleClone create(final TwilioRestClient client) { + String path = "/v2/RegulatoryCompliance/Bundles/{BundleSid}/Clones"; - path = - path.replace( - "{" + "BundleSid" + "}", - this.pathBundleSid.toString() - ); - path = - path.replace( - "{" + "TargetAccountSid" + "}", - this.targetAccountSid.toString() - ); + path = path.replace("{" + "BundleSid" + "}", this.pathbundleSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.NUMBERS.toString(), - path + HttpMethod.POST, + Domains.NUMBERS.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "BundleClone creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("BundleClone creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return BundleClone.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return BundleClone.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (targetAccountSid != null) { - request.addPostParam("TargetAccountSid", targetAccountSid); + Serializer.toString(request, "TargetAccountSid", targetAccountSid, ParameterType.URLENCODED); } + + if (moveToDraft != null) { - request.addPostParam("MoveToDraft", moveToDraft.toString()); + Serializer.toString(request, "MoveToDraft", moveToDraft, ParameterType.URLENCODED); } + + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/numbers/v2/HostedNumberOrder.java b/src/main/java/com/twilio/rest/numbers/v2/HostedNumberOrder.java index 6363d99966..8ec89517a4 100644 --- a/src/main/java/com/twilio/rest/numbers/v2/HostedNumberOrder.java +++ b/src/main/java/com/twilio/rest/numbers/v2/HostedNumberOrder.java @@ -18,73 +18,121 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.type.PhoneNumberCapabilities; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.List; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class HostedNumberOrder extends Resource { - private static final long serialVersionUID = 99296181753609L; - public static HostedNumberOrderCreator creator( - final com.twilio.type.PhoneNumber phoneNumber, - final com.twilio.type.PhoneNumber contactPhoneNumber, - final String addressSid, - final String email - ) { + public static HostedNumberOrderCreator creator(final com.twilio.type.PhoneNumber phoneNumber, final com.twilio.type.PhoneNumber contactPhoneNumber, final String addressSid, final String email) { return new HostedNumberOrderCreator( - phoneNumber, - contactPhoneNumber, - addressSid, - email + phoneNumber, contactPhoneNumber, addressSid, email ); } - public static HostedNumberOrderDeleter deleter(final String pathSid) { - return new HostedNumberOrderDeleter(pathSid); + + public static HostedNumberOrderDeleter deleter(final String pathsid) { + return new HostedNumberOrderDeleter( + pathsid + ); } - public static HostedNumberOrderFetcher fetcher(final String pathSid) { - return new HostedNumberOrderFetcher(pathSid); + + public static HostedNumberOrderFetcher fetcher(final String pathsid) { + return new HostedNumberOrderFetcher( + pathsid + ); } + public static HostedNumberOrderReader reader() { - return new HostedNumberOrderReader(); + return new HostedNumberOrderReader( + + ); } - public static HostedNumberOrderUpdater updater( - final String pathSid, - final HostedNumberOrder.Status status - ) { - return new HostedNumberOrderUpdater(pathSid, status); + + public static HostedNumberOrderUpdater updater(final String pathsid, final HostedNumberOrder.Status status) { + return new HostedNumberOrderUpdater( + pathsid, status + ); + } + + + public enum Status { + TWILIO_PROCESSING("twilio-processing"), + RECEIVED("received"), + PENDING_VERIFICATION("pending-verification"), + VERIFIED("verified"), + PENDING_LOA("pending-loa"), + CARRIER_PROCESSING("carrier-processing"), + TESTING("testing"), + COMPLETED("completed"), + FAILED("failed"), + ACTION_REQUIRED("action-required"); + + private final String value; + + private Status(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static Status forValue(final String value) { + return Promoter.enumFromString(value, Status.values()); + } } + public enum VerificationType { + PHONE_CALL("phone-call"); + + private final String value; + + private VerificationType(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static VerificationType forValue(final String value) { + return Promoter.enumFromString(value, VerificationType.values()); + } + } + + /** * Converts a JSON String into a HostedNumberOrder object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return HostedNumberOrder object represented by the provided JSON */ - public static HostedNumberOrder fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static HostedNumberOrder fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, HostedNumberOrder.class); @@ -99,14 +147,11 @@ public static HostedNumberOrder fromJson( * Converts a JSON InputStream into a HostedNumberOrder object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return HostedNumberOrder object represented by the provided JSON */ - public static HostedNumberOrder fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static HostedNumberOrder fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, HostedNumberOrder.class); @@ -117,207 +162,127 @@ public static HostedNumberOrder fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String incomingPhoneNumberSid; + @Getter private final String addressSid; - private final String signingDocumentSid; - private final com.twilio.type.PhoneNumber phoneNumber; + @Getter + private final String bulkHostingRequestSid; + @Getter private final PhoneNumberCapabilities capabilities; - private final String friendlyName; - private final HostedNumberOrder.Status status; - private final String failureReason; + @Getter + private final List ccEmails; + @Getter + private final com.twilio.type.PhoneNumber contactPhoneNumber; + @Getter + private final String contactTitle; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; + @Getter private final String email; - private final List ccEmails; - private final URI url; - private final String contactTitle; - private final com.twilio.type.PhoneNumber contactPhoneNumber; - private final String bulkHostingRequestSid; + @Getter + private final String failureReason; + @Getter + private final String friendlyName; + @Getter + private final String incomingPhoneNumberSid; + @Getter private final String nextStep; + @Getter + private final com.twilio.type.PhoneNumber phoneNumber; + @Getter + private final String sid; + @Getter + private final String signingDocumentSid; + @Getter + private final HostedNumberOrder.Status status; + @Getter + private final URI url; + @Getter private final Integer verificationAttempts; - private final List verificationCallSids; + @Getter private final Integer verificationCallDelay; + @Getter private final String verificationCallExtension; + @Getter + private final List verificationCallSids; + @Getter private final String verificationCode; + @Getter private final HostedNumberOrder.VerificationType verificationType; @JsonCreator private HostedNumberOrder( - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty( - "incoming_phone_number_sid" - ) final String incomingPhoneNumberSid, - @JsonProperty("address_sid") final String addressSid, - @JsonProperty("signing_document_sid") final String signingDocumentSid, - @JsonProperty( - "phone_number" - ) final com.twilio.type.PhoneNumber phoneNumber, - @JsonProperty( - "capabilities" - ) final PhoneNumberCapabilities capabilities, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("status") final HostedNumberOrder.Status status, - @JsonProperty("failure_reason") final String failureReason, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("email") final String email, - @JsonProperty("cc_emails") final List ccEmails, - @JsonProperty("url") final URI url, - @JsonProperty("contact_title") final String contactTitle, - @JsonProperty( - "contact_phone_number" - ) final com.twilio.type.PhoneNumber contactPhoneNumber, - @JsonProperty( - "bulk_hosting_request_sid" - ) final String bulkHostingRequestSid, - @JsonProperty("next_step") final String nextStep, - @JsonProperty( - "verification_attempts" - ) final Integer verificationAttempts, - @JsonProperty("verification_call_sids") final List< - String - > verificationCallSids, - @JsonProperty( - "verification_call_delay" - ) final Integer verificationCallDelay, - @JsonProperty( - "verification_call_extension" - ) final String verificationCallExtension, - @JsonProperty("verification_code") final String verificationCode, - @JsonProperty( - "verification_type" - ) final HostedNumberOrder.VerificationType verificationType + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("address_sid") final String addressSid, + @JsonProperty("bulk_hosting_request_sid") final String bulkHostingRequestSid, + @JsonProperty("capabilities") final PhoneNumberCapabilities capabilities, + @JsonProperty("cc_emails") final List ccEmails, + @JsonProperty("contact_phone_number") final com.twilio.type.PhoneNumber contactPhoneNumber, + @JsonProperty("contact_title") final String contactTitle, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("email") final String email, + @JsonProperty("failure_reason") final String failureReason, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("incoming_phone_number_sid") final String incomingPhoneNumberSid, + @JsonProperty("next_step") final String nextStep, + @JsonProperty("phone_number") final com.twilio.type.PhoneNumber phoneNumber, + @JsonProperty("sid") final String sid, + @JsonProperty("signing_document_sid") final String signingDocumentSid, + @JsonProperty("status") final HostedNumberOrder.Status status, + @JsonProperty("url") final URI url, + @JsonProperty("verification_attempts") final Integer verificationAttempts, + @JsonProperty("verification_call_delay") final Integer verificationCallDelay, + @JsonProperty("verification_call_extension") final String verificationCallExtension, + @JsonProperty("verification_call_sids") final List verificationCallSids, + @JsonProperty("verification_code") final String verificationCode, + @JsonProperty("verification_type") final HostedNumberOrder.VerificationType verificationType ) { - this.sid = sid; this.accountSid = accountSid; - this.incomingPhoneNumberSid = incomingPhoneNumberSid; this.addressSid = addressSid; - this.signingDocumentSid = signingDocumentSid; - this.phoneNumber = phoneNumber; + this.bulkHostingRequestSid = bulkHostingRequestSid; this.capabilities = capabilities; - this.friendlyName = friendlyName; - this.status = status; - this.failureReason = failureReason; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); - this.email = email; this.ccEmails = ccEmails; - this.url = url; - this.contactTitle = contactTitle; this.contactPhoneNumber = contactPhoneNumber; - this.bulkHostingRequestSid = bulkHostingRequestSid; + this.contactTitle = contactTitle; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; + this.email = email; + this.failureReason = failureReason; + this.friendlyName = friendlyName; + this.incomingPhoneNumberSid = incomingPhoneNumberSid; this.nextStep = nextStep; + this.phoneNumber = phoneNumber; + this.sid = sid; + this.signingDocumentSid = signingDocumentSid; + this.status = status; + this.url = url; this.verificationAttempts = verificationAttempts; - this.verificationCallSids = verificationCallSids; this.verificationCallDelay = verificationCallDelay; this.verificationCallExtension = verificationCallExtension; + this.verificationCallSids = verificationCallSids; this.verificationCode = verificationCode; this.verificationType = verificationType; } - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getIncomingPhoneNumberSid() { - return this.incomingPhoneNumberSid; - } - - public final String getAddressSid() { - return this.addressSid; - } - - public final String getSigningDocumentSid() { - return this.signingDocumentSid; - } - - public final com.twilio.type.PhoneNumber getPhoneNumber() { - return this.phoneNumber; - } - - public final PhoneNumberCapabilities getCapabilities() { - return this.capabilities; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final HostedNumberOrder.Status getStatus() { - return this.status; - } - - public final String getFailureReason() { - return this.failureReason; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final String getEmail() { - return this.email; - } - - public final List getCcEmails() { - return this.ccEmails; - } - - public final URI getUrl() { - return this.url; - } - - public final String getContactTitle() { - return this.contactTitle; - } - - public final com.twilio.type.PhoneNumber getContactPhoneNumber() { - return this.contactPhoneNumber; - } - - public final String getBulkHostingRequestSid() { - return this.bulkHostingRequestSid; - } - - public final String getNextStep() { - return this.nextStep; - } - - public final Integer getVerificationAttempts() { - return this.verificationAttempts; - } - - public final List getVerificationCallSids() { - return this.verificationCallSids; - } - - public final Integer getVerificationCallDelay() { - return this.verificationCallDelay; - } - - public final String getVerificationCallExtension() { - return this.verificationCallExtension; - } - - public final String getVerificationCode() { - return this.verificationCode; - } - - public final HostedNumberOrder.VerificationType getVerificationType() { - return this.verificationType; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -329,123 +294,66 @@ public boolean equals(final Object o) { } HostedNumberOrder other = (HostedNumberOrder) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals( - incomingPhoneNumberSid, - other.incomingPhoneNumberSid - ) && - Objects.equals(addressSid, other.addressSid) && - Objects.equals(signingDocumentSid, other.signingDocumentSid) && - Objects.equals(phoneNumber, other.phoneNumber) && - Objects.equals(capabilities, other.capabilities) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(status, other.status) && - Objects.equals(failureReason, other.failureReason) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(email, other.email) && - Objects.equals(ccEmails, other.ccEmails) && - Objects.equals(url, other.url) && - Objects.equals(contactTitle, other.contactTitle) && - Objects.equals(contactPhoneNumber, other.contactPhoneNumber) && - Objects.equals( - bulkHostingRequestSid, - other.bulkHostingRequestSid - ) && - Objects.equals(nextStep, other.nextStep) && - Objects.equals(verificationAttempts, other.verificationAttempts) && - Objects.equals(verificationCallSids, other.verificationCallSids) && - Objects.equals( - verificationCallDelay, - other.verificationCallDelay - ) && - Objects.equals( - verificationCallExtension, - other.verificationCallExtension - ) && - Objects.equals(verificationCode, other.verificationCode) && - Objects.equals(verificationType, other.verificationType) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(addressSid, other.addressSid) && + Objects.equals(bulkHostingRequestSid, other.bulkHostingRequestSid) && + Objects.equals(capabilities, other.capabilities) && + Objects.equals(ccEmails, other.ccEmails) && + Objects.equals(contactPhoneNumber, other.contactPhoneNumber) && + Objects.equals(contactTitle, other.contactTitle) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(email, other.email) && + Objects.equals(failureReason, other.failureReason) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(incomingPhoneNumberSid, other.incomingPhoneNumberSid) && + Objects.equals(nextStep, other.nextStep) && + Objects.equals(phoneNumber, other.phoneNumber) && + Objects.equals(sid, other.sid) && + Objects.equals(signingDocumentSid, other.signingDocumentSid) && + Objects.equals(status, other.status) && + Objects.equals(url, other.url) && + Objects.equals(verificationAttempts, other.verificationAttempts) && + Objects.equals(verificationCallDelay, other.verificationCallDelay) && + Objects.equals(verificationCallExtension, other.verificationCallExtension) && + Objects.equals(verificationCallSids, other.verificationCallSids) && + Objects.equals(verificationCode, other.verificationCode) && + Objects.equals(verificationType, other.verificationType) ); } @Override public int hashCode() { return Objects.hash( - sid, - accountSid, - incomingPhoneNumberSid, - addressSid, - signingDocumentSid, - phoneNumber, - capabilities, - friendlyName, - status, - failureReason, - dateCreated, - dateUpdated, - email, - ccEmails, - url, - contactTitle, - contactPhoneNumber, - bulkHostingRequestSid, - nextStep, - verificationAttempts, - verificationCallSids, - verificationCallDelay, - verificationCallExtension, - verificationCode, - verificationType + accountSid, + addressSid, + bulkHostingRequestSid, + capabilities, + ccEmails, + contactPhoneNumber, + contactTitle, + dateCreated, + dateUpdated, + email, + failureReason, + friendlyName, + incomingPhoneNumberSid, + nextStep, + phoneNumber, + sid, + signingDocumentSid, + status, + url, + verificationAttempts, + verificationCallDelay, + verificationCallExtension, + verificationCallSids, + verificationCode, + verificationType ); } - public enum Status { - TWILIO_PROCESSING("twilio-processing"), - RECEIVED("received"), - PENDING_VERIFICATION("pending-verification"), - VERIFIED("verified"), - PENDING_LOA("pending-loa"), - CARRIER_PROCESSING("carrier-processing"), - TESTING("testing"), - COMPLETED("completed"), - FAILED("failed"), - ACTION_REQUIRED("action-required"); - private final String value; - - private Status(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static Status forValue(final String value) { - return Promoter.enumFromString(value, Status.values()); - } - } - - public enum VerificationType { - PHONE_CALL("phone-call"); - - private final String value; - - private VerificationType(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static VerificationType forValue(final String value) { - return Promoter.enumFromString(value, VerificationType.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/numbers/v2/HostedNumberOrderCreator.java b/src/main/java/com/twilio/rest/numbers/v2/HostedNumberOrderCreator.java index 1345e5ce8a..f931ad026a 100644 --- a/src/main/java/com/twilio/rest/numbers/v2/HostedNumberOrderCreator.java +++ b/src/main/java/com/twilio/rest/numbers/v2/HostedNumberOrderCreator.java @@ -14,9 +14,12 @@ package com.twilio.rest.numbers.v2; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; import com.twilio.converter.Promoter; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,9 +28,8 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.net.URI; -import java.net.URI; -import java.util.List; import java.util.List; public class HostedNumberOrderCreator extends Creator { @@ -49,21 +51,15 @@ public class HostedNumberOrderCreator extends Creator { private String smsApplicationSid; private String contactTitle; - public HostedNumberOrderCreator( - final com.twilio.type.PhoneNumber phoneNumber, - final com.twilio.type.PhoneNumber contactPhoneNumber, - final String addressSid, - final String email - ) { + public HostedNumberOrderCreator(final com.twilio.type.PhoneNumber phoneNumber, final com.twilio.type.PhoneNumber contactPhoneNumber, final String addressSid, final String email) { this.phoneNumber = phoneNumber; this.contactPhoneNumber = contactPhoneNumber; this.addressSid = addressSid; this.email = email; } - public HostedNumberOrderCreator setPhoneNumber( - final com.twilio.type.PhoneNumber phoneNumber - ) { + + public HostedNumberOrderCreator setPhoneNumber(final com.twilio.type.PhoneNumber phoneNumber) { this.phoneNumber = phoneNumber; return this; } @@ -72,19 +68,13 @@ public HostedNumberOrderCreator setPhoneNumber(final String phoneNumber) { return setPhoneNumber(Promoter.phoneNumberFromString(phoneNumber)); } - public HostedNumberOrderCreator setContactPhoneNumber( - final com.twilio.type.PhoneNumber contactPhoneNumber - ) { + public HostedNumberOrderCreator setContactPhoneNumber(final com.twilio.type.PhoneNumber contactPhoneNumber) { this.contactPhoneNumber = contactPhoneNumber; return this; } - public HostedNumberOrderCreator setContactPhoneNumber( - final String contactPhoneNumber - ) { - return setContactPhoneNumber( - Promoter.phoneNumberFromString(contactPhoneNumber) - ); + public HostedNumberOrderCreator setContactPhoneNumber(final String contactPhoneNumber) { + return setContactPhoneNumber(Promoter.phoneNumberFromString(contactPhoneNumber)); } public HostedNumberOrderCreator setAddressSid(final String addressSid) { @@ -92,21 +82,25 @@ public HostedNumberOrderCreator setAddressSid(final String addressSid) { return this; } + public HostedNumberOrderCreator setEmail(final String email) { this.email = email; return this; } + public HostedNumberOrderCreator setAccountSid(final String accountSid) { this.accountSid = accountSid; return this; } + public HostedNumberOrderCreator setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + public HostedNumberOrderCreator setCcEmails(final List ccEmails) { this.ccEmails = ccEmails; return this; @@ -121,186 +115,170 @@ public HostedNumberOrderCreator setSmsUrl(final URI smsUrl) { return this; } - public HostedNumberOrderCreator setSmsUrl(final String smsUrl) { - return setSmsUrl(Promoter.uriFromString(smsUrl)); - } public HostedNumberOrderCreator setSmsMethod(final HttpMethod smsMethod) { this.smsMethod = smsMethod; return this; } - public HostedNumberOrderCreator setSmsFallbackUrl( - final URI smsFallbackUrl - ) { + + public HostedNumberOrderCreator setSmsFallbackUrl(final URI smsFallbackUrl) { this.smsFallbackUrl = smsFallbackUrl; return this; } - public HostedNumberOrderCreator setSmsFallbackUrl( - final String smsFallbackUrl - ) { - return setSmsFallbackUrl(Promoter.uriFromString(smsFallbackUrl)); - } - public HostedNumberOrderCreator setSmsCapability( - final Boolean smsCapability - ) { + public HostedNumberOrderCreator setSmsCapability(final Boolean smsCapability) { this.smsCapability = smsCapability; return this; } - public HostedNumberOrderCreator setSmsFallbackMethod( - final HttpMethod smsFallbackMethod - ) { + + public HostedNumberOrderCreator setSmsFallbackMethod(final HttpMethod smsFallbackMethod) { this.smsFallbackMethod = smsFallbackMethod; return this; } - public HostedNumberOrderCreator setStatusCallbackUrl( - final URI statusCallbackUrl - ) { + + public HostedNumberOrderCreator setStatusCallbackUrl(final URI statusCallbackUrl) { this.statusCallbackUrl = statusCallbackUrl; return this; } - public HostedNumberOrderCreator setStatusCallbackUrl( - final String statusCallbackUrl - ) { - return setStatusCallbackUrl(Promoter.uriFromString(statusCallbackUrl)); - } - public HostedNumberOrderCreator setStatusCallbackMethod( - final HttpMethod statusCallbackMethod - ) { + public HostedNumberOrderCreator setStatusCallbackMethod(final HttpMethod statusCallbackMethod) { this.statusCallbackMethod = statusCallbackMethod; return this; } - public HostedNumberOrderCreator setSmsApplicationSid( - final String smsApplicationSid - ) { + + public HostedNumberOrderCreator setSmsApplicationSid(final String smsApplicationSid) { this.smsApplicationSid = smsApplicationSid; return this; } + public HostedNumberOrderCreator setContactTitle(final String contactTitle) { this.contactTitle = contactTitle; return this; } + @Override public HostedNumberOrder create(final TwilioRestClient client) { + String path = "/v2/HostedNumber/Orders"; - path = - path.replace( - "{" + "PhoneNumber" + "}", - this.phoneNumber.toString() - ); - path = - path.replace( - "{" + "ContactPhoneNumber" + "}", - this.contactPhoneNumber.toString() - ); - path = - path.replace("{" + "AddressSid" + "}", this.addressSid.toString()); - path = path.replace("{" + "Email" + "}", this.email.toString()); Request request = new Request( - HttpMethod.POST, - Domains.NUMBERS.toString(), - path + HttpMethod.POST, + Domains.NUMBERS.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "HostedNumberOrder creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("HostedNumberOrder creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return HostedNumberOrder.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return HostedNumberOrder.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (phoneNumber != null) { - request.addPostParam("PhoneNumber", phoneNumber.toString()); + Serializer.toString(request, "PhoneNumber", phoneNumber, ParameterType.URLENCODED); } + + if (contactPhoneNumber != null) { - request.addPostParam( - "ContactPhoneNumber", - contactPhoneNumber.toString() - ); + Serializer.toString(request, "ContactPhoneNumber", contactPhoneNumber, ParameterType.URLENCODED); } + + if (addressSid != null) { - request.addPostParam("AddressSid", addressSid); + Serializer.toString(request, "AddressSid", addressSid, ParameterType.URLENCODED); } + + if (email != null) { - request.addPostParam("Email", email); + Serializer.toString(request, "Email", email, ParameterType.URLENCODED); } + + if (accountSid != null) { - request.addPostParam("AccountSid", accountSid); + Serializer.toString(request, "AccountSid", accountSid, ParameterType.URLENCODED); } + + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + if (ccEmails != null) { - for (String prop : ccEmails) { - request.addPostParam("CcEmails", prop); + for (String param : ccEmails) { + Serializer.toString(request, "CcEmails", param, ParameterType.URLENCODED); } } + + if (smsUrl != null) { - request.addPostParam("SmsUrl", smsUrl.toString()); + Serializer.toString(request, "SmsUrl", smsUrl, ParameterType.URLENCODED); } + + if (smsMethod != null) { - request.addPostParam("SmsMethod", smsMethod.toString()); + Serializer.toString(request, "SmsMethod", smsMethod, ParameterType.URLENCODED); } + + if (smsFallbackUrl != null) { - request.addPostParam("SmsFallbackUrl", smsFallbackUrl.toString()); + Serializer.toString(request, "SmsFallbackUrl", smsFallbackUrl, ParameterType.URLENCODED); } + + if (smsCapability != null) { - request.addPostParam("SmsCapability", smsCapability.toString()); + Serializer.toString(request, "SmsCapability", smsCapability, ParameterType.URLENCODED); } + + if (smsFallbackMethod != null) { - request.addPostParam( - "SmsFallbackMethod", - smsFallbackMethod.toString() - ); + Serializer.toString(request, "SmsFallbackMethod", smsFallbackMethod, ParameterType.URLENCODED); } + + if (statusCallbackUrl != null) { - request.addPostParam( - "StatusCallbackUrl", - statusCallbackUrl.toString() - ); + Serializer.toString(request, "StatusCallbackUrl", statusCallbackUrl, ParameterType.URLENCODED); } + + if (statusCallbackMethod != null) { - request.addPostParam( - "StatusCallbackMethod", - statusCallbackMethod.toString() - ); + Serializer.toString(request, "StatusCallbackMethod", statusCallbackMethod, ParameterType.URLENCODED); } + + if (smsApplicationSid != null) { - request.addPostParam("SmsApplicationSid", smsApplicationSid); + Serializer.toString(request, "SmsApplicationSid", smsApplicationSid, ParameterType.URLENCODED); } + + if (contactTitle != null) { - request.addPostParam("ContactTitle", contactTitle); + Serializer.toString(request, "ContactTitle", contactTitle, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/numbers/v2/HostedNumberOrderDeleter.java b/src/main/java/com/twilio/rest/numbers/v2/HostedNumberOrderDeleter.java index 504a447748..7404902816 100644 --- a/src/main/java/com/twilio/rest/numbers/v2/HostedNumberOrderDeleter.java +++ b/src/main/java/com/twilio/rest/numbers/v2/HostedNumberOrderDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.numbers.v2; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,40 +26,38 @@ public class HostedNumberOrderDeleter extends Deleter { - private String pathSid; + private String pathsid; - public HostedNumberOrderDeleter(final String pathSid) { - this.pathSid = pathSid; + public HostedNumberOrderDeleter(final String pathsid) { + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/v2/HostedNumber/Orders/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.NUMBERS.toString(), - path + HttpMethod.DELETE, + Domains.NUMBERS.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "HostedNumberOrder delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("HostedNumberOrder delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/numbers/v2/HostedNumberOrderFetcher.java b/src/main/java/com/twilio/rest/numbers/v2/HostedNumberOrderFetcher.java index 5388c976bf..5c33ba3140 100644 --- a/src/main/java/com/twilio/rest/numbers/v2/HostedNumberOrderFetcher.java +++ b/src/main/java/com/twilio/rest/numbers/v2/HostedNumberOrderFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.numbers.v2; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,47 +26,41 @@ public class HostedNumberOrderFetcher extends Fetcher { - private String pathSid; + private String pathsid; - public HostedNumberOrderFetcher(final String pathSid) { - this.pathSid = pathSid; + public HostedNumberOrderFetcher(final String pathsid) { + this.pathsid = pathsid; } + @Override public HostedNumberOrder fetch(final TwilioRestClient client) { + String path = "/v2/HostedNumber/Orders/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.NUMBERS.toString(), - path + HttpMethod.GET, + Domains.NUMBERS.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "HostedNumberOrder fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("HostedNumberOrder fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return HostedNumberOrder.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return HostedNumberOrder.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/numbers/v2/HostedNumberOrderReader.java b/src/main/java/com/twilio/rest/numbers/v2/HostedNumberOrderReader.java index 09bfabf89b..7519fcf70f 100644 --- a/src/main/java/com/twilio/rest/numbers/v2/HostedNumberOrderReader.java +++ b/src/main/java/com/twilio/rest/numbers/v2/HostedNumberOrderReader.java @@ -17,8 +17,9 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; import com.twilio.converter.Promoter; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -37,25 +38,23 @@ public class HostedNumberOrderReader extends Reader { private String friendlyName; private Long pageSize; - public HostedNumberOrderReader() {} + public HostedNumberOrderReader() { + } + - public HostedNumberOrderReader setStatus( - final HostedNumberOrder.Status status - ) { + public HostedNumberOrderReader setStatus(final HostedNumberOrder.Status status) { this.status = status; return this; } - public HostedNumberOrderReader setSmsCapability( - final Boolean smsCapability - ) { + + public HostedNumberOrderReader setSmsCapability(final Boolean smsCapability) { this.smsCapability = smsCapability; return this; } - public HostedNumberOrderReader setPhoneNumber( - final com.twilio.type.PhoneNumber phoneNumber - ) { + + public HostedNumberOrderReader setPhoneNumber(final com.twilio.type.PhoneNumber phoneNumber) { this.phoneNumber = phoneNumber; return this; } @@ -64,133 +63,116 @@ public HostedNumberOrderReader setPhoneNumber(final String phoneNumber) { return setPhoneNumber(Promoter.phoneNumberFromString(phoneNumber)); } - public HostedNumberOrderReader setIncomingPhoneNumberSid( - final String incomingPhoneNumberSid - ) { + public HostedNumberOrderReader setIncomingPhoneNumberSid(final String incomingPhoneNumberSid) { this.incomingPhoneNumberSid = incomingPhoneNumberSid; return this; } + public HostedNumberOrderReader setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + public HostedNumberOrderReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v2/HostedNumber/Orders"; + Request request = new Request( - HttpMethod.GET, - Domains.NUMBERS.toString(), - path + HttpMethod.GET, + Domains.NUMBERS.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "HostedNumberOrder read failed: Unable to connect to server" - ); + throw new ApiConnectionException("HostedNumberOrder read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "items", - response.getContent(), - HostedNumberOrder.class, - client.getObjectMapper() - ); + "items", + response.getContent(), + HostedNumberOrder.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.NUMBERS.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.NUMBERS.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (status != null) { - request.addQueryParam("Status", status.toString()); + Serializer.toString(request, "Status", status, ParameterType.QUERY); } + + if (smsCapability != null) { - request.addQueryParam("SmsCapability", smsCapability.toString()); + Serializer.toString(request, "SmsCapability", smsCapability, ParameterType.QUERY); } + + if (phoneNumber != null) { - request.addQueryParam("PhoneNumber", phoneNumber.toString()); + Serializer.toString(request, "PhoneNumber", phoneNumber, ParameterType.QUERY); } + + if (incomingPhoneNumberSid != null) { - request.addQueryParam( - "IncomingPhoneNumberSid", - incomingPhoneNumberSid - ); + Serializer.toString(request, "IncomingPhoneNumberSid", incomingPhoneNumberSid, ParameterType.QUERY); } + + if (friendlyName != null) { - request.addQueryParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.QUERY); } + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/numbers/v2/HostedNumberOrderUpdater.java b/src/main/java/com/twilio/rest/numbers/v2/HostedNumberOrderUpdater.java index 3bbc4823fa..f4c052e7a2 100644 --- a/src/main/java/com/twilio/rest/numbers/v2/HostedNumberOrderUpdater.java +++ b/src/main/java/com/twilio/rest/numbers/v2/HostedNumberOrderUpdater.java @@ -16,6 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -26,95 +28,85 @@ import com.twilio.rest.Domains; public class HostedNumberOrderUpdater extends Updater { - - private String pathSid; + private String pathsid; private HostedNumberOrder.Status status; private Integer verificationCallDelay; private String verificationCallExtension; - public HostedNumberOrderUpdater( - final String pathSid, - final HostedNumberOrder.Status status - ) { - this.pathSid = pathSid; + public HostedNumberOrderUpdater(final String pathsid, final HostedNumberOrder.Status status) { + this.pathsid = pathsid; this.status = status; } - public HostedNumberOrderUpdater setStatus( - final HostedNumberOrder.Status status - ) { + + public HostedNumberOrderUpdater setStatus(final HostedNumberOrder.Status status) { this.status = status; return this; } - public HostedNumberOrderUpdater setVerificationCallDelay( - final Integer verificationCallDelay - ) { + + public HostedNumberOrderUpdater setVerificationCallDelay(final Integer verificationCallDelay) { this.verificationCallDelay = verificationCallDelay; return this; } - public HostedNumberOrderUpdater setVerificationCallExtension( - final String verificationCallExtension - ) { + + public HostedNumberOrderUpdater setVerificationCallExtension(final String verificationCallExtension) { this.verificationCallExtension = verificationCallExtension; return this; } + @Override public HostedNumberOrder update(final TwilioRestClient client) { + String path = "/v2/HostedNumber/Orders/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); - path = path.replace("{" + "Status" + "}", this.status.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.NUMBERS.toString(), - path + HttpMethod.POST, + Domains.NUMBERS.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "HostedNumberOrder update failed: Unable to connect to server" - ); + throw new ApiConnectionException("HostedNumberOrder update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return HostedNumberOrder.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return HostedNumberOrder.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (status != null) { - request.addPostParam("Status", status.toString()); + Serializer.toString(request, "Status", status, ParameterType.URLENCODED); } + + if (verificationCallDelay != null) { - request.addPostParam( - "VerificationCallDelay", - verificationCallDelay.toString() - ); + Serializer.toString(request, "VerificationCallDelay", verificationCallDelay, ParameterType.URLENCODED); } + + if (verificationCallExtension != null) { - request.addPostParam( - "VerificationCallExtension", - verificationCallExtension - ); + Serializer.toString(request, "VerificationCallExtension", verificationCallExtension, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/numbers/v2/authorizationdocument/DependentHostedNumberOrder.java b/src/main/java/com/twilio/rest/numbers/v2/authorizationdocument/DependentHostedNumberOrder.java index 01b4345f77..14329df912 100644 --- a/src/main/java/com/twilio/rest/numbers/v2/authorizationdocument/DependentHostedNumberOrder.java +++ b/src/main/java/com/twilio/rest/numbers/v2/authorizationdocument/DependentHostedNumberOrder.java @@ -18,51 +18,73 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.type.PhoneNumberCapabilities; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.time.ZonedDateTime; import java.util.List; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class DependentHostedNumberOrder extends Resource { - private static final long serialVersionUID = 76724825729320L; - public static DependentHostedNumberOrderReader reader( - final String pathSigningDocumentSid - ) { - return new DependentHostedNumberOrderReader(pathSigningDocumentSid); + public static DependentHostedNumberOrderReader reader(final String pathsigningDocumentSid) { + return new DependentHostedNumberOrderReader( + pathsigningDocumentSid + ); } + + public enum Status { + RECEIVED("received"), + VERIFIED("verified"), + PENDING_LOA("pending-loa"), + CARRIER_PROCESSING("carrier-processing"), + COMPLETED("completed"), + FAILED("failed"), + ACTION_REQUIRED("action-required"); + + private final String value; + + private Status(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static Status forValue(final String value) { + return Promoter.enumFromString(value, Status.values()); + } + } + + /** * Converts a JSON String into a DependentHostedNumberOrder object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return DependentHostedNumberOrder object represented by the provided JSON */ - public static DependentHostedNumberOrder fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static DependentHostedNumberOrder fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { - return objectMapper.readValue( - json, - DependentHostedNumberOrder.class - ); + return objectMapper.readValue(json, DependentHostedNumberOrder.class); } catch (final JsonMappingException | JsonParseException e) { throw new ApiException(e.getMessage(), e); } catch (final IOException e) { @@ -74,20 +96,14 @@ public static DependentHostedNumberOrder fromJson( * Converts a JSON InputStream into a DependentHostedNumberOrder object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return DependentHostedNumberOrder object represented by the provided JSON */ - public static DependentHostedNumberOrder fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static DependentHostedNumberOrder fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { - return objectMapper.readValue( - json, - DependentHostedNumberOrder.class - ); + return objectMapper.readValue(json, DependentHostedNumberOrder.class); } catch (final JsonMappingException | JsonParseException e) { throw new ApiException(e.getMessage(), e); } catch (final IOException e) { @@ -95,146 +111,97 @@ public static DependentHostedNumberOrder fromJson( } } - private final String sid; - private final String bulkHostingRequestSid; - private final String nextStep; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String incomingPhoneNumberSid; + @Getter private final String addressSid; - private final String signingDocumentSid; - private final com.twilio.type.PhoneNumber phoneNumber; + @Getter + private final String bulkHostingRequestSid; + @Getter private final PhoneNumberCapabilities capabilities; - private final String friendlyName; - private final DependentHostedNumberOrder.Status status; - private final String failureReason; + @Getter + private final List ccEmails; + @Getter + private final com.twilio.type.PhoneNumber contactPhoneNumber; + @Getter + private final String contactTitle; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; + @Getter private final String email; - private final List ccEmails; - private final String contactTitle; - private final com.twilio.type.PhoneNumber contactPhoneNumber; + @Getter + private final String failureReason; + @Getter + private final String friendlyName; + @Getter + private final String incomingPhoneNumberSid; + @Getter + private final String nextStep; + @Getter + private final com.twilio.type.PhoneNumber phoneNumber; + @Getter + private final String sid; + @Getter + private final String signingDocumentSid; + @Getter + private final DependentHostedNumberOrder.Status status; @JsonCreator private DependentHostedNumberOrder( - @JsonProperty("sid") final String sid, - @JsonProperty( - "bulk_hosting_request_sid" - ) final String bulkHostingRequestSid, - @JsonProperty("next_step") final String nextStep, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty( - "incoming_phone_number_sid" - ) final String incomingPhoneNumberSid, - @JsonProperty("address_sid") final String addressSid, - @JsonProperty("signing_document_sid") final String signingDocumentSid, - @JsonProperty( - "phone_number" - ) final com.twilio.type.PhoneNumber phoneNumber, - @JsonProperty( - "capabilities" - ) final PhoneNumberCapabilities capabilities, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("status") final DependentHostedNumberOrder.Status status, - @JsonProperty("failure_reason") final String failureReason, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("email") final String email, - @JsonProperty("cc_emails") final List ccEmails, - @JsonProperty("contact_title") final String contactTitle, - @JsonProperty( - "contact_phone_number" - ) final com.twilio.type.PhoneNumber contactPhoneNumber + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("address_sid") final String addressSid, + @JsonProperty("bulk_hosting_request_sid") final String bulkHostingRequestSid, + @JsonProperty("capabilities") final PhoneNumberCapabilities capabilities, + @JsonProperty("cc_emails") final List ccEmails, + @JsonProperty("contact_phone_number") final com.twilio.type.PhoneNumber contactPhoneNumber, + @JsonProperty("contact_title") final String contactTitle, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("email") final String email, + @JsonProperty("failure_reason") final String failureReason, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("incoming_phone_number_sid") final String incomingPhoneNumberSid, + @JsonProperty("next_step") final String nextStep, + @JsonProperty("phone_number") final com.twilio.type.PhoneNumber phoneNumber, + @JsonProperty("sid") final String sid, + @JsonProperty("signing_document_sid") final String signingDocumentSid, + @JsonProperty("status") final DependentHostedNumberOrder.Status status ) { - this.sid = sid; - this.bulkHostingRequestSid = bulkHostingRequestSid; - this.nextStep = nextStep; this.accountSid = accountSid; - this.incomingPhoneNumberSid = incomingPhoneNumberSid; this.addressSid = addressSid; - this.signingDocumentSid = signingDocumentSid; - this.phoneNumber = phoneNumber; + this.bulkHostingRequestSid = bulkHostingRequestSid; this.capabilities = capabilities; - this.friendlyName = friendlyName; - this.status = status; - this.failureReason = failureReason; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); - this.email = email; this.ccEmails = ccEmails; - this.contactTitle = contactTitle; this.contactPhoneNumber = contactPhoneNumber; - } - - public final String getSid() { - return this.sid; - } - - public final String getBulkHostingRequestSid() { - return this.bulkHostingRequestSid; - } - - public final String getNextStep() { - return this.nextStep; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getIncomingPhoneNumberSid() { - return this.incomingPhoneNumberSid; - } - - public final String getAddressSid() { - return this.addressSid; - } - - public final String getSigningDocumentSid() { - return this.signingDocumentSid; - } - - public final com.twilio.type.PhoneNumber getPhoneNumber() { - return this.phoneNumber; - } - - public final PhoneNumberCapabilities getCapabilities() { - return this.capabilities; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final DependentHostedNumberOrder.Status getStatus() { - return this.status; - } - - public final String getFailureReason() { - return this.failureReason; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final String getEmail() { - return this.email; - } - - public final List getCcEmails() { - return this.ccEmails; - } - - public final String getContactTitle() { - return this.contactTitle; - } - - public final com.twilio.type.PhoneNumber getContactPhoneNumber() { - return this.contactPhoneNumber; + this.contactTitle = contactTitle; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; + this.email = email; + this.failureReason = failureReason; + this.friendlyName = friendlyName; + this.incomingPhoneNumberSid = incomingPhoneNumberSid; + this.nextStep = nextStep; + this.phoneNumber = phoneNumber; + this.sid = sid; + this.signingDocumentSid = signingDocumentSid; + this.status = status; } @Override @@ -248,81 +215,52 @@ public boolean equals(final Object o) { } DependentHostedNumberOrder other = (DependentHostedNumberOrder) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals( - bulkHostingRequestSid, - other.bulkHostingRequestSid - ) && - Objects.equals(nextStep, other.nextStep) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals( - incomingPhoneNumberSid, - other.incomingPhoneNumberSid - ) && - Objects.equals(addressSid, other.addressSid) && - Objects.equals(signingDocumentSid, other.signingDocumentSid) && - Objects.equals(phoneNumber, other.phoneNumber) && - Objects.equals(capabilities, other.capabilities) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(status, other.status) && - Objects.equals(failureReason, other.failureReason) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(email, other.email) && - Objects.equals(ccEmails, other.ccEmails) && - Objects.equals(contactTitle, other.contactTitle) && - Objects.equals(contactPhoneNumber, other.contactPhoneNumber) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(addressSid, other.addressSid) && + Objects.equals(bulkHostingRequestSid, other.bulkHostingRequestSid) && + Objects.equals(capabilities, other.capabilities) && + Objects.equals(ccEmails, other.ccEmails) && + Objects.equals(contactPhoneNumber, other.contactPhoneNumber) && + Objects.equals(contactTitle, other.contactTitle) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(email, other.email) && + Objects.equals(failureReason, other.failureReason) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(incomingPhoneNumberSid, other.incomingPhoneNumberSid) && + Objects.equals(nextStep, other.nextStep) && + Objects.equals(phoneNumber, other.phoneNumber) && + Objects.equals(sid, other.sid) && + Objects.equals(signingDocumentSid, other.signingDocumentSid) && + Objects.equals(status, other.status) ); } @Override public int hashCode() { return Objects.hash( - sid, - bulkHostingRequestSid, - nextStep, - accountSid, - incomingPhoneNumberSid, - addressSid, - signingDocumentSid, - phoneNumber, - capabilities, - friendlyName, - status, - failureReason, - dateCreated, - dateUpdated, - email, - ccEmails, - contactTitle, - contactPhoneNumber + accountSid, + addressSid, + bulkHostingRequestSid, + capabilities, + ccEmails, + contactPhoneNumber, + contactTitle, + dateCreated, + dateUpdated, + email, + failureReason, + friendlyName, + incomingPhoneNumberSid, + nextStep, + phoneNumber, + sid, + signingDocumentSid, + status ); } - public enum Status { - RECEIVED("received"), - VERIFIED("verified"), - PENDING_LOA("pending-loa"), - CARRIER_PROCESSING("carrier-processing"), - COMPLETED("completed"), - FAILED("failed"), - ACTION_REQUIRED("action-required"); - - private final String value; - - private Status(final String value) { - this.value = value; - } - public String toString() { - return value; - } - - @JsonCreator - public static Status forValue(final String value) { - return Promoter.enumFromString(value, Status.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/numbers/v2/authorizationdocument/DependentHostedNumberOrderReader.java b/src/main/java/com/twilio/rest/numbers/v2/authorizationdocument/DependentHostedNumberOrderReader.java index 7256d833a6..62248c408e 100644 --- a/src/main/java/com/twilio/rest/numbers/v2/authorizationdocument/DependentHostedNumberOrderReader.java +++ b/src/main/java/com/twilio/rest/numbers/v2/authorizationdocument/DependentHostedNumberOrderReader.java @@ -17,8 +17,9 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; import com.twilio.converter.Promoter; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -28,178 +29,141 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class DependentHostedNumberOrderReader - extends Reader { +public class DependentHostedNumberOrderReader extends Reader { - private String pathSigningDocumentSid; + private String pathsigningDocumentSid; private DependentHostedNumberOrder.Status status; private com.twilio.type.PhoneNumber phoneNumber; private String incomingPhoneNumberSid; private String friendlyName; private Long pageSize; - public DependentHostedNumberOrderReader( - final String pathSigningDocumentSid - ) { - this.pathSigningDocumentSid = pathSigningDocumentSid; + public DependentHostedNumberOrderReader(final String pathsigningDocumentSid) { + this.pathsigningDocumentSid = pathsigningDocumentSid; } - public DependentHostedNumberOrderReader setStatus( - final DependentHostedNumberOrder.Status status - ) { + + public DependentHostedNumberOrderReader setStatus(final DependentHostedNumberOrder.Status status) { this.status = status; return this; } - public DependentHostedNumberOrderReader setPhoneNumber( - final com.twilio.type.PhoneNumber phoneNumber - ) { + + public DependentHostedNumberOrderReader setPhoneNumber(final com.twilio.type.PhoneNumber phoneNumber) { this.phoneNumber = phoneNumber; return this; } - public DependentHostedNumberOrderReader setPhoneNumber( - final String phoneNumber - ) { + public DependentHostedNumberOrderReader setPhoneNumber(final String phoneNumber) { return setPhoneNumber(Promoter.phoneNumberFromString(phoneNumber)); } - public DependentHostedNumberOrderReader setIncomingPhoneNumberSid( - final String incomingPhoneNumberSid - ) { + public DependentHostedNumberOrderReader setIncomingPhoneNumberSid(final String incomingPhoneNumberSid) { this.incomingPhoneNumberSid = incomingPhoneNumberSid; return this; } - public DependentHostedNumberOrderReader setFriendlyName( - final String friendlyName - ) { + + public DependentHostedNumberOrderReader setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + public DependentHostedNumberOrderReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override - public ResourceSet read( - final TwilioRestClient client - ) { + public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } - public Page firstPage( - final TwilioRestClient client - ) { - String path = - "/v2/HostedNumber/AuthorizationDocuments/{SigningDocumentSid}/DependentHostedNumberOrders"; - path = - path.replace( - "{" + "SigningDocumentSid" + "}", - this.pathSigningDocumentSid.toString() - ); + public Page firstPage(final TwilioRestClient client) { + + String path = "/v2/HostedNumber/AuthorizationDocuments/{SigningDocumentSid}/DependentHostedNumberOrders"; + + path = path.replace("{" + "SigningDocumentSid" + "}", this.pathsigningDocumentSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.NUMBERS.toString(), - path + HttpMethod.GET, + Domains.NUMBERS.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "DependentHostedNumberOrder read failed: Unable to connect to server" - ); + throw new ApiConnectionException("DependentHostedNumberOrder read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "items", - response.getContent(), - DependentHostedNumberOrder.class, - client.getObjectMapper() - ); + "items", + response.getContent(), + DependentHostedNumberOrder.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.NUMBERS.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.NUMBERS.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (status != null) { - request.addQueryParam("Status", status.toString()); + Serializer.toString(request, "Status", status, ParameterType.QUERY); } + + if (phoneNumber != null) { - request.addQueryParam("PhoneNumber", phoneNumber.toString()); + Serializer.toString(request, "PhoneNumber", phoneNumber, ParameterType.QUERY); } + + if (incomingPhoneNumberSid != null) { - request.addQueryParam( - "IncomingPhoneNumberSid", - incomingPhoneNumberSid - ); + Serializer.toString(request, "IncomingPhoneNumberSid", incomingPhoneNumberSid, ParameterType.QUERY); } + + if (friendlyName != null) { - request.addQueryParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.QUERY); } + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/Bundle.java b/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/Bundle.java index 9371ac3164..ab242aadba 100644 --- a/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/Bundle.java +++ b/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/Bundle.java @@ -18,63 +18,157 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Bundle extends Resource { - private static final long serialVersionUID = 198185819431201L; - public static BundleCreator creator( - final String friendlyName, - final String email - ) { - return new BundleCreator(friendlyName, email); + public static BundleCreator creator(final String friendlyName, final String email) { + return new BundleCreator( + friendlyName, email + ); } - public static BundleDeleter deleter(final String pathSid) { - return new BundleDeleter(pathSid); + + public static BundleDeleter deleter(final String pathsid) { + return new BundleDeleter( + pathsid + ); } - public static BundleFetcher fetcher(final String pathSid) { - return new BundleFetcher(pathSid); + + public static BundleFetcher fetcher(final String pathsid) { + return new BundleFetcher( + pathsid + ); } + public static BundleReader reader() { - return new BundleReader(); + return new BundleReader( + + ); + } + + + public static BundleUpdater updater(final String pathsid) { + return new BundleUpdater( + pathsid + ); + } + + + public enum Status { + DRAFT("draft"), + PENDING_REVIEW("pending-review"), + IN_REVIEW("in-review"), + TWILIO_REJECTED("twilio-rejected"), + TWILIO_APPROVED("twilio-approved"), + PROVISIONALLY_APPROVED("provisionally-approved"); + + private final String value; + + private Status(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static Status forValue(final String value) { + return Promoter.enumFromString(value, Status.values()); + } + } + + public enum SortDirection { + ASC("ASC"), + DESC("DESC"); + + private final String value; + + private SortDirection(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static SortDirection forValue(final String value) { + return Promoter.enumFromString(value, SortDirection.values()); + } } - public static BundleUpdater updater(final String pathSid) { - return new BundleUpdater(pathSid); + public enum EndUserType { + INDIVIDUAL("individual"), + BUSINESS("business"); + + private final String value; + + private EndUserType(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static EndUserType forValue(final String value) { + return Promoter.enumFromString(value, EndUserType.values()); + } } + public enum SortBy { + VALID_UNTIL("valid-until"), + DATE_UPDATED("date-updated"); + + private final String value; + + private SortBy(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static SortBy forValue(final String value) { + return Promoter.enumFromString(value, SortBy.values()); + } + } + + /** * Converts a JSON String into a Bundle object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Bundle object represented by the provided JSON */ - public static Bundle fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Bundle fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Bundle.class); @@ -89,14 +183,11 @@ public static Bundle fromJson( * Converts a JSON InputStream into a Bundle object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Bundle object represented by the provided JSON */ - public static Bundle fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Bundle fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Bundle.class); @@ -107,94 +198,74 @@ public static Bundle fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String regulationSid; + @Getter + private final ZonedDateTime dateCreated; + @Getter + private final ZonedDateTime dateUpdated; + @Getter + private final String email; + @Getter private final String friendlyName; + @Getter + private final Map links; + @Getter + private final String regulationSid; + @Getter + private final String sid; + @Getter private final Bundle.Status status; - private final ZonedDateTime validUntil; - private final String email; + @Getter private final URI statusCallback; - private final ZonedDateTime dateCreated; - private final ZonedDateTime dateUpdated; + @Getter private final URI url; - private final Map links; + @Getter + private final ZonedDateTime validUntil; @JsonCreator private Bundle( - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("regulation_sid") final String regulationSid, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("status") final Bundle.Status status, - @JsonProperty("valid_until") final String validUntil, - @JsonProperty("email") final String email, - @JsonProperty("status_callback") final URI statusCallback, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("url") final URI url, - @JsonProperty("links") final Map links + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("email") final String email, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("links") final Map links, + @JsonProperty("regulation_sid") final String regulationSid, + @JsonProperty("sid") final String sid, + @JsonProperty("status") final Bundle.Status status, + @JsonProperty("status_callback") final URI statusCallback, + @JsonProperty("url") final URI url, + @JsonProperty("valid_until") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime validUntil ) { - this.sid = sid; this.accountSid = accountSid; - this.regulationSid = regulationSid; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; + this.email = email; this.friendlyName = friendlyName; + this.links = links; + this.regulationSid = regulationSid; + this.sid = sid; this.status = status; - this.validUntil = DateConverter.iso8601DateTimeFromString(validUntil); - this.email = email; this.statusCallback = statusCallback; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); this.url = url; - this.links = links; - } - - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getRegulationSid() { - return this.regulationSid; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final Bundle.Status getStatus() { - return this.status; - } - - public final ZonedDateTime getValidUntil() { - return this.validUntil; - } - - public final String getEmail() { - return this.email; - } - - public final URI getStatusCallback() { - return this.statusCallback; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final URI getUrl() { - return this.url; - } - - public final Map getLinks() { - return this.links; + this.validUntil = validUntil; } @Override @@ -208,122 +279,40 @@ public boolean equals(final Object o) { } Bundle other = (Bundle) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(regulationSid, other.regulationSid) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(status, other.status) && - Objects.equals(validUntil, other.validUntil) && - Objects.equals(email, other.email) && - Objects.equals(statusCallback, other.statusCallback) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(url, other.url) && - Objects.equals(links, other.links) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(email, other.email) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(links, other.links) && + Objects.equals(regulationSid, other.regulationSid) && + Objects.equals(sid, other.sid) && + Objects.equals(status, other.status) && + Objects.equals(statusCallback, other.statusCallback) && + Objects.equals(url, other.url) && + Objects.equals(validUntil, other.validUntil) ); } @Override public int hashCode() { return Objects.hash( - sid, - accountSid, - regulationSid, - friendlyName, - status, - validUntil, - email, - statusCallback, - dateCreated, - dateUpdated, - url, - links + accountSid, + dateCreated, + dateUpdated, + email, + friendlyName, + links, + regulationSid, + sid, + status, + statusCallback, + url, + validUntil ); } - public enum EndUserType { - INDIVIDUAL("individual"), - BUSINESS("business"); - - private final String value; - - private EndUserType(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - @JsonCreator - public static EndUserType forValue(final String value) { - return Promoter.enumFromString(value, EndUserType.values()); - } - } - - public enum Status { - DRAFT("draft"), - PENDING_REVIEW("pending-review"), - IN_REVIEW("in-review"), - TWILIO_REJECTED("twilio-rejected"), - TWILIO_APPROVED("twilio-approved"), - PROVISIONALLY_APPROVED("provisionally-approved"); - - private final String value; - - private Status(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static Status forValue(final String value) { - return Promoter.enumFromString(value, Status.values()); - } - } - - public enum SortBy { - VALID_UNTIL("valid-until"), - DATE_UPDATED("date-updated"); - - private final String value; - - private SortBy(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static SortBy forValue(final String value) { - return Promoter.enumFromString(value, SortBy.values()); - } - } - - public enum SortDirection { - ASC("ASC"), - DESC("DESC"); - - private final String value; - - private SortDirection(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static SortDirection forValue(final String value) { - return Promoter.enumFromString(value, SortDirection.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/BundleCreator.java b/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/BundleCreator.java index 82283bf6f9..5ff0f4746f 100644 --- a/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/BundleCreator.java +++ b/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/BundleCreator.java @@ -14,9 +14,11 @@ package com.twilio.rest.numbers.v2.regulatorycompliance; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; -import com.twilio.converter.Promoter; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,7 +27,7 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -import java.net.URI; + import java.net.URI; public class BundleCreator extends Creator { @@ -44,83 +46,80 @@ public BundleCreator(final String friendlyName, final String email) { this.email = email; } + public BundleCreator setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + public BundleCreator setEmail(final String email) { this.email = email; return this; } + public BundleCreator setStatusCallback(final URI statusCallback) { this.statusCallback = statusCallback; return this; } - public BundleCreator setStatusCallback(final String statusCallback) { - return setStatusCallback(Promoter.uriFromString(statusCallback)); - } public BundleCreator setRegulationSid(final String regulationSid) { this.regulationSid = regulationSid; return this; } + public BundleCreator setIsoCountry(final String isoCountry) { this.isoCountry = isoCountry; return this; } + public BundleCreator setEndUserType(final Bundle.EndUserType endUserType) { this.endUserType = endUserType; return this; } + public BundleCreator setNumberType(final String numberType) { this.numberType = numberType; return this; } + public BundleCreator setIsTest(final Boolean isTest) { this.isTest = isTest; return this; } + @Override public Bundle create(final TwilioRestClient client) { + String path = "/v2/RegulatoryCompliance/Bundles"; - path = - path.replace( - "{" + "FriendlyName" + "}", - this.friendlyName.toString() - ); - path = path.replace("{" + "Email" + "}", this.email.toString()); Request request = new Request( - HttpMethod.POST, - Domains.NUMBERS.toString(), - path + HttpMethod.POST, + Domains.NUMBERS.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Bundle creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("Bundle creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -129,29 +128,46 @@ public Bundle create(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + if (email != null) { - request.addPostParam("Email", email); + Serializer.toString(request, "Email", email, ParameterType.URLENCODED); } + + if (statusCallback != null) { - request.addPostParam("StatusCallback", statusCallback.toString()); + Serializer.toString(request, "StatusCallback", statusCallback, ParameterType.URLENCODED); } + + if (regulationSid != null) { - request.addPostParam("RegulationSid", regulationSid); + Serializer.toString(request, "RegulationSid", regulationSid, ParameterType.URLENCODED); } + + if (isoCountry != null) { - request.addPostParam("IsoCountry", isoCountry); + Serializer.toString(request, "IsoCountry", isoCountry, ParameterType.URLENCODED); } + + if (endUserType != null) { - request.addPostParam("EndUserType", endUserType.toString()); + Serializer.toString(request, "EndUserType", endUserType, ParameterType.URLENCODED); } + + if (numberType != null) { - request.addPostParam("NumberType", numberType); + Serializer.toString(request, "NumberType", numberType, ParameterType.URLENCODED); } + + if (isTest != null) { - request.addPostParam("IsTest", isTest.toString()); + Serializer.toString(request, "IsTest", isTest, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/BundleDeleter.java b/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/BundleDeleter.java index 444d603ae0..42ca059261 100644 --- a/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/BundleDeleter.java +++ b/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/BundleDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.numbers.v2.regulatorycompliance; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,40 +26,38 @@ public class BundleDeleter extends Deleter { - private String pathSid; + private String pathsid; - public BundleDeleter(final String pathSid) { - this.pathSid = pathSid; + public BundleDeleter(final String pathsid) { + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/v2/RegulatoryCompliance/Bundles/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.NUMBERS.toString(), - path + HttpMethod.DELETE, + Domains.NUMBERS.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Bundle delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("Bundle delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/BundleFetcher.java b/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/BundleFetcher.java index 52a2e4689d..6d41832abc 100644 --- a/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/BundleFetcher.java +++ b/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/BundleFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.numbers.v2.regulatorycompliance; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,44 +26,41 @@ public class BundleFetcher extends Fetcher { - private String pathSid; + private String pathsid; - public BundleFetcher(final String pathSid) { - this.pathSid = pathSid; + public BundleFetcher(final String pathsid) { + this.pathsid = pathsid; } + @Override public Bundle fetch(final TwilioRestClient client) { + String path = "/v2/RegulatoryCompliance/Bundles/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.NUMBERS.toString(), - path + HttpMethod.GET, + Domains.NUMBERS.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Bundle fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Bundle fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Bundle.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/BundleReader.java b/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/BundleReader.java index 22e869d57e..6fcb433d1b 100644 --- a/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/BundleReader.java +++ b/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/BundleReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -26,8 +27,8 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.time.ZonedDateTime; -import java.time.format.DateTimeFormatter; public class BundleReader extends Reader { @@ -44,211 +45,204 @@ public class BundleReader extends Reader { private ZonedDateTime validUntilDateAfter; private Long pageSize; - public BundleReader() {} + public BundleReader() { + } + public BundleReader setStatus(final Bundle.Status status) { this.status = status; return this; } + public BundleReader setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + public BundleReader setRegulationSid(final String regulationSid) { this.regulationSid = regulationSid; return this; } + public BundleReader setIsoCountry(final String isoCountry) { this.isoCountry = isoCountry; return this; } + public BundleReader setNumberType(final String numberType) { this.numberType = numberType; return this; } + public BundleReader setHasValidUntilDate(final Boolean hasValidUntilDate) { this.hasValidUntilDate = hasValidUntilDate; return this; } + public BundleReader setSortBy(final Bundle.SortBy sortBy) { this.sortBy = sortBy; return this; } - public BundleReader setSortDirection( - final Bundle.SortDirection sortDirection - ) { + + public BundleReader setSortDirection(final Bundle.SortDirection sortDirection) { this.sortDirection = sortDirection; return this; } + public BundleReader setValidUntilDate(final ZonedDateTime validUntilDate) { this.validUntilDate = validUntilDate; return this; } - public BundleReader setValidUntilDateBefore( - final ZonedDateTime validUntilDateBefore - ) { + + public BundleReader setValidUntilDateBefore(final ZonedDateTime validUntilDateBefore) { this.validUntilDateBefore = validUntilDateBefore; return this; } - public BundleReader setValidUntilDateAfter( - final ZonedDateTime validUntilDateAfter - ) { + + public BundleReader setValidUntilDateAfter(final ZonedDateTime validUntilDateAfter) { this.validUntilDateAfter = validUntilDateAfter; return this; } + public BundleReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v2/RegulatoryCompliance/Bundles"; + Request request = new Request( - HttpMethod.GET, - Domains.NUMBERS.toString(), - path + HttpMethod.GET, + Domains.NUMBERS.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Bundle read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Bundle read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "results", - response.getContent(), - Bundle.class, - client.getObjectMapper() - ); + "results", + response.getContent(), + Bundle.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.NUMBERS.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.NUMBERS.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (status != null) { - request.addQueryParam("Status", status.toString()); + Serializer.toString(request, "Status", status, ParameterType.QUERY); } + + if (friendlyName != null) { - request.addQueryParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.QUERY); } + + if (regulationSid != null) { - request.addQueryParam("RegulationSid", regulationSid); + Serializer.toString(request, "RegulationSid", regulationSid, ParameterType.QUERY); } + + if (isoCountry != null) { - request.addQueryParam("IsoCountry", isoCountry); + Serializer.toString(request, "IsoCountry", isoCountry, ParameterType.QUERY); } + + if (numberType != null) { - request.addQueryParam("NumberType", numberType); + Serializer.toString(request, "NumberType", numberType, ParameterType.QUERY); } + + if (hasValidUntilDate != null) { - request.addQueryParam( - "HasValidUntilDate", - hasValidUntilDate.toString() - ); + Serializer.toString(request, "HasValidUntilDate", hasValidUntilDate, ParameterType.QUERY); } + + if (sortBy != null) { - request.addQueryParam("SortBy", sortBy.toString()); + Serializer.toString(request, "SortBy", sortBy, ParameterType.QUERY); } + + if (sortDirection != null) { - request.addQueryParam("SortDirection", sortDirection.toString()); + Serializer.toString(request, "SortDirection", sortDirection, ParameterType.QUERY); } + + if (validUntilDate != null) { - request.addQueryParam( - "ValidUntilDate", - validUntilDate.format( - DateTimeFormatter.ofPattern( - Request.QUERY_STRING_DATE_TIME_FORMAT - ) - ) - ); - } else if ( - validUntilDateAfter != null || validUntilDateBefore != null - ) { - request.addQueryDateTimeRange( - "ValidUntilDate", - validUntilDateAfter, - validUntilDateBefore - ); + Serializer.toString(request, "ValidUntilDate", validUntilDate, ParameterType.QUERY); } - if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + + + if (validUntilDateBefore != null) { + Serializer.toString(request, "ValidUntilDate<", validUntilDateBefore, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); + + if (validUntilDateAfter != null) { + Serializer.toString(request, "ValidUntilDate>", validUntilDateAfter, ParameterType.QUERY); } + + + if (pageSize != null) { + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); + } + + } } diff --git a/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/BundleUpdater.java b/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/BundleUpdater.java index e092972611..d4c94340c2 100644 --- a/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/BundleUpdater.java +++ b/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/BundleUpdater.java @@ -16,7 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; -import com.twilio.converter.Promoter; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,72 +26,72 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.net.URI; public class BundleUpdater extends Updater { - - private String pathSid; + private String pathsid; private Bundle.Status status; private URI statusCallback; private String friendlyName; private String email; - public BundleUpdater(final String pathSid) { - this.pathSid = pathSid; + public BundleUpdater(final String pathsid) { + this.pathsid = pathsid; } + public BundleUpdater setStatus(final Bundle.Status status) { this.status = status; return this; } + public BundleUpdater setStatusCallback(final URI statusCallback) { this.statusCallback = statusCallback; return this; } - public BundleUpdater setStatusCallback(final String statusCallback) { - return setStatusCallback(Promoter.uriFromString(statusCallback)); - } public BundleUpdater setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + public BundleUpdater setEmail(final String email) { this.email = email; return this; } + @Override public Bundle update(final TwilioRestClient client) { + String path = "/v2/RegulatoryCompliance/Bundles/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.NUMBERS.toString(), - path + HttpMethod.POST, + Domains.NUMBERS.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Bundle update failed: Unable to connect to server" - ); + throw new ApiConnectionException("Bundle update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -99,17 +100,26 @@ public Bundle update(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (status != null) { - request.addPostParam("Status", status.toString()); + Serializer.toString(request, "Status", status, ParameterType.URLENCODED); } + + if (statusCallback != null) { - request.addPostParam("StatusCallback", statusCallback.toString()); + Serializer.toString(request, "StatusCallback", statusCallback, ParameterType.URLENCODED); } + + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + if (email != null) { - request.addPostParam("Email", email); + Serializer.toString(request, "Email", email, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/EndUser.java b/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/EndUser.java index 6bfd90c4ab..575ad8f1b3 100644 --- a/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/EndUser.java +++ b/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/EndUser.java @@ -18,63 +18,92 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; -import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class EndUser extends Resource { - private static final long serialVersionUID = 94888387451102L; - public static EndUserCreator creator( - final String friendlyName, - final EndUser.Type type - ) { - return new EndUserCreator(friendlyName, type); + public static EndUserCreator creator(final String friendlyName, final EndUser.Type type) { + return new EndUserCreator( + friendlyName, type + ); } - public static EndUserDeleter deleter(final String pathSid) { - return new EndUserDeleter(pathSid); + + public static EndUserDeleter deleter(final String pathsid) { + return new EndUserDeleter( + pathsid + ); } - public static EndUserFetcher fetcher(final String pathSid) { - return new EndUserFetcher(pathSid); + + public static EndUserFetcher fetcher(final String pathsid) { + return new EndUserFetcher( + pathsid + ); } + public static EndUserReader reader() { - return new EndUserReader(); + return new EndUserReader( + + ); } - public static EndUserUpdater updater(final String pathSid) { - return new EndUserUpdater(pathSid); + + public static EndUserUpdater updater(final String pathsid) { + return new EndUserUpdater( + pathsid + ); } + + public enum Type { + INDIVIDUAL("individual"), + BUSINESS("business"); + + private final String value; + + private Type(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static Type forValue(final String value) { + return Promoter.enumFromString(value, Type.values()); + } + } + + /** * Converts a JSON String into a EndUser object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return EndUser object represented by the provided JSON */ - public static EndUser fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static EndUser fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, EndUser.class); @@ -89,14 +118,11 @@ public static EndUser fromJson( * Converts a JSON InputStream into a EndUser object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return EndUser object represented by the provided JSON */ - public static EndUser fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static EndUser fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, EndUser.class); @@ -107,68 +133,59 @@ public static EndUser fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String friendlyName; - private final EndUser.Type type; - private final Map attributes; + @Getter + private final Object attributes; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; + @Getter + private final String friendlyName; + @Getter + private final String sid; + @Getter + private final EndUser.Type type; + @Getter private final URI url; @JsonCreator private EndUser( - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("type") final EndUser.Type type, - @JsonProperty("attributes") final Map attributes, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("url") final URI url + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("attributes") final Object attributes, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("sid") final String sid, + @JsonProperty("type") final EndUser.Type type, + @JsonProperty("url") final URI url ) { - this.sid = sid; this.accountSid = accountSid; + this.attributes = attributes; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.friendlyName = friendlyName; + this.sid = sid; this.type = type; - this.attributes = attributes; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); this.url = url; } - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final EndUser.Type getType() { - return this.type; - } - - public final Map getAttributes() { - return this.attributes; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final URI getUrl() { - return this.url; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -180,50 +197,32 @@ public boolean equals(final Object o) { } EndUser other = (EndUser) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(type, other.type) && - Objects.equals(attributes, other.attributes) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(url, other.url) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(attributes, other.attributes) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(sid, other.sid) && + Objects.equals(type, other.type) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - sid, - accountSid, - friendlyName, - type, - attributes, - dateCreated, - dateUpdated, - url + accountSid, + attributes, + dateCreated, + dateUpdated, + friendlyName, + sid, + type, + url ); } - public enum Type { - INDIVIDUAL("individual"), - BUSINESS("business"); - - private final String value; - private Type(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static Type forValue(final String value) { - return Promoter.enumFromString(value, Type.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/EndUserCreator.java b/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/EndUserCreator.java index 9f301c0623..69af2f080f 100644 --- a/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/EndUserCreator.java +++ b/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/EndUserCreator.java @@ -14,10 +14,11 @@ package com.twilio.rest.numbers.v2.regulatorycompliance; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; -import com.twilio.converter.Converter; -import com.twilio.converter.Converter; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -38,54 +39,50 @@ public EndUserCreator(final String friendlyName, final EndUser.Type type) { this.type = type; } + public EndUserCreator setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + public EndUserCreator setType(final EndUser.Type type) { this.type = type; return this; } + public EndUserCreator setAttributes(final Object attributes) { this.attributes = attributes; return this; } + @Override public EndUser create(final TwilioRestClient client) { + String path = "/v2/RegulatoryCompliance/EndUsers"; - path = - path.replace( - "{" + "FriendlyName" + "}", - this.friendlyName.toString() - ); - path = path.replace("{" + "Type" + "}", this.type.toString()); Request request = new Request( - HttpMethod.POST, - Domains.NUMBERS.toString(), - path + HttpMethod.POST, + Domains.NUMBERS.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "EndUser creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("EndUser creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -94,17 +91,21 @@ public EndUser create(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + if (type != null) { - request.addPostParam("Type", type.toString()); + Serializer.toString(request, "Type", type, ParameterType.URLENCODED); } + + if (attributes != null) { - request.addPostParam( - "Attributes", - Converter.objectToJson(attributes) - ); + Serializer.toString(request, "Attributes", attributes, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/EndUserDeleter.java b/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/EndUserDeleter.java index 9a5da72eff..e7b5b6ae46 100644 --- a/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/EndUserDeleter.java +++ b/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/EndUserDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.numbers.v2.regulatorycompliance; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,40 +26,38 @@ public class EndUserDeleter extends Deleter { - private String pathSid; + private String pathsid; - public EndUserDeleter(final String pathSid) { - this.pathSid = pathSid; + public EndUserDeleter(final String pathsid) { + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/v2/RegulatoryCompliance/EndUsers/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.NUMBERS.toString(), - path + HttpMethod.DELETE, + Domains.NUMBERS.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "EndUser delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("EndUser delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/EndUserFetcher.java b/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/EndUserFetcher.java index 798ca035fe..1954c94c34 100644 --- a/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/EndUserFetcher.java +++ b/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/EndUserFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.numbers.v2.regulatorycompliance; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,44 +26,41 @@ public class EndUserFetcher extends Fetcher { - private String pathSid; + private String pathsid; - public EndUserFetcher(final String pathSid) { - this.pathSid = pathSid; + public EndUserFetcher(final String pathsid) { + this.pathsid = pathsid; } + @Override public EndUser fetch(final TwilioRestClient client) { + String path = "/v2/RegulatoryCompliance/EndUsers/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.NUMBERS.toString(), - path + HttpMethod.GET, + Domains.NUMBERS.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "EndUser fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("EndUser fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return EndUser.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/EndUserReader.java b/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/EndUserReader.java index 01843adefa..5ea4880372 100644 --- a/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/EndUserReader.java +++ b/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/EndUserReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -31,105 +32,83 @@ public class EndUserReader extends Reader { private Long pageSize; - public EndUserReader() {} + public EndUserReader() { + } + public EndUserReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v2/RegulatoryCompliance/EndUsers"; + Request request = new Request( - HttpMethod.GET, - Domains.NUMBERS.toString(), - path + HttpMethod.GET, + Domains.NUMBERS.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "EndUser read failed: Unable to connect to server" - ); + throw new ApiConnectionException("EndUser read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "results", - response.getContent(), - EndUser.class, - client.getObjectMapper() - ); + "results", + response.getContent(), + EndUser.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.NUMBERS.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.NUMBERS.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/EndUserType.java b/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/EndUserType.java index ecbfa77468..53c7c66dc2 100644 --- a/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/EndUserType.java +++ b/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/EndUserType.java @@ -18,46 +18,48 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.util.List; -import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class EndUserType extends Resource { - private static final long serialVersionUID = 67038001521206L; - public static EndUserTypeFetcher fetcher(final String pathSid) { - return new EndUserTypeFetcher(pathSid); + public static EndUserTypeFetcher fetcher(final String pathsid) { + return new EndUserTypeFetcher( + pathsid + ); } + public static EndUserTypeReader reader() { - return new EndUserTypeReader(); + return new EndUserTypeReader( + + ); } + /** * Converts a JSON String into a EndUserType object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return EndUserType object represented by the provided JSON */ - public static EndUserType fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static EndUserType fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, EndUserType.class); @@ -72,14 +74,11 @@ public static EndUserType fromJson( * Converts a JSON InputStream into a EndUserType object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return EndUserType object represented by the provided JSON */ - public static EndUserType fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static EndUserType fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, EndUserType.class); @@ -90,47 +89,45 @@ public static EndUserType fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter + private final List fields; + @Getter private final String friendlyName; + @Getter private final String machineName; - private final List> fields; + @Getter + private final String sid; + @Getter private final URI url; @JsonCreator private EndUserType( - @JsonProperty("sid") final String sid, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("machine_name") final String machineName, - @JsonProperty("fields") final List> fields, - @JsonProperty("url") final URI url + @JsonProperty("fields") final List fields, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("machine_name") final String machineName, + @JsonProperty("sid") final String sid, + @JsonProperty("url") final URI url ) { - this.sid = sid; + this.fields = fields; this.friendlyName = friendlyName; this.machineName = machineName; - this.fields = fields; + this.sid = sid; this.url = url; } - public final String getSid() { - return this.sid; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final String getMachineName() { - return this.machineName; - } - - public final List> getFields() { - return this.fields; - } - - public final URI getUrl() { - return this.url; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -142,18 +139,26 @@ public boolean equals(final Object o) { } EndUserType other = (EndUserType) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(machineName, other.machineName) && - Objects.equals(fields, other.fields) && - Objects.equals(url, other.url) + Objects.equals(fields, other.fields) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(machineName, other.machineName) && + Objects.equals(sid, other.sid) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { - return Objects.hash(sid, friendlyName, machineName, fields, url); + return Objects.hash( + fields, + friendlyName, + machineName, + sid, + url + ); } + + } + diff --git a/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/EndUserTypeFetcher.java b/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/EndUserTypeFetcher.java index 9acfe83bfd..2d461d029b 100644 --- a/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/EndUserTypeFetcher.java +++ b/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/EndUserTypeFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.numbers.v2.regulatorycompliance; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,47 +26,41 @@ public class EndUserTypeFetcher extends Fetcher { - private String pathSid; + private String pathsid; - public EndUserTypeFetcher(final String pathSid) { - this.pathSid = pathSid; + public EndUserTypeFetcher(final String pathsid) { + this.pathsid = pathsid; } + @Override public EndUserType fetch(final TwilioRestClient client) { + String path = "/v2/RegulatoryCompliance/EndUserTypes/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.NUMBERS.toString(), - path + HttpMethod.GET, + Domains.NUMBERS.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "EndUserType fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("EndUserType fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return EndUserType.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return EndUserType.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/EndUserTypeReader.java b/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/EndUserTypeReader.java index ba07319be4..064d41da3d 100644 --- a/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/EndUserTypeReader.java +++ b/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/EndUserTypeReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -31,105 +32,83 @@ public class EndUserTypeReader extends Reader { private Long pageSize; - public EndUserTypeReader() {} + public EndUserTypeReader() { + } + public EndUserTypeReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v2/RegulatoryCompliance/EndUserTypes"; + Request request = new Request( - HttpMethod.GET, - Domains.NUMBERS.toString(), - path + HttpMethod.GET, + Domains.NUMBERS.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "EndUserType read failed: Unable to connect to server" - ); + throw new ApiConnectionException("EndUserType read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "end_user_types", - response.getContent(), - EndUserType.class, - client.getObjectMapper() - ); + "end_user_types", + response.getContent(), + EndUserType.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.NUMBERS.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.NUMBERS.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/EndUserUpdater.java b/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/EndUserUpdater.java index 189bd34787..3c60be10b4 100644 --- a/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/EndUserUpdater.java +++ b/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/EndUserUpdater.java @@ -16,7 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; -import com.twilio.converter.Converter; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,53 +28,54 @@ import com.twilio.rest.Domains; public class EndUserUpdater extends Updater { - - private String pathSid; + private String pathsid; private String friendlyName; private Object attributes; - public EndUserUpdater(final String pathSid) { - this.pathSid = pathSid; + public EndUserUpdater(final String pathsid) { + this.pathsid = pathsid; } + public EndUserUpdater setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + public EndUserUpdater setAttributes(final Object attributes) { this.attributes = attributes; return this; } + @Override public EndUser update(final TwilioRestClient client) { + String path = "/v2/RegulatoryCompliance/EndUsers/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.NUMBERS.toString(), - path + HttpMethod.POST, + Domains.NUMBERS.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "EndUser update failed: Unable to connect to server" - ); + throw new ApiConnectionException("EndUser update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -82,14 +84,16 @@ public EndUser update(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + if (attributes != null) { - request.addPostParam( - "Attributes", - Converter.objectToJson(attributes) - ); + Serializer.toString(request, "Attributes", attributes, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/Regulation.java b/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/Regulation.java index 5c89d54944..2a6157a588 100644 --- a/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/Regulation.java +++ b/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/Regulation.java @@ -18,46 +18,69 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; -import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Regulation extends Resource { - private static final long serialVersionUID = 10727481359923L; - public static RegulationFetcher fetcher(final String pathSid) { - return new RegulationFetcher(pathSid); + public static RegulationFetcher fetcher(final String pathsid) { + return new RegulationFetcher( + pathsid + ); } + public static RegulationReader reader() { - return new RegulationReader(); + return new RegulationReader( + + ); + } + + + public enum EndUserType { + INDIVIDUAL("individual"), + BUSINESS("business"); + + private final String value; + + private EndUserType(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static EndUserType forValue(final String value) { + return Promoter.enumFromString(value, EndUserType.values()); + } } + /** * Converts a JSON String into a Regulation object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Regulation object represented by the provided JSON */ - public static Regulation fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Regulation fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Regulation.class); @@ -72,14 +95,11 @@ public static Regulation fromJson( * Converts a JSON InputStream into a Regulation object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Regulation object represented by the provided JSON */ - public static Regulation fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Regulation fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Regulation.class); @@ -90,61 +110,53 @@ public static Regulation fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter + private final Regulation.EndUserType endUserType; + @Getter private final String friendlyName; + @Getter private final String isoCountry; + @Getter private final String numberType; - private final Regulation.EndUserType endUserType; - private final Map requirements; + @Getter + private final Object requirements; + @Getter + private final String sid; + @Getter private final URI url; @JsonCreator private Regulation( - @JsonProperty("sid") final String sid, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("iso_country") final String isoCountry, - @JsonProperty("number_type") final String numberType, - @JsonProperty("end_user_type") final Regulation.EndUserType endUserType, - @JsonProperty("requirements") final Map requirements, - @JsonProperty("url") final URI url + @JsonProperty("end_user_type") final Regulation.EndUserType endUserType, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("iso_country") final String isoCountry, + @JsonProperty("number_type") final String numberType, + @JsonProperty("requirements") final Object requirements, + @JsonProperty("sid") final String sid, + @JsonProperty("url") final URI url ) { - this.sid = sid; + this.endUserType = endUserType; this.friendlyName = friendlyName; this.isoCountry = isoCountry; this.numberType = numberType; - this.endUserType = endUserType; this.requirements = requirements; + this.sid = sid; this.url = url; } - public final String getSid() { - return this.sid; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final String getIsoCountry() { - return this.isoCountry; - } - - public final String getNumberType() { - return this.numberType; - } - - public final Regulation.EndUserType getEndUserType() { - return this.endUserType; - } - - public final Map getRequirements() { - return this.requirements; - } - - public final URI getUrl() { - return this.url; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -156,48 +168,30 @@ public boolean equals(final Object o) { } Regulation other = (Regulation) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(isoCountry, other.isoCountry) && - Objects.equals(numberType, other.numberType) && - Objects.equals(endUserType, other.endUserType) && - Objects.equals(requirements, other.requirements) && - Objects.equals(url, other.url) + Objects.equals(endUserType, other.endUserType) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(isoCountry, other.isoCountry) && + Objects.equals(numberType, other.numberType) && + Objects.equals(requirements, other.requirements) && + Objects.equals(sid, other.sid) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - sid, - friendlyName, - isoCountry, - numberType, - endUserType, - requirements, - url + endUserType, + friendlyName, + isoCountry, + numberType, + requirements, + sid, + url ); } - public enum EndUserType { - INDIVIDUAL("individual"), - BUSINESS("business"); - - private final String value; - - private EndUserType(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - @JsonCreator - public static EndUserType forValue(final String value) { - return Promoter.enumFromString(value, EndUserType.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/RegulationFetcher.java b/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/RegulationFetcher.java index 18870f1066..319c7e9c63 100644 --- a/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/RegulationFetcher.java +++ b/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/RegulationFetcher.java @@ -15,7 +15,8 @@ package com.twilio.rest.numbers.v2.regulatorycompliance; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,65 +28,59 @@ public class RegulationFetcher extends Fetcher { - private String pathSid; + private String pathsid; private Boolean includeConstraints; - public RegulationFetcher(final String pathSid) { - this.pathSid = pathSid; + public RegulationFetcher(final String pathsid) { + this.pathsid = pathsid; } - public RegulationFetcher setIncludeConstraints( - final Boolean includeConstraints - ) { + + public RegulationFetcher setIncludeConstraints(final Boolean includeConstraints) { this.includeConstraints = includeConstraints; return this; } + @Override public Regulation fetch(final TwilioRestClient client) { + String path = "/v2/RegulatoryCompliance/Regulations/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.NUMBERS.toString(), - path + HttpMethod.GET, + Domains.NUMBERS.toString(), + path ); addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Regulation fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Regulation fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return Regulation.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Regulation.fromJson(response.getStream(), client.getObjectMapper()); } private void addQueryParams(final Request request) { + + if (includeConstraints != null) { - request.addQueryParam( - "IncludeConstraints", - includeConstraints.toString() - ); + Serializer.toString(request, "IncludeConstraints", includeConstraints, ParameterType.QUERY); } + + } } diff --git a/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/RegulationReader.java b/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/RegulationReader.java index ab025a5130..cba7d7d88d 100644 --- a/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/RegulationReader.java +++ b/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/RegulationReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -35,144 +36,127 @@ public class RegulationReader extends Reader { private Boolean includeConstraints; private Long pageSize; - public RegulationReader() {} + public RegulationReader() { + } + - public RegulationReader setEndUserType( - final Regulation.EndUserType endUserType - ) { + public RegulationReader setEndUserType(final Regulation.EndUserType endUserType) { this.endUserType = endUserType; return this; } + public RegulationReader setIsoCountry(final String isoCountry) { this.isoCountry = isoCountry; return this; } + public RegulationReader setNumberType(final String numberType) { this.numberType = numberType; return this; } - public RegulationReader setIncludeConstraints( - final Boolean includeConstraints - ) { + + public RegulationReader setIncludeConstraints(final Boolean includeConstraints) { this.includeConstraints = includeConstraints; return this; } + public RegulationReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v2/RegulatoryCompliance/Regulations"; + Request request = new Request( - HttpMethod.GET, - Domains.NUMBERS.toString(), - path + HttpMethod.GET, + Domains.NUMBERS.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Regulation read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Regulation read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "results", - response.getContent(), - Regulation.class, - client.getObjectMapper() - ); + "results", + response.getContent(), + Regulation.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.NUMBERS.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.NUMBERS.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (endUserType != null) { - request.addQueryParam("EndUserType", endUserType.toString()); + Serializer.toString(request, "EndUserType", endUserType, ParameterType.QUERY); } + + if (isoCountry != null) { - request.addQueryParam("IsoCountry", isoCountry); + Serializer.toString(request, "IsoCountry", isoCountry, ParameterType.QUERY); } + + if (numberType != null) { - request.addQueryParam("NumberType", numberType); + Serializer.toString(request, "NumberType", numberType, ParameterType.QUERY); } + + if (includeConstraints != null) { - request.addQueryParam( - "IncludeConstraints", - includeConstraints.toString() - ); + Serializer.toString(request, "IncludeConstraints", includeConstraints, ParameterType.QUERY); } + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/SupportingDocument.java b/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/SupportingDocument.java index 50135af80f..cdab487646 100644 --- a/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/SupportingDocument.java +++ b/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/SupportingDocument.java @@ -18,64 +18,97 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.List; -import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class SupportingDocument extends Resource { - private static final long serialVersionUID = 89965125257195L; - public static SupportingDocumentCreator creator( - final String friendlyName, - final String type - ) { - return new SupportingDocumentCreator(friendlyName, type); + public static SupportingDocumentCreator creator(final String friendlyName, final String type) { + return new SupportingDocumentCreator( + friendlyName, type + ); } - public static SupportingDocumentDeleter deleter(final String pathSid) { - return new SupportingDocumentDeleter(pathSid); + + public static SupportingDocumentDeleter deleter(final String pathsid) { + return new SupportingDocumentDeleter( + pathsid + ); } - public static SupportingDocumentFetcher fetcher(final String pathSid) { - return new SupportingDocumentFetcher(pathSid); + + public static SupportingDocumentFetcher fetcher(final String pathsid) { + return new SupportingDocumentFetcher( + pathsid + ); } + public static SupportingDocumentReader reader() { - return new SupportingDocumentReader(); + return new SupportingDocumentReader( + + ); } - public static SupportingDocumentUpdater updater(final String pathSid) { - return new SupportingDocumentUpdater(pathSid); + + public static SupportingDocumentUpdater updater(final String pathsid) { + return new SupportingDocumentUpdater( + pathsid + ); + } + + + public enum Status { + DRAFT("draft"), + PENDING_REVIEW("pending-review"), + REJECTED("rejected"), + APPROVED("approved"), + EXPIRED("expired"), + PROVISIONALLY_APPROVED("provisionally-approved"); + + private final String value; + + private Status(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static Status forValue(final String value) { + return Promoter.enumFromString(value, Status.values()); + } } + /** * Converts a JSON String into a SupportingDocument object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return SupportingDocument object represented by the provided JSON */ - public static SupportingDocument fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static SupportingDocument fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, SupportingDocument.class); @@ -90,14 +123,11 @@ public static SupportingDocument fromJson( * Converts a JSON InputStream into a SupportingDocument object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return SupportingDocument object represented by the provided JSON */ - public static SupportingDocument fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static SupportingDocument fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, SupportingDocument.class); @@ -108,96 +138,75 @@ public static SupportingDocument fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; + @Getter + private final Object attributes; + @Getter + private final ZonedDateTime dateCreated; + @Getter + private final ZonedDateTime dateUpdated; + @Getter + private final List errors; + @Getter + private final String failureReason; + @Getter private final String friendlyName; + @Getter private final String mimeType; + @Getter + private final String sid; + @Getter private final SupportingDocument.Status status; - private final String failureReason; - private final List> errors; + @Getter private final String type; - private final Map attributes; - private final ZonedDateTime dateCreated; - private final ZonedDateTime dateUpdated; + @Getter private final URI url; @JsonCreator private SupportingDocument( - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("mime_type") final String mimeType, - @JsonProperty("status") final SupportingDocument.Status status, - @JsonProperty("failure_reason") final String failureReason, - @JsonProperty("errors") final List> errors, - @JsonProperty("type") final String type, - @JsonProperty("attributes") final Map attributes, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("url") final URI url + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("attributes") final Object attributes, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("errors") final List errors, + @JsonProperty("failure_reason") final String failureReason, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("mime_type") final String mimeType, + @JsonProperty("sid") final String sid, + @JsonProperty("status") final SupportingDocument.Status status, + @JsonProperty("type") final String type, + @JsonProperty("url") final URI url ) { - this.sid = sid; this.accountSid = accountSid; + this.attributes = attributes; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; + this.errors = errors; + this.failureReason = failureReason; this.friendlyName = friendlyName; this.mimeType = mimeType; + this.sid = sid; this.status = status; - this.failureReason = failureReason; - this.errors = errors; this.type = type; - this.attributes = attributes; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); this.url = url; } - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final String getMimeType() { - return this.mimeType; - } - - public final SupportingDocument.Status getStatus() { - return this.status; - } - - public final String getFailureReason() { - return this.failureReason; - } - - public final List> getErrors() { - return this.errors; - } - - public final String getType() { - return this.type; - } - - public final Map getAttributes() { - return this.attributes; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final URI getUrl() { - return this.url; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -209,62 +218,40 @@ public boolean equals(final Object o) { } SupportingDocument other = (SupportingDocument) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(mimeType, other.mimeType) && - Objects.equals(status, other.status) && - Objects.equals(failureReason, other.failureReason) && - Objects.equals(errors, other.errors) && - Objects.equals(type, other.type) && - Objects.equals(attributes, other.attributes) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(url, other.url) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(attributes, other.attributes) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(errors, other.errors) && + Objects.equals(failureReason, other.failureReason) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(mimeType, other.mimeType) && + Objects.equals(sid, other.sid) && + Objects.equals(status, other.status) && + Objects.equals(type, other.type) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - sid, - accountSid, - friendlyName, - mimeType, - status, - failureReason, - errors, - type, - attributes, - dateCreated, - dateUpdated, - url + accountSid, + attributes, + dateCreated, + dateUpdated, + errors, + failureReason, + friendlyName, + mimeType, + sid, + status, + type, + url ); } - public enum Status { - DRAFT("draft"), - PENDING_REVIEW("pending-review"), - REJECTED("rejected"), - APPROVED("approved"), - EXPIRED("expired"), - PROVISIONALLY_APPROVED("provisionally-approved"); - - private final String value; - private Status(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static Status forValue(final String value) { - return Promoter.enumFromString(value, Status.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/SupportingDocumentCreator.java b/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/SupportingDocumentCreator.java index 9c53a94eb5..2a479c5177 100644 --- a/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/SupportingDocumentCreator.java +++ b/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/SupportingDocumentCreator.java @@ -14,10 +14,11 @@ package com.twilio.rest.numbers.v2.regulatorycompliance; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; -import com.twilio.converter.Converter; -import com.twilio.converter.Converter; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -33,86 +34,78 @@ public class SupportingDocumentCreator extends Creator { private String type; private Object attributes; - public SupportingDocumentCreator( - final String friendlyName, - final String type - ) { + public SupportingDocumentCreator(final String friendlyName, final String type) { this.friendlyName = friendlyName; this.type = type; } - public SupportingDocumentCreator setFriendlyName( - final String friendlyName - ) { + + public SupportingDocumentCreator setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + public SupportingDocumentCreator setType(final String type) { this.type = type; return this; } + public SupportingDocumentCreator setAttributes(final Object attributes) { this.attributes = attributes; return this; } + @Override public SupportingDocument create(final TwilioRestClient client) { + String path = "/v2/RegulatoryCompliance/SupportingDocuments"; - path = - path.replace( - "{" + "FriendlyName" + "}", - this.friendlyName.toString() - ); - path = path.replace("{" + "Type" + "}", this.type.toString()); Request request = new Request( - HttpMethod.POST, - Domains.NUMBERS.toString(), - path + HttpMethod.POST, + Domains.NUMBERS.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "SupportingDocument creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("SupportingDocument creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return SupportingDocument.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return SupportingDocument.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + if (type != null) { - request.addPostParam("Type", type); + Serializer.toString(request, "Type", type, ParameterType.URLENCODED); } + + if (attributes != null) { - request.addPostParam( - "Attributes", - Converter.objectToJson(attributes) - ); + Serializer.toString(request, "Attributes", attributes, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/SupportingDocumentDeleter.java b/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/SupportingDocumentDeleter.java index 85328851f4..1ced8673a3 100644 --- a/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/SupportingDocumentDeleter.java +++ b/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/SupportingDocumentDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.numbers.v2.regulatorycompliance; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,40 +26,38 @@ public class SupportingDocumentDeleter extends Deleter { - private String pathSid; + private String pathsid; - public SupportingDocumentDeleter(final String pathSid) { - this.pathSid = pathSid; + public SupportingDocumentDeleter(final String pathsid) { + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/v2/RegulatoryCompliance/SupportingDocuments/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.NUMBERS.toString(), - path + HttpMethod.DELETE, + Domains.NUMBERS.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "SupportingDocument delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("SupportingDocument delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/SupportingDocumentFetcher.java b/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/SupportingDocumentFetcher.java index 9095d0f400..891a360c60 100644 --- a/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/SupportingDocumentFetcher.java +++ b/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/SupportingDocumentFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.numbers.v2.regulatorycompliance; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,47 +26,41 @@ public class SupportingDocumentFetcher extends Fetcher { - private String pathSid; + private String pathsid; - public SupportingDocumentFetcher(final String pathSid) { - this.pathSid = pathSid; + public SupportingDocumentFetcher(final String pathsid) { + this.pathsid = pathsid; } + @Override public SupportingDocument fetch(final TwilioRestClient client) { + String path = "/v2/RegulatoryCompliance/SupportingDocuments/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.NUMBERS.toString(), - path + HttpMethod.GET, + Domains.NUMBERS.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "SupportingDocument fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("SupportingDocument fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return SupportingDocument.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return SupportingDocument.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/SupportingDocumentReader.java b/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/SupportingDocumentReader.java index c8842c73e9..c2c1c55705 100644 --- a/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/SupportingDocumentReader.java +++ b/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/SupportingDocumentReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -31,105 +32,83 @@ public class SupportingDocumentReader extends Reader { private Long pageSize; - public SupportingDocumentReader() {} + public SupportingDocumentReader() { + } + public SupportingDocumentReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v2/RegulatoryCompliance/SupportingDocuments"; + Request request = new Request( - HttpMethod.GET, - Domains.NUMBERS.toString(), - path + HttpMethod.GET, + Domains.NUMBERS.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "SupportingDocument read failed: Unable to connect to server" - ); + throw new ApiConnectionException("SupportingDocument read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "results", - response.getContent(), - SupportingDocument.class, - client.getObjectMapper() - ); + "results", + response.getContent(), + SupportingDocument.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.NUMBERS.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.NUMBERS.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/SupportingDocumentType.java b/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/SupportingDocumentType.java index 6e49f965c4..41ed7d69c6 100644 --- a/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/SupportingDocumentType.java +++ b/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/SupportingDocumentType.java @@ -18,46 +18,48 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.util.List; -import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class SupportingDocumentType extends Resource { - private static final long serialVersionUID = 67038001521206L; - public static SupportingDocumentTypeFetcher fetcher(final String pathSid) { - return new SupportingDocumentTypeFetcher(pathSid); + public static SupportingDocumentTypeFetcher fetcher(final String pathsid) { + return new SupportingDocumentTypeFetcher( + pathsid + ); } + public static SupportingDocumentTypeReader reader() { - return new SupportingDocumentTypeReader(); + return new SupportingDocumentTypeReader( + + ); } + /** * Converts a JSON String into a SupportingDocumentType object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return SupportingDocumentType object represented by the provided JSON */ - public static SupportingDocumentType fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static SupportingDocumentType fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, SupportingDocumentType.class); @@ -72,14 +74,11 @@ public static SupportingDocumentType fromJson( * Converts a JSON InputStream into a SupportingDocumentType object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return SupportingDocumentType object represented by the provided JSON */ - public static SupportingDocumentType fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static SupportingDocumentType fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, SupportingDocumentType.class); @@ -90,47 +89,45 @@ public static SupportingDocumentType fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter + private final List fields; + @Getter private final String friendlyName; + @Getter private final String machineName; - private final List> fields; + @Getter + private final String sid; + @Getter private final URI url; @JsonCreator private SupportingDocumentType( - @JsonProperty("sid") final String sid, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("machine_name") final String machineName, - @JsonProperty("fields") final List> fields, - @JsonProperty("url") final URI url + @JsonProperty("fields") final List fields, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("machine_name") final String machineName, + @JsonProperty("sid") final String sid, + @JsonProperty("url") final URI url ) { - this.sid = sid; + this.fields = fields; this.friendlyName = friendlyName; this.machineName = machineName; - this.fields = fields; + this.sid = sid; this.url = url; } - public final String getSid() { - return this.sid; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final String getMachineName() { - return this.machineName; - } - - public final List> getFields() { - return this.fields; - } - - public final URI getUrl() { - return this.url; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -142,18 +139,26 @@ public boolean equals(final Object o) { } SupportingDocumentType other = (SupportingDocumentType) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(machineName, other.machineName) && - Objects.equals(fields, other.fields) && - Objects.equals(url, other.url) + Objects.equals(fields, other.fields) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(machineName, other.machineName) && + Objects.equals(sid, other.sid) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { - return Objects.hash(sid, friendlyName, machineName, fields, url); + return Objects.hash( + fields, + friendlyName, + machineName, + sid, + url + ); } + + } + diff --git a/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/SupportingDocumentTypeFetcher.java b/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/SupportingDocumentTypeFetcher.java index 3f4d6dd6b9..a19c05e553 100644 --- a/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/SupportingDocumentTypeFetcher.java +++ b/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/SupportingDocumentTypeFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.numbers.v2.regulatorycompliance; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,50 +24,43 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class SupportingDocumentTypeFetcher - extends Fetcher { +public class SupportingDocumentTypeFetcher extends Fetcher { - private String pathSid; + private String pathsid; - public SupportingDocumentTypeFetcher(final String pathSid) { - this.pathSid = pathSid; + public SupportingDocumentTypeFetcher(final String pathsid) { + this.pathsid = pathsid; } + @Override public SupportingDocumentType fetch(final TwilioRestClient client) { + String path = "/v2/RegulatoryCompliance/SupportingDocumentTypes/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.NUMBERS.toString(), - path + HttpMethod.GET, + Domains.NUMBERS.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "SupportingDocumentType fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("SupportingDocumentType fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return SupportingDocumentType.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return SupportingDocumentType.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/SupportingDocumentTypeReader.java b/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/SupportingDocumentTypeReader.java index 70ad4837a4..81a967614f 100644 --- a/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/SupportingDocumentTypeReader.java +++ b/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/SupportingDocumentTypeReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,114 +28,87 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class SupportingDocumentTypeReader - extends Reader { +public class SupportingDocumentTypeReader extends Reader { private Long pageSize; - public SupportingDocumentTypeReader() {} + public SupportingDocumentTypeReader() { + } + public SupportingDocumentTypeReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override - public ResourceSet read( - final TwilioRestClient client - ) { + public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } - public Page firstPage( - final TwilioRestClient client - ) { + public Page firstPage(final TwilioRestClient client) { + String path = "/v2/RegulatoryCompliance/SupportingDocumentTypes"; + Request request = new Request( - HttpMethod.GET, - Domains.NUMBERS.toString(), - path + HttpMethod.GET, + Domains.NUMBERS.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "SupportingDocumentType read failed: Unable to connect to server" - ); + throw new ApiConnectionException("SupportingDocumentType read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "supporting_document_types", - response.getContent(), - SupportingDocumentType.class, - client.getObjectMapper() - ); + "supporting_document_types", + response.getContent(), + SupportingDocumentType.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.NUMBERS.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.NUMBERS.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/SupportingDocumentUpdater.java b/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/SupportingDocumentUpdater.java index 4a243f5fc5..f55a47e6df 100644 --- a/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/SupportingDocumentUpdater.java +++ b/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/SupportingDocumentUpdater.java @@ -16,7 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; -import com.twilio.converter.Converter; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,74 +28,72 @@ import com.twilio.rest.Domains; public class SupportingDocumentUpdater extends Updater { - - private String pathSid; + private String pathsid; private String friendlyName; private Object attributes; - public SupportingDocumentUpdater(final String pathSid) { - this.pathSid = pathSid; + public SupportingDocumentUpdater(final String pathsid) { + this.pathsid = pathsid; } - public SupportingDocumentUpdater setFriendlyName( - final String friendlyName - ) { + + public SupportingDocumentUpdater setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + public SupportingDocumentUpdater setAttributes(final Object attributes) { this.attributes = attributes; return this; } + @Override public SupportingDocument update(final TwilioRestClient client) { + String path = "/v2/RegulatoryCompliance/SupportingDocuments/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.NUMBERS.toString(), - path + HttpMethod.POST, + Domains.NUMBERS.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "SupportingDocument update failed: Unable to connect to server" - ); + throw new ApiConnectionException("SupportingDocument update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return SupportingDocument.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return SupportingDocument.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + if (attributes != null) { - request.addPostParam( - "Attributes", - Converter.objectToJson(attributes) - ); + Serializer.toString(request, "Attributes", attributes, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/bundle/BundleCopy.java b/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/bundle/BundleCopy.java index 04ac0cb803..4a4e985204 100644 --- a/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/bundle/BundleCopy.java +++ b/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/bundle/BundleCopy.java @@ -18,46 +18,75 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class BundleCopy extends Resource { - private static final long serialVersionUID = 169816383944206L; - public static BundleCopyCreator creator(final String pathBundleSid) { - return new BundleCopyCreator(pathBundleSid); + public static BundleCopyCreator creator(final String pathbundleSid) { + return new BundleCopyCreator( + pathbundleSid + ); } - public static BundleCopyReader reader(final String pathBundleSid) { - return new BundleCopyReader(pathBundleSid); + + public static BundleCopyReader reader(final String pathbundleSid) { + return new BundleCopyReader( + pathbundleSid + ); } + + public enum Status { + DRAFT("draft"), + PENDING_REVIEW("pending-review"), + IN_REVIEW("in-review"), + TWILIO_REJECTED("twilio-rejected"), + TWILIO_APPROVED("twilio-approved"), + PROVISIONALLY_APPROVED("provisionally-approved"); + + private final String value; + + private Status(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static Status forValue(final String value) { + return Promoter.enumFromString(value, Status.values()); + } + } + + /** * Converts a JSON String into a BundleCopy object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return BundleCopy object represented by the provided JSON */ - public static BundleCopy fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static BundleCopy fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, BundleCopy.class); @@ -72,14 +101,11 @@ public static BundleCopy fromJson( * Converts a JSON InputStream into a BundleCopy object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return BundleCopy object represented by the provided JSON */ - public static BundleCopy fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static BundleCopy fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, BundleCopy.class); @@ -90,80 +116,66 @@ public static BundleCopy fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String regulationSid; + @Getter + private final ZonedDateTime dateCreated; + @Getter + private final ZonedDateTime dateUpdated; + @Getter + private final String email; + @Getter private final String friendlyName; + @Getter + private final String regulationSid; + @Getter + private final String sid; + @Getter private final BundleCopy.Status status; - private final ZonedDateTime validUntil; - private final String email; + @Getter private final URI statusCallback; - private final ZonedDateTime dateCreated; - private final ZonedDateTime dateUpdated; + @Getter + private final ZonedDateTime validUntil; @JsonCreator private BundleCopy( - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("regulation_sid") final String regulationSid, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("status") final BundleCopy.Status status, - @JsonProperty("valid_until") final String validUntil, - @JsonProperty("email") final String email, - @JsonProperty("status_callback") final URI statusCallback, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("email") final String email, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("regulation_sid") final String regulationSid, + @JsonProperty("sid") final String sid, + @JsonProperty("status") final BundleCopy.Status status, + @JsonProperty("status_callback") final URI statusCallback, + @JsonProperty("valid_until") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime validUntil ) { - this.sid = sid; this.accountSid = accountSid; - this.regulationSid = regulationSid; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; + this.email = email; this.friendlyName = friendlyName; + this.regulationSid = regulationSid; + this.sid = sid; this.status = status; - this.validUntil = DateConverter.iso8601DateTimeFromString(validUntil); - this.email = email; this.statusCallback = statusCallback; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); - } - - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getRegulationSid() { - return this.regulationSid; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final BundleCopy.Status getStatus() { - return this.status; - } - - public final ZonedDateTime getValidUntil() { - return this.validUntil; - } - - public final String getEmail() { - return this.email; - } - - public final URI getStatusCallback() { - return this.statusCallback; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; + this.validUntil = validUntil; } @Override @@ -177,58 +189,36 @@ public boolean equals(final Object o) { } BundleCopy other = (BundleCopy) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(regulationSid, other.regulationSid) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(status, other.status) && - Objects.equals(validUntil, other.validUntil) && - Objects.equals(email, other.email) && - Objects.equals(statusCallback, other.statusCallback) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(email, other.email) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(regulationSid, other.regulationSid) && + Objects.equals(sid, other.sid) && + Objects.equals(status, other.status) && + Objects.equals(statusCallback, other.statusCallback) && + Objects.equals(validUntil, other.validUntil) ); } @Override public int hashCode() { return Objects.hash( - sid, - accountSid, - regulationSid, - friendlyName, - status, - validUntil, - email, - statusCallback, - dateCreated, - dateUpdated + accountSid, + dateCreated, + dateUpdated, + email, + friendlyName, + regulationSid, + sid, + status, + statusCallback, + validUntil ); } - public enum Status { - DRAFT("draft"), - PENDING_REVIEW("pending-review"), - IN_REVIEW("in-review"), - TWILIO_REJECTED("twilio-rejected"), - TWILIO_APPROVED("twilio-approved"), - PROVISIONALLY_APPROVED("provisionally-approved"); - - private final String value; - - private Status(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - @JsonCreator - public static Status forValue(final String value) { - return Promoter.enumFromString(value, Status.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/bundle/BundleCopyCreator.java b/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/bundle/BundleCopyCreator.java index b1dbe5309d..57a0b19db6 100644 --- a/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/bundle/BundleCopyCreator.java +++ b/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/bundle/BundleCopyCreator.java @@ -14,8 +14,11 @@ package com.twilio.rest.numbers.v2.regulatorycompliance.bundle; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,63 +30,60 @@ public class BundleCopyCreator extends Creator { - private String pathBundleSid; + private String pathbundleSid; private String friendlyName; - public BundleCopyCreator(final String pathBundleSid) { - this.pathBundleSid = pathBundleSid; + public BundleCopyCreator(final String pathbundleSid) { + this.pathbundleSid = pathbundleSid; } + public BundleCopyCreator setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + @Override public BundleCopy create(final TwilioRestClient client) { + String path = "/v2/RegulatoryCompliance/Bundles/{BundleSid}/Copies"; - path = - path.replace( - "{" + "BundleSid" + "}", - this.pathBundleSid.toString() - ); + path = path.replace("{" + "BundleSid" + "}", this.pathbundleSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.NUMBERS.toString(), - path + HttpMethod.POST, + Domains.NUMBERS.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "BundleCopy creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("BundleCopy creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return BundleCopy.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return BundleCopy.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/bundle/BundleCopyReader.java b/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/bundle/BundleCopyReader.java index f37625f23b..2fa97957c5 100644 --- a/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/bundle/BundleCopyReader.java +++ b/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/bundle/BundleCopyReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,115 +30,88 @@ public class BundleCopyReader extends Reader { - private String pathBundleSid; + private String pathbundleSid; private Long pageSize; - public BundleCopyReader(final String pathBundleSid) { - this.pathBundleSid = pathBundleSid; + public BundleCopyReader(final String pathbundleSid) { + this.pathbundleSid = pathbundleSid; } + public BundleCopyReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v2/RegulatoryCompliance/Bundles/{BundleSid}/Copies"; - path = - path.replace( - "{" + "BundleSid" + "}", - this.pathBundleSid.toString() - ); + + path = path.replace("{" + "BundleSid" + "}", this.pathbundleSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.NUMBERS.toString(), - path + HttpMethod.GET, + Domains.NUMBERS.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "BundleCopy read failed: Unable to connect to server" - ); + throw new ApiConnectionException("BundleCopy read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "results", - response.getContent(), - BundleCopy.class, - client.getObjectMapper() - ); + "results", + response.getContent(), + BundleCopy.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.NUMBERS.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.NUMBERS.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/bundle/Evaluation.java b/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/bundle/Evaluation.java index 669f216872..1a9fa3d144 100644 --- a/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/bundle/Evaluation.java +++ b/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/bundle/Evaluation.java @@ -18,56 +18,79 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.List; -import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Evaluation extends Resource { - private static final long serialVersionUID = 28761307513576L; - public static EvaluationCreator creator(final String pathBundleSid) { - return new EvaluationCreator(pathBundleSid); + public static EvaluationCreator creator(final String pathbundleSid) { + return new EvaluationCreator( + pathbundleSid + ); } - public static EvaluationFetcher fetcher( - final String pathBundleSid, - final String pathSid - ) { - return new EvaluationFetcher(pathBundleSid, pathSid); + + public static EvaluationFetcher fetcher(final String pathbundleSid, final String pathsid) { + return new EvaluationFetcher( + pathbundleSid, pathsid + ); + } + + + public static EvaluationReader reader(final String pathbundleSid) { + return new EvaluationReader( + pathbundleSid + ); } - public static EvaluationReader reader(final String pathBundleSid) { - return new EvaluationReader(pathBundleSid); + + public enum Status { + COMPLIANT("compliant"), + NONCOMPLIANT("noncompliant"); + + private final String value; + + private Status(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static Status forValue(final String value) { + return Promoter.enumFromString(value, Status.values()); + } } + /** * Converts a JSON String into a Evaluation object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Evaluation object represented by the provided JSON */ - public static Evaluation fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Evaluation fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Evaluation.class); @@ -82,14 +105,11 @@ public static Evaluation fromJson( * Converts a JSON InputStream into a Evaluation object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Evaluation object represented by the provided JSON */ - public static Evaluation fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Evaluation fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Evaluation.class); @@ -100,68 +120,58 @@ public static Evaluation fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String regulationSid; + @Getter private final String bundleSid; - private final Evaluation.Status status; - private final List> results; + @Getter private final ZonedDateTime dateCreated; + @Getter + private final String regulationSid; + @Getter + private final List results; + @Getter + private final String sid; + @Getter + private final Evaluation.Status status; + @Getter private final URI url; @JsonCreator private Evaluation( - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("regulation_sid") final String regulationSid, - @JsonProperty("bundle_sid") final String bundleSid, - @JsonProperty("status") final Evaluation.Status status, - @JsonProperty("results") final List> results, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("url") final URI url + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("bundle_sid") final String bundleSid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("regulation_sid") final String regulationSid, + @JsonProperty("results") final List results, + @JsonProperty("sid") final String sid, + @JsonProperty("status") final Evaluation.Status status, + @JsonProperty("url") final URI url ) { - this.sid = sid; this.accountSid = accountSid; - this.regulationSid = regulationSid; this.bundleSid = bundleSid; - this.status = status; + this.dateCreated = dateCreated; + this.regulationSid = regulationSid; this.results = results; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); + this.sid = sid; + this.status = status; this.url = url; } - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getRegulationSid() { - return this.regulationSid; - } - - public final String getBundleSid() { - return this.bundleSid; - } - - public final Evaluation.Status getStatus() { - return this.status; - } - - public final List> getResults() { - return this.results; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final URI getUrl() { - return this.url; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -173,50 +183,32 @@ public boolean equals(final Object o) { } Evaluation other = (Evaluation) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(regulationSid, other.regulationSid) && - Objects.equals(bundleSid, other.bundleSid) && - Objects.equals(status, other.status) && - Objects.equals(results, other.results) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(url, other.url) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(bundleSid, other.bundleSid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(regulationSid, other.regulationSid) && + Objects.equals(results, other.results) && + Objects.equals(sid, other.sid) && + Objects.equals(status, other.status) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - sid, - accountSid, - regulationSid, - bundleSid, - status, - results, - dateCreated, - url + accountSid, + bundleSid, + dateCreated, + regulationSid, + results, + sid, + status, + url ); } - public enum Status { - COMPLIANT("compliant"), - NONCOMPLIANT("noncompliant"); - - private final String value; - - private Status(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - @JsonCreator - public static Status forValue(final String value) { - return Promoter.enumFromString(value, Status.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/bundle/EvaluationCreator.java b/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/bundle/EvaluationCreator.java index 0946249a25..ae18f8ab3c 100644 --- a/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/bundle/EvaluationCreator.java +++ b/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/bundle/EvaluationCreator.java @@ -14,8 +14,8 @@ package com.twilio.rest.numbers.v2.regulatorycompliance.bundle; + import com.twilio.base.Creator; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,51 +27,42 @@ public class EvaluationCreator extends Creator { - private String pathBundleSid; + private String pathbundleSid; - public EvaluationCreator(final String pathBundleSid) { - this.pathBundleSid = pathBundleSid; + public EvaluationCreator(final String pathbundleSid) { + this.pathbundleSid = pathbundleSid; } + @Override public Evaluation create(final TwilioRestClient client) { - String path = - "/v2/RegulatoryCompliance/Bundles/{BundleSid}/Evaluations"; - path = - path.replace( - "{" + "BundleSid" + "}", - this.pathBundleSid.toString() - ); + String path = "/v2/RegulatoryCompliance/Bundles/{BundleSid}/Evaluations"; + + path = path.replace("{" + "BundleSid" + "}", this.pathbundleSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.NUMBERS.toString(), - path + HttpMethod.POST, + Domains.NUMBERS.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Evaluation creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("Evaluation creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Evaluation.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Evaluation.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/bundle/EvaluationFetcher.java b/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/bundle/EvaluationFetcher.java index 01efeb26e9..d29dc485db 100644 --- a/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/bundle/EvaluationFetcher.java +++ b/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/bundle/EvaluationFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.numbers.v2.regulatorycompliance.bundle; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,55 +26,44 @@ public class EvaluationFetcher extends Fetcher { - private String pathBundleSid; - private String pathSid; + private String pathbundleSid; + private String pathsid; - public EvaluationFetcher(final String pathBundleSid, final String pathSid) { - this.pathBundleSid = pathBundleSid; - this.pathSid = pathSid; + public EvaluationFetcher(final String pathbundleSid, final String pathsid) { + this.pathbundleSid = pathbundleSid; + this.pathsid = pathsid; } + @Override public Evaluation fetch(final TwilioRestClient client) { - String path = - "/v2/RegulatoryCompliance/Bundles/{BundleSid}/Evaluations/{Sid}"; - path = - path.replace( - "{" + "BundleSid" + "}", - this.pathBundleSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/v2/RegulatoryCompliance/Bundles/{BundleSid}/Evaluations/{Sid}"; + + path = path.replace("{" + "BundleSid" + "}", this.pathbundleSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.NUMBERS.toString(), - path + HttpMethod.GET, + Domains.NUMBERS.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Evaluation fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Evaluation fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return Evaluation.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Evaluation.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/bundle/EvaluationReader.java b/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/bundle/EvaluationReader.java index 7b5ea7fc24..8e89ccf6ed 100644 --- a/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/bundle/EvaluationReader.java +++ b/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/bundle/EvaluationReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,116 +30,88 @@ public class EvaluationReader extends Reader { - private String pathBundleSid; + private String pathbundleSid; private Long pageSize; - public EvaluationReader(final String pathBundleSid) { - this.pathBundleSid = pathBundleSid; + public EvaluationReader(final String pathbundleSid) { + this.pathbundleSid = pathbundleSid; } + public EvaluationReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { - String path = - "/v2/RegulatoryCompliance/Bundles/{BundleSid}/Evaluations"; - path = - path.replace( - "{" + "BundleSid" + "}", - this.pathBundleSid.toString() - ); + + String path = "/v2/RegulatoryCompliance/Bundles/{BundleSid}/Evaluations"; + + path = path.replace("{" + "BundleSid" + "}", this.pathbundleSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.NUMBERS.toString(), - path + HttpMethod.GET, + Domains.NUMBERS.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Evaluation read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Evaluation read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "results", - response.getContent(), - Evaluation.class, - client.getObjectMapper() - ); + "results", + response.getContent(), + Evaluation.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.NUMBERS.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.NUMBERS.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/bundle/ItemAssignment.java b/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/bundle/ItemAssignment.java index 39b8640921..ba57d2713c 100644 --- a/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/bundle/ItemAssignment.java +++ b/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/bundle/ItemAssignment.java @@ -18,62 +18,63 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class ItemAssignment extends Resource { - private static final long serialVersionUID = 241370748977037L; - public static ItemAssignmentCreator creator( - final String pathBundleSid, - final String objectSid - ) { - return new ItemAssignmentCreator(pathBundleSid, objectSid); + public static ItemAssignmentCreator creator(final String pathbundleSid, final String objectSid) { + return new ItemAssignmentCreator( + pathbundleSid, objectSid + ); } - public static ItemAssignmentDeleter deleter( - final String pathBundleSid, - final String pathSid - ) { - return new ItemAssignmentDeleter(pathBundleSid, pathSid); + + public static ItemAssignmentDeleter deleter(final String pathbundleSid, final String pathsid) { + return new ItemAssignmentDeleter( + pathbundleSid, pathsid + ); } - public static ItemAssignmentFetcher fetcher( - final String pathBundleSid, - final String pathSid - ) { - return new ItemAssignmentFetcher(pathBundleSid, pathSid); + + public static ItemAssignmentFetcher fetcher(final String pathbundleSid, final String pathsid) { + return new ItemAssignmentFetcher( + pathbundleSid, pathsid + ); } - public static ItemAssignmentReader reader(final String pathBundleSid) { - return new ItemAssignmentReader(pathBundleSid); + + public static ItemAssignmentReader reader(final String pathbundleSid) { + return new ItemAssignmentReader( + pathbundleSid + ); } + /** * Converts a JSON String into a ItemAssignment object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return ItemAssignment object represented by the provided JSON */ - public static ItemAssignment fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static ItemAssignment fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, ItemAssignment.class); @@ -88,14 +89,11 @@ public static ItemAssignment fromJson( * Converts a JSON InputStream into a ItemAssignment object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return ItemAssignment object represented by the provided JSON */ - public static ItemAssignment fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static ItemAssignment fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, ItemAssignment.class); @@ -106,54 +104,50 @@ public static ItemAssignment fromJson( } } - private final String sid; - private final String bundleSid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String objectSid; + @Getter + private final String bundleSid; + @Getter private final ZonedDateTime dateCreated; + @Getter + private final String objectSid; + @Getter + private final String sid; + @Getter private final URI url; @JsonCreator private ItemAssignment( - @JsonProperty("sid") final String sid, - @JsonProperty("bundle_sid") final String bundleSid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("object_sid") final String objectSid, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("url") final URI url + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("bundle_sid") final String bundleSid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("object_sid") final String objectSid, + @JsonProperty("sid") final String sid, + @JsonProperty("url") final URI url ) { - this.sid = sid; - this.bundleSid = bundleSid; this.accountSid = accountSid; + this.bundleSid = bundleSid; + this.dateCreated = dateCreated; this.objectSid = objectSid; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); + this.sid = sid; this.url = url; } - public final String getSid() { - return this.sid; - } - - public final String getBundleSid() { - return this.bundleSid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getObjectSid() { - return this.objectSid; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final URI getUrl() { - return this.url; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -165,26 +159,28 @@ public boolean equals(final Object o) { } ItemAssignment other = (ItemAssignment) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(bundleSid, other.bundleSid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(objectSid, other.objectSid) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(url, other.url) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(bundleSid, other.bundleSid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(objectSid, other.objectSid) && + Objects.equals(sid, other.sid) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - sid, - bundleSid, - accountSid, - objectSid, - dateCreated, - url + accountSid, + bundleSid, + dateCreated, + objectSid, + sid, + url ); } + + } + diff --git a/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/bundle/ItemAssignmentCreator.java b/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/bundle/ItemAssignmentCreator.java index be03c6d7fa..786e10cf1d 100644 --- a/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/bundle/ItemAssignmentCreator.java +++ b/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/bundle/ItemAssignmentCreator.java @@ -14,8 +14,11 @@ package com.twilio.rest.numbers.v2.regulatorycompliance.bundle; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,69 +30,61 @@ public class ItemAssignmentCreator extends Creator { - private String pathBundleSid; + private String pathbundleSid; private String objectSid; - public ItemAssignmentCreator( - final String pathBundleSid, - final String objectSid - ) { - this.pathBundleSid = pathBundleSid; + public ItemAssignmentCreator(final String pathbundleSid, final String objectSid) { + this.pathbundleSid = pathbundleSid; this.objectSid = objectSid; } + public ItemAssignmentCreator setObjectSid(final String objectSid) { this.objectSid = objectSid; return this; } + @Override public ItemAssignment create(final TwilioRestClient client) { - String path = - "/v2/RegulatoryCompliance/Bundles/{BundleSid}/ItemAssignments"; - path = - path.replace( - "{" + "BundleSid" + "}", - this.pathBundleSid.toString() - ); - path = path.replace("{" + "ObjectSid" + "}", this.objectSid.toString()); + String path = "/v2/RegulatoryCompliance/Bundles/{BundleSid}/ItemAssignments"; + + path = path.replace("{" + "BundleSid" + "}", this.pathbundleSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.NUMBERS.toString(), - path + HttpMethod.POST, + Domains.NUMBERS.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "ItemAssignment creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("ItemAssignment creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return ItemAssignment.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return ItemAssignment.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (objectSid != null) { - request.addPostParam("ObjectSid", objectSid); + Serializer.toString(request, "ObjectSid", objectSid, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/bundle/ItemAssignmentDeleter.java b/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/bundle/ItemAssignmentDeleter.java index 38511c1a9f..d0b80c06ff 100644 --- a/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/bundle/ItemAssignmentDeleter.java +++ b/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/bundle/ItemAssignmentDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.numbers.v2.regulatorycompliance.bundle; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,51 +26,41 @@ public class ItemAssignmentDeleter extends Deleter { - private String pathBundleSid; - private String pathSid; + private String pathbundleSid; + private String pathsid; - public ItemAssignmentDeleter( - final String pathBundleSid, - final String pathSid - ) { - this.pathBundleSid = pathBundleSid; - this.pathSid = pathSid; + public ItemAssignmentDeleter(final String pathbundleSid, final String pathsid) { + this.pathbundleSid = pathbundleSid; + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { - String path = - "/v2/RegulatoryCompliance/Bundles/{BundleSid}/ItemAssignments/{Sid}"; - path = - path.replace( - "{" + "BundleSid" + "}", - this.pathBundleSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/v2/RegulatoryCompliance/Bundles/{BundleSid}/ItemAssignments/{Sid}"; + + path = path.replace("{" + "BundleSid" + "}", this.pathbundleSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.NUMBERS.toString(), - path + HttpMethod.DELETE, + Domains.NUMBERS.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "ItemAssignment delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("ItemAssignment delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/bundle/ItemAssignmentFetcher.java b/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/bundle/ItemAssignmentFetcher.java index 0d79626f75..9bf807187e 100644 --- a/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/bundle/ItemAssignmentFetcher.java +++ b/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/bundle/ItemAssignmentFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.numbers.v2.regulatorycompliance.bundle; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,58 +26,44 @@ public class ItemAssignmentFetcher extends Fetcher { - private String pathBundleSid; - private String pathSid; + private String pathbundleSid; + private String pathsid; - public ItemAssignmentFetcher( - final String pathBundleSid, - final String pathSid - ) { - this.pathBundleSid = pathBundleSid; - this.pathSid = pathSid; + public ItemAssignmentFetcher(final String pathbundleSid, final String pathsid) { + this.pathbundleSid = pathbundleSid; + this.pathsid = pathsid; } + @Override public ItemAssignment fetch(final TwilioRestClient client) { - String path = - "/v2/RegulatoryCompliance/Bundles/{BundleSid}/ItemAssignments/{Sid}"; - path = - path.replace( - "{" + "BundleSid" + "}", - this.pathBundleSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/v2/RegulatoryCompliance/Bundles/{BundleSid}/ItemAssignments/{Sid}"; + + path = path.replace("{" + "BundleSid" + "}", this.pathbundleSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.NUMBERS.toString(), - path + HttpMethod.GET, + Domains.NUMBERS.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "ItemAssignment fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("ItemAssignment fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return ItemAssignment.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return ItemAssignment.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/bundle/ItemAssignmentReader.java b/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/bundle/ItemAssignmentReader.java index 51c2f5b8cd..0fc79ee676 100644 --- a/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/bundle/ItemAssignmentReader.java +++ b/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/bundle/ItemAssignmentReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,116 +30,88 @@ public class ItemAssignmentReader extends Reader { - private String pathBundleSid; + private String pathbundleSid; private Long pageSize; - public ItemAssignmentReader(final String pathBundleSid) { - this.pathBundleSid = pathBundleSid; + public ItemAssignmentReader(final String pathbundleSid) { + this.pathbundleSid = pathbundleSid; } + public ItemAssignmentReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { - String path = - "/v2/RegulatoryCompliance/Bundles/{BundleSid}/ItemAssignments"; - path = - path.replace( - "{" + "BundleSid" + "}", - this.pathBundleSid.toString() - ); + + String path = "/v2/RegulatoryCompliance/Bundles/{BundleSid}/ItemAssignments"; + + path = path.replace("{" + "BundleSid" + "}", this.pathbundleSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.NUMBERS.toString(), - path + HttpMethod.GET, + Domains.NUMBERS.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "ItemAssignment read failed: Unable to connect to server" - ); + throw new ApiConnectionException("ItemAssignment read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "results", - response.getContent(), - ItemAssignment.class, - client.getObjectMapper() - ); + "results", + response.getContent(), + ItemAssignment.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.NUMBERS.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.NUMBERS.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/bundle/ReplaceItems.java b/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/bundle/ReplaceItems.java index 9af6e75dac..82a71afe22 100644 --- a/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/bundle/ReplaceItems.java +++ b/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/bundle/ReplaceItems.java @@ -18,45 +18,68 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class ReplaceItems extends Resource { - private static final long serialVersionUID = 154268646541269L; - public static ReplaceItemsCreator creator( - final String pathBundleSid, - final String fromBundleSid - ) { - return new ReplaceItemsCreator(pathBundleSid, fromBundleSid); + public static ReplaceItemsCreator creator(final String pathbundleSid, final String fromBundleSid) { + return new ReplaceItemsCreator( + pathbundleSid, fromBundleSid + ); } + + public enum Status { + DRAFT("draft"), + PENDING_REVIEW("pending-review"), + IN_REVIEW("in-review"), + TWILIO_REJECTED("twilio-rejected"), + TWILIO_APPROVED("twilio-approved"), + PROVISIONALLY_APPROVED("provisionally-approved"); + + private final String value; + + private Status(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static Status forValue(final String value) { + return Promoter.enumFromString(value, Status.values()); + } + } + + /** * Converts a JSON String into a ReplaceItems object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return ReplaceItems object represented by the provided JSON */ - public static ReplaceItems fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static ReplaceItems fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, ReplaceItems.class); @@ -71,14 +94,11 @@ public static ReplaceItems fromJson( * Converts a JSON InputStream into a ReplaceItems object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return ReplaceItems object represented by the provided JSON */ - public static ReplaceItems fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static ReplaceItems fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, ReplaceItems.class); @@ -89,80 +109,66 @@ public static ReplaceItems fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String regulationSid; + @Getter + private final ZonedDateTime dateCreated; + @Getter + private final ZonedDateTime dateUpdated; + @Getter + private final String email; + @Getter private final String friendlyName; + @Getter + private final String regulationSid; + @Getter + private final String sid; + @Getter private final ReplaceItems.Status status; - private final ZonedDateTime validUntil; - private final String email; + @Getter private final URI statusCallback; - private final ZonedDateTime dateCreated; - private final ZonedDateTime dateUpdated; + @Getter + private final ZonedDateTime validUntil; @JsonCreator private ReplaceItems( - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("regulation_sid") final String regulationSid, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("status") final ReplaceItems.Status status, - @JsonProperty("valid_until") final String validUntil, - @JsonProperty("email") final String email, - @JsonProperty("status_callback") final URI statusCallback, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("email") final String email, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("regulation_sid") final String regulationSid, + @JsonProperty("sid") final String sid, + @JsonProperty("status") final ReplaceItems.Status status, + @JsonProperty("status_callback") final URI statusCallback, + @JsonProperty("valid_until") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime validUntil ) { - this.sid = sid; this.accountSid = accountSid; - this.regulationSid = regulationSid; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; + this.email = email; this.friendlyName = friendlyName; + this.regulationSid = regulationSid; + this.sid = sid; this.status = status; - this.validUntil = DateConverter.iso8601DateTimeFromString(validUntil); - this.email = email; this.statusCallback = statusCallback; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); - } - - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getRegulationSid() { - return this.regulationSid; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final ReplaceItems.Status getStatus() { - return this.status; - } - - public final ZonedDateTime getValidUntil() { - return this.validUntil; - } - - public final String getEmail() { - return this.email; - } - - public final URI getStatusCallback() { - return this.statusCallback; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; + this.validUntil = validUntil; } @Override @@ -176,58 +182,36 @@ public boolean equals(final Object o) { } ReplaceItems other = (ReplaceItems) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(regulationSid, other.regulationSid) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(status, other.status) && - Objects.equals(validUntil, other.validUntil) && - Objects.equals(email, other.email) && - Objects.equals(statusCallback, other.statusCallback) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(email, other.email) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(regulationSid, other.regulationSid) && + Objects.equals(sid, other.sid) && + Objects.equals(status, other.status) && + Objects.equals(statusCallback, other.statusCallback) && + Objects.equals(validUntil, other.validUntil) ); } @Override public int hashCode() { return Objects.hash( - sid, - accountSid, - regulationSid, - friendlyName, - status, - validUntil, - email, - statusCallback, - dateCreated, - dateUpdated + accountSid, + dateCreated, + dateUpdated, + email, + friendlyName, + regulationSid, + sid, + status, + statusCallback, + validUntil ); } - public enum Status { - DRAFT("draft"), - PENDING_REVIEW("pending-review"), - IN_REVIEW("in-review"), - TWILIO_REJECTED("twilio-rejected"), - TWILIO_APPROVED("twilio-approved"), - PROVISIONALLY_APPROVED("provisionally-approved"); - - private final String value; - - private Status(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - @JsonCreator - public static Status forValue(final String value) { - return Promoter.enumFromString(value, Status.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/bundle/ReplaceItemsCreator.java b/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/bundle/ReplaceItemsCreator.java index 0510ca4e33..878bfeb3e1 100644 --- a/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/bundle/ReplaceItemsCreator.java +++ b/src/main/java/com/twilio/rest/numbers/v2/regulatorycompliance/bundle/ReplaceItemsCreator.java @@ -14,8 +14,11 @@ package com.twilio.rest.numbers.v2.regulatorycompliance.bundle; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,73 +30,61 @@ public class ReplaceItemsCreator extends Creator { - private String pathBundleSid; + private String pathbundleSid; private String fromBundleSid; - public ReplaceItemsCreator( - final String pathBundleSid, - final String fromBundleSid - ) { - this.pathBundleSid = pathBundleSid; + public ReplaceItemsCreator(final String pathbundleSid, final String fromBundleSid) { + this.pathbundleSid = pathbundleSid; this.fromBundleSid = fromBundleSid; } + public ReplaceItemsCreator setFromBundleSid(final String fromBundleSid) { this.fromBundleSid = fromBundleSid; return this; } + @Override public ReplaceItems create(final TwilioRestClient client) { - String path = - "/v2/RegulatoryCompliance/Bundles/{BundleSid}/ReplaceItems"; - path = - path.replace( - "{" + "BundleSid" + "}", - this.pathBundleSid.toString() - ); - path = - path.replace( - "{" + "FromBundleSid" + "}", - this.fromBundleSid.toString() - ); + String path = "/v2/RegulatoryCompliance/Bundles/{BundleSid}/ReplaceItems"; + + path = path.replace("{" + "BundleSid" + "}", this.pathbundleSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.NUMBERS.toString(), - path + HttpMethod.POST, + Domains.NUMBERS.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "ReplaceItems creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("ReplaceItems creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return ReplaceItems.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return ReplaceItems.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (fromBundleSid != null) { - request.addPostParam("FromBundleSid", fromBundleSid); + Serializer.toString(request, "FromBundleSid", fromBundleSid, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/numbers/v3/HostedNumberOrder.java b/src/main/java/com/twilio/rest/numbers/v3/HostedNumberOrder.java new file mode 100644 index 0000000000..469e820d9e --- /dev/null +++ b/src/main/java/com/twilio/rest/numbers/v3/HostedNumberOrder.java @@ -0,0 +1,340 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Numbers + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package com.twilio.rest.numbers.v3; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.twilio.base.Resource; +import com.twilio.converter.Promoter; +import com.twilio.exception.ApiConnectionException; +import com.twilio.exception.ApiException; +import com.twilio.type.PhoneNumberCapabilities; +import lombok.Getter; +import lombok.ToString; + +import java.io.IOException; +import java.io.InputStream; +import java.net.URI; +import java.time.ZonedDateTime; +import java.util.List; +import java.util.Objects; + +@JsonIgnoreProperties(ignoreUnknown = true) +@ToString +public class HostedNumberOrder extends Resource { + + + public static HostedNumberOrderCreator creator(final com.twilio.type.PhoneNumber phoneNumber, final Boolean smsCapability) { + return new HostedNumberOrderCreator( + phoneNumber, smsCapability + ); + } + + + public enum VerificationType { + PHONE_CALL("phone-call"), + PHONE_BILL("phone-bill"); + + private final String value; + + private VerificationType(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static VerificationType forValue(final String value) { + return Promoter.enumFromString(value, VerificationType.values()); + } + } + + public enum HostedNumberOrderEnumStatus { + TWILIO_PROCESSING("twilio-processing"), + RECEIVED("received"), + PENDING_VERIFICATION("pending-verification"), + VERIFIED("verified"), + PENDING_LOA("pending-loa"), + CARRIER_PROCESSING("carrier-processing"), + TESTING("testing"), + COMPLETED("completed"), + FAILED("failed"), + ACTION_REQUIRED("action-required"); + + private final String value; + + private HostedNumberOrderEnumStatus(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static HostedNumberOrderEnumStatus forValue(final String value) { + return Promoter.enumFromString(value, HostedNumberOrderEnumStatus.values()); + } + } + + public enum HostedNumberOrderEnumVerificationType { + PHONE_CALL("phone-call"), + PHONE_BILL("phone-bill"); + + private final String value; + + private HostedNumberOrderEnumVerificationType(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static HostedNumberOrderEnumVerificationType forValue(final String value) { + return Promoter.enumFromString(value, HostedNumberOrderEnumVerificationType.values()); + } + } + + + /** + * Converts a JSON String into a HostedNumberOrder object using the provided ObjectMapper. + * + * @param json Raw JSON String + * @param objectMapper Jackson ObjectMapper + * @return HostedNumberOrder object represented by the provided JSON + */ + public static HostedNumberOrder fromJson(final String json, final ObjectMapper objectMapper) { + // Convert all checked exceptions to Runtime + try { + return objectMapper.readValue(json, HostedNumberOrder.class); + } catch (final JsonMappingException | JsonParseException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + /** + * Converts a JSON InputStream into a HostedNumberOrder object using the provided + * ObjectMapper. + * + * @param json Raw JSON InputStream + * @param objectMapper Jackson ObjectMapper + * @return HostedNumberOrder object represented by the provided JSON + */ + public static HostedNumberOrder fromJson(final InputStream json, final ObjectMapper objectMapper) { + // Convert all checked exceptions to Runtime + try { + return objectMapper.readValue(json, HostedNumberOrder.class); + } catch (final JsonMappingException | JsonParseException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter + private final String accountSid; + @Getter + private final String addressSid; + @Getter + private final Integer callDelay; + @Getter + private final PhoneNumberCapabilities capabilities; + @Getter + private final List ccEmails; + @Getter + private final ZonedDateTime dateCreated; + @Getter + private final ZonedDateTime dateUpdated; + @Getter + private final String email; + @Getter + private final String extension; + @Getter + private final String failureReason; + @Getter + private final String friendlyName; + @Getter + private final String incomingPhoneNumberSid; + @Getter + private final com.twilio.type.PhoneNumber phoneNumber; + @Getter + private final String sid; + @Getter + private final String signingDocumentSid; + @Getter + private final HostedNumberOrder.HostedNumberOrderEnumStatus status; + @Getter + private final String uniqueName; + @Getter + private final URI url; + @Getter + private final Integer verificationAttempts; + @Getter + private final List verificationCallSids; + @Getter + private final String verificationCode; + @Getter + private final String verificationDocumentSid; + @Getter + private final HostedNumberOrder.HostedNumberOrderEnumVerificationType verificationType; + + @JsonCreator + private HostedNumberOrder( + @JsonProperty("accountSid") final String accountSid, + @JsonProperty("addressSid") final String addressSid, + @JsonProperty("callDelay") final Integer callDelay, + @JsonProperty("capabilities") final PhoneNumberCapabilities capabilities, + @JsonProperty("ccEmails") final List ccEmails, + @JsonProperty("dateCreated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("dateUpdated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("email") final String email, + @JsonProperty("extension") final String extension, + @JsonProperty("failureReason") final String failureReason, + @JsonProperty("friendlyName") final String friendlyName, + @JsonProperty("incomingPhoneNumberSid") final String incomingPhoneNumberSid, + @JsonProperty("phoneNumber") final com.twilio.type.PhoneNumber phoneNumber, + @JsonProperty("sid") final String sid, + @JsonProperty("signingDocumentSid") final String signingDocumentSid, + @JsonProperty("status") final HostedNumberOrder.HostedNumberOrderEnumStatus status, + @JsonProperty("uniqueName") final String uniqueName, + @JsonProperty("url") final URI url, + @JsonProperty("verificationAttempts") final Integer verificationAttempts, + @JsonProperty("verificationCallSids") final List verificationCallSids, + @JsonProperty("verificationCode") final String verificationCode, + @JsonProperty("verificationDocumentSid") final String verificationDocumentSid, + @JsonProperty("verificationType") final HostedNumberOrder.HostedNumberOrderEnumVerificationType verificationType + ) { + this.accountSid = accountSid; + this.addressSid = addressSid; + this.callDelay = callDelay; + this.capabilities = capabilities; + this.ccEmails = ccEmails; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; + this.email = email; + this.extension = extension; + this.failureReason = failureReason; + this.friendlyName = friendlyName; + this.incomingPhoneNumberSid = incomingPhoneNumberSid; + this.phoneNumber = phoneNumber; + this.sid = sid; + this.signingDocumentSid = signingDocumentSid; + this.status = status; + this.uniqueName = uniqueName; + this.url = url; + this.verificationAttempts = verificationAttempts; + this.verificationCallSids = verificationCallSids; + this.verificationCode = verificationCode; + this.verificationDocumentSid = verificationDocumentSid; + this.verificationType = verificationType; + } + + @Override + public boolean equals(final Object o) { + if (this == o) { + return true; + } + + if (o == null || getClass() != o.getClass()) { + return false; + } + + HostedNumberOrder other = (HostedNumberOrder) o; + return ( + Objects.equals(accountSid, other.accountSid) && + Objects.equals(addressSid, other.addressSid) && + Objects.equals(callDelay, other.callDelay) && + Objects.equals(capabilities, other.capabilities) && + Objects.equals(ccEmails, other.ccEmails) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(email, other.email) && + Objects.equals(extension, other.extension) && + Objects.equals(failureReason, other.failureReason) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(incomingPhoneNumberSid, other.incomingPhoneNumberSid) && + Objects.equals(phoneNumber, other.phoneNumber) && + Objects.equals(sid, other.sid) && + Objects.equals(signingDocumentSid, other.signingDocumentSid) && + Objects.equals(status, other.status) && + Objects.equals(uniqueName, other.uniqueName) && + Objects.equals(url, other.url) && + Objects.equals(verificationAttempts, other.verificationAttempts) && + Objects.equals(verificationCallSids, other.verificationCallSids) && + Objects.equals(verificationCode, other.verificationCode) && + Objects.equals(verificationDocumentSid, other.verificationDocumentSid) && + Objects.equals(verificationType, other.verificationType) + ); + } + + @Override + public int hashCode() { + return Objects.hash( + accountSid, + addressSid, + callDelay, + capabilities, + ccEmails, + dateCreated, + dateUpdated, + email, + extension, + failureReason, + friendlyName, + incomingPhoneNumberSid, + phoneNumber, + sid, + signingDocumentSid, + status, + uniqueName, + url, + verificationAttempts, + verificationCallSids, + verificationCode, + verificationDocumentSid, + verificationType + ); + } + + +} + diff --git a/src/main/java/com/twilio/rest/numbers/v3/HostedNumberOrderCreator.java b/src/main/java/com/twilio/rest/numbers/v3/HostedNumberOrderCreator.java new file mode 100644 index 0000000000..22f5737e12 --- /dev/null +++ b/src/main/java/com/twilio/rest/numbers/v3/HostedNumberOrderCreator.java @@ -0,0 +1,291 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Numbers + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package com.twilio.rest.numbers.v3; + + +import com.twilio.base.Creator; +import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Promoter; +import com.twilio.converter.Serializer; +import com.twilio.exception.ApiConnectionException; +import com.twilio.exception.ApiException; +import com.twilio.exception.RestException; +import com.twilio.http.HttpMethod; +import com.twilio.http.Request; +import com.twilio.http.Response; +import com.twilio.http.TwilioRestClient; +import com.twilio.rest.Domains; + +import java.net.URI; +import java.util.List; + +public class HostedNumberOrderCreator extends Creator { + + private com.twilio.type.PhoneNumber phoneNumber; + private Boolean smsCapability; + private String accountSid; + private String friendlyName; + private String uniqueName; + private List ccEmails; + private URI smsUrl; + private HttpMethod smsMethod; + private URI smsFallbackUrl; + private HttpMethod smsFallbackMethod; + private URI statusCallbackUrl; + private HttpMethod statusCallbackMethod; + private String smsApplicationSid; + private String addressSid; + private String email; + private HostedNumberOrder.VerificationType verificationType; + private String verificationDocumentSid; + + public HostedNumberOrderCreator(final com.twilio.type.PhoneNumber phoneNumber, final Boolean smsCapability) { + this.phoneNumber = phoneNumber; + this.smsCapability = smsCapability; + } + + + public HostedNumberOrderCreator setPhoneNumber(final com.twilio.type.PhoneNumber phoneNumber) { + this.phoneNumber = phoneNumber; + return this; + } + + public HostedNumberOrderCreator setPhoneNumber(final String phoneNumber) { + return setPhoneNumber(Promoter.phoneNumberFromString(phoneNumber)); + } + + public HostedNumberOrderCreator setSmsCapability(final Boolean smsCapability) { + this.smsCapability = smsCapability; + return this; + } + + + public HostedNumberOrderCreator setAccountSid(final String accountSid) { + this.accountSid = accountSid; + return this; + } + + + public HostedNumberOrderCreator setFriendlyName(final String friendlyName) { + this.friendlyName = friendlyName; + return this; + } + + + public HostedNumberOrderCreator setUniqueName(final String uniqueName) { + this.uniqueName = uniqueName; + return this; + } + + + public HostedNumberOrderCreator setCcEmails(final List ccEmails) { + this.ccEmails = ccEmails; + return this; + } + + public HostedNumberOrderCreator setCcEmails(final String ccEmails) { + return setCcEmails(Promoter.listOfOne(ccEmails)); + } + + public HostedNumberOrderCreator setSmsUrl(final URI smsUrl) { + this.smsUrl = smsUrl; + return this; + } + + + public HostedNumberOrderCreator setSmsMethod(final HttpMethod smsMethod) { + this.smsMethod = smsMethod; + return this; + } + + + public HostedNumberOrderCreator setSmsFallbackUrl(final URI smsFallbackUrl) { + this.smsFallbackUrl = smsFallbackUrl; + return this; + } + + + public HostedNumberOrderCreator setSmsFallbackMethod(final HttpMethod smsFallbackMethod) { + this.smsFallbackMethod = smsFallbackMethod; + return this; + } + + + public HostedNumberOrderCreator setStatusCallbackUrl(final URI statusCallbackUrl) { + this.statusCallbackUrl = statusCallbackUrl; + return this; + } + + + public HostedNumberOrderCreator setStatusCallbackMethod(final HttpMethod statusCallbackMethod) { + this.statusCallbackMethod = statusCallbackMethod; + return this; + } + + + public HostedNumberOrderCreator setSmsApplicationSid(final String smsApplicationSid) { + this.smsApplicationSid = smsApplicationSid; + return this; + } + + + public HostedNumberOrderCreator setAddressSid(final String addressSid) { + this.addressSid = addressSid; + return this; + } + + + public HostedNumberOrderCreator setEmail(final String email) { + this.email = email; + return this; + } + + + public HostedNumberOrderCreator setVerificationType(final HostedNumberOrder.VerificationType verificationType) { + this.verificationType = verificationType; + return this; + } + + + public HostedNumberOrderCreator setVerificationDocumentSid(final String verificationDocumentSid) { + this.verificationDocumentSid = verificationDocumentSid; + return this; + } + + + @Override + public HostedNumberOrder create(final TwilioRestClient client) { + + String path = "/v3/HostedNumbers/HostedNumberOrders"; + + + Request request = new Request( + HttpMethod.POST, + Domains.NUMBERS.toString(), + path + ); + request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + addPostParams(request); + + Response response = client.request(request); + + if (response == null) { + throw new ApiConnectionException("HostedNumberOrder creation failed: Unable to connect to server"); + } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { + RestException restException = RestException.fromJson( + response.getStream(), + client.getObjectMapper() + ); + if (restException == null) { + throw new ApiException("Server Error, no content", response.getStatusCode()); + } + throw new ApiException(restException); + } + + return HostedNumberOrder.fromJson(response.getStream(), client.getObjectMapper()); + } + + private void addPostParams(final Request request) { + + if (phoneNumber != null) { + Serializer.toString(request, "phoneNumber", phoneNumber, ParameterType.URLENCODED); + } + + + if (smsCapability != null) { + Serializer.toString(request, "smsCapability", smsCapability, ParameterType.URLENCODED); + } + + + if (accountSid != null) { + Serializer.toString(request, "accountSid", accountSid, ParameterType.URLENCODED); + } + + + if (friendlyName != null) { + Serializer.toString(request, "friendlyName", friendlyName, ParameterType.URLENCODED); + } + + + if (uniqueName != null) { + Serializer.toString(request, "uniqueName", uniqueName, ParameterType.URLENCODED); + } + + + if (ccEmails != null) { + for (String param : ccEmails) { + Serializer.toString(request, "ccEmails", param, ParameterType.URLENCODED); + } + } + + + if (smsUrl != null) { + Serializer.toString(request, "smsUrl", smsUrl, ParameterType.URLENCODED); + } + + + if (smsMethod != null) { + Serializer.toString(request, "smsMethod", smsMethod, ParameterType.URLENCODED); + } + + + if (smsFallbackUrl != null) { + Serializer.toString(request, "smsFallbackUrl", smsFallbackUrl, ParameterType.URLENCODED); + } + + + if (smsFallbackMethod != null) { + Serializer.toString(request, "smsFallbackMethod", smsFallbackMethod, ParameterType.URLENCODED); + } + + + if (statusCallbackUrl != null) { + Serializer.toString(request, "statusCallbackUrl", statusCallbackUrl, ParameterType.URLENCODED); + } + + + if (statusCallbackMethod != null) { + Serializer.toString(request, "statusCallbackMethod", statusCallbackMethod, ParameterType.URLENCODED); + } + + + if (smsApplicationSid != null) { + Serializer.toString(request, "smsApplicationSid", smsApplicationSid, ParameterType.URLENCODED); + } + + + if (addressSid != null) { + Serializer.toString(request, "addressSid", addressSid, ParameterType.URLENCODED); + } + + + if (email != null) { + Serializer.toString(request, "email", email, ParameterType.URLENCODED); + } + + + if (verificationType != null) { + Serializer.toString(request, "verificationType", verificationType, ParameterType.URLENCODED); + } + + + if (verificationDocumentSid != null) { + Serializer.toString(request, "verificationDocumentSid", verificationDocumentSid, ParameterType.URLENCODED); + } + + + } +} diff --git a/src/main/java/com/twilio/rest/oauth/v1/Authorize.java b/src/main/java/com/twilio/rest/oauth/v1/Authorize.java index 4a1c0e6a06..7852074c0f 100644 --- a/src/main/java/com/twilio/rest/oauth/v1/Authorize.java +++ b/src/main/java/com/twilio/rest/oauth/v1/Authorize.java @@ -18,39 +18,40 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Authorize extends Resource { - private static final long serialVersionUID = 245900587626041L; public static AuthorizeFetcher fetcher() { - return new AuthorizeFetcher(); + return new AuthorizeFetcher( + + ); } + /** * Converts a JSON String into a Authorize object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Authorize object represented by the provided JSON */ - public static Authorize fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Authorize fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Authorize.class); @@ -65,14 +66,11 @@ public static Authorize fromJson( * Converts a JSON InputStream into a Authorize object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Authorize object represented by the provided JSON */ - public static Authorize fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Authorize fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Authorize.class); @@ -83,17 +81,29 @@ public static Authorize fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final URI redirectTo; @JsonCreator - private Authorize(@JsonProperty("redirect_to") final URI redirectTo) { + private Authorize( + @JsonProperty("redirect_to") final URI redirectTo + ) { this.redirectTo = redirectTo; } - public final URI getRedirectTo() { - return this.redirectTo; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -105,12 +115,18 @@ public boolean equals(final Object o) { } Authorize other = (Authorize) o; - - return Objects.equals(redirectTo, other.redirectTo); + return ( + Objects.equals(redirectTo, other.redirectTo) + ); } @Override public int hashCode() { - return Objects.hash(redirectTo); + return Objects.hash( + redirectTo + ); } + + } + diff --git a/src/main/java/com/twilio/rest/oauth/v1/AuthorizeFetcher.java b/src/main/java/com/twilio/rest/oauth/v1/AuthorizeFetcher.java index 6b66ab822a..e79be51444 100644 --- a/src/main/java/com/twilio/rest/oauth/v1/AuthorizeFetcher.java +++ b/src/main/java/com/twilio/rest/oauth/v1/AuthorizeFetcher.java @@ -16,13 +16,14 @@ import com.twilio.auth_strategy.NoAuthStrategy; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; import com.twilio.http.HttpMethod; -import com.twilio.http.Response; import com.twilio.http.Request; +import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; @@ -34,88 +35,98 @@ public class AuthorizeFetcher extends Fetcher { private String scope; private String state; - public AuthorizeFetcher() {} + public AuthorizeFetcher() { + } + public AuthorizeFetcher setResponseType(final String responseType) { this.responseType = responseType; return this; } + public AuthorizeFetcher setClientId(final String clientId) { this.clientId = clientId; return this; } + public AuthorizeFetcher setRedirectUri(final String redirectUri) { this.redirectUri = redirectUri; return this; } + public AuthorizeFetcher setScope(final String scope) { this.scope = scope; return this; } + public AuthorizeFetcher setState(final String state) { this.state = state; return this; } + @Override public Authorize fetch(final TwilioRestClient client) { + String path = "/v1/authorize"; + Request request = new Request( - HttpMethod.GET, - Domains.OAUTH.toString(), - path + HttpMethod.GET, + Domains.OAUTH.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); request.setAuth(NoAuthStrategy.getInstance()); + addQueryParams(request); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Authorize fetch failed: Unable to connect to server" - ); - } else if ( - !TwilioRestClient.SUCCESS.test(response.getStatusCode()) - ) { + throw new ApiConnectionException("Authorize fetch failed: Unable to connect to server"); + } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return Authorize.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Authorize.fromJson(response.getStream(), client.getObjectMapper()); } private void addQueryParams(final Request request) { + + if (responseType != null) { - request.addQueryParam("ResponseType", responseType); + Serializer.toString(request, "ResponseType", responseType, ParameterType.QUERY); } + + if (clientId != null) { - request.addQueryParam("ClientId", clientId); + Serializer.toString(request, "ClientId", clientId, ParameterType.QUERY); } + + if (redirectUri != null) { - request.addQueryParam("RedirectUri", redirectUri); + Serializer.toString(request, "RedirectUri", redirectUri, ParameterType.QUERY); } + + if (scope != null) { - request.addQueryParam("Scope", scope); + Serializer.toString(request, "Scope", scope, ParameterType.QUERY); } + + if (state != null) { - request.addQueryParam("State", state); + Serializer.toString(request, "State", state, ParameterType.QUERY); } + + } } diff --git a/src/main/java/com/twilio/rest/oauth/v1/Token.java b/src/main/java/com/twilio/rest/oauth/v1/Token.java index 0914298465..4424a9cf43 100644 --- a/src/main/java/com/twilio/rest/oauth/v1/Token.java +++ b/src/main/java/com/twilio/rest/oauth/v1/Token.java @@ -18,41 +18,39 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Token extends Resource { - private static final long serialVersionUID = 258139119277894L; - public static TokenCreator creator( - final String grantType, - final String clientId - ) { - return new TokenCreator(grantType, clientId); + public static TokenCreator creator(final String grantType, final String clientId) { + return new TokenCreator( + grantType, clientId + ); } + /** * Converts a JSON String into a Token object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Token object represented by the provided JSON */ - public static Token fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Token fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Token.class); @@ -67,14 +65,11 @@ public static Token fromJson( * Converts a JSON InputStream into a Token object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Token object represented by the provided JSON */ - public static Token fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Token fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Token.class); @@ -85,45 +80,43 @@ public static Token fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accessToken; - private final String refreshToken; + @Getter + private final Long expiresIn; + @Getter private final String idToken; + @Getter + private final String refreshToken; + @Getter private final String tokenType; - private final Long expiresIn; @JsonCreator private Token( - @JsonProperty("access_token") final String accessToken, - @JsonProperty("refresh_token") final String refreshToken, - @JsonProperty("id_token") final String idToken, - @JsonProperty("token_type") final String tokenType, - @JsonProperty("expires_in") final Long expiresIn + @JsonProperty("access_token") final String accessToken, + @JsonProperty("expires_in") final Long expiresIn, + @JsonProperty("id_token") final String idToken, + @JsonProperty("refresh_token") final String refreshToken, + @JsonProperty("token_type") final String tokenType ) { this.accessToken = accessToken; - this.refreshToken = refreshToken; + this.expiresIn = expiresIn; this.idToken = idToken; + this.refreshToken = refreshToken; this.tokenType = tokenType; - this.expiresIn = expiresIn; - } - - public final String getAccessToken() { - return this.accessToken; - } - - public final String getRefreshToken() { - return this.refreshToken; - } - - public final String getIdToken() { - return this.idToken; - } - - public final String getTokenType() { - return this.tokenType; - } - - public final Long getExpiresIn() { - return this.expiresIn; } @Override @@ -137,24 +130,26 @@ public boolean equals(final Object o) { } Token other = (Token) o; - return ( - Objects.equals(accessToken, other.accessToken) && - Objects.equals(refreshToken, other.refreshToken) && - Objects.equals(idToken, other.idToken) && - Objects.equals(tokenType, other.tokenType) && - Objects.equals(expiresIn, other.expiresIn) + Objects.equals(accessToken, other.accessToken) && + Objects.equals(expiresIn, other.expiresIn) && + Objects.equals(idToken, other.idToken) && + Objects.equals(refreshToken, other.refreshToken) && + Objects.equals(tokenType, other.tokenType) ); } @Override public int hashCode() { return Objects.hash( - accessToken, - refreshToken, - idToken, - tokenType, - expiresIn + accessToken, + expiresIn, + idToken, + refreshToken, + tokenType ); } + + } + diff --git a/src/main/java/com/twilio/rest/oauth/v1/TokenCreator.java b/src/main/java/com/twilio/rest/oauth/v1/TokenCreator.java index edc3882649..18240fcff6 100644 --- a/src/main/java/com/twilio/rest/oauth/v1/TokenCreator.java +++ b/src/main/java/com/twilio/rest/oauth/v1/TokenCreator.java @@ -14,16 +14,19 @@ package com.twilio.rest.oauth.v1; + import com.twilio.auth_strategy.NoAuthStrategy; import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; import com.twilio.http.HttpMethod; +import com.twilio.http.Request; import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; -import com.twilio.http.Request; import com.twilio.rest.Domains; public class TokenCreator extends Creator { @@ -42,78 +45,81 @@ public TokenCreator(final String grantType, final String clientId) { this.clientId = clientId; } + public TokenCreator setGrantType(final String grantType) { this.grantType = grantType; return this; } + public TokenCreator setClientId(final String clientId) { this.clientId = clientId; return this; } + public TokenCreator setClientSecret(final String clientSecret) { this.clientSecret = clientSecret; return this; } + public TokenCreator setCode(final String code) { this.code = code; return this; } + public TokenCreator setRedirectUri(final String redirectUri) { this.redirectUri = redirectUri; return this; } + public TokenCreator setAudience(final String audience) { this.audience = audience; return this; } + public TokenCreator setRefreshToken(final String refreshToken) { this.refreshToken = refreshToken; return this; } + public TokenCreator setScope(final String scope) { this.scope = scope; return this; } + @Override public Token create(final TwilioRestClient client) { + String path = "/v1/token"; - path = path.replace("{" + "GrantType" + "}", this.grantType.toString()); - path = path.replace("{" + "ClientId" + "}", this.clientId.toString()); Request request = new Request( - HttpMethod.POST, - Domains.OAUTH.toString(), - path + HttpMethod.POST, + Domains.OAUTH.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); request.setAuth(NoAuthStrategy.getInstance()); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Token creation failed: Unable to connect to server" - ); - } else if ( - !TwilioRestClient.SUCCESS.test(response.getStatusCode()) - ) { + throw new ApiConnectionException("Token creation failed: Unable to connect to server"); + } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -122,29 +128,46 @@ public Token create(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (grantType != null) { - request.addPostParam("GrantType", grantType); + Serializer.toString(request, "GrantType", grantType, ParameterType.URLENCODED); } + + if (clientId != null) { - request.addPostParam("ClientId", clientId); + Serializer.toString(request, "ClientId", clientId, ParameterType.URLENCODED); } + + if (clientSecret != null) { - request.addPostParam("ClientSecret", clientSecret); + Serializer.toString(request, "ClientSecret", clientSecret, ParameterType.URLENCODED); } + + if (code != null) { - request.addPostParam("Code", code); + Serializer.toString(request, "Code", code, ParameterType.URLENCODED); } + + if (redirectUri != null) { - request.addPostParam("RedirectUri", redirectUri); + Serializer.toString(request, "RedirectUri", redirectUri, ParameterType.URLENCODED); } + + if (audience != null) { - request.addPostParam("Audience", audience); + Serializer.toString(request, "Audience", audience, ParameterType.URLENCODED); } + + if (refreshToken != null) { - request.addPostParam("RefreshToken", refreshToken); + Serializer.toString(request, "RefreshToken", refreshToken, ParameterType.URLENCODED); } + + if (scope != null) { - request.addPostParam("Scope", scope); + Serializer.toString(request, "Scope", scope, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/oauth/v2/Token.java b/src/main/java/com/twilio/rest/oauth/v2/Token.java new file mode 100644 index 0000000000..211060ea30 --- /dev/null +++ b/src/main/java/com/twilio/rest/oauth/v2/Token.java @@ -0,0 +1,155 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * User OAuth API + * User OAuth API + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package com.twilio.rest.oauth.v2; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.twilio.base.Resource; +import com.twilio.exception.ApiConnectionException; +import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + +import java.io.IOException; +import java.io.InputStream; +import java.util.Objects; + +@JsonIgnoreProperties(ignoreUnknown = true) +@ToString +public class Token extends Resource { + + + public static TokenCreator creator(final String grantType, final String clientId) { + return new TokenCreator( + grantType, clientId + ); + } + + + /** + * Converts a JSON String into a Token object using the provided ObjectMapper. + * + * @param json Raw JSON String + * @param objectMapper Jackson ObjectMapper + * @return Token object represented by the provided JSON + */ + public static Token fromJson(final String json, final ObjectMapper objectMapper) { + // Convert all checked exceptions to Runtime + try { + return objectMapper.readValue(json, Token.class); + } catch (final JsonMappingException | JsonParseException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + /** + * Converts a JSON InputStream into a Token object using the provided + * ObjectMapper. + * + * @param json Raw JSON InputStream + * @param objectMapper Jackson ObjectMapper + * @return Token object represented by the provided JSON + */ + public static Token fromJson(final InputStream json, final ObjectMapper objectMapper) { + // Convert all checked exceptions to Runtime + try { + return objectMapper.readValue(json, Token.class); + } catch (final JsonMappingException | JsonParseException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter + private final String accessToken; + @Getter + private final Long expiresIn; + @Getter + private final String idToken; + @Getter + private final String refreshToken; + @Getter + private final String tokenType; + + @JsonCreator + private Token( + @JsonProperty("access_token") final String accessToken, + @JsonProperty("expires_in") final Long expiresIn, + @JsonProperty("id_token") final String idToken, + @JsonProperty("refresh_token") final String refreshToken, + @JsonProperty("token_type") final String tokenType + ) { + this.accessToken = accessToken; + this.expiresIn = expiresIn; + this.idToken = idToken; + this.refreshToken = refreshToken; + this.tokenType = tokenType; + } + + @Override + public boolean equals(final Object o) { + if (this == o) { + return true; + } + + if (o == null || getClass() != o.getClass()) { + return false; + } + + Token other = (Token) o; + return ( + Objects.equals(accessToken, other.accessToken) && + Objects.equals(expiresIn, other.expiresIn) && + Objects.equals(idToken, other.idToken) && + Objects.equals(refreshToken, other.refreshToken) && + Objects.equals(tokenType, other.tokenType) + ); + } + + @Override + public int hashCode() { + return Objects.hash( + accessToken, + expiresIn, + idToken, + refreshToken, + tokenType + ); + } + + +} + diff --git a/src/main/java/com/twilio/rest/oauth/v2/TokenCreator.java b/src/main/java/com/twilio/rest/oauth/v2/TokenCreator.java new file mode 100644 index 0000000000..8fabebaa74 --- /dev/null +++ b/src/main/java/com/twilio/rest/oauth/v2/TokenCreator.java @@ -0,0 +1,173 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * User OAuth API + * User OAuth API + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package com.twilio.rest.oauth.v2; + + +import com.twilio.auth_strategy.NoAuthStrategy; +import com.twilio.base.Creator; +import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; +import com.twilio.exception.ApiConnectionException; +import com.twilio.exception.ApiException; +import com.twilio.exception.RestException; +import com.twilio.http.HttpMethod; +import com.twilio.http.Request; +import com.twilio.http.Response; +import com.twilio.http.TwilioRestClient; +import com.twilio.rest.Domains; + +public class TokenCreator extends Creator { + + private String grantType; + private String clientId; + private String clientSecret; + private String code; + private String redirectUri; + private String audience; + private String refreshToken; + private String scope; + + public TokenCreator(final String grantType, final String clientId) { + this.grantType = grantType; + this.clientId = clientId; + } + + + public TokenCreator setGrantType(final String grantType) { + this.grantType = grantType; + return this; + } + + + public TokenCreator setClientId(final String clientId) { + this.clientId = clientId; + return this; + } + + + public TokenCreator setClientSecret(final String clientSecret) { + this.clientSecret = clientSecret; + return this; + } + + + public TokenCreator setCode(final String code) { + this.code = code; + return this; + } + + + public TokenCreator setRedirectUri(final String redirectUri) { + this.redirectUri = redirectUri; + return this; + } + + + public TokenCreator setAudience(final String audience) { + this.audience = audience; + return this; + } + + + public TokenCreator setRefreshToken(final String refreshToken) { + this.refreshToken = refreshToken; + return this; + } + + + public TokenCreator setScope(final String scope) { + this.scope = scope; + return this; + } + + + @Override + public Token create(final TwilioRestClient client) { + + String path = "/v2/token"; + + + Request request = new Request( + HttpMethod.POST, + Domains.OAUTH.toString(), + path + ); + request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + request.setAuth(NoAuthStrategy.getInstance()); + addPostParams(request); + + Response response = client.request(request); + + if (response == null) { + throw new ApiConnectionException("Token creation failed: Unable to connect to server"); + } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { + RestException restException = RestException.fromJson( + response.getStream(), + client.getObjectMapper() + ); + if (restException == null) { + throw new ApiException("Server Error, no content", response.getStatusCode()); + } + throw new ApiException(restException); + } + + return Token.fromJson(response.getStream(), client.getObjectMapper()); + } + + private void addPostParams(final Request request) { + + if (grantType != null) { + Serializer.toString(request, "grant_type", grantType, ParameterType.URLENCODED); + } + + + if (clientId != null) { + Serializer.toString(request, "client_id", clientId, ParameterType.URLENCODED); + } + + + if (clientSecret != null) { + Serializer.toString(request, "client_secret", clientSecret, ParameterType.URLENCODED); + } + + + if (code != null) { + Serializer.toString(request, "code", code, ParameterType.URLENCODED); + } + + + if (redirectUri != null) { + Serializer.toString(request, "redirect_uri", redirectUri, ParameterType.URLENCODED); + } + + + if (audience != null) { + Serializer.toString(request, "audience", audience, ParameterType.URLENCODED); + } + + + if (refreshToken != null) { + Serializer.toString(request, "refresh_token", refreshToken, ParameterType.URLENCODED); + } + + + if (scope != null) { + Serializer.toString(request, "scope", scope, ParameterType.URLENCODED); + } + + + } +} diff --git a/src/main/java/com/twilio/rest/preview/hostedNumbers/AuthorizationDocument.java b/src/main/java/com/twilio/rest/preview/hostedNumbers/AuthorizationDocument.java index 9bb552cfaf..55ebf734a7 100644 --- a/src/main/java/com/twilio/rest/preview/hostedNumbers/AuthorizationDocument.java +++ b/src/main/java/com/twilio/rest/preview/hostedNumbers/AuthorizationDocument.java @@ -18,69 +18,90 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.List; import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class AuthorizationDocument extends Resource { - private static final long serialVersionUID = 7314983531290L; - public static AuthorizationDocumentCreator creator( - final List hostedNumberOrderSids, - final String addressSid, - final String email, - final String contactTitle, - final String contactPhoneNumber - ) { + public static AuthorizationDocumentCreator creator(final List hostedNumberOrderSids, final String addressSid, final String email, final String contactTitle, final String contactPhoneNumber) { return new AuthorizationDocumentCreator( - hostedNumberOrderSids, - addressSid, - email, - contactTitle, - contactPhoneNumber + hostedNumberOrderSids, addressSid, email, contactTitle, contactPhoneNumber ); } - public static AuthorizationDocumentFetcher fetcher(final String pathSid) { - return new AuthorizationDocumentFetcher(pathSid); + + public static AuthorizationDocumentFetcher fetcher(final String pathsid) { + return new AuthorizationDocumentFetcher( + pathsid + ); } + public static AuthorizationDocumentReader reader() { - return new AuthorizationDocumentReader(); + return new AuthorizationDocumentReader( + + ); } - public static AuthorizationDocumentUpdater updater(final String pathSid) { - return new AuthorizationDocumentUpdater(pathSid); + + public static AuthorizationDocumentUpdater updater(final String pathsid) { + return new AuthorizationDocumentUpdater( + pathsid + ); } + + public enum Status { + OPENED("opened"), + SIGNING("signing"), + SIGNED("signed"), + CANCELED("canceled"), + FAILED("failed"); + + private final String value; + + private Status(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static Status forValue(final String value) { + return Promoter.enumFromString(value, Status.values()); + } + } + + /** * Converts a JSON String into a AuthorizationDocument object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return AuthorizationDocument object represented by the provided JSON */ - public static AuthorizationDocument fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static AuthorizationDocument fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, AuthorizationDocument.class); @@ -95,14 +116,11 @@ public static AuthorizationDocument fromJson( * Converts a JSON InputStream into a AuthorizationDocument object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return AuthorizationDocument object represented by the provided JSON */ - public static AuthorizationDocument fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static AuthorizationDocument fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, AuthorizationDocument.class); @@ -113,73 +131,61 @@ public static AuthorizationDocument fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String addressSid; - private final AuthorizationDocument.Status status; - private final String email; + @Getter private final List ccEmails; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; - private final URI url; + @Getter + private final String email; + @Getter private final Map links; + @Getter + private final String sid; + @Getter + private final AuthorizationDocument.Status status; + @Getter + private final URI url; @JsonCreator private AuthorizationDocument( - @JsonProperty("sid") final String sid, - @JsonProperty("address_sid") final String addressSid, - @JsonProperty("status") final AuthorizationDocument.Status status, - @JsonProperty("email") final String email, - @JsonProperty("cc_emails") final List ccEmails, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("url") final URI url, - @JsonProperty("links") final Map links + @JsonProperty("address_sid") final String addressSid, + @JsonProperty("cc_emails") final List ccEmails, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("email") final String email, + @JsonProperty("links") final Map links, + @JsonProperty("sid") final String sid, + @JsonProperty("status") final AuthorizationDocument.Status status, + @JsonProperty("url") final URI url ) { - this.sid = sid; this.addressSid = addressSid; - this.status = status; - this.email = email; this.ccEmails = ccEmails; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); - this.url = url; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; + this.email = email; this.links = links; - } - - public final String getSid() { - return this.sid; - } - - public final String getAddressSid() { - return this.addressSid; - } - - public final AuthorizationDocument.Status getStatus() { - return this.status; - } - - public final String getEmail() { - return this.email; - } - - public final List getCcEmails() { - return this.ccEmails; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final URI getUrl() { - return this.url; - } - - public final Map getLinks() { - return this.links; + this.sid = sid; + this.status = status; + this.url = url; } @Override @@ -193,55 +199,34 @@ public boolean equals(final Object o) { } AuthorizationDocument other = (AuthorizationDocument) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(addressSid, other.addressSid) && - Objects.equals(status, other.status) && - Objects.equals(email, other.email) && - Objects.equals(ccEmails, other.ccEmails) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(url, other.url) && - Objects.equals(links, other.links) + Objects.equals(addressSid, other.addressSid) && + Objects.equals(ccEmails, other.ccEmails) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(email, other.email) && + Objects.equals(links, other.links) && + Objects.equals(sid, other.sid) && + Objects.equals(status, other.status) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - sid, - addressSid, - status, - email, - ccEmails, - dateCreated, - dateUpdated, - url, - links + addressSid, + ccEmails, + dateCreated, + dateUpdated, + email, + links, + sid, + status, + url ); } - public enum Status { - OPENED("opened"), - SIGNING("signing"), - SIGNED("signed"), - CANCELED("canceled"), - FAILED("failed"); - - private final String value; - - private Status(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - @JsonCreator - public static Status forValue(final String value) { - return Promoter.enumFromString(value, Status.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/preview/hostedNumbers/AuthorizationDocumentCreator.java b/src/main/java/com/twilio/rest/preview/hostedNumbers/AuthorizationDocumentCreator.java index f4e3807170..b1c959d796 100644 --- a/src/main/java/com/twilio/rest/preview/hostedNumbers/AuthorizationDocumentCreator.java +++ b/src/main/java/com/twilio/rest/preview/hostedNumbers/AuthorizationDocumentCreator.java @@ -14,9 +14,12 @@ package com.twilio.rest.preview.hostedNumbers; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; import com.twilio.converter.Promoter; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,11 +28,10 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -import java.util.List; + import java.util.List; -public class AuthorizationDocumentCreator - extends Creator { +public class AuthorizationDocumentCreator extends Creator { private List hostedNumberOrderSids; private String addressSid; @@ -38,13 +40,7 @@ public class AuthorizationDocumentCreator private String contactPhoneNumber; private List ccEmails; - public AuthorizationDocumentCreator( - final List hostedNumberOrderSids, - final String addressSid, - final String email, - final String contactTitle, - final String contactPhoneNumber - ) { + public AuthorizationDocumentCreator(final List hostedNumberOrderSids, final String addressSid, final String email, final String contactTitle, final String contactPhoneNumber) { this.hostedNumberOrderSids = hostedNumberOrderSids; this.addressSid = addressSid; this.email = email; @@ -52,19 +48,14 @@ public AuthorizationDocumentCreator( this.contactPhoneNumber = contactPhoneNumber; } - public AuthorizationDocumentCreator setHostedNumberOrderSids( - final List hostedNumberOrderSids - ) { + + public AuthorizationDocumentCreator setHostedNumberOrderSids(final List hostedNumberOrderSids) { this.hostedNumberOrderSids = hostedNumberOrderSids; return this; } - public AuthorizationDocumentCreator setHostedNumberOrderSids( - final String hostedNumberOrderSids - ) { - return setHostedNumberOrderSids( - Promoter.listOfOne(hostedNumberOrderSids) - ); + public AuthorizationDocumentCreator setHostedNumberOrderSids(final String hostedNumberOrderSids) { + return setHostedNumberOrderSids(Promoter.listOfOne(hostedNumberOrderSids)); } public AuthorizationDocumentCreator setAddressSid(final String addressSid) { @@ -72,28 +63,26 @@ public AuthorizationDocumentCreator setAddressSid(final String addressSid) { return this; } + public AuthorizationDocumentCreator setEmail(final String email) { this.email = email; return this; } - public AuthorizationDocumentCreator setContactTitle( - final String contactTitle - ) { + + public AuthorizationDocumentCreator setContactTitle(final String contactTitle) { this.contactTitle = contactTitle; return this; } - public AuthorizationDocumentCreator setContactPhoneNumber( - final String contactPhoneNumber - ) { + + public AuthorizationDocumentCreator setContactPhoneNumber(final String contactPhoneNumber) { this.contactPhoneNumber = contactPhoneNumber; return this; } - public AuthorizationDocumentCreator setCcEmails( - final List ccEmails - ) { + + public AuthorizationDocumentCreator setCcEmails(final List ccEmails) { this.ccEmails = ccEmails; return this; } @@ -104,81 +93,71 @@ public AuthorizationDocumentCreator setCcEmails(final String ccEmails) { @Override public AuthorizationDocument create(final TwilioRestClient client) { + String path = "/HostedNumbers/AuthorizationDocuments"; - path = - path.replace( - "{" + "HostedNumberOrderSids" + "}", - this.hostedNumberOrderSids.toString() - ); - path = - path.replace("{" + "AddressSid" + "}", this.addressSid.toString()); - path = path.replace("{" + "Email" + "}", this.email.toString()); - path = - path.replace( - "{" + "ContactTitle" + "}", - this.contactTitle.toString() - ); - path = - path.replace( - "{" + "ContactPhoneNumber" + "}", - this.contactPhoneNumber.toString() - ); Request request = new Request( - HttpMethod.POST, - Domains.PREVIEW.toString(), - path + HttpMethod.POST, + Domains.PREVIEW.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "AuthorizationDocument creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("AuthorizationDocument creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return AuthorizationDocument.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return AuthorizationDocument.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + + if (hostedNumberOrderSids != null) { - for (String prop : hostedNumberOrderSids) { - request.addPostParam("HostedNumberOrderSids", prop); + for (String param : hostedNumberOrderSids) { + Serializer.toString(request, "HostedNumberOrderSids", param, ParameterType.URLENCODED); } } + + if (addressSid != null) { - request.addPostParam("AddressSid", addressSid); + Serializer.toString(request, "AddressSid", addressSid, ParameterType.URLENCODED); } + + if (email != null) { - request.addPostParam("Email", email); + Serializer.toString(request, "Email", email, ParameterType.URLENCODED); } + + if (contactTitle != null) { - request.addPostParam("ContactTitle", contactTitle); + Serializer.toString(request, "ContactTitle", contactTitle, ParameterType.URLENCODED); } + + if (contactPhoneNumber != null) { - request.addPostParam("ContactPhoneNumber", contactPhoneNumber); + Serializer.toString(request, "ContactPhoneNumber", contactPhoneNumber, ParameterType.URLENCODED); } + + if (ccEmails != null) { - for (String prop : ccEmails) { - request.addPostParam("CcEmails", prop); + for (String param : ccEmails) { + Serializer.toString(request, "CcEmails", param, ParameterType.URLENCODED); } } + } } diff --git a/src/main/java/com/twilio/rest/preview/hostedNumbers/AuthorizationDocumentFetcher.java b/src/main/java/com/twilio/rest/preview/hostedNumbers/AuthorizationDocumentFetcher.java index 380a84664f..2e5df5e7f1 100644 --- a/src/main/java/com/twilio/rest/preview/hostedNumbers/AuthorizationDocumentFetcher.java +++ b/src/main/java/com/twilio/rest/preview/hostedNumbers/AuthorizationDocumentFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.preview.hostedNumbers; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,50 +24,43 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class AuthorizationDocumentFetcher - extends Fetcher { +public class AuthorizationDocumentFetcher extends Fetcher { - private String pathSid; + private String pathsid; - public AuthorizationDocumentFetcher(final String pathSid) { - this.pathSid = pathSid; + public AuthorizationDocumentFetcher(final String pathsid) { + this.pathsid = pathsid; } + @Override public AuthorizationDocument fetch(final TwilioRestClient client) { + String path = "/HostedNumbers/AuthorizationDocuments/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.PREVIEW.toString(), - path + HttpMethod.GET, + Domains.PREVIEW.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "AuthorizationDocument fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("AuthorizationDocument fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return AuthorizationDocument.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return AuthorizationDocument.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/preview/hostedNumbers/AuthorizationDocumentReader.java b/src/main/java/com/twilio/rest/preview/hostedNumbers/AuthorizationDocumentReader.java index 5935b34fb5..922a13b596 100644 --- a/src/main/java/com/twilio/rest/preview/hostedNumbers/AuthorizationDocumentReader.java +++ b/src/main/java/com/twilio/rest/preview/hostedNumbers/AuthorizationDocumentReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -33,127 +34,105 @@ public class AuthorizationDocumentReader extends Reader { private AuthorizationDocument.Status status; private Long pageSize; - public AuthorizationDocumentReader() {} + public AuthorizationDocumentReader() { + } + public AuthorizationDocumentReader setEmail(final String email) { this.email = email; return this; } - public AuthorizationDocumentReader setStatus( - final AuthorizationDocument.Status status - ) { + + public AuthorizationDocumentReader setStatus(final AuthorizationDocument.Status status) { this.status = status; return this; } + public AuthorizationDocumentReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override - public ResourceSet read( - final TwilioRestClient client - ) { + public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } - public Page firstPage( - final TwilioRestClient client - ) { + public Page firstPage(final TwilioRestClient client) { + String path = "/HostedNumbers/AuthorizationDocuments"; + Request request = new Request( - HttpMethod.GET, - Domains.PREVIEW.toString(), - path + HttpMethod.GET, + Domains.PREVIEW.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "AuthorizationDocument read failed: Unable to connect to server" - ); + throw new ApiConnectionException("AuthorizationDocument read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "items", - response.getContent(), - AuthorizationDocument.class, - client.getObjectMapper() - ); + "items", + response.getContent(), + AuthorizationDocument.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.PREVIEW.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.PREVIEW.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (email != null) { - request.addQueryParam("Email", email); + Serializer.toString(request, "Email", email, ParameterType.QUERY); } + + if (status != null) { - request.addQueryParam("Status", status.toString()); + Serializer.toString(request, "Status", status, ParameterType.QUERY); } + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/preview/hostedNumbers/AuthorizationDocumentUpdater.java b/src/main/java/com/twilio/rest/preview/hostedNumbers/AuthorizationDocumentUpdater.java index 5b18c2093a..20691dabde 100644 --- a/src/main/java/com/twilio/rest/preview/hostedNumbers/AuthorizationDocumentUpdater.java +++ b/src/main/java/com/twilio/rest/preview/hostedNumbers/AuthorizationDocumentUpdater.java @@ -16,7 +16,9 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; import com.twilio.converter.Promoter; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,12 +27,11 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -import java.util.List; -public class AuthorizationDocumentUpdater - extends Updater { +import java.util.List; - private String pathSid; +public class AuthorizationDocumentUpdater extends Updater { + private String pathsid; private List hostedNumberOrderSids; private String addressSid; private String email; @@ -39,23 +40,18 @@ public class AuthorizationDocumentUpdater private String contactTitle; private String contactPhoneNumber; - public AuthorizationDocumentUpdater(final String pathSid) { - this.pathSid = pathSid; + public AuthorizationDocumentUpdater(final String pathsid) { + this.pathsid = pathsid; } - public AuthorizationDocumentUpdater setHostedNumberOrderSids( - final List hostedNumberOrderSids - ) { + + public AuthorizationDocumentUpdater setHostedNumberOrderSids(final List hostedNumberOrderSids) { this.hostedNumberOrderSids = hostedNumberOrderSids; return this; } - public AuthorizationDocumentUpdater setHostedNumberOrderSids( - final String hostedNumberOrderSids - ) { - return setHostedNumberOrderSids( - Promoter.listOfOne(hostedNumberOrderSids) - ); + public AuthorizationDocumentUpdater setHostedNumberOrderSids(final String hostedNumberOrderSids) { + return setHostedNumberOrderSids(Promoter.listOfOne(hostedNumberOrderSids)); } public AuthorizationDocumentUpdater setAddressSid(final String addressSid) { @@ -63,14 +59,14 @@ public AuthorizationDocumentUpdater setAddressSid(final String addressSid) { return this; } + public AuthorizationDocumentUpdater setEmail(final String email) { this.email = email; return this; } - public AuthorizationDocumentUpdater setCcEmails( - final List ccEmails - ) { + + public AuthorizationDocumentUpdater setCcEmails(final List ccEmails) { this.ccEmails = ccEmails; return this; } @@ -79,90 +75,99 @@ public AuthorizationDocumentUpdater setCcEmails(final String ccEmails) { return setCcEmails(Promoter.listOfOne(ccEmails)); } - public AuthorizationDocumentUpdater setStatus( - final AuthorizationDocument.Status status - ) { + public AuthorizationDocumentUpdater setStatus(final AuthorizationDocument.Status status) { this.status = status; return this; } - public AuthorizationDocumentUpdater setContactTitle( - final String contactTitle - ) { + + public AuthorizationDocumentUpdater setContactTitle(final String contactTitle) { this.contactTitle = contactTitle; return this; } - public AuthorizationDocumentUpdater setContactPhoneNumber( - final String contactPhoneNumber - ) { + + public AuthorizationDocumentUpdater setContactPhoneNumber(final String contactPhoneNumber) { this.contactPhoneNumber = contactPhoneNumber; return this; } + @Override public AuthorizationDocument update(final TwilioRestClient client) { + String path = "/HostedNumbers/AuthorizationDocuments/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.PREVIEW.toString(), - path + HttpMethod.POST, + Domains.PREVIEW.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "AuthorizationDocument update failed: Unable to connect to server" - ); + throw new ApiConnectionException("AuthorizationDocument update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return AuthorizationDocument.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return AuthorizationDocument.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + + if (hostedNumberOrderSids != null) { - for (String prop : hostedNumberOrderSids) { - request.addPostParam("HostedNumberOrderSids", prop); + for (String param : hostedNumberOrderSids) { + Serializer.toString(request, "HostedNumberOrderSids", param, ParameterType.URLENCODED); } } + + if (addressSid != null) { - request.addPostParam("AddressSid", addressSid); + Serializer.toString(request, "AddressSid", addressSid, ParameterType.URLENCODED); } + + if (email != null) { - request.addPostParam("Email", email); + Serializer.toString(request, "Email", email, ParameterType.URLENCODED); } + + if (ccEmails != null) { - for (String prop : ccEmails) { - request.addPostParam("CcEmails", prop); + for (String param : ccEmails) { + Serializer.toString(request, "CcEmails", param, ParameterType.URLENCODED); } } + + if (status != null) { - request.addPostParam("Status", status.toString()); + Serializer.toString(request, "Status", status, ParameterType.URLENCODED); } + + if (contactTitle != null) { - request.addPostParam("ContactTitle", contactTitle); + Serializer.toString(request, "ContactTitle", contactTitle, ParameterType.URLENCODED); } + + if (contactPhoneNumber != null) { - request.addPostParam("ContactPhoneNumber", contactPhoneNumber); + Serializer.toString(request, "ContactPhoneNumber", contactPhoneNumber, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/preview/hostedNumbers/HostedNumberOrder.java b/src/main/java/com/twilio/rest/preview/hostedNumbers/HostedNumberOrder.java index 1accd8a6ea..93054e2c95 100644 --- a/src/main/java/com/twilio/rest/preview/hostedNumbers/HostedNumberOrder.java +++ b/src/main/java/com/twilio/rest/preview/hostedNumbers/HostedNumberOrder.java @@ -18,63 +18,121 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.type.PhoneNumberCapabilities; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.List; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class HostedNumberOrder extends Resource { - private static final long serialVersionUID = 7609372871434L; - public static HostedNumberOrderCreator creator( - final com.twilio.type.PhoneNumber phoneNumber, - final Boolean smsCapability - ) { - return new HostedNumberOrderCreator(phoneNumber, smsCapability); + public static HostedNumberOrderCreator creator(final com.twilio.type.PhoneNumber phoneNumber, final Boolean smsCapability) { + return new HostedNumberOrderCreator( + phoneNumber, smsCapability + ); } - public static HostedNumberOrderDeleter deleter(final String pathSid) { - return new HostedNumberOrderDeleter(pathSid); + + public static HostedNumberOrderDeleter deleter(final String pathsid) { + return new HostedNumberOrderDeleter( + pathsid + ); } - public static HostedNumberOrderFetcher fetcher(final String pathSid) { - return new HostedNumberOrderFetcher(pathSid); + + public static HostedNumberOrderFetcher fetcher(final String pathsid) { + return new HostedNumberOrderFetcher( + pathsid + ); } + public static HostedNumberOrderReader reader() { - return new HostedNumberOrderReader(); + return new HostedNumberOrderReader( + + ); } - public static HostedNumberOrderUpdater updater(final String pathSid) { - return new HostedNumberOrderUpdater(pathSid); + + public static HostedNumberOrderUpdater updater(final String pathsid) { + return new HostedNumberOrderUpdater( + pathsid + ); + } + + + public enum Status { + RECEIVED("received"), + PENDING_VERIFICATION("pending-verification"), + VERIFIED("verified"), + PENDING_LOA("pending-loa"), + CARRIER_PROCESSING("carrier-processing"), + TESTING("testing"), + COMPLETED("completed"), + FAILED("failed"), + ACTION_REQUIRED("action-required"); + + private final String value; + + private Status(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static Status forValue(final String value) { + return Promoter.enumFromString(value, Status.values()); + } } + public enum VerificationType { + PHONE_CALL("phone-call"), + PHONE_BILL("phone-bill"); + + private final String value; + + private VerificationType(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static VerificationType forValue(final String value) { + return Promoter.enumFromString(value, VerificationType.values()); + } + } + + /** * Converts a JSON String into a HostedNumberOrder object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return HostedNumberOrder object represented by the provided JSON */ - public static HostedNumberOrder fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static HostedNumberOrder fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, HostedNumberOrder.class); @@ -89,14 +147,11 @@ public static HostedNumberOrder fromJson( * Converts a JSON InputStream into a HostedNumberOrder object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return HostedNumberOrder object represented by the provided JSON */ - public static HostedNumberOrder fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static HostedNumberOrder fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, HostedNumberOrder.class); @@ -107,185 +162,117 @@ public static HostedNumberOrder fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String incomingPhoneNumberSid; + @Getter private final String addressSid; - private final String signingDocumentSid; - private final com.twilio.type.PhoneNumber phoneNumber; + @Getter + private final Integer callDelay; + @Getter private final PhoneNumberCapabilities capabilities; - private final String friendlyName; - private final String uniqueName; - private final HostedNumberOrder.Status status; - private final String failureReason; + @Getter + private final List ccEmails; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; - private final Integer verificationAttempts; + @Getter private final String email; - private final List ccEmails; - private final URI url; - private final HostedNumberOrder.VerificationType verificationType; - private final String verificationDocumentSid; + @Getter private final String extension; - private final Integer callDelay; - private final String verificationCode; + @Getter + private final String failureReason; + @Getter + private final String friendlyName; + @Getter + private final String incomingPhoneNumberSid; + @Getter + private final com.twilio.type.PhoneNumber phoneNumber; + @Getter + private final String sid; + @Getter + private final String signingDocumentSid; + @Getter + private final HostedNumberOrder.Status status; + @Getter + private final String uniqueName; + @Getter + private final URI url; + @Getter + private final Integer verificationAttempts; + @Getter private final List verificationCallSids; + @Getter + private final String verificationCode; + @Getter + private final String verificationDocumentSid; + @Getter + private final HostedNumberOrder.VerificationType verificationType; @JsonCreator private HostedNumberOrder( - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty( - "incoming_phone_number_sid" - ) final String incomingPhoneNumberSid, - @JsonProperty("address_sid") final String addressSid, - @JsonProperty("signing_document_sid") final String signingDocumentSid, - @JsonProperty( - "phone_number" - ) final com.twilio.type.PhoneNumber phoneNumber, - @JsonProperty( - "capabilities" - ) final PhoneNumberCapabilities capabilities, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("unique_name") final String uniqueName, - @JsonProperty("status") final HostedNumberOrder.Status status, - @JsonProperty("failure_reason") final String failureReason, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty( - "verification_attempts" - ) final Integer verificationAttempts, - @JsonProperty("email") final String email, - @JsonProperty("cc_emails") final List ccEmails, - @JsonProperty("url") final URI url, - @JsonProperty( - "verification_type" - ) final HostedNumberOrder.VerificationType verificationType, - @JsonProperty( - "verification_document_sid" - ) final String verificationDocumentSid, - @JsonProperty("extension") final String extension, - @JsonProperty("call_delay") final Integer callDelay, - @JsonProperty("verification_code") final String verificationCode, - @JsonProperty("verification_call_sids") final List< - String - > verificationCallSids + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("address_sid") final String addressSid, + @JsonProperty("call_delay") final Integer callDelay, + @JsonProperty("capabilities") final PhoneNumberCapabilities capabilities, + @JsonProperty("cc_emails") final List ccEmails, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("email") final String email, + @JsonProperty("extension") final String extension, + @JsonProperty("failure_reason") final String failureReason, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("incoming_phone_number_sid") final String incomingPhoneNumberSid, + @JsonProperty("phone_number") final com.twilio.type.PhoneNumber phoneNumber, + @JsonProperty("sid") final String sid, + @JsonProperty("signing_document_sid") final String signingDocumentSid, + @JsonProperty("status") final HostedNumberOrder.Status status, + @JsonProperty("unique_name") final String uniqueName, + @JsonProperty("url") final URI url, + @JsonProperty("verification_attempts") final Integer verificationAttempts, + @JsonProperty("verification_call_sids") final List verificationCallSids, + @JsonProperty("verification_code") final String verificationCode, + @JsonProperty("verification_document_sid") final String verificationDocumentSid, + @JsonProperty("verification_type") final HostedNumberOrder.VerificationType verificationType ) { - this.sid = sid; this.accountSid = accountSid; - this.incomingPhoneNumberSid = incomingPhoneNumberSid; this.addressSid = addressSid; - this.signingDocumentSid = signingDocumentSid; - this.phoneNumber = phoneNumber; + this.callDelay = callDelay; this.capabilities = capabilities; + this.ccEmails = ccEmails; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; + this.email = email; + this.extension = extension; + this.failureReason = failureReason; this.friendlyName = friendlyName; - this.uniqueName = uniqueName; + this.incomingPhoneNumberSid = incomingPhoneNumberSid; + this.phoneNumber = phoneNumber; + this.sid = sid; + this.signingDocumentSid = signingDocumentSid; this.status = status; - this.failureReason = failureReason; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); - this.verificationAttempts = verificationAttempts; - this.email = email; - this.ccEmails = ccEmails; + this.uniqueName = uniqueName; this.url = url; - this.verificationType = verificationType; - this.verificationDocumentSid = verificationDocumentSid; - this.extension = extension; - this.callDelay = callDelay; - this.verificationCode = verificationCode; + this.verificationAttempts = verificationAttempts; this.verificationCallSids = verificationCallSids; - } - - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getIncomingPhoneNumberSid() { - return this.incomingPhoneNumberSid; - } - - public final String getAddressSid() { - return this.addressSid; - } - - public final String getSigningDocumentSid() { - return this.signingDocumentSid; - } - - public final com.twilio.type.PhoneNumber getPhoneNumber() { - return this.phoneNumber; - } - - public final PhoneNumberCapabilities getCapabilities() { - return this.capabilities; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final String getUniqueName() { - return this.uniqueName; - } - - public final HostedNumberOrder.Status getStatus() { - return this.status; - } - - public final String getFailureReason() { - return this.failureReason; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final Integer getVerificationAttempts() { - return this.verificationAttempts; - } - - public final String getEmail() { - return this.email; - } - - public final List getCcEmails() { - return this.ccEmails; - } - - public final URI getUrl() { - return this.url; - } - - public final HostedNumberOrder.VerificationType getVerificationType() { - return this.verificationType; - } - - public final String getVerificationDocumentSid() { - return this.verificationDocumentSid; - } - - public final String getExtension() { - return this.extension; - } - - public final Integer getCallDelay() { - return this.callDelay; - } - - public final String getVerificationCode() { - return this.verificationCode; - } - - public final List getVerificationCallSids() { - return this.verificationCallSids; + this.verificationCode = verificationCode; + this.verificationDocumentSid = verificationDocumentSid; + this.verificationType = verificationType; } @Override @@ -299,113 +286,62 @@ public boolean equals(final Object o) { } HostedNumberOrder other = (HostedNumberOrder) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals( - incomingPhoneNumberSid, - other.incomingPhoneNumberSid - ) && - Objects.equals(addressSid, other.addressSid) && - Objects.equals(signingDocumentSid, other.signingDocumentSid) && - Objects.equals(phoneNumber, other.phoneNumber) && - Objects.equals(capabilities, other.capabilities) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(uniqueName, other.uniqueName) && - Objects.equals(status, other.status) && - Objects.equals(failureReason, other.failureReason) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(verificationAttempts, other.verificationAttempts) && - Objects.equals(email, other.email) && - Objects.equals(ccEmails, other.ccEmails) && - Objects.equals(url, other.url) && - Objects.equals(verificationType, other.verificationType) && - Objects.equals( - verificationDocumentSid, - other.verificationDocumentSid - ) && - Objects.equals(extension, other.extension) && - Objects.equals(callDelay, other.callDelay) && - Objects.equals(verificationCode, other.verificationCode) && - Objects.equals(verificationCallSids, other.verificationCallSids) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(addressSid, other.addressSid) && + Objects.equals(callDelay, other.callDelay) && + Objects.equals(capabilities, other.capabilities) && + Objects.equals(ccEmails, other.ccEmails) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(email, other.email) && + Objects.equals(extension, other.extension) && + Objects.equals(failureReason, other.failureReason) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(incomingPhoneNumberSid, other.incomingPhoneNumberSid) && + Objects.equals(phoneNumber, other.phoneNumber) && + Objects.equals(sid, other.sid) && + Objects.equals(signingDocumentSid, other.signingDocumentSid) && + Objects.equals(status, other.status) && + Objects.equals(uniqueName, other.uniqueName) && + Objects.equals(url, other.url) && + Objects.equals(verificationAttempts, other.verificationAttempts) && + Objects.equals(verificationCallSids, other.verificationCallSids) && + Objects.equals(verificationCode, other.verificationCode) && + Objects.equals(verificationDocumentSid, other.verificationDocumentSid) && + Objects.equals(verificationType, other.verificationType) ); } @Override public int hashCode() { return Objects.hash( - sid, - accountSid, - incomingPhoneNumberSid, - addressSid, - signingDocumentSid, - phoneNumber, - capabilities, - friendlyName, - uniqueName, - status, - failureReason, - dateCreated, - dateUpdated, - verificationAttempts, - email, - ccEmails, - url, - verificationType, - verificationDocumentSid, - extension, - callDelay, - verificationCode, - verificationCallSids + accountSid, + addressSid, + callDelay, + capabilities, + ccEmails, + dateCreated, + dateUpdated, + email, + extension, + failureReason, + friendlyName, + incomingPhoneNumberSid, + phoneNumber, + sid, + signingDocumentSid, + status, + uniqueName, + url, + verificationAttempts, + verificationCallSids, + verificationCode, + verificationDocumentSid, + verificationType ); } - public enum Status { - RECEIVED("received"), - PENDING_VERIFICATION("pending-verification"), - VERIFIED("verified"), - PENDING_LOA("pending-loa"), - CARRIER_PROCESSING("carrier-processing"), - TESTING("testing"), - COMPLETED("completed"), - FAILED("failed"), - ACTION_REQUIRED("action-required"); - - private final String value; - private Status(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static Status forValue(final String value) { - return Promoter.enumFromString(value, Status.values()); - } - } - - public enum VerificationType { - PHONE_CALL("phone-call"), - PHONE_BILL("phone-bill"); - - private final String value; - - private VerificationType(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static VerificationType forValue(final String value) { - return Promoter.enumFromString(value, VerificationType.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/preview/hostedNumbers/HostedNumberOrderCreator.java b/src/main/java/com/twilio/rest/preview/hostedNumbers/HostedNumberOrderCreator.java index 927eba9f60..d2cd709b04 100644 --- a/src/main/java/com/twilio/rest/preview/hostedNumbers/HostedNumberOrderCreator.java +++ b/src/main/java/com/twilio/rest/preview/hostedNumbers/HostedNumberOrderCreator.java @@ -14,9 +14,12 @@ package com.twilio.rest.preview.hostedNumbers; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; import com.twilio.converter.Promoter; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,10 +28,9 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -import java.net.URI; + import java.net.URI; import java.util.List; -import java.util.List; public class HostedNumberOrderCreator extends Creator { @@ -50,17 +52,13 @@ public class HostedNumberOrderCreator extends Creator { private HostedNumberOrder.VerificationType verificationType; private String verificationDocumentSid; - public HostedNumberOrderCreator( - final com.twilio.type.PhoneNumber phoneNumber, - final Boolean smsCapability - ) { + public HostedNumberOrderCreator(final com.twilio.type.PhoneNumber phoneNumber, final Boolean smsCapability) { this.phoneNumber = phoneNumber; this.smsCapability = smsCapability; } - public HostedNumberOrderCreator setPhoneNumber( - final com.twilio.type.PhoneNumber phoneNumber - ) { + + public HostedNumberOrderCreator setPhoneNumber(final com.twilio.type.PhoneNumber phoneNumber) { this.phoneNumber = phoneNumber; return this; } @@ -69,28 +67,30 @@ public HostedNumberOrderCreator setPhoneNumber(final String phoneNumber) { return setPhoneNumber(Promoter.phoneNumberFromString(phoneNumber)); } - public HostedNumberOrderCreator setSmsCapability( - final Boolean smsCapability - ) { + public HostedNumberOrderCreator setSmsCapability(final Boolean smsCapability) { this.smsCapability = smsCapability; return this; } + public HostedNumberOrderCreator setAccountSid(final String accountSid) { this.accountSid = accountSid; return this; } + public HostedNumberOrderCreator setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + public HostedNumberOrderCreator setUniqueName(final String uniqueName) { this.uniqueName = uniqueName; return this; } + public HostedNumberOrderCreator setCcEmails(final List ccEmails) { this.ccEmails = ccEmails; return this; @@ -105,201 +105,187 @@ public HostedNumberOrderCreator setSmsUrl(final URI smsUrl) { return this; } - public HostedNumberOrderCreator setSmsUrl(final String smsUrl) { - return setSmsUrl(Promoter.uriFromString(smsUrl)); - } public HostedNumberOrderCreator setSmsMethod(final HttpMethod smsMethod) { this.smsMethod = smsMethod; return this; } - public HostedNumberOrderCreator setSmsFallbackUrl( - final URI smsFallbackUrl - ) { + + public HostedNumberOrderCreator setSmsFallbackUrl(final URI smsFallbackUrl) { this.smsFallbackUrl = smsFallbackUrl; return this; } - public HostedNumberOrderCreator setSmsFallbackUrl( - final String smsFallbackUrl - ) { - return setSmsFallbackUrl(Promoter.uriFromString(smsFallbackUrl)); - } - public HostedNumberOrderCreator setSmsFallbackMethod( - final HttpMethod smsFallbackMethod - ) { + public HostedNumberOrderCreator setSmsFallbackMethod(final HttpMethod smsFallbackMethod) { this.smsFallbackMethod = smsFallbackMethod; return this; } - public HostedNumberOrderCreator setStatusCallbackUrl( - final URI statusCallbackUrl - ) { + + public HostedNumberOrderCreator setStatusCallbackUrl(final URI statusCallbackUrl) { this.statusCallbackUrl = statusCallbackUrl; return this; } - public HostedNumberOrderCreator setStatusCallbackUrl( - final String statusCallbackUrl - ) { - return setStatusCallbackUrl(Promoter.uriFromString(statusCallbackUrl)); - } - public HostedNumberOrderCreator setStatusCallbackMethod( - final HttpMethod statusCallbackMethod - ) { + public HostedNumberOrderCreator setStatusCallbackMethod(final HttpMethod statusCallbackMethod) { this.statusCallbackMethod = statusCallbackMethod; return this; } - public HostedNumberOrderCreator setSmsApplicationSid( - final String smsApplicationSid - ) { + + public HostedNumberOrderCreator setSmsApplicationSid(final String smsApplicationSid) { this.smsApplicationSid = smsApplicationSid; return this; } + public HostedNumberOrderCreator setAddressSid(final String addressSid) { this.addressSid = addressSid; return this; } + public HostedNumberOrderCreator setEmail(final String email) { this.email = email; return this; } - public HostedNumberOrderCreator setVerificationType( - final HostedNumberOrder.VerificationType verificationType - ) { + + public HostedNumberOrderCreator setVerificationType(final HostedNumberOrder.VerificationType verificationType) { this.verificationType = verificationType; return this; } - public HostedNumberOrderCreator setVerificationDocumentSid( - final String verificationDocumentSid - ) { + + public HostedNumberOrderCreator setVerificationDocumentSid(final String verificationDocumentSid) { this.verificationDocumentSid = verificationDocumentSid; return this; } + @Override public HostedNumberOrder create(final TwilioRestClient client) { + String path = "/HostedNumbers/HostedNumberOrders"; - path = - path.replace( - "{" + "PhoneNumber" + "}", - this.phoneNumber.toString() - ); - path = - path.replace( - "{" + "SmsCapability" + "}", - this.smsCapability.toString() - ); Request request = new Request( - HttpMethod.POST, - Domains.PREVIEW.toString(), - path + HttpMethod.POST, + Domains.PREVIEW.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "HostedNumberOrder creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("HostedNumberOrder creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return HostedNumberOrder.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return HostedNumberOrder.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (phoneNumber != null) { - request.addPostParam("PhoneNumber", phoneNumber.toString()); + Serializer.toString(request, "PhoneNumber", phoneNumber, ParameterType.URLENCODED); } + + if (smsCapability != null) { - request.addPostParam("SmsCapability", smsCapability.toString()); + Serializer.toString(request, "SmsCapability", smsCapability, ParameterType.URLENCODED); } + + if (accountSid != null) { - request.addPostParam("AccountSid", accountSid); + Serializer.toString(request, "AccountSid", accountSid, ParameterType.URLENCODED); } + + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + if (uniqueName != null) { - request.addPostParam("UniqueName", uniqueName); + Serializer.toString(request, "UniqueName", uniqueName, ParameterType.URLENCODED); } + + if (ccEmails != null) { - for (String prop : ccEmails) { - request.addPostParam("CcEmails", prop); + for (String param : ccEmails) { + Serializer.toString(request, "CcEmails", param, ParameterType.URLENCODED); } } + + if (smsUrl != null) { - request.addPostParam("SmsUrl", smsUrl.toString()); + Serializer.toString(request, "SmsUrl", smsUrl, ParameterType.URLENCODED); } + + if (smsMethod != null) { - request.addPostParam("SmsMethod", smsMethod.toString()); + Serializer.toString(request, "SmsMethod", smsMethod, ParameterType.URLENCODED); } + + if (smsFallbackUrl != null) { - request.addPostParam("SmsFallbackUrl", smsFallbackUrl.toString()); + Serializer.toString(request, "SmsFallbackUrl", smsFallbackUrl, ParameterType.URLENCODED); } + + if (smsFallbackMethod != null) { - request.addPostParam( - "SmsFallbackMethod", - smsFallbackMethod.toString() - ); + Serializer.toString(request, "SmsFallbackMethod", smsFallbackMethod, ParameterType.URLENCODED); } + + if (statusCallbackUrl != null) { - request.addPostParam( - "StatusCallbackUrl", - statusCallbackUrl.toString() - ); + Serializer.toString(request, "StatusCallbackUrl", statusCallbackUrl, ParameterType.URLENCODED); } + + if (statusCallbackMethod != null) { - request.addPostParam( - "StatusCallbackMethod", - statusCallbackMethod.toString() - ); + Serializer.toString(request, "StatusCallbackMethod", statusCallbackMethod, ParameterType.URLENCODED); } + + if (smsApplicationSid != null) { - request.addPostParam("SmsApplicationSid", smsApplicationSid); + Serializer.toString(request, "SmsApplicationSid", smsApplicationSid, ParameterType.URLENCODED); } + + if (addressSid != null) { - request.addPostParam("AddressSid", addressSid); + Serializer.toString(request, "AddressSid", addressSid, ParameterType.URLENCODED); } + + if (email != null) { - request.addPostParam("Email", email); + Serializer.toString(request, "Email", email, ParameterType.URLENCODED); } + + if (verificationType != null) { - request.addPostParam( - "VerificationType", - verificationType.toString() - ); + Serializer.toString(request, "VerificationType", verificationType, ParameterType.URLENCODED); } + + if (verificationDocumentSid != null) { - request.addPostParam( - "VerificationDocumentSid", - verificationDocumentSid - ); + Serializer.toString(request, "VerificationDocumentSid", verificationDocumentSid, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/preview/hostedNumbers/HostedNumberOrderDeleter.java b/src/main/java/com/twilio/rest/preview/hostedNumbers/HostedNumberOrderDeleter.java index 2213d18cb9..b43d883532 100644 --- a/src/main/java/com/twilio/rest/preview/hostedNumbers/HostedNumberOrderDeleter.java +++ b/src/main/java/com/twilio/rest/preview/hostedNumbers/HostedNumberOrderDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.preview.hostedNumbers; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,40 +26,38 @@ public class HostedNumberOrderDeleter extends Deleter { - private String pathSid; + private String pathsid; - public HostedNumberOrderDeleter(final String pathSid) { - this.pathSid = pathSid; + public HostedNumberOrderDeleter(final String pathsid) { + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/HostedNumbers/HostedNumberOrders/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.PREVIEW.toString(), - path + HttpMethod.DELETE, + Domains.PREVIEW.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "HostedNumberOrder delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("HostedNumberOrder delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/preview/hostedNumbers/HostedNumberOrderFetcher.java b/src/main/java/com/twilio/rest/preview/hostedNumbers/HostedNumberOrderFetcher.java index 5caa2aa477..c7764096dd 100644 --- a/src/main/java/com/twilio/rest/preview/hostedNumbers/HostedNumberOrderFetcher.java +++ b/src/main/java/com/twilio/rest/preview/hostedNumbers/HostedNumberOrderFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.preview.hostedNumbers; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,47 +26,41 @@ public class HostedNumberOrderFetcher extends Fetcher { - private String pathSid; + private String pathsid; - public HostedNumberOrderFetcher(final String pathSid) { - this.pathSid = pathSid; + public HostedNumberOrderFetcher(final String pathsid) { + this.pathsid = pathsid; } + @Override public HostedNumberOrder fetch(final TwilioRestClient client) { + String path = "/HostedNumbers/HostedNumberOrders/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.PREVIEW.toString(), - path + HttpMethod.GET, + Domains.PREVIEW.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "HostedNumberOrder fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("HostedNumberOrder fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return HostedNumberOrder.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return HostedNumberOrder.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/preview/hostedNumbers/HostedNumberOrderReader.java b/src/main/java/com/twilio/rest/preview/hostedNumbers/HostedNumberOrderReader.java index 0b85f94362..4baf28d22f 100644 --- a/src/main/java/com/twilio/rest/preview/hostedNumbers/HostedNumberOrderReader.java +++ b/src/main/java/com/twilio/rest/preview/hostedNumbers/HostedNumberOrderReader.java @@ -17,8 +17,9 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; import com.twilio.converter.Promoter; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -37,18 +38,17 @@ public class HostedNumberOrderReader extends Reader { private String uniqueName; private Long pageSize; - public HostedNumberOrderReader() {} + public HostedNumberOrderReader() { + } + - public HostedNumberOrderReader setStatus( - final HostedNumberOrder.Status status - ) { + public HostedNumberOrderReader setStatus(final HostedNumberOrder.Status status) { this.status = status; return this; } - public HostedNumberOrderReader setPhoneNumber( - final com.twilio.type.PhoneNumber phoneNumber - ) { + + public HostedNumberOrderReader setPhoneNumber(final com.twilio.type.PhoneNumber phoneNumber) { this.phoneNumber = phoneNumber; return this; } @@ -57,138 +57,122 @@ public HostedNumberOrderReader setPhoneNumber(final String phoneNumber) { return setPhoneNumber(Promoter.phoneNumberFromString(phoneNumber)); } - public HostedNumberOrderReader setIncomingPhoneNumberSid( - final String incomingPhoneNumberSid - ) { + public HostedNumberOrderReader setIncomingPhoneNumberSid(final String incomingPhoneNumberSid) { this.incomingPhoneNumberSid = incomingPhoneNumberSid; return this; } + public HostedNumberOrderReader setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + public HostedNumberOrderReader setUniqueName(final String uniqueName) { this.uniqueName = uniqueName; return this; } + public HostedNumberOrderReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/HostedNumbers/HostedNumberOrders"; + Request request = new Request( - HttpMethod.GET, - Domains.PREVIEW.toString(), - path + HttpMethod.GET, + Domains.PREVIEW.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "HostedNumberOrder read failed: Unable to connect to server" - ); + throw new ApiConnectionException("HostedNumberOrder read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "items", - response.getContent(), - HostedNumberOrder.class, - client.getObjectMapper() - ); + "items", + response.getContent(), + HostedNumberOrder.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.PREVIEW.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.PREVIEW.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (status != null) { - request.addQueryParam("Status", status.toString()); + Serializer.toString(request, "Status", status, ParameterType.QUERY); } + + if (phoneNumber != null) { - request.addQueryParam("PhoneNumber", phoneNumber.toString()); + Serializer.toString(request, "PhoneNumber", phoneNumber, ParameterType.QUERY); } + + if (incomingPhoneNumberSid != null) { - request.addQueryParam( - "IncomingPhoneNumberSid", - incomingPhoneNumberSid - ); + Serializer.toString(request, "IncomingPhoneNumberSid", incomingPhoneNumberSid, ParameterType.QUERY); } + + if (friendlyName != null) { - request.addQueryParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.QUERY); } + + if (uniqueName != null) { - request.addQueryParam("UniqueName", uniqueName); + Serializer.toString(request, "UniqueName", uniqueName, ParameterType.QUERY); } + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/preview/hostedNumbers/HostedNumberOrderUpdater.java b/src/main/java/com/twilio/rest/preview/hostedNumbers/HostedNumberOrderUpdater.java index 3c9ca13dfb..d2f63bc792 100644 --- a/src/main/java/com/twilio/rest/preview/hostedNumbers/HostedNumberOrderUpdater.java +++ b/src/main/java/com/twilio/rest/preview/hostedNumbers/HostedNumberOrderUpdater.java @@ -16,7 +16,9 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; import com.twilio.converter.Promoter; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,11 +27,11 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.util.List; public class HostedNumberOrderUpdater extends Updater { - - private String pathSid; + private String pathsid; private String friendlyName; private String uniqueName; private String email; @@ -41,25 +43,29 @@ public class HostedNumberOrderUpdater extends Updater { private String extension; private Integer callDelay; - public HostedNumberOrderUpdater(final String pathSid) { - this.pathSid = pathSid; + public HostedNumberOrderUpdater(final String pathsid) { + this.pathsid = pathsid; } + public HostedNumberOrderUpdater setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + public HostedNumberOrderUpdater setUniqueName(final String uniqueName) { this.uniqueName = uniqueName; return this; } + public HostedNumberOrderUpdater setEmail(final String email) { this.email = email; return this; } + public HostedNumberOrderUpdater setCcEmails(final List ccEmails) { this.ccEmails = ccEmails; return this; @@ -69,120 +75,129 @@ public HostedNumberOrderUpdater setCcEmails(final String ccEmails) { return setCcEmails(Promoter.listOfOne(ccEmails)); } - public HostedNumberOrderUpdater setStatus( - final HostedNumberOrder.Status status - ) { + public HostedNumberOrderUpdater setStatus(final HostedNumberOrder.Status status) { this.status = status; return this; } - public HostedNumberOrderUpdater setVerificationCode( - final String verificationCode - ) { + + public HostedNumberOrderUpdater setVerificationCode(final String verificationCode) { this.verificationCode = verificationCode; return this; } - public HostedNumberOrderUpdater setVerificationType( - final HostedNumberOrder.VerificationType verificationType - ) { + + public HostedNumberOrderUpdater setVerificationType(final HostedNumberOrder.VerificationType verificationType) { this.verificationType = verificationType; return this; } - public HostedNumberOrderUpdater setVerificationDocumentSid( - final String verificationDocumentSid - ) { + + public HostedNumberOrderUpdater setVerificationDocumentSid(final String verificationDocumentSid) { this.verificationDocumentSid = verificationDocumentSid; return this; } + public HostedNumberOrderUpdater setExtension(final String extension) { this.extension = extension; return this; } + public HostedNumberOrderUpdater setCallDelay(final Integer callDelay) { this.callDelay = callDelay; return this; } + @Override public HostedNumberOrder update(final TwilioRestClient client) { + String path = "/HostedNumbers/HostedNumberOrders/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.PREVIEW.toString(), - path + HttpMethod.POST, + Domains.PREVIEW.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "HostedNumberOrder update failed: Unable to connect to server" - ); + throw new ApiConnectionException("HostedNumberOrder update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return HostedNumberOrder.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return HostedNumberOrder.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + if (uniqueName != null) { - request.addPostParam("UniqueName", uniqueName); + Serializer.toString(request, "UniqueName", uniqueName, ParameterType.URLENCODED); } + + if (email != null) { - request.addPostParam("Email", email); + Serializer.toString(request, "Email", email, ParameterType.URLENCODED); } + + if (ccEmails != null) { - for (String prop : ccEmails) { - request.addPostParam("CcEmails", prop); + for (String param : ccEmails) { + Serializer.toString(request, "CcEmails", param, ParameterType.URLENCODED); } } + + if (status != null) { - request.addPostParam("Status", status.toString()); + Serializer.toString(request, "Status", status, ParameterType.URLENCODED); } + + if (verificationCode != null) { - request.addPostParam("VerificationCode", verificationCode); + Serializer.toString(request, "VerificationCode", verificationCode, ParameterType.URLENCODED); } + + if (verificationType != null) { - request.addPostParam( - "VerificationType", - verificationType.toString() - ); + Serializer.toString(request, "VerificationType", verificationType, ParameterType.URLENCODED); } + + if (verificationDocumentSid != null) { - request.addPostParam( - "VerificationDocumentSid", - verificationDocumentSid - ); + Serializer.toString(request, "VerificationDocumentSid", verificationDocumentSid, ParameterType.URLENCODED); } + + if (extension != null) { - request.addPostParam("Extension", extension); + Serializer.toString(request, "Extension", extension, ParameterType.URLENCODED); } + + if (callDelay != null) { - request.addPostParam("CallDelay", callDelay.toString()); + Serializer.toString(request, "CallDelay", callDelay, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/preview/hostedNumbers/authorizationdocument/DependentHostedNumberOrder.java b/src/main/java/com/twilio/rest/preview/hostedNumbers/authorizationdocument/DependentHostedNumberOrder.java index a568b081d8..6718bd547b 100644 --- a/src/main/java/com/twilio/rest/preview/hostedNumbers/authorizationdocument/DependentHostedNumberOrder.java +++ b/src/main/java/com/twilio/rest/preview/hostedNumbers/authorizationdocument/DependentHostedNumberOrder.java @@ -18,51 +18,95 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.type.PhoneNumberCapabilities; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.time.ZonedDateTime; import java.util.List; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class DependentHostedNumberOrder extends Resource { - private static final long serialVersionUID = 65583991731077L; - public static DependentHostedNumberOrderReader reader( - final String pathSigningDocumentSid - ) { - return new DependentHostedNumberOrderReader(pathSigningDocumentSid); + public static DependentHostedNumberOrderReader reader(final String pathsigningDocumentSid) { + return new DependentHostedNumberOrderReader( + pathsigningDocumentSid + ); + } + + + public enum Status { + RECEIVED("received"), + PENDING_VERIFICATION("pending-verification"), + VERIFIED("verified"), + PENDING_LOA("pending-loa"), + CARRIER_PROCESSING("carrier-processing"), + TESTING("testing"), + COMPLETED("completed"), + FAILED("failed"), + ACTION_REQUIRED("action-required"); + + private final String value; + + private Status(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static Status forValue(final String value) { + return Promoter.enumFromString(value, Status.values()); + } + } + + public enum VerificationType { + PHONE_CALL("phone-call"), + PHONE_BILL("phone-bill"); + + private final String value; + + private VerificationType(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static VerificationType forValue(final String value) { + return Promoter.enumFromString(value, VerificationType.values()); + } } + /** * Converts a JSON String into a DependentHostedNumberOrder object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return DependentHostedNumberOrder object represented by the provided JSON */ - public static DependentHostedNumberOrder fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static DependentHostedNumberOrder fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { - return objectMapper.readValue( - json, - DependentHostedNumberOrder.class - ); + return objectMapper.readValue(json, DependentHostedNumberOrder.class); } catch (final JsonMappingException | JsonParseException e) { throw new ApiException(e.getMessage(), e); } catch (final IOException e) { @@ -74,20 +118,14 @@ public static DependentHostedNumberOrder fromJson( * Converts a JSON InputStream into a DependentHostedNumberOrder object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return DependentHostedNumberOrder object represented by the provided JSON */ - public static DependentHostedNumberOrder fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static DependentHostedNumberOrder fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { - return objectMapper.readValue( - json, - DependentHostedNumberOrder.class - ); + return objectMapper.readValue(json, DependentHostedNumberOrder.class); } catch (final JsonMappingException | JsonParseException e) { throw new ApiException(e.getMessage(), e); } catch (final IOException e) { @@ -95,178 +133,113 @@ public static DependentHostedNumberOrder fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String incomingPhoneNumberSid; + @Getter private final String addressSid; - private final String signingDocumentSid; - private final com.twilio.type.PhoneNumber phoneNumber; + @Getter + private final Integer callDelay; + @Getter private final PhoneNumberCapabilities capabilities; - private final String friendlyName; - private final String uniqueName; - private final DependentHostedNumberOrder.Status status; - private final String failureReason; + @Getter + private final List ccEmails; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; - private final Integer verificationAttempts; + @Getter private final String email; - private final List ccEmails; - private final DependentHostedNumberOrder.VerificationType verificationType; - private final String verificationDocumentSid; + @Getter private final String extension; - private final Integer callDelay; - private final String verificationCode; + @Getter + private final String failureReason; + @Getter + private final String friendlyName; + @Getter + private final String incomingPhoneNumberSid; + @Getter + private final com.twilio.type.PhoneNumber phoneNumber; + @Getter + private final String sid; + @Getter + private final String signingDocumentSid; + @Getter + private final DependentHostedNumberOrder.Status status; + @Getter + private final String uniqueName; + @Getter + private final Integer verificationAttempts; + @Getter private final List verificationCallSids; + @Getter + private final String verificationCode; + @Getter + private final String verificationDocumentSid; + @Getter + private final DependentHostedNumberOrder.VerificationType verificationType; @JsonCreator private DependentHostedNumberOrder( - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty( - "incoming_phone_number_sid" - ) final String incomingPhoneNumberSid, - @JsonProperty("address_sid") final String addressSid, - @JsonProperty("signing_document_sid") final String signingDocumentSid, - @JsonProperty( - "phone_number" - ) final com.twilio.type.PhoneNumber phoneNumber, - @JsonProperty( - "capabilities" - ) final PhoneNumberCapabilities capabilities, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("unique_name") final String uniqueName, - @JsonProperty("status") final DependentHostedNumberOrder.Status status, - @JsonProperty("failure_reason") final String failureReason, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty( - "verification_attempts" - ) final Integer verificationAttempts, - @JsonProperty("email") final String email, - @JsonProperty("cc_emails") final List ccEmails, - @JsonProperty( - "verification_type" - ) final DependentHostedNumberOrder.VerificationType verificationType, - @JsonProperty( - "verification_document_sid" - ) final String verificationDocumentSid, - @JsonProperty("extension") final String extension, - @JsonProperty("call_delay") final Integer callDelay, - @JsonProperty("verification_code") final String verificationCode, - @JsonProperty("verification_call_sids") final List< - String - > verificationCallSids + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("address_sid") final String addressSid, + @JsonProperty("call_delay") final Integer callDelay, + @JsonProperty("capabilities") final PhoneNumberCapabilities capabilities, + @JsonProperty("cc_emails") final List ccEmails, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("email") final String email, + @JsonProperty("extension") final String extension, + @JsonProperty("failure_reason") final String failureReason, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("incoming_phone_number_sid") final String incomingPhoneNumberSid, + @JsonProperty("phone_number") final com.twilio.type.PhoneNumber phoneNumber, + @JsonProperty("sid") final String sid, + @JsonProperty("signing_document_sid") final String signingDocumentSid, + @JsonProperty("status") final DependentHostedNumberOrder.Status status, + @JsonProperty("unique_name") final String uniqueName, + @JsonProperty("verification_attempts") final Integer verificationAttempts, + @JsonProperty("verification_call_sids") final List verificationCallSids, + @JsonProperty("verification_code") final String verificationCode, + @JsonProperty("verification_document_sid") final String verificationDocumentSid, + @JsonProperty("verification_type") final DependentHostedNumberOrder.VerificationType verificationType ) { - this.sid = sid; this.accountSid = accountSid; - this.incomingPhoneNumberSid = incomingPhoneNumberSid; this.addressSid = addressSid; - this.signingDocumentSid = signingDocumentSid; - this.phoneNumber = phoneNumber; + this.callDelay = callDelay; this.capabilities = capabilities; + this.ccEmails = ccEmails; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; + this.email = email; + this.extension = extension; + this.failureReason = failureReason; this.friendlyName = friendlyName; - this.uniqueName = uniqueName; + this.incomingPhoneNumberSid = incomingPhoneNumberSid; + this.phoneNumber = phoneNumber; + this.sid = sid; + this.signingDocumentSid = signingDocumentSid; this.status = status; - this.failureReason = failureReason; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); + this.uniqueName = uniqueName; this.verificationAttempts = verificationAttempts; - this.email = email; - this.ccEmails = ccEmails; - this.verificationType = verificationType; - this.verificationDocumentSid = verificationDocumentSid; - this.extension = extension; - this.callDelay = callDelay; - this.verificationCode = verificationCode; this.verificationCallSids = verificationCallSids; - } - - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getIncomingPhoneNumberSid() { - return this.incomingPhoneNumberSid; - } - - public final String getAddressSid() { - return this.addressSid; - } - - public final String getSigningDocumentSid() { - return this.signingDocumentSid; - } - - public final com.twilio.type.PhoneNumber getPhoneNumber() { - return this.phoneNumber; - } - - public final PhoneNumberCapabilities getCapabilities() { - return this.capabilities; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final String getUniqueName() { - return this.uniqueName; - } - - public final DependentHostedNumberOrder.Status getStatus() { - return this.status; - } - - public final String getFailureReason() { - return this.failureReason; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final Integer getVerificationAttempts() { - return this.verificationAttempts; - } - - public final String getEmail() { - return this.email; - } - - public final List getCcEmails() { - return this.ccEmails; - } - - public final DependentHostedNumberOrder.VerificationType getVerificationType() { - return this.verificationType; - } - - public final String getVerificationDocumentSid() { - return this.verificationDocumentSid; - } - - public final String getExtension() { - return this.extension; - } - - public final Integer getCallDelay() { - return this.callDelay; - } - - public final String getVerificationCode() { - return this.verificationCode; - } - - public final List getVerificationCallSids() { - return this.verificationCallSids; + this.verificationCode = verificationCode; + this.verificationDocumentSid = verificationDocumentSid; + this.verificationType = verificationType; } @Override @@ -280,111 +253,60 @@ public boolean equals(final Object o) { } DependentHostedNumberOrder other = (DependentHostedNumberOrder) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals( - incomingPhoneNumberSid, - other.incomingPhoneNumberSid - ) && - Objects.equals(addressSid, other.addressSid) && - Objects.equals(signingDocumentSid, other.signingDocumentSid) && - Objects.equals(phoneNumber, other.phoneNumber) && - Objects.equals(capabilities, other.capabilities) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(uniqueName, other.uniqueName) && - Objects.equals(status, other.status) && - Objects.equals(failureReason, other.failureReason) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(verificationAttempts, other.verificationAttempts) && - Objects.equals(email, other.email) && - Objects.equals(ccEmails, other.ccEmails) && - Objects.equals(verificationType, other.verificationType) && - Objects.equals( - verificationDocumentSid, - other.verificationDocumentSid - ) && - Objects.equals(extension, other.extension) && - Objects.equals(callDelay, other.callDelay) && - Objects.equals(verificationCode, other.verificationCode) && - Objects.equals(verificationCallSids, other.verificationCallSids) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(addressSid, other.addressSid) && + Objects.equals(callDelay, other.callDelay) && + Objects.equals(capabilities, other.capabilities) && + Objects.equals(ccEmails, other.ccEmails) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(email, other.email) && + Objects.equals(extension, other.extension) && + Objects.equals(failureReason, other.failureReason) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(incomingPhoneNumberSid, other.incomingPhoneNumberSid) && + Objects.equals(phoneNumber, other.phoneNumber) && + Objects.equals(sid, other.sid) && + Objects.equals(signingDocumentSid, other.signingDocumentSid) && + Objects.equals(status, other.status) && + Objects.equals(uniqueName, other.uniqueName) && + Objects.equals(verificationAttempts, other.verificationAttempts) && + Objects.equals(verificationCallSids, other.verificationCallSids) && + Objects.equals(verificationCode, other.verificationCode) && + Objects.equals(verificationDocumentSid, other.verificationDocumentSid) && + Objects.equals(verificationType, other.verificationType) ); } @Override public int hashCode() { return Objects.hash( - sid, - accountSid, - incomingPhoneNumberSid, - addressSid, - signingDocumentSid, - phoneNumber, - capabilities, - friendlyName, - uniqueName, - status, - failureReason, - dateCreated, - dateUpdated, - verificationAttempts, - email, - ccEmails, - verificationType, - verificationDocumentSid, - extension, - callDelay, - verificationCode, - verificationCallSids + accountSid, + addressSid, + callDelay, + capabilities, + ccEmails, + dateCreated, + dateUpdated, + email, + extension, + failureReason, + friendlyName, + incomingPhoneNumberSid, + phoneNumber, + sid, + signingDocumentSid, + status, + uniqueName, + verificationAttempts, + verificationCallSids, + verificationCode, + verificationDocumentSid, + verificationType ); } - public enum VerificationType { - PHONE_CALL("phone-call"), - PHONE_BILL("phone-bill"); - private final String value; - - private VerificationType(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static VerificationType forValue(final String value) { - return Promoter.enumFromString(value, VerificationType.values()); - } - } - - public enum Status { - RECEIVED("received"), - PENDING_VERIFICATION("pending-verification"), - VERIFIED("verified"), - PENDING_LOA("pending-loa"), - CARRIER_PROCESSING("carrier-processing"), - TESTING("testing"), - COMPLETED("completed"), - FAILED("failed"), - ACTION_REQUIRED("action-required"); - - private final String value; - - private Status(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static Status forValue(final String value) { - return Promoter.enumFromString(value, Status.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/preview/hostedNumbers/authorizationdocument/DependentHostedNumberOrderReader.java b/src/main/java/com/twilio/rest/preview/hostedNumbers/authorizationdocument/DependentHostedNumberOrderReader.java index fe7b1f69bf..8df4bceaef 100644 --- a/src/main/java/com/twilio/rest/preview/hostedNumbers/authorizationdocument/DependentHostedNumberOrderReader.java +++ b/src/main/java/com/twilio/rest/preview/hostedNumbers/authorizationdocument/DependentHostedNumberOrderReader.java @@ -17,8 +17,9 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; import com.twilio.converter.Promoter; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -28,10 +29,9 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class DependentHostedNumberOrderReader - extends Reader { +public class DependentHostedNumberOrderReader extends Reader { - private String pathSigningDocumentSid; + private String pathsigningDocumentSid; private DependentHostedNumberOrder.Status status; private com.twilio.type.PhoneNumber phoneNumber; private String incomingPhoneNumberSid; @@ -39,178 +39,143 @@ public class DependentHostedNumberOrderReader private String uniqueName; private Long pageSize; - public DependentHostedNumberOrderReader( - final String pathSigningDocumentSid - ) { - this.pathSigningDocumentSid = pathSigningDocumentSid; + public DependentHostedNumberOrderReader(final String pathsigningDocumentSid) { + this.pathsigningDocumentSid = pathsigningDocumentSid; } - public DependentHostedNumberOrderReader setStatus( - final DependentHostedNumberOrder.Status status - ) { + + public DependentHostedNumberOrderReader setStatus(final DependentHostedNumberOrder.Status status) { this.status = status; return this; } - public DependentHostedNumberOrderReader setPhoneNumber( - final com.twilio.type.PhoneNumber phoneNumber - ) { + + public DependentHostedNumberOrderReader setPhoneNumber(final com.twilio.type.PhoneNumber phoneNumber) { this.phoneNumber = phoneNumber; return this; } - public DependentHostedNumberOrderReader setPhoneNumber( - final String phoneNumber - ) { + public DependentHostedNumberOrderReader setPhoneNumber(final String phoneNumber) { return setPhoneNumber(Promoter.phoneNumberFromString(phoneNumber)); } - public DependentHostedNumberOrderReader setIncomingPhoneNumberSid( - final String incomingPhoneNumberSid - ) { + public DependentHostedNumberOrderReader setIncomingPhoneNumberSid(final String incomingPhoneNumberSid) { this.incomingPhoneNumberSid = incomingPhoneNumberSid; return this; } - public DependentHostedNumberOrderReader setFriendlyName( - final String friendlyName - ) { + + public DependentHostedNumberOrderReader setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } - public DependentHostedNumberOrderReader setUniqueName( - final String uniqueName - ) { + + public DependentHostedNumberOrderReader setUniqueName(final String uniqueName) { this.uniqueName = uniqueName; return this; } + public DependentHostedNumberOrderReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override - public ResourceSet read( - final TwilioRestClient client - ) { + public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } - public Page firstPage( - final TwilioRestClient client - ) { - String path = - "/HostedNumbers/AuthorizationDocuments/{SigningDocumentSid}/DependentHostedNumberOrders"; - path = - path.replace( - "{" + "SigningDocumentSid" + "}", - this.pathSigningDocumentSid.toString() - ); + public Page firstPage(final TwilioRestClient client) { + + String path = "/HostedNumbers/AuthorizationDocuments/{SigningDocumentSid}/DependentHostedNumberOrders"; + + path = path.replace("{" + "SigningDocumentSid" + "}", this.pathsigningDocumentSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.PREVIEW.toString(), - path + HttpMethod.GET, + Domains.PREVIEW.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "DependentHostedNumberOrder read failed: Unable to connect to server" - ); + throw new ApiConnectionException("DependentHostedNumberOrder read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "items", - response.getContent(), - DependentHostedNumberOrder.class, - client.getObjectMapper() - ); + "items", + response.getContent(), + DependentHostedNumberOrder.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.PREVIEW.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.PREVIEW.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (status != null) { - request.addQueryParam("Status", status.toString()); + Serializer.toString(request, "Status", status, ParameterType.QUERY); } + + if (phoneNumber != null) { - request.addQueryParam("PhoneNumber", phoneNumber.toString()); + Serializer.toString(request, "PhoneNumber", phoneNumber, ParameterType.QUERY); } + + if (incomingPhoneNumberSid != null) { - request.addQueryParam( - "IncomingPhoneNumberSid", - incomingPhoneNumberSid - ); + Serializer.toString(request, "IncomingPhoneNumberSid", incomingPhoneNumberSid, ParameterType.QUERY); } + + if (friendlyName != null) { - request.addQueryParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.QUERY); } + + if (uniqueName != null) { - request.addQueryParam("UniqueName", uniqueName); + Serializer.toString(request, "UniqueName", uniqueName, ParameterType.QUERY); } + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/preview/marketplace/AvailableAddOn.java b/src/main/java/com/twilio/rest/preview/marketplace/AvailableAddOn.java index 568c5c8b67..65f07da625 100644 --- a/src/main/java/com/twilio/rest/preview/marketplace/AvailableAddOn.java +++ b/src/main/java/com/twilio/rest/preview/marketplace/AvailableAddOn.java @@ -18,45 +18,48 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class AvailableAddOn extends Resource { - private static final long serialVersionUID = 265387241353044L; - public static AvailableAddOnFetcher fetcher(final String pathSid) { - return new AvailableAddOnFetcher(pathSid); + public static AvailableAddOnFetcher fetcher(final String pathsid) { + return new AvailableAddOnFetcher( + pathsid + ); } + public static AvailableAddOnReader reader() { - return new AvailableAddOnReader(); + return new AvailableAddOnReader( + + ); } + /** * Converts a JSON String into a AvailableAddOn object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return AvailableAddOn object represented by the provided JSON */ - public static AvailableAddOn fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static AvailableAddOn fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, AvailableAddOn.class); @@ -71,14 +74,11 @@ public static AvailableAddOn fromJson( * Converts a JSON InputStream into a AvailableAddOn object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return AvailableAddOn object represented by the provided JSON */ - public static AvailableAddOn fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static AvailableAddOn fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, AvailableAddOn.class); @@ -89,62 +89,51 @@ public static AvailableAddOn fromJson( } } - private final String sid; - private final String friendlyName; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter + private final Object configurationSchema; + @Getter private final String description; + @Getter + private final String friendlyName; + @Getter + private final Map links; + @Getter private final String pricingType; - private final Map configurationSchema; + @Getter + private final String sid; + @Getter private final URI url; - private final Map links; @JsonCreator private AvailableAddOn( - @JsonProperty("sid") final String sid, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("description") final String description, - @JsonProperty("pricing_type") final String pricingType, - @JsonProperty("configuration_schema") final Map< - String, - Object - > configurationSchema, - @JsonProperty("url") final URI url, - @JsonProperty("links") final Map links + @JsonProperty("configuration_schema") final Object configurationSchema, + @JsonProperty("description") final String description, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("links") final Map links, + @JsonProperty("pricing_type") final String pricingType, + @JsonProperty("sid") final String sid, + @JsonProperty("url") final URI url ) { - this.sid = sid; - this.friendlyName = friendlyName; + this.configurationSchema = configurationSchema; this.description = description; + this.friendlyName = friendlyName; + this.links = links; this.pricingType = pricingType; - this.configurationSchema = configurationSchema; + this.sid = sid; this.url = url; - this.links = links; - } - - public final String getSid() { - return this.sid; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final String getDescription() { - return this.description; - } - - public final String getPricingType() { - return this.pricingType; - } - - public final Map getConfigurationSchema() { - return this.configurationSchema; - } - - public final URI getUrl() { - return this.url; - } - - public final Map getLinks() { - return this.links; } @Override @@ -158,28 +147,30 @@ public boolean equals(final Object o) { } AvailableAddOn other = (AvailableAddOn) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(description, other.description) && - Objects.equals(pricingType, other.pricingType) && - Objects.equals(configurationSchema, other.configurationSchema) && - Objects.equals(url, other.url) && - Objects.equals(links, other.links) + Objects.equals(configurationSchema, other.configurationSchema) && + Objects.equals(description, other.description) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(links, other.links) && + Objects.equals(pricingType, other.pricingType) && + Objects.equals(sid, other.sid) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - sid, - friendlyName, - description, - pricingType, - configurationSchema, - url, - links + configurationSchema, + description, + friendlyName, + links, + pricingType, + sid, + url ); } + + } + diff --git a/src/main/java/com/twilio/rest/preview/marketplace/AvailableAddOnFetcher.java b/src/main/java/com/twilio/rest/preview/marketplace/AvailableAddOnFetcher.java index 5dd8cde62f..e1d8c4cb66 100644 --- a/src/main/java/com/twilio/rest/preview/marketplace/AvailableAddOnFetcher.java +++ b/src/main/java/com/twilio/rest/preview/marketplace/AvailableAddOnFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.preview.marketplace; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,47 +26,41 @@ public class AvailableAddOnFetcher extends Fetcher { - private String pathSid; + private String pathsid; - public AvailableAddOnFetcher(final String pathSid) { - this.pathSid = pathSid; + public AvailableAddOnFetcher(final String pathsid) { + this.pathsid = pathsid; } + @Override public AvailableAddOn fetch(final TwilioRestClient client) { + String path = "/marketplace/AvailableAddOns/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.PREVIEW.toString(), - path + HttpMethod.GET, + Domains.PREVIEW.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "AvailableAddOn fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("AvailableAddOn fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return AvailableAddOn.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return AvailableAddOn.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/preview/marketplace/AvailableAddOnReader.java b/src/main/java/com/twilio/rest/preview/marketplace/AvailableAddOnReader.java index 5ec24cc194..9551606732 100644 --- a/src/main/java/com/twilio/rest/preview/marketplace/AvailableAddOnReader.java +++ b/src/main/java/com/twilio/rest/preview/marketplace/AvailableAddOnReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -31,105 +32,83 @@ public class AvailableAddOnReader extends Reader { private Long pageSize; - public AvailableAddOnReader() {} + public AvailableAddOnReader() { + } + public AvailableAddOnReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/marketplace/AvailableAddOns"; + Request request = new Request( - HttpMethod.GET, - Domains.PREVIEW.toString(), - path + HttpMethod.GET, + Domains.PREVIEW.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "AvailableAddOn read failed: Unable to connect to server" - ); + throw new ApiConnectionException("AvailableAddOn read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "available_add_ons", - response.getContent(), - AvailableAddOn.class, - client.getObjectMapper() - ); + "available_add_ons", + response.getContent(), + AvailableAddOn.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.PREVIEW.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.PREVIEW.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/preview/marketplace/InstalledAddOn.java b/src/main/java/com/twilio/rest/preview/marketplace/InstalledAddOn.java index 864a5bec86..ab82e76c6b 100644 --- a/src/main/java/com/twilio/rest/preview/marketplace/InstalledAddOn.java +++ b/src/main/java/com/twilio/rest/preview/marketplace/InstalledAddOn.java @@ -18,65 +18,71 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class InstalledAddOn extends Resource { - private static final long serialVersionUID = 250400645130930L; - public static InstalledAddOnCreator creator( - final String availableAddOnSid, - final Boolean acceptTermsOfService - ) { + public static InstalledAddOnCreator creator(final String availableAddOnSid, final Boolean acceptTermsOfService) { return new InstalledAddOnCreator( - availableAddOnSid, - acceptTermsOfService + availableAddOnSid, acceptTermsOfService ); } - public static InstalledAddOnDeleter deleter(final String pathSid) { - return new InstalledAddOnDeleter(pathSid); + + public static InstalledAddOnDeleter deleter(final String pathsid) { + return new InstalledAddOnDeleter( + pathsid + ); } - public static InstalledAddOnFetcher fetcher(final String pathSid) { - return new InstalledAddOnFetcher(pathSid); + + public static InstalledAddOnFetcher fetcher(final String pathsid) { + return new InstalledAddOnFetcher( + pathsid + ); } + public static InstalledAddOnReader reader() { - return new InstalledAddOnReader(); + return new InstalledAddOnReader( + + ); } - public static InstalledAddOnUpdater updater(final String pathSid) { - return new InstalledAddOnUpdater(pathSid); + + public static InstalledAddOnUpdater updater(final String pathsid) { + return new InstalledAddOnUpdater( + pathsid + ); } + /** * Converts a JSON String into a InstalledAddOn object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return InstalledAddOn object represented by the provided JSON */ - public static InstalledAddOn fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static InstalledAddOn fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, InstalledAddOn.class); @@ -91,14 +97,11 @@ public static InstalledAddOn fromJson( * Converts a JSON InputStream into a InstalledAddOn object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return InstalledAddOn object represented by the provided JSON */ - public static InstalledAddOn fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static InstalledAddOn fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, InstalledAddOn.class); @@ -109,80 +112,65 @@ public static InstalledAddOn fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String friendlyName; - private final String description; - private final Map configuration; - private final String uniqueName; + @Getter + private final Object configuration; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; - private final URI url; + @Getter + private final String description; + @Getter + private final String friendlyName; + @Getter private final Map links; + @Getter + private final String sid; + @Getter + private final String uniqueName; + @Getter + private final URI url; @JsonCreator private InstalledAddOn( - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("description") final String description, - @JsonProperty("configuration") final Map configuration, - @JsonProperty("unique_name") final String uniqueName, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("url") final URI url, - @JsonProperty("links") final Map links + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("configuration") final Object configuration, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("description") final String description, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("links") final Map links, + @JsonProperty("sid") final String sid, + @JsonProperty("unique_name") final String uniqueName, + @JsonProperty("url") final URI url ) { - this.sid = sid; this.accountSid = accountSid; - this.friendlyName = friendlyName; - this.description = description; this.configuration = configuration; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; + this.description = description; + this.friendlyName = friendlyName; + this.links = links; + this.sid = sid; this.uniqueName = uniqueName; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); this.url = url; - this.links = links; - } - - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final String getDescription() { - return this.description; - } - - public final Map getConfiguration() { - return this.configuration; - } - - public final String getUniqueName() { - return this.uniqueName; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final URI getUrl() { - return this.url; - } - - public final Map getLinks() { - return this.links; } @Override @@ -196,34 +184,36 @@ public boolean equals(final Object o) { } InstalledAddOn other = (InstalledAddOn) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(description, other.description) && - Objects.equals(configuration, other.configuration) && - Objects.equals(uniqueName, other.uniqueName) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(url, other.url) && - Objects.equals(links, other.links) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(configuration, other.configuration) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(description, other.description) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(links, other.links) && + Objects.equals(sid, other.sid) && + Objects.equals(uniqueName, other.uniqueName) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - sid, - accountSid, - friendlyName, - description, - configuration, - uniqueName, - dateCreated, - dateUpdated, - url, - links + accountSid, + configuration, + dateCreated, + dateUpdated, + description, + friendlyName, + links, + sid, + uniqueName, + url ); } + + } + diff --git a/src/main/java/com/twilio/rest/preview/marketplace/InstalledAddOnCreator.java b/src/main/java/com/twilio/rest/preview/marketplace/InstalledAddOnCreator.java index 21254453bc..ae9ea59bbb 100644 --- a/src/main/java/com/twilio/rest/preview/marketplace/InstalledAddOnCreator.java +++ b/src/main/java/com/twilio/rest/preview/marketplace/InstalledAddOnCreator.java @@ -14,10 +14,11 @@ package com.twilio.rest.preview.marketplace; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; -import com.twilio.converter.Converter; -import com.twilio.converter.Converter; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -34,103 +35,89 @@ public class InstalledAddOnCreator extends Creator { private Object configuration; private String uniqueName; - public InstalledAddOnCreator( - final String availableAddOnSid, - final Boolean acceptTermsOfService - ) { + public InstalledAddOnCreator(final String availableAddOnSid, final Boolean acceptTermsOfService) { this.availableAddOnSid = availableAddOnSid; this.acceptTermsOfService = acceptTermsOfService; } - public InstalledAddOnCreator setAvailableAddOnSid( - final String availableAddOnSid - ) { + + public InstalledAddOnCreator setAvailableAddOnSid(final String availableAddOnSid) { this.availableAddOnSid = availableAddOnSid; return this; } - public InstalledAddOnCreator setAcceptTermsOfService( - final Boolean acceptTermsOfService - ) { + + public InstalledAddOnCreator setAcceptTermsOfService(final Boolean acceptTermsOfService) { this.acceptTermsOfService = acceptTermsOfService; return this; } + public InstalledAddOnCreator setConfiguration(final Object configuration) { this.configuration = configuration; return this; } + public InstalledAddOnCreator setUniqueName(final String uniqueName) { this.uniqueName = uniqueName; return this; } + @Override public InstalledAddOn create(final TwilioRestClient client) { + String path = "/marketplace/InstalledAddOns"; - path = - path.replace( - "{" + "AvailableAddOnSid" + "}", - this.availableAddOnSid.toString() - ); - path = - path.replace( - "{" + "AcceptTermsOfService" + "}", - this.acceptTermsOfService.toString() - ); Request request = new Request( - HttpMethod.POST, - Domains.PREVIEW.toString(), - path + HttpMethod.POST, + Domains.PREVIEW.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "InstalledAddOn creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("InstalledAddOn creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return InstalledAddOn.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return InstalledAddOn.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (availableAddOnSid != null) { - request.addPostParam("AvailableAddOnSid", availableAddOnSid); + Serializer.toString(request, "AvailableAddOnSid", availableAddOnSid, ParameterType.URLENCODED); } + + if (acceptTermsOfService != null) { - request.addPostParam( - "AcceptTermsOfService", - acceptTermsOfService.toString() - ); + Serializer.toString(request, "AcceptTermsOfService", acceptTermsOfService, ParameterType.URLENCODED); } + + if (configuration != null) { - request.addPostParam( - "Configuration", - Converter.objectToJson(configuration) - ); + Serializer.toString(request, "Configuration", configuration, ParameterType.URLENCODED); } + + if (uniqueName != null) { - request.addPostParam("UniqueName", uniqueName); + Serializer.toString(request, "UniqueName", uniqueName, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/preview/marketplace/InstalledAddOnDeleter.java b/src/main/java/com/twilio/rest/preview/marketplace/InstalledAddOnDeleter.java index 2a591908c7..9181ad9f2a 100644 --- a/src/main/java/com/twilio/rest/preview/marketplace/InstalledAddOnDeleter.java +++ b/src/main/java/com/twilio/rest/preview/marketplace/InstalledAddOnDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.preview.marketplace; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,40 +26,38 @@ public class InstalledAddOnDeleter extends Deleter { - private String pathSid; + private String pathsid; - public InstalledAddOnDeleter(final String pathSid) { - this.pathSid = pathSid; + public InstalledAddOnDeleter(final String pathsid) { + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/marketplace/InstalledAddOns/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.PREVIEW.toString(), - path + HttpMethod.DELETE, + Domains.PREVIEW.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "InstalledAddOn delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("InstalledAddOn delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/preview/marketplace/InstalledAddOnFetcher.java b/src/main/java/com/twilio/rest/preview/marketplace/InstalledAddOnFetcher.java index 27fddce6f8..215d813b39 100644 --- a/src/main/java/com/twilio/rest/preview/marketplace/InstalledAddOnFetcher.java +++ b/src/main/java/com/twilio/rest/preview/marketplace/InstalledAddOnFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.preview.marketplace; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,47 +26,41 @@ public class InstalledAddOnFetcher extends Fetcher { - private String pathSid; + private String pathsid; - public InstalledAddOnFetcher(final String pathSid) { - this.pathSid = pathSid; + public InstalledAddOnFetcher(final String pathsid) { + this.pathsid = pathsid; } + @Override public InstalledAddOn fetch(final TwilioRestClient client) { + String path = "/marketplace/InstalledAddOns/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.PREVIEW.toString(), - path + HttpMethod.GET, + Domains.PREVIEW.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "InstalledAddOn fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("InstalledAddOn fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return InstalledAddOn.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return InstalledAddOn.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/preview/marketplace/InstalledAddOnReader.java b/src/main/java/com/twilio/rest/preview/marketplace/InstalledAddOnReader.java index 03a8a10ff9..d01b8ce70e 100644 --- a/src/main/java/com/twilio/rest/preview/marketplace/InstalledAddOnReader.java +++ b/src/main/java/com/twilio/rest/preview/marketplace/InstalledAddOnReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -31,105 +32,83 @@ public class InstalledAddOnReader extends Reader { private Long pageSize; - public InstalledAddOnReader() {} + public InstalledAddOnReader() { + } + public InstalledAddOnReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/marketplace/InstalledAddOns"; + Request request = new Request( - HttpMethod.GET, - Domains.PREVIEW.toString(), - path + HttpMethod.GET, + Domains.PREVIEW.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "InstalledAddOn read failed: Unable to connect to server" - ); + throw new ApiConnectionException("InstalledAddOn read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "installed_add_ons", - response.getContent(), - InstalledAddOn.class, - client.getObjectMapper() - ); + "installed_add_ons", + response.getContent(), + InstalledAddOn.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.PREVIEW.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.PREVIEW.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/preview/marketplace/InstalledAddOnUpdater.java b/src/main/java/com/twilio/rest/preview/marketplace/InstalledAddOnUpdater.java index bb4dc1e55b..3a7fc9f020 100644 --- a/src/main/java/com/twilio/rest/preview/marketplace/InstalledAddOnUpdater.java +++ b/src/main/java/com/twilio/rest/preview/marketplace/InstalledAddOnUpdater.java @@ -16,7 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; -import com.twilio.converter.Converter; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,72 +28,72 @@ import com.twilio.rest.Domains; public class InstalledAddOnUpdater extends Updater { - - private String pathSid; + private String pathsid; private Object configuration; private String uniqueName; - public InstalledAddOnUpdater(final String pathSid) { - this.pathSid = pathSid; + public InstalledAddOnUpdater(final String pathsid) { + this.pathsid = pathsid; } + public InstalledAddOnUpdater setConfiguration(final Object configuration) { this.configuration = configuration; return this; } + public InstalledAddOnUpdater setUniqueName(final String uniqueName) { this.uniqueName = uniqueName; return this; } + @Override public InstalledAddOn update(final TwilioRestClient client) { + String path = "/marketplace/InstalledAddOns/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.PREVIEW.toString(), - path + HttpMethod.POST, + Domains.PREVIEW.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "InstalledAddOn update failed: Unable to connect to server" - ); + throw new ApiConnectionException("InstalledAddOn update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return InstalledAddOn.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return InstalledAddOn.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (configuration != null) { - request.addPostParam( - "Configuration", - Converter.objectToJson(configuration) - ); + Serializer.toString(request, "Configuration", configuration, ParameterType.URLENCODED); } + + if (uniqueName != null) { - request.addPostParam("UniqueName", uniqueName); + Serializer.toString(request, "UniqueName", uniqueName, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/preview/marketplace/availableaddon/AvailableAddOnExtension.java b/src/main/java/com/twilio/rest/preview/marketplace/availableaddon/AvailableAddOnExtension.java index 9e62d2a07d..e0dd89a6db 100644 --- a/src/main/java/com/twilio/rest/preview/marketplace/availableaddon/AvailableAddOnExtension.java +++ b/src/main/java/com/twilio/rest/preview/marketplace/availableaddon/AvailableAddOnExtension.java @@ -18,51 +18,47 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class AvailableAddOnExtension extends Resource { - private static final long serialVersionUID = 15009232316880L; - public static AvailableAddOnExtensionFetcher fetcher( - final String pathAvailableAddOnSid, - final String pathSid - ) { + public static AvailableAddOnExtensionFetcher fetcher(final String pathavailableAddOnSid, final String pathsid) { return new AvailableAddOnExtensionFetcher( - pathAvailableAddOnSid, - pathSid + pathavailableAddOnSid, pathsid ); } - public static AvailableAddOnExtensionReader reader( - final String pathAvailableAddOnSid - ) { - return new AvailableAddOnExtensionReader(pathAvailableAddOnSid); + + public static AvailableAddOnExtensionReader reader(final String pathavailableAddOnSid) { + return new AvailableAddOnExtensionReader( + pathavailableAddOnSid + ); } + /** * Converts a JSON String into a AvailableAddOnExtension object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return AvailableAddOnExtension object represented by the provided JSON */ - public static AvailableAddOnExtension fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static AvailableAddOnExtension fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, AvailableAddOnExtension.class); @@ -77,14 +73,11 @@ public static AvailableAddOnExtension fromJson( * Converts a JSON InputStream into a AvailableAddOnExtension object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return AvailableAddOnExtension object represented by the provided JSON */ - public static AvailableAddOnExtension fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static AvailableAddOnExtension fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, AvailableAddOnExtension.class); @@ -95,54 +88,49 @@ public static AvailableAddOnExtension fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String availableAddOnSid; + @Getter private final String friendlyName; + @Getter private final String productName; + @Getter + private final String sid; + @Getter private final String uniqueName; + @Getter private final URI url; @JsonCreator private AvailableAddOnExtension( - @JsonProperty("sid") final String sid, - @JsonProperty("available_add_on_sid") final String availableAddOnSid, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("product_name") final String productName, - @JsonProperty("unique_name") final String uniqueName, - @JsonProperty("url") final URI url + @JsonProperty("available_add_on_sid") final String availableAddOnSid, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("product_name") final String productName, + @JsonProperty("sid") final String sid, + @JsonProperty("unique_name") final String uniqueName, + @JsonProperty("url") final URI url ) { - this.sid = sid; this.availableAddOnSid = availableAddOnSid; this.friendlyName = friendlyName; this.productName = productName; + this.sid = sid; this.uniqueName = uniqueName; this.url = url; } - public final String getSid() { - return this.sid; - } - - public final String getAvailableAddOnSid() { - return this.availableAddOnSid; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final String getProductName() { - return this.productName; - } - - public final String getUniqueName() { - return this.uniqueName; - } - - public final URI getUrl() { - return this.url; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -154,26 +142,28 @@ public boolean equals(final Object o) { } AvailableAddOnExtension other = (AvailableAddOnExtension) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(availableAddOnSid, other.availableAddOnSid) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(productName, other.productName) && - Objects.equals(uniqueName, other.uniqueName) && - Objects.equals(url, other.url) + Objects.equals(availableAddOnSid, other.availableAddOnSid) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(productName, other.productName) && + Objects.equals(sid, other.sid) && + Objects.equals(uniqueName, other.uniqueName) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - sid, - availableAddOnSid, - friendlyName, - productName, - uniqueName, - url + availableAddOnSid, + friendlyName, + productName, + sid, + uniqueName, + url ); } + + } + diff --git a/src/main/java/com/twilio/rest/preview/marketplace/availableaddon/AvailableAddOnExtensionFetcher.java b/src/main/java/com/twilio/rest/preview/marketplace/availableaddon/AvailableAddOnExtensionFetcher.java index c03c6da0b8..65b918e7b7 100644 --- a/src/main/java/com/twilio/rest/preview/marketplace/availableaddon/AvailableAddOnExtensionFetcher.java +++ b/src/main/java/com/twilio/rest/preview/marketplace/availableaddon/AvailableAddOnExtensionFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.preview.marketplace.availableaddon; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,61 +24,46 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class AvailableAddOnExtensionFetcher - extends Fetcher { +public class AvailableAddOnExtensionFetcher extends Fetcher { - private String pathAvailableAddOnSid; - private String pathSid; + private String pathavailableAddOnSid; + private String pathsid; - public AvailableAddOnExtensionFetcher( - final String pathAvailableAddOnSid, - final String pathSid - ) { - this.pathAvailableAddOnSid = pathAvailableAddOnSid; - this.pathSid = pathSid; + public AvailableAddOnExtensionFetcher(final String pathavailableAddOnSid, final String pathsid) { + this.pathavailableAddOnSid = pathavailableAddOnSid; + this.pathsid = pathsid; } + @Override public AvailableAddOnExtension fetch(final TwilioRestClient client) { - String path = - "/marketplace/AvailableAddOns/{AvailableAddOnSid}/Extensions/{Sid}"; - path = - path.replace( - "{" + "AvailableAddOnSid" + "}", - this.pathAvailableAddOnSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/marketplace/AvailableAddOns/{AvailableAddOnSid}/Extensions/{Sid}"; + + path = path.replace("{" + "AvailableAddOnSid" + "}", this.pathavailableAddOnSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.PREVIEW.toString(), - path + HttpMethod.GET, + Domains.PREVIEW.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "AvailableAddOnExtension fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("AvailableAddOnExtension fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return AvailableAddOnExtension.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return AvailableAddOnExtension.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/preview/marketplace/availableaddon/AvailableAddOnExtensionReader.java b/src/main/java/com/twilio/rest/preview/marketplace/availableaddon/AvailableAddOnExtensionReader.java index 813eb75aca..6dbfe4f1f0 100644 --- a/src/main/java/com/twilio/rest/preview/marketplace/availableaddon/AvailableAddOnExtensionReader.java +++ b/src/main/java/com/twilio/rest/preview/marketplace/availableaddon/AvailableAddOnExtensionReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,123 +28,90 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class AvailableAddOnExtensionReader - extends Reader { +public class AvailableAddOnExtensionReader extends Reader { - private String pathAvailableAddOnSid; + private String pathavailableAddOnSid; private Long pageSize; - public AvailableAddOnExtensionReader(final String pathAvailableAddOnSid) { - this.pathAvailableAddOnSid = pathAvailableAddOnSid; + public AvailableAddOnExtensionReader(final String pathavailableAddOnSid) { + this.pathavailableAddOnSid = pathavailableAddOnSid; } + public AvailableAddOnExtensionReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override - public ResourceSet read( - final TwilioRestClient client - ) { + public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } - public Page firstPage( - final TwilioRestClient client - ) { - String path = - "/marketplace/AvailableAddOns/{AvailableAddOnSid}/Extensions"; - path = - path.replace( - "{" + "AvailableAddOnSid" + "}", - this.pathAvailableAddOnSid.toString() - ); + public Page firstPage(final TwilioRestClient client) { + + String path = "/marketplace/AvailableAddOns/{AvailableAddOnSid}/Extensions"; + + path = path.replace("{" + "AvailableAddOnSid" + "}", this.pathavailableAddOnSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.PREVIEW.toString(), - path + HttpMethod.GET, + Domains.PREVIEW.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "AvailableAddOnExtension read failed: Unable to connect to server" - ); + throw new ApiConnectionException("AvailableAddOnExtension read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "extensions", - response.getContent(), - AvailableAddOnExtension.class, - client.getObjectMapper() - ); + "extensions", + response.getContent(), + AvailableAddOnExtension.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.PREVIEW.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.PREVIEW.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/preview/marketplace/installedaddon/InstalledAddOnExtension.java b/src/main/java/com/twilio/rest/preview/marketplace/installedaddon/InstalledAddOnExtension.java index 3cca5a44a1..6f9f774830 100644 --- a/src/main/java/com/twilio/rest/preview/marketplace/installedaddon/InstalledAddOnExtension.java +++ b/src/main/java/com/twilio/rest/preview/marketplace/installedaddon/InstalledAddOnExtension.java @@ -18,63 +18,54 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class InstalledAddOnExtension extends Resource { - private static final long serialVersionUID = 244872409958696L; - public static InstalledAddOnExtensionFetcher fetcher( - final String pathInstalledAddOnSid, - final String pathSid - ) { + public static InstalledAddOnExtensionFetcher fetcher(final String pathinstalledAddOnSid, final String pathsid) { return new InstalledAddOnExtensionFetcher( - pathInstalledAddOnSid, - pathSid + pathinstalledAddOnSid, pathsid ); } - public static InstalledAddOnExtensionReader reader( - final String pathInstalledAddOnSid - ) { - return new InstalledAddOnExtensionReader(pathInstalledAddOnSid); + + public static InstalledAddOnExtensionReader reader(final String pathinstalledAddOnSid) { + return new InstalledAddOnExtensionReader( + pathinstalledAddOnSid + ); } - public static InstalledAddOnExtensionUpdater updater( - final String pathInstalledAddOnSid, - final String pathSid, - final Boolean enabled - ) { + + public static InstalledAddOnExtensionUpdater updater(final String pathinstalledAddOnSid, final String pathsid, final Boolean enabled) { return new InstalledAddOnExtensionUpdater( - pathInstalledAddOnSid, - pathSid, - enabled + pathinstalledAddOnSid, pathsid, enabled ); } + /** * Converts a JSON String into a InstalledAddOnExtension object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return InstalledAddOnExtension object represented by the provided JSON */ - public static InstalledAddOnExtension fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static InstalledAddOnExtension fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, InstalledAddOnExtension.class); @@ -89,14 +80,11 @@ public static InstalledAddOnExtension fromJson( * Converts a JSON InputStream into a InstalledAddOnExtension object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return InstalledAddOnExtension object represented by the provided JSON */ - public static InstalledAddOnExtension fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static InstalledAddOnExtension fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, InstalledAddOnExtension.class); @@ -107,61 +95,53 @@ public static InstalledAddOnExtension fromJson( } } - private final String sid; - private final String installedAddOnSid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter + private final Boolean enabled; + @Getter private final String friendlyName; + @Getter + private final String installedAddOnSid; + @Getter private final String productName; + @Getter + private final String sid; + @Getter private final String uniqueName; - private final Boolean enabled; + @Getter private final URI url; @JsonCreator private InstalledAddOnExtension( - @JsonProperty("sid") final String sid, - @JsonProperty("installed_add_on_sid") final String installedAddOnSid, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("product_name") final String productName, - @JsonProperty("unique_name") final String uniqueName, - @JsonProperty("enabled") final Boolean enabled, - @JsonProperty("url") final URI url + @JsonProperty("enabled") final Boolean enabled, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("installed_add_on_sid") final String installedAddOnSid, + @JsonProperty("product_name") final String productName, + @JsonProperty("sid") final String sid, + @JsonProperty("unique_name") final String uniqueName, + @JsonProperty("url") final URI url ) { - this.sid = sid; - this.installedAddOnSid = installedAddOnSid; + this.enabled = enabled; this.friendlyName = friendlyName; + this.installedAddOnSid = installedAddOnSid; this.productName = productName; + this.sid = sid; this.uniqueName = uniqueName; - this.enabled = enabled; this.url = url; } - public final String getSid() { - return this.sid; - } - - public final String getInstalledAddOnSid() { - return this.installedAddOnSid; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final String getProductName() { - return this.productName; - } - - public final String getUniqueName() { - return this.uniqueName; - } - - public final Boolean getEnabled() { - return this.enabled; - } - - public final URI getUrl() { - return this.url; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -173,28 +153,30 @@ public boolean equals(final Object o) { } InstalledAddOnExtension other = (InstalledAddOnExtension) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(installedAddOnSid, other.installedAddOnSid) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(productName, other.productName) && - Objects.equals(uniqueName, other.uniqueName) && - Objects.equals(enabled, other.enabled) && - Objects.equals(url, other.url) + Objects.equals(enabled, other.enabled) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(installedAddOnSid, other.installedAddOnSid) && + Objects.equals(productName, other.productName) && + Objects.equals(sid, other.sid) && + Objects.equals(uniqueName, other.uniqueName) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - sid, - installedAddOnSid, - friendlyName, - productName, - uniqueName, - enabled, - url + enabled, + friendlyName, + installedAddOnSid, + productName, + sid, + uniqueName, + url ); } + + } + diff --git a/src/main/java/com/twilio/rest/preview/marketplace/installedaddon/InstalledAddOnExtensionFetcher.java b/src/main/java/com/twilio/rest/preview/marketplace/installedaddon/InstalledAddOnExtensionFetcher.java index e78d937f56..9da5df8f41 100644 --- a/src/main/java/com/twilio/rest/preview/marketplace/installedaddon/InstalledAddOnExtensionFetcher.java +++ b/src/main/java/com/twilio/rest/preview/marketplace/installedaddon/InstalledAddOnExtensionFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.preview.marketplace.installedaddon; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,61 +24,46 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class InstalledAddOnExtensionFetcher - extends Fetcher { +public class InstalledAddOnExtensionFetcher extends Fetcher { - private String pathInstalledAddOnSid; - private String pathSid; + private String pathinstalledAddOnSid; + private String pathsid; - public InstalledAddOnExtensionFetcher( - final String pathInstalledAddOnSid, - final String pathSid - ) { - this.pathInstalledAddOnSid = pathInstalledAddOnSid; - this.pathSid = pathSid; + public InstalledAddOnExtensionFetcher(final String pathinstalledAddOnSid, final String pathsid) { + this.pathinstalledAddOnSid = pathinstalledAddOnSid; + this.pathsid = pathsid; } + @Override public InstalledAddOnExtension fetch(final TwilioRestClient client) { - String path = - "/marketplace/InstalledAddOns/{InstalledAddOnSid}/Extensions/{Sid}"; - path = - path.replace( - "{" + "InstalledAddOnSid" + "}", - this.pathInstalledAddOnSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/marketplace/InstalledAddOns/{InstalledAddOnSid}/Extensions/{Sid}"; + + path = path.replace("{" + "InstalledAddOnSid" + "}", this.pathinstalledAddOnSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.PREVIEW.toString(), - path + HttpMethod.GET, + Domains.PREVIEW.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "InstalledAddOnExtension fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("InstalledAddOnExtension fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return InstalledAddOnExtension.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return InstalledAddOnExtension.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/preview/marketplace/installedaddon/InstalledAddOnExtensionReader.java b/src/main/java/com/twilio/rest/preview/marketplace/installedaddon/InstalledAddOnExtensionReader.java index 84a21c5477..58a95a0326 100644 --- a/src/main/java/com/twilio/rest/preview/marketplace/installedaddon/InstalledAddOnExtensionReader.java +++ b/src/main/java/com/twilio/rest/preview/marketplace/installedaddon/InstalledAddOnExtensionReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,123 +28,90 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class InstalledAddOnExtensionReader - extends Reader { +public class InstalledAddOnExtensionReader extends Reader { - private String pathInstalledAddOnSid; + private String pathinstalledAddOnSid; private Long pageSize; - public InstalledAddOnExtensionReader(final String pathInstalledAddOnSid) { - this.pathInstalledAddOnSid = pathInstalledAddOnSid; + public InstalledAddOnExtensionReader(final String pathinstalledAddOnSid) { + this.pathinstalledAddOnSid = pathinstalledAddOnSid; } + public InstalledAddOnExtensionReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override - public ResourceSet read( - final TwilioRestClient client - ) { + public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } - public Page firstPage( - final TwilioRestClient client - ) { - String path = - "/marketplace/InstalledAddOns/{InstalledAddOnSid}/Extensions"; - path = - path.replace( - "{" + "InstalledAddOnSid" + "}", - this.pathInstalledAddOnSid.toString() - ); + public Page firstPage(final TwilioRestClient client) { + + String path = "/marketplace/InstalledAddOns/{InstalledAddOnSid}/Extensions"; + + path = path.replace("{" + "InstalledAddOnSid" + "}", this.pathinstalledAddOnSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.PREVIEW.toString(), - path + HttpMethod.GET, + Domains.PREVIEW.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "InstalledAddOnExtension read failed: Unable to connect to server" - ); + throw new ApiConnectionException("InstalledAddOnExtension read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "extensions", - response.getContent(), - InstalledAddOnExtension.class, - client.getObjectMapper() - ); + "extensions", + response.getContent(), + InstalledAddOnExtension.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.PREVIEW.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.PREVIEW.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/preview/marketplace/installedaddon/InstalledAddOnExtensionUpdater.java b/src/main/java/com/twilio/rest/preview/marketplace/installedaddon/InstalledAddOnExtensionUpdater.java index 0c87350840..403b04f943 100644 --- a/src/main/java/com/twilio/rest/preview/marketplace/installedaddon/InstalledAddOnExtensionUpdater.java +++ b/src/main/java/com/twilio/rest/preview/marketplace/installedaddon/InstalledAddOnExtensionUpdater.java @@ -16,6 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,76 +27,65 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class InstalledAddOnExtensionUpdater - extends Updater { - - private String pathInstalledAddOnSid; - private String pathSid; +public class InstalledAddOnExtensionUpdater extends Updater { + private String pathinstalledAddOnSid; + private String pathsid; private Boolean enabled; - public InstalledAddOnExtensionUpdater( - final String pathInstalledAddOnSid, - final String pathSid, - final Boolean enabled - ) { - this.pathInstalledAddOnSid = pathInstalledAddOnSid; - this.pathSid = pathSid; + public InstalledAddOnExtensionUpdater(final String pathinstalledAddOnSid, final String pathsid, final Boolean enabled) { + this.pathinstalledAddOnSid = pathinstalledAddOnSid; + this.pathsid = pathsid; this.enabled = enabled; } + public InstalledAddOnExtensionUpdater setEnabled(final Boolean enabled) { this.enabled = enabled; return this; } + @Override public InstalledAddOnExtension update(final TwilioRestClient client) { - String path = - "/marketplace/InstalledAddOns/{InstalledAddOnSid}/Extensions/{Sid}"; - path = - path.replace( - "{" + "InstalledAddOnSid" + "}", - this.pathInstalledAddOnSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); - path = path.replace("{" + "Enabled" + "}", this.enabled.toString()); + String path = "/marketplace/InstalledAddOns/{InstalledAddOnSid}/Extensions/{Sid}"; + + path = path.replace("{" + "InstalledAddOnSid" + "}", this.pathinstalledAddOnSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.PREVIEW.toString(), - path + HttpMethod.POST, + Domains.PREVIEW.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "InstalledAddOnExtension update failed: Unable to connect to server" - ); + throw new ApiConnectionException("InstalledAddOnExtension update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return InstalledAddOnExtension.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return InstalledAddOnExtension.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (enabled != null) { - request.addPostParam("Enabled", enabled.toString()); + Serializer.toString(request, "Enabled", enabled, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/preview/wireless/Command.java b/src/main/java/com/twilio/rest/preview/wireless/Command.java index a51ef30e47..1a8ab9d94c 100644 --- a/src/main/java/com/twilio/rest/preview/wireless/Command.java +++ b/src/main/java/com/twilio/rest/preview/wireless/Command.java @@ -18,49 +18,56 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Command extends Resource { - private static final long serialVersionUID = 211711437701945L; public static CommandCreator creator(final String command) { - return new CommandCreator(command); + return new CommandCreator( + command + ); } - public static CommandFetcher fetcher(final String pathSid) { - return new CommandFetcher(pathSid); + + public static CommandFetcher fetcher(final String pathsid) { + return new CommandFetcher( + pathsid + ); } + public static CommandReader reader() { - return new CommandReader(); + return new CommandReader( + + ); } + /** * Converts a JSON String into a Command object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Command object represented by the provided JSON */ - public static Command fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Command fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Command.class); @@ -75,14 +82,11 @@ public static Command fromJson( * Converts a JSON InputStream into a Command object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Command object represented by the provided JSON */ - public static Command fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Command fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Command.class); @@ -93,89 +97,71 @@ public static Command fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String deviceSid; - private final String simSid; + @Getter private final String command; + @Getter private final String commandMode; - private final String status; - private final String direction; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; + @Getter + private final String deviceSid; + @Getter + private final String direction; + @Getter + private final String sid; + @Getter + private final String simSid; + @Getter + private final String status; + @Getter private final URI url; @JsonCreator private Command( - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("device_sid") final String deviceSid, - @JsonProperty("sim_sid") final String simSid, - @JsonProperty("command") final String command, - @JsonProperty("command_mode") final String commandMode, - @JsonProperty("status") final String status, - @JsonProperty("direction") final String direction, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("url") final URI url + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("command") final String command, + @JsonProperty("command_mode") final String commandMode, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("device_sid") final String deviceSid, + @JsonProperty("direction") final String direction, + @JsonProperty("sid") final String sid, + @JsonProperty("sim_sid") final String simSid, + @JsonProperty("status") final String status, + @JsonProperty("url") final URI url ) { - this.sid = sid; this.accountSid = accountSid; - this.deviceSid = deviceSid; - this.simSid = simSid; this.command = command; this.commandMode = commandMode; - this.status = status; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; + this.deviceSid = deviceSid; this.direction = direction; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); + this.sid = sid; + this.simSid = simSid; + this.status = status; this.url = url; } - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getDeviceSid() { - return this.deviceSid; - } - - public final String getSimSid() { - return this.simSid; - } - - public final String getCommand() { - return this.command; - } - - public final String getCommandMode() { - return this.commandMode; - } - - public final String getStatus() { - return this.status; - } - - public final String getDirection() { - return this.direction; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final URI getUrl() { - return this.url; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -187,36 +173,38 @@ public boolean equals(final Object o) { } Command other = (Command) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(deviceSid, other.deviceSid) && - Objects.equals(simSid, other.simSid) && - Objects.equals(command, other.command) && - Objects.equals(commandMode, other.commandMode) && - Objects.equals(status, other.status) && - Objects.equals(direction, other.direction) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(url, other.url) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(command, other.command) && + Objects.equals(commandMode, other.commandMode) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(deviceSid, other.deviceSid) && + Objects.equals(direction, other.direction) && + Objects.equals(sid, other.sid) && + Objects.equals(simSid, other.simSid) && + Objects.equals(status, other.status) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - sid, - accountSid, - deviceSid, - simSid, - command, - commandMode, - status, - direction, - dateCreated, - dateUpdated, - url + accountSid, + command, + commandMode, + dateCreated, + dateUpdated, + deviceSid, + direction, + sid, + simSid, + status, + url ); } + + } + diff --git a/src/main/java/com/twilio/rest/preview/wireless/CommandCreator.java b/src/main/java/com/twilio/rest/preview/wireless/CommandCreator.java index a5db8bc55b..073b27735b 100644 --- a/src/main/java/com/twilio/rest/preview/wireless/CommandCreator.java +++ b/src/main/java/com/twilio/rest/preview/wireless/CommandCreator.java @@ -14,9 +14,11 @@ package com.twilio.rest.preview.wireless; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; -import com.twilio.converter.Promoter; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,7 +27,7 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -import java.net.URI; + import java.net.URI; public class CommandCreator extends Creator { @@ -42,73 +44,74 @@ public CommandCreator(final String command) { this.command = command; } + public CommandCreator setCommand(final String command) { this.command = command; return this; } + public CommandCreator setDevice(final String device) { this.device = device; return this; } + public CommandCreator setSim(final String sim) { this.sim = sim; return this; } + public CommandCreator setCallbackMethod(final String callbackMethod) { this.callbackMethod = callbackMethod; return this; } + public CommandCreator setCallbackUrl(final URI callbackUrl) { this.callbackUrl = callbackUrl; return this; } - public CommandCreator setCallbackUrl(final String callbackUrl) { - return setCallbackUrl(Promoter.uriFromString(callbackUrl)); - } public CommandCreator setCommandMode(final String commandMode) { this.commandMode = commandMode; return this; } + public CommandCreator setIncludeSid(final String includeSid) { this.includeSid = includeSid; return this; } + @Override public Command create(final TwilioRestClient client) { + String path = "/wireless/Commands"; - path = path.replace("{" + "Command" + "}", this.command.toString()); Request request = new Request( - HttpMethod.POST, - Domains.PREVIEW.toString(), - path + HttpMethod.POST, + Domains.PREVIEW.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Command creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("Command creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -117,26 +120,41 @@ public Command create(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (command != null) { - request.addPostParam("Command", command); + Serializer.toString(request, "Command", command, ParameterType.URLENCODED); } + + if (device != null) { - request.addPostParam("Device", device); + Serializer.toString(request, "Device", device, ParameterType.URLENCODED); } + + if (sim != null) { - request.addPostParam("Sim", sim); + Serializer.toString(request, "Sim", sim, ParameterType.URLENCODED); } + + if (callbackMethod != null) { - request.addPostParam("CallbackMethod", callbackMethod); + Serializer.toString(request, "CallbackMethod", callbackMethod, ParameterType.URLENCODED); } + + if (callbackUrl != null) { - request.addPostParam("CallbackUrl", callbackUrl.toString()); + Serializer.toString(request, "CallbackUrl", callbackUrl, ParameterType.URLENCODED); } + + if (commandMode != null) { - request.addPostParam("CommandMode", commandMode); + Serializer.toString(request, "CommandMode", commandMode, ParameterType.URLENCODED); } + + if (includeSid != null) { - request.addPostParam("IncludeSid", includeSid); + Serializer.toString(request, "IncludeSid", includeSid, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/preview/wireless/CommandFetcher.java b/src/main/java/com/twilio/rest/preview/wireless/CommandFetcher.java index eaa2012c74..b456796147 100644 --- a/src/main/java/com/twilio/rest/preview/wireless/CommandFetcher.java +++ b/src/main/java/com/twilio/rest/preview/wireless/CommandFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.preview.wireless; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,44 +26,41 @@ public class CommandFetcher extends Fetcher { - private String pathSid; + private String pathsid; - public CommandFetcher(final String pathSid) { - this.pathSid = pathSid; + public CommandFetcher(final String pathsid) { + this.pathsid = pathsid; } + @Override public Command fetch(final TwilioRestClient client) { + String path = "/wireless/Commands/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.PREVIEW.toString(), - path + HttpMethod.GET, + Domains.PREVIEW.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Command fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Command fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Command.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/preview/wireless/CommandReader.java b/src/main/java/com/twilio/rest/preview/wireless/CommandReader.java index 5f07eb0eef..881e9099ce 100644 --- a/src/main/java/com/twilio/rest/preview/wireless/CommandReader.java +++ b/src/main/java/com/twilio/rest/preview/wireless/CommandReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -35,137 +36,127 @@ public class CommandReader extends Reader { private String direction; private Long pageSize; - public CommandReader() {} + public CommandReader() { + } + public CommandReader setDevice(final String device) { this.device = device; return this; } + public CommandReader setSim(final String sim) { this.sim = sim; return this; } + public CommandReader setStatus(final String status) { this.status = status; return this; } + public CommandReader setDirection(final String direction) { this.direction = direction; return this; } + public CommandReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/wireless/Commands"; + Request request = new Request( - HttpMethod.GET, - Domains.PREVIEW.toString(), - path + HttpMethod.GET, + Domains.PREVIEW.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Command read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Command read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "commands", - response.getContent(), - Command.class, - client.getObjectMapper() - ); + "commands", + response.getContent(), + Command.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.PREVIEW.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.PREVIEW.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (device != null) { - request.addQueryParam("Device", device); + Serializer.toString(request, "Device", device, ParameterType.QUERY); } + + if (sim != null) { - request.addQueryParam("Sim", sim); + Serializer.toString(request, "Sim", sim, ParameterType.QUERY); } + + if (status != null) { - request.addQueryParam("Status", status); + Serializer.toString(request, "Status", status, ParameterType.QUERY); } + + if (direction != null) { - request.addQueryParam("Direction", direction); + Serializer.toString(request, "Direction", direction, ParameterType.QUERY); } + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/preview/wireless/RatePlan.java b/src/main/java/com/twilio/rest/preview/wireless/RatePlan.java index 03a9b944fb..0ecca3965d 100644 --- a/src/main/java/com/twilio/rest/preview/wireless/RatePlan.java +++ b/src/main/java/com/twilio/rest/preview/wireless/RatePlan.java @@ -18,58 +18,71 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.List; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class RatePlan extends Resource { - private static final long serialVersionUID = 138565285894419L; public static RatePlanCreator creator() { - return new RatePlanCreator(); + return new RatePlanCreator( + + ); } - public static RatePlanDeleter deleter(final String pathSid) { - return new RatePlanDeleter(pathSid); + + public static RatePlanDeleter deleter(final String pathsid) { + return new RatePlanDeleter( + pathsid + ); } - public static RatePlanFetcher fetcher(final String pathSid) { - return new RatePlanFetcher(pathSid); + + public static RatePlanFetcher fetcher(final String pathsid) { + return new RatePlanFetcher( + pathsid + ); } + public static RatePlanReader reader() { - return new RatePlanReader(); + return new RatePlanReader( + + ); } - public static RatePlanUpdater updater(final String pathSid) { - return new RatePlanUpdater(pathSid); + + public static RatePlanUpdater updater(final String pathsid) { + return new RatePlanUpdater( + pathsid + ); } + /** * Converts a JSON String into a RatePlan object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return RatePlan object represented by the provided JSON */ - public static RatePlan fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static RatePlan fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, RatePlan.class); @@ -84,14 +97,11 @@ public static RatePlan fromJson( * Converts a JSON InputStream into a RatePlan object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return RatePlan object represented by the provided JSON */ - public static RatePlan fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static RatePlan fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, RatePlan.class); @@ -102,112 +112,81 @@ public static RatePlan fromJson( } } - private final String sid; - private final String uniqueName; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String friendlyName; + @Getter private final Boolean dataEnabled; - private final String dataMetering; + @Getter private final Integer dataLimit; - private final Boolean messagingEnabled; - private final Boolean voiceEnabled; - private final Boolean nationalRoamingEnabled; - private final List internationalRoaming; + @Getter + private final String dataMetering; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; + @Getter + private final String friendlyName; + @Getter + private final List internationalRoaming; + @Getter + private final Boolean messagingEnabled; + @Getter + private final Boolean nationalRoamingEnabled; + @Getter + private final String sid; + @Getter + private final String uniqueName; + @Getter private final URI url; + @Getter + private final Boolean voiceEnabled; @JsonCreator private RatePlan( - @JsonProperty("sid") final String sid, - @JsonProperty("unique_name") final String uniqueName, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("data_enabled") final Boolean dataEnabled, - @JsonProperty("data_metering") final String dataMetering, - @JsonProperty("data_limit") final Integer dataLimit, - @JsonProperty("messaging_enabled") final Boolean messagingEnabled, - @JsonProperty("voice_enabled") final Boolean voiceEnabled, - @JsonProperty( - "national_roaming_enabled" - ) final Boolean nationalRoamingEnabled, - @JsonProperty("international_roaming") final List< - String - > internationalRoaming, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("url") final URI url + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("data_enabled") final Boolean dataEnabled, + @JsonProperty("data_limit") final Integer dataLimit, + @JsonProperty("data_metering") final String dataMetering, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("international_roaming") final List internationalRoaming, + @JsonProperty("messaging_enabled") final Boolean messagingEnabled, + @JsonProperty("national_roaming_enabled") final Boolean nationalRoamingEnabled, + @JsonProperty("sid") final String sid, + @JsonProperty("unique_name") final String uniqueName, + @JsonProperty("url") final URI url, + @JsonProperty("voice_enabled") final Boolean voiceEnabled ) { - this.sid = sid; - this.uniqueName = uniqueName; this.accountSid = accountSid; - this.friendlyName = friendlyName; this.dataEnabled = dataEnabled; - this.dataMetering = dataMetering; this.dataLimit = dataLimit; + this.dataMetering = dataMetering; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; + this.friendlyName = friendlyName; + this.internationalRoaming = internationalRoaming; this.messagingEnabled = messagingEnabled; - this.voiceEnabled = voiceEnabled; this.nationalRoamingEnabled = nationalRoamingEnabled; - this.internationalRoaming = internationalRoaming; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); + this.sid = sid; + this.uniqueName = uniqueName; this.url = url; - } - - public final String getSid() { - return this.sid; - } - - public final String getUniqueName() { - return this.uniqueName; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final Boolean getDataEnabled() { - return this.dataEnabled; - } - - public final String getDataMetering() { - return this.dataMetering; - } - - public final Integer getDataLimit() { - return this.dataLimit; - } - - public final Boolean getMessagingEnabled() { - return this.messagingEnabled; - } - - public final Boolean getVoiceEnabled() { - return this.voiceEnabled; - } - - public final Boolean getNationalRoamingEnabled() { - return this.nationalRoamingEnabled; - } - - public final List getInternationalRoaming() { - return this.internationalRoaming; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final URI getUrl() { - return this.url; + this.voiceEnabled = voiceEnabled; } @Override @@ -221,45 +200,44 @@ public boolean equals(final Object o) { } RatePlan other = (RatePlan) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(uniqueName, other.uniqueName) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(dataEnabled, other.dataEnabled) && - Objects.equals(dataMetering, other.dataMetering) && - Objects.equals(dataLimit, other.dataLimit) && - Objects.equals(messagingEnabled, other.messagingEnabled) && - Objects.equals(voiceEnabled, other.voiceEnabled) && - Objects.equals( - nationalRoamingEnabled, - other.nationalRoamingEnabled - ) && - Objects.equals(internationalRoaming, other.internationalRoaming) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(url, other.url) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(dataEnabled, other.dataEnabled) && + Objects.equals(dataLimit, other.dataLimit) && + Objects.equals(dataMetering, other.dataMetering) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(internationalRoaming, other.internationalRoaming) && + Objects.equals(messagingEnabled, other.messagingEnabled) && + Objects.equals(nationalRoamingEnabled, other.nationalRoamingEnabled) && + Objects.equals(sid, other.sid) && + Objects.equals(uniqueName, other.uniqueName) && + Objects.equals(url, other.url) && + Objects.equals(voiceEnabled, other.voiceEnabled) ); } @Override public int hashCode() { return Objects.hash( - sid, - uniqueName, - accountSid, - friendlyName, - dataEnabled, - dataMetering, - dataLimit, - messagingEnabled, - voiceEnabled, - nationalRoamingEnabled, - internationalRoaming, - dateCreated, - dateUpdated, - url + accountSid, + dataEnabled, + dataLimit, + dataMetering, + dateCreated, + dateUpdated, + friendlyName, + internationalRoaming, + messagingEnabled, + nationalRoamingEnabled, + sid, + uniqueName, + url, + voiceEnabled ); } + + } + diff --git a/src/main/java/com/twilio/rest/preview/wireless/RatePlanCreator.java b/src/main/java/com/twilio/rest/preview/wireless/RatePlanCreator.java index d23a059deb..d46eef30ac 100644 --- a/src/main/java/com/twilio/rest/preview/wireless/RatePlanCreator.java +++ b/src/main/java/com/twilio/rest/preview/wireless/RatePlanCreator.java @@ -14,9 +14,12 @@ package com.twilio.rest.preview.wireless; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; import com.twilio.converter.Promoter; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,7 +28,7 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -import java.util.List; + import java.util.List; public class RatePlanCreator extends Creator { @@ -41,144 +44,157 @@ public class RatePlanCreator extends Creator { private Boolean nationalRoamingEnabled; private List internationalRoaming; - public RatePlanCreator() {} + public RatePlanCreator() { + } + public RatePlanCreator setUniqueName(final String uniqueName) { this.uniqueName = uniqueName; return this; } + public RatePlanCreator setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + public RatePlanCreator setDataEnabled(final Boolean dataEnabled) { this.dataEnabled = dataEnabled; return this; } + public RatePlanCreator setDataLimit(final Integer dataLimit) { this.dataLimit = dataLimit; return this; } + public RatePlanCreator setDataMetering(final String dataMetering) { this.dataMetering = dataMetering; return this; } + public RatePlanCreator setMessagingEnabled(final Boolean messagingEnabled) { this.messagingEnabled = messagingEnabled; return this; } + public RatePlanCreator setVoiceEnabled(final Boolean voiceEnabled) { this.voiceEnabled = voiceEnabled; return this; } + public RatePlanCreator setCommandsEnabled(final Boolean commandsEnabled) { this.commandsEnabled = commandsEnabled; return this; } - public RatePlanCreator setNationalRoamingEnabled( - final Boolean nationalRoamingEnabled - ) { + + public RatePlanCreator setNationalRoamingEnabled(final Boolean nationalRoamingEnabled) { this.nationalRoamingEnabled = nationalRoamingEnabled; return this; } - public RatePlanCreator setInternationalRoaming( - final List internationalRoaming - ) { + + public RatePlanCreator setInternationalRoaming(final List internationalRoaming) { this.internationalRoaming = internationalRoaming; return this; } - public RatePlanCreator setInternationalRoaming( - final String internationalRoaming - ) { - return setInternationalRoaming( - Promoter.listOfOne(internationalRoaming) - ); + public RatePlanCreator setInternationalRoaming(final String internationalRoaming) { + return setInternationalRoaming(Promoter.listOfOne(internationalRoaming)); } @Override public RatePlan create(final TwilioRestClient client) { + String path = "/wireless/RatePlans"; + Request request = new Request( - HttpMethod.POST, - Domains.PREVIEW.toString(), - path + HttpMethod.POST, + Domains.PREVIEW.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "RatePlan creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("RatePlan creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return RatePlan.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return RatePlan.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (uniqueName != null) { - request.addPostParam("UniqueName", uniqueName); + Serializer.toString(request, "UniqueName", uniqueName, ParameterType.URLENCODED); } + + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + if (dataEnabled != null) { - request.addPostParam("DataEnabled", dataEnabled.toString()); + Serializer.toString(request, "DataEnabled", dataEnabled, ParameterType.URLENCODED); } + + if (dataLimit != null) { - request.addPostParam("DataLimit", dataLimit.toString()); + Serializer.toString(request, "DataLimit", dataLimit, ParameterType.URLENCODED); } + + if (dataMetering != null) { - request.addPostParam("DataMetering", dataMetering); + Serializer.toString(request, "DataMetering", dataMetering, ParameterType.URLENCODED); } + + if (messagingEnabled != null) { - request.addPostParam( - "MessagingEnabled", - messagingEnabled.toString() - ); + Serializer.toString(request, "MessagingEnabled", messagingEnabled, ParameterType.URLENCODED); } + + if (voiceEnabled != null) { - request.addPostParam("VoiceEnabled", voiceEnabled.toString()); + Serializer.toString(request, "VoiceEnabled", voiceEnabled, ParameterType.URLENCODED); } + + if (commandsEnabled != null) { - request.addPostParam("CommandsEnabled", commandsEnabled.toString()); + Serializer.toString(request, "CommandsEnabled", commandsEnabled, ParameterType.URLENCODED); } + + if (nationalRoamingEnabled != null) { - request.addPostParam( - "NationalRoamingEnabled", - nationalRoamingEnabled.toString() - ); + Serializer.toString(request, "NationalRoamingEnabled", nationalRoamingEnabled, ParameterType.URLENCODED); } + + if (internationalRoaming != null) { - for (String prop : internationalRoaming) { - request.addPostParam("InternationalRoaming", prop); + for (String param : internationalRoaming) { + Serializer.toString(request, "InternationalRoaming", param, ParameterType.URLENCODED); } } + } } diff --git a/src/main/java/com/twilio/rest/preview/wireless/RatePlanDeleter.java b/src/main/java/com/twilio/rest/preview/wireless/RatePlanDeleter.java index ffb83cafcc..f45b79eb70 100644 --- a/src/main/java/com/twilio/rest/preview/wireless/RatePlanDeleter.java +++ b/src/main/java/com/twilio/rest/preview/wireless/RatePlanDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.preview.wireless; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,40 +26,38 @@ public class RatePlanDeleter extends Deleter { - private String pathSid; + private String pathsid; - public RatePlanDeleter(final String pathSid) { - this.pathSid = pathSid; + public RatePlanDeleter(final String pathsid) { + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/wireless/RatePlans/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.PREVIEW.toString(), - path + HttpMethod.DELETE, + Domains.PREVIEW.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "RatePlan delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("RatePlan delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/preview/wireless/RatePlanFetcher.java b/src/main/java/com/twilio/rest/preview/wireless/RatePlanFetcher.java index f67542debd..a67e3217ab 100644 --- a/src/main/java/com/twilio/rest/preview/wireless/RatePlanFetcher.java +++ b/src/main/java/com/twilio/rest/preview/wireless/RatePlanFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.preview.wireless; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,47 +26,41 @@ public class RatePlanFetcher extends Fetcher { - private String pathSid; + private String pathsid; - public RatePlanFetcher(final String pathSid) { - this.pathSid = pathSid; + public RatePlanFetcher(final String pathsid) { + this.pathsid = pathsid; } + @Override public RatePlan fetch(final TwilioRestClient client) { + String path = "/wireless/RatePlans/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.PREVIEW.toString(), - path + HttpMethod.GET, + Domains.PREVIEW.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "RatePlan fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("RatePlan fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return RatePlan.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return RatePlan.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/preview/wireless/RatePlanReader.java b/src/main/java/com/twilio/rest/preview/wireless/RatePlanReader.java index e93615105b..602304cbae 100644 --- a/src/main/java/com/twilio/rest/preview/wireless/RatePlanReader.java +++ b/src/main/java/com/twilio/rest/preview/wireless/RatePlanReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -31,105 +32,83 @@ public class RatePlanReader extends Reader { private Long pageSize; - public RatePlanReader() {} + public RatePlanReader() { + } + public RatePlanReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/wireless/RatePlans"; + Request request = new Request( - HttpMethod.GET, - Domains.PREVIEW.toString(), - path + HttpMethod.GET, + Domains.PREVIEW.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "RatePlan read failed: Unable to connect to server" - ); + throw new ApiConnectionException("RatePlan read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "rate_plans", - response.getContent(), - RatePlan.class, - client.getObjectMapper() - ); + "rate_plans", + response.getContent(), + RatePlan.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.PREVIEW.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.PREVIEW.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/preview/wireless/RatePlanUpdater.java b/src/main/java/com/twilio/rest/preview/wireless/RatePlanUpdater.java index 3f9997afd0..cb7c52ce4b 100644 --- a/src/main/java/com/twilio/rest/preview/wireless/RatePlanUpdater.java +++ b/src/main/java/com/twilio/rest/preview/wireless/RatePlanUpdater.java @@ -16,6 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -26,69 +28,72 @@ import com.twilio.rest.Domains; public class RatePlanUpdater extends Updater { - - private String pathSid; + private String pathsid; private String uniqueName; private String friendlyName; - public RatePlanUpdater(final String pathSid) { - this.pathSid = pathSid; + public RatePlanUpdater(final String pathsid) { + this.pathsid = pathsid; } + public RatePlanUpdater setUniqueName(final String uniqueName) { this.uniqueName = uniqueName; return this; } + public RatePlanUpdater setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + @Override public RatePlan update(final TwilioRestClient client) { + String path = "/wireless/RatePlans/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.PREVIEW.toString(), - path + HttpMethod.POST, + Domains.PREVIEW.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "RatePlan update failed: Unable to connect to server" - ); + throw new ApiConnectionException("RatePlan update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return RatePlan.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return RatePlan.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (uniqueName != null) { - request.addPostParam("UniqueName", uniqueName); + Serializer.toString(request, "UniqueName", uniqueName, ParameterType.URLENCODED); } + + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/preview/wireless/Sim.java b/src/main/java/com/twilio/rest/preview/wireless/Sim.java index 0a11ea0d21..bd2dab5bc2 100644 --- a/src/main/java/com/twilio/rest/preview/wireless/Sim.java +++ b/src/main/java/com/twilio/rest/preview/wireless/Sim.java @@ -18,52 +18,58 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.http.HttpMethod; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Sim extends Resource { - private static final long serialVersionUID = 220976187959759L; - public static SimFetcher fetcher(final String pathSid) { - return new SimFetcher(pathSid); + public static SimFetcher fetcher(final String pathsid) { + return new SimFetcher( + pathsid + ); } + public static SimReader reader() { - return new SimReader(); + return new SimReader( + + ); } - public static SimUpdater updater(final String pathSid) { - return new SimUpdater(pathSid); + + public static SimUpdater updater(final String pathsid) { + return new SimUpdater( + pathsid + ); } + /** * Converts a JSON String into a Sim object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Sim object represented by the provided JSON */ - public static Sim fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Sim fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Sim.class); @@ -78,14 +84,11 @@ public static Sim fromJson( * Converts a JSON InputStream into a Sim object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Sim object represented by the provided JSON */ - public static Sim fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Sim fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Sim.class); @@ -96,168 +99,113 @@ public static Sim fromJson( } } - private final String sid; - private final String uniqueName; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String ratePlanSid; + @Getter + private final String commandsCallbackMethod; + @Getter + private final URI commandsCallbackUrl; + @Getter + private final ZonedDateTime dateCreated; + @Getter + private final ZonedDateTime dateUpdated; + @Getter + private final String eId; + @Getter private final String friendlyName; + @Getter private final String iccid; - private final String eId; - private final String status; - private final URI commandsCallbackUrl; - private final String commandsCallbackMethod; + @Getter + private final Map links; + @Getter + private final String ratePlanSid; + @Getter + private final String sid; + @Getter private final HttpMethod smsFallbackMethod; + @Getter private final URI smsFallbackUrl; + @Getter private final HttpMethod smsMethod; + @Getter private final URI smsUrl; + @Getter + private final String status; + @Getter + private final String uniqueName; + @Getter + private final URI url; + @Getter private final HttpMethod voiceFallbackMethod; + @Getter private final URI voiceFallbackUrl; + @Getter private final HttpMethod voiceMethod; + @Getter private final URI voiceUrl; - private final ZonedDateTime dateCreated; - private final ZonedDateTime dateUpdated; - private final URI url; - private final Map links; @JsonCreator private Sim( - @JsonProperty("sid") final String sid, - @JsonProperty("unique_name") final String uniqueName, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("rate_plan_sid") final String ratePlanSid, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("iccid") final String iccid, - @JsonProperty("e_id") final String eId, - @JsonProperty("status") final String status, - @JsonProperty("commands_callback_url") final URI commandsCallbackUrl, - @JsonProperty( - "commands_callback_method" - ) final String commandsCallbackMethod, - @JsonProperty("sms_fallback_method") final HttpMethod smsFallbackMethod, - @JsonProperty("sms_fallback_url") final URI smsFallbackUrl, - @JsonProperty("sms_method") final HttpMethod smsMethod, - @JsonProperty("sms_url") final URI smsUrl, - @JsonProperty( - "voice_fallback_method" - ) final HttpMethod voiceFallbackMethod, - @JsonProperty("voice_fallback_url") final URI voiceFallbackUrl, - @JsonProperty("voice_method") final HttpMethod voiceMethod, - @JsonProperty("voice_url") final URI voiceUrl, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("url") final URI url, - @JsonProperty("links") final Map links + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("commands_callback_method") final String commandsCallbackMethod, + @JsonProperty("commands_callback_url") final URI commandsCallbackUrl, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("e_id") final String eId, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("iccid") final String iccid, + @JsonProperty("links") final Map links, + @JsonProperty("rate_plan_sid") final String ratePlanSid, + @JsonProperty("sid") final String sid, + @JsonProperty("sms_fallback_method") final HttpMethod smsFallbackMethod, + @JsonProperty("sms_fallback_url") final URI smsFallbackUrl, + @JsonProperty("sms_method") final HttpMethod smsMethod, + @JsonProperty("sms_url") final URI smsUrl, + @JsonProperty("status") final String status, + @JsonProperty("unique_name") final String uniqueName, + @JsonProperty("url") final URI url, + @JsonProperty("voice_fallback_method") final HttpMethod voiceFallbackMethod, + @JsonProperty("voice_fallback_url") final URI voiceFallbackUrl, + @JsonProperty("voice_method") final HttpMethod voiceMethod, + @JsonProperty("voice_url") final URI voiceUrl ) { - this.sid = sid; - this.uniqueName = uniqueName; this.accountSid = accountSid; - this.ratePlanSid = ratePlanSid; + this.commandsCallbackMethod = commandsCallbackMethod; + this.commandsCallbackUrl = commandsCallbackUrl; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; + this.eId = eId; this.friendlyName = friendlyName; this.iccid = iccid; - this.eId = eId; - this.status = status; - this.commandsCallbackUrl = commandsCallbackUrl; - this.commandsCallbackMethod = commandsCallbackMethod; + this.links = links; + this.ratePlanSid = ratePlanSid; + this.sid = sid; this.smsFallbackMethod = smsFallbackMethod; this.smsFallbackUrl = smsFallbackUrl; this.smsMethod = smsMethod; this.smsUrl = smsUrl; + this.status = status; + this.uniqueName = uniqueName; + this.url = url; this.voiceFallbackMethod = voiceFallbackMethod; this.voiceFallbackUrl = voiceFallbackUrl; this.voiceMethod = voiceMethod; this.voiceUrl = voiceUrl; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); - this.url = url; - this.links = links; - } - - public final String getSid() { - return this.sid; - } - - public final String getUniqueName() { - return this.uniqueName; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getRatePlanSid() { - return this.ratePlanSid; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final String getIccid() { - return this.iccid; - } - - public final String getEId() { - return this.eId; - } - - public final String getStatus() { - return this.status; - } - - public final URI getCommandsCallbackUrl() { - return this.commandsCallbackUrl; - } - - public final String getCommandsCallbackMethod() { - return this.commandsCallbackMethod; - } - - public final HttpMethod getSmsFallbackMethod() { - return this.smsFallbackMethod; - } - - public final URI getSmsFallbackUrl() { - return this.smsFallbackUrl; - } - - public final HttpMethod getSmsMethod() { - return this.smsMethod; - } - - public final URI getSmsUrl() { - return this.smsUrl; - } - - public final HttpMethod getVoiceFallbackMethod() { - return this.voiceFallbackMethod; - } - - public final URI getVoiceFallbackUrl() { - return this.voiceFallbackUrl; - } - - public final HttpMethod getVoiceMethod() { - return this.voiceMethod; - } - - public final URI getVoiceUrl() { - return this.voiceUrl; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final URI getUrl() { - return this.url; - } - - public final Map getLinks() { - return this.links; } @Override @@ -271,61 +219,60 @@ public boolean equals(final Object o) { } Sim other = (Sim) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(uniqueName, other.uniqueName) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(ratePlanSid, other.ratePlanSid) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(iccid, other.iccid) && - Objects.equals(eId, other.eId) && - Objects.equals(status, other.status) && - Objects.equals(commandsCallbackUrl, other.commandsCallbackUrl) && - Objects.equals( - commandsCallbackMethod, - other.commandsCallbackMethod - ) && - Objects.equals(smsFallbackMethod, other.smsFallbackMethod) && - Objects.equals(smsFallbackUrl, other.smsFallbackUrl) && - Objects.equals(smsMethod, other.smsMethod) && - Objects.equals(smsUrl, other.smsUrl) && - Objects.equals(voiceFallbackMethod, other.voiceFallbackMethod) && - Objects.equals(voiceFallbackUrl, other.voiceFallbackUrl) && - Objects.equals(voiceMethod, other.voiceMethod) && - Objects.equals(voiceUrl, other.voiceUrl) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(url, other.url) && - Objects.equals(links, other.links) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(commandsCallbackMethod, other.commandsCallbackMethod) && + Objects.equals(commandsCallbackUrl, other.commandsCallbackUrl) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(eId, other.eId) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(iccid, other.iccid) && + Objects.equals(links, other.links) && + Objects.equals(ratePlanSid, other.ratePlanSid) && + Objects.equals(sid, other.sid) && + Objects.equals(smsFallbackMethod, other.smsFallbackMethod) && + Objects.equals(smsFallbackUrl, other.smsFallbackUrl) && + Objects.equals(smsMethod, other.smsMethod) && + Objects.equals(smsUrl, other.smsUrl) && + Objects.equals(status, other.status) && + Objects.equals(uniqueName, other.uniqueName) && + Objects.equals(url, other.url) && + Objects.equals(voiceFallbackMethod, other.voiceFallbackMethod) && + Objects.equals(voiceFallbackUrl, other.voiceFallbackUrl) && + Objects.equals(voiceMethod, other.voiceMethod) && + Objects.equals(voiceUrl, other.voiceUrl) ); } @Override public int hashCode() { return Objects.hash( - sid, - uniqueName, - accountSid, - ratePlanSid, - friendlyName, - iccid, - eId, - status, - commandsCallbackUrl, - commandsCallbackMethod, - smsFallbackMethod, - smsFallbackUrl, - smsMethod, - smsUrl, - voiceFallbackMethod, - voiceFallbackUrl, - voiceMethod, - voiceUrl, - dateCreated, - dateUpdated, - url, - links + accountSid, + commandsCallbackMethod, + commandsCallbackUrl, + dateCreated, + dateUpdated, + eId, + friendlyName, + iccid, + links, + ratePlanSid, + sid, + smsFallbackMethod, + smsFallbackUrl, + smsMethod, + smsUrl, + status, + uniqueName, + url, + voiceFallbackMethod, + voiceFallbackUrl, + voiceMethod, + voiceUrl ); } + + } + diff --git a/src/main/java/com/twilio/rest/preview/wireless/SimFetcher.java b/src/main/java/com/twilio/rest/preview/wireless/SimFetcher.java index 0ec47ad61d..7db187f49a 100644 --- a/src/main/java/com/twilio/rest/preview/wireless/SimFetcher.java +++ b/src/main/java/com/twilio/rest/preview/wireless/SimFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.preview.wireless; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,44 +26,41 @@ public class SimFetcher extends Fetcher { - private String pathSid; + private String pathsid; - public SimFetcher(final String pathSid) { - this.pathSid = pathSid; + public SimFetcher(final String pathsid) { + this.pathsid = pathsid; } + @Override public Sim fetch(final TwilioRestClient client) { + String path = "/wireless/Sims/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.PREVIEW.toString(), - path + HttpMethod.GET, + Domains.PREVIEW.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Sim fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Sim fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Sim.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/preview/wireless/SimReader.java b/src/main/java/com/twilio/rest/preview/wireless/SimReader.java index f46d500f6d..4ab665c78d 100644 --- a/src/main/java/com/twilio/rest/preview/wireless/SimReader.java +++ b/src/main/java/com/twilio/rest/preview/wireless/SimReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -36,145 +37,138 @@ public class SimReader extends Reader { private String simRegistrationCode; private Long pageSize; - public SimReader() {} + public SimReader() { + } + public SimReader setStatus(final String status) { this.status = status; return this; } + public SimReader setIccid(final String iccid) { this.iccid = iccid; return this; } + public SimReader setRatePlan(final String ratePlan) { this.ratePlan = ratePlan; return this; } + public SimReader setEid(final String eid) { this.eid = eid; return this; } + public SimReader setSimRegistrationCode(final String simRegistrationCode) { this.simRegistrationCode = simRegistrationCode; return this; } + public SimReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/wireless/Sims"; + Request request = new Request( - HttpMethod.GET, - Domains.PREVIEW.toString(), - path + HttpMethod.GET, + Domains.PREVIEW.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Sim read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Sim read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "sims", - response.getContent(), - Sim.class, - client.getObjectMapper() - ); + "sims", + response.getContent(), + Sim.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.PREVIEW.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.PREVIEW.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (status != null) { - request.addQueryParam("Status", status); + Serializer.toString(request, "Status", status, ParameterType.QUERY); } + + if (iccid != null) { - request.addQueryParam("Iccid", iccid); + Serializer.toString(request, "Iccid", iccid, ParameterType.QUERY); } + + if (ratePlan != null) { - request.addQueryParam("RatePlan", ratePlan); + Serializer.toString(request, "RatePlan", ratePlan, ParameterType.QUERY); } + + if (eid != null) { - request.addQueryParam("EId", eid); + Serializer.toString(request, "EId", eid, ParameterType.QUERY); } + + if (simRegistrationCode != null) { - request.addQueryParam("SimRegistrationCode", simRegistrationCode); + Serializer.toString(request, "SimRegistrationCode", simRegistrationCode, ParameterType.QUERY); } + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/preview/wireless/SimUpdater.java b/src/main/java/com/twilio/rest/preview/wireless/SimUpdater.java index d3bae173f1..8eb9ecb9d4 100644 --- a/src/main/java/com/twilio/rest/preview/wireless/SimUpdater.java +++ b/src/main/java/com/twilio/rest/preview/wireless/SimUpdater.java @@ -16,7 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; -import com.twilio.converter.Promoter; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,11 +26,11 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.net.URI; public class SimUpdater extends Updater { - - private String pathSid; + private String pathsid; private String uniqueName; private String callbackMethod; private URI callbackUrl; @@ -47,148 +48,134 @@ public class SimUpdater extends Updater { private HttpMethod voiceMethod; private URI voiceUrl; - public SimUpdater(final String pathSid) { - this.pathSid = pathSid; + public SimUpdater(final String pathsid) { + this.pathsid = pathsid; } + public SimUpdater setUniqueName(final String uniqueName) { this.uniqueName = uniqueName; return this; } + public SimUpdater setCallbackMethod(final String callbackMethod) { this.callbackMethod = callbackMethod; return this; } + public SimUpdater setCallbackUrl(final URI callbackUrl) { this.callbackUrl = callbackUrl; return this; } - public SimUpdater setCallbackUrl(final String callbackUrl) { - return setCallbackUrl(Promoter.uriFromString(callbackUrl)); - } public SimUpdater setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + public SimUpdater setRatePlan(final String ratePlan) { this.ratePlan = ratePlan; return this; } + public SimUpdater setStatus(final String status) { this.status = status; return this; } - public SimUpdater setCommandsCallbackMethod( - final HttpMethod commandsCallbackMethod - ) { + + public SimUpdater setCommandsCallbackMethod(final HttpMethod commandsCallbackMethod) { this.commandsCallbackMethod = commandsCallbackMethod; return this; } + public SimUpdater setCommandsCallbackUrl(final URI commandsCallbackUrl) { this.commandsCallbackUrl = commandsCallbackUrl; return this; } - public SimUpdater setCommandsCallbackUrl(final String commandsCallbackUrl) { - return setCommandsCallbackUrl( - Promoter.uriFromString(commandsCallbackUrl) - ); - } public SimUpdater setSmsFallbackMethod(final HttpMethod smsFallbackMethod) { this.smsFallbackMethod = smsFallbackMethod; return this; } + public SimUpdater setSmsFallbackUrl(final URI smsFallbackUrl) { this.smsFallbackUrl = smsFallbackUrl; return this; } - public SimUpdater setSmsFallbackUrl(final String smsFallbackUrl) { - return setSmsFallbackUrl(Promoter.uriFromString(smsFallbackUrl)); - } public SimUpdater setSmsMethod(final HttpMethod smsMethod) { this.smsMethod = smsMethod; return this; } + public SimUpdater setSmsUrl(final URI smsUrl) { this.smsUrl = smsUrl; return this; } - public SimUpdater setSmsUrl(final String smsUrl) { - return setSmsUrl(Promoter.uriFromString(smsUrl)); - } - public SimUpdater setVoiceFallbackMethod( - final HttpMethod voiceFallbackMethod - ) { + public SimUpdater setVoiceFallbackMethod(final HttpMethod voiceFallbackMethod) { this.voiceFallbackMethod = voiceFallbackMethod; return this; } + public SimUpdater setVoiceFallbackUrl(final URI voiceFallbackUrl) { this.voiceFallbackUrl = voiceFallbackUrl; return this; } - public SimUpdater setVoiceFallbackUrl(final String voiceFallbackUrl) { - return setVoiceFallbackUrl(Promoter.uriFromString(voiceFallbackUrl)); - } public SimUpdater setVoiceMethod(final HttpMethod voiceMethod) { this.voiceMethod = voiceMethod; return this; } + public SimUpdater setVoiceUrl(final URI voiceUrl) { this.voiceUrl = voiceUrl; return this; } - public SimUpdater setVoiceUrl(final String voiceUrl) { - return setVoiceUrl(Promoter.uriFromString(voiceUrl)); - } @Override public Sim update(final TwilioRestClient client) { + String path = "/wireless/Sims/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.PREVIEW.toString(), - path + HttpMethod.POST, + Domains.PREVIEW.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Sim update failed: Unable to connect to server" - ); + throw new ApiConnectionException("Sim update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -197,68 +184,86 @@ public Sim update(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (uniqueName != null) { - request.addPostParam("UniqueName", uniqueName); + Serializer.toString(request, "UniqueName", uniqueName, ParameterType.URLENCODED); } + + if (callbackMethod != null) { - request.addPostParam("CallbackMethod", callbackMethod); + Serializer.toString(request, "CallbackMethod", callbackMethod, ParameterType.URLENCODED); } + + if (callbackUrl != null) { - request.addPostParam("CallbackUrl", callbackUrl.toString()); + Serializer.toString(request, "CallbackUrl", callbackUrl, ParameterType.URLENCODED); } + + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + if (ratePlan != null) { - request.addPostParam("RatePlan", ratePlan); + Serializer.toString(request, "RatePlan", ratePlan, ParameterType.URLENCODED); } + + if (status != null) { - request.addPostParam("Status", status); + Serializer.toString(request, "Status", status, ParameterType.URLENCODED); } + + if (commandsCallbackMethod != null) { - request.addPostParam( - "CommandsCallbackMethod", - commandsCallbackMethod.toString() - ); + Serializer.toString(request, "CommandsCallbackMethod", commandsCallbackMethod, ParameterType.URLENCODED); } + + if (commandsCallbackUrl != null) { - request.addPostParam( - "CommandsCallbackUrl", - commandsCallbackUrl.toString() - ); + Serializer.toString(request, "CommandsCallbackUrl", commandsCallbackUrl, ParameterType.URLENCODED); } + + if (smsFallbackMethod != null) { - request.addPostParam( - "SmsFallbackMethod", - smsFallbackMethod.toString() - ); + Serializer.toString(request, "SmsFallbackMethod", smsFallbackMethod, ParameterType.URLENCODED); } + + if (smsFallbackUrl != null) { - request.addPostParam("SmsFallbackUrl", smsFallbackUrl.toString()); + Serializer.toString(request, "SmsFallbackUrl", smsFallbackUrl, ParameterType.URLENCODED); } + + if (smsMethod != null) { - request.addPostParam("SmsMethod", smsMethod.toString()); + Serializer.toString(request, "SmsMethod", smsMethod, ParameterType.URLENCODED); } + + if (smsUrl != null) { - request.addPostParam("SmsUrl", smsUrl.toString()); + Serializer.toString(request, "SmsUrl", smsUrl, ParameterType.URLENCODED); } + + if (voiceFallbackMethod != null) { - request.addPostParam( - "VoiceFallbackMethod", - voiceFallbackMethod.toString() - ); + Serializer.toString(request, "VoiceFallbackMethod", voiceFallbackMethod, ParameterType.URLENCODED); } + + if (voiceFallbackUrl != null) { - request.addPostParam( - "VoiceFallbackUrl", - voiceFallbackUrl.toString() - ); + Serializer.toString(request, "VoiceFallbackUrl", voiceFallbackUrl, ParameterType.URLENCODED); } + + if (voiceMethod != null) { - request.addPostParam("VoiceMethod", voiceMethod.toString()); + Serializer.toString(request, "VoiceMethod", voiceMethod, ParameterType.URLENCODED); } + + if (voiceUrl != null) { - request.addPostParam("VoiceUrl", voiceUrl.toString()); + Serializer.toString(request, "VoiceUrl", voiceUrl, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/preview/wireless/sim/Usage.java b/src/main/java/com/twilio/rest/preview/wireless/sim/Usage.java index c2683da2c1..428af790e4 100644 --- a/src/main/java/com/twilio/rest/preview/wireless/sim/Usage.java +++ b/src/main/java/com/twilio/rest/preview/wireless/sim/Usage.java @@ -18,41 +18,40 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; -import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Usage extends Resource { - private static final long serialVersionUID = 23834274390782L; - public static UsageFetcher fetcher(final String pathSimSid) { - return new UsageFetcher(pathSimSid); + public static UsageFetcher fetcher(final String pathsimSid) { + return new UsageFetcher( + pathsimSid + ); } + /** * Converts a JSON String into a Usage object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Usage object represented by the provided JSON */ - public static Usage fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Usage fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Usage.class); @@ -67,14 +66,11 @@ public static Usage fromJson( * Converts a JSON InputStream into a Usage object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Usage object represented by the provided JSON */ - public static Usage fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Usage fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Usage.class); @@ -85,75 +81,61 @@ public static Usage fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter + private final String accountSid; + @Getter + private final Object commandsCosts; + @Getter + private final Object commandsUsage; + @Getter + private final Object dataCosts; + @Getter + private final Object dataUsage; + @Getter + private final Object period; + @Getter private final String simSid; + @Getter private final String simUniqueName; - private final String accountSid; - private final Map period; - private final Map commandsUsage; - private final Map commandsCosts; - private final Map dataUsage; - private final Map dataCosts; + @Getter private final URI url; @JsonCreator private Usage( - @JsonProperty("sim_sid") final String simSid, - @JsonProperty("sim_unique_name") final String simUniqueName, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("period") final Map period, - @JsonProperty("commands_usage") final Map commandsUsage, - @JsonProperty("commands_costs") final Map commandsCosts, - @JsonProperty("data_usage") final Map dataUsage, - @JsonProperty("data_costs") final Map dataCosts, - @JsonProperty("url") final URI url + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("commands_costs") final Object commandsCosts, + @JsonProperty("commands_usage") final Object commandsUsage, + @JsonProperty("data_costs") final Object dataCosts, + @JsonProperty("data_usage") final Object dataUsage, + @JsonProperty("period") final Object period, + @JsonProperty("sim_sid") final String simSid, + @JsonProperty("sim_unique_name") final String simUniqueName, + @JsonProperty("url") final URI url ) { - this.simSid = simSid; - this.simUniqueName = simUniqueName; this.accountSid = accountSid; - this.period = period; - this.commandsUsage = commandsUsage; this.commandsCosts = commandsCosts; - this.dataUsage = dataUsage; + this.commandsUsage = commandsUsage; this.dataCosts = dataCosts; + this.dataUsage = dataUsage; + this.period = period; + this.simSid = simSid; + this.simUniqueName = simUniqueName; this.url = url; } - public final String getSimSid() { - return this.simSid; - } - - public final String getSimUniqueName() { - return this.simUniqueName; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final Map getPeriod() { - return this.period; - } - - public final Map getCommandsUsage() { - return this.commandsUsage; - } - - public final Map getCommandsCosts() { - return this.commandsCosts; - } - - public final Map getDataUsage() { - return this.dataUsage; - } - - public final Map getDataCosts() { - return this.dataCosts; - } - - public final URI getUrl() { - return this.url; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -165,32 +147,34 @@ public boolean equals(final Object o) { } Usage other = (Usage) o; - return ( - Objects.equals(simSid, other.simSid) && - Objects.equals(simUniqueName, other.simUniqueName) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(period, other.period) && - Objects.equals(commandsUsage, other.commandsUsage) && - Objects.equals(commandsCosts, other.commandsCosts) && - Objects.equals(dataUsage, other.dataUsage) && - Objects.equals(dataCosts, other.dataCosts) && - Objects.equals(url, other.url) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(commandsCosts, other.commandsCosts) && + Objects.equals(commandsUsage, other.commandsUsage) && + Objects.equals(dataCosts, other.dataCosts) && + Objects.equals(dataUsage, other.dataUsage) && + Objects.equals(period, other.period) && + Objects.equals(simSid, other.simSid) && + Objects.equals(simUniqueName, other.simUniqueName) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - simSid, - simUniqueName, - accountSid, - period, - commandsUsage, - commandsCosts, - dataUsage, - dataCosts, - url + accountSid, + commandsCosts, + commandsUsage, + dataCosts, + dataUsage, + period, + simSid, + simUniqueName, + url ); } + + } + diff --git a/src/main/java/com/twilio/rest/preview/wireless/sim/UsageFetcher.java b/src/main/java/com/twilio/rest/preview/wireless/sim/UsageFetcher.java index 935e1082f3..0dea61fe25 100644 --- a/src/main/java/com/twilio/rest/preview/wireless/sim/UsageFetcher.java +++ b/src/main/java/com/twilio/rest/preview/wireless/sim/UsageFetcher.java @@ -15,7 +15,8 @@ package com.twilio.rest.preview.wireless.sim; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,66 +28,71 @@ public class UsageFetcher extends Fetcher { - private String pathSimSid; + private String pathsimSid; private String end; private String start; - public UsageFetcher(final String pathSimSid) { - this.pathSimSid = pathSimSid; + public UsageFetcher(final String pathsimSid) { + this.pathsimSid = pathsimSid; } + public UsageFetcher setEnd(final String end) { this.end = end; return this; } + public UsageFetcher setStart(final String start) { this.start = start; return this; } + @Override public Usage fetch(final TwilioRestClient client) { + String path = "/wireless/Sims/{SimSid}/Usage"; - path = path.replace("{" + "SimSid" + "}", this.pathSimSid.toString()); + path = path.replace("{" + "SimSid" + "}", this.pathsimSid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.PREVIEW.toString(), - path + HttpMethod.GET, + Domains.PREVIEW.toString(), + path ); addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Usage fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Usage fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Usage.fromJson(response.getStream(), client.getObjectMapper()); } private void addQueryParams(final Request request) { + + if (end != null) { - request.addQueryParam("End", end); + Serializer.toString(request, "End", end, ParameterType.QUERY); } + + if (start != null) { - request.addQueryParam("Start", start); + Serializer.toString(request, "Start", start, ParameterType.QUERY); } + + } } diff --git a/src/main/java/com/twilio/rest/previewiam/organizations/Account.java b/src/main/java/com/twilio/rest/previewiam/organizations/Account.java index bffd937287..27bad0e38f 100644 --- a/src/main/java/com/twilio/rest/previewiam/organizations/Account.java +++ b/src/main/java/com/twilio/rest/previewiam/organizations/Account.java @@ -18,48 +18,72 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.time.ZonedDateTime; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Account extends Resource { - private static final long serialVersionUID = 140632441815443L; - public static AccountFetcher fetcher( - final String pathOrganizationSid, - final String pathAccountSid - ) { - return new AccountFetcher(pathOrganizationSid, pathAccountSid); + public static AccountFetcher fetcher(final String pathorganizationSid, final String pathaccountSid) { + return new AccountFetcher( + pathorganizationSid, pathaccountSid + ); + } + + + public static AccountReader reader(final String pathorganizationSid) { + return new AccountReader( + pathorganizationSid + ); } - public static AccountReader reader(final String pathOrganizationSid) { - return new AccountReader(pathOrganizationSid); + + public enum Status { + ACTIVE("active"), + SUSPENDED("suspended"), + PENDING_CLOSURE("pending_closure"), + CLOSED("closed"); + + private final String value; + + private Status(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static Status forValue(final String value) { + return Promoter.enumFromString(value, Status.values()); + } } + /** * Converts a JSON String into a Account object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Account object represented by the provided JSON */ - public static Account fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Account fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Account.class); @@ -74,14 +98,11 @@ public static Account fromJson( * Converts a JSON InputStream into a Account object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Account object represented by the provided JSON */ - public static Account fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Account fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Account.class); @@ -92,45 +113,44 @@ public static Account fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; + @Getter + private final ZonedDateTime dateCreated; + @Getter private final String friendlyName; - private final Account.StatusEnum status; + @Getter private final String ownerSid; - private final ZonedDateTime dateCreated; + @Getter + private final Account.Status status; @JsonCreator private Account( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("status") final Account.StatusEnum status, - @JsonProperty("owner_sid") final String ownerSid, - @JsonProperty("date_created") final String dateCreated + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("owner_sid") final String ownerSid, + @JsonProperty("status") final Account.Status status ) { this.accountSid = accountSid; + this.dateCreated = dateCreated; this.friendlyName = friendlyName; - this.status = status; this.ownerSid = ownerSid; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final Account.StatusEnum getStatus() { - return this.status; - } - - public final String getOwnerSid() { - return this.ownerSid; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; + this.status = status; } @Override @@ -144,46 +164,26 @@ public boolean equals(final Object o) { } Account other = (Account) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(status, other.status) && - Objects.equals(ownerSid, other.ownerSid) && - Objects.equals(dateCreated, other.dateCreated) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(ownerSid, other.ownerSid) && + Objects.equals(status, other.status) ); } @Override public int hashCode() { return Objects.hash( - accountSid, - friendlyName, - status, - ownerSid, - dateCreated + accountSid, + dateCreated, + friendlyName, + ownerSid, + status ); } - public enum StatusEnum { - ACTIVE("active"), - SUSPENDED("suspended"), - PENDING_CLOSURE("pending_closure"), - CLOSED("closed"); - - private final String value; - - private StatusEnum(final String value) { - this.value = value; - } - public String toString() { - return value; - } - - @JsonCreator - public static StatusEnum forValue(final String value) { - return Promoter.enumFromString(value, StatusEnum.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/previewiam/organizations/AccountFetcher.java b/src/main/java/com/twilio/rest/previewiam/organizations/AccountFetcher.java index 1949891f1d..2cb2e1f7ec 100644 --- a/src/main/java/com/twilio/rest/previewiam/organizations/AccountFetcher.java +++ b/src/main/java/com/twilio/rest/previewiam/organizations/AccountFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.previewiam.organizations; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,60 +26,44 @@ public class AccountFetcher extends Fetcher { - private String pathOrganizationSid; - private String pathAccountSid; + private String pathorganizationSid; + private String pathaccountSid; - public AccountFetcher( - final String pathOrganizationSid, - final String pathAccountSid - ) { - this.pathOrganizationSid = pathOrganizationSid; - this.pathAccountSid = pathAccountSid; + public AccountFetcher(final String pathorganizationSid, final String pathaccountSid) { + this.pathorganizationSid = pathorganizationSid; + this.pathaccountSid = pathaccountSid; } + @Override public Account fetch(final TwilioRestClient client) { + String path = "/Organizations/{OrganizationSid}/Accounts/{AccountSid}"; - path = - path.replace( - "{" + "OrganizationSid" + "}", - this.pathOrganizationSid.toString() - ); - path = - path.replace( - "{" + "AccountSid" + "}", - this.pathAccountSid.toString() - ); + path = path.replace("{" + "OrganizationSid" + "}", this.pathorganizationSid.toString()); + path = path.replace("{" + "AccountSid" + "}", this.pathaccountSid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.PREVIEWIAM.toString(), - path + HttpMethod.GET, + Domains.PREVIEWIAM.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Account fetch failed: Unable to connect to server" - ); - } else if ( - !TwilioRestClient.SUCCESS.test(response.getStatusCode()) - ) { + throw new ApiConnectionException("Account fetch failed: Unable to connect to server"); + } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Account.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/previewiam/organizations/AccountReader.java b/src/main/java/com/twilio/rest/previewiam/organizations/AccountReader.java index 7c2a384f3f..3771bf606e 100644 --- a/src/main/java/com/twilio/rest/previewiam/organizations/AccountReader.java +++ b/src/main/java/com/twilio/rest/previewiam/organizations/AccountReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,120 +30,88 @@ public class AccountReader extends Reader { - private String pathOrganizationSid; + private String pathorganizationSid; private Integer pageSize; - public AccountReader(final String pathOrganizationSid) { - this.pathOrganizationSid = pathOrganizationSid; + public AccountReader(final String pathorganizationSid) { + this.pathorganizationSid = pathorganizationSid; } + public AccountReader setPageSize(final Integer pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/Organizations/{OrganizationSid}/Accounts"; - path = - path.replace( - "{" + "OrganizationSid" + "}", - this.pathOrganizationSid.toString() - ); + + path = path.replace("{" + "OrganizationSid" + "}", this.pathorganizationSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.PREVIEWIAM.toString(), - path + HttpMethod.GET, + Domains.PREVIEWIAM.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Account read failed: Unable to connect to server" - ); - } else if ( - !TwilioRestClient.SUCCESS.test(response.getStatusCode()) - ) { + throw new ApiConnectionException("Account read failed: Unable to connect to server"); + } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "content", - response.getContent(), - Account.class, - client.getObjectMapper() - ); + "content", + response.getContent(), + Account.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.PREVIEWIAM.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.PREVIEWIAM.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - targetUrl - ); - + public Page getPage(final String targetUrl, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, targetUrl); return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/previewiam/organizations/RoleAssignment.java b/src/main/java/com/twilio/rest/previewiam/organizations/RoleAssignment.java index 882781fe09..9198e6f48f 100644 --- a/src/main/java/com/twilio/rest/previewiam/organizations/RoleAssignment.java +++ b/src/main/java/com/twilio/rest/previewiam/organizations/RoleAssignment.java @@ -25,22 +25,49 @@ import com.twilio.base.Resource; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; -import java.io.IOException; -import java.io.InputStream; -import java.util.Objects; import lombok.Getter; import lombok.Setter; import lombok.ToString; -import lombok.ToString; + +import java.io.IOException; +import java.io.InputStream; +import java.util.Objects; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class RoleAssignment extends Resource { - private static final long serialVersionUID = 175566213667704L; + public static RoleAssignmentCreator creator(final String pathorganizationSid, final RoleAssignment.PublicApiCreateRoleAssignmentRequest publicApiCreateRoleAssignmentRequest) { + return new RoleAssignmentCreator( + pathorganizationSid, publicApiCreateRoleAssignmentRequest + ); + } + + + public static RoleAssignmentDeleter deleter(final String pathorganizationSid, final String pathroleAssignmentSid) { + return new RoleAssignmentDeleter( + pathorganizationSid, pathroleAssignmentSid + ); + } + + + public static RoleAssignmentReader reader(final String pathorganizationSid) { + return new RoleAssignmentReader( + pathorganizationSid + ); + } + + + //@JsonDeserialize(builder = PublicApiCreateRoleAssignmentRequest.Builder.class) + @JsonInclude(JsonInclude.Include.NON_EMPTY) @ToString public static class PublicApiCreateRoleAssignmentRequest { + public PublicApiCreateRoleAssignmentRequest(final String roleSid, final String scope, final String identity) { + this.roleSid = roleSid; + this.scope = scope; + this.identity = identity; + } @JsonInclude(JsonInclude.Include.NON_EMPTY) @JsonProperty("role_sid") @@ -60,64 +87,16 @@ public static class PublicApiCreateRoleAssignmentRequest { @Setter private String identity; - public PublicApiCreateRoleAssignmentRequest( - final String roleSid, - final String scope, - final String identity - ) { - this.roleSid = roleSid; - this.scope = scope; - this.identity = identity; - } - - public static PublicApiCreateRoleAssignmentRequest fromJson( - String jsonString, - ObjectMapper mapper - ) throws IOException { - return mapper.readValue( - jsonString, - PublicApiCreateRoleAssignmentRequest.class - ); - } - } - - public static RoleAssignmentCreator creator( - final String pathOrganizationSid, - final RoleAssignment.PublicApiCreateRoleAssignmentRequest publicApiCreateRoleAssignmentRequest - ) { - return new RoleAssignmentCreator( - pathOrganizationSid, - publicApiCreateRoleAssignmentRequest - ); - } - - public static RoleAssignmentDeleter deleter( - final String pathOrganizationSid, - final String pathRoleAssignmentSid - ) { - return new RoleAssignmentDeleter( - pathOrganizationSid, - pathRoleAssignmentSid - ); - } - - public static RoleAssignmentReader reader( - final String pathOrganizationSid - ) { - return new RoleAssignmentReader(pathOrganizationSid); } /** * Converts a JSON String into a RoleAssignment object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return RoleAssignment object represented by the provided JSON */ - public static RoleAssignment fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static RoleAssignment fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, RoleAssignment.class); @@ -132,14 +111,11 @@ public static RoleAssignment fromJson( * Converts a JSON InputStream into a RoleAssignment object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return RoleAssignment object represented by the provided JSON */ - public static RoleAssignment fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static RoleAssignment fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, RoleAssignment.class); @@ -162,38 +138,27 @@ public static String toJson(Object object, ObjectMapper mapper) { } } - private final String sid; + + @Getter + private final String identity; + @Getter private final String roleSid; + @Getter private final String scope; - private final String identity; + @Getter + private final String sid; @JsonCreator private RoleAssignment( - @JsonProperty("sid") final String sid, - @JsonProperty("role_sid") final String roleSid, - @JsonProperty("scope") final String scope, - @JsonProperty("identity") final String identity + @JsonProperty("identity") final String identity, + @JsonProperty("role_sid") final String roleSid, + @JsonProperty("scope") final String scope, + @JsonProperty("sid") final String sid ) { - this.sid = sid; + this.identity = identity; this.roleSid = roleSid; this.scope = scope; - this.identity = identity; - } - - public final String getSid() { - return this.sid; - } - - public final String getRoleSid() { - return this.roleSid; - } - - public final String getScope() { - return this.scope; - } - - public final String getIdentity() { - return this.identity; + this.sid = sid; } @Override @@ -207,17 +172,24 @@ public boolean equals(final Object o) { } RoleAssignment other = (RoleAssignment) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(roleSid, other.roleSid) && - Objects.equals(scope, other.scope) && - Objects.equals(identity, other.identity) + Objects.equals(identity, other.identity) && + Objects.equals(roleSid, other.roleSid) && + Objects.equals(scope, other.scope) && + Objects.equals(sid, other.sid) ); } @Override public int hashCode() { - return Objects.hash(sid, roleSid, scope, identity); + return Objects.hash( + identity, + roleSid, + scope, + sid + ); } + + } + diff --git a/src/main/java/com/twilio/rest/previewiam/organizations/RoleAssignmentCreator.java b/src/main/java/com/twilio/rest/previewiam/organizations/RoleAssignmentCreator.java index 1a22c181ed..58cee82e22 100644 --- a/src/main/java/com/twilio/rest/previewiam/organizations/RoleAssignmentCreator.java +++ b/src/main/java/com/twilio/rest/previewiam/organizations/RoleAssignmentCreator.java @@ -28,87 +28,59 @@ public class RoleAssignmentCreator extends Creator { - private String pathOrganizationSid; + private String pathorganizationSid; private RoleAssignment.PublicApiCreateRoleAssignmentRequest publicApiCreateRoleAssignmentRequest; - public RoleAssignmentCreator( - final String pathOrganizationSid, - final RoleAssignment.PublicApiCreateRoleAssignmentRequest publicApiCreateRoleAssignmentRequest - ) { - this.pathOrganizationSid = pathOrganizationSid; - this.publicApiCreateRoleAssignmentRequest = - publicApiCreateRoleAssignmentRequest; + public RoleAssignmentCreator(final String pathorganizationSid, final RoleAssignment.PublicApiCreateRoleAssignmentRequest publicApiCreateRoleAssignmentRequest) { + this.pathorganizationSid = pathorganizationSid; + this.publicApiCreateRoleAssignmentRequest = publicApiCreateRoleAssignmentRequest; } - public RoleAssignmentCreator setPublicApiCreateRoleAssignmentRequest( - final RoleAssignment.PublicApiCreateRoleAssignmentRequest publicApiCreateRoleAssignmentRequest - ) { - this.publicApiCreateRoleAssignmentRequest = - publicApiCreateRoleAssignmentRequest; + + public RoleAssignmentCreator setPublicApiCreateRoleAssignmentRequest(final RoleAssignment.PublicApiCreateRoleAssignmentRequest publicApiCreateRoleAssignmentRequest) { + this.publicApiCreateRoleAssignmentRequest = publicApiCreateRoleAssignmentRequest; return this; } + @Override public RoleAssignment create(final TwilioRestClient client) { + String path = "/Organizations/{OrganizationSid}/RoleAssignments"; - path = - path.replace( - "{" + "OrganizationSid" + "}", - this.pathOrganizationSid.toString() - ); - path = - path.replace( - "{" + "PublicApiCreateRoleAssignmentRequest" + "}", - this.publicApiCreateRoleAssignmentRequest.toString() - ); + path = path.replace("{" + "OrganizationSid" + "}", this.pathorganizationSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.PREVIEWIAM.toString(), - path + HttpMethod.POST, + Domains.PREVIEWIAM.toString(), + path ); request.setContentType(EnumConstants.ContentType.JSON); addPostParams(request, client); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "RoleAssignment creation failed: Unable to connect to server" - ); - } else if ( - !TwilioRestClient.SUCCESS.test(response.getStatusCode()) - ) { + throw new ApiConnectionException("RoleAssignment creation failed: Unable to connect to server"); + } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return RoleAssignment.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return RoleAssignment.fromJson(response.getStream(), client.getObjectMapper()); } - private void addPostParams( - final Request request, - TwilioRestClient client - ) { + private void addPostParams(final Request request, TwilioRestClient client) { ObjectMapper objectMapper = client.getObjectMapper(); if (publicApiCreateRoleAssignmentRequest != null) { - request.setBody( - RoleAssignment.toJson( - publicApiCreateRoleAssignmentRequest, - objectMapper - ) - ); + request.setBody(RoleAssignment.toJson(publicApiCreateRoleAssignmentRequest, objectMapper)); } } } diff --git a/src/main/java/com/twilio/rest/previewiam/organizations/RoleAssignmentDeleter.java b/src/main/java/com/twilio/rest/previewiam/organizations/RoleAssignmentDeleter.java index 514bacadf6..36c65d9d9f 100644 --- a/src/main/java/com/twilio/rest/previewiam/organizations/RoleAssignmentDeleter.java +++ b/src/main/java/com/twilio/rest/previewiam/organizations/RoleAssignmentDeleter.java @@ -15,69 +15,52 @@ package com.twilio.rest.previewiam.organizations; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; import com.twilio.http.HttpMethod; -import com.twilio.http.Response; import com.twilio.http.Request; +import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; public class RoleAssignmentDeleter extends Deleter { - private String pathOrganizationSid; - private String pathRoleAssignmentSid; + private String pathorganizationSid; + private String pathroleAssignmentSid; - public RoleAssignmentDeleter( - final String pathOrganizationSid, - final String pathRoleAssignmentSid - ) { - this.pathOrganizationSid = pathOrganizationSid; - this.pathRoleAssignmentSid = pathRoleAssignmentSid; + public RoleAssignmentDeleter(final String pathorganizationSid, final String pathroleAssignmentSid) { + this.pathorganizationSid = pathorganizationSid; + this.pathroleAssignmentSid = pathroleAssignmentSid; } + @Override public boolean delete(final TwilioRestClient client) { - String path = - "/Organizations/{OrganizationSid}/RoleAssignments/{RoleAssignmentSid}"; - path = - path.replace( - "{" + "OrganizationSid" + "}", - this.pathOrganizationSid.toString() - ); - path = - path.replace( - "{" + "RoleAssignmentSid" + "}", - this.pathRoleAssignmentSid.toString() - ); + String path = "/Organizations/{OrganizationSid}/RoleAssignments/{RoleAssignmentSid}"; + + path = path.replace("{" + "OrganizationSid" + "}", this.pathorganizationSid.toString()); + path = path.replace("{" + "RoleAssignmentSid" + "}", this.pathroleAssignmentSid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.PREVIEWIAM.toString(), - path + HttpMethod.DELETE, + Domains.PREVIEWIAM.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "RoleAssignment delete failed: Unable to connect to server" - ); - } else if ( - !TwilioRestClient.SUCCESS.test(response.getStatusCode()) - ) { + throw new ApiConnectionException("RoleAssignment delete failed: Unable to connect to server"); + } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/previewiam/organizations/RoleAssignmentReader.java b/src/main/java/com/twilio/rest/previewiam/organizations/RoleAssignmentReader.java index e10fca0991..ee855fc25f 100644 --- a/src/main/java/com/twilio/rest/previewiam/organizations/RoleAssignmentReader.java +++ b/src/main/java/com/twilio/rest/previewiam/organizations/RoleAssignmentReader.java @@ -17,154 +17,125 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; import com.twilio.http.HttpMethod; -import com.twilio.http.Response; import com.twilio.http.Request; +import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; public class RoleAssignmentReader extends Reader { - private String pathOrganizationSid; + private String pathorganizationSid; private Integer pageSize; private String identity; private String scope; - public RoleAssignmentReader(final String pathOrganizationSid) { - this.pathOrganizationSid = pathOrganizationSid; + public RoleAssignmentReader(final String pathorganizationSid) { + this.pathorganizationSid = pathorganizationSid; } + public RoleAssignmentReader setPageSize(final Integer pageSize) { this.pageSize = pageSize; return this; } + public RoleAssignmentReader setIdentity(final String identity) { this.identity = identity; return this; } + public RoleAssignmentReader setScope(final String scope) { this.scope = scope; return this; } + @Override - public ResourceSet read( - final TwilioRestClient client - ) { + public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } - public Page firstPage( - final TwilioRestClient client - ) { + public Page firstPage(final TwilioRestClient client) { + String path = "/Organizations/{OrganizationSid}/RoleAssignments"; - path = - path.replace( - "{" + "OrganizationSid" + "}", - this.pathOrganizationSid.toString() - ); + + path = path.replace("{" + "OrganizationSid" + "}", this.pathorganizationSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.PREVIEWIAM.toString(), - path + HttpMethod.GET, + Domains.PREVIEWIAM.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "RoleAssignment read failed: Unable to connect to server" - ); - } else if ( - !TwilioRestClient.SUCCESS.test(response.getStatusCode()) - ) { + throw new ApiConnectionException("RoleAssignment read failed: Unable to connect to server"); + } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "content", - response.getContent(), - RoleAssignment.class, - client.getObjectMapper() - ); + "content", + response.getContent(), + RoleAssignment.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.PREVIEWIAM.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.PREVIEWIAM.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - targetUrl - ); - + public Page getPage(final String targetUrl, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, targetUrl); return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } + + if (identity != null) { - request.addQueryParam("Identity", identity); + Serializer.toString(request, "Identity", identity, ParameterType.QUERY); } + + if (scope != null) { - request.addQueryParam("Scope", scope); + Serializer.toString(request, "Scope", scope, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/previewiam/organizations/User.java b/src/main/java/com/twilio/rest/previewiam/organizations/User.java index 94359dbbbf..1c130295f3 100644 --- a/src/main/java/com/twilio/rest/previewiam/organizations/User.java +++ b/src/main/java/com/twilio/rest/previewiam/organizations/User.java @@ -22,118 +22,67 @@ import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.time.ZonedDateTime; import java.util.List; import java.util.Objects; -import lombok.Getter; -import lombok.Setter; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class User extends Resource { - private static final long serialVersionUID = 281207691925540L; - - @ToString - public static class ScimName { - @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("givenName") - @Getter - @Setter - private String givenName; - - @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("familyName") - @Getter - @Setter - private String familyName; - - public static ScimName fromJson(String jsonString, ObjectMapper mapper) - throws IOException { - return mapper.readValue(jsonString, ScimName.class); - } + public static UserCreator creator(final String pathorganizationSid, final User.ScimUser scimUser) { + return new UserCreator( + pathorganizationSid, scimUser + ); } - @ToString - public static class ScimEmailAddress { - @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("primary") - @Getter - @Setter - private Boolean primary; - - @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("value") - @Getter - @Setter - private String value; - - @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("type") - @Getter - @Setter - private String type; - - public static ScimEmailAddress fromJson( - String jsonString, - ObjectMapper mapper - ) throws IOException { - return mapper.readValue(jsonString, ScimEmailAddress.class); - } + public static UserDeleter deleter(final String pathorganizationSid, final String pathuserSid) { + return new UserDeleter( + pathorganizationSid, pathuserSid + ); } - @ToString - public static class ScimMeta { - - @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("resourceType") - @Getter - @Setter - private String resourceType; - - @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("created") - @Getter - @Setter - private ZonedDateTime created; - public String getCreated() { - return created.toInstant().toString(); - } + public static UserFetcher fetcher(final String pathorganizationSid, final String pathuserSid) { + return new UserFetcher( + pathorganizationSid, pathuserSid + ); + } - @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("lastModified") - @Getter - @Setter - private ZonedDateTime lastModified; - public String getLastModified() { - return lastModified.toInstant().toString(); - } + public static UserReader reader(final String pathorganizationSid) { + return new UserReader( + pathorganizationSid + ); + } - @JsonInclude(JsonInclude.Include.NON_EMPTY) - @JsonProperty("version") - @Getter - @Setter - private String version; - public static ScimMeta fromJson(String jsonString, ObjectMapper mapper) - throws IOException { - return mapper.readValue(jsonString, ScimMeta.class); - } + public static UserUpdater updater(final String pathorganizationSid, final String pathuserSid, final User.ScimUser scimUser) { + return new UserUpdater( + pathorganizationSid, pathuserSid, scimUser + ); } + + //@JsonDeserialize(builder = ScimUser.Builder.class) + @JsonInclude(JsonInclude.Include.NON_EMPTY) @ToString public static class ScimUser { + public ScimUser(final String userName) { + this.userName = userName; + } @JsonInclude(JsonInclude.Include.NON_EMPTY) @JsonProperty("id") @@ -201,60 +150,93 @@ public static class ScimUser { @Setter private ScimMeta meta; - public ScimUser(final String userName) { - this.userName = userName; - } - - public static ScimUser fromJson(String jsonString, ObjectMapper mapper) - throws IOException { - return mapper.readValue(jsonString, ScimUser.class); - } } - public static UserCreator creator( - final String pathOrganizationSid, - final User.ScimUser scimUser - ) { - return new UserCreator(pathOrganizationSid, scimUser); - } + //@JsonDeserialize(builder = ScimEmailAddress.Builder.class) + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @ToString + public static class ScimEmailAddress { - public static UserDeleter deleter( - final String pathOrganizationSid, - final String pathUserSid - ) { - return new UserDeleter(pathOrganizationSid, pathUserSid); - } + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("primary") + @Getter + @Setter + private Boolean primary; + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("value") + @Getter + @Setter + private String value; + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("type") + @Getter + @Setter + private String type; - public static UserFetcher fetcher( - final String pathOrganizationSid, - final String pathUserSid - ) { - return new UserFetcher(pathOrganizationSid, pathUserSid); } - public static UserReader reader(final String pathOrganizationSid) { - return new UserReader(pathOrganizationSid); + //@JsonDeserialize(builder = ScimMeta.Builder.class) + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @ToString + public static class ScimMeta { + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("resourceType") + @Getter + @Setter + private String resourceType; + + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("created") + @Getter + @Setter + private ZonedDateTime created; + + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("lastModified") + @Getter + @Setter + private ZonedDateTime lastModified; + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("version") + @Getter + @Setter + private String version; + } - public static UserUpdater updater( - final String pathOrganizationSid, - final String pathUserSid, - final User.ScimUser scimUser - ) { - return new UserUpdater(pathOrganizationSid, pathUserSid, scimUser); + //@JsonDeserialize(builder = ScimName.Builder.class) + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @ToString + public static class ScimName { + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("givenName") + @Getter + @Setter + private String givenName; + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("familyName") + @Getter + @Setter + private String familyName; + } /** * Converts a JSON String into a User object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return User object represented by the provided JSON */ - public static User fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static User fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, User.class); @@ -269,14 +251,11 @@ public static User fromJson( * Converts a JSON InputStream into a User object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return User object represented by the provided JSON */ - public static User fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static User fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, User.class); @@ -299,87 +278,55 @@ public static String toJson(Object object, ObjectMapper mapper) { } } - private final String id; - private final String externalId; - private final String userName; + + @Getter + private final Boolean active; + @Getter private final String displayName; - private final ScimName name; + @Getter private final List emails; - private final Boolean active; + @Getter + private final String externalId; + @Getter + private final String id; + @Getter private final String locale; - private final String timezone; - private final List schemas; + @Getter private final ScimMeta meta; + @Getter + private final ScimName name; + @Getter + private final List schemas; + @Getter + private final String timezone; + @Getter + private final String userName; @JsonCreator private User( - @JsonProperty("id") final String id, - @JsonProperty("external_id") final String externalId, - @JsonProperty("user_name") final String userName, - @JsonProperty("display_name") final String displayName, - @JsonProperty("name") final ScimName name, - @JsonProperty("emails") final List emails, - @JsonProperty("active") final Boolean active, - @JsonProperty("locale") final String locale, - @JsonProperty("timezone") final String timezone, - @JsonProperty("schemas") final List schemas, - @JsonProperty("meta") final ScimMeta meta + @JsonProperty("active") final Boolean active, + @JsonProperty("displayName") final String displayName, + @JsonProperty("emails") final List emails, + @JsonProperty("externalId") final String externalId, + @JsonProperty("id") final String id, + @JsonProperty("locale") final String locale, + @JsonProperty("meta") final ScimMeta meta, + @JsonProperty("name") final ScimName name, + @JsonProperty("schemas") final List schemas, + @JsonProperty("timezone") final String timezone, + @JsonProperty("userName") final String userName ) { - this.id = id; - this.externalId = externalId; - this.userName = userName; + this.active = active; this.displayName = displayName; - this.name = name; this.emails = emails; - this.active = active; + this.externalId = externalId; + this.id = id; this.locale = locale; - this.timezone = timezone; - this.schemas = schemas; this.meta = meta; - } - - public final String getId() { - return this.id; - } - - public final String getExternalId() { - return this.externalId; - } - - public final String getUserName() { - return this.userName; - } - - public final String getDisplayName() { - return this.displayName; - } - - public final ScimName getName() { - return this.name; - } - - public final List getEmails() { - return this.emails; - } - - public final Boolean getActive() { - return this.active; - } - - public final String getLocale() { - return this.locale; - } - - public final String getTimezone() { - return this.timezone; - } - - public final List getSchemas() { - return this.schemas; - } - - public final ScimMeta getMeta() { - return this.meta; + this.name = name; + this.schemas = schemas; + this.timezone = timezone; + this.userName = userName; } @Override @@ -393,36 +340,38 @@ public boolean equals(final Object o) { } User other = (User) o; - return ( - Objects.equals(id, other.id) && - Objects.equals(externalId, other.externalId) && - Objects.equals(userName, other.userName) && - Objects.equals(displayName, other.displayName) && - Objects.equals(name, other.name) && - Objects.equals(emails, other.emails) && - Objects.equals(active, other.active) && - Objects.equals(locale, other.locale) && - Objects.equals(timezone, other.timezone) && - Objects.equals(schemas, other.schemas) && - Objects.equals(meta, other.meta) + Objects.equals(active, other.active) && + Objects.equals(displayName, other.displayName) && + Objects.equals(emails, other.emails) && + Objects.equals(externalId, other.externalId) && + Objects.equals(id, other.id) && + Objects.equals(locale, other.locale) && + Objects.equals(meta, other.meta) && + Objects.equals(name, other.name) && + Objects.equals(schemas, other.schemas) && + Objects.equals(timezone, other.timezone) && + Objects.equals(userName, other.userName) ); } @Override public int hashCode() { return Objects.hash( - id, - externalId, - userName, - displayName, - name, - emails, - active, - locale, - timezone, - schemas, - meta + active, + displayName, + emails, + externalId, + id, + locale, + meta, + name, + schemas, + timezone, + userName ); } + + } + diff --git a/src/main/java/com/twilio/rest/previewiam/organizations/UserCreator.java b/src/main/java/com/twilio/rest/previewiam/organizations/UserCreator.java index e768088a50..67bf5b0022 100644 --- a/src/main/java/com/twilio/rest/previewiam/organizations/UserCreator.java +++ b/src/main/java/com/twilio/rest/previewiam/organizations/UserCreator.java @@ -21,64 +21,55 @@ import com.twilio.exception.ApiException; import com.twilio.exception.RestException; import com.twilio.http.HttpMethod; +import com.twilio.http.Request; import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; -import com.twilio.http.Request; import com.twilio.rest.Domains; public class UserCreator extends Creator { - private String pathOrganizationSid; + private String pathorganizationSid; private User.ScimUser scimUser; - public UserCreator( - final String pathOrganizationSid, - final User.ScimUser scimUser - ) { - this.pathOrganizationSid = pathOrganizationSid; + public UserCreator(final String pathorganizationSid, final User.ScimUser scimUser) { + this.pathorganizationSid = pathorganizationSid; this.scimUser = scimUser; } + public UserCreator setScimUser(final User.ScimUser scimUser) { this.scimUser = scimUser; return this; } + @Override public User create(final TwilioRestClient client) { + String path = "/Organizations/{OrganizationSid}/scim/Users"; - path = - path.replace( - "{" + "OrganizationSid" + "}", - this.pathOrganizationSid.toString() - ); - path = path.replace("{" + "ScimUser" + "}", this.scimUser.toString()); + path = path.replace("{" + "OrganizationSid" + "}", this.pathorganizationSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.PREVIEWIAM.toString(), - path + HttpMethod.POST, + Domains.PREVIEWIAM.toString(), + path ); request.setContentType(EnumConstants.ContentType.JSON); addPostParams(request, client); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "User creation failed: Unable to connect to server" - ); - } else if ( - !TwilioRestClient.SUCCESS.test(response.getStatusCode()) - ) { + throw new ApiConnectionException("User creation failed: Unable to connect to server"); + } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -86,10 +77,7 @@ public User create(final TwilioRestClient client) { return User.fromJson(response.getStream(), client.getObjectMapper()); } - private void addPostParams( - final Request request, - TwilioRestClient client - ) { + private void addPostParams(final Request request, TwilioRestClient client) { ObjectMapper objectMapper = client.getObjectMapper(); if (scimUser != null) { request.setBody(User.toJson(scimUser, objectMapper)); diff --git a/src/main/java/com/twilio/rest/previewiam/organizations/UserDeleter.java b/src/main/java/com/twilio/rest/previewiam/organizations/UserDeleter.java index dcb8c56787..62ec5a973f 100644 --- a/src/main/java/com/twilio/rest/previewiam/organizations/UserDeleter.java +++ b/src/main/java/com/twilio/rest/previewiam/organizations/UserDeleter.java @@ -15,64 +15,52 @@ package com.twilio.rest.previewiam.organizations; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; import com.twilio.http.HttpMethod; -import com.twilio.http.Response; import com.twilio.http.Request; +import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; public class UserDeleter extends Deleter { - private String pathOrganizationSid; - private String pathUserSid; + private String pathorganizationSid; + private String pathuserSid; - public UserDeleter( - final String pathOrganizationSid, - final String pathUserSid - ) { - this.pathOrganizationSid = pathOrganizationSid; - this.pathUserSid = pathUserSid; + public UserDeleter(final String pathorganizationSid, final String pathuserSid) { + this.pathorganizationSid = pathorganizationSid; + this.pathuserSid = pathuserSid; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/Organizations/{OrganizationSid}/scim/Users/{UserSid}"; - path = - path.replace( - "{" + "OrganizationSid" + "}", - this.pathOrganizationSid.toString() - ); - path = path.replace("{" + "UserSid" + "}", this.pathUserSid.toString()); + path = path.replace("{" + "OrganizationSid" + "}", this.pathorganizationSid.toString()); + path = path.replace("{" + "UserSid" + "}", this.pathuserSid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.PREVIEWIAM.toString(), - path + HttpMethod.DELETE, + Domains.PREVIEWIAM.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "User delete failed: Unable to connect to server" - ); - } else if ( - !TwilioRestClient.SUCCESS.test(response.getStatusCode()) - ) { + throw new ApiConnectionException("User delete failed: Unable to connect to server"); + } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/previewiam/organizations/UserFetcher.java b/src/main/java/com/twilio/rest/previewiam/organizations/UserFetcher.java index 0270ac88dc..c6fdaf2dae 100644 --- a/src/main/java/com/twilio/rest/previewiam/organizations/UserFetcher.java +++ b/src/main/java/com/twilio/rest/previewiam/organizations/UserFetcher.java @@ -15,68 +15,55 @@ package com.twilio.rest.previewiam.organizations; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; import com.twilio.http.HttpMethod; -import com.twilio.http.Response; import com.twilio.http.Request; +import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; public class UserFetcher extends Fetcher { - private String pathOrganizationSid; - private String pathUserSid; + private String pathorganizationSid; + private String pathuserSid; - public UserFetcher( - final String pathOrganizationSid, - final String pathUserSid - ) { - this.pathOrganizationSid = pathOrganizationSid; - this.pathUserSid = pathUserSid; + public UserFetcher(final String pathorganizationSid, final String pathuserSid) { + this.pathorganizationSid = pathorganizationSid; + this.pathuserSid = pathuserSid; } + @Override public User fetch(final TwilioRestClient client) { + String path = "/Organizations/{OrganizationSid}/scim/Users/{UserSid}"; - path = - path.replace( - "{" + "OrganizationSid" + "}", - this.pathOrganizationSid.toString() - ); - path = path.replace("{" + "UserSid" + "}", this.pathUserSid.toString()); + path = path.replace("{" + "OrganizationSid" + "}", this.pathorganizationSid.toString()); + path = path.replace("{" + "UserSid" + "}", this.pathuserSid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.PREVIEWIAM.toString(), - path + HttpMethod.GET, + Domains.PREVIEWIAM.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "User fetch failed: Unable to connect to server" - ); - } else if ( - !TwilioRestClient.SUCCESS.test(response.getStatusCode()) - ) { + throw new ApiConnectionException("User fetch failed: Unable to connect to server"); + } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return User.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/previewiam/organizations/UserReader.java b/src/main/java/com/twilio/rest/previewiam/organizations/UserReader.java index c6bb6a57eb..1785903888 100644 --- a/src/main/java/com/twilio/rest/previewiam/organizations/UserReader.java +++ b/src/main/java/com/twilio/rest/previewiam/organizations/UserReader.java @@ -17,132 +17,101 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; import com.twilio.http.HttpMethod; -import com.twilio.http.Response; import com.twilio.http.Request; +import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; public class UserReader extends Reader { - private String pathOrganizationSid; + private String pathorganizationSid; private String filter; - public UserReader(final String pathOrganizationSid) { - this.pathOrganizationSid = pathOrganizationSid; + public UserReader(final String pathorganizationSid) { + this.pathorganizationSid = pathorganizationSid; } + public UserReader setFilter(final String filter) { this.filter = filter; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/Organizations/{OrganizationSid}/scim/Users"; - path = - path.replace( - "{" + "OrganizationSid" + "}", - this.pathOrganizationSid.toString() - ); + + path = path.replace("{" + "OrganizationSid" + "}", this.pathorganizationSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.PREVIEWIAM.toString(), - path + HttpMethod.GET, + Domains.PREVIEWIAM.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "User read failed: Unable to connect to server" - ); - } else if ( - !TwilioRestClient.SUCCESS.test(response.getStatusCode()) - ) { + throw new ApiConnectionException("User read failed: Unable to connect to server"); + } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "Resources", - response.getContent(), - User.class, - client.getObjectMapper() - ); + "Resources", + response.getContent(), + User.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.PREVIEWIAM.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.PREVIEWIAM.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - targetUrl - ); - + public Page getPage(final String targetUrl, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, targetUrl); return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (filter != null) { - request.addQueryParam("filter", filter); + Serializer.toString(request, "filter", filter, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/previewiam/organizations/UserUpdater.java b/src/main/java/com/twilio/rest/previewiam/organizations/UserUpdater.java index 9b3c2a0d4b..0ee24209f4 100644 --- a/src/main/java/com/twilio/rest/previewiam/organizations/UserUpdater.java +++ b/src/main/java/com/twilio/rest/previewiam/organizations/UserUpdater.java @@ -17,79 +17,71 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; import com.twilio.http.HttpMethod; -import com.twilio.http.Response; import com.twilio.http.Request; +import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; public class UserUpdater extends Updater { - - private String pathOrganizationSid; - private String pathUserSid; - private User.ScimUser scimUser; + private String pathorganizationSid; + private String pathuserSid; private String ifMatch; + private User.ScimUser scimUser; - public UserUpdater( - final String pathOrganizationSid, - final String pathUserSid, - final User.ScimUser scimUser - ) { - this.pathOrganizationSid = pathOrganizationSid; - this.pathUserSid = pathUserSid; + public UserUpdater(final String pathorganizationSid, final String pathuserSid, final User.ScimUser scimUser) { + this.pathorganizationSid = pathorganizationSid; + this.pathuserSid = pathuserSid; this.scimUser = scimUser; } + public UserUpdater setScimUser(final User.ScimUser scimUser) { this.scimUser = scimUser; return this; } + public UserUpdater setIfMatch(final String ifMatch) { this.ifMatch = ifMatch; return this; } + @Override public User update(final TwilioRestClient client) { + String path = "/Organizations/{OrganizationSid}/scim/Users/{UserSid}"; - path = - path.replace( - "{" + "OrganizationSid" + "}", - this.pathOrganizationSid.toString() - ); - path = path.replace("{" + "UserSid" + "}", this.pathUserSid.toString()); - path = path.replace("{" + "ScimUser" + "}", this.scimUser.toString()); + path = path.replace("{" + "OrganizationSid" + "}", this.pathorganizationSid.toString()); + path = path.replace("{" + "UserSid" + "}", this.pathuserSid.toString()); + Request request = new Request( - HttpMethod.PUT, - Domains.PREVIEWIAM.toString(), - path + HttpMethod.PUT, + Domains.PREVIEWIAM.toString(), + path ); request.setContentType(EnumConstants.ContentType.JSON); - addPostParams(request, client); addHeaderParams(request); + addPostParams(request, client); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "User update failed: Unable to connect to server" - ); - } else if ( - !TwilioRestClient.SUCCESS.test(response.getStatusCode()) - ) { + throw new ApiConnectionException("User update failed: Unable to connect to server"); + } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -97,19 +89,18 @@ public User update(final TwilioRestClient client) { return User.fromJson(response.getStream(), client.getObjectMapper()); } - private void addPostParams( - final Request request, - TwilioRestClient client - ) { - ObjectMapper objectMapper = client.getObjectMapper(); - if (scimUser != null) { - request.setBody(User.toJson(scimUser, objectMapper)); + private void addHeaderParams(final Request request) { + + if (ifMatch != null) { + Serializer.toString(request, "If-Match", ifMatch, ParameterType.HEADER); } + } - private void addHeaderParams(final Request request) { - if (ifMatch != null) { - request.addHeaderParam("If-Match", ifMatch); + private void addPostParams(final Request request, TwilioRestClient client) { + ObjectMapper objectMapper = client.getObjectMapper(); + if (scimUser != null) { + request.setBody(User.toJson(scimUser, objectMapper)); } } } diff --git a/src/main/java/com/twilio/rest/previewiam/v1/Authorize.java b/src/main/java/com/twilio/rest/previewiam/v1/Authorize.java index 7c41e281bc..ffed94d28d 100644 --- a/src/main/java/com/twilio/rest/previewiam/v1/Authorize.java +++ b/src/main/java/com/twilio/rest/previewiam/v1/Authorize.java @@ -18,39 +18,40 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Authorize extends Resource { - private static final long serialVersionUID = 245900587626041L; public static AuthorizeFetcher fetcher() { - return new AuthorizeFetcher(); + return new AuthorizeFetcher( + + ); } + /** * Converts a JSON String into a Authorize object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Authorize object represented by the provided JSON */ - public static Authorize fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Authorize fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Authorize.class); @@ -65,14 +66,11 @@ public static Authorize fromJson( * Converts a JSON InputStream into a Authorize object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Authorize object represented by the provided JSON */ - public static Authorize fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Authorize fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Authorize.class); @@ -83,17 +81,29 @@ public static Authorize fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final URI redirectTo; @JsonCreator - private Authorize(@JsonProperty("redirect_to") final URI redirectTo) { + private Authorize( + @JsonProperty("redirect_to") final URI redirectTo + ) { this.redirectTo = redirectTo; } - public final URI getRedirectTo() { - return this.redirectTo; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -105,12 +115,18 @@ public boolean equals(final Object o) { } Authorize other = (Authorize) o; - - return Objects.equals(redirectTo, other.redirectTo); + return ( + Objects.equals(redirectTo, other.redirectTo) + ); } @Override public int hashCode() { - return Objects.hash(redirectTo); + return Objects.hash( + redirectTo + ); } + + } + diff --git a/src/main/java/com/twilio/rest/previewiam/v1/AuthorizeFetcher.java b/src/main/java/com/twilio/rest/previewiam/v1/AuthorizeFetcher.java index ff85651635..a57ee42882 100644 --- a/src/main/java/com/twilio/rest/previewiam/v1/AuthorizeFetcher.java +++ b/src/main/java/com/twilio/rest/previewiam/v1/AuthorizeFetcher.java @@ -16,14 +16,15 @@ import com.twilio.auth_strategy.NoAuthStrategy; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; import com.twilio.http.HttpMethod; +import com.twilio.http.Request; import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; -import com.twilio.http.Request; import com.twilio.rest.Domains; public class AuthorizeFetcher extends Fetcher { @@ -34,88 +35,98 @@ public class AuthorizeFetcher extends Fetcher { private String scope; private String state; - public AuthorizeFetcher() {} + public AuthorizeFetcher() { + } + public AuthorizeFetcher setResponseType(final String responseType) { this.responseType = responseType; return this; } + public AuthorizeFetcher setClientId(final String clientId) { this.clientId = clientId; return this; } + public AuthorizeFetcher setRedirectUri(final String redirectUri) { this.redirectUri = redirectUri; return this; } + public AuthorizeFetcher setScope(final String scope) { this.scope = scope; return this; } + public AuthorizeFetcher setState(final String state) { this.state = state; return this; } + @Override public Authorize fetch(final TwilioRestClient client) { + String path = "/v1/authorize"; + Request request = new Request( - HttpMethod.GET, - Domains.PREVIEWIAM.toString(), - path + HttpMethod.GET, + Domains.PREVIEWIAM.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); request.setAuth(NoAuthStrategy.getInstance()); + addQueryParams(request); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Authorize fetch failed: Unable to connect to server" - ); - } else if ( - !TwilioRestClient.SUCCESS.test(response.getStatusCode()) - ) { + throw new ApiConnectionException("Authorize fetch failed: Unable to connect to server"); + } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return Authorize.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Authorize.fromJson(response.getStream(), client.getObjectMapper()); } private void addQueryParams(final Request request) { + + if (responseType != null) { - request.addQueryParam("response_type", responseType); + Serializer.toString(request, "response_type", responseType, ParameterType.QUERY); } + + if (clientId != null) { - request.addQueryParam("client_id", clientId); + Serializer.toString(request, "client_id", clientId, ParameterType.QUERY); } + + if (redirectUri != null) { - request.addQueryParam("redirect_uri", redirectUri); + Serializer.toString(request, "redirect_uri", redirectUri, ParameterType.QUERY); } + + if (scope != null) { - request.addQueryParam("scope", scope); + Serializer.toString(request, "scope", scope, ParameterType.QUERY); } + + if (state != null) { - request.addQueryParam("state", state); + Serializer.toString(request, "state", state, ParameterType.QUERY); } + + } } diff --git a/src/main/java/com/twilio/rest/previewiam/v1/Token.java b/src/main/java/com/twilio/rest/previewiam/v1/Token.java index 99349efcdc..98ed50b874 100644 --- a/src/main/java/com/twilio/rest/previewiam/v1/Token.java +++ b/src/main/java/com/twilio/rest/previewiam/v1/Token.java @@ -18,41 +18,39 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Token extends Resource { - private static final long serialVersionUID = 258139119277894L; - public static TokenCreator creator( - final String grantType, - final String clientId - ) { - return new TokenCreator(grantType, clientId); + public static TokenCreator creator(final String grantType, final String clientId) { + return new TokenCreator( + grantType, clientId + ); } + /** * Converts a JSON String into a Token object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Token object represented by the provided JSON */ - public static Token fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Token fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Token.class); @@ -67,14 +65,11 @@ public static Token fromJson( * Converts a JSON InputStream into a Token object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Token object represented by the provided JSON */ - public static Token fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Token fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Token.class); @@ -85,45 +80,43 @@ public static Token fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accessToken; - private final String refreshToken; + @Getter + private final Long expiresIn; + @Getter private final String idToken; + @Getter + private final String refreshToken; + @Getter private final String tokenType; - private final Long expiresIn; @JsonCreator private Token( - @JsonProperty("access_token") final String accessToken, - @JsonProperty("refresh_token") final String refreshToken, - @JsonProperty("id_token") final String idToken, - @JsonProperty("token_type") final String tokenType, - @JsonProperty("expires_in") final Long expiresIn + @JsonProperty("access_token") final String accessToken, + @JsonProperty("expires_in") final Long expiresIn, + @JsonProperty("id_token") final String idToken, + @JsonProperty("refresh_token") final String refreshToken, + @JsonProperty("token_type") final String tokenType ) { this.accessToken = accessToken; - this.refreshToken = refreshToken; + this.expiresIn = expiresIn; this.idToken = idToken; + this.refreshToken = refreshToken; this.tokenType = tokenType; - this.expiresIn = expiresIn; - } - - public final String getAccessToken() { - return this.accessToken; - } - - public final String getRefreshToken() { - return this.refreshToken; - } - - public final String getIdToken() { - return this.idToken; - } - - public final String getTokenType() { - return this.tokenType; - } - - public final Long getExpiresIn() { - return this.expiresIn; } @Override @@ -137,24 +130,26 @@ public boolean equals(final Object o) { } Token other = (Token) o; - return ( - Objects.equals(accessToken, other.accessToken) && - Objects.equals(refreshToken, other.refreshToken) && - Objects.equals(idToken, other.idToken) && - Objects.equals(tokenType, other.tokenType) && - Objects.equals(expiresIn, other.expiresIn) + Objects.equals(accessToken, other.accessToken) && + Objects.equals(expiresIn, other.expiresIn) && + Objects.equals(idToken, other.idToken) && + Objects.equals(refreshToken, other.refreshToken) && + Objects.equals(tokenType, other.tokenType) ); } @Override public int hashCode() { return Objects.hash( - accessToken, - refreshToken, - idToken, - tokenType, - expiresIn + accessToken, + expiresIn, + idToken, + refreshToken, + tokenType ); } + + } + diff --git a/src/main/java/com/twilio/rest/previewiam/v1/TokenCreator.java b/src/main/java/com/twilio/rest/previewiam/v1/TokenCreator.java index 74e8715b2c..5ee163e3b6 100644 --- a/src/main/java/com/twilio/rest/previewiam/v1/TokenCreator.java +++ b/src/main/java/com/twilio/rest/previewiam/v1/TokenCreator.java @@ -14,18 +14,19 @@ package com.twilio.rest.previewiam.v1; + import com.twilio.auth_strategy.NoAuthStrategy; import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; import com.twilio.http.HttpMethod; -import com.twilio.http.Response; -import com.twilio.http.TwilioRestClient; import com.twilio.http.Request; +import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; -import com.twilio.http.Request; import com.twilio.rest.Domains; public class TokenCreator extends Creator { @@ -44,79 +45,81 @@ public TokenCreator(final String grantType, final String clientId) { this.clientId = clientId; } + public TokenCreator setGrantType(final String grantType) { this.grantType = grantType; return this; } + public TokenCreator setClientId(final String clientId) { this.clientId = clientId; return this; } + public TokenCreator setClientSecret(final String clientSecret) { this.clientSecret = clientSecret; return this; } + public TokenCreator setCode(final String code) { this.code = code; return this; } + public TokenCreator setRedirectUri(final String redirectUri) { this.redirectUri = redirectUri; return this; } + public TokenCreator setAudience(final String audience) { this.audience = audience; return this; } + public TokenCreator setRefreshToken(final String refreshToken) { this.refreshToken = refreshToken; return this; } + public TokenCreator setScope(final String scope) { this.scope = scope; return this; } + @Override public Token create(final TwilioRestClient client) { + String path = "/v1/token"; - path = - path.replace("{" + "grant_type" + "}", this.grantType.toString()); - path = path.replace("{" + "client_id" + "}", this.clientId.toString()); Request request = new Request( - HttpMethod.POST, - Domains.PREVIEWIAM.toString(), - path + HttpMethod.POST, + Domains.PREVIEWIAM.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); request.setAuth(NoAuthStrategy.getInstance()); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Token creation failed: Unable to connect to server" - ); - } else if ( - !TwilioRestClient.SUCCESS.test(response.getStatusCode()) - ) { + throw new ApiConnectionException("Token creation failed: Unable to connect to server"); + } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -125,29 +128,46 @@ public Token create(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (grantType != null) { - request.addPostParam("grant_type", grantType); + Serializer.toString(request, "grant_type", grantType, ParameterType.URLENCODED); } + + if (clientId != null) { - request.addPostParam("client_id", clientId); + Serializer.toString(request, "client_id", clientId, ParameterType.URLENCODED); } + + if (clientSecret != null) { - request.addPostParam("client_secret", clientSecret); + Serializer.toString(request, "client_secret", clientSecret, ParameterType.URLENCODED); } + + if (code != null) { - request.addPostParam("code", code); + Serializer.toString(request, "code", code, ParameterType.URLENCODED); } + + if (redirectUri != null) { - request.addPostParam("redirect_uri", redirectUri); + Serializer.toString(request, "redirect_uri", redirectUri, ParameterType.URLENCODED); } + + if (audience != null) { - request.addPostParam("audience", audience); + Serializer.toString(request, "audience", audience, ParameterType.URLENCODED); } + + if (refreshToken != null) { - request.addPostParam("refresh_token", refreshToken); + Serializer.toString(request, "refresh_token", refreshToken, ParameterType.URLENCODED); } + + if (scope != null) { - request.addPostParam("scope", scope); + Serializer.toString(request, "scope", scope, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/pricing/v1/messaging/Country.java b/src/main/java/com/twilio/rest/pricing/v1/messaging/Country.java index b94e824fc8..05ed5e40b8 100644 --- a/src/main/java/com/twilio/rest/pricing/v1/messaging/Country.java +++ b/src/main/java/com/twilio/rest/pricing/v1/messaging/Country.java @@ -18,49 +18,52 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.CurrencyDeserializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.type.InboundSmsPrice; import com.twilio.type.OutboundSmsPrice; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.util.Currency; import java.util.List; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Country extends Resource { - private static final long serialVersionUID = 141644803807942L; - public static CountryFetcher fetcher(final String pathIsoCountry) { - return new CountryFetcher(pathIsoCountry); + public static CountryFetcher fetcher(final String pathisoCountry) { + return new CountryFetcher( + pathisoCountry + ); } + public static CountryReader reader() { - return new CountryReader(); + return new CountryReader( + + ); } + /** * Converts a JSON String into a Country object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Country object represented by the provided JSON */ - public static Country fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Country fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Country.class); @@ -75,14 +78,11 @@ public static Country fromJson( * Converts a JSON InputStream into a Country object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Country object represented by the provided JSON */ - public static Country fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Country fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Country.class); @@ -93,60 +93,50 @@ public static Country fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String country; + @Getter + private final List inboundSmsPrices; + @Getter private final String isoCountry; + @Getter private final List outboundSmsPrices; - private final List inboundSmsPrices; + @Getter private final Currency priceUnit; + @Getter private final URI url; @JsonCreator private Country( - @JsonProperty("country") final String country, - @JsonProperty("iso_country") final String isoCountry, - @JsonProperty("outbound_sms_prices") final List< - OutboundSmsPrice - > outboundSmsPrices, - @JsonProperty("inbound_sms_prices") final List< - InboundSmsPrice - > inboundSmsPrices, - @JsonProperty("price_unit") @JsonDeserialize( - using = com.twilio.converter.CurrencyDeserializer.class - ) final Currency priceUnit, - @JsonProperty("url") final URI url + @JsonProperty("country") final String country, + @JsonProperty("inbound_sms_prices") final List inboundSmsPrices, + @JsonProperty("iso_country") final String isoCountry, + @JsonProperty("outbound_sms_prices") final List outboundSmsPrices, + @JsonProperty("price_unit") + @JsonDeserialize(using = com.twilio.converter.CurrencyDeserializer.class) final Currency priceUnit, + @JsonProperty("url") final URI url ) { this.country = country; + this.inboundSmsPrices = inboundSmsPrices; this.isoCountry = isoCountry; this.outboundSmsPrices = outboundSmsPrices; - this.inboundSmsPrices = inboundSmsPrices; this.priceUnit = priceUnit; this.url = url; } - public final String getCountry() { - return this.country; - } - - public final String getIsoCountry() { - return this.isoCountry; - } - - public final List getOutboundSmsPrices() { - return this.outboundSmsPrices; - } - - public final List getInboundSmsPrices() { - return this.inboundSmsPrices; - } - - public final Currency getPriceUnit() { - return this.priceUnit; - } - - public final URI getUrl() { - return this.url; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -158,26 +148,28 @@ public boolean equals(final Object o) { } Country other = (Country) o; - return ( - Objects.equals(country, other.country) && - Objects.equals(isoCountry, other.isoCountry) && - Objects.equals(outboundSmsPrices, other.outboundSmsPrices) && - Objects.equals(inboundSmsPrices, other.inboundSmsPrices) && - Objects.equals(priceUnit, other.priceUnit) && - Objects.equals(url, other.url) + Objects.equals(country, other.country) && + Objects.equals(inboundSmsPrices, other.inboundSmsPrices) && + Objects.equals(isoCountry, other.isoCountry) && + Objects.equals(outboundSmsPrices, other.outboundSmsPrices) && + Objects.equals(priceUnit, other.priceUnit) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - country, - isoCountry, - outboundSmsPrices, - inboundSmsPrices, - priceUnit, - url + country, + inboundSmsPrices, + isoCountry, + outboundSmsPrices, + priceUnit, + url ); } + + } + diff --git a/src/main/java/com/twilio/rest/pricing/v1/messaging/CountryFetcher.java b/src/main/java/com/twilio/rest/pricing/v1/messaging/CountryFetcher.java index 2950ddb3f9..3e6230468f 100644 --- a/src/main/java/com/twilio/rest/pricing/v1/messaging/CountryFetcher.java +++ b/src/main/java/com/twilio/rest/pricing/v1/messaging/CountryFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.pricing.v1.messaging; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,48 +26,41 @@ public class CountryFetcher extends Fetcher { - private String pathIsoCountry; + private String pathisoCountry; - public CountryFetcher(final String pathIsoCountry) { - this.pathIsoCountry = pathIsoCountry; + public CountryFetcher(final String pathisoCountry) { + this.pathisoCountry = pathisoCountry; } + @Override public Country fetch(final TwilioRestClient client) { + String path = "/v1/Messaging/Countries/{IsoCountry}"; - path = - path.replace( - "{" + "IsoCountry" + "}", - this.pathIsoCountry.toString() - ); + path = path.replace("{" + "IsoCountry" + "}", this.pathisoCountry.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.PRICING.toString(), - path + HttpMethod.GET, + Domains.PRICING.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Country fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Country fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Country.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/pricing/v1/messaging/CountryReader.java b/src/main/java/com/twilio/rest/pricing/v1/messaging/CountryReader.java index d0e2ffc261..f9104f1f37 100644 --- a/src/main/java/com/twilio/rest/pricing/v1/messaging/CountryReader.java +++ b/src/main/java/com/twilio/rest/pricing/v1/messaging/CountryReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -31,105 +32,83 @@ public class CountryReader extends Reader { private Long pageSize; - public CountryReader() {} + public CountryReader() { + } + public CountryReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/Messaging/Countries"; + Request request = new Request( - HttpMethod.GET, - Domains.PRICING.toString(), - path + HttpMethod.GET, + Domains.PRICING.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Country read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Country read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "countries", - response.getContent(), - Country.class, - client.getObjectMapper() - ); + "countries", + response.getContent(), + Country.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.PRICING.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.PRICING.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/pricing/v1/phonenumber/Country.java b/src/main/java/com/twilio/rest/pricing/v1/phonenumber/Country.java index b7460493df..be3b4d021e 100644 --- a/src/main/java/com/twilio/rest/pricing/v1/phonenumber/Country.java +++ b/src/main/java/com/twilio/rest/pricing/v1/phonenumber/Country.java @@ -18,48 +18,51 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.CurrencyDeserializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.type.PhoneNumberPrice; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.util.Currency; import java.util.List; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Country extends Resource { - private static final long serialVersionUID = 141644803807942L; - public static CountryFetcher fetcher(final String pathIsoCountry) { - return new CountryFetcher(pathIsoCountry); + public static CountryFetcher fetcher(final String pathisoCountry) { + return new CountryFetcher( + pathisoCountry + ); } + public static CountryReader reader() { - return new CountryReader(); + return new CountryReader( + + ); } + /** * Converts a JSON String into a Country object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Country object represented by the provided JSON */ - public static Country fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Country fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Country.class); @@ -74,14 +77,11 @@ public static Country fromJson( * Converts a JSON InputStream into a Country object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Country object represented by the provided JSON */ - public static Country fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Country fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Country.class); @@ -92,23 +92,38 @@ public static Country fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String country; + @Getter private final String isoCountry; + @Getter private final List phoneNumberPrices; + @Getter private final Currency priceUnit; + @Getter private final URI url; @JsonCreator private Country( - @JsonProperty("country") final String country, - @JsonProperty("iso_country") final String isoCountry, - @JsonProperty("phone_number_prices") final List< - PhoneNumberPrice - > phoneNumberPrices, - @JsonProperty("price_unit") @JsonDeserialize( - using = com.twilio.converter.CurrencyDeserializer.class - ) final Currency priceUnit, - @JsonProperty("url") final URI url + @JsonProperty("country") final String country, + @JsonProperty("iso_country") final String isoCountry, + @JsonProperty("phone_number_prices") final List phoneNumberPrices, + @JsonProperty("price_unit") + @JsonDeserialize(using = com.twilio.converter.CurrencyDeserializer.class) final Currency priceUnit, + @JsonProperty("url") final URI url ) { this.country = country; this.isoCountry = isoCountry; @@ -117,26 +132,6 @@ private Country( this.url = url; } - public final String getCountry() { - return this.country; - } - - public final String getIsoCountry() { - return this.isoCountry; - } - - public final List getPhoneNumberPrices() { - return this.phoneNumberPrices; - } - - public final Currency getPriceUnit() { - return this.priceUnit; - } - - public final URI getUrl() { - return this.url; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -148,24 +143,26 @@ public boolean equals(final Object o) { } Country other = (Country) o; - return ( - Objects.equals(country, other.country) && - Objects.equals(isoCountry, other.isoCountry) && - Objects.equals(phoneNumberPrices, other.phoneNumberPrices) && - Objects.equals(priceUnit, other.priceUnit) && - Objects.equals(url, other.url) + Objects.equals(country, other.country) && + Objects.equals(isoCountry, other.isoCountry) && + Objects.equals(phoneNumberPrices, other.phoneNumberPrices) && + Objects.equals(priceUnit, other.priceUnit) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - country, - isoCountry, - phoneNumberPrices, - priceUnit, - url + country, + isoCountry, + phoneNumberPrices, + priceUnit, + url ); } + + } + diff --git a/src/main/java/com/twilio/rest/pricing/v1/phonenumber/CountryFetcher.java b/src/main/java/com/twilio/rest/pricing/v1/phonenumber/CountryFetcher.java index 7364f2e685..c5ea66786a 100644 --- a/src/main/java/com/twilio/rest/pricing/v1/phonenumber/CountryFetcher.java +++ b/src/main/java/com/twilio/rest/pricing/v1/phonenumber/CountryFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.pricing.v1.phonenumber; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,48 +26,41 @@ public class CountryFetcher extends Fetcher { - private String pathIsoCountry; + private String pathisoCountry; - public CountryFetcher(final String pathIsoCountry) { - this.pathIsoCountry = pathIsoCountry; + public CountryFetcher(final String pathisoCountry) { + this.pathisoCountry = pathisoCountry; } + @Override public Country fetch(final TwilioRestClient client) { + String path = "/v1/PhoneNumbers/Countries/{IsoCountry}"; - path = - path.replace( - "{" + "IsoCountry" + "}", - this.pathIsoCountry.toString() - ); + path = path.replace("{" + "IsoCountry" + "}", this.pathisoCountry.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.PRICING.toString(), - path + HttpMethod.GET, + Domains.PRICING.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Country fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Country fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Country.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/pricing/v1/phonenumber/CountryReader.java b/src/main/java/com/twilio/rest/pricing/v1/phonenumber/CountryReader.java index 757fa24a85..2a94f9dcac 100644 --- a/src/main/java/com/twilio/rest/pricing/v1/phonenumber/CountryReader.java +++ b/src/main/java/com/twilio/rest/pricing/v1/phonenumber/CountryReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -31,105 +32,83 @@ public class CountryReader extends Reader { private Long pageSize; - public CountryReader() {} + public CountryReader() { + } + public CountryReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/PhoneNumbers/Countries"; + Request request = new Request( - HttpMethod.GET, - Domains.PRICING.toString(), - path + HttpMethod.GET, + Domains.PRICING.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Country read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Country read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "countries", - response.getContent(), - Country.class, - client.getObjectMapper() - ); + "countries", + response.getContent(), + Country.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.PRICING.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.PRICING.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/pricing/v1/voice/Country.java b/src/main/java/com/twilio/rest/pricing/v1/voice/Country.java index 766b5a0ced..923397ac37 100644 --- a/src/main/java/com/twilio/rest/pricing/v1/voice/Country.java +++ b/src/main/java/com/twilio/rest/pricing/v1/voice/Country.java @@ -18,49 +18,52 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.CurrencyDeserializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.type.InboundCallPrice; import com.twilio.type.OutboundPrefixPrice; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.util.Currency; import java.util.List; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Country extends Resource { - private static final long serialVersionUID = 141644803807942L; - public static CountryFetcher fetcher(final String pathIsoCountry) { - return new CountryFetcher(pathIsoCountry); + public static CountryFetcher fetcher(final String pathisoCountry) { + return new CountryFetcher( + pathisoCountry + ); } + public static CountryReader reader() { - return new CountryReader(); + return new CountryReader( + + ); } + /** * Converts a JSON String into a Country object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Country object represented by the provided JSON */ - public static Country fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Country fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Country.class); @@ -75,14 +78,11 @@ public static Country fromJson( * Converts a JSON InputStream into a Country object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Country object represented by the provided JSON */ - public static Country fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Country fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Country.class); @@ -93,60 +93,50 @@ public static Country fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String country; + @Getter + private final List inboundCallPrices; + @Getter private final String isoCountry; + @Getter private final List outboundPrefixPrices; - private final List inboundCallPrices; + @Getter private final Currency priceUnit; + @Getter private final URI url; @JsonCreator private Country( - @JsonProperty("country") final String country, - @JsonProperty("iso_country") final String isoCountry, - @JsonProperty("outbound_prefix_prices") final List< - OutboundPrefixPrice - > outboundPrefixPrices, - @JsonProperty("inbound_call_prices") final List< - InboundCallPrice - > inboundCallPrices, - @JsonProperty("price_unit") @JsonDeserialize( - using = com.twilio.converter.CurrencyDeserializer.class - ) final Currency priceUnit, - @JsonProperty("url") final URI url + @JsonProperty("country") final String country, + @JsonProperty("inbound_call_prices") final List inboundCallPrices, + @JsonProperty("iso_country") final String isoCountry, + @JsonProperty("outbound_prefix_prices") final List outboundPrefixPrices, + @JsonProperty("price_unit") + @JsonDeserialize(using = com.twilio.converter.CurrencyDeserializer.class) final Currency priceUnit, + @JsonProperty("url") final URI url ) { this.country = country; + this.inboundCallPrices = inboundCallPrices; this.isoCountry = isoCountry; this.outboundPrefixPrices = outboundPrefixPrices; - this.inboundCallPrices = inboundCallPrices; this.priceUnit = priceUnit; this.url = url; } - public final String getCountry() { - return this.country; - } - - public final String getIsoCountry() { - return this.isoCountry; - } - - public final List getOutboundPrefixPrices() { - return this.outboundPrefixPrices; - } - - public final List getInboundCallPrices() { - return this.inboundCallPrices; - } - - public final Currency getPriceUnit() { - return this.priceUnit; - } - - public final URI getUrl() { - return this.url; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -158,26 +148,28 @@ public boolean equals(final Object o) { } Country other = (Country) o; - return ( - Objects.equals(country, other.country) && - Objects.equals(isoCountry, other.isoCountry) && - Objects.equals(outboundPrefixPrices, other.outboundPrefixPrices) && - Objects.equals(inboundCallPrices, other.inboundCallPrices) && - Objects.equals(priceUnit, other.priceUnit) && - Objects.equals(url, other.url) + Objects.equals(country, other.country) && + Objects.equals(inboundCallPrices, other.inboundCallPrices) && + Objects.equals(isoCountry, other.isoCountry) && + Objects.equals(outboundPrefixPrices, other.outboundPrefixPrices) && + Objects.equals(priceUnit, other.priceUnit) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - country, - isoCountry, - outboundPrefixPrices, - inboundCallPrices, - priceUnit, - url + country, + inboundCallPrices, + isoCountry, + outboundPrefixPrices, + priceUnit, + url ); } + + } + diff --git a/src/main/java/com/twilio/rest/pricing/v1/voice/CountryFetcher.java b/src/main/java/com/twilio/rest/pricing/v1/voice/CountryFetcher.java index 1f3128bd44..9cbf8d4dae 100644 --- a/src/main/java/com/twilio/rest/pricing/v1/voice/CountryFetcher.java +++ b/src/main/java/com/twilio/rest/pricing/v1/voice/CountryFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.pricing.v1.voice; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,48 +26,41 @@ public class CountryFetcher extends Fetcher { - private String pathIsoCountry; + private String pathisoCountry; - public CountryFetcher(final String pathIsoCountry) { - this.pathIsoCountry = pathIsoCountry; + public CountryFetcher(final String pathisoCountry) { + this.pathisoCountry = pathisoCountry; } + @Override public Country fetch(final TwilioRestClient client) { + String path = "/v1/Voice/Countries/{IsoCountry}"; - path = - path.replace( - "{" + "IsoCountry" + "}", - this.pathIsoCountry.toString() - ); + path = path.replace("{" + "IsoCountry" + "}", this.pathisoCountry.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.PRICING.toString(), - path + HttpMethod.GET, + Domains.PRICING.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Country fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Country fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Country.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/pricing/v1/voice/CountryReader.java b/src/main/java/com/twilio/rest/pricing/v1/voice/CountryReader.java index 62d22fb175..2d978b3e75 100644 --- a/src/main/java/com/twilio/rest/pricing/v1/voice/CountryReader.java +++ b/src/main/java/com/twilio/rest/pricing/v1/voice/CountryReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -31,105 +32,83 @@ public class CountryReader extends Reader { private Long pageSize; - public CountryReader() {} + public CountryReader() { + } + public CountryReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/Voice/Countries"; + Request request = new Request( - HttpMethod.GET, - Domains.PRICING.toString(), - path + HttpMethod.GET, + Domains.PRICING.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Country read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Country read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "countries", - response.getContent(), - Country.class, - client.getObjectMapper() - ); + "countries", + response.getContent(), + Country.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.PRICING.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.PRICING.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/pricing/v1/voice/Number.java b/src/main/java/com/twilio/rest/pricing/v1/voice/Number.java index 84501022ef..7743ff52bf 100644 --- a/src/main/java/com/twilio/rest/pricing/v1/voice/Number.java +++ b/src/main/java/com/twilio/rest/pricing/v1/voice/Number.java @@ -18,46 +18,44 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.CurrencyDeserializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.type.InboundCallPrice; import com.twilio.type.OutboundCallPrice; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.util.Currency; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Number extends Resource { - private static final long serialVersionUID = 23882142179085L; - public static NumberFetcher fetcher( - final com.twilio.type.PhoneNumber pathNumber - ) { - return new NumberFetcher(pathNumber); + public static NumberFetcher fetcher(final com.twilio.type.PhoneNumber pathnumber) { + return new NumberFetcher( + pathnumber + ); } + /** * Converts a JSON String into a Number object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Number object represented by the provided JSON */ - public static Number fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Number fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Number.class); @@ -72,14 +70,11 @@ public static Number fromJson( * Converts a JSON InputStream into a Number object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Number object represented by the provided JSON */ - public static Number fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Number fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Number.class); @@ -90,67 +85,54 @@ public static Number fromJson( } } - private final com.twilio.type.PhoneNumber number; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String country; + @Getter + private final InboundCallPrice inboundCallPrice; + @Getter private final String isoCountry; + @Getter + private final com.twilio.type.PhoneNumber number; + @Getter private final OutboundCallPrice outboundCallPrice; - private final InboundCallPrice inboundCallPrice; + @Getter private final Currency priceUnit; + @Getter private final URI url; @JsonCreator private Number( - @JsonProperty("number") final com.twilio.type.PhoneNumber number, - @JsonProperty("country") final String country, - @JsonProperty("iso_country") final String isoCountry, - @JsonProperty( - "outbound_call_price" - ) final OutboundCallPrice outboundCallPrice, - @JsonProperty( - "inbound_call_price" - ) final InboundCallPrice inboundCallPrice, - @JsonProperty("price_unit") @JsonDeserialize( - using = com.twilio.converter.CurrencyDeserializer.class - ) final Currency priceUnit, - @JsonProperty("url") final URI url + @JsonProperty("country") final String country, + @JsonProperty("inbound_call_price") final InboundCallPrice inboundCallPrice, + @JsonProperty("iso_country") final String isoCountry, + @JsonProperty("number") final com.twilio.type.PhoneNumber number, + @JsonProperty("outbound_call_price") final OutboundCallPrice outboundCallPrice, + @JsonProperty("price_unit") + @JsonDeserialize(using = com.twilio.converter.CurrencyDeserializer.class) final Currency priceUnit, + @JsonProperty("url") final URI url ) { - this.number = number; this.country = country; + this.inboundCallPrice = inboundCallPrice; this.isoCountry = isoCountry; + this.number = number; this.outboundCallPrice = outboundCallPrice; - this.inboundCallPrice = inboundCallPrice; this.priceUnit = priceUnit; this.url = url; } - public final com.twilio.type.PhoneNumber getNumber() { - return this.number; - } - - public final String getCountry() { - return this.country; - } - - public final String getIsoCountry() { - return this.isoCountry; - } - - public final OutboundCallPrice getOutboundCallPrice() { - return this.outboundCallPrice; - } - - public final InboundCallPrice getInboundCallPrice() { - return this.inboundCallPrice; - } - - public final Currency getPriceUnit() { - return this.priceUnit; - } - - public final URI getUrl() { - return this.url; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -162,28 +144,30 @@ public boolean equals(final Object o) { } Number other = (Number) o; - return ( - Objects.equals(number, other.number) && - Objects.equals(country, other.country) && - Objects.equals(isoCountry, other.isoCountry) && - Objects.equals(outboundCallPrice, other.outboundCallPrice) && - Objects.equals(inboundCallPrice, other.inboundCallPrice) && - Objects.equals(priceUnit, other.priceUnit) && - Objects.equals(url, other.url) + Objects.equals(country, other.country) && + Objects.equals(inboundCallPrice, other.inboundCallPrice) && + Objects.equals(isoCountry, other.isoCountry) && + Objects.equals(number, other.number) && + Objects.equals(outboundCallPrice, other.outboundCallPrice) && + Objects.equals(priceUnit, other.priceUnit) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - number, - country, - isoCountry, - outboundCallPrice, - inboundCallPrice, - priceUnit, - url + country, + inboundCallPrice, + isoCountry, + number, + outboundCallPrice, + priceUnit, + url ); } + + } + diff --git a/src/main/java/com/twilio/rest/pricing/v1/voice/NumberFetcher.java b/src/main/java/com/twilio/rest/pricing/v1/voice/NumberFetcher.java index ff3d62d4e3..c91510ed4a 100644 --- a/src/main/java/com/twilio/rest/pricing/v1/voice/NumberFetcher.java +++ b/src/main/java/com/twilio/rest/pricing/v1/voice/NumberFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.pricing.v1.voice; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,44 +26,41 @@ public class NumberFetcher extends Fetcher { - private com.twilio.type.PhoneNumber pathNumber; + private com.twilio.type.PhoneNumber pathnumber; - public NumberFetcher(final com.twilio.type.PhoneNumber pathNumber) { - this.pathNumber = pathNumber; + public NumberFetcher(final com.twilio.type.PhoneNumber pathnumber) { + this.pathnumber = pathnumber; } + @Override public Number fetch(final TwilioRestClient client) { + String path = "/v1/Voice/Numbers/{Number}"; - path = path.replace("{" + "Number" + "}", this.pathNumber.toString()); + path = path.replace("{" + "Number" + "}", this.pathnumber.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.PRICING.toString(), - path + HttpMethod.GET, + Domains.PRICING.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Number fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Number fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Number.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/pricing/v2/Country.java b/src/main/java/com/twilio/rest/pricing/v2/Country.java index a95ebb6743..7ad33c88cc 100644 --- a/src/main/java/com/twilio/rest/pricing/v2/Country.java +++ b/src/main/java/com/twilio/rest/pricing/v2/Country.java @@ -18,49 +18,52 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.CurrencyDeserializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.type.InboundCallPrice; import com.twilio.type.OutboundPrefixPriceWithOrigin; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.util.Currency; import java.util.List; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Country extends Resource { - private static final long serialVersionUID = 141644803807942L; - public static CountryFetcher fetcher(final String pathIsoCountry) { - return new CountryFetcher(pathIsoCountry); + public static CountryFetcher fetcher(final String pathisoCountry) { + return new CountryFetcher( + pathisoCountry + ); } + public static CountryReader reader() { - return new CountryReader(); + return new CountryReader( + + ); } + /** * Converts a JSON String into a Country object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Country object represented by the provided JSON */ - public static Country fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Country fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Country.class); @@ -75,14 +78,11 @@ public static Country fromJson( * Converts a JSON InputStream into a Country object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Country object represented by the provided JSON */ - public static Country fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Country fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Country.class); @@ -93,62 +93,50 @@ public static Country fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String country; + @Getter private final String isoCountry; - private final List terminatingPrefixPrices; + @Getter private final List originatingCallPrices; + @Getter private final Currency priceUnit; + @Getter + private final List terminatingPrefixPrices; + @Getter private final URI url; @JsonCreator private Country( - @JsonProperty("country") final String country, - @JsonProperty("iso_country") final String isoCountry, - @JsonProperty("terminating_prefix_prices") final List< - OutboundPrefixPriceWithOrigin - > terminatingPrefixPrices, - @JsonProperty("originating_call_prices") final List< - InboundCallPrice - > originatingCallPrices, - @JsonProperty("price_unit") @JsonDeserialize( - using = com.twilio.converter.CurrencyDeserializer.class - ) final Currency priceUnit, - @JsonProperty("url") final URI url + @JsonProperty("country") final String country, + @JsonProperty("iso_country") final String isoCountry, + @JsonProperty("originating_call_prices") final List originatingCallPrices, + @JsonProperty("price_unit") + @JsonDeserialize(using = com.twilio.converter.CurrencyDeserializer.class) final Currency priceUnit, + @JsonProperty("terminating_prefix_prices") final List terminatingPrefixPrices, + @JsonProperty("url") final URI url ) { this.country = country; this.isoCountry = isoCountry; - this.terminatingPrefixPrices = terminatingPrefixPrices; this.originatingCallPrices = originatingCallPrices; this.priceUnit = priceUnit; + this.terminatingPrefixPrices = terminatingPrefixPrices; this.url = url; } - public final String getCountry() { - return this.country; - } - - public final String getIsoCountry() { - return this.isoCountry; - } - - public final List< - OutboundPrefixPriceWithOrigin - > getTerminatingPrefixPrices() { - return this.terminatingPrefixPrices; - } - - public final List getOriginatingCallPrices() { - return this.originatingCallPrices; - } - - public final Currency getPriceUnit() { - return this.priceUnit; - } - - public final URI getUrl() { - return this.url; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -160,32 +148,28 @@ public boolean equals(final Object o) { } Country other = (Country) o; - return ( - Objects.equals(country, other.country) && - Objects.equals(isoCountry, other.isoCountry) && - Objects.equals( - terminatingPrefixPrices, - other.terminatingPrefixPrices - ) && - Objects.equals( - originatingCallPrices, - other.originatingCallPrices - ) && - Objects.equals(priceUnit, other.priceUnit) && - Objects.equals(url, other.url) + Objects.equals(country, other.country) && + Objects.equals(isoCountry, other.isoCountry) && + Objects.equals(originatingCallPrices, other.originatingCallPrices) && + Objects.equals(priceUnit, other.priceUnit) && + Objects.equals(terminatingPrefixPrices, other.terminatingPrefixPrices) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - country, - isoCountry, - terminatingPrefixPrices, - originatingCallPrices, - priceUnit, - url + country, + isoCountry, + originatingCallPrices, + priceUnit, + terminatingPrefixPrices, + url ); } + + } + diff --git a/src/main/java/com/twilio/rest/pricing/v2/CountryFetcher.java b/src/main/java/com/twilio/rest/pricing/v2/CountryFetcher.java index 7ee2711751..115f8519eb 100644 --- a/src/main/java/com/twilio/rest/pricing/v2/CountryFetcher.java +++ b/src/main/java/com/twilio/rest/pricing/v2/CountryFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.pricing.v2; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,48 +26,41 @@ public class CountryFetcher extends Fetcher { - private String pathIsoCountry; + private String pathisoCountry; - public CountryFetcher(final String pathIsoCountry) { - this.pathIsoCountry = pathIsoCountry; + public CountryFetcher(final String pathisoCountry) { + this.pathisoCountry = pathisoCountry; } + @Override public Country fetch(final TwilioRestClient client) { + String path = "/v2/Trunking/Countries/{IsoCountry}"; - path = - path.replace( - "{" + "IsoCountry" + "}", - this.pathIsoCountry.toString() - ); + path = path.replace("{" + "IsoCountry" + "}", this.pathisoCountry.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.PRICING.toString(), - path + HttpMethod.GET, + Domains.PRICING.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Country fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Country fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Country.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/pricing/v2/CountryReader.java b/src/main/java/com/twilio/rest/pricing/v2/CountryReader.java index 59d7e5d1a4..538b5d5df4 100644 --- a/src/main/java/com/twilio/rest/pricing/v2/CountryReader.java +++ b/src/main/java/com/twilio/rest/pricing/v2/CountryReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -31,105 +32,83 @@ public class CountryReader extends Reader { private Long pageSize; - public CountryReader() {} + public CountryReader() { + } + public CountryReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v2/Trunking/Countries"; + Request request = new Request( - HttpMethod.GET, - Domains.PRICING.toString(), - path + HttpMethod.GET, + Domains.PRICING.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Country read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Country read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "countries", - response.getContent(), - Country.class, - client.getObjectMapper() - ); + "countries", + response.getContent(), + Country.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.PRICING.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.PRICING.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/pricing/v2/Number.java b/src/main/java/com/twilio/rest/pricing/v2/Number.java index 3d8c0f89fe..5f4f890729 100644 --- a/src/main/java/com/twilio/rest/pricing/v2/Number.java +++ b/src/main/java/com/twilio/rest/pricing/v2/Number.java @@ -18,47 +18,45 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.CurrencyDeserializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.type.InboundCallPrice; import com.twilio.type.OutboundPrefixPriceWithOrigin; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.util.Currency; import java.util.List; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Number extends Resource { - private static final long serialVersionUID = 12955680623193L; - public static NumberFetcher fetcher( - final com.twilio.type.PhoneNumber pathDestinationNumber - ) { - return new NumberFetcher(pathDestinationNumber); + public static NumberFetcher fetcher(final com.twilio.type.PhoneNumber pathdestinationNumber) { + return new NumberFetcher( + pathdestinationNumber + ); } + /** * Converts a JSON String into a Number object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Number object represented by the provided JSON */ - public static Number fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Number fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Number.class); @@ -73,14 +71,11 @@ public static Number fromJson( * Converts a JSON InputStream into a Number object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Number object represented by the provided JSON */ - public static Number fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Number fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Number.class); @@ -91,80 +86,58 @@ public static Number fromJson( } } - private final com.twilio.type.PhoneNumber destinationNumber; - private final com.twilio.type.PhoneNumber originationNumber; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String country; + @Getter + private final com.twilio.type.PhoneNumber destinationNumber; + @Getter private final String isoCountry; - private final List terminatingPrefixPrices; + @Getter private final InboundCallPrice originatingCallPrice; + @Getter + private final com.twilio.type.PhoneNumber originationNumber; + @Getter private final Currency priceUnit; + @Getter + private final List terminatingPrefixPrices; + @Getter private final URI url; @JsonCreator private Number( - @JsonProperty( - "destination_number" - ) final com.twilio.type.PhoneNumber destinationNumber, - @JsonProperty( - "origination_number" - ) final com.twilio.type.PhoneNumber originationNumber, - @JsonProperty("country") final String country, - @JsonProperty("iso_country") final String isoCountry, - @JsonProperty("terminating_prefix_prices") final List< - OutboundPrefixPriceWithOrigin - > terminatingPrefixPrices, - @JsonProperty( - "originating_call_price" - ) final InboundCallPrice originatingCallPrice, - @JsonProperty("price_unit") @JsonDeserialize( - using = com.twilio.converter.CurrencyDeserializer.class - ) final Currency priceUnit, - @JsonProperty("url") final URI url + @JsonProperty("country") final String country, + @JsonProperty("destination_number") final com.twilio.type.PhoneNumber destinationNumber, + @JsonProperty("iso_country") final String isoCountry, + @JsonProperty("originating_call_price") final InboundCallPrice originatingCallPrice, + @JsonProperty("origination_number") final com.twilio.type.PhoneNumber originationNumber, + @JsonProperty("price_unit") + @JsonDeserialize(using = com.twilio.converter.CurrencyDeserializer.class) final Currency priceUnit, + @JsonProperty("terminating_prefix_prices") final List terminatingPrefixPrices, + @JsonProperty("url") final URI url ) { - this.destinationNumber = destinationNumber; - this.originationNumber = originationNumber; this.country = country; + this.destinationNumber = destinationNumber; this.isoCountry = isoCountry; - this.terminatingPrefixPrices = terminatingPrefixPrices; this.originatingCallPrice = originatingCallPrice; + this.originationNumber = originationNumber; this.priceUnit = priceUnit; + this.terminatingPrefixPrices = terminatingPrefixPrices; this.url = url; } - public final com.twilio.type.PhoneNumber getDestinationNumber() { - return this.destinationNumber; - } - - public final com.twilio.type.PhoneNumber getOriginationNumber() { - return this.originationNumber; - } - - public final String getCountry() { - return this.country; - } - - public final String getIsoCountry() { - return this.isoCountry; - } - - public final List< - OutboundPrefixPriceWithOrigin - > getTerminatingPrefixPrices() { - return this.terminatingPrefixPrices; - } - - public final InboundCallPrice getOriginatingCallPrice() { - return this.originatingCallPrice; - } - - public final Currency getPriceUnit() { - return this.priceUnit; - } - - public final URI getUrl() { - return this.url; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -176,33 +149,32 @@ public boolean equals(final Object o) { } Number other = (Number) o; - return ( - Objects.equals(destinationNumber, other.destinationNumber) && - Objects.equals(originationNumber, other.originationNumber) && - Objects.equals(country, other.country) && - Objects.equals(isoCountry, other.isoCountry) && - Objects.equals( - terminatingPrefixPrices, - other.terminatingPrefixPrices - ) && - Objects.equals(originatingCallPrice, other.originatingCallPrice) && - Objects.equals(priceUnit, other.priceUnit) && - Objects.equals(url, other.url) + Objects.equals(country, other.country) && + Objects.equals(destinationNumber, other.destinationNumber) && + Objects.equals(isoCountry, other.isoCountry) && + Objects.equals(originatingCallPrice, other.originatingCallPrice) && + Objects.equals(originationNumber, other.originationNumber) && + Objects.equals(priceUnit, other.priceUnit) && + Objects.equals(terminatingPrefixPrices, other.terminatingPrefixPrices) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - destinationNumber, - originationNumber, - country, - isoCountry, - terminatingPrefixPrices, - originatingCallPrice, - priceUnit, - url + country, + destinationNumber, + isoCountry, + originatingCallPrice, + originationNumber, + priceUnit, + terminatingPrefixPrices, + url ); } + + } + diff --git a/src/main/java/com/twilio/rest/pricing/v2/NumberFetcher.java b/src/main/java/com/twilio/rest/pricing/v2/NumberFetcher.java index e41c589818..5ba4f0c8e6 100644 --- a/src/main/java/com/twilio/rest/pricing/v2/NumberFetcher.java +++ b/src/main/java/com/twilio/rest/pricing/v2/NumberFetcher.java @@ -15,8 +15,9 @@ package com.twilio.rest.pricing.v2; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; import com.twilio.converter.Promoter; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -28,74 +29,62 @@ public class NumberFetcher extends Fetcher { - private com.twilio.type.PhoneNumber pathDestinationNumber; + private com.twilio.type.PhoneNumber pathdestinationNumber; private com.twilio.type.PhoneNumber originationNumber; - public NumberFetcher( - final com.twilio.type.PhoneNumber pathDestinationNumber - ) { - this.pathDestinationNumber = pathDestinationNumber; + public NumberFetcher(final com.twilio.type.PhoneNumber pathdestinationNumber) { + this.pathdestinationNumber = pathdestinationNumber; } - public NumberFetcher setOriginationNumber( - final com.twilio.type.PhoneNumber originationNumber - ) { + + public NumberFetcher setOriginationNumber(final com.twilio.type.PhoneNumber originationNumber) { this.originationNumber = originationNumber; return this; } public NumberFetcher setOriginationNumber(final String originationNumber) { - return setOriginationNumber( - Promoter.phoneNumberFromString(originationNumber) - ); + return setOriginationNumber(Promoter.phoneNumberFromString(originationNumber)); } @Override public Number fetch(final TwilioRestClient client) { + String path = "/v2/Trunking/Numbers/{DestinationNumber}"; - path = - path.replace( - "{" + "DestinationNumber" + "}", - this.pathDestinationNumber.toString() - ); + path = path.replace("{" + "DestinationNumber" + "}", this.pathdestinationNumber.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.PRICING.toString(), - path + HttpMethod.GET, + Domains.PRICING.toString(), + path ); addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Number fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Number fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Number.fromJson(response.getStream(), client.getObjectMapper()); } private void addQueryParams(final Request request) { + + if (originationNumber != null) { - request.addQueryParam( - "OriginationNumber", - originationNumber.toString() - ); + Serializer.toString(request, "OriginationNumber", originationNumber, ParameterType.QUERY); } + + } } diff --git a/src/main/java/com/twilio/rest/pricing/v2/voice/Country.java b/src/main/java/com/twilio/rest/pricing/v2/voice/Country.java index 18a482f54f..9bab673bdf 100644 --- a/src/main/java/com/twilio/rest/pricing/v2/voice/Country.java +++ b/src/main/java/com/twilio/rest/pricing/v2/voice/Country.java @@ -18,49 +18,52 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.CurrencyDeserializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.type.InboundCallPrice; import com.twilio.type.OutboundPrefixPriceWithOrigin; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.util.Currency; import java.util.List; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Country extends Resource { - private static final long serialVersionUID = 141644803807942L; - public static CountryFetcher fetcher(final String pathIsoCountry) { - return new CountryFetcher(pathIsoCountry); + public static CountryFetcher fetcher(final String pathisoCountry) { + return new CountryFetcher( + pathisoCountry + ); } + public static CountryReader reader() { - return new CountryReader(); + return new CountryReader( + + ); } + /** * Converts a JSON String into a Country object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Country object represented by the provided JSON */ - public static Country fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Country fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Country.class); @@ -75,14 +78,11 @@ public static Country fromJson( * Converts a JSON InputStream into a Country object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Country object represented by the provided JSON */ - public static Country fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Country fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Country.class); @@ -93,60 +93,50 @@ public static Country fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String country; + @Getter + private final List inboundCallPrices; + @Getter private final String isoCountry; + @Getter private final List outboundPrefixPrices; - private final List inboundCallPrices; + @Getter private final Currency priceUnit; + @Getter private final URI url; @JsonCreator private Country( - @JsonProperty("country") final String country, - @JsonProperty("iso_country") final String isoCountry, - @JsonProperty("outbound_prefix_prices") final List< - OutboundPrefixPriceWithOrigin - > outboundPrefixPrices, - @JsonProperty("inbound_call_prices") final List< - InboundCallPrice - > inboundCallPrices, - @JsonProperty("price_unit") @JsonDeserialize( - using = com.twilio.converter.CurrencyDeserializer.class - ) final Currency priceUnit, - @JsonProperty("url") final URI url + @JsonProperty("country") final String country, + @JsonProperty("inbound_call_prices") final List inboundCallPrices, + @JsonProperty("iso_country") final String isoCountry, + @JsonProperty("outbound_prefix_prices") final List outboundPrefixPrices, + @JsonProperty("price_unit") + @JsonDeserialize(using = com.twilio.converter.CurrencyDeserializer.class) final Currency priceUnit, + @JsonProperty("url") final URI url ) { this.country = country; + this.inboundCallPrices = inboundCallPrices; this.isoCountry = isoCountry; this.outboundPrefixPrices = outboundPrefixPrices; - this.inboundCallPrices = inboundCallPrices; this.priceUnit = priceUnit; this.url = url; } - public final String getCountry() { - return this.country; - } - - public final String getIsoCountry() { - return this.isoCountry; - } - - public final List getOutboundPrefixPrices() { - return this.outboundPrefixPrices; - } - - public final List getInboundCallPrices() { - return this.inboundCallPrices; - } - - public final Currency getPriceUnit() { - return this.priceUnit; - } - - public final URI getUrl() { - return this.url; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -158,26 +148,28 @@ public boolean equals(final Object o) { } Country other = (Country) o; - return ( - Objects.equals(country, other.country) && - Objects.equals(isoCountry, other.isoCountry) && - Objects.equals(outboundPrefixPrices, other.outboundPrefixPrices) && - Objects.equals(inboundCallPrices, other.inboundCallPrices) && - Objects.equals(priceUnit, other.priceUnit) && - Objects.equals(url, other.url) + Objects.equals(country, other.country) && + Objects.equals(inboundCallPrices, other.inboundCallPrices) && + Objects.equals(isoCountry, other.isoCountry) && + Objects.equals(outboundPrefixPrices, other.outboundPrefixPrices) && + Objects.equals(priceUnit, other.priceUnit) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - country, - isoCountry, - outboundPrefixPrices, - inboundCallPrices, - priceUnit, - url + country, + inboundCallPrices, + isoCountry, + outboundPrefixPrices, + priceUnit, + url ); } + + } + diff --git a/src/main/java/com/twilio/rest/pricing/v2/voice/CountryFetcher.java b/src/main/java/com/twilio/rest/pricing/v2/voice/CountryFetcher.java index 83255a782f..c3c8951b14 100644 --- a/src/main/java/com/twilio/rest/pricing/v2/voice/CountryFetcher.java +++ b/src/main/java/com/twilio/rest/pricing/v2/voice/CountryFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.pricing.v2.voice; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,48 +26,41 @@ public class CountryFetcher extends Fetcher { - private String pathIsoCountry; + private String pathisoCountry; - public CountryFetcher(final String pathIsoCountry) { - this.pathIsoCountry = pathIsoCountry; + public CountryFetcher(final String pathisoCountry) { + this.pathisoCountry = pathisoCountry; } + @Override public Country fetch(final TwilioRestClient client) { + String path = "/v2/Voice/Countries/{IsoCountry}"; - path = - path.replace( - "{" + "IsoCountry" + "}", - this.pathIsoCountry.toString() - ); + path = path.replace("{" + "IsoCountry" + "}", this.pathisoCountry.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.PRICING.toString(), - path + HttpMethod.GET, + Domains.PRICING.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Country fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Country fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Country.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/pricing/v2/voice/CountryReader.java b/src/main/java/com/twilio/rest/pricing/v2/voice/CountryReader.java index 2ed3eb2a4c..036be24027 100644 --- a/src/main/java/com/twilio/rest/pricing/v2/voice/CountryReader.java +++ b/src/main/java/com/twilio/rest/pricing/v2/voice/CountryReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -31,105 +32,83 @@ public class CountryReader extends Reader { private Long pageSize; - public CountryReader() {} + public CountryReader() { + } + public CountryReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v2/Voice/Countries"; + Request request = new Request( - HttpMethod.GET, - Domains.PRICING.toString(), - path + HttpMethod.GET, + Domains.PRICING.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Country read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Country read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "countries", - response.getContent(), - Country.class, - client.getObjectMapper() - ); + "countries", + response.getContent(), + Country.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.PRICING.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.PRICING.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/pricing/v2/voice/Number.java b/src/main/java/com/twilio/rest/pricing/v2/voice/Number.java index cb87bffd51..d0b4f6bc7d 100644 --- a/src/main/java/com/twilio/rest/pricing/v2/voice/Number.java +++ b/src/main/java/com/twilio/rest/pricing/v2/voice/Number.java @@ -18,47 +18,45 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.CurrencyDeserializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.type.InboundCallPrice; import com.twilio.type.OutboundCallPriceWithOrigin; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.util.Currency; import java.util.List; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Number extends Resource { - private static final long serialVersionUID = 252636644344470L; - public static NumberFetcher fetcher( - final com.twilio.type.PhoneNumber pathDestinationNumber - ) { - return new NumberFetcher(pathDestinationNumber); + public static NumberFetcher fetcher(final com.twilio.type.PhoneNumber pathdestinationNumber) { + return new NumberFetcher( + pathdestinationNumber + ); } + /** * Converts a JSON String into a Number object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Number object represented by the provided JSON */ - public static Number fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Number fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Number.class); @@ -73,14 +71,11 @@ public static Number fromJson( * Converts a JSON InputStream into a Number object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Number object represented by the provided JSON */ - public static Number fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Number fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Number.class); @@ -91,78 +86,58 @@ public static Number fromJson( } } - private final com.twilio.type.PhoneNumber destinationNumber; - private final com.twilio.type.PhoneNumber originationNumber; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String country; + @Getter + private final com.twilio.type.PhoneNumber destinationNumber; + @Getter + private final InboundCallPrice inboundCallPrice; + @Getter private final String isoCountry; + @Getter + private final com.twilio.type.PhoneNumber originationNumber; + @Getter private final List outboundCallPrices; - private final InboundCallPrice inboundCallPrice; + @Getter private final Currency priceUnit; + @Getter private final URI url; @JsonCreator private Number( - @JsonProperty( - "destination_number" - ) final com.twilio.type.PhoneNumber destinationNumber, - @JsonProperty( - "origination_number" - ) final com.twilio.type.PhoneNumber originationNumber, - @JsonProperty("country") final String country, - @JsonProperty("iso_country") final String isoCountry, - @JsonProperty("outbound_call_prices") final List< - OutboundCallPriceWithOrigin - > outboundCallPrices, - @JsonProperty( - "inbound_call_price" - ) final InboundCallPrice inboundCallPrice, - @JsonProperty("price_unit") @JsonDeserialize( - using = com.twilio.converter.CurrencyDeserializer.class - ) final Currency priceUnit, - @JsonProperty("url") final URI url + @JsonProperty("country") final String country, + @JsonProperty("destination_number") final com.twilio.type.PhoneNumber destinationNumber, + @JsonProperty("inbound_call_price") final InboundCallPrice inboundCallPrice, + @JsonProperty("iso_country") final String isoCountry, + @JsonProperty("origination_number") final com.twilio.type.PhoneNumber originationNumber, + @JsonProperty("outbound_call_prices") final List outboundCallPrices, + @JsonProperty("price_unit") + @JsonDeserialize(using = com.twilio.converter.CurrencyDeserializer.class) final Currency priceUnit, + @JsonProperty("url") final URI url ) { - this.destinationNumber = destinationNumber; - this.originationNumber = originationNumber; this.country = country; + this.destinationNumber = destinationNumber; + this.inboundCallPrice = inboundCallPrice; this.isoCountry = isoCountry; + this.originationNumber = originationNumber; this.outboundCallPrices = outboundCallPrices; - this.inboundCallPrice = inboundCallPrice; this.priceUnit = priceUnit; this.url = url; } - public final com.twilio.type.PhoneNumber getDestinationNumber() { - return this.destinationNumber; - } - - public final com.twilio.type.PhoneNumber getOriginationNumber() { - return this.originationNumber; - } - - public final String getCountry() { - return this.country; - } - - public final String getIsoCountry() { - return this.isoCountry; - } - - public final List getOutboundCallPrices() { - return this.outboundCallPrices; - } - - public final InboundCallPrice getInboundCallPrice() { - return this.inboundCallPrice; - } - - public final Currency getPriceUnit() { - return this.priceUnit; - } - - public final URI getUrl() { - return this.url; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -174,30 +149,32 @@ public boolean equals(final Object o) { } Number other = (Number) o; - return ( - Objects.equals(destinationNumber, other.destinationNumber) && - Objects.equals(originationNumber, other.originationNumber) && - Objects.equals(country, other.country) && - Objects.equals(isoCountry, other.isoCountry) && - Objects.equals(outboundCallPrices, other.outboundCallPrices) && - Objects.equals(inboundCallPrice, other.inboundCallPrice) && - Objects.equals(priceUnit, other.priceUnit) && - Objects.equals(url, other.url) + Objects.equals(country, other.country) && + Objects.equals(destinationNumber, other.destinationNumber) && + Objects.equals(inboundCallPrice, other.inboundCallPrice) && + Objects.equals(isoCountry, other.isoCountry) && + Objects.equals(originationNumber, other.originationNumber) && + Objects.equals(outboundCallPrices, other.outboundCallPrices) && + Objects.equals(priceUnit, other.priceUnit) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - destinationNumber, - originationNumber, - country, - isoCountry, - outboundCallPrices, - inboundCallPrice, - priceUnit, - url + country, + destinationNumber, + inboundCallPrice, + isoCountry, + originationNumber, + outboundCallPrices, + priceUnit, + url ); } + + } + diff --git a/src/main/java/com/twilio/rest/pricing/v2/voice/NumberFetcher.java b/src/main/java/com/twilio/rest/pricing/v2/voice/NumberFetcher.java index 806d653a7b..2be7374f74 100644 --- a/src/main/java/com/twilio/rest/pricing/v2/voice/NumberFetcher.java +++ b/src/main/java/com/twilio/rest/pricing/v2/voice/NumberFetcher.java @@ -15,8 +15,9 @@ package com.twilio.rest.pricing.v2.voice; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; import com.twilio.converter.Promoter; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -28,74 +29,62 @@ public class NumberFetcher extends Fetcher { - private com.twilio.type.PhoneNumber pathDestinationNumber; + private com.twilio.type.PhoneNumber pathdestinationNumber; private com.twilio.type.PhoneNumber originationNumber; - public NumberFetcher( - final com.twilio.type.PhoneNumber pathDestinationNumber - ) { - this.pathDestinationNumber = pathDestinationNumber; + public NumberFetcher(final com.twilio.type.PhoneNumber pathdestinationNumber) { + this.pathdestinationNumber = pathdestinationNumber; } - public NumberFetcher setOriginationNumber( - final com.twilio.type.PhoneNumber originationNumber - ) { + + public NumberFetcher setOriginationNumber(final com.twilio.type.PhoneNumber originationNumber) { this.originationNumber = originationNumber; return this; } public NumberFetcher setOriginationNumber(final String originationNumber) { - return setOriginationNumber( - Promoter.phoneNumberFromString(originationNumber) - ); + return setOriginationNumber(Promoter.phoneNumberFromString(originationNumber)); } @Override public Number fetch(final TwilioRestClient client) { + String path = "/v2/Voice/Numbers/{DestinationNumber}"; - path = - path.replace( - "{" + "DestinationNumber" + "}", - this.pathDestinationNumber.toString() - ); + path = path.replace("{" + "DestinationNumber" + "}", this.pathdestinationNumber.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.PRICING.toString(), - path + HttpMethod.GET, + Domains.PRICING.toString(), + path ); addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Number fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Number fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Number.fromJson(response.getStream(), client.getObjectMapper()); } private void addQueryParams(final Request request) { + + if (originationNumber != null) { - request.addQueryParam( - "OriginationNumber", - originationNumber.toString() - ); + Serializer.toString(request, "OriginationNumber", originationNumber, ParameterType.QUERY); } + + } } diff --git a/src/main/java/com/twilio/rest/proxy/v1/Service.java b/src/main/java/com/twilio/rest/proxy/v1/Service.java index 65eb5245f6..08ba210172 100644 --- a/src/main/java/com/twilio/rest/proxy/v1/Service.java +++ b/src/main/java/com/twilio/rest/proxy/v1/Service.java @@ -18,60 +18,115 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Service extends Resource { - private static final long serialVersionUID = 120259795390146L; public static ServiceCreator creator(final String uniqueName) { - return new ServiceCreator(uniqueName); + return new ServiceCreator( + uniqueName + ); } - public static ServiceDeleter deleter(final String pathSid) { - return new ServiceDeleter(pathSid); + + public static ServiceDeleter deleter(final String pathsid) { + return new ServiceDeleter( + pathsid + ); } - public static ServiceFetcher fetcher(final String pathSid) { - return new ServiceFetcher(pathSid); + + public static ServiceFetcher fetcher(final String pathsid) { + return new ServiceFetcher( + pathsid + ); } + public static ServiceReader reader() { - return new ServiceReader(); + return new ServiceReader( + + ); + } + + + public static ServiceUpdater updater(final String pathsid) { + return new ServiceUpdater( + pathsid + ); } - public static ServiceUpdater updater(final String pathSid) { - return new ServiceUpdater(pathSid); + + public enum GeoMatchLevel { + AREA_CODE("area-code"), + OVERLAY("overlay"), + RADIUS("radius"), + COUNTRY("country"); + + private final String value; + + private GeoMatchLevel(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static GeoMatchLevel forValue(final String value) { + return Promoter.enumFromString(value, GeoMatchLevel.values()); + } } + public enum NumberSelectionBehavior { + AVOID_STICKY("avoid-sticky"), + PREFER_STICKY("prefer-sticky"); + + private final String value; + + private NumberSelectionBehavior(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static NumberSelectionBehavior forValue(final String value) { + return Promoter.enumFromString(value, NumberSelectionBehavior.values()); + } + } + + /** * Converts a JSON String into a Service object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Service object represented by the provided JSON */ - public static Service fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Service fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Service.class); @@ -86,14 +141,11 @@ public static Service fromJson( * Converts a JSON InputStream into a Service object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Service object represented by the provided JSON */ - public static Service fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Service fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Service.class); @@ -104,114 +156,81 @@ public static Service fromJson( } } - private final String sid; - private final String uniqueName; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String chatInstanceSid; + @Getter private final URI callbackUrl; + @Getter + private final String chatInstanceSid; + @Getter + private final ZonedDateTime dateCreated; + @Getter + private final ZonedDateTime dateUpdated; + @Getter private final Integer defaultTtl; - private final Service.NumberSelectionBehavior numberSelectionBehavior; + @Getter private final Service.GeoMatchLevel geoMatchLevel; + @Getter private final URI interceptCallbackUrl; + @Getter + private final Map links; + @Getter + private final Service.NumberSelectionBehavior numberSelectionBehavior; + @Getter private final URI outOfSessionCallbackUrl; - private final ZonedDateTime dateCreated; - private final ZonedDateTime dateUpdated; + @Getter + private final String sid; + @Getter + private final String uniqueName; + @Getter private final URI url; - private final Map links; @JsonCreator private Service( - @JsonProperty("sid") final String sid, - @JsonProperty("unique_name") final String uniqueName, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("chat_instance_sid") final String chatInstanceSid, - @JsonProperty("callback_url") final URI callbackUrl, - @JsonProperty("default_ttl") final Integer defaultTtl, - @JsonProperty( - "number_selection_behavior" - ) final Service.NumberSelectionBehavior numberSelectionBehavior, - @JsonProperty( - "geo_match_level" - ) final Service.GeoMatchLevel geoMatchLevel, - @JsonProperty("intercept_callback_url") final URI interceptCallbackUrl, - @JsonProperty( - "out_of_session_callback_url" - ) final URI outOfSessionCallbackUrl, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("url") final URI url, - @JsonProperty("links") final Map links + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("callback_url") final URI callbackUrl, + @JsonProperty("chat_instance_sid") final String chatInstanceSid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("default_ttl") final Integer defaultTtl, + @JsonProperty("geo_match_level") final Service.GeoMatchLevel geoMatchLevel, + @JsonProperty("intercept_callback_url") final URI interceptCallbackUrl, + @JsonProperty("links") final Map links, + @JsonProperty("number_selection_behavior") final Service.NumberSelectionBehavior numberSelectionBehavior, + @JsonProperty("out_of_session_callback_url") final URI outOfSessionCallbackUrl, + @JsonProperty("sid") final String sid, + @JsonProperty("unique_name") final String uniqueName, + @JsonProperty("url") final URI url ) { - this.sid = sid; - this.uniqueName = uniqueName; this.accountSid = accountSid; - this.chatInstanceSid = chatInstanceSid; this.callbackUrl = callbackUrl; + this.chatInstanceSid = chatInstanceSid; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.defaultTtl = defaultTtl; - this.numberSelectionBehavior = numberSelectionBehavior; this.geoMatchLevel = geoMatchLevel; this.interceptCallbackUrl = interceptCallbackUrl; + this.links = links; + this.numberSelectionBehavior = numberSelectionBehavior; this.outOfSessionCallbackUrl = outOfSessionCallbackUrl; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); + this.sid = sid; + this.uniqueName = uniqueName; this.url = url; - this.links = links; - } - - public final String getSid() { - return this.sid; - } - - public final String getUniqueName() { - return this.uniqueName; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getChatInstanceSid() { - return this.chatInstanceSid; - } - - public final URI getCallbackUrl() { - return this.callbackUrl; - } - - public final Integer getDefaultTtl() { - return this.defaultTtl; - } - - public final Service.NumberSelectionBehavior getNumberSelectionBehavior() { - return this.numberSelectionBehavior; - } - - public final Service.GeoMatchLevel getGeoMatchLevel() { - return this.geoMatchLevel; - } - - public final URI getInterceptCallbackUrl() { - return this.interceptCallbackUrl; - } - - public final URI getOutOfSessionCallbackUrl() { - return this.outOfSessionCallbackUrl; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final URI getUrl() { - return this.url; - } - - public final Map getLinks() { - return this.links; } @Override @@ -225,93 +244,44 @@ public boolean equals(final Object o) { } Service other = (Service) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(uniqueName, other.uniqueName) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(chatInstanceSid, other.chatInstanceSid) && - Objects.equals(callbackUrl, other.callbackUrl) && - Objects.equals(defaultTtl, other.defaultTtl) && - Objects.equals( - numberSelectionBehavior, - other.numberSelectionBehavior - ) && - Objects.equals(geoMatchLevel, other.geoMatchLevel) && - Objects.equals(interceptCallbackUrl, other.interceptCallbackUrl) && - Objects.equals( - outOfSessionCallbackUrl, - other.outOfSessionCallbackUrl - ) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(url, other.url) && - Objects.equals(links, other.links) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(callbackUrl, other.callbackUrl) && + Objects.equals(chatInstanceSid, other.chatInstanceSid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(defaultTtl, other.defaultTtl) && + Objects.equals(geoMatchLevel, other.geoMatchLevel) && + Objects.equals(interceptCallbackUrl, other.interceptCallbackUrl) && + Objects.equals(links, other.links) && + Objects.equals(numberSelectionBehavior, other.numberSelectionBehavior) && + Objects.equals(outOfSessionCallbackUrl, other.outOfSessionCallbackUrl) && + Objects.equals(sid, other.sid) && + Objects.equals(uniqueName, other.uniqueName) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - sid, - uniqueName, - accountSid, - chatInstanceSid, - callbackUrl, - defaultTtl, - numberSelectionBehavior, - geoMatchLevel, - interceptCallbackUrl, - outOfSessionCallbackUrl, - dateCreated, - dateUpdated, - url, - links + accountSid, + callbackUrl, + chatInstanceSid, + dateCreated, + dateUpdated, + defaultTtl, + geoMatchLevel, + interceptCallbackUrl, + links, + numberSelectionBehavior, + outOfSessionCallbackUrl, + sid, + uniqueName, + url ); } - public enum GeoMatchLevel { - AREA_CODE("area-code"), - OVERLAY("overlay"), - RADIUS("radius"), - COUNTRY("country"); - private final String value; - - private GeoMatchLevel(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static GeoMatchLevel forValue(final String value) { - return Promoter.enumFromString(value, GeoMatchLevel.values()); - } - } - - public enum NumberSelectionBehavior { - AVOID_STICKY("avoid-sticky"), - PREFER_STICKY("prefer-sticky"); - - private final String value; - - private NumberSelectionBehavior(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static NumberSelectionBehavior forValue(final String value) { - return Promoter.enumFromString( - value, - NumberSelectionBehavior.values() - ); - } - } } + diff --git a/src/main/java/com/twilio/rest/proxy/v1/ServiceCreator.java b/src/main/java/com/twilio/rest/proxy/v1/ServiceCreator.java index 46cd659e7a..85d2e28ff6 100644 --- a/src/main/java/com/twilio/rest/proxy/v1/ServiceCreator.java +++ b/src/main/java/com/twilio/rest/proxy/v1/ServiceCreator.java @@ -14,9 +14,11 @@ package com.twilio.rest.proxy.v1; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; -import com.twilio.converter.Promoter; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,7 +27,7 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -import java.net.URI; + import java.net.URI; public class ServiceCreator extends Creator { @@ -43,103 +45,80 @@ public ServiceCreator(final String uniqueName) { this.uniqueName = uniqueName; } + public ServiceCreator setUniqueName(final String uniqueName) { this.uniqueName = uniqueName; return this; } + public ServiceCreator setDefaultTtl(final Integer defaultTtl) { this.defaultTtl = defaultTtl; return this; } + public ServiceCreator setCallbackUrl(final URI callbackUrl) { this.callbackUrl = callbackUrl; return this; } - public ServiceCreator setCallbackUrl(final String callbackUrl) { - return setCallbackUrl(Promoter.uriFromString(callbackUrl)); - } - public ServiceCreator setGeoMatchLevel( - final Service.GeoMatchLevel geoMatchLevel - ) { + public ServiceCreator setGeoMatchLevel(final Service.GeoMatchLevel geoMatchLevel) { this.geoMatchLevel = geoMatchLevel; return this; } - public ServiceCreator setNumberSelectionBehavior( - final Service.NumberSelectionBehavior numberSelectionBehavior - ) { + + public ServiceCreator setNumberSelectionBehavior(final Service.NumberSelectionBehavior numberSelectionBehavior) { this.numberSelectionBehavior = numberSelectionBehavior; return this; } - public ServiceCreator setInterceptCallbackUrl( - final URI interceptCallbackUrl - ) { + + public ServiceCreator setInterceptCallbackUrl(final URI interceptCallbackUrl) { this.interceptCallbackUrl = interceptCallbackUrl; return this; } - public ServiceCreator setInterceptCallbackUrl( - final String interceptCallbackUrl - ) { - return setInterceptCallbackUrl( - Promoter.uriFromString(interceptCallbackUrl) - ); - } - public ServiceCreator setOutOfSessionCallbackUrl( - final URI outOfSessionCallbackUrl - ) { + public ServiceCreator setOutOfSessionCallbackUrl(final URI outOfSessionCallbackUrl) { this.outOfSessionCallbackUrl = outOfSessionCallbackUrl; return this; } - public ServiceCreator setOutOfSessionCallbackUrl( - final String outOfSessionCallbackUrl - ) { - return setOutOfSessionCallbackUrl( - Promoter.uriFromString(outOfSessionCallbackUrl) - ); - } public ServiceCreator setChatInstanceSid(final String chatInstanceSid) { this.chatInstanceSid = chatInstanceSid; return this; } + @Override public Service create(final TwilioRestClient client) { + String path = "/v1/Services"; - path = - path.replace("{" + "UniqueName" + "}", this.uniqueName.toString()); Request request = new Request( - HttpMethod.POST, - Domains.PROXY.toString(), - path + HttpMethod.POST, + Domains.PROXY.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Service creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("Service creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -148,38 +127,46 @@ public Service create(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (uniqueName != null) { - request.addPostParam("UniqueName", uniqueName); + Serializer.toString(request, "UniqueName", uniqueName, ParameterType.URLENCODED); } + + if (defaultTtl != null) { - request.addPostParam("DefaultTtl", defaultTtl.toString()); + Serializer.toString(request, "DefaultTtl", defaultTtl, ParameterType.URLENCODED); } + + if (callbackUrl != null) { - request.addPostParam("CallbackUrl", callbackUrl.toString()); + Serializer.toString(request, "CallbackUrl", callbackUrl, ParameterType.URLENCODED); } + + if (geoMatchLevel != null) { - request.addPostParam("GeoMatchLevel", geoMatchLevel.toString()); + Serializer.toString(request, "GeoMatchLevel", geoMatchLevel, ParameterType.URLENCODED); } + + if (numberSelectionBehavior != null) { - request.addPostParam( - "NumberSelectionBehavior", - numberSelectionBehavior.toString() - ); + Serializer.toString(request, "NumberSelectionBehavior", numberSelectionBehavior, ParameterType.URLENCODED); } + + if (interceptCallbackUrl != null) { - request.addPostParam( - "InterceptCallbackUrl", - interceptCallbackUrl.toString() - ); + Serializer.toString(request, "InterceptCallbackUrl", interceptCallbackUrl, ParameterType.URLENCODED); } + + if (outOfSessionCallbackUrl != null) { - request.addPostParam( - "OutOfSessionCallbackUrl", - outOfSessionCallbackUrl.toString() - ); + Serializer.toString(request, "OutOfSessionCallbackUrl", outOfSessionCallbackUrl, ParameterType.URLENCODED); } + + if (chatInstanceSid != null) { - request.addPostParam("ChatInstanceSid", chatInstanceSid); + Serializer.toString(request, "ChatInstanceSid", chatInstanceSid, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/proxy/v1/ServiceDeleter.java b/src/main/java/com/twilio/rest/proxy/v1/ServiceDeleter.java index 1f47397620..725b151f57 100644 --- a/src/main/java/com/twilio/rest/proxy/v1/ServiceDeleter.java +++ b/src/main/java/com/twilio/rest/proxy/v1/ServiceDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.proxy.v1; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,40 +26,38 @@ public class ServiceDeleter extends Deleter { - private String pathSid; + private String pathsid; - public ServiceDeleter(final String pathSid) { - this.pathSid = pathSid; + public ServiceDeleter(final String pathsid) { + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/v1/Services/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.PROXY.toString(), - path + HttpMethod.DELETE, + Domains.PROXY.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Service delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("Service delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/proxy/v1/ServiceFetcher.java b/src/main/java/com/twilio/rest/proxy/v1/ServiceFetcher.java index 606a216395..b9db240865 100644 --- a/src/main/java/com/twilio/rest/proxy/v1/ServiceFetcher.java +++ b/src/main/java/com/twilio/rest/proxy/v1/ServiceFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.proxy.v1; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,44 +26,41 @@ public class ServiceFetcher extends Fetcher { - private String pathSid; + private String pathsid; - public ServiceFetcher(final String pathSid) { - this.pathSid = pathSid; + public ServiceFetcher(final String pathsid) { + this.pathsid = pathsid; } + @Override public Service fetch(final TwilioRestClient client) { + String path = "/v1/Services/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.PROXY.toString(), - path + HttpMethod.GET, + Domains.PROXY.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Service fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Service fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Service.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/proxy/v1/ServiceReader.java b/src/main/java/com/twilio/rest/proxy/v1/ServiceReader.java index 3a5dfc7521..68ff0ee5c9 100644 --- a/src/main/java/com/twilio/rest/proxy/v1/ServiceReader.java +++ b/src/main/java/com/twilio/rest/proxy/v1/ServiceReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -31,105 +32,83 @@ public class ServiceReader extends Reader { private Long pageSize; - public ServiceReader() {} + public ServiceReader() { + } + public ServiceReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/Services"; + Request request = new Request( - HttpMethod.GET, - Domains.PROXY.toString(), - path + HttpMethod.GET, + Domains.PROXY.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Service read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Service read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "services", - response.getContent(), - Service.class, - client.getObjectMapper() - ); + "services", + response.getContent(), + Service.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.PROXY.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.PROXY.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/proxy/v1/ServiceUpdater.java b/src/main/java/com/twilio/rest/proxy/v1/ServiceUpdater.java index e833b391ac..e59210ad42 100644 --- a/src/main/java/com/twilio/rest/proxy/v1/ServiceUpdater.java +++ b/src/main/java/com/twilio/rest/proxy/v1/ServiceUpdater.java @@ -16,7 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; -import com.twilio.converter.Promoter; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,11 +26,11 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.net.URI; public class ServiceUpdater extends Updater { - - private String pathSid; + private String pathsid; private String uniqueName; private Integer defaultTtl; private URI callbackUrl; @@ -39,106 +40,86 @@ public class ServiceUpdater extends Updater { private URI outOfSessionCallbackUrl; private String chatInstanceSid; - public ServiceUpdater(final String pathSid) { - this.pathSid = pathSid; + public ServiceUpdater(final String pathsid) { + this.pathsid = pathsid; } + public ServiceUpdater setUniqueName(final String uniqueName) { this.uniqueName = uniqueName; return this; } + public ServiceUpdater setDefaultTtl(final Integer defaultTtl) { this.defaultTtl = defaultTtl; return this; } + public ServiceUpdater setCallbackUrl(final URI callbackUrl) { this.callbackUrl = callbackUrl; return this; } - public ServiceUpdater setCallbackUrl(final String callbackUrl) { - return setCallbackUrl(Promoter.uriFromString(callbackUrl)); - } - public ServiceUpdater setGeoMatchLevel( - final Service.GeoMatchLevel geoMatchLevel - ) { + public ServiceUpdater setGeoMatchLevel(final Service.GeoMatchLevel geoMatchLevel) { this.geoMatchLevel = geoMatchLevel; return this; } - public ServiceUpdater setNumberSelectionBehavior( - final Service.NumberSelectionBehavior numberSelectionBehavior - ) { + + public ServiceUpdater setNumberSelectionBehavior(final Service.NumberSelectionBehavior numberSelectionBehavior) { this.numberSelectionBehavior = numberSelectionBehavior; return this; } - public ServiceUpdater setInterceptCallbackUrl( - final URI interceptCallbackUrl - ) { + + public ServiceUpdater setInterceptCallbackUrl(final URI interceptCallbackUrl) { this.interceptCallbackUrl = interceptCallbackUrl; return this; } - public ServiceUpdater setInterceptCallbackUrl( - final String interceptCallbackUrl - ) { - return setInterceptCallbackUrl( - Promoter.uriFromString(interceptCallbackUrl) - ); - } - public ServiceUpdater setOutOfSessionCallbackUrl( - final URI outOfSessionCallbackUrl - ) { + public ServiceUpdater setOutOfSessionCallbackUrl(final URI outOfSessionCallbackUrl) { this.outOfSessionCallbackUrl = outOfSessionCallbackUrl; return this; } - public ServiceUpdater setOutOfSessionCallbackUrl( - final String outOfSessionCallbackUrl - ) { - return setOutOfSessionCallbackUrl( - Promoter.uriFromString(outOfSessionCallbackUrl) - ); - } public ServiceUpdater setChatInstanceSid(final String chatInstanceSid) { this.chatInstanceSid = chatInstanceSid; return this; } + @Override public Service update(final TwilioRestClient client) { + String path = "/v1/Services/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.PROXY.toString(), - path + HttpMethod.POST, + Domains.PROXY.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Service update failed: Unable to connect to server" - ); + throw new ApiConnectionException("Service update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -147,38 +128,46 @@ public Service update(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (uniqueName != null) { - request.addPostParam("UniqueName", uniqueName); + Serializer.toString(request, "UniqueName", uniqueName, ParameterType.URLENCODED); } + + if (defaultTtl != null) { - request.addPostParam("DefaultTtl", defaultTtl.toString()); + Serializer.toString(request, "DefaultTtl", defaultTtl, ParameterType.URLENCODED); } + + if (callbackUrl != null) { - request.addPostParam("CallbackUrl", callbackUrl.toString()); + Serializer.toString(request, "CallbackUrl", callbackUrl, ParameterType.URLENCODED); } + + if (geoMatchLevel != null) { - request.addPostParam("GeoMatchLevel", geoMatchLevel.toString()); + Serializer.toString(request, "GeoMatchLevel", geoMatchLevel, ParameterType.URLENCODED); } + + if (numberSelectionBehavior != null) { - request.addPostParam( - "NumberSelectionBehavior", - numberSelectionBehavior.toString() - ); + Serializer.toString(request, "NumberSelectionBehavior", numberSelectionBehavior, ParameterType.URLENCODED); } + + if (interceptCallbackUrl != null) { - request.addPostParam( - "InterceptCallbackUrl", - interceptCallbackUrl.toString() - ); + Serializer.toString(request, "InterceptCallbackUrl", interceptCallbackUrl, ParameterType.URLENCODED); } + + if (outOfSessionCallbackUrl != null) { - request.addPostParam( - "OutOfSessionCallbackUrl", - outOfSessionCallbackUrl.toString() - ); + Serializer.toString(request, "OutOfSessionCallbackUrl", outOfSessionCallbackUrl, ParameterType.URLENCODED); } + + if (chatInstanceSid != null) { - request.addPostParam("ChatInstanceSid", chatInstanceSid); + Serializer.toString(request, "ChatInstanceSid", chatInstanceSid, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/proxy/v1/service/PhoneNumber.java b/src/main/java/com/twilio/rest/proxy/v1/service/PhoneNumber.java index 714612794f..25cffba4ce 100644 --- a/src/main/java/com/twilio/rest/proxy/v1/service/PhoneNumber.java +++ b/src/main/java/com/twilio/rest/proxy/v1/service/PhoneNumber.java @@ -18,67 +18,71 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.type.PhoneNumberCapabilities; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class PhoneNumber extends Resource { - private static final long serialVersionUID = 71034679090032L; - public static PhoneNumberCreator creator(final String pathServiceSid) { - return new PhoneNumberCreator(pathServiceSid); + public static PhoneNumberCreator creator(final String pathserviceSid) { + return new PhoneNumberCreator( + pathserviceSid + ); } - public static PhoneNumberDeleter deleter( - final String pathServiceSid, - final String pathSid - ) { - return new PhoneNumberDeleter(pathServiceSid, pathSid); + + public static PhoneNumberDeleter deleter(final String pathserviceSid, final String pathsid) { + return new PhoneNumberDeleter( + pathserviceSid, pathsid + ); } - public static PhoneNumberFetcher fetcher( - final String pathServiceSid, - final String pathSid - ) { - return new PhoneNumberFetcher(pathServiceSid, pathSid); + + public static PhoneNumberFetcher fetcher(final String pathserviceSid, final String pathsid) { + return new PhoneNumberFetcher( + pathserviceSid, pathsid + ); } - public static PhoneNumberReader reader(final String pathServiceSid) { - return new PhoneNumberReader(pathServiceSid); + + public static PhoneNumberReader reader(final String pathserviceSid) { + return new PhoneNumberReader( + pathserviceSid + ); } - public static PhoneNumberUpdater updater( - final String pathServiceSid, - final String pathSid - ) { - return new PhoneNumberUpdater(pathServiceSid, pathSid); + + public static PhoneNumberUpdater updater(final String pathserviceSid, final String pathsid) { + return new PhoneNumberUpdater( + pathserviceSid, pathsid + ); } + /** * Converts a JSON String into a PhoneNumber object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return PhoneNumber object represented by the provided JSON */ - public static PhoneNumber fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static PhoneNumber fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, PhoneNumber.class); @@ -93,14 +97,11 @@ public static PhoneNumber fromJson( * Converts a JSON InputStream into a PhoneNumber object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return PhoneNumber object represented by the provided JSON */ - public static PhoneNumber fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static PhoneNumber fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, PhoneNumber.class); @@ -111,98 +112,73 @@ public static PhoneNumber fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String serviceSid; + @Getter + private final PhoneNumberCapabilities capabilities; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; - private final com.twilio.type.PhoneNumber phoneNumber; + @Getter private final String friendlyName; + @Getter + private final Integer inUse; + @Getter + private final Boolean isReserved; + @Getter private final String isoCountry; - private final PhoneNumberCapabilities capabilities; + @Getter + private final com.twilio.type.PhoneNumber phoneNumber; + @Getter + private final String serviceSid; + @Getter + private final String sid; + @Getter private final URI url; - private final Boolean isReserved; - private final Integer inUse; @JsonCreator private PhoneNumber( - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("service_sid") final String serviceSid, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty( - "phone_number" - ) final com.twilio.type.PhoneNumber phoneNumber, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("iso_country") final String isoCountry, - @JsonProperty( - "capabilities" - ) final PhoneNumberCapabilities capabilities, - @JsonProperty("url") final URI url, - @JsonProperty("is_reserved") final Boolean isReserved, - @JsonProperty("in_use") final Integer inUse + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("capabilities") final PhoneNumberCapabilities capabilities, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("in_use") final Integer inUse, + @JsonProperty("is_reserved") final Boolean isReserved, + @JsonProperty("iso_country") final String isoCountry, + @JsonProperty("phone_number") final com.twilio.type.PhoneNumber phoneNumber, + @JsonProperty("service_sid") final String serviceSid, + @JsonProperty("sid") final String sid, + @JsonProperty("url") final URI url ) { - this.sid = sid; this.accountSid = accountSid; - this.serviceSid = serviceSid; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); - this.phoneNumber = phoneNumber; + this.capabilities = capabilities; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.friendlyName = friendlyName; + this.inUse = inUse; + this.isReserved = isReserved; this.isoCountry = isoCountry; - this.capabilities = capabilities; + this.phoneNumber = phoneNumber; + this.serviceSid = serviceSid; + this.sid = sid; this.url = url; - this.isReserved = isReserved; - this.inUse = inUse; - } - - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getServiceSid() { - return this.serviceSid; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final com.twilio.type.PhoneNumber getPhoneNumber() { - return this.phoneNumber; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final String getIsoCountry() { - return this.isoCountry; - } - - public final PhoneNumberCapabilities getCapabilities() { - return this.capabilities; - } - - public final URI getUrl() { - return this.url; - } - - public final Boolean getIsReserved() { - return this.isReserved; - } - - public final Integer getInUse() { - return this.inUse; } @Override @@ -216,38 +192,40 @@ public boolean equals(final Object o) { } PhoneNumber other = (PhoneNumber) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(serviceSid, other.serviceSid) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(phoneNumber, other.phoneNumber) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(isoCountry, other.isoCountry) && - Objects.equals(capabilities, other.capabilities) && - Objects.equals(url, other.url) && - Objects.equals(isReserved, other.isReserved) && - Objects.equals(inUse, other.inUse) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(capabilities, other.capabilities) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(inUse, other.inUse) && + Objects.equals(isReserved, other.isReserved) && + Objects.equals(isoCountry, other.isoCountry) && + Objects.equals(phoneNumber, other.phoneNumber) && + Objects.equals(serviceSid, other.serviceSid) && + Objects.equals(sid, other.sid) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - sid, - accountSid, - serviceSid, - dateCreated, - dateUpdated, - phoneNumber, - friendlyName, - isoCountry, - capabilities, - url, - isReserved, - inUse + accountSid, + capabilities, + dateCreated, + dateUpdated, + friendlyName, + inUse, + isReserved, + isoCountry, + phoneNumber, + serviceSid, + sid, + url ); } + + } + diff --git a/src/main/java/com/twilio/rest/proxy/v1/service/PhoneNumberCreator.java b/src/main/java/com/twilio/rest/proxy/v1/service/PhoneNumberCreator.java index 3cd2fe5565..8b1b0d9c65 100644 --- a/src/main/java/com/twilio/rest/proxy/v1/service/PhoneNumberCreator.java +++ b/src/main/java/com/twilio/rest/proxy/v1/service/PhoneNumberCreator.java @@ -14,9 +14,12 @@ package com.twilio.rest.proxy.v1.service; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; import com.twilio.converter.Promoter; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -28,23 +31,23 @@ public class PhoneNumberCreator extends Creator { - private String pathServiceSid; + private String pathserviceSid; private String sid; private com.twilio.type.PhoneNumber phoneNumber; private Boolean isReserved; - public PhoneNumberCreator(final String pathServiceSid) { - this.pathServiceSid = pathServiceSid; + public PhoneNumberCreator(final String pathserviceSid) { + this.pathserviceSid = pathserviceSid; } + public PhoneNumberCreator setSid(final String sid) { this.sid = sid; return this; } - public PhoneNumberCreator setPhoneNumber( - final com.twilio.type.PhoneNumber phoneNumber - ) { + + public PhoneNumberCreator setPhoneNumber(final com.twilio.type.PhoneNumber phoneNumber) { this.phoneNumber = phoneNumber; return this; } @@ -58,57 +61,57 @@ public PhoneNumberCreator setIsReserved(final Boolean isReserved) { return this; } + @Override public PhoneNumber create(final TwilioRestClient client) { + String path = "/v1/Services/{ServiceSid}/PhoneNumbers"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.PROXY.toString(), - path + HttpMethod.POST, + Domains.PROXY.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "PhoneNumber creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("PhoneNumber creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return PhoneNumber.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return PhoneNumber.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (sid != null) { - request.addPostParam("Sid", sid); + Serializer.toString(request, "Sid", sid, ParameterType.URLENCODED); } + + if (phoneNumber != null) { - request.addPostParam("PhoneNumber", phoneNumber.toString()); + Serializer.toString(request, "PhoneNumber", phoneNumber, ParameterType.URLENCODED); } + + if (isReserved != null) { - request.addPostParam("IsReserved", isReserved.toString()); + Serializer.toString(request, "IsReserved", isReserved, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/proxy/v1/service/PhoneNumberDeleter.java b/src/main/java/com/twilio/rest/proxy/v1/service/PhoneNumberDeleter.java index 0bd6cc0139..ca433a92b1 100644 --- a/src/main/java/com/twilio/rest/proxy/v1/service/PhoneNumberDeleter.java +++ b/src/main/java/com/twilio/rest/proxy/v1/service/PhoneNumberDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.proxy.v1.service; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,50 +26,41 @@ public class PhoneNumberDeleter extends Deleter { - private String pathServiceSid; - private String pathSid; + private String pathserviceSid; + private String pathsid; - public PhoneNumberDeleter( - final String pathServiceSid, - final String pathSid - ) { - this.pathServiceSid = pathServiceSid; - this.pathSid = pathSid; + public PhoneNumberDeleter(final String pathserviceSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/v1/Services/{ServiceSid}/PhoneNumbers/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.PROXY.toString(), - path + HttpMethod.DELETE, + Domains.PROXY.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "PhoneNumber delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("PhoneNumber delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/proxy/v1/service/PhoneNumberFetcher.java b/src/main/java/com/twilio/rest/proxy/v1/service/PhoneNumberFetcher.java index 8a95caf8f9..64a4dcb3b5 100644 --- a/src/main/java/com/twilio/rest/proxy/v1/service/PhoneNumberFetcher.java +++ b/src/main/java/com/twilio/rest/proxy/v1/service/PhoneNumberFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.proxy.v1.service; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,57 +26,44 @@ public class PhoneNumberFetcher extends Fetcher { - private String pathServiceSid; - private String pathSid; + private String pathserviceSid; + private String pathsid; - public PhoneNumberFetcher( - final String pathServiceSid, - final String pathSid - ) { - this.pathServiceSid = pathServiceSid; - this.pathSid = pathSid; + public PhoneNumberFetcher(final String pathserviceSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathsid = pathsid; } + @Override public PhoneNumber fetch(final TwilioRestClient client) { + String path = "/v1/Services/{ServiceSid}/PhoneNumbers/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.PROXY.toString(), - path + HttpMethod.GET, + Domains.PROXY.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "PhoneNumber fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("PhoneNumber fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return PhoneNumber.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return PhoneNumber.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/proxy/v1/service/PhoneNumberReader.java b/src/main/java/com/twilio/rest/proxy/v1/service/PhoneNumberReader.java index f6c6df8d75..f4355b54cf 100644 --- a/src/main/java/com/twilio/rest/proxy/v1/service/PhoneNumberReader.java +++ b/src/main/java/com/twilio/rest/proxy/v1/service/PhoneNumberReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,115 +30,88 @@ public class PhoneNumberReader extends Reader { - private String pathServiceSid; + private String pathserviceSid; private Long pageSize; - public PhoneNumberReader(final String pathServiceSid) { - this.pathServiceSid = pathServiceSid; + public PhoneNumberReader(final String pathserviceSid) { + this.pathserviceSid = pathserviceSid; } + public PhoneNumberReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/Services/{ServiceSid}/PhoneNumbers"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.PROXY.toString(), - path + HttpMethod.GET, + Domains.PROXY.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "PhoneNumber read failed: Unable to connect to server" - ); + throw new ApiConnectionException("PhoneNumber read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "phone_numbers", - response.getContent(), - PhoneNumber.class, - client.getObjectMapper() - ); + "phone_numbers", + response.getContent(), + PhoneNumber.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.PROXY.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.PROXY.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/proxy/v1/service/PhoneNumberUpdater.java b/src/main/java/com/twilio/rest/proxy/v1/service/PhoneNumberUpdater.java index 1b6713e411..1428980826 100644 --- a/src/main/java/com/twilio/rest/proxy/v1/service/PhoneNumberUpdater.java +++ b/src/main/java/com/twilio/rest/proxy/v1/service/PhoneNumberUpdater.java @@ -16,6 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -26,70 +28,63 @@ import com.twilio.rest.Domains; public class PhoneNumberUpdater extends Updater { - - private String pathServiceSid; - private String pathSid; + private String pathserviceSid; + private String pathsid; private Boolean isReserved; - public PhoneNumberUpdater( - final String pathServiceSid, - final String pathSid - ) { - this.pathServiceSid = pathServiceSid; - this.pathSid = pathSid; + public PhoneNumberUpdater(final String pathserviceSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathsid = pathsid; } + public PhoneNumberUpdater setIsReserved(final Boolean isReserved) { this.isReserved = isReserved; return this; } + @Override public PhoneNumber update(final TwilioRestClient client) { + String path = "/v1/Services/{ServiceSid}/PhoneNumbers/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.PROXY.toString(), - path + HttpMethod.POST, + Domains.PROXY.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "PhoneNumber update failed: Unable to connect to server" - ); + throw new ApiConnectionException("PhoneNumber update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return PhoneNumber.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return PhoneNumber.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (isReserved != null) { - request.addPostParam("IsReserved", isReserved.toString()); + Serializer.toString(request, "IsReserved", isReserved, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/proxy/v1/service/Session.java b/src/main/java/com/twilio/rest/proxy/v1/service/Session.java index 2c8db7c6ad..5bffa446fe 100644 --- a/src/main/java/com/twilio/rest/proxy/v1/service/Session.java +++ b/src/main/java/com/twilio/rest/proxy/v1/service/Session.java @@ -18,69 +18,117 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Session extends Resource { - private static final long serialVersionUID = 86537474068288L; - public static SessionCreator creator(final String pathServiceSid) { - return new SessionCreator(pathServiceSid); + public static SessionCreator creator(final String pathserviceSid) { + return new SessionCreator( + pathserviceSid + ); } - public static SessionDeleter deleter( - final String pathServiceSid, - final String pathSid - ) { - return new SessionDeleter(pathServiceSid, pathSid); + + public static SessionDeleter deleter(final String pathserviceSid, final String pathsid) { + return new SessionDeleter( + pathserviceSid, pathsid + ); } - public static SessionFetcher fetcher( - final String pathServiceSid, - final String pathSid - ) { - return new SessionFetcher(pathServiceSid, pathSid); + + public static SessionFetcher fetcher(final String pathserviceSid, final String pathsid) { + return new SessionFetcher( + pathserviceSid, pathsid + ); } - public static SessionReader reader(final String pathServiceSid) { - return new SessionReader(pathServiceSid); + + public static SessionReader reader(final String pathserviceSid) { + return new SessionReader( + pathserviceSid + ); } - public static SessionUpdater updater( - final String pathServiceSid, - final String pathSid - ) { - return new SessionUpdater(pathServiceSid, pathSid); + + public static SessionUpdater updater(final String pathserviceSid, final String pathsid) { + return new SessionUpdater( + pathserviceSid, pathsid + ); + } + + + public enum Status { + OPEN("open"), + IN_PROGRESS("in-progress"), + CLOSED("closed"), + FAILED("failed"), + UNKNOWN("unknown"); + + private final String value; + + private Status(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static Status forValue(final String value) { + return Promoter.enumFromString(value, Status.values()); + } } + public enum Mode { + MESSAGE_ONLY("message-only"), + VOICE_ONLY("voice-only"), + VOICE_AND_MESSAGE("voice-and-message"); + + private final String value; + + private Mode(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static Mode forValue(final String value) { + return Promoter.enumFromString(value, Mode.values()); + } + } + + /** * Converts a JSON String into a Session object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Session object represented by the provided JSON */ - public static Session fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Session fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Session.class); @@ -95,14 +143,11 @@ public static Session fromJson( * Converts a JSON InputStream into a Session object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Session object represented by the provided JSON */ - public static Session fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Session fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Session.class); @@ -113,123 +158,93 @@ public static Session fromJson( } } - private final String sid; - private final String serviceSid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final ZonedDateTime dateStarted; + @Getter + private final String closedReason; + @Getter + private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateEnded; - private final ZonedDateTime dateLastInteraction; + @Getter private final ZonedDateTime dateExpiry; - private final String uniqueName; + @Getter + private final ZonedDateTime dateLastInteraction; + @Getter + private final ZonedDateTime dateStarted; + @Getter + private final ZonedDateTime dateUpdated; + @Getter + private final Map links; + @Getter + private final Session.Mode mode; + @Getter + private final String serviceSid; + @Getter + private final String sid; + @Getter private final Session.Status status; - private final String closedReason; + @Getter private final Integer ttl; - private final Session.Mode mode; - private final ZonedDateTime dateCreated; - private final ZonedDateTime dateUpdated; + @Getter + private final String uniqueName; + @Getter private final URI url; - private final Map links; @JsonCreator private Session( - @JsonProperty("sid") final String sid, - @JsonProperty("service_sid") final String serviceSid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("date_started") final String dateStarted, - @JsonProperty("date_ended") final String dateEnded, - @JsonProperty("date_last_interaction") final String dateLastInteraction, - @JsonProperty("date_expiry") final String dateExpiry, - @JsonProperty("unique_name") final String uniqueName, - @JsonProperty("status") final Session.Status status, - @JsonProperty("closed_reason") final String closedReason, - @JsonProperty("ttl") final Integer ttl, - @JsonProperty("mode") final Session.Mode mode, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("url") final URI url, - @JsonProperty("links") final Map links + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("closed_reason") final String closedReason, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_ended") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateEnded, + @JsonProperty("date_expiry") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateExpiry, + @JsonProperty("date_last_interaction") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateLastInteraction, + @JsonProperty("date_started") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateStarted, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("links") final Map links, + @JsonProperty("mode") final Session.Mode mode, + @JsonProperty("service_sid") final String serviceSid, + @JsonProperty("sid") final String sid, + @JsonProperty("status") final Session.Status status, + @JsonProperty("ttl") final Integer ttl, + @JsonProperty("unique_name") final String uniqueName, + @JsonProperty("url") final URI url ) { - this.sid = sid; - this.serviceSid = serviceSid; this.accountSid = accountSid; - this.dateStarted = DateConverter.iso8601DateTimeFromString(dateStarted); - this.dateEnded = DateConverter.iso8601DateTimeFromString(dateEnded); - this.dateLastInteraction = - DateConverter.iso8601DateTimeFromString(dateLastInteraction); - this.dateExpiry = DateConverter.iso8601DateTimeFromString(dateExpiry); - this.uniqueName = uniqueName; - this.status = status; this.closedReason = closedReason; - this.ttl = ttl; + this.dateCreated = dateCreated; + this.dateEnded = dateEnded; + this.dateExpiry = dateExpiry; + this.dateLastInteraction = dateLastInteraction; + this.dateStarted = dateStarted; + this.dateUpdated = dateUpdated; + this.links = links; this.mode = mode; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); + this.serviceSid = serviceSid; + this.sid = sid; + this.status = status; + this.ttl = ttl; + this.uniqueName = uniqueName; this.url = url; - this.links = links; - } - - public final String getSid() { - return this.sid; - } - - public final String getServiceSid() { - return this.serviceSid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final ZonedDateTime getDateStarted() { - return this.dateStarted; - } - - public final ZonedDateTime getDateEnded() { - return this.dateEnded; - } - - public final ZonedDateTime getDateLastInteraction() { - return this.dateLastInteraction; - } - - public final ZonedDateTime getDateExpiry() { - return this.dateExpiry; - } - - public final String getUniqueName() { - return this.uniqueName; - } - - public final Session.Status getStatus() { - return this.status; - } - - public final String getClosedReason() { - return this.closedReason; - } - - public final Integer getTtl() { - return this.ttl; - } - - public final Session.Mode getMode() { - return this.mode; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final URI getUrl() { - return this.url; - } - - public final Map getLinks() { - return this.links; } @Override @@ -243,90 +258,48 @@ public boolean equals(final Object o) { } Session other = (Session) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(serviceSid, other.serviceSid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(dateStarted, other.dateStarted) && - Objects.equals(dateEnded, other.dateEnded) && - Objects.equals(dateLastInteraction, other.dateLastInteraction) && - Objects.equals(dateExpiry, other.dateExpiry) && - Objects.equals(uniqueName, other.uniqueName) && - Objects.equals(status, other.status) && - Objects.equals(closedReason, other.closedReason) && - Objects.equals(ttl, other.ttl) && - Objects.equals(mode, other.mode) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(url, other.url) && - Objects.equals(links, other.links) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(closedReason, other.closedReason) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateEnded, other.dateEnded) && + Objects.equals(dateExpiry, other.dateExpiry) && + Objects.equals(dateLastInteraction, other.dateLastInteraction) && + Objects.equals(dateStarted, other.dateStarted) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(links, other.links) && + Objects.equals(mode, other.mode) && + Objects.equals(serviceSid, other.serviceSid) && + Objects.equals(sid, other.sid) && + Objects.equals(status, other.status) && + Objects.equals(ttl, other.ttl) && + Objects.equals(uniqueName, other.uniqueName) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - sid, - serviceSid, - accountSid, - dateStarted, - dateEnded, - dateLastInteraction, - dateExpiry, - uniqueName, - status, - closedReason, - ttl, - mode, - dateCreated, - dateUpdated, - url, - links + accountSid, + closedReason, + dateCreated, + dateEnded, + dateExpiry, + dateLastInteraction, + dateStarted, + dateUpdated, + links, + mode, + serviceSid, + sid, + status, + ttl, + uniqueName, + url ); } - public enum Status { - OPEN("open"), - IN_PROGRESS("in-progress"), - CLOSED("closed"), - FAILED("failed"), - UNKNOWN("unknown"); - - private final String value; - private Status(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static Status forValue(final String value) { - return Promoter.enumFromString(value, Status.values()); - } - } - - public enum Mode { - MESSAGE_ONLY("message-only"), - VOICE_ONLY("voice-only"), - VOICE_AND_MESSAGE("voice-and-message"); - - private final String value; - - private Mode(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static Mode forValue(final String value) { - return Promoter.enumFromString(value, Mode.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/proxy/v1/service/SessionCreator.java b/src/main/java/com/twilio/rest/proxy/v1/service/SessionCreator.java index db40a233aa..ea2d7153ce 100644 --- a/src/main/java/com/twilio/rest/proxy/v1/service/SessionCreator.java +++ b/src/main/java/com/twilio/rest/proxy/v1/service/SessionCreator.java @@ -14,11 +14,12 @@ package com.twilio.rest.proxy.v1.service; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; -import com.twilio.converter.Converter; -import com.twilio.converter.Converter; +import com.twilio.constant.EnumConstants.ParameterType; import com.twilio.converter.Promoter; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,13 +28,13 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.time.ZonedDateTime; import java.util.List; -import java.util.List; public class SessionCreator extends Creator { - private String pathServiceSid; + private String pathserviceSid; private String uniqueName; private ZonedDateTime dateExpiry; private Integer ttl; @@ -41,35 +42,41 @@ public class SessionCreator extends Creator { private Session.Status status; private List participants; - public SessionCreator(final String pathServiceSid) { - this.pathServiceSid = pathServiceSid; + public SessionCreator(final String pathserviceSid) { + this.pathserviceSid = pathserviceSid; } + public SessionCreator setUniqueName(final String uniqueName) { this.uniqueName = uniqueName; return this; } + public SessionCreator setDateExpiry(final ZonedDateTime dateExpiry) { this.dateExpiry = dateExpiry; return this; } + public SessionCreator setTtl(final Integer ttl) { this.ttl = ttl; return this; } + public SessionCreator setMode(final Session.Mode mode) { this.mode = mode; return this; } + public SessionCreator setStatus(final Session.Status status) { this.status = status; return this; } + public SessionCreator setParticipants(final List participants) { this.participants = participants; return this; @@ -81,36 +88,31 @@ public SessionCreator setParticipants(final Object participants) { @Override public Session create(final TwilioRestClient client) { + String path = "/v1/Services/{ServiceSid}/Sessions"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.PROXY.toString(), - path + HttpMethod.POST, + Domains.PROXY.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Session creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("Session creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -119,31 +121,37 @@ public Session create(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (uniqueName != null) { - request.addPostParam("UniqueName", uniqueName); + Serializer.toString(request, "UniqueName", uniqueName, ParameterType.URLENCODED); } + + if (dateExpiry != null) { - request.addPostParam( - "DateExpiry", - dateExpiry.toInstant().toString() - ); + Serializer.toString(request, "DateExpiry", dateExpiry, ParameterType.URLENCODED); } + + if (ttl != null) { - request.addPostParam("Ttl", ttl.toString()); + Serializer.toString(request, "Ttl", ttl, ParameterType.URLENCODED); } + + if (mode != null) { - request.addPostParam("Mode", mode.toString()); + Serializer.toString(request, "Mode", mode, ParameterType.URLENCODED); } + + if (status != null) { - request.addPostParam("Status", status.toString()); + Serializer.toString(request, "Status", status, ParameterType.URLENCODED); } + + if (participants != null) { - for (Object prop : participants) { - request.addPostParam( - "Participants", - Converter.objectToJson(prop) - ); + for (Object param : participants) { + Serializer.toString(request, "Participants", param, ParameterType.URLENCODED); } } + } } diff --git a/src/main/java/com/twilio/rest/proxy/v1/service/SessionDeleter.java b/src/main/java/com/twilio/rest/proxy/v1/service/SessionDeleter.java index 531d986ab2..4c406b7406 100644 --- a/src/main/java/com/twilio/rest/proxy/v1/service/SessionDeleter.java +++ b/src/main/java/com/twilio/rest/proxy/v1/service/SessionDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.proxy.v1.service; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,47 +26,41 @@ public class SessionDeleter extends Deleter { - private String pathServiceSid; - private String pathSid; + private String pathserviceSid; + private String pathsid; - public SessionDeleter(final String pathServiceSid, final String pathSid) { - this.pathServiceSid = pathServiceSid; - this.pathSid = pathSid; + public SessionDeleter(final String pathserviceSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/v1/Services/{ServiceSid}/Sessions/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.PROXY.toString(), - path + HttpMethod.DELETE, + Domains.PROXY.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Session delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("Session delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/proxy/v1/service/SessionFetcher.java b/src/main/java/com/twilio/rest/proxy/v1/service/SessionFetcher.java index ffb4f307a8..466a691e86 100644 --- a/src/main/java/com/twilio/rest/proxy/v1/service/SessionFetcher.java +++ b/src/main/java/com/twilio/rest/proxy/v1/service/SessionFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.proxy.v1.service; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,51 +26,44 @@ public class SessionFetcher extends Fetcher { - private String pathServiceSid; - private String pathSid; + private String pathserviceSid; + private String pathsid; - public SessionFetcher(final String pathServiceSid, final String pathSid) { - this.pathServiceSid = pathServiceSid; - this.pathSid = pathSid; + public SessionFetcher(final String pathserviceSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathsid = pathsid; } + @Override public Session fetch(final TwilioRestClient client) { + String path = "/v1/Services/{ServiceSid}/Sessions/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.PROXY.toString(), - path + HttpMethod.GET, + Domains.PROXY.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Session fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Session fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Session.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/proxy/v1/service/SessionReader.java b/src/main/java/com/twilio/rest/proxy/v1/service/SessionReader.java index 2eca754a08..99d8a068f7 100644 --- a/src/main/java/com/twilio/rest/proxy/v1/service/SessionReader.java +++ b/src/main/java/com/twilio/rest/proxy/v1/service/SessionReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,115 +30,88 @@ public class SessionReader extends Reader { - private String pathServiceSid; + private String pathserviceSid; private Long pageSize; - public SessionReader(final String pathServiceSid) { - this.pathServiceSid = pathServiceSid; + public SessionReader(final String pathserviceSid) { + this.pathserviceSid = pathserviceSid; } + public SessionReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/Services/{ServiceSid}/Sessions"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.PROXY.toString(), - path + HttpMethod.GET, + Domains.PROXY.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Session read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Session read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "sessions", - response.getContent(), - Session.class, - client.getObjectMapper() - ); + "sessions", + response.getContent(), + Session.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.PROXY.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.PROXY.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/proxy/v1/service/SessionUpdater.java b/src/main/java/com/twilio/rest/proxy/v1/service/SessionUpdater.java index 58b6020f14..13eca4dd9f 100644 --- a/src/main/java/com/twilio/rest/proxy/v1/service/SessionUpdater.java +++ b/src/main/java/com/twilio/rest/proxy/v1/service/SessionUpdater.java @@ -16,6 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -24,69 +26,68 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.time.ZonedDateTime; public class SessionUpdater extends Updater { - - private String pathServiceSid; - private String pathSid; + private String pathserviceSid; + private String pathsid; private ZonedDateTime dateExpiry; private Integer ttl; private Session.Status status; - public SessionUpdater(final String pathServiceSid, final String pathSid) { - this.pathServiceSid = pathServiceSid; - this.pathSid = pathSid; + public SessionUpdater(final String pathserviceSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathsid = pathsid; } + public SessionUpdater setDateExpiry(final ZonedDateTime dateExpiry) { this.dateExpiry = dateExpiry; return this; } + public SessionUpdater setTtl(final Integer ttl) { this.ttl = ttl; return this; } + public SessionUpdater setStatus(final Session.Status status) { this.status = status; return this; } + @Override public Session update(final TwilioRestClient client) { + String path = "/v1/Services/{ServiceSid}/Sessions/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.PROXY.toString(), - path + HttpMethod.POST, + Domains.PROXY.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Session update failed: Unable to connect to server" - ); + throw new ApiConnectionException("Session update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -95,17 +96,21 @@ public Session update(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (dateExpiry != null) { - request.addPostParam( - "DateExpiry", - dateExpiry.toInstant().toString() - ); + Serializer.toString(request, "DateExpiry", dateExpiry, ParameterType.URLENCODED); } + + if (ttl != null) { - request.addPostParam("Ttl", ttl.toString()); + Serializer.toString(request, "Ttl", ttl, ParameterType.URLENCODED); } + + if (status != null) { - request.addPostParam("Status", status.toString()); + Serializer.toString(request, "Status", status, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/proxy/v1/service/session/Interaction.java b/src/main/java/com/twilio/rest/proxy/v1/service/session/Interaction.java index 9167ddc0a9..8caa109e19 100644 --- a/src/main/java/com/twilio/rest/proxy/v1/service/session/Interaction.java +++ b/src/main/java/com/twilio/rest/proxy/v1/service/session/Interaction.java @@ -18,61 +18,118 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Interaction extends Resource { - private static final long serialVersionUID = 104550389018086L; - public static InteractionDeleter deleter( - final String pathServiceSid, - final String pathSessionSid, - final String pathSid - ) { - return new InteractionDeleter(pathServiceSid, pathSessionSid, pathSid); + public static InteractionDeleter deleter(final String pathserviceSid, final String pathsessionSid, final String pathsid) { + return new InteractionDeleter( + pathserviceSid, pathsessionSid, pathsid + ); } - public static InteractionFetcher fetcher( - final String pathServiceSid, - final String pathSessionSid, - final String pathSid - ) { - return new InteractionFetcher(pathServiceSid, pathSessionSid, pathSid); + + public static InteractionFetcher fetcher(final String pathserviceSid, final String pathsessionSid, final String pathsid) { + return new InteractionFetcher( + pathserviceSid, pathsessionSid, pathsid + ); } - public static InteractionReader reader( - final String pathServiceSid, - final String pathSessionSid - ) { - return new InteractionReader(pathServiceSid, pathSessionSid); + + public static InteractionReader reader(final String pathserviceSid, final String pathsessionSid) { + return new InteractionReader( + pathserviceSid, pathsessionSid + ); + } + + + public enum Type { + MESSAGE("message"), + VOICE("voice"), + UNKNOWN("unknown"); + + private final String value; + + private Type(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static Type forValue(final String value) { + return Promoter.enumFromString(value, Type.values()); + } + } + + public enum ResourceStatus { + ACCEPTED("accepted"), + ANSWERED("answered"), + BUSY("busy"), + CANCELED("canceled"), + COMPLETED("completed"), + DELETED("deleted"), + DELIVERED("delivered"), + DELIVERY_UNKNOWN("delivery-unknown"), + FAILED("failed"), + IN_PROGRESS("in-progress"), + INITIATED("initiated"), + NO_ANSWER("no-answer"), + QUEUED("queued"), + RECEIVED("received"), + RECEIVING("receiving"), + RINGING("ringing"), + SCHEDULED("scheduled"), + SENDING("sending"), + SENT("sent"), + UNDELIVERED("undelivered"), + UNKNOWN("unknown"); + + private final String value; + + private ResourceStatus(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static ResourceStatus forValue(final String value) { + return Promoter.enumFromString(value, ResourceStatus.values()); + } } + /** * Converts a JSON String into a Interaction object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Interaction object represented by the provided JSON */ - public static Interaction fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Interaction fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Interaction.class); @@ -87,14 +144,11 @@ public static Interaction fromJson( * Converts a JSON InputStream into a Interaction object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Interaction object represented by the provided JSON */ - public static Interaction fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Interaction fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Interaction.class); @@ -105,64 +159,86 @@ public static Interaction fromJson( } } - private final String sid; - private final String sessionSid; - private final String serviceSid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; + @Getter private final String data; - private final Interaction.Type type; + @Getter + private final ZonedDateTime dateCreated; + @Getter + private final ZonedDateTime dateUpdated; + @Getter private final String inboundParticipantSid; + @Getter private final String inboundResourceSid; + @Getter private final Interaction.ResourceStatus inboundResourceStatus; + @Getter private final String inboundResourceType; + @Getter private final URI inboundResourceUrl; + @Getter private final String outboundParticipantSid; + @Getter private final String outboundResourceSid; + @Getter private final Interaction.ResourceStatus outboundResourceStatus; + @Getter private final String outboundResourceType; + @Getter private final URI outboundResourceUrl; - private final ZonedDateTime dateCreated; - private final ZonedDateTime dateUpdated; + @Getter + private final String serviceSid; + @Getter + private final String sessionSid; + @Getter + private final String sid; + @Getter + private final Interaction.Type type; + @Getter private final URI url; @JsonCreator private Interaction( - @JsonProperty("sid") final String sid, - @JsonProperty("session_sid") final String sessionSid, - @JsonProperty("service_sid") final String serviceSid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("data") final String data, - @JsonProperty("type") final Interaction.Type type, - @JsonProperty( - "inbound_participant_sid" - ) final String inboundParticipantSid, - @JsonProperty("inbound_resource_sid") final String inboundResourceSid, - @JsonProperty( - "inbound_resource_status" - ) final Interaction.ResourceStatus inboundResourceStatus, - @JsonProperty("inbound_resource_type") final String inboundResourceType, - @JsonProperty("inbound_resource_url") final URI inboundResourceUrl, - @JsonProperty( - "outbound_participant_sid" - ) final String outboundParticipantSid, - @JsonProperty("outbound_resource_sid") final String outboundResourceSid, - @JsonProperty( - "outbound_resource_status" - ) final Interaction.ResourceStatus outboundResourceStatus, - @JsonProperty( - "outbound_resource_type" - ) final String outboundResourceType, - @JsonProperty("outbound_resource_url") final URI outboundResourceUrl, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("url") final URI url + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("data") final String data, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("inbound_participant_sid") final String inboundParticipantSid, + @JsonProperty("inbound_resource_sid") final String inboundResourceSid, + @JsonProperty("inbound_resource_status") final Interaction.ResourceStatus inboundResourceStatus, + @JsonProperty("inbound_resource_type") final String inboundResourceType, + @JsonProperty("inbound_resource_url") final URI inboundResourceUrl, + @JsonProperty("outbound_participant_sid") final String outboundParticipantSid, + @JsonProperty("outbound_resource_sid") final String outboundResourceSid, + @JsonProperty("outbound_resource_status") final Interaction.ResourceStatus outboundResourceStatus, + @JsonProperty("outbound_resource_type") final String outboundResourceType, + @JsonProperty("outbound_resource_url") final URI outboundResourceUrl, + @JsonProperty("service_sid") final String serviceSid, + @JsonProperty("session_sid") final String sessionSid, + @JsonProperty("sid") final String sid, + @JsonProperty("type") final Interaction.Type type, + @JsonProperty("url") final URI url ) { - this.sid = sid; - this.sessionSid = sessionSid; - this.serviceSid = serviceSid; this.accountSid = accountSid; this.data = data; - this.type = type; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.inboundParticipantSid = inboundParticipantSid; this.inboundResourceSid = inboundResourceSid; this.inboundResourceStatus = inboundResourceStatus; @@ -173,87 +249,13 @@ private Interaction( this.outboundResourceStatus = outboundResourceStatus; this.outboundResourceType = outboundResourceType; this.outboundResourceUrl = outboundResourceUrl; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); + this.serviceSid = serviceSid; + this.sessionSid = sessionSid; + this.sid = sid; + this.type = type; this.url = url; } - public final String getSid() { - return this.sid; - } - - public final String getSessionSid() { - return this.sessionSid; - } - - public final String getServiceSid() { - return this.serviceSid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getData() { - return this.data; - } - - public final Interaction.Type getType() { - return this.type; - } - - public final String getInboundParticipantSid() { - return this.inboundParticipantSid; - } - - public final String getInboundResourceSid() { - return this.inboundResourceSid; - } - - public final Interaction.ResourceStatus getInboundResourceStatus() { - return this.inboundResourceStatus; - } - - public final String getInboundResourceType() { - return this.inboundResourceType; - } - - public final URI getInboundResourceUrl() { - return this.inboundResourceUrl; - } - - public final String getOutboundParticipantSid() { - return this.outboundParticipantSid; - } - - public final String getOutboundResourceSid() { - return this.outboundResourceSid; - } - - public final Interaction.ResourceStatus getOutboundResourceStatus() { - return this.outboundResourceStatus; - } - - public final String getOutboundResourceType() { - return this.outboundResourceType; - } - - public final URI getOutboundResourceUrl() { - return this.outboundResourceUrl; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final URI getUrl() { - return this.url; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -265,124 +267,54 @@ public boolean equals(final Object o) { } Interaction other = (Interaction) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(sessionSid, other.sessionSid) && - Objects.equals(serviceSid, other.serviceSid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(data, other.data) && - Objects.equals(type, other.type) && - Objects.equals( - inboundParticipantSid, - other.inboundParticipantSid - ) && - Objects.equals(inboundResourceSid, other.inboundResourceSid) && - Objects.equals( - inboundResourceStatus, - other.inboundResourceStatus - ) && - Objects.equals(inboundResourceType, other.inboundResourceType) && - Objects.equals(inboundResourceUrl, other.inboundResourceUrl) && - Objects.equals( - outboundParticipantSid, - other.outboundParticipantSid - ) && - Objects.equals(outboundResourceSid, other.outboundResourceSid) && - Objects.equals( - outboundResourceStatus, - other.outboundResourceStatus - ) && - Objects.equals(outboundResourceType, other.outboundResourceType) && - Objects.equals(outboundResourceUrl, other.outboundResourceUrl) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(url, other.url) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(data, other.data) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(inboundParticipantSid, other.inboundParticipantSid) && + Objects.equals(inboundResourceSid, other.inboundResourceSid) && + Objects.equals(inboundResourceStatus, other.inboundResourceStatus) && + Objects.equals(inboundResourceType, other.inboundResourceType) && + Objects.equals(inboundResourceUrl, other.inboundResourceUrl) && + Objects.equals(outboundParticipantSid, other.outboundParticipantSid) && + Objects.equals(outboundResourceSid, other.outboundResourceSid) && + Objects.equals(outboundResourceStatus, other.outboundResourceStatus) && + Objects.equals(outboundResourceType, other.outboundResourceType) && + Objects.equals(outboundResourceUrl, other.outboundResourceUrl) && + Objects.equals(serviceSid, other.serviceSid) && + Objects.equals(sessionSid, other.sessionSid) && + Objects.equals(sid, other.sid) && + Objects.equals(type, other.type) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - sid, - sessionSid, - serviceSid, - accountSid, - data, - type, - inboundParticipantSid, - inboundResourceSid, - inboundResourceStatus, - inboundResourceType, - inboundResourceUrl, - outboundParticipantSid, - outboundResourceSid, - outboundResourceStatus, - outboundResourceType, - outboundResourceUrl, - dateCreated, - dateUpdated, - url + accountSid, + data, + dateCreated, + dateUpdated, + inboundParticipantSid, + inboundResourceSid, + inboundResourceStatus, + inboundResourceType, + inboundResourceUrl, + outboundParticipantSid, + outboundResourceSid, + outboundResourceStatus, + outboundResourceType, + outboundResourceUrl, + serviceSid, + sessionSid, + sid, + type, + url ); } - public enum ResourceStatus { - ACCEPTED("accepted"), - ANSWERED("answered"), - BUSY("busy"), - CANCELED("canceled"), - COMPLETED("completed"), - DELETED("deleted"), - DELIVERED("delivered"), - DELIVERY_UNKNOWN("delivery-unknown"), - FAILED("failed"), - IN_PROGRESS("in-progress"), - INITIATED("initiated"), - NO_ANSWER("no-answer"), - QUEUED("queued"), - RECEIVED("received"), - RECEIVING("receiving"), - RINGING("ringing"), - SCHEDULED("scheduled"), - SENDING("sending"), - SENT("sent"), - UNDELIVERED("undelivered"), - UNKNOWN("unknown"); - - private final String value; - - private ResourceStatus(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static ResourceStatus forValue(final String value) { - return Promoter.enumFromString(value, ResourceStatus.values()); - } - } - - public enum Type { - MESSAGE("message"), - VOICE("voice"), - UNKNOWN("unknown"); - - private final String value; - - private Type(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - @JsonCreator - public static Type forValue(final String value) { - return Promoter.enumFromString(value, Type.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/proxy/v1/service/session/InteractionDeleter.java b/src/main/java/com/twilio/rest/proxy/v1/service/session/InteractionDeleter.java index 4bf4c52776..491ba6ffc2 100644 --- a/src/main/java/com/twilio/rest/proxy/v1/service/session/InteractionDeleter.java +++ b/src/main/java/com/twilio/rest/proxy/v1/service/session/InteractionDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.proxy.v1.service.session; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,59 +26,44 @@ public class InteractionDeleter extends Deleter { - private String pathServiceSid; - private String pathSessionSid; - private String pathSid; + private String pathserviceSid; + private String pathsessionSid; + private String pathsid; - public InteractionDeleter( - final String pathServiceSid, - final String pathSessionSid, - final String pathSid - ) { - this.pathServiceSid = pathServiceSid; - this.pathSessionSid = pathSessionSid; - this.pathSid = pathSid; + public InteractionDeleter(final String pathserviceSid, final String pathsessionSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathsessionSid = pathsessionSid; + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { - String path = - "/v1/Services/{ServiceSid}/Sessions/{SessionSid}/Interactions/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = - path.replace( - "{" + "SessionSid" + "}", - this.pathSessionSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/v1/Services/{ServiceSid}/Sessions/{SessionSid}/Interactions/{Sid}"; + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "SessionSid" + "}", this.pathsessionSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.PROXY.toString(), - path + HttpMethod.DELETE, + Domains.PROXY.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Interaction delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("Interaction delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/proxy/v1/service/session/InteractionFetcher.java b/src/main/java/com/twilio/rest/proxy/v1/service/session/InteractionFetcher.java index 57dc6e524d..a32d753926 100644 --- a/src/main/java/com/twilio/rest/proxy/v1/service/session/InteractionFetcher.java +++ b/src/main/java/com/twilio/rest/proxy/v1/service/session/InteractionFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.proxy.v1.service.session; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,66 +26,47 @@ public class InteractionFetcher extends Fetcher { - private String pathServiceSid; - private String pathSessionSid; - private String pathSid; + private String pathserviceSid; + private String pathsessionSid; + private String pathsid; - public InteractionFetcher( - final String pathServiceSid, - final String pathSessionSid, - final String pathSid - ) { - this.pathServiceSid = pathServiceSid; - this.pathSessionSid = pathSessionSid; - this.pathSid = pathSid; + public InteractionFetcher(final String pathserviceSid, final String pathsessionSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathsessionSid = pathsessionSid; + this.pathsid = pathsid; } + @Override public Interaction fetch(final TwilioRestClient client) { - String path = - "/v1/Services/{ServiceSid}/Sessions/{SessionSid}/Interactions/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = - path.replace( - "{" + "SessionSid" + "}", - this.pathSessionSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/v1/Services/{ServiceSid}/Sessions/{SessionSid}/Interactions/{Sid}"; + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "SessionSid" + "}", this.pathsessionSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.PROXY.toString(), - path + HttpMethod.GET, + Domains.PROXY.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Interaction fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Interaction fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return Interaction.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Interaction.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/proxy/v1/service/session/InteractionReader.java b/src/main/java/com/twilio/rest/proxy/v1/service/session/InteractionReader.java index 5a67027658..60afa6c621 100644 --- a/src/main/java/com/twilio/rest/proxy/v1/service/session/InteractionReader.java +++ b/src/main/java/com/twilio/rest/proxy/v1/service/session/InteractionReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,126 +30,91 @@ public class InteractionReader extends Reader { - private String pathServiceSid; - private String pathSessionSid; + private String pathserviceSid; + private String pathsessionSid; private Long pageSize; - public InteractionReader( - final String pathServiceSid, - final String pathSessionSid - ) { - this.pathServiceSid = pathServiceSid; - this.pathSessionSid = pathSessionSid; + public InteractionReader(final String pathserviceSid, final String pathsessionSid) { + this.pathserviceSid = pathserviceSid; + this.pathsessionSid = pathsessionSid; } + public InteractionReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { - String path = - "/v1/Services/{ServiceSid}/Sessions/{SessionSid}/Interactions"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = - path.replace( - "{" + "SessionSid" + "}", - this.pathSessionSid.toString() - ); + + String path = "/v1/Services/{ServiceSid}/Sessions/{SessionSid}/Interactions"; + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "SessionSid" + "}", this.pathsessionSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.PROXY.toString(), - path + HttpMethod.GET, + Domains.PROXY.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Interaction read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Interaction read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "interactions", - response.getContent(), - Interaction.class, - client.getObjectMapper() - ); + "interactions", + response.getContent(), + Interaction.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.PROXY.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.PROXY.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/proxy/v1/service/session/Participant.java b/src/main/java/com/twilio/rest/proxy/v1/service/session/Participant.java index dc56bc5c04..56aff6f888 100644 --- a/src/main/java/com/twilio/rest/proxy/v1/service/session/Participant.java +++ b/src/main/java/com/twilio/rest/proxy/v1/service/session/Participant.java @@ -18,74 +18,64 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Participant extends Resource { - private static final long serialVersionUID = 85413043665121L; - public static ParticipantCreator creator( - final String pathServiceSid, - final String pathSessionSid, - final String identifier - ) { + public static ParticipantCreator creator(final String pathserviceSid, final String pathsessionSid, final String identifier) { return new ParticipantCreator( - pathServiceSid, - pathSessionSid, - identifier + pathserviceSid, pathsessionSid, identifier ); } - public static ParticipantDeleter deleter( - final String pathServiceSid, - final String pathSessionSid, - final String pathSid - ) { - return new ParticipantDeleter(pathServiceSid, pathSessionSid, pathSid); + + public static ParticipantDeleter deleter(final String pathserviceSid, final String pathsessionSid, final String pathsid) { + return new ParticipantDeleter( + pathserviceSid, pathsessionSid, pathsid + ); } - public static ParticipantFetcher fetcher( - final String pathServiceSid, - final String pathSessionSid, - final String pathSid - ) { - return new ParticipantFetcher(pathServiceSid, pathSessionSid, pathSid); + + public static ParticipantFetcher fetcher(final String pathserviceSid, final String pathsessionSid, final String pathsid) { + return new ParticipantFetcher( + pathserviceSid, pathsessionSid, pathsid + ); } - public static ParticipantReader reader( - final String pathServiceSid, - final String pathSessionSid - ) { - return new ParticipantReader(pathServiceSid, pathSessionSid); + + public static ParticipantReader reader(final String pathserviceSid, final String pathsessionSid) { + return new ParticipantReader( + pathserviceSid, pathsessionSid + ); } + /** * Converts a JSON String into a Participant object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Participant object represented by the provided JSON */ - public static Participant fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Participant fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Participant.class); @@ -100,14 +90,11 @@ public static Participant fromJson( * Converts a JSON InputStream into a Participant object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Participant object represented by the provided JSON */ - public static Participant fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Participant fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Participant.class); @@ -118,101 +105,78 @@ public static Participant fromJson( } } - private final String sid; - private final String sessionSid; - private final String serviceSid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; + @Getter + private final ZonedDateTime dateCreated; + @Getter + private final ZonedDateTime dateDeleted; + @Getter + private final ZonedDateTime dateUpdated; + @Getter private final String friendlyName; + @Getter private final String identifier; + @Getter + private final Map links; + @Getter private final String proxyIdentifier; + @Getter private final String proxyIdentifierSid; - private final ZonedDateTime dateDeleted; - private final ZonedDateTime dateCreated; - private final ZonedDateTime dateUpdated; + @Getter + private final String serviceSid; + @Getter + private final String sessionSid; + @Getter + private final String sid; + @Getter private final URI url; - private final Map links; @JsonCreator private Participant( - @JsonProperty("sid") final String sid, - @JsonProperty("session_sid") final String sessionSid, - @JsonProperty("service_sid") final String serviceSid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("identifier") final String identifier, - @JsonProperty("proxy_identifier") final String proxyIdentifier, - @JsonProperty("proxy_identifier_sid") final String proxyIdentifierSid, - @JsonProperty("date_deleted") final String dateDeleted, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("url") final URI url, - @JsonProperty("links") final Map links + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_deleted") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateDeleted, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("identifier") final String identifier, + @JsonProperty("links") final Map links, + @JsonProperty("proxy_identifier") final String proxyIdentifier, + @JsonProperty("proxy_identifier_sid") final String proxyIdentifierSid, + @JsonProperty("service_sid") final String serviceSid, + @JsonProperty("session_sid") final String sessionSid, + @JsonProperty("sid") final String sid, + @JsonProperty("url") final URI url ) { - this.sid = sid; - this.sessionSid = sessionSid; - this.serviceSid = serviceSid; this.accountSid = accountSid; + this.dateCreated = dateCreated; + this.dateDeleted = dateDeleted; + this.dateUpdated = dateUpdated; this.friendlyName = friendlyName; this.identifier = identifier; + this.links = links; this.proxyIdentifier = proxyIdentifier; this.proxyIdentifierSid = proxyIdentifierSid; - this.dateDeleted = DateConverter.iso8601DateTimeFromString(dateDeleted); - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); + this.serviceSid = serviceSid; + this.sessionSid = sessionSid; + this.sid = sid; this.url = url; - this.links = links; - } - - public final String getSid() { - return this.sid; - } - - public final String getSessionSid() { - return this.sessionSid; - } - - public final String getServiceSid() { - return this.serviceSid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final String getIdentifier() { - return this.identifier; - } - - public final String getProxyIdentifier() { - return this.proxyIdentifier; - } - - public final String getProxyIdentifierSid() { - return this.proxyIdentifierSid; - } - - public final ZonedDateTime getDateDeleted() { - return this.dateDeleted; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final URI getUrl() { - return this.url; - } - - public final Map getLinks() { - return this.links; } @Override @@ -226,40 +190,42 @@ public boolean equals(final Object o) { } Participant other = (Participant) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(sessionSid, other.sessionSid) && - Objects.equals(serviceSid, other.serviceSid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(identifier, other.identifier) && - Objects.equals(proxyIdentifier, other.proxyIdentifier) && - Objects.equals(proxyIdentifierSid, other.proxyIdentifierSid) && - Objects.equals(dateDeleted, other.dateDeleted) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(url, other.url) && - Objects.equals(links, other.links) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateDeleted, other.dateDeleted) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(identifier, other.identifier) && + Objects.equals(links, other.links) && + Objects.equals(proxyIdentifier, other.proxyIdentifier) && + Objects.equals(proxyIdentifierSid, other.proxyIdentifierSid) && + Objects.equals(serviceSid, other.serviceSid) && + Objects.equals(sessionSid, other.sessionSid) && + Objects.equals(sid, other.sid) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - sid, - sessionSid, - serviceSid, - accountSid, - friendlyName, - identifier, - proxyIdentifier, - proxyIdentifierSid, - dateDeleted, - dateCreated, - dateUpdated, - url, - links + accountSid, + dateCreated, + dateDeleted, + dateUpdated, + friendlyName, + identifier, + links, + proxyIdentifier, + proxyIdentifierSid, + serviceSid, + sessionSid, + sid, + url ); } + + } + diff --git a/src/main/java/com/twilio/rest/proxy/v1/service/session/ParticipantCreator.java b/src/main/java/com/twilio/rest/proxy/v1/service/session/ParticipantCreator.java index cde5261a10..bd05ef4a1f 100644 --- a/src/main/java/com/twilio/rest/proxy/v1/service/session/ParticipantCreator.java +++ b/src/main/java/com/twilio/rest/proxy/v1/service/session/ParticipantCreator.java @@ -14,8 +14,11 @@ package com.twilio.rest.proxy.v1.service.session; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,107 +30,100 @@ public class ParticipantCreator extends Creator { - private String pathServiceSid; - private String pathSessionSid; + private String pathserviceSid; + private String pathsessionSid; private String identifier; private String friendlyName; private String proxyIdentifier; private String proxyIdentifierSid; - public ParticipantCreator( - final String pathServiceSid, - final String pathSessionSid, - final String identifier - ) { - this.pathServiceSid = pathServiceSid; - this.pathSessionSid = pathSessionSid; + public ParticipantCreator(final String pathserviceSid, final String pathsessionSid, final String identifier) { + this.pathserviceSid = pathserviceSid; + this.pathsessionSid = pathsessionSid; this.identifier = identifier; } + public ParticipantCreator setIdentifier(final String identifier) { this.identifier = identifier; return this; } + public ParticipantCreator setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + public ParticipantCreator setProxyIdentifier(final String proxyIdentifier) { this.proxyIdentifier = proxyIdentifier; return this; } - public ParticipantCreator setProxyIdentifierSid( - final String proxyIdentifierSid - ) { + + public ParticipantCreator setProxyIdentifierSid(final String proxyIdentifierSid) { this.proxyIdentifierSid = proxyIdentifierSid; return this; } + @Override public Participant create(final TwilioRestClient client) { - String path = - "/v1/Services/{ServiceSid}/Sessions/{SessionSid}/Participants"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = - path.replace( - "{" + "SessionSid" + "}", - this.pathSessionSid.toString() - ); - path = - path.replace("{" + "Identifier" + "}", this.identifier.toString()); + String path = "/v1/Services/{ServiceSid}/Sessions/{SessionSid}/Participants"; + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "SessionSid" + "}", this.pathsessionSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.PROXY.toString(), - path + HttpMethod.POST, + Domains.PROXY.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Participant creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("Participant creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Participant.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Participant.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (identifier != null) { - request.addPostParam("Identifier", identifier); + Serializer.toString(request, "Identifier", identifier, ParameterType.URLENCODED); } + + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + if (proxyIdentifier != null) { - request.addPostParam("ProxyIdentifier", proxyIdentifier); + Serializer.toString(request, "ProxyIdentifier", proxyIdentifier, ParameterType.URLENCODED); } + + if (proxyIdentifierSid != null) { - request.addPostParam("ProxyIdentifierSid", proxyIdentifierSid); + Serializer.toString(request, "ProxyIdentifierSid", proxyIdentifierSid, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/proxy/v1/service/session/ParticipantDeleter.java b/src/main/java/com/twilio/rest/proxy/v1/service/session/ParticipantDeleter.java index 0ef7a5f609..dd0f73f439 100644 --- a/src/main/java/com/twilio/rest/proxy/v1/service/session/ParticipantDeleter.java +++ b/src/main/java/com/twilio/rest/proxy/v1/service/session/ParticipantDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.proxy.v1.service.session; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,59 +26,44 @@ public class ParticipantDeleter extends Deleter { - private String pathServiceSid; - private String pathSessionSid; - private String pathSid; + private String pathserviceSid; + private String pathsessionSid; + private String pathsid; - public ParticipantDeleter( - final String pathServiceSid, - final String pathSessionSid, - final String pathSid - ) { - this.pathServiceSid = pathServiceSid; - this.pathSessionSid = pathSessionSid; - this.pathSid = pathSid; + public ParticipantDeleter(final String pathserviceSid, final String pathsessionSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathsessionSid = pathsessionSid; + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { - String path = - "/v1/Services/{ServiceSid}/Sessions/{SessionSid}/Participants/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = - path.replace( - "{" + "SessionSid" + "}", - this.pathSessionSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/v1/Services/{ServiceSid}/Sessions/{SessionSid}/Participants/{Sid}"; + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "SessionSid" + "}", this.pathsessionSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.PROXY.toString(), - path + HttpMethod.DELETE, + Domains.PROXY.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Participant delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("Participant delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/proxy/v1/service/session/ParticipantFetcher.java b/src/main/java/com/twilio/rest/proxy/v1/service/session/ParticipantFetcher.java index e3747402c4..35121c7d64 100644 --- a/src/main/java/com/twilio/rest/proxy/v1/service/session/ParticipantFetcher.java +++ b/src/main/java/com/twilio/rest/proxy/v1/service/session/ParticipantFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.proxy.v1.service.session; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,66 +26,47 @@ public class ParticipantFetcher extends Fetcher { - private String pathServiceSid; - private String pathSessionSid; - private String pathSid; + private String pathserviceSid; + private String pathsessionSid; + private String pathsid; - public ParticipantFetcher( - final String pathServiceSid, - final String pathSessionSid, - final String pathSid - ) { - this.pathServiceSid = pathServiceSid; - this.pathSessionSid = pathSessionSid; - this.pathSid = pathSid; + public ParticipantFetcher(final String pathserviceSid, final String pathsessionSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathsessionSid = pathsessionSid; + this.pathsid = pathsid; } + @Override public Participant fetch(final TwilioRestClient client) { - String path = - "/v1/Services/{ServiceSid}/Sessions/{SessionSid}/Participants/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = - path.replace( - "{" + "SessionSid" + "}", - this.pathSessionSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/v1/Services/{ServiceSid}/Sessions/{SessionSid}/Participants/{Sid}"; + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "SessionSid" + "}", this.pathsessionSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.PROXY.toString(), - path + HttpMethod.GET, + Domains.PROXY.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Participant fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Participant fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return Participant.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Participant.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/proxy/v1/service/session/ParticipantReader.java b/src/main/java/com/twilio/rest/proxy/v1/service/session/ParticipantReader.java index 68d3d0699d..650207ed32 100644 --- a/src/main/java/com/twilio/rest/proxy/v1/service/session/ParticipantReader.java +++ b/src/main/java/com/twilio/rest/proxy/v1/service/session/ParticipantReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,126 +30,91 @@ public class ParticipantReader extends Reader { - private String pathServiceSid; - private String pathSessionSid; + private String pathserviceSid; + private String pathsessionSid; private Long pageSize; - public ParticipantReader( - final String pathServiceSid, - final String pathSessionSid - ) { - this.pathServiceSid = pathServiceSid; - this.pathSessionSid = pathSessionSid; + public ParticipantReader(final String pathserviceSid, final String pathsessionSid) { + this.pathserviceSid = pathserviceSid; + this.pathsessionSid = pathsessionSid; } + public ParticipantReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { - String path = - "/v1/Services/{ServiceSid}/Sessions/{SessionSid}/Participants"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = - path.replace( - "{" + "SessionSid" + "}", - this.pathSessionSid.toString() - ); + + String path = "/v1/Services/{ServiceSid}/Sessions/{SessionSid}/Participants"; + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "SessionSid" + "}", this.pathsessionSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.PROXY.toString(), - path + HttpMethod.GET, + Domains.PROXY.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Participant read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Participant read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "participants", - response.getContent(), - Participant.class, - client.getObjectMapper() - ); + "participants", + response.getContent(), + Participant.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.PROXY.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.PROXY.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/proxy/v1/service/session/participant/MessageInteraction.java b/src/main/java/com/twilio/rest/proxy/v1/service/session/participant/MessageInteraction.java index 2cc5764aa6..c719843558 100644 --- a/src/main/java/com/twilio/rest/proxy/v1/service/session/participant/MessageInteraction.java +++ b/src/main/java/com/twilio/rest/proxy/v1/service/session/participant/MessageInteraction.java @@ -18,93 +18,126 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.List; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class MessageInteraction extends Resource { - private static final long serialVersionUID = 183572948894378L; - public static MessageInteractionCreator creator( - final String pathServiceSid, - final String pathSessionSid, - final String pathParticipantSid, - final String body - ) { + public static MessageInteractionCreator creator(final String pathserviceSid, final String pathsessionSid, final String pathparticipantSid, final String body) { return new MessageInteractionCreator( - pathServiceSid, - pathSessionSid, - pathParticipantSid, - body + pathserviceSid, pathsessionSid, pathparticipantSid, body ); } - public static MessageInteractionCreator creator( - final String pathServiceSid, - final String pathSessionSid, - final String pathParticipantSid, - final List mediaUrl - ) { + + public static MessageInteractionCreator creator(final String pathserviceSid, final String pathsessionSid, final String pathparticipantSid, final List mediaUrl) { return new MessageInteractionCreator( - pathServiceSid, - pathSessionSid, - pathParticipantSid, - mediaUrl + pathserviceSid, pathsessionSid, pathparticipantSid, mediaUrl ); } - public static MessageInteractionFetcher fetcher( - final String pathServiceSid, - final String pathSessionSid, - final String pathParticipantSid, - final String pathSid - ) { + + public static MessageInteractionFetcher fetcher(final String pathserviceSid, final String pathsessionSid, final String pathparticipantSid, final String pathsid) { return new MessageInteractionFetcher( - pathServiceSid, - pathSessionSid, - pathParticipantSid, - pathSid + pathserviceSid, pathsessionSid, pathparticipantSid, pathsid ); } - public static MessageInteractionReader reader( - final String pathServiceSid, - final String pathSessionSid, - final String pathParticipantSid - ) { + + public static MessageInteractionReader reader(final String pathserviceSid, final String pathsessionSid, final String pathparticipantSid) { return new MessageInteractionReader( - pathServiceSid, - pathSessionSid, - pathParticipantSid + pathserviceSid, pathsessionSid, pathparticipantSid ); } + + public enum Type { + MESSAGE("message"), + VOICE("voice"), + UNKNOWN("unknown"); + + private final String value; + + private Type(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static Type forValue(final String value) { + return Promoter.enumFromString(value, Type.values()); + } + } + + public enum ResourceStatus { + ACCEPTED("accepted"), + ANSWERED("answered"), + BUSY("busy"), + CANCELED("canceled"), + COMPLETED("completed"), + DELETED("deleted"), + DELIVERED("delivered"), + DELIVERY_UNKNOWN("delivery-unknown"), + FAILED("failed"), + IN_PROGRESS("in-progress"), + INITIATED("initiated"), + NO_ANSWER("no-answer"), + QUEUED("queued"), + RECEIVED("received"), + RECEIVING("receiving"), + RINGING("ringing"), + SCHEDULED("scheduled"), + SENDING("sending"), + SENT("sent"), + UNDELIVERED("undelivered"), + UNKNOWN("unknown"); + + private final String value; + + private ResourceStatus(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static ResourceStatus forValue(final String value) { + return Promoter.enumFromString(value, ResourceStatus.values()); + } + } + + /** * Converts a JSON String into a MessageInteraction object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return MessageInteraction object represented by the provided JSON */ - public static MessageInteraction fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static MessageInteraction fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, MessageInteraction.class); @@ -119,14 +152,11 @@ public static MessageInteraction fromJson( * Converts a JSON InputStream into a MessageInteraction object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return MessageInteraction object represented by the provided JSON */ - public static MessageInteraction fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static MessageInteraction fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, MessageInteraction.class); @@ -137,67 +167,89 @@ public static MessageInteraction fromJson( } } - private final String sid; - private final String sessionSid; - private final String serviceSid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; + @Getter private final String data; - private final MessageInteraction.Type type; - private final String participantSid; + @Getter + private final ZonedDateTime dateCreated; + @Getter + private final ZonedDateTime dateUpdated; + @Getter private final String inboundParticipantSid; + @Getter private final String inboundResourceSid; + @Getter private final MessageInteraction.ResourceStatus inboundResourceStatus; + @Getter private final String inboundResourceType; + @Getter private final URI inboundResourceUrl; + @Getter private final String outboundParticipantSid; + @Getter private final String outboundResourceSid; + @Getter private final MessageInteraction.ResourceStatus outboundResourceStatus; + @Getter private final String outboundResourceType; + @Getter private final URI outboundResourceUrl; - private final ZonedDateTime dateCreated; - private final ZonedDateTime dateUpdated; + @Getter + private final String participantSid; + @Getter + private final String serviceSid; + @Getter + private final String sessionSid; + @Getter + private final String sid; + @Getter + private final MessageInteraction.Type type; + @Getter private final URI url; @JsonCreator private MessageInteraction( - @JsonProperty("sid") final String sid, - @JsonProperty("session_sid") final String sessionSid, - @JsonProperty("service_sid") final String serviceSid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("data") final String data, - @JsonProperty("type") final MessageInteraction.Type type, - @JsonProperty("participant_sid") final String participantSid, - @JsonProperty( - "inbound_participant_sid" - ) final String inboundParticipantSid, - @JsonProperty("inbound_resource_sid") final String inboundResourceSid, - @JsonProperty( - "inbound_resource_status" - ) final MessageInteraction.ResourceStatus inboundResourceStatus, - @JsonProperty("inbound_resource_type") final String inboundResourceType, - @JsonProperty("inbound_resource_url") final URI inboundResourceUrl, - @JsonProperty( - "outbound_participant_sid" - ) final String outboundParticipantSid, - @JsonProperty("outbound_resource_sid") final String outboundResourceSid, - @JsonProperty( - "outbound_resource_status" - ) final MessageInteraction.ResourceStatus outboundResourceStatus, - @JsonProperty( - "outbound_resource_type" - ) final String outboundResourceType, - @JsonProperty("outbound_resource_url") final URI outboundResourceUrl, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("url") final URI url + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("data") final String data, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("inbound_participant_sid") final String inboundParticipantSid, + @JsonProperty("inbound_resource_sid") final String inboundResourceSid, + @JsonProperty("inbound_resource_status") final MessageInteraction.ResourceStatus inboundResourceStatus, + @JsonProperty("inbound_resource_type") final String inboundResourceType, + @JsonProperty("inbound_resource_url") final URI inboundResourceUrl, + @JsonProperty("outbound_participant_sid") final String outboundParticipantSid, + @JsonProperty("outbound_resource_sid") final String outboundResourceSid, + @JsonProperty("outbound_resource_status") final MessageInteraction.ResourceStatus outboundResourceStatus, + @JsonProperty("outbound_resource_type") final String outboundResourceType, + @JsonProperty("outbound_resource_url") final URI outboundResourceUrl, + @JsonProperty("participant_sid") final String participantSid, + @JsonProperty("service_sid") final String serviceSid, + @JsonProperty("session_sid") final String sessionSid, + @JsonProperty("sid") final String sid, + @JsonProperty("type") final MessageInteraction.Type type, + @JsonProperty("url") final URI url ) { - this.sid = sid; - this.sessionSid = sessionSid; - this.serviceSid = serviceSid; this.accountSid = accountSid; this.data = data; - this.type = type; - this.participantSid = participantSid; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.inboundParticipantSid = inboundParticipantSid; this.inboundResourceSid = inboundResourceSid; this.inboundResourceStatus = inboundResourceStatus; @@ -208,91 +260,14 @@ private MessageInteraction( this.outboundResourceStatus = outboundResourceStatus; this.outboundResourceType = outboundResourceType; this.outboundResourceUrl = outboundResourceUrl; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); + this.participantSid = participantSid; + this.serviceSid = serviceSid; + this.sessionSid = sessionSid; + this.sid = sid; + this.type = type; this.url = url; } - public final String getSid() { - return this.sid; - } - - public final String getSessionSid() { - return this.sessionSid; - } - - public final String getServiceSid() { - return this.serviceSid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getData() { - return this.data; - } - - public final MessageInteraction.Type getType() { - return this.type; - } - - public final String getParticipantSid() { - return this.participantSid; - } - - public final String getInboundParticipantSid() { - return this.inboundParticipantSid; - } - - public final String getInboundResourceSid() { - return this.inboundResourceSid; - } - - public final MessageInteraction.ResourceStatus getInboundResourceStatus() { - return this.inboundResourceStatus; - } - - public final String getInboundResourceType() { - return this.inboundResourceType; - } - - public final URI getInboundResourceUrl() { - return this.inboundResourceUrl; - } - - public final String getOutboundParticipantSid() { - return this.outboundParticipantSid; - } - - public final String getOutboundResourceSid() { - return this.outboundResourceSid; - } - - public final MessageInteraction.ResourceStatus getOutboundResourceStatus() { - return this.outboundResourceStatus; - } - - public final String getOutboundResourceType() { - return this.outboundResourceType; - } - - public final URI getOutboundResourceUrl() { - return this.outboundResourceUrl; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final URI getUrl() { - return this.url; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -304,126 +279,56 @@ public boolean equals(final Object o) { } MessageInteraction other = (MessageInteraction) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(sessionSid, other.sessionSid) && - Objects.equals(serviceSid, other.serviceSid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(data, other.data) && - Objects.equals(type, other.type) && - Objects.equals(participantSid, other.participantSid) && - Objects.equals( - inboundParticipantSid, - other.inboundParticipantSid - ) && - Objects.equals(inboundResourceSid, other.inboundResourceSid) && - Objects.equals( - inboundResourceStatus, - other.inboundResourceStatus - ) && - Objects.equals(inboundResourceType, other.inboundResourceType) && - Objects.equals(inboundResourceUrl, other.inboundResourceUrl) && - Objects.equals( - outboundParticipantSid, - other.outboundParticipantSid - ) && - Objects.equals(outboundResourceSid, other.outboundResourceSid) && - Objects.equals( - outboundResourceStatus, - other.outboundResourceStatus - ) && - Objects.equals(outboundResourceType, other.outboundResourceType) && - Objects.equals(outboundResourceUrl, other.outboundResourceUrl) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(url, other.url) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(data, other.data) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(inboundParticipantSid, other.inboundParticipantSid) && + Objects.equals(inboundResourceSid, other.inboundResourceSid) && + Objects.equals(inboundResourceStatus, other.inboundResourceStatus) && + Objects.equals(inboundResourceType, other.inboundResourceType) && + Objects.equals(inboundResourceUrl, other.inboundResourceUrl) && + Objects.equals(outboundParticipantSid, other.outboundParticipantSid) && + Objects.equals(outboundResourceSid, other.outboundResourceSid) && + Objects.equals(outboundResourceStatus, other.outboundResourceStatus) && + Objects.equals(outboundResourceType, other.outboundResourceType) && + Objects.equals(outboundResourceUrl, other.outboundResourceUrl) && + Objects.equals(participantSid, other.participantSid) && + Objects.equals(serviceSid, other.serviceSid) && + Objects.equals(sessionSid, other.sessionSid) && + Objects.equals(sid, other.sid) && + Objects.equals(type, other.type) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - sid, - sessionSid, - serviceSid, - accountSid, - data, - type, - participantSid, - inboundParticipantSid, - inboundResourceSid, - inboundResourceStatus, - inboundResourceType, - inboundResourceUrl, - outboundParticipantSid, - outboundResourceSid, - outboundResourceStatus, - outboundResourceType, - outboundResourceUrl, - dateCreated, - dateUpdated, - url + accountSid, + data, + dateCreated, + dateUpdated, + inboundParticipantSid, + inboundResourceSid, + inboundResourceStatus, + inboundResourceType, + inboundResourceUrl, + outboundParticipantSid, + outboundResourceSid, + outboundResourceStatus, + outboundResourceType, + outboundResourceUrl, + participantSid, + serviceSid, + sessionSid, + sid, + type, + url ); } - public enum Type { - MESSAGE("message"), - VOICE("voice"), - UNKNOWN("unknown"); - - private final String value; - - private Type(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static Type forValue(final String value) { - return Promoter.enumFromString(value, Type.values()); - } - } - - public enum ResourceStatus { - ACCEPTED("accepted"), - ANSWERED("answered"), - BUSY("busy"), - CANCELED("canceled"), - COMPLETED("completed"), - DELETED("deleted"), - DELIVERED("delivered"), - DELIVERY_UNKNOWN("delivery-unknown"), - FAILED("failed"), - IN_PROGRESS("in-progress"), - INITIATED("initiated"), - NO_ANSWER("no-answer"), - QUEUED("queued"), - RECEIVED("received"), - RECEIVING("receiving"), - RINGING("ringing"), - SCHEDULED("scheduled"), - SENDING("sending"), - SENT("sent"), - UNDELIVERED("undelivered"), - UNKNOWN("unknown"); - - private final String value; - private ResourceStatus(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static ResourceStatus forValue(final String value) { - return Promoter.enumFromString(value, ResourceStatus.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/proxy/v1/service/session/participant/MessageInteractionCreator.java b/src/main/java/com/twilio/rest/proxy/v1/service/session/participant/MessageInteractionCreator.java index 5094fd1b55..952b70efaf 100644 --- a/src/main/java/com/twilio/rest/proxy/v1/service/session/participant/MessageInteractionCreator.java +++ b/src/main/java/com/twilio/rest/proxy/v1/service/session/participant/MessageInteractionCreator.java @@ -14,9 +14,12 @@ package com.twilio.rest.proxy.v1.service.session.participant; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; import com.twilio.converter.Promoter; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,48 +28,39 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -import java.net.URI; + import java.net.URI; import java.util.List; -import java.util.List; public class MessageInteractionCreator extends Creator { - private String pathServiceSid; - private String pathSessionSid; - private String pathParticipantSid; + private String pathserviceSid; + private String pathsessionSid; + private String pathparticipantSid; private String body; private List mediaUrl; - public MessageInteractionCreator( - final String pathServiceSid, - final String pathSessionSid, - final String pathParticipantSid, - final String body - ) { - this.pathServiceSid = pathServiceSid; - this.pathSessionSid = pathSessionSid; - this.pathParticipantSid = pathParticipantSid; + public MessageInteractionCreator(final String pathserviceSid, final String pathsessionSid, final String pathparticipantSid, final String body) { + this.pathserviceSid = pathserviceSid; + this.pathsessionSid = pathsessionSid; + this.pathparticipantSid = pathparticipantSid; this.body = body; } - public MessageInteractionCreator( - final String pathServiceSid, - final String pathSessionSid, - final String pathParticipantSid, - final List mediaUrl - ) { - this.pathServiceSid = pathServiceSid; - this.pathSessionSid = pathSessionSid; - this.pathParticipantSid = pathParticipantSid; + public MessageInteractionCreator(final String pathserviceSid, final String pathsessionSid, final String pathparticipantSid, final List mediaUrl) { + this.pathserviceSid = pathserviceSid; + this.pathsessionSid = pathsessionSid; + this.pathparticipantSid = pathparticipantSid; this.mediaUrl = mediaUrl; } + public MessageInteractionCreator setBody(final String body) { this.body = body; return this; } + public MessageInteractionCreator setMediaUrl(final List mediaUrl) { this.mediaUrl = mediaUrl; return this; @@ -76,71 +70,54 @@ public MessageInteractionCreator setMediaUrl(final URI mediaUrl) { return setMediaUrl(Promoter.listOfOne(mediaUrl)); } - public MessageInteractionCreator setMediaUrl(final String mediaUrl) { - return setMediaUrl(Promoter.uriFromString(mediaUrl)); - } - @Override public MessageInteraction create(final TwilioRestClient client) { - String path = - "/v1/Services/{ServiceSid}/Sessions/{SessionSid}/Participants/{ParticipantSid}/MessageInteractions"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = - path.replace( - "{" + "SessionSid" + "}", - this.pathSessionSid.toString() - ); - path = - path.replace( - "{" + "ParticipantSid" + "}", - this.pathParticipantSid.toString() - ); + String path = "/v1/Services/{ServiceSid}/Sessions/{SessionSid}/Participants/{ParticipantSid}/MessageInteractions"; + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "SessionSid" + "}", this.pathsessionSid.toString()); + path = path.replace("{" + "ParticipantSid" + "}", this.pathparticipantSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.PROXY.toString(), - path + HttpMethod.POST, + Domains.PROXY.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "MessageInteraction creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("MessageInteraction creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return MessageInteraction.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return MessageInteraction.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (body != null) { - request.addPostParam("Body", body); + Serializer.toString(request, "Body", body, ParameterType.URLENCODED); } + + if (mediaUrl != null) { - for (URI prop : mediaUrl) { - request.addPostParam("MediaUrl", prop.toString()); + for (URI param : mediaUrl) { + Serializer.toString(request, "MediaUrl", param, ParameterType.URLENCODED); } } + } } diff --git a/src/main/java/com/twilio/rest/proxy/v1/service/session/participant/MessageInteractionFetcher.java b/src/main/java/com/twilio/rest/proxy/v1/service/session/participant/MessageInteractionFetcher.java index 38175fbf68..45048b8605 100644 --- a/src/main/java/com/twilio/rest/proxy/v1/service/session/participant/MessageInteractionFetcher.java +++ b/src/main/java/com/twilio/rest/proxy/v1/service/session/participant/MessageInteractionFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.proxy.v1.service.session.participant; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,74 +26,50 @@ public class MessageInteractionFetcher extends Fetcher { - private String pathServiceSid; - private String pathSessionSid; - private String pathParticipantSid; - private String pathSid; + private String pathserviceSid; + private String pathsessionSid; + private String pathparticipantSid; + private String pathsid; - public MessageInteractionFetcher( - final String pathServiceSid, - final String pathSessionSid, - final String pathParticipantSid, - final String pathSid - ) { - this.pathServiceSid = pathServiceSid; - this.pathSessionSid = pathSessionSid; - this.pathParticipantSid = pathParticipantSid; - this.pathSid = pathSid; + public MessageInteractionFetcher(final String pathserviceSid, final String pathsessionSid, final String pathparticipantSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathsessionSid = pathsessionSid; + this.pathparticipantSid = pathparticipantSid; + this.pathsid = pathsid; } + @Override public MessageInteraction fetch(final TwilioRestClient client) { - String path = - "/v1/Services/{ServiceSid}/Sessions/{SessionSid}/Participants/{ParticipantSid}/MessageInteractions/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = - path.replace( - "{" + "SessionSid" + "}", - this.pathSessionSid.toString() - ); - path = - path.replace( - "{" + "ParticipantSid" + "}", - this.pathParticipantSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/v1/Services/{ServiceSid}/Sessions/{SessionSid}/Participants/{ParticipantSid}/MessageInteractions/{Sid}"; + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "SessionSid" + "}", this.pathsessionSid.toString()); + path = path.replace("{" + "ParticipantSid" + "}", this.pathparticipantSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.PROXY.toString(), - path + HttpMethod.GET, + Domains.PROXY.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "MessageInteraction fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("MessageInteraction fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return MessageInteraction.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return MessageInteraction.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/proxy/v1/service/session/participant/MessageInteractionReader.java b/src/main/java/com/twilio/rest/proxy/v1/service/session/participant/MessageInteractionReader.java index 3fe5b3a90d..0d7ad0a9c5 100644 --- a/src/main/java/com/twilio/rest/proxy/v1/service/session/participant/MessageInteractionReader.java +++ b/src/main/java/com/twilio/rest/proxy/v1/service/session/participant/MessageInteractionReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,134 +30,94 @@ public class MessageInteractionReader extends Reader { - private String pathServiceSid; - private String pathSessionSid; - private String pathParticipantSid; + private String pathserviceSid; + private String pathsessionSid; + private String pathparticipantSid; private Long pageSize; - public MessageInteractionReader( - final String pathServiceSid, - final String pathSessionSid, - final String pathParticipantSid - ) { - this.pathServiceSid = pathServiceSid; - this.pathSessionSid = pathSessionSid; - this.pathParticipantSid = pathParticipantSid; + public MessageInteractionReader(final String pathserviceSid, final String pathsessionSid, final String pathparticipantSid) { + this.pathserviceSid = pathserviceSid; + this.pathsessionSid = pathsessionSid; + this.pathparticipantSid = pathparticipantSid; } + public MessageInteractionReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { - String path = - "/v1/Services/{ServiceSid}/Sessions/{SessionSid}/Participants/{ParticipantSid}/MessageInteractions"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = - path.replace( - "{" + "SessionSid" + "}", - this.pathSessionSid.toString() - ); - path = - path.replace( - "{" + "ParticipantSid" + "}", - this.pathParticipantSid.toString() - ); + + String path = "/v1/Services/{ServiceSid}/Sessions/{SessionSid}/Participants/{ParticipantSid}/MessageInteractions"; + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "SessionSid" + "}", this.pathsessionSid.toString()); + path = path.replace("{" + "ParticipantSid" + "}", this.pathparticipantSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.PROXY.toString(), - path + HttpMethod.GET, + Domains.PROXY.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "MessageInteraction read failed: Unable to connect to server" - ); + throw new ApiConnectionException("MessageInteraction read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "interactions", - response.getContent(), - MessageInteraction.class, - client.getObjectMapper() - ); + "interactions", + response.getContent(), + MessageInteraction.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.PROXY.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.PROXY.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/routes/v2/PhoneNumber.java b/src/main/java/com/twilio/rest/routes/v2/PhoneNumber.java index 66aacca932..527a7a42a2 100644 --- a/src/main/java/com/twilio/rest/routes/v2/PhoneNumber.java +++ b/src/main/java/com/twilio/rest/routes/v2/PhoneNumber.java @@ -18,45 +18,49 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class PhoneNumber extends Resource { - private static final long serialVersionUID = 213320512216415L; - public static PhoneNumberFetcher fetcher(final String pathPhoneNumber) { - return new PhoneNumberFetcher(pathPhoneNumber); + public static PhoneNumberFetcher fetcher(final String pathphoneNumber) { + return new PhoneNumberFetcher( + pathphoneNumber + ); } - public static PhoneNumberUpdater updater(final String pathPhoneNumber) { - return new PhoneNumberUpdater(pathPhoneNumber); + + public static PhoneNumberUpdater updater(final String pathphoneNumber) { + return new PhoneNumberUpdater( + pathphoneNumber + ); } + /** * Converts a JSON String into a PhoneNumber object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return PhoneNumber object represented by the provided JSON */ - public static PhoneNumber fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static PhoneNumber fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, PhoneNumber.class); @@ -71,14 +75,11 @@ public static PhoneNumber fromJson( * Converts a JSON InputStream into a PhoneNumber object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return PhoneNumber object represented by the provided JSON */ - public static PhoneNumber fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static PhoneNumber fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, PhoneNumber.class); @@ -89,66 +90,57 @@ public static PhoneNumber fromJson( } } - private final String phoneNumber; - private final URI url; - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String friendlyName; - private final String voiceRegion; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; + @Getter + private final String friendlyName; + @Getter + private final String phoneNumber; + @Getter + private final String sid; + @Getter + private final URI url; + @Getter + private final String voiceRegion; @JsonCreator private PhoneNumber( - @JsonProperty("phone_number") final String phoneNumber, - @JsonProperty("url") final URI url, - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("voice_region") final String voiceRegion, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("phone_number") final String phoneNumber, + @JsonProperty("sid") final String sid, + @JsonProperty("url") final URI url, + @JsonProperty("voice_region") final String voiceRegion ) { - this.phoneNumber = phoneNumber; - this.url = url; - this.sid = sid; this.accountSid = accountSid; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.friendlyName = friendlyName; + this.phoneNumber = phoneNumber; + this.sid = sid; + this.url = url; this.voiceRegion = voiceRegion; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); - } - - public final String getPhoneNumber() { - return this.phoneNumber; - } - - public final URI getUrl() { - return this.url; - } - - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final String getVoiceRegion() { - return this.voiceRegion; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; } @Override @@ -162,30 +154,32 @@ public boolean equals(final Object o) { } PhoneNumber other = (PhoneNumber) o; - return ( - Objects.equals(phoneNumber, other.phoneNumber) && - Objects.equals(url, other.url) && - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(voiceRegion, other.voiceRegion) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(phoneNumber, other.phoneNumber) && + Objects.equals(sid, other.sid) && + Objects.equals(url, other.url) && + Objects.equals(voiceRegion, other.voiceRegion) ); } @Override public int hashCode() { return Objects.hash( - phoneNumber, - url, - sid, - accountSid, - friendlyName, - voiceRegion, - dateCreated, - dateUpdated + accountSid, + dateCreated, + dateUpdated, + friendlyName, + phoneNumber, + sid, + url, + voiceRegion ); } + + } + diff --git a/src/main/java/com/twilio/rest/routes/v2/PhoneNumberFetcher.java b/src/main/java/com/twilio/rest/routes/v2/PhoneNumberFetcher.java index 28aa5805db..7596cc36dc 100644 --- a/src/main/java/com/twilio/rest/routes/v2/PhoneNumberFetcher.java +++ b/src/main/java/com/twilio/rest/routes/v2/PhoneNumberFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.routes.v2; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,51 +26,41 @@ public class PhoneNumberFetcher extends Fetcher { - private String pathPhoneNumber; + private String pathphoneNumber; - public PhoneNumberFetcher(final String pathPhoneNumber) { - this.pathPhoneNumber = pathPhoneNumber; + public PhoneNumberFetcher(final String pathphoneNumber) { + this.pathphoneNumber = pathphoneNumber; } + @Override public PhoneNumber fetch(final TwilioRestClient client) { + String path = "/v2/PhoneNumbers/{PhoneNumber}"; - path = - path.replace( - "{" + "PhoneNumber" + "}", - this.pathPhoneNumber.toString() - ); + path = path.replace("{" + "PhoneNumber" + "}", this.pathphoneNumber.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.ROUTES.toString(), - path + HttpMethod.GET, + Domains.ROUTES.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "PhoneNumber fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("PhoneNumber fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return PhoneNumber.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return PhoneNumber.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/routes/v2/PhoneNumberUpdater.java b/src/main/java/com/twilio/rest/routes/v2/PhoneNumberUpdater.java index 22a48d1439..d8d369411b 100644 --- a/src/main/java/com/twilio/rest/routes/v2/PhoneNumberUpdater.java +++ b/src/main/java/com/twilio/rest/routes/v2/PhoneNumberUpdater.java @@ -16,6 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -26,73 +28,72 @@ import com.twilio.rest.Domains; public class PhoneNumberUpdater extends Updater { - - private String pathPhoneNumber; + private String pathphoneNumber; private String voiceRegion; private String friendlyName; - public PhoneNumberUpdater(final String pathPhoneNumber) { - this.pathPhoneNumber = pathPhoneNumber; + public PhoneNumberUpdater(final String pathphoneNumber) { + this.pathphoneNumber = pathphoneNumber; } + public PhoneNumberUpdater setVoiceRegion(final String voiceRegion) { this.voiceRegion = voiceRegion; return this; } + public PhoneNumberUpdater setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + @Override public PhoneNumber update(final TwilioRestClient client) { + String path = "/v2/PhoneNumbers/{PhoneNumber}"; - path = - path.replace( - "{" + "PhoneNumber" + "}", - this.pathPhoneNumber.toString() - ); + path = path.replace("{" + "PhoneNumber" + "}", this.pathphoneNumber.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.ROUTES.toString(), - path + HttpMethod.POST, + Domains.ROUTES.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "PhoneNumber update failed: Unable to connect to server" - ); + throw new ApiConnectionException("PhoneNumber update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return PhoneNumber.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return PhoneNumber.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (voiceRegion != null) { - request.addPostParam("VoiceRegion", voiceRegion); + Serializer.toString(request, "VoiceRegion", voiceRegion, ParameterType.URLENCODED); } + + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/routes/v2/SipDomain.java b/src/main/java/com/twilio/rest/routes/v2/SipDomain.java index c1f8dd1129..8a332176fb 100644 --- a/src/main/java/com/twilio/rest/routes/v2/SipDomain.java +++ b/src/main/java/com/twilio/rest/routes/v2/SipDomain.java @@ -18,45 +18,49 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class SipDomain extends Resource { - private static final long serialVersionUID = 81903226613345L; - public static SipDomainFetcher fetcher(final String pathSipDomain) { - return new SipDomainFetcher(pathSipDomain); + public static SipDomainFetcher fetcher(final String pathsipDomain) { + return new SipDomainFetcher( + pathsipDomain + ); } - public static SipDomainUpdater updater(final String pathSipDomain) { - return new SipDomainUpdater(pathSipDomain); + + public static SipDomainUpdater updater(final String pathsipDomain) { + return new SipDomainUpdater( + pathsipDomain + ); } + /** * Converts a JSON String into a SipDomain object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return SipDomain object represented by the provided JSON */ - public static SipDomain fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static SipDomain fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, SipDomain.class); @@ -71,14 +75,11 @@ public static SipDomain fromJson( * Converts a JSON InputStream into a SipDomain object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return SipDomain object represented by the provided JSON */ - public static SipDomain fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static SipDomain fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, SipDomain.class); @@ -89,66 +90,57 @@ public static SipDomain fromJson( } } - private final String sipDomain; - private final URI url; - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String friendlyName; - private final String voiceRegion; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; + @Getter + private final String friendlyName; + @Getter + private final String sid; + @Getter + private final String sipDomain; + @Getter + private final URI url; + @Getter + private final String voiceRegion; @JsonCreator private SipDomain( - @JsonProperty("sip_domain") final String sipDomain, - @JsonProperty("url") final URI url, - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("voice_region") final String voiceRegion, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("sid") final String sid, + @JsonProperty("sip_domain") final String sipDomain, + @JsonProperty("url") final URI url, + @JsonProperty("voice_region") final String voiceRegion ) { - this.sipDomain = sipDomain; - this.url = url; - this.sid = sid; this.accountSid = accountSid; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.friendlyName = friendlyName; + this.sid = sid; + this.sipDomain = sipDomain; + this.url = url; this.voiceRegion = voiceRegion; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); - } - - public final String getSipDomain() { - return this.sipDomain; - } - - public final URI getUrl() { - return this.url; - } - - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final String getVoiceRegion() { - return this.voiceRegion; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; } @Override @@ -162,30 +154,32 @@ public boolean equals(final Object o) { } SipDomain other = (SipDomain) o; - return ( - Objects.equals(sipDomain, other.sipDomain) && - Objects.equals(url, other.url) && - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(voiceRegion, other.voiceRegion) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(sid, other.sid) && + Objects.equals(sipDomain, other.sipDomain) && + Objects.equals(url, other.url) && + Objects.equals(voiceRegion, other.voiceRegion) ); } @Override public int hashCode() { return Objects.hash( - sipDomain, - url, - sid, - accountSid, - friendlyName, - voiceRegion, - dateCreated, - dateUpdated + accountSid, + dateCreated, + dateUpdated, + friendlyName, + sid, + sipDomain, + url, + voiceRegion ); } + + } + diff --git a/src/main/java/com/twilio/rest/routes/v2/SipDomainFetcher.java b/src/main/java/com/twilio/rest/routes/v2/SipDomainFetcher.java index dfa8f48a82..45a371de35 100644 --- a/src/main/java/com/twilio/rest/routes/v2/SipDomainFetcher.java +++ b/src/main/java/com/twilio/rest/routes/v2/SipDomainFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.routes.v2; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,51 +26,41 @@ public class SipDomainFetcher extends Fetcher { - private String pathSipDomain; + private String pathsipDomain; - public SipDomainFetcher(final String pathSipDomain) { - this.pathSipDomain = pathSipDomain; + public SipDomainFetcher(final String pathsipDomain) { + this.pathsipDomain = pathsipDomain; } + @Override public SipDomain fetch(final TwilioRestClient client) { + String path = "/v2/SipDomains/{SipDomain}"; - path = - path.replace( - "{" + "SipDomain" + "}", - this.pathSipDomain.toString() - ); + path = path.replace("{" + "SipDomain" + "}", this.pathsipDomain.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.ROUTES.toString(), - path + HttpMethod.GET, + Domains.ROUTES.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "SipDomain fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("SipDomain fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return SipDomain.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return SipDomain.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/routes/v2/SipDomainUpdater.java b/src/main/java/com/twilio/rest/routes/v2/SipDomainUpdater.java index 26feacef9e..4d4687b56b 100644 --- a/src/main/java/com/twilio/rest/routes/v2/SipDomainUpdater.java +++ b/src/main/java/com/twilio/rest/routes/v2/SipDomainUpdater.java @@ -16,6 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -26,73 +28,72 @@ import com.twilio.rest.Domains; public class SipDomainUpdater extends Updater { - - private String pathSipDomain; + private String pathsipDomain; private String voiceRegion; private String friendlyName; - public SipDomainUpdater(final String pathSipDomain) { - this.pathSipDomain = pathSipDomain; + public SipDomainUpdater(final String pathsipDomain) { + this.pathsipDomain = pathsipDomain; } + public SipDomainUpdater setVoiceRegion(final String voiceRegion) { this.voiceRegion = voiceRegion; return this; } + public SipDomainUpdater setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + @Override public SipDomain update(final TwilioRestClient client) { + String path = "/v2/SipDomains/{SipDomain}"; - path = - path.replace( - "{" + "SipDomain" + "}", - this.pathSipDomain.toString() - ); + path = path.replace("{" + "SipDomain" + "}", this.pathsipDomain.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.ROUTES.toString(), - path + HttpMethod.POST, + Domains.ROUTES.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "SipDomain update failed: Unable to connect to server" - ); + throw new ApiConnectionException("SipDomain update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return SipDomain.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return SipDomain.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (voiceRegion != null) { - request.addPostParam("VoiceRegion", voiceRegion); + Serializer.toString(request, "VoiceRegion", voiceRegion, ParameterType.URLENCODED); } + + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/routes/v2/Trunk.java b/src/main/java/com/twilio/rest/routes/v2/Trunk.java index 590a1494bf..761b2766a1 100644 --- a/src/main/java/com/twilio/rest/routes/v2/Trunk.java +++ b/src/main/java/com/twilio/rest/routes/v2/Trunk.java @@ -18,45 +18,49 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Trunk extends Resource { - private static final long serialVersionUID = 71100118275281L; - public static TrunkFetcher fetcher(final String pathSipTrunkDomain) { - return new TrunkFetcher(pathSipTrunkDomain); + public static TrunkFetcher fetcher(final String pathsipTrunkDomain) { + return new TrunkFetcher( + pathsipTrunkDomain + ); } - public static TrunkUpdater updater(final String pathSipTrunkDomain) { - return new TrunkUpdater(pathSipTrunkDomain); + + public static TrunkUpdater updater(final String pathsipTrunkDomain) { + return new TrunkUpdater( + pathsipTrunkDomain + ); } + /** * Converts a JSON String into a Trunk object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Trunk object represented by the provided JSON */ - public static Trunk fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Trunk fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Trunk.class); @@ -71,14 +75,11 @@ public static Trunk fromJson( * Converts a JSON InputStream into a Trunk object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Trunk object represented by the provided JSON */ - public static Trunk fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Trunk fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Trunk.class); @@ -89,66 +90,57 @@ public static Trunk fromJson( } } - private final String sipTrunkDomain; - private final URI url; - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String friendlyName; - private final String voiceRegion; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; + @Getter + private final String friendlyName; + @Getter + private final String sid; + @Getter + private final String sipTrunkDomain; + @Getter + private final URI url; + @Getter + private final String voiceRegion; @JsonCreator private Trunk( - @JsonProperty("sip_trunk_domain") final String sipTrunkDomain, - @JsonProperty("url") final URI url, - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("voice_region") final String voiceRegion, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("sid") final String sid, + @JsonProperty("sip_trunk_domain") final String sipTrunkDomain, + @JsonProperty("url") final URI url, + @JsonProperty("voice_region") final String voiceRegion ) { - this.sipTrunkDomain = sipTrunkDomain; - this.url = url; - this.sid = sid; this.accountSid = accountSid; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.friendlyName = friendlyName; + this.sid = sid; + this.sipTrunkDomain = sipTrunkDomain; + this.url = url; this.voiceRegion = voiceRegion; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); - } - - public final String getSipTrunkDomain() { - return this.sipTrunkDomain; - } - - public final URI getUrl() { - return this.url; - } - - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final String getVoiceRegion() { - return this.voiceRegion; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; } @Override @@ -162,30 +154,32 @@ public boolean equals(final Object o) { } Trunk other = (Trunk) o; - return ( - Objects.equals(sipTrunkDomain, other.sipTrunkDomain) && - Objects.equals(url, other.url) && - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(voiceRegion, other.voiceRegion) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(sid, other.sid) && + Objects.equals(sipTrunkDomain, other.sipTrunkDomain) && + Objects.equals(url, other.url) && + Objects.equals(voiceRegion, other.voiceRegion) ); } @Override public int hashCode() { return Objects.hash( - sipTrunkDomain, - url, - sid, - accountSid, - friendlyName, - voiceRegion, - dateCreated, - dateUpdated + accountSid, + dateCreated, + dateUpdated, + friendlyName, + sid, + sipTrunkDomain, + url, + voiceRegion ); } + + } + diff --git a/src/main/java/com/twilio/rest/routes/v2/TrunkFetcher.java b/src/main/java/com/twilio/rest/routes/v2/TrunkFetcher.java index 28a16ec552..8521e4f02c 100644 --- a/src/main/java/com/twilio/rest/routes/v2/TrunkFetcher.java +++ b/src/main/java/com/twilio/rest/routes/v2/TrunkFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.routes.v2; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,48 +26,41 @@ public class TrunkFetcher extends Fetcher { - private String pathSipTrunkDomain; + private String pathsipTrunkDomain; - public TrunkFetcher(final String pathSipTrunkDomain) { - this.pathSipTrunkDomain = pathSipTrunkDomain; + public TrunkFetcher(final String pathsipTrunkDomain) { + this.pathsipTrunkDomain = pathsipTrunkDomain; } + @Override public Trunk fetch(final TwilioRestClient client) { + String path = "/v2/Trunks/{SipTrunkDomain}"; - path = - path.replace( - "{" + "SipTrunkDomain" + "}", - this.pathSipTrunkDomain.toString() - ); + path = path.replace("{" + "SipTrunkDomain" + "}", this.pathsipTrunkDomain.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.ROUTES.toString(), - path + HttpMethod.GET, + Domains.ROUTES.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Trunk fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Trunk fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Trunk.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/routes/v2/TrunkUpdater.java b/src/main/java/com/twilio/rest/routes/v2/TrunkUpdater.java index e7cb444097..805fb25a29 100644 --- a/src/main/java/com/twilio/rest/routes/v2/TrunkUpdater.java +++ b/src/main/java/com/twilio/rest/routes/v2/TrunkUpdater.java @@ -16,6 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -26,57 +28,54 @@ import com.twilio.rest.Domains; public class TrunkUpdater extends Updater { - - private String pathSipTrunkDomain; + private String pathsipTrunkDomain; private String voiceRegion; private String friendlyName; - public TrunkUpdater(final String pathSipTrunkDomain) { - this.pathSipTrunkDomain = pathSipTrunkDomain; + public TrunkUpdater(final String pathsipTrunkDomain) { + this.pathsipTrunkDomain = pathsipTrunkDomain; } + public TrunkUpdater setVoiceRegion(final String voiceRegion) { this.voiceRegion = voiceRegion; return this; } + public TrunkUpdater setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + @Override public Trunk update(final TwilioRestClient client) { + String path = "/v2/Trunks/{SipTrunkDomain}"; - path = - path.replace( - "{" + "SipTrunkDomain" + "}", - this.pathSipTrunkDomain.toString() - ); + path = path.replace("{" + "SipTrunkDomain" + "}", this.pathsipTrunkDomain.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.ROUTES.toString(), - path + HttpMethod.POST, + Domains.ROUTES.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Trunk update failed: Unable to connect to server" - ); + throw new ApiConnectionException("Trunk update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -85,11 +84,16 @@ public Trunk update(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (voiceRegion != null) { - request.addPostParam("VoiceRegion", voiceRegion); + Serializer.toString(request, "VoiceRegion", voiceRegion, ParameterType.URLENCODED); } + + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/serverless/v1/Service.java b/src/main/java/com/twilio/rest/serverless/v1/Service.java index 4ecb0ac584..3693070802 100644 --- a/src/main/java/com/twilio/rest/serverless/v1/Service.java +++ b/src/main/java/com/twilio/rest/serverless/v1/Service.java @@ -18,62 +18,71 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Service extends Resource { - private static final long serialVersionUID = 60847550969739L; - public static ServiceCreator creator( - final String uniqueName, - final String friendlyName - ) { - return new ServiceCreator(uniqueName, friendlyName); + public static ServiceCreator creator(final String uniqueName, final String friendlyName) { + return new ServiceCreator( + uniqueName, friendlyName + ); } - public static ServiceDeleter deleter(final String pathSid) { - return new ServiceDeleter(pathSid); + + public static ServiceDeleter deleter(final String pathsid) { + return new ServiceDeleter( + pathsid + ); } - public static ServiceFetcher fetcher(final String pathSid) { - return new ServiceFetcher(pathSid); + + public static ServiceFetcher fetcher(final String pathsid) { + return new ServiceFetcher( + pathsid + ); } + public static ServiceReader reader() { - return new ServiceReader(); + return new ServiceReader( + + ); } - public static ServiceUpdater updater(final String pathSid) { - return new ServiceUpdater(pathSid); + + public static ServiceUpdater updater(final String pathsid) { + return new ServiceUpdater( + pathsid + ); } + /** * Converts a JSON String into a Service object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Service object represented by the provided JSON */ - public static Service fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Service fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Service.class); @@ -88,14 +97,11 @@ public static Service fromJson( * Converts a JSON InputStream into a Service object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Service object represented by the provided JSON */ - public static Service fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Service fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Service.class); @@ -106,87 +112,69 @@ public static Service fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; + @Getter + private final ZonedDateTime dateCreated; + @Getter + private final ZonedDateTime dateUpdated; + @Getter + private final String domainBase; + @Getter private final String friendlyName; - private final String uniqueName; + @Getter private final Boolean includeCredentials; + @Getter + private final Map links; + @Getter + private final String sid; + @Getter private final Boolean uiEditable; - private final String domainBase; - private final ZonedDateTime dateCreated; - private final ZonedDateTime dateUpdated; + @Getter + private final String uniqueName; + @Getter private final URI url; - private final Map links; @JsonCreator private Service( - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("unique_name") final String uniqueName, - @JsonProperty("include_credentials") final Boolean includeCredentials, - @JsonProperty("ui_editable") final Boolean uiEditable, - @JsonProperty("domain_base") final String domainBase, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("url") final URI url, - @JsonProperty("links") final Map links + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("domain_base") final String domainBase, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("include_credentials") final Boolean includeCredentials, + @JsonProperty("links") final Map links, + @JsonProperty("sid") final String sid, + @JsonProperty("ui_editable") final Boolean uiEditable, + @JsonProperty("unique_name") final String uniqueName, + @JsonProperty("url") final URI url ) { - this.sid = sid; this.accountSid = accountSid; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; + this.domainBase = domainBase; this.friendlyName = friendlyName; - this.uniqueName = uniqueName; this.includeCredentials = includeCredentials; + this.links = links; + this.sid = sid; this.uiEditable = uiEditable; - this.domainBase = domainBase; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); + this.uniqueName = uniqueName; this.url = url; - this.links = links; - } - - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final String getUniqueName() { - return this.uniqueName; - } - - public final Boolean getIncludeCredentials() { - return this.includeCredentials; - } - - public final Boolean getUiEditable() { - return this.uiEditable; - } - - public final String getDomainBase() { - return this.domainBase; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final URI getUrl() { - return this.url; - } - - public final Map getLinks() { - return this.links; } @Override @@ -200,36 +188,38 @@ public boolean equals(final Object o) { } Service other = (Service) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(uniqueName, other.uniqueName) && - Objects.equals(includeCredentials, other.includeCredentials) && - Objects.equals(uiEditable, other.uiEditable) && - Objects.equals(domainBase, other.domainBase) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(url, other.url) && - Objects.equals(links, other.links) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(domainBase, other.domainBase) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(includeCredentials, other.includeCredentials) && + Objects.equals(links, other.links) && + Objects.equals(sid, other.sid) && + Objects.equals(uiEditable, other.uiEditable) && + Objects.equals(uniqueName, other.uniqueName) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - sid, - accountSid, - friendlyName, - uniqueName, - includeCredentials, - uiEditable, - domainBase, - dateCreated, - dateUpdated, - url, - links + accountSid, + dateCreated, + dateUpdated, + domainBase, + friendlyName, + includeCredentials, + links, + sid, + uiEditable, + uniqueName, + url ); } + + } + diff --git a/src/main/java/com/twilio/rest/serverless/v1/ServiceCreator.java b/src/main/java/com/twilio/rest/serverless/v1/ServiceCreator.java index 9619da8719..d8b774b14e 100644 --- a/src/main/java/com/twilio/rest/serverless/v1/ServiceCreator.java +++ b/src/main/java/com/twilio/rest/serverless/v1/ServiceCreator.java @@ -14,8 +14,11 @@ package com.twilio.rest.serverless.v1; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -37,62 +40,56 @@ public ServiceCreator(final String uniqueName, final String friendlyName) { this.friendlyName = friendlyName; } + public ServiceCreator setUniqueName(final String uniqueName) { this.uniqueName = uniqueName; return this; } + public ServiceCreator setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } - public ServiceCreator setIncludeCredentials( - final Boolean includeCredentials - ) { + + public ServiceCreator setIncludeCredentials(final Boolean includeCredentials) { this.includeCredentials = includeCredentials; return this; } + public ServiceCreator setUiEditable(final Boolean uiEditable) { this.uiEditable = uiEditable; return this; } + @Override public Service create(final TwilioRestClient client) { + String path = "/v1/Services"; - path = - path.replace("{" + "UniqueName" + "}", this.uniqueName.toString()); - path = - path.replace( - "{" + "FriendlyName" + "}", - this.friendlyName.toString() - ); Request request = new Request( - HttpMethod.POST, - Domains.SERVERLESS.toString(), - path + HttpMethod.POST, + Domains.SERVERLESS.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Service creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("Service creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -101,20 +98,26 @@ public Service create(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (uniqueName != null) { - request.addPostParam("UniqueName", uniqueName); + Serializer.toString(request, "UniqueName", uniqueName, ParameterType.URLENCODED); } + + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + if (includeCredentials != null) { - request.addPostParam( - "IncludeCredentials", - includeCredentials.toString() - ); + Serializer.toString(request, "IncludeCredentials", includeCredentials, ParameterType.URLENCODED); } + + if (uiEditable != null) { - request.addPostParam("UiEditable", uiEditable.toString()); + Serializer.toString(request, "UiEditable", uiEditable, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/serverless/v1/ServiceDeleter.java b/src/main/java/com/twilio/rest/serverless/v1/ServiceDeleter.java index d6edbe1be0..fcbc7c8d85 100644 --- a/src/main/java/com/twilio/rest/serverless/v1/ServiceDeleter.java +++ b/src/main/java/com/twilio/rest/serverless/v1/ServiceDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.serverless.v1; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,40 +26,38 @@ public class ServiceDeleter extends Deleter { - private String pathSid; + private String pathsid; - public ServiceDeleter(final String pathSid) { - this.pathSid = pathSid; + public ServiceDeleter(final String pathsid) { + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/v1/Services/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.SERVERLESS.toString(), - path + HttpMethod.DELETE, + Domains.SERVERLESS.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Service delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("Service delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/serverless/v1/ServiceFetcher.java b/src/main/java/com/twilio/rest/serverless/v1/ServiceFetcher.java index c4e5aff593..7a5ab7980e 100644 --- a/src/main/java/com/twilio/rest/serverless/v1/ServiceFetcher.java +++ b/src/main/java/com/twilio/rest/serverless/v1/ServiceFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.serverless.v1; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,44 +26,41 @@ public class ServiceFetcher extends Fetcher { - private String pathSid; + private String pathsid; - public ServiceFetcher(final String pathSid) { - this.pathSid = pathSid; + public ServiceFetcher(final String pathsid) { + this.pathsid = pathsid; } + @Override public Service fetch(final TwilioRestClient client) { + String path = "/v1/Services/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.SERVERLESS.toString(), - path + HttpMethod.GET, + Domains.SERVERLESS.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Service fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Service fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Service.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/serverless/v1/ServiceReader.java b/src/main/java/com/twilio/rest/serverless/v1/ServiceReader.java index 05e09b001f..27636c2604 100644 --- a/src/main/java/com/twilio/rest/serverless/v1/ServiceReader.java +++ b/src/main/java/com/twilio/rest/serverless/v1/ServiceReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -31,105 +32,83 @@ public class ServiceReader extends Reader { private Long pageSize; - public ServiceReader() {} + public ServiceReader() { + } + public ServiceReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/Services"; + Request request = new Request( - HttpMethod.GET, - Domains.SERVERLESS.toString(), - path + HttpMethod.GET, + Domains.SERVERLESS.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Service read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Service read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "services", - response.getContent(), - Service.class, - client.getObjectMapper() - ); + "services", + response.getContent(), + Service.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.SERVERLESS.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.SERVERLESS.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/serverless/v1/ServiceUpdater.java b/src/main/java/com/twilio/rest/serverless/v1/ServiceUpdater.java index dca1ac2f1b..47c4a4d51a 100644 --- a/src/main/java/com/twilio/rest/serverless/v1/ServiceUpdater.java +++ b/src/main/java/com/twilio/rest/serverless/v1/ServiceUpdater.java @@ -16,6 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -26,61 +28,61 @@ import com.twilio.rest.Domains; public class ServiceUpdater extends Updater { - - private String pathSid; + private String pathsid; private Boolean includeCredentials; private String friendlyName; private Boolean uiEditable; - public ServiceUpdater(final String pathSid) { - this.pathSid = pathSid; + public ServiceUpdater(final String pathsid) { + this.pathsid = pathsid; } - public ServiceUpdater setIncludeCredentials( - final Boolean includeCredentials - ) { + + public ServiceUpdater setIncludeCredentials(final Boolean includeCredentials) { this.includeCredentials = includeCredentials; return this; } + public ServiceUpdater setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + public ServiceUpdater setUiEditable(final Boolean uiEditable) { this.uiEditable = uiEditable; return this; } + @Override public Service update(final TwilioRestClient client) { + String path = "/v1/Services/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.SERVERLESS.toString(), - path + HttpMethod.POST, + Domains.SERVERLESS.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Service update failed: Unable to connect to server" - ); + throw new ApiConnectionException("Service update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -89,17 +91,21 @@ public Service update(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (includeCredentials != null) { - request.addPostParam( - "IncludeCredentials", - includeCredentials.toString() - ); + Serializer.toString(request, "IncludeCredentials", includeCredentials, ParameterType.URLENCODED); } + + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + if (uiEditable != null) { - request.addPostParam("UiEditable", uiEditable.toString()); + Serializer.toString(request, "UiEditable", uiEditable, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/serverless/v1/service/Asset.java b/src/main/java/com/twilio/rest/serverless/v1/service/Asset.java index 0778553bf6..36659445e1 100644 --- a/src/main/java/com/twilio/rest/serverless/v1/service/Asset.java +++ b/src/main/java/com/twilio/rest/serverless/v1/service/Asset.java @@ -18,72 +18,71 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Asset extends Resource { - private static final long serialVersionUID = 60673471687127L; - public static AssetCreator creator( - final String pathServiceSid, - final String friendlyName - ) { - return new AssetCreator(pathServiceSid, friendlyName); + public static AssetCreator creator(final String pathserviceSid, final String friendlyName) { + return new AssetCreator( + pathserviceSid, friendlyName + ); } - public static AssetDeleter deleter( - final String pathServiceSid, - final String pathSid - ) { - return new AssetDeleter(pathServiceSid, pathSid); + + public static AssetDeleter deleter(final String pathserviceSid, final String pathsid) { + return new AssetDeleter( + pathserviceSid, pathsid + ); } - public static AssetFetcher fetcher( - final String pathServiceSid, - final String pathSid - ) { - return new AssetFetcher(pathServiceSid, pathSid); + + public static AssetFetcher fetcher(final String pathserviceSid, final String pathsid) { + return new AssetFetcher( + pathserviceSid, pathsid + ); } - public static AssetReader reader(final String pathServiceSid) { - return new AssetReader(pathServiceSid); + + public static AssetReader reader(final String pathserviceSid) { + return new AssetReader( + pathserviceSid + ); } - public static AssetUpdater updater( - final String pathServiceSid, - final String pathSid, - final String friendlyName - ) { - return new AssetUpdater(pathServiceSid, pathSid, friendlyName); + + public static AssetUpdater updater(final String pathserviceSid, final String pathsid, final String friendlyName) { + return new AssetUpdater( + pathserviceSid, pathsid, friendlyName + ); } + /** * Converts a JSON String into a Asset object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Asset object represented by the provided JSON */ - public static Asset fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Asset fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Asset.class); @@ -98,14 +97,11 @@ public static Asset fromJson( * Converts a JSON InputStream into a Asset object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Asset object represented by the provided JSON */ - public static Asset fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Asset fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Asset.class); @@ -116,66 +112,57 @@ public static Asset fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String serviceSid; - private final String friendlyName; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; - private final URI url; + @Getter + private final String friendlyName; + @Getter private final Map links; + @Getter + private final String serviceSid; + @Getter + private final String sid; + @Getter + private final URI url; @JsonCreator private Asset( - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("service_sid") final String serviceSid, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("url") final URI url, - @JsonProperty("links") final Map links + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("links") final Map links, + @JsonProperty("service_sid") final String serviceSid, + @JsonProperty("sid") final String sid, + @JsonProperty("url") final URI url ) { - this.sid = sid; this.accountSid = accountSid; - this.serviceSid = serviceSid; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.friendlyName = friendlyName; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); - this.url = url; this.links = links; - } - - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getServiceSid() { - return this.serviceSid; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final URI getUrl() { - return this.url; - } - - public final Map getLinks() { - return this.links; + this.serviceSid = serviceSid; + this.sid = sid; + this.url = url; } @Override @@ -189,30 +176,32 @@ public boolean equals(final Object o) { } Asset other = (Asset) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(serviceSid, other.serviceSid) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(url, other.url) && - Objects.equals(links, other.links) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(links, other.links) && + Objects.equals(serviceSid, other.serviceSid) && + Objects.equals(sid, other.sid) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - sid, - accountSid, - serviceSid, - friendlyName, - dateCreated, - dateUpdated, - url, - links + accountSid, + dateCreated, + dateUpdated, + friendlyName, + links, + serviceSid, + sid, + url ); } + + } + diff --git a/src/main/java/com/twilio/rest/serverless/v1/service/AssetCreator.java b/src/main/java/com/twilio/rest/serverless/v1/service/AssetCreator.java index b2f5c0f023..840fdafa11 100644 --- a/src/main/java/com/twilio/rest/serverless/v1/service/AssetCreator.java +++ b/src/main/java/com/twilio/rest/serverless/v1/service/AssetCreator.java @@ -14,8 +14,11 @@ package com.twilio.rest.serverless.v1.service; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,59 +30,48 @@ public class AssetCreator extends Creator { - private String pathServiceSid; + private String pathserviceSid; private String friendlyName; - public AssetCreator( - final String pathServiceSid, - final String friendlyName - ) { - this.pathServiceSid = pathServiceSid; + public AssetCreator(final String pathserviceSid, final String friendlyName) { + this.pathserviceSid = pathserviceSid; this.friendlyName = friendlyName; } + public AssetCreator setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + @Override public Asset create(final TwilioRestClient client) { + String path = "/v1/Services/{ServiceSid}/Assets"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = - path.replace( - "{" + "FriendlyName" + "}", - this.friendlyName.toString() - ); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.SERVERLESS.toString(), - path + HttpMethod.POST, + Domains.SERVERLESS.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Asset creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("Asset creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -88,8 +80,11 @@ public Asset create(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/serverless/v1/service/AssetDeleter.java b/src/main/java/com/twilio/rest/serverless/v1/service/AssetDeleter.java index 82cb21766b..57b129c0fb 100644 --- a/src/main/java/com/twilio/rest/serverless/v1/service/AssetDeleter.java +++ b/src/main/java/com/twilio/rest/serverless/v1/service/AssetDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.serverless.v1.service; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,47 +26,41 @@ public class AssetDeleter extends Deleter { - private String pathServiceSid; - private String pathSid; + private String pathserviceSid; + private String pathsid; - public AssetDeleter(final String pathServiceSid, final String pathSid) { - this.pathServiceSid = pathServiceSid; - this.pathSid = pathSid; + public AssetDeleter(final String pathserviceSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/v1/Services/{ServiceSid}/Assets/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.SERVERLESS.toString(), - path + HttpMethod.DELETE, + Domains.SERVERLESS.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Asset delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("Asset delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/serverless/v1/service/AssetFetcher.java b/src/main/java/com/twilio/rest/serverless/v1/service/AssetFetcher.java index 77a91051b6..6413c984b0 100644 --- a/src/main/java/com/twilio/rest/serverless/v1/service/AssetFetcher.java +++ b/src/main/java/com/twilio/rest/serverless/v1/service/AssetFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.serverless.v1.service; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,51 +26,44 @@ public class AssetFetcher extends Fetcher { - private String pathServiceSid; - private String pathSid; + private String pathserviceSid; + private String pathsid; - public AssetFetcher(final String pathServiceSid, final String pathSid) { - this.pathServiceSid = pathServiceSid; - this.pathSid = pathSid; + public AssetFetcher(final String pathserviceSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathsid = pathsid; } + @Override public Asset fetch(final TwilioRestClient client) { + String path = "/v1/Services/{ServiceSid}/Assets/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.SERVERLESS.toString(), - path + HttpMethod.GET, + Domains.SERVERLESS.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Asset fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Asset fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Asset.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/serverless/v1/service/AssetReader.java b/src/main/java/com/twilio/rest/serverless/v1/service/AssetReader.java index 95f2a562bd..8019ea186c 100644 --- a/src/main/java/com/twilio/rest/serverless/v1/service/AssetReader.java +++ b/src/main/java/com/twilio/rest/serverless/v1/service/AssetReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,115 +30,88 @@ public class AssetReader extends Reader { - private String pathServiceSid; + private String pathserviceSid; private Long pageSize; - public AssetReader(final String pathServiceSid) { - this.pathServiceSid = pathServiceSid; + public AssetReader(final String pathserviceSid) { + this.pathserviceSid = pathserviceSid; } + public AssetReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/Services/{ServiceSid}/Assets"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.SERVERLESS.toString(), - path + HttpMethod.GET, + Domains.SERVERLESS.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Asset read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Asset read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "assets", - response.getContent(), - Asset.class, - client.getObjectMapper() - ); + "assets", + response.getContent(), + Asset.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.SERVERLESS.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.SERVERLESS.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/serverless/v1/service/AssetUpdater.java b/src/main/java/com/twilio/rest/serverless/v1/service/AssetUpdater.java index d0012dc5d3..545dddf0cf 100644 --- a/src/main/java/com/twilio/rest/serverless/v1/service/AssetUpdater.java +++ b/src/main/java/com/twilio/rest/serverless/v1/service/AssetUpdater.java @@ -16,6 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -26,64 +28,51 @@ import com.twilio.rest.Domains; public class AssetUpdater extends Updater { - - private String pathServiceSid; - private String pathSid; + private String pathserviceSid; + private String pathsid; private String friendlyName; - public AssetUpdater( - final String pathServiceSid, - final String pathSid, - final String friendlyName - ) { - this.pathServiceSid = pathServiceSid; - this.pathSid = pathSid; + public AssetUpdater(final String pathserviceSid, final String pathsid, final String friendlyName) { + this.pathserviceSid = pathserviceSid; + this.pathsid = pathsid; this.friendlyName = friendlyName; } + public AssetUpdater setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + @Override public Asset update(final TwilioRestClient client) { + String path = "/v1/Services/{ServiceSid}/Assets/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); - path = - path.replace( - "{" + "FriendlyName" + "}", - this.friendlyName.toString() - ); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.SERVERLESS.toString(), - path + HttpMethod.POST, + Domains.SERVERLESS.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Asset update failed: Unable to connect to server" - ); + throw new ApiConnectionException("Asset update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -92,8 +81,11 @@ public Asset update(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/serverless/v1/service/Build.java b/src/main/java/com/twilio/rest/serverless/v1/service/Build.java index 30dfe72cf9..fe384a18c8 100644 --- a/src/main/java/com/twilio/rest/serverless/v1/service/Build.java +++ b/src/main/java/com/twilio/rest/serverless/v1/service/Build.java @@ -18,63 +18,114 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.List; import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Build extends Resource { - private static final long serialVersionUID = 76818411121781L; - public static BuildCreator creator(final String pathServiceSid) { - return new BuildCreator(pathServiceSid); + public static BuildCreator creator(final String pathserviceSid) { + return new BuildCreator( + pathserviceSid + ); } - public static BuildDeleter deleter( - final String pathServiceSid, - final String pathSid - ) { - return new BuildDeleter(pathServiceSid, pathSid); + + public static BuildDeleter deleter(final String pathserviceSid, final String pathsid) { + return new BuildDeleter( + pathserviceSid, pathsid + ); } - public static BuildFetcher fetcher( - final String pathServiceSid, - final String pathSid - ) { - return new BuildFetcher(pathServiceSid, pathSid); + + public static BuildFetcher fetcher(final String pathserviceSid, final String pathsid) { + return new BuildFetcher( + pathserviceSid, pathsid + ); + } + + + public static BuildReader reader(final String pathserviceSid) { + return new BuildReader( + pathserviceSid + ); } - public static BuildReader reader(final String pathServiceSid) { - return new BuildReader(pathServiceSid); + + public enum Status { + BUILDING("building"), + COMPLETED("completed"), + FAILED("failed"); + + private final String value; + + private Status(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static Status forValue(final String value) { + return Promoter.enumFromString(value, Status.values()); + } } + public enum Runtime { + NODE8("node8"), + NODE10("node10"), + NODE12("node12"), + NODE14("node14"), + NODE16("node16"), + NODE18("node18"), + NODE20("node20"), + NODE22("node22"); + + private final String value; + + private Runtime(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static Runtime forValue(final String value) { + return Promoter.enumFromString(value, Runtime.values()); + } + } + + /** * Converts a JSON String into a Build object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Build object represented by the provided JSON */ - public static Build fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Build fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Build.class); @@ -89,14 +140,11 @@ public static Build fromJson( * Converts a JSON InputStream into a Build object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Build object represented by the provided JSON */ - public static Build fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Build fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Build.class); @@ -107,100 +155,73 @@ public static Build fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String serviceSid; - private final Build.Status status; - private final List> assetVersions; - private final List> functionVersions; - private final List> dependencies; - private final Build.Runtime runtime; + @Getter + private final List assetVersions; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; - private final URI url; + @Getter + private final List dependencies; + @Getter + private final List functionVersions; + @Getter private final Map links; + @Getter + private final Build.Runtime runtime; + @Getter + private final String serviceSid; + @Getter + private final String sid; + @Getter + private final Build.Status status; + @Getter + private final URI url; @JsonCreator private Build( - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("service_sid") final String serviceSid, - @JsonProperty("status") final Build.Status status, - @JsonProperty("asset_versions") final List< - Map - > assetVersions, - @JsonProperty("function_versions") final List< - Map - > functionVersions, - @JsonProperty("dependencies") final List< - Map - > dependencies, - @JsonProperty("runtime") final Build.Runtime runtime, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("url") final URI url, - @JsonProperty("links") final Map links + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("asset_versions") final List assetVersions, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("dependencies") final List dependencies, + @JsonProperty("function_versions") final List functionVersions, + @JsonProperty("links") final Map links, + @JsonProperty("runtime") final Build.Runtime runtime, + @JsonProperty("service_sid") final String serviceSid, + @JsonProperty("sid") final String sid, + @JsonProperty("status") final Build.Status status, + @JsonProperty("url") final URI url ) { - this.sid = sid; this.accountSid = accountSid; - this.serviceSid = serviceSid; - this.status = status; this.assetVersions = assetVersions; - this.functionVersions = functionVersions; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.dependencies = dependencies; + this.functionVersions = functionVersions; + this.links = links; this.runtime = runtime; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); + this.serviceSid = serviceSid; + this.sid = sid; + this.status = status; this.url = url; - this.links = links; - } - - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getServiceSid() { - return this.serviceSid; - } - - public final Build.Status getStatus() { - return this.status; - } - - public final List> getAssetVersions() { - return this.assetVersions; - } - - public final List> getFunctionVersions() { - return this.functionVersions; - } - - public final List> getDependencies() { - return this.dependencies; - } - - public final Build.Runtime getRuntime() { - return this.runtime; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final URI getUrl() { - return this.url; - } - - public final Map getLinks() { - return this.links; } @Override @@ -214,85 +235,40 @@ public boolean equals(final Object o) { } Build other = (Build) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(serviceSid, other.serviceSid) && - Objects.equals(status, other.status) && - Objects.equals(assetVersions, other.assetVersions) && - Objects.equals(functionVersions, other.functionVersions) && - Objects.equals(dependencies, other.dependencies) && - Objects.equals(runtime, other.runtime) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(url, other.url) && - Objects.equals(links, other.links) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(assetVersions, other.assetVersions) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(dependencies, other.dependencies) && + Objects.equals(functionVersions, other.functionVersions) && + Objects.equals(links, other.links) && + Objects.equals(runtime, other.runtime) && + Objects.equals(serviceSid, other.serviceSid) && + Objects.equals(sid, other.sid) && + Objects.equals(status, other.status) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - sid, - accountSid, - serviceSid, - status, - assetVersions, - functionVersions, - dependencies, - runtime, - dateCreated, - dateUpdated, - url, - links + accountSid, + assetVersions, + dateCreated, + dateUpdated, + dependencies, + functionVersions, + links, + runtime, + serviceSid, + sid, + status, + url ); } - public enum Runtime { - NODE8("node8"), - NODE10("node10"), - NODE12("node12"), - NODE14("node14"), - NODE16("node16"), - NODE18("node18"), - NODE20("node20"), - NODE22("node22"); - - private final String value; - - private Runtime(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static Runtime forValue(final String value) { - return Promoter.enumFromString(value, Runtime.values()); - } - } - - public enum Status { - BUILDING("building"), - COMPLETED("completed"), - FAILED("failed"); - - private final String value; - - private Status(final String value) { - this.value = value; - } - public String toString() { - return value; - } - - @JsonCreator - public static Status forValue(final String value) { - return Promoter.enumFromString(value, Status.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/serverless/v1/service/BuildCreator.java b/src/main/java/com/twilio/rest/serverless/v1/service/BuildCreator.java index f5dc64971a..f25919ee2f 100644 --- a/src/main/java/com/twilio/rest/serverless/v1/service/BuildCreator.java +++ b/src/main/java/com/twilio/rest/serverless/v1/service/BuildCreator.java @@ -14,9 +14,12 @@ package com.twilio.rest.serverless.v1.service; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; import com.twilio.converter.Promoter; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,21 +28,22 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -import java.util.List; + import java.util.List; public class BuildCreator extends Creator { - private String pathServiceSid; + private String pathserviceSid; private List assetVersions; private List functionVersions; private String dependencies; private String runtime; - public BuildCreator(final String pathServiceSid) { - this.pathServiceSid = pathServiceSid; + public BuildCreator(final String pathserviceSid) { + this.pathserviceSid = pathserviceSid; } + public BuildCreator setAssetVersions(final List assetVersions) { this.assetVersions = assetVersions; return this; @@ -49,9 +53,7 @@ public BuildCreator setAssetVersions(final String assetVersions) { return setAssetVersions(Promoter.listOfOne(assetVersions)); } - public BuildCreator setFunctionVersions( - final List functionVersions - ) { + public BuildCreator setFunctionVersions(final List functionVersions) { this.functionVersions = functionVersions; return this; } @@ -65,43 +67,40 @@ public BuildCreator setDependencies(final String dependencies) { return this; } + public BuildCreator setRuntime(final String runtime) { this.runtime = runtime; return this; } + @Override public Build create(final TwilioRestClient client) { + String path = "/v1/Services/{ServiceSid}/Builds"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.SERVERLESS.toString(), - path + HttpMethod.POST, + Domains.SERVERLESS.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Build creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("Build creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -110,21 +109,31 @@ public Build create(final TwilioRestClient client) { } private void addPostParams(final Request request) { + + if (assetVersions != null) { - for (String prop : assetVersions) { - request.addPostParam("AssetVersions", prop); + for (String param : assetVersions) { + Serializer.toString(request, "AssetVersions", param, ParameterType.URLENCODED); } } + + if (functionVersions != null) { - for (String prop : functionVersions) { - request.addPostParam("FunctionVersions", prop); + for (String param : functionVersions) { + Serializer.toString(request, "FunctionVersions", param, ParameterType.URLENCODED); } } + + if (dependencies != null) { - request.addPostParam("Dependencies", dependencies); + Serializer.toString(request, "Dependencies", dependencies, ParameterType.URLENCODED); } + + if (runtime != null) { - request.addPostParam("Runtime", runtime); + Serializer.toString(request, "Runtime", runtime, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/serverless/v1/service/BuildDeleter.java b/src/main/java/com/twilio/rest/serverless/v1/service/BuildDeleter.java index de1de3a0be..79d330c936 100644 --- a/src/main/java/com/twilio/rest/serverless/v1/service/BuildDeleter.java +++ b/src/main/java/com/twilio/rest/serverless/v1/service/BuildDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.serverless.v1.service; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,47 +26,41 @@ public class BuildDeleter extends Deleter { - private String pathServiceSid; - private String pathSid; + private String pathserviceSid; + private String pathsid; - public BuildDeleter(final String pathServiceSid, final String pathSid) { - this.pathServiceSid = pathServiceSid; - this.pathSid = pathSid; + public BuildDeleter(final String pathserviceSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/v1/Services/{ServiceSid}/Builds/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.SERVERLESS.toString(), - path + HttpMethod.DELETE, + Domains.SERVERLESS.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Build delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("Build delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/serverless/v1/service/BuildFetcher.java b/src/main/java/com/twilio/rest/serverless/v1/service/BuildFetcher.java index b864dd1976..baa37f0e7a 100644 --- a/src/main/java/com/twilio/rest/serverless/v1/service/BuildFetcher.java +++ b/src/main/java/com/twilio/rest/serverless/v1/service/BuildFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.serverless.v1.service; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,51 +26,44 @@ public class BuildFetcher extends Fetcher { - private String pathServiceSid; - private String pathSid; + private String pathserviceSid; + private String pathsid; - public BuildFetcher(final String pathServiceSid, final String pathSid) { - this.pathServiceSid = pathServiceSid; - this.pathSid = pathSid; + public BuildFetcher(final String pathserviceSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathsid = pathsid; } + @Override public Build fetch(final TwilioRestClient client) { + String path = "/v1/Services/{ServiceSid}/Builds/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.SERVERLESS.toString(), - path + HttpMethod.GET, + Domains.SERVERLESS.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Build fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Build fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Build.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/serverless/v1/service/BuildReader.java b/src/main/java/com/twilio/rest/serverless/v1/service/BuildReader.java index aef8924d8b..a4f7dc283f 100644 --- a/src/main/java/com/twilio/rest/serverless/v1/service/BuildReader.java +++ b/src/main/java/com/twilio/rest/serverless/v1/service/BuildReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,115 +30,88 @@ public class BuildReader extends Reader { - private String pathServiceSid; + private String pathserviceSid; private Long pageSize; - public BuildReader(final String pathServiceSid) { - this.pathServiceSid = pathServiceSid; + public BuildReader(final String pathserviceSid) { + this.pathserviceSid = pathserviceSid; } + public BuildReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/Services/{ServiceSid}/Builds"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.SERVERLESS.toString(), - path + HttpMethod.GET, + Domains.SERVERLESS.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Build read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Build read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "builds", - response.getContent(), - Build.class, - client.getObjectMapper() - ); + "builds", + response.getContent(), + Build.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.SERVERLESS.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.SERVERLESS.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/serverless/v1/service/Environment.java b/src/main/java/com/twilio/rest/serverless/v1/service/Environment.java index 19463d800c..5680f303b3 100644 --- a/src/main/java/com/twilio/rest/serverless/v1/service/Environment.java +++ b/src/main/java/com/twilio/rest/serverless/v1/service/Environment.java @@ -18,64 +18,64 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Environment extends Resource { - private static final long serialVersionUID = 36784486672291L; - public static EnvironmentCreator creator( - final String pathServiceSid, - final String uniqueName - ) { - return new EnvironmentCreator(pathServiceSid, uniqueName); + public static EnvironmentCreator creator(final String pathserviceSid, final String uniqueName) { + return new EnvironmentCreator( + pathserviceSid, uniqueName + ); } - public static EnvironmentDeleter deleter( - final String pathServiceSid, - final String pathSid - ) { - return new EnvironmentDeleter(pathServiceSid, pathSid); + + public static EnvironmentDeleter deleter(final String pathserviceSid, final String pathsid) { + return new EnvironmentDeleter( + pathserviceSid, pathsid + ); } - public static EnvironmentFetcher fetcher( - final String pathServiceSid, - final String pathSid - ) { - return new EnvironmentFetcher(pathServiceSid, pathSid); + + public static EnvironmentFetcher fetcher(final String pathserviceSid, final String pathsid) { + return new EnvironmentFetcher( + pathserviceSid, pathsid + ); } - public static EnvironmentReader reader(final String pathServiceSid) { - return new EnvironmentReader(pathServiceSid); + + public static EnvironmentReader reader(final String pathserviceSid) { + return new EnvironmentReader( + pathserviceSid + ); } + /** * Converts a JSON String into a Environment object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Environment object represented by the provided JSON */ - public static Environment fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Environment fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Environment.class); @@ -90,14 +90,11 @@ public static Environment fromJson( * Converts a JSON InputStream into a Environment object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Environment object represented by the provided JSON */ - public static Environment fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Environment fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Environment.class); @@ -108,87 +105,69 @@ public static Environment fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String serviceSid; + @Getter private final String buildSid; - private final String uniqueName; - private final String domainSuffix; - private final String domainName; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; - private final URI url; + @Getter + private final String domainName; + @Getter + private final String domainSuffix; + @Getter private final Map links; + @Getter + private final String serviceSid; + @Getter + private final String sid; + @Getter + private final String uniqueName; + @Getter + private final URI url; @JsonCreator private Environment( - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("service_sid") final String serviceSid, - @JsonProperty("build_sid") final String buildSid, - @JsonProperty("unique_name") final String uniqueName, - @JsonProperty("domain_suffix") final String domainSuffix, - @JsonProperty("domain_name") final String domainName, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("url") final URI url, - @JsonProperty("links") final Map links + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("build_sid") final String buildSid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("domain_name") final String domainName, + @JsonProperty("domain_suffix") final String domainSuffix, + @JsonProperty("links") final Map links, + @JsonProperty("service_sid") final String serviceSid, + @JsonProperty("sid") final String sid, + @JsonProperty("unique_name") final String uniqueName, + @JsonProperty("url") final URI url ) { - this.sid = sid; this.accountSid = accountSid; - this.serviceSid = serviceSid; this.buildSid = buildSid; - this.uniqueName = uniqueName; - this.domainSuffix = domainSuffix; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.domainName = domainName; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); - this.url = url; + this.domainSuffix = domainSuffix; this.links = links; - } - - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getServiceSid() { - return this.serviceSid; - } - - public final String getBuildSid() { - return this.buildSid; - } - - public final String getUniqueName() { - return this.uniqueName; - } - - public final String getDomainSuffix() { - return this.domainSuffix; - } - - public final String getDomainName() { - return this.domainName; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final URI getUrl() { - return this.url; - } - - public final Map getLinks() { - return this.links; + this.serviceSid = serviceSid; + this.sid = sid; + this.uniqueName = uniqueName; + this.url = url; } @Override @@ -202,36 +181,38 @@ public boolean equals(final Object o) { } Environment other = (Environment) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(serviceSid, other.serviceSid) && - Objects.equals(buildSid, other.buildSid) && - Objects.equals(uniqueName, other.uniqueName) && - Objects.equals(domainSuffix, other.domainSuffix) && - Objects.equals(domainName, other.domainName) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(url, other.url) && - Objects.equals(links, other.links) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(buildSid, other.buildSid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(domainName, other.domainName) && + Objects.equals(domainSuffix, other.domainSuffix) && + Objects.equals(links, other.links) && + Objects.equals(serviceSid, other.serviceSid) && + Objects.equals(sid, other.sid) && + Objects.equals(uniqueName, other.uniqueName) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - sid, - accountSid, - serviceSid, - buildSid, - uniqueName, - domainSuffix, - domainName, - dateCreated, - dateUpdated, - url, - links + accountSid, + buildSid, + dateCreated, + dateUpdated, + domainName, + domainSuffix, + links, + serviceSid, + sid, + uniqueName, + url ); } + + } + diff --git a/src/main/java/com/twilio/rest/serverless/v1/service/EnvironmentCreator.java b/src/main/java/com/twilio/rest/serverless/v1/service/EnvironmentCreator.java index 745eae15d4..9025eb4cac 100644 --- a/src/main/java/com/twilio/rest/serverless/v1/service/EnvironmentCreator.java +++ b/src/main/java/com/twilio/rest/serverless/v1/service/EnvironmentCreator.java @@ -14,8 +14,11 @@ package com.twilio.rest.serverless.v1.service; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,78 +30,73 @@ public class EnvironmentCreator extends Creator { - private String pathServiceSid; + private String pathserviceSid; private String uniqueName; private String domainSuffix; - public EnvironmentCreator( - final String pathServiceSid, - final String uniqueName - ) { - this.pathServiceSid = pathServiceSid; + public EnvironmentCreator(final String pathserviceSid, final String uniqueName) { + this.pathserviceSid = pathserviceSid; this.uniqueName = uniqueName; } + public EnvironmentCreator setUniqueName(final String uniqueName) { this.uniqueName = uniqueName; return this; } + public EnvironmentCreator setDomainSuffix(final String domainSuffix) { this.domainSuffix = domainSuffix; return this; } + @Override public Environment create(final TwilioRestClient client) { + String path = "/v1/Services/{ServiceSid}/Environments"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = - path.replace("{" + "UniqueName" + "}", this.uniqueName.toString()); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.SERVERLESS.toString(), - path + HttpMethod.POST, + Domains.SERVERLESS.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Environment creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("Environment creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Environment.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Environment.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (uniqueName != null) { - request.addPostParam("UniqueName", uniqueName); + Serializer.toString(request, "UniqueName", uniqueName, ParameterType.URLENCODED); } + + if (domainSuffix != null) { - request.addPostParam("DomainSuffix", domainSuffix); + Serializer.toString(request, "DomainSuffix", domainSuffix, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/serverless/v1/service/EnvironmentDeleter.java b/src/main/java/com/twilio/rest/serverless/v1/service/EnvironmentDeleter.java index abad01428f..d999114880 100644 --- a/src/main/java/com/twilio/rest/serverless/v1/service/EnvironmentDeleter.java +++ b/src/main/java/com/twilio/rest/serverless/v1/service/EnvironmentDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.serverless.v1.service; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,50 +26,41 @@ public class EnvironmentDeleter extends Deleter { - private String pathServiceSid; - private String pathSid; + private String pathserviceSid; + private String pathsid; - public EnvironmentDeleter( - final String pathServiceSid, - final String pathSid - ) { - this.pathServiceSid = pathServiceSid; - this.pathSid = pathSid; + public EnvironmentDeleter(final String pathserviceSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/v1/Services/{ServiceSid}/Environments/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.SERVERLESS.toString(), - path + HttpMethod.DELETE, + Domains.SERVERLESS.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Environment delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("Environment delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/serverless/v1/service/EnvironmentFetcher.java b/src/main/java/com/twilio/rest/serverless/v1/service/EnvironmentFetcher.java index 6e04aabc0e..d556a1287e 100644 --- a/src/main/java/com/twilio/rest/serverless/v1/service/EnvironmentFetcher.java +++ b/src/main/java/com/twilio/rest/serverless/v1/service/EnvironmentFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.serverless.v1.service; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,57 +26,44 @@ public class EnvironmentFetcher extends Fetcher { - private String pathServiceSid; - private String pathSid; + private String pathserviceSid; + private String pathsid; - public EnvironmentFetcher( - final String pathServiceSid, - final String pathSid - ) { - this.pathServiceSid = pathServiceSid; - this.pathSid = pathSid; + public EnvironmentFetcher(final String pathserviceSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathsid = pathsid; } + @Override public Environment fetch(final TwilioRestClient client) { + String path = "/v1/Services/{ServiceSid}/Environments/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.SERVERLESS.toString(), - path + HttpMethod.GET, + Domains.SERVERLESS.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Environment fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Environment fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return Environment.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Environment.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/serverless/v1/service/EnvironmentReader.java b/src/main/java/com/twilio/rest/serverless/v1/service/EnvironmentReader.java index f5c0e0c76f..29bb91e65f 100644 --- a/src/main/java/com/twilio/rest/serverless/v1/service/EnvironmentReader.java +++ b/src/main/java/com/twilio/rest/serverless/v1/service/EnvironmentReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,115 +30,88 @@ public class EnvironmentReader extends Reader { - private String pathServiceSid; + private String pathserviceSid; private Long pageSize; - public EnvironmentReader(final String pathServiceSid) { - this.pathServiceSid = pathServiceSid; + public EnvironmentReader(final String pathserviceSid) { + this.pathserviceSid = pathserviceSid; } + public EnvironmentReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/Services/{ServiceSid}/Environments"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.SERVERLESS.toString(), - path + HttpMethod.GET, + Domains.SERVERLESS.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Environment read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Environment read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "environments", - response.getContent(), - Environment.class, - client.getObjectMapper() - ); + "environments", + response.getContent(), + Environment.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.SERVERLESS.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.SERVERLESS.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/serverless/v1/service/Function.java b/src/main/java/com/twilio/rest/serverless/v1/service/Function.java index c5180634d8..e1958c7475 100644 --- a/src/main/java/com/twilio/rest/serverless/v1/service/Function.java +++ b/src/main/java/com/twilio/rest/serverless/v1/service/Function.java @@ -18,72 +18,71 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Function extends Resource { - private static final long serialVersionUID = 60673471687127L; - public static FunctionCreator creator( - final String pathServiceSid, - final String friendlyName - ) { - return new FunctionCreator(pathServiceSid, friendlyName); + public static FunctionCreator creator(final String pathserviceSid, final String friendlyName) { + return new FunctionCreator( + pathserviceSid, friendlyName + ); } - public static FunctionDeleter deleter( - final String pathServiceSid, - final String pathSid - ) { - return new FunctionDeleter(pathServiceSid, pathSid); + + public static FunctionDeleter deleter(final String pathserviceSid, final String pathsid) { + return new FunctionDeleter( + pathserviceSid, pathsid + ); } - public static FunctionFetcher fetcher( - final String pathServiceSid, - final String pathSid - ) { - return new FunctionFetcher(pathServiceSid, pathSid); + + public static FunctionFetcher fetcher(final String pathserviceSid, final String pathsid) { + return new FunctionFetcher( + pathserviceSid, pathsid + ); } - public static FunctionReader reader(final String pathServiceSid) { - return new FunctionReader(pathServiceSid); + + public static FunctionReader reader(final String pathserviceSid) { + return new FunctionReader( + pathserviceSid + ); } - public static FunctionUpdater updater( - final String pathServiceSid, - final String pathSid, - final String friendlyName - ) { - return new FunctionUpdater(pathServiceSid, pathSid, friendlyName); + + public static FunctionUpdater updater(final String pathserviceSid, final String pathsid, final String friendlyName) { + return new FunctionUpdater( + pathserviceSid, pathsid, friendlyName + ); } + /** * Converts a JSON String into a Function object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Function object represented by the provided JSON */ - public static Function fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Function fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Function.class); @@ -98,14 +97,11 @@ public static Function fromJson( * Converts a JSON InputStream into a Function object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Function object represented by the provided JSON */ - public static Function fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Function fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Function.class); @@ -116,66 +112,57 @@ public static Function fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String serviceSid; - private final String friendlyName; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; - private final URI url; + @Getter + private final String friendlyName; + @Getter private final Map links; + @Getter + private final String serviceSid; + @Getter + private final String sid; + @Getter + private final URI url; @JsonCreator private Function( - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("service_sid") final String serviceSid, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("url") final URI url, - @JsonProperty("links") final Map links + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("links") final Map links, + @JsonProperty("service_sid") final String serviceSid, + @JsonProperty("sid") final String sid, + @JsonProperty("url") final URI url ) { - this.sid = sid; this.accountSid = accountSid; - this.serviceSid = serviceSid; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.friendlyName = friendlyName; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); - this.url = url; this.links = links; - } - - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getServiceSid() { - return this.serviceSid; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final URI getUrl() { - return this.url; - } - - public final Map getLinks() { - return this.links; + this.serviceSid = serviceSid; + this.sid = sid; + this.url = url; } @Override @@ -189,30 +176,32 @@ public boolean equals(final Object o) { } Function other = (Function) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(serviceSid, other.serviceSid) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(url, other.url) && - Objects.equals(links, other.links) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(links, other.links) && + Objects.equals(serviceSid, other.serviceSid) && + Objects.equals(sid, other.sid) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - sid, - accountSid, - serviceSid, - friendlyName, - dateCreated, - dateUpdated, - url, - links + accountSid, + dateCreated, + dateUpdated, + friendlyName, + links, + serviceSid, + sid, + url ); } + + } + diff --git a/src/main/java/com/twilio/rest/serverless/v1/service/FunctionCreator.java b/src/main/java/com/twilio/rest/serverless/v1/service/FunctionCreator.java index 4358a75d8d..447c21954f 100644 --- a/src/main/java/com/twilio/rest/serverless/v1/service/FunctionCreator.java +++ b/src/main/java/com/twilio/rest/serverless/v1/service/FunctionCreator.java @@ -14,8 +14,11 @@ package com.twilio.rest.serverless.v1.service; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,72 +30,61 @@ public class FunctionCreator extends Creator { - private String pathServiceSid; + private String pathserviceSid; private String friendlyName; - public FunctionCreator( - final String pathServiceSid, - final String friendlyName - ) { - this.pathServiceSid = pathServiceSid; + public FunctionCreator(final String pathserviceSid, final String friendlyName) { + this.pathserviceSid = pathserviceSid; this.friendlyName = friendlyName; } + public FunctionCreator setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + @Override public Function create(final TwilioRestClient client) { + String path = "/v1/Services/{ServiceSid}/Functions"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = - path.replace( - "{" + "FriendlyName" + "}", - this.friendlyName.toString() - ); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.SERVERLESS.toString(), - path + HttpMethod.POST, + Domains.SERVERLESS.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Function creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("Function creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Function.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Function.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/serverless/v1/service/FunctionDeleter.java b/src/main/java/com/twilio/rest/serverless/v1/service/FunctionDeleter.java index 75e10f10c4..8b6b4555f3 100644 --- a/src/main/java/com/twilio/rest/serverless/v1/service/FunctionDeleter.java +++ b/src/main/java/com/twilio/rest/serverless/v1/service/FunctionDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.serverless.v1.service; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,47 +26,41 @@ public class FunctionDeleter extends Deleter { - private String pathServiceSid; - private String pathSid; + private String pathserviceSid; + private String pathsid; - public FunctionDeleter(final String pathServiceSid, final String pathSid) { - this.pathServiceSid = pathServiceSid; - this.pathSid = pathSid; + public FunctionDeleter(final String pathserviceSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/v1/Services/{ServiceSid}/Functions/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.SERVERLESS.toString(), - path + HttpMethod.DELETE, + Domains.SERVERLESS.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Function delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("Function delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/serverless/v1/service/FunctionFetcher.java b/src/main/java/com/twilio/rest/serverless/v1/service/FunctionFetcher.java index d00f6f697d..19486da7c9 100644 --- a/src/main/java/com/twilio/rest/serverless/v1/service/FunctionFetcher.java +++ b/src/main/java/com/twilio/rest/serverless/v1/service/FunctionFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.serverless.v1.service; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,54 +26,44 @@ public class FunctionFetcher extends Fetcher { - private String pathServiceSid; - private String pathSid; + private String pathserviceSid; + private String pathsid; - public FunctionFetcher(final String pathServiceSid, final String pathSid) { - this.pathServiceSid = pathServiceSid; - this.pathSid = pathSid; + public FunctionFetcher(final String pathserviceSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathsid = pathsid; } + @Override public Function fetch(final TwilioRestClient client) { + String path = "/v1/Services/{ServiceSid}/Functions/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.SERVERLESS.toString(), - path + HttpMethod.GET, + Domains.SERVERLESS.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Function fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Function fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return Function.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Function.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/serverless/v1/service/FunctionReader.java b/src/main/java/com/twilio/rest/serverless/v1/service/FunctionReader.java index fe669a8309..76dc6e621b 100644 --- a/src/main/java/com/twilio/rest/serverless/v1/service/FunctionReader.java +++ b/src/main/java/com/twilio/rest/serverless/v1/service/FunctionReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,115 +30,88 @@ public class FunctionReader extends Reader { - private String pathServiceSid; + private String pathserviceSid; private Long pageSize; - public FunctionReader(final String pathServiceSid) { - this.pathServiceSid = pathServiceSid; + public FunctionReader(final String pathserviceSid) { + this.pathserviceSid = pathserviceSid; } + public FunctionReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/Services/{ServiceSid}/Functions"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.SERVERLESS.toString(), - path + HttpMethod.GET, + Domains.SERVERLESS.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Function read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Function read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "functions", - response.getContent(), - Function.class, - client.getObjectMapper() - ); + "functions", + response.getContent(), + Function.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.SERVERLESS.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.SERVERLESS.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/serverless/v1/service/FunctionUpdater.java b/src/main/java/com/twilio/rest/serverless/v1/service/FunctionUpdater.java index 67411c6ae0..04de58d836 100644 --- a/src/main/java/com/twilio/rest/serverless/v1/service/FunctionUpdater.java +++ b/src/main/java/com/twilio/rest/serverless/v1/service/FunctionUpdater.java @@ -16,6 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -26,77 +28,64 @@ import com.twilio.rest.Domains; public class FunctionUpdater extends Updater { - - private String pathServiceSid; - private String pathSid; + private String pathserviceSid; + private String pathsid; private String friendlyName; - public FunctionUpdater( - final String pathServiceSid, - final String pathSid, - final String friendlyName - ) { - this.pathServiceSid = pathServiceSid; - this.pathSid = pathSid; + public FunctionUpdater(final String pathserviceSid, final String pathsid, final String friendlyName) { + this.pathserviceSid = pathserviceSid; + this.pathsid = pathsid; this.friendlyName = friendlyName; } + public FunctionUpdater setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + @Override public Function update(final TwilioRestClient client) { + String path = "/v1/Services/{ServiceSid}/Functions/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); - path = - path.replace( - "{" + "FriendlyName" + "}", - this.friendlyName.toString() - ); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.SERVERLESS.toString(), - path + HttpMethod.POST, + Domains.SERVERLESS.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Function update failed: Unable to connect to server" - ); + throw new ApiConnectionException("Function update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Function.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Function.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/serverless/v1/service/asset/AssetVersion.java b/src/main/java/com/twilio/rest/serverless/v1/service/asset/AssetVersion.java index a8cc25e5b0..3a7d943b40 100644 --- a/src/main/java/com/twilio/rest/serverless/v1/service/asset/AssetVersion.java +++ b/src/main/java/com/twilio/rest/serverless/v1/service/asset/AssetVersion.java @@ -18,53 +18,72 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class AssetVersion extends Resource { - private static final long serialVersionUID = 215359401104297L; - public static AssetVersionFetcher fetcher( - final String pathServiceSid, - final String pathAssetSid, - final String pathSid - ) { - return new AssetVersionFetcher(pathServiceSid, pathAssetSid, pathSid); + public static AssetVersionFetcher fetcher(final String pathserviceSid, final String pathassetSid, final String pathsid) { + return new AssetVersionFetcher( + pathserviceSid, pathassetSid, pathsid + ); } - public static AssetVersionReader reader( - final String pathServiceSid, - final String pathAssetSid - ) { - return new AssetVersionReader(pathServiceSid, pathAssetSid); + + public static AssetVersionReader reader(final String pathserviceSid, final String pathassetSid) { + return new AssetVersionReader( + pathserviceSid, pathassetSid + ); } + + public enum Visibility { + PUBLIC("public"), + PRIVATE("private"), + PROTECTED("protected"); + + private final String value; + + private Visibility(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static Visibility forValue(final String value) { + return Promoter.enumFromString(value, Visibility.values()); + } + } + + /** * Converts a JSON String into a AssetVersion object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return AssetVersion object represented by the provided JSON */ - public static AssetVersion fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static AssetVersion fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, AssetVersion.class); @@ -79,14 +98,11 @@ public static AssetVersion fromJson( * Converts a JSON InputStream into a AssetVersion object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return AssetVersion object represented by the provided JSON */ - public static AssetVersion fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static AssetVersion fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, AssetVersion.class); @@ -97,66 +113,56 @@ public static AssetVersion fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String serviceSid; + @Getter private final String assetSid; - private final String path; - private final AssetVersion.Visibility visibility; + @Getter private final ZonedDateTime dateCreated; + @Getter + private final String path; + @Getter + private final String serviceSid; + @Getter + private final String sid; + @Getter private final URI url; + @Getter + private final AssetVersion.Visibility visibility; @JsonCreator private AssetVersion( - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("service_sid") final String serviceSid, - @JsonProperty("asset_sid") final String assetSid, - @JsonProperty("path") final String path, - @JsonProperty("visibility") final AssetVersion.Visibility visibility, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("url") final URI url + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("asset_sid") final String assetSid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("path") final String path, + @JsonProperty("service_sid") final String serviceSid, + @JsonProperty("sid") final String sid, + @JsonProperty("url") final URI url, + @JsonProperty("visibility") final AssetVersion.Visibility visibility ) { - this.sid = sid; this.accountSid = accountSid; - this.serviceSid = serviceSid; this.assetSid = assetSid; + this.dateCreated = dateCreated; this.path = path; - this.visibility = visibility; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); + this.serviceSid = serviceSid; + this.sid = sid; this.url = url; - } - - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getServiceSid() { - return this.serviceSid; - } - - public final String getAssetSid() { - return this.assetSid; - } - - public final String getPath() { - return this.path; - } - - public final AssetVersion.Visibility getVisibility() { - return this.visibility; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final URI getUrl() { - return this.url; + this.visibility = visibility; } @Override @@ -170,51 +176,32 @@ public boolean equals(final Object o) { } AssetVersion other = (AssetVersion) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(serviceSid, other.serviceSid) && - Objects.equals(assetSid, other.assetSid) && - Objects.equals(path, other.path) && - Objects.equals(visibility, other.visibility) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(url, other.url) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(assetSid, other.assetSid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(path, other.path) && + Objects.equals(serviceSid, other.serviceSid) && + Objects.equals(sid, other.sid) && + Objects.equals(url, other.url) && + Objects.equals(visibility, other.visibility) ); } @Override public int hashCode() { return Objects.hash( - sid, - accountSid, - serviceSid, - assetSid, - path, - visibility, - dateCreated, - url + accountSid, + assetSid, + dateCreated, + path, + serviceSid, + sid, + url, + visibility ); } - public enum Visibility { - PUBLIC("public"), - PRIVATE("private"), - PROTECTED("protected"); - - private final String value; - private Visibility(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static Visibility forValue(final String value) { - return Promoter.enumFromString(value, Visibility.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/serverless/v1/service/asset/AssetVersionFetcher.java b/src/main/java/com/twilio/rest/serverless/v1/service/asset/AssetVersionFetcher.java index c4f1cf8d00..6036bbd1c9 100644 --- a/src/main/java/com/twilio/rest/serverless/v1/service/asset/AssetVersionFetcher.java +++ b/src/main/java/com/twilio/rest/serverless/v1/service/asset/AssetVersionFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.serverless.v1.service.asset; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,63 +26,47 @@ public class AssetVersionFetcher extends Fetcher { - private String pathServiceSid; - private String pathAssetSid; - private String pathSid; + private String pathserviceSid; + private String pathassetSid; + private String pathsid; - public AssetVersionFetcher( - final String pathServiceSid, - final String pathAssetSid, - final String pathSid - ) { - this.pathServiceSid = pathServiceSid; - this.pathAssetSid = pathAssetSid; - this.pathSid = pathSid; + public AssetVersionFetcher(final String pathserviceSid, final String pathassetSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathassetSid = pathassetSid; + this.pathsid = pathsid; } + @Override public AssetVersion fetch(final TwilioRestClient client) { - String path = - "/v1/Services/{ServiceSid}/Assets/{AssetSid}/Versions/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = - path.replace("{" + "AssetSid" + "}", this.pathAssetSid.toString()); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/v1/Services/{ServiceSid}/Assets/{AssetSid}/Versions/{Sid}"; + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "AssetSid" + "}", this.pathassetSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.SERVERLESS.toString(), - path + HttpMethod.GET, + Domains.SERVERLESS.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "AssetVersion fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("AssetVersion fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return AssetVersion.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return AssetVersion.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/serverless/v1/service/asset/AssetVersionReader.java b/src/main/java/com/twilio/rest/serverless/v1/service/asset/AssetVersionReader.java index 26349d7497..66ccb0b67b 100644 --- a/src/main/java/com/twilio/rest/serverless/v1/service/asset/AssetVersionReader.java +++ b/src/main/java/com/twilio/rest/serverless/v1/service/asset/AssetVersionReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,122 +30,91 @@ public class AssetVersionReader extends Reader { - private String pathServiceSid; - private String pathAssetSid; + private String pathserviceSid; + private String pathassetSid; private Long pageSize; - public AssetVersionReader( - final String pathServiceSid, - final String pathAssetSid - ) { - this.pathServiceSid = pathServiceSid; - this.pathAssetSid = pathAssetSid; + public AssetVersionReader(final String pathserviceSid, final String pathassetSid) { + this.pathserviceSid = pathserviceSid; + this.pathassetSid = pathassetSid; } + public AssetVersionReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/Services/{ServiceSid}/Assets/{AssetSid}/Versions"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = - path.replace("{" + "AssetSid" + "}", this.pathAssetSid.toString()); + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "AssetSid" + "}", this.pathassetSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.SERVERLESS.toString(), - path + HttpMethod.GET, + Domains.SERVERLESS.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "AssetVersion read failed: Unable to connect to server" - ); + throw new ApiConnectionException("AssetVersion read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "asset_versions", - response.getContent(), - AssetVersion.class, - client.getObjectMapper() - ); + "asset_versions", + response.getContent(), + AssetVersion.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.SERVERLESS.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.SERVERLESS.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/serverless/v1/service/build/BuildStatus.java b/src/main/java/com/twilio/rest/serverless/v1/service/build/BuildStatus.java index f00e9175cb..5b075542e0 100644 --- a/src/main/java/com/twilio/rest/serverless/v1/service/build/BuildStatus.java +++ b/src/main/java/com/twilio/rest/serverless/v1/service/build/BuildStatus.java @@ -18,43 +18,63 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class BuildStatus extends Resource { - private static final long serialVersionUID = 256582650740181L; - public static BuildStatusFetcher fetcher( - final String pathServiceSid, - final String pathSid - ) { - return new BuildStatusFetcher(pathServiceSid, pathSid); + public static BuildStatusFetcher fetcher(final String pathserviceSid, final String pathsid) { + return new BuildStatusFetcher( + pathserviceSid, pathsid + ); + } + + + public enum Status { + BUILDING("building"), + COMPLETED("completed"), + FAILED("failed"); + + private final String value; + + private Status(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static Status forValue(final String value) { + return Promoter.enumFromString(value, Status.values()); + } } + /** * Converts a JSON String into a BuildStatus object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return BuildStatus object represented by the provided JSON */ - public static BuildStatus fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static BuildStatus fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, BuildStatus.class); @@ -69,14 +89,11 @@ public static BuildStatus fromJson( * Converts a JSON InputStream into a BuildStatus object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return BuildStatus object represented by the provided JSON */ - public static BuildStatus fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static BuildStatus fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, BuildStatus.class); @@ -87,47 +104,45 @@ public static BuildStatus fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; + @Getter private final String serviceSid; + @Getter + private final String sid; + @Getter private final BuildStatus.Status status; + @Getter private final URI url; @JsonCreator private BuildStatus( - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("service_sid") final String serviceSid, - @JsonProperty("status") final BuildStatus.Status status, - @JsonProperty("url") final URI url + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("service_sid") final String serviceSid, + @JsonProperty("sid") final String sid, + @JsonProperty("status") final BuildStatus.Status status, + @JsonProperty("url") final URI url ) { - this.sid = sid; this.accountSid = accountSid; this.serviceSid = serviceSid; + this.sid = sid; this.status = status; this.url = url; } - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getServiceSid() { - return this.serviceSid; - } - - public final BuildStatus.Status getStatus() { - return this.status; - } - - public final URI getUrl() { - return this.url; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -139,39 +154,26 @@ public boolean equals(final Object o) { } BuildStatus other = (BuildStatus) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(serviceSid, other.serviceSid) && - Objects.equals(status, other.status) && - Objects.equals(url, other.url) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(serviceSid, other.serviceSid) && + Objects.equals(sid, other.sid) && + Objects.equals(status, other.status) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { - return Objects.hash(sid, accountSid, serviceSid, status, url); + return Objects.hash( + accountSid, + serviceSid, + sid, + status, + url + ); } - public enum Status { - BUILDING("building"), - COMPLETED("completed"), - FAILED("failed"); - - private final String value; - - private Status(final String value) { - this.value = value; - } - public String toString() { - return value; - } - - @JsonCreator - public static Status forValue(final String value) { - return Promoter.enumFromString(value, Status.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/serverless/v1/service/build/BuildStatusFetcher.java b/src/main/java/com/twilio/rest/serverless/v1/service/build/BuildStatusFetcher.java index 5d6ef0cac2..23c7a363c4 100644 --- a/src/main/java/com/twilio/rest/serverless/v1/service/build/BuildStatusFetcher.java +++ b/src/main/java/com/twilio/rest/serverless/v1/service/build/BuildStatusFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.serverless.v1.service.build; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,57 +26,44 @@ public class BuildStatusFetcher extends Fetcher { - private String pathServiceSid; - private String pathSid; + private String pathserviceSid; + private String pathsid; - public BuildStatusFetcher( - final String pathServiceSid, - final String pathSid - ) { - this.pathServiceSid = pathServiceSid; - this.pathSid = pathSid; + public BuildStatusFetcher(final String pathserviceSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathsid = pathsid; } + @Override public BuildStatus fetch(final TwilioRestClient client) { + String path = "/v1/Services/{ServiceSid}/Builds/{Sid}/Status"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.SERVERLESS.toString(), - path + HttpMethod.GET, + Domains.SERVERLESS.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "BuildStatus fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("BuildStatus fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return BuildStatus.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return BuildStatus.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/serverless/v1/service/environment/Deployment.java b/src/main/java/com/twilio/rest/serverless/v1/service/environment/Deployment.java index d65cc5bbf8..197c9ac9f6 100644 --- a/src/main/java/com/twilio/rest/serverless/v1/service/environment/Deployment.java +++ b/src/main/java/com/twilio/rest/serverless/v1/service/environment/Deployment.java @@ -18,63 +18,56 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Deployment extends Resource { - private static final long serialVersionUID = 53350837896565L; - public static DeploymentCreator creator( - final String pathServiceSid, - final String pathEnvironmentSid - ) { - return new DeploymentCreator(pathServiceSid, pathEnvironmentSid); + public static DeploymentCreator creator(final String pathserviceSid, final String pathenvironmentSid) { + return new DeploymentCreator( + pathserviceSid, pathenvironmentSid + ); } - public static DeploymentFetcher fetcher( - final String pathServiceSid, - final String pathEnvironmentSid, - final String pathSid - ) { + + public static DeploymentFetcher fetcher(final String pathserviceSid, final String pathenvironmentSid, final String pathsid) { return new DeploymentFetcher( - pathServiceSid, - pathEnvironmentSid, - pathSid + pathserviceSid, pathenvironmentSid, pathsid ); } - public static DeploymentReader reader( - final String pathServiceSid, - final String pathEnvironmentSid - ) { - return new DeploymentReader(pathServiceSid, pathEnvironmentSid); + + public static DeploymentReader reader(final String pathserviceSid, final String pathenvironmentSid) { + return new DeploymentReader( + pathserviceSid, pathenvironmentSid + ); } + /** * Converts a JSON String into a Deployment object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Deployment object represented by the provided JSON */ - public static Deployment fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Deployment fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Deployment.class); @@ -89,14 +82,11 @@ public static Deployment fromJson( * Converts a JSON InputStream into a Deployment object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Deployment object represented by the provided JSON */ - public static Deployment fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Deployment fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Deployment.class); @@ -107,68 +97,59 @@ public static Deployment fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String serviceSid; - private final String environmentSid; + @Getter private final String buildSid; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; + @Getter + private final String environmentSid; + @Getter + private final String serviceSid; + @Getter + private final String sid; + @Getter private final URI url; @JsonCreator private Deployment( - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("service_sid") final String serviceSid, - @JsonProperty("environment_sid") final String environmentSid, - @JsonProperty("build_sid") final String buildSid, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("url") final URI url + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("build_sid") final String buildSid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("environment_sid") final String environmentSid, + @JsonProperty("service_sid") final String serviceSid, + @JsonProperty("sid") final String sid, + @JsonProperty("url") final URI url ) { - this.sid = sid; this.accountSid = accountSid; - this.serviceSid = serviceSid; - this.environmentSid = environmentSid; this.buildSid = buildSid; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; + this.environmentSid = environmentSid; + this.serviceSid = serviceSid; + this.sid = sid; this.url = url; } - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getServiceSid() { - return this.serviceSid; - } - - public final String getEnvironmentSid() { - return this.environmentSid; - } - - public final String getBuildSid() { - return this.buildSid; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final URI getUrl() { - return this.url; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -180,30 +161,32 @@ public boolean equals(final Object o) { } Deployment other = (Deployment) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(serviceSid, other.serviceSid) && - Objects.equals(environmentSid, other.environmentSid) && - Objects.equals(buildSid, other.buildSid) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(url, other.url) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(buildSid, other.buildSid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(environmentSid, other.environmentSid) && + Objects.equals(serviceSid, other.serviceSid) && + Objects.equals(sid, other.sid) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - sid, - accountSid, - serviceSid, - environmentSid, - buildSid, - dateCreated, - dateUpdated, - url + accountSid, + buildSid, + dateCreated, + dateUpdated, + environmentSid, + serviceSid, + sid, + url ); } + + } + diff --git a/src/main/java/com/twilio/rest/serverless/v1/service/environment/DeploymentCreator.java b/src/main/java/com/twilio/rest/serverless/v1/service/environment/DeploymentCreator.java index cf96fdb3aa..4ec7fbcac0 100644 --- a/src/main/java/com/twilio/rest/serverless/v1/service/environment/DeploymentCreator.java +++ b/src/main/java/com/twilio/rest/serverless/v1/service/environment/DeploymentCreator.java @@ -14,8 +14,11 @@ package com.twilio.rest.serverless.v1.service.environment; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,83 +30,75 @@ public class DeploymentCreator extends Creator { - private String pathServiceSid; - private String pathEnvironmentSid; + private String pathserviceSid; + private String pathenvironmentSid; private String buildSid; private Boolean isPlugin; - public DeploymentCreator( - final String pathServiceSid, - final String pathEnvironmentSid - ) { - this.pathServiceSid = pathServiceSid; - this.pathEnvironmentSid = pathEnvironmentSid; + public DeploymentCreator(final String pathserviceSid, final String pathenvironmentSid) { + this.pathserviceSid = pathserviceSid; + this.pathenvironmentSid = pathenvironmentSid; } + public DeploymentCreator setBuildSid(final String buildSid) { this.buildSid = buildSid; return this; } + public DeploymentCreator setIsPlugin(final Boolean isPlugin) { this.isPlugin = isPlugin; return this; } + @Override public Deployment create(final TwilioRestClient client) { - String path = - "/v1/Services/{ServiceSid}/Environments/{EnvironmentSid}/Deployments"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = - path.replace( - "{" + "EnvironmentSid" + "}", - this.pathEnvironmentSid.toString() - ); + String path = "/v1/Services/{ServiceSid}/Environments/{EnvironmentSid}/Deployments"; + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "EnvironmentSid" + "}", this.pathenvironmentSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.SERVERLESS.toString(), - path + HttpMethod.POST, + Domains.SERVERLESS.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Deployment creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("Deployment creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Deployment.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Deployment.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (buildSid != null) { - request.addPostParam("BuildSid", buildSid); + Serializer.toString(request, "BuildSid", buildSid, ParameterType.URLENCODED); } + + if (isPlugin != null) { - request.addPostParam("IsPlugin", isPlugin.toString()); + Serializer.toString(request, "IsPlugin", isPlugin, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/serverless/v1/service/environment/DeploymentFetcher.java b/src/main/java/com/twilio/rest/serverless/v1/service/environment/DeploymentFetcher.java index 6a8b5d05fd..4d9f2925ff 100644 --- a/src/main/java/com/twilio/rest/serverless/v1/service/environment/DeploymentFetcher.java +++ b/src/main/java/com/twilio/rest/serverless/v1/service/environment/DeploymentFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.serverless.v1.service.environment; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,66 +26,47 @@ public class DeploymentFetcher extends Fetcher { - private String pathServiceSid; - private String pathEnvironmentSid; - private String pathSid; + private String pathserviceSid; + private String pathenvironmentSid; + private String pathsid; - public DeploymentFetcher( - final String pathServiceSid, - final String pathEnvironmentSid, - final String pathSid - ) { - this.pathServiceSid = pathServiceSid; - this.pathEnvironmentSid = pathEnvironmentSid; - this.pathSid = pathSid; + public DeploymentFetcher(final String pathserviceSid, final String pathenvironmentSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathenvironmentSid = pathenvironmentSid; + this.pathsid = pathsid; } + @Override public Deployment fetch(final TwilioRestClient client) { - String path = - "/v1/Services/{ServiceSid}/Environments/{EnvironmentSid}/Deployments/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = - path.replace( - "{" + "EnvironmentSid" + "}", - this.pathEnvironmentSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/v1/Services/{ServiceSid}/Environments/{EnvironmentSid}/Deployments/{Sid}"; + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "EnvironmentSid" + "}", this.pathenvironmentSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.SERVERLESS.toString(), - path + HttpMethod.GET, + Domains.SERVERLESS.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Deployment fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Deployment fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return Deployment.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Deployment.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/serverless/v1/service/environment/DeploymentReader.java b/src/main/java/com/twilio/rest/serverless/v1/service/environment/DeploymentReader.java index d8d27c7046..8c19e7025e 100644 --- a/src/main/java/com/twilio/rest/serverless/v1/service/environment/DeploymentReader.java +++ b/src/main/java/com/twilio/rest/serverless/v1/service/environment/DeploymentReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,126 +30,91 @@ public class DeploymentReader extends Reader { - private String pathServiceSid; - private String pathEnvironmentSid; + private String pathserviceSid; + private String pathenvironmentSid; private Long pageSize; - public DeploymentReader( - final String pathServiceSid, - final String pathEnvironmentSid - ) { - this.pathServiceSid = pathServiceSid; - this.pathEnvironmentSid = pathEnvironmentSid; + public DeploymentReader(final String pathserviceSid, final String pathenvironmentSid) { + this.pathserviceSid = pathserviceSid; + this.pathenvironmentSid = pathenvironmentSid; } + public DeploymentReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { - String path = - "/v1/Services/{ServiceSid}/Environments/{EnvironmentSid}/Deployments"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = - path.replace( - "{" + "EnvironmentSid" + "}", - this.pathEnvironmentSid.toString() - ); + + String path = "/v1/Services/{ServiceSid}/Environments/{EnvironmentSid}/Deployments"; + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "EnvironmentSid" + "}", this.pathenvironmentSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.SERVERLESS.toString(), - path + HttpMethod.GET, + Domains.SERVERLESS.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Deployment read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Deployment read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "deployments", - response.getContent(), - Deployment.class, - client.getObjectMapper() - ); + "deployments", + response.getContent(), + Deployment.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.SERVERLESS.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.SERVERLESS.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/serverless/v1/service/environment/Log.java b/src/main/java/com/twilio/rest/serverless/v1/service/environment/Log.java index 72abb9f912..276c2e8fe6 100644 --- a/src/main/java/com/twilio/rest/serverless/v1/service/environment/Log.java +++ b/src/main/java/com/twilio/rest/serverless/v1/service/environment/Log.java @@ -18,52 +18,49 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Log extends Resource { - private static final long serialVersionUID = 41290346867159L; - public static LogFetcher fetcher( - final String pathServiceSid, - final String pathEnvironmentSid, - final String pathSid - ) { - return new LogFetcher(pathServiceSid, pathEnvironmentSid, pathSid); + public static LogFetcher fetcher(final String pathserviceSid, final String pathenvironmentSid, final String pathsid) { + return new LogFetcher( + pathserviceSid, pathenvironmentSid, pathsid + ); } - public static LogReader reader( - final String pathServiceSid, - final String pathEnvironmentSid - ) { - return new LogReader(pathServiceSid, pathEnvironmentSid); + + public static LogReader reader(final String pathserviceSid, final String pathenvironmentSid) { + return new LogReader( + pathserviceSid, pathenvironmentSid + ); } + /** * Converts a JSON String into a Log object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Log object represented by the provided JSON */ - public static Log fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Log fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Log.class); @@ -78,14 +75,11 @@ public static Log fromJson( * Converts a JSON InputStream into a Log object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Log object represented by the provided JSON */ - public static Log fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Log fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Log.class); @@ -96,96 +90,74 @@ public static Log fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String serviceSid; - private final String environmentSid; + @Getter private final String buildSid; + @Getter + private final ZonedDateTime dateCreated; + @Getter private final String deploymentSid; + @Getter + private final String environmentSid; + @Getter private final String functionSid; - private final String requestSid; + @Getter private final String level; + @Getter private final String message; - private final ZonedDateTime dateCreated; + @Getter + private final String requestSid; + @Getter + private final String serviceSid; + @Getter + private final String sid; + @Getter private final URI url; @JsonCreator private Log( - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("service_sid") final String serviceSid, - @JsonProperty("environment_sid") final String environmentSid, - @JsonProperty("build_sid") final String buildSid, - @JsonProperty("deployment_sid") final String deploymentSid, - @JsonProperty("function_sid") final String functionSid, - @JsonProperty("request_sid") final String requestSid, - @JsonProperty("level") final String level, - @JsonProperty("message") final String message, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("url") final URI url + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("build_sid") final String buildSid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("deployment_sid") final String deploymentSid, + @JsonProperty("environment_sid") final String environmentSid, + @JsonProperty("function_sid") final String functionSid, + @JsonProperty("level") final String level, + @JsonProperty("message") final String message, + @JsonProperty("request_sid") final String requestSid, + @JsonProperty("service_sid") final String serviceSid, + @JsonProperty("sid") final String sid, + @JsonProperty("url") final URI url ) { - this.sid = sid; this.accountSid = accountSid; - this.serviceSid = serviceSid; - this.environmentSid = environmentSid; this.buildSid = buildSid; + this.dateCreated = dateCreated; this.deploymentSid = deploymentSid; + this.environmentSid = environmentSid; this.functionSid = functionSid; - this.requestSid = requestSid; this.level = level; this.message = message; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); + this.requestSid = requestSid; + this.serviceSid = serviceSid; + this.sid = sid; this.url = url; } - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getServiceSid() { - return this.serviceSid; - } - - public final String getEnvironmentSid() { - return this.environmentSid; - } - - public final String getBuildSid() { - return this.buildSid; - } - - public final String getDeploymentSid() { - return this.deploymentSid; - } - - public final String getFunctionSid() { - return this.functionSid; - } - - public final String getRequestSid() { - return this.requestSid; - } - - public final String getLevel() { - return this.level; - } - - public final String getMessage() { - return this.message; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final URI getUrl() { - return this.url; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -197,38 +169,40 @@ public boolean equals(final Object o) { } Log other = (Log) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(serviceSid, other.serviceSid) && - Objects.equals(environmentSid, other.environmentSid) && - Objects.equals(buildSid, other.buildSid) && - Objects.equals(deploymentSid, other.deploymentSid) && - Objects.equals(functionSid, other.functionSid) && - Objects.equals(requestSid, other.requestSid) && - Objects.equals(level, other.level) && - Objects.equals(message, other.message) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(url, other.url) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(buildSid, other.buildSid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(deploymentSid, other.deploymentSid) && + Objects.equals(environmentSid, other.environmentSid) && + Objects.equals(functionSid, other.functionSid) && + Objects.equals(level, other.level) && + Objects.equals(message, other.message) && + Objects.equals(requestSid, other.requestSid) && + Objects.equals(serviceSid, other.serviceSid) && + Objects.equals(sid, other.sid) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - sid, - accountSid, - serviceSid, - environmentSid, - buildSid, - deploymentSid, - functionSid, - requestSid, - level, - message, - dateCreated, - url + accountSid, + buildSid, + dateCreated, + deploymentSid, + environmentSid, + functionSid, + level, + message, + requestSid, + serviceSid, + sid, + url ); } + + } + diff --git a/src/main/java/com/twilio/rest/serverless/v1/service/environment/LogFetcher.java b/src/main/java/com/twilio/rest/serverless/v1/service/environment/LogFetcher.java index abf9a590c4..971a4866b4 100644 --- a/src/main/java/com/twilio/rest/serverless/v1/service/environment/LogFetcher.java +++ b/src/main/java/com/twilio/rest/serverless/v1/service/environment/LogFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.serverless.v1.service.environment; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,63 +26,47 @@ public class LogFetcher extends Fetcher { - private String pathServiceSid; - private String pathEnvironmentSid; - private String pathSid; + private String pathserviceSid; + private String pathenvironmentSid; + private String pathsid; - public LogFetcher( - final String pathServiceSid, - final String pathEnvironmentSid, - final String pathSid - ) { - this.pathServiceSid = pathServiceSid; - this.pathEnvironmentSid = pathEnvironmentSid; - this.pathSid = pathSid; + public LogFetcher(final String pathserviceSid, final String pathenvironmentSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathenvironmentSid = pathenvironmentSid; + this.pathsid = pathsid; } + @Override public Log fetch(final TwilioRestClient client) { - String path = - "/v1/Services/{ServiceSid}/Environments/{EnvironmentSid}/Logs/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = - path.replace( - "{" + "EnvironmentSid" + "}", - this.pathEnvironmentSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/v1/Services/{ServiceSid}/Environments/{EnvironmentSid}/Logs/{Sid}"; + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "EnvironmentSid" + "}", this.pathenvironmentSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.SERVERLESS.toString(), - path + HttpMethod.GET, + Domains.SERVERLESS.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Log fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Log fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Log.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/serverless/v1/service/environment/LogReader.java b/src/main/java/com/twilio/rest/serverless/v1/service/environment/LogReader.java index bd891a7864..317b96017d 100644 --- a/src/main/java/com/twilio/rest/serverless/v1/service/environment/LogReader.java +++ b/src/main/java/com/twilio/rest/serverless/v1/service/environment/LogReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -26,162 +27,132 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.time.ZonedDateTime; public class LogReader extends Reader { - private String pathServiceSid; - private String pathEnvironmentSid; + private String pathserviceSid; + private String pathenvironmentSid; private String functionSid; private ZonedDateTime startDate; private ZonedDateTime endDate; private Long pageSize; - public LogReader( - final String pathServiceSid, - final String pathEnvironmentSid - ) { - this.pathServiceSid = pathServiceSid; - this.pathEnvironmentSid = pathEnvironmentSid; + public LogReader(final String pathserviceSid, final String pathenvironmentSid) { + this.pathserviceSid = pathserviceSid; + this.pathenvironmentSid = pathenvironmentSid; } + public LogReader setFunctionSid(final String functionSid) { this.functionSid = functionSid; return this; } + public LogReader setStartDate(final ZonedDateTime startDate) { this.startDate = startDate; return this; } + public LogReader setEndDate(final ZonedDateTime endDate) { this.endDate = endDate; return this; } + public LogReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { - String path = - "/v1/Services/{ServiceSid}/Environments/{EnvironmentSid}/Logs"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = - path.replace( - "{" + "EnvironmentSid" + "}", - this.pathEnvironmentSid.toString() - ); + + String path = "/v1/Services/{ServiceSid}/Environments/{EnvironmentSid}/Logs"; + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "EnvironmentSid" + "}", this.pathenvironmentSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.SERVERLESS.toString(), - path + HttpMethod.GET, + Domains.SERVERLESS.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Log read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Log read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "logs", - response.getContent(), - Log.class, - client.getObjectMapper() - ); + "logs", + response.getContent(), + Log.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.SERVERLESS.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.SERVERLESS.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (functionSid != null) { - request.addQueryParam("FunctionSid", functionSid); + Serializer.toString(request, "FunctionSid", functionSid, ParameterType.QUERY); } + + if (startDate != null) { - request.addQueryParam( - "StartDate", - startDate.toInstant().toString() - ); + Serializer.toString(request, "StartDate", startDate, ParameterType.QUERY); } + if (endDate != null) { - request.addQueryParam("EndDate", endDate.toInstant().toString()); + Serializer.toString(request, "EndDate", endDate, ParameterType.QUERY); } + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/serverless/v1/service/environment/Variable.java b/src/main/java/com/twilio/rest/serverless/v1/service/environment/Variable.java index 2c5f45dec3..a08f3221e5 100644 --- a/src/main/java/com/twilio/rest/serverless/v1/service/environment/Variable.java +++ b/src/main/java/com/twilio/rest/serverless/v1/service/environment/Variable.java @@ -18,82 +18,70 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Variable extends Resource { - private static final long serialVersionUID = 240706939520174L; - public static VariableCreator creator( - final String pathServiceSid, - final String pathEnvironmentSid, - final String key, - final String value - ) { + public static VariableCreator creator(final String pathserviceSid, final String pathenvironmentSid, final String key, final String value) { return new VariableCreator( - pathServiceSid, - pathEnvironmentSid, - key, - value + pathserviceSid, pathenvironmentSid, key, value ); } - public static VariableDeleter deleter( - final String pathServiceSid, - final String pathEnvironmentSid, - final String pathSid - ) { - return new VariableDeleter(pathServiceSid, pathEnvironmentSid, pathSid); + + public static VariableDeleter deleter(final String pathserviceSid, final String pathenvironmentSid, final String pathsid) { + return new VariableDeleter( + pathserviceSid, pathenvironmentSid, pathsid + ); } - public static VariableFetcher fetcher( - final String pathServiceSid, - final String pathEnvironmentSid, - final String pathSid - ) { - return new VariableFetcher(pathServiceSid, pathEnvironmentSid, pathSid); + + public static VariableFetcher fetcher(final String pathserviceSid, final String pathenvironmentSid, final String pathsid) { + return new VariableFetcher( + pathserviceSid, pathenvironmentSid, pathsid + ); } - public static VariableReader reader( - final String pathServiceSid, - final String pathEnvironmentSid - ) { - return new VariableReader(pathServiceSid, pathEnvironmentSid); + + public static VariableReader reader(final String pathserviceSid, final String pathenvironmentSid) { + return new VariableReader( + pathserviceSid, pathenvironmentSid + ); } - public static VariableUpdater updater( - final String pathServiceSid, - final String pathEnvironmentSid, - final String pathSid - ) { - return new VariableUpdater(pathServiceSid, pathEnvironmentSid, pathSid); + + public static VariableUpdater updater(final String pathserviceSid, final String pathenvironmentSid, final String pathsid) { + return new VariableUpdater( + pathserviceSid, pathenvironmentSid, pathsid + ); } + /** * Converts a JSON String into a Variable object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Variable object represented by the provided JSON */ - public static Variable fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Variable fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Variable.class); @@ -108,14 +96,11 @@ public static Variable fromJson( * Converts a JSON InputStream into a Variable object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Variable object represented by the provided JSON */ - public static Variable fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Variable fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Variable.class); @@ -126,73 +111,61 @@ public static Variable fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String serviceSid; - private final String environmentSid; - private final String key; - private final String value; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; + @Getter + private final String environmentSid; + @Getter + private final String key; + @Getter + private final String serviceSid; + @Getter + private final String sid; + @Getter private final URI url; + @Getter + private final String value; @JsonCreator private Variable( - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("service_sid") final String serviceSid, - @JsonProperty("environment_sid") final String environmentSid, - @JsonProperty("key") final String key, - @JsonProperty("value") final String value, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("url") final URI url + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("environment_sid") final String environmentSid, + @JsonProperty("key") final String key, + @JsonProperty("service_sid") final String serviceSid, + @JsonProperty("sid") final String sid, + @JsonProperty("url") final URI url, + @JsonProperty("value") final String value ) { - this.sid = sid; this.accountSid = accountSid; - this.serviceSid = serviceSid; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.environmentSid = environmentSid; this.key = key; - this.value = value; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); + this.serviceSid = serviceSid; + this.sid = sid; this.url = url; - } - - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getServiceSid() { - return this.serviceSid; - } - - public final String getEnvironmentSid() { - return this.environmentSid; - } - - public final String getKey() { - return this.key; - } - - public final String getValue() { - return this.value; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final URI getUrl() { - return this.url; + this.value = value; } @Override @@ -206,32 +179,34 @@ public boolean equals(final Object o) { } Variable other = (Variable) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(serviceSid, other.serviceSid) && - Objects.equals(environmentSid, other.environmentSid) && - Objects.equals(key, other.key) && - Objects.equals(value, other.value) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(url, other.url) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(environmentSid, other.environmentSid) && + Objects.equals(key, other.key) && + Objects.equals(serviceSid, other.serviceSid) && + Objects.equals(sid, other.sid) && + Objects.equals(url, other.url) && + Objects.equals(value, other.value) ); } @Override public int hashCode() { return Objects.hash( - sid, - accountSid, - serviceSid, - environmentSid, - key, - value, - dateCreated, - dateUpdated, - url + accountSid, + dateCreated, + dateUpdated, + environmentSid, + key, + serviceSid, + sid, + url, + value ); } + + } + diff --git a/src/main/java/com/twilio/rest/serverless/v1/service/environment/VariableCreator.java b/src/main/java/com/twilio/rest/serverless/v1/service/environment/VariableCreator.java index 647249ec6a..2d9482865c 100644 --- a/src/main/java/com/twilio/rest/serverless/v1/service/environment/VariableCreator.java +++ b/src/main/java/com/twilio/rest/serverless/v1/service/environment/VariableCreator.java @@ -14,8 +14,11 @@ package com.twilio.rest.serverless.v1.service.environment; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,89 +30,77 @@ public class VariableCreator extends Creator { - private String pathServiceSid; - private String pathEnvironmentSid; + private String pathserviceSid; + private String pathenvironmentSid; private String key; private String value; - public VariableCreator( - final String pathServiceSid, - final String pathEnvironmentSid, - final String key, - final String value - ) { - this.pathServiceSid = pathServiceSid; - this.pathEnvironmentSid = pathEnvironmentSid; + public VariableCreator(final String pathserviceSid, final String pathenvironmentSid, final String key, final String value) { + this.pathserviceSid = pathserviceSid; + this.pathenvironmentSid = pathenvironmentSid; this.key = key; this.value = value; } + public VariableCreator setKey(final String key) { this.key = key; return this; } + public VariableCreator setValue(final String value) { this.value = value; return this; } + @Override public Variable create(final TwilioRestClient client) { - String path = - "/v1/Services/{ServiceSid}/Environments/{EnvironmentSid}/Variables"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = - path.replace( - "{" + "EnvironmentSid" + "}", - this.pathEnvironmentSid.toString() - ); - path = path.replace("{" + "Key" + "}", this.key.toString()); - path = path.replace("{" + "Value" + "}", this.value.toString()); + String path = "/v1/Services/{ServiceSid}/Environments/{EnvironmentSid}/Variables"; + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "EnvironmentSid" + "}", this.pathenvironmentSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.SERVERLESS.toString(), - path + HttpMethod.POST, + Domains.SERVERLESS.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Variable creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("Variable creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Variable.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Variable.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (key != null) { - request.addPostParam("Key", key); + Serializer.toString(request, "Key", key, ParameterType.URLENCODED); } + + if (value != null) { - request.addPostParam("Value", value); + Serializer.toString(request, "Value", value, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/serverless/v1/service/environment/VariableDeleter.java b/src/main/java/com/twilio/rest/serverless/v1/service/environment/VariableDeleter.java index ccfcc57349..ff28d01b31 100644 --- a/src/main/java/com/twilio/rest/serverless/v1/service/environment/VariableDeleter.java +++ b/src/main/java/com/twilio/rest/serverless/v1/service/environment/VariableDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.serverless.v1.service.environment; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,59 +26,44 @@ public class VariableDeleter extends Deleter { - private String pathServiceSid; - private String pathEnvironmentSid; - private String pathSid; + private String pathserviceSid; + private String pathenvironmentSid; + private String pathsid; - public VariableDeleter( - final String pathServiceSid, - final String pathEnvironmentSid, - final String pathSid - ) { - this.pathServiceSid = pathServiceSid; - this.pathEnvironmentSid = pathEnvironmentSid; - this.pathSid = pathSid; + public VariableDeleter(final String pathserviceSid, final String pathenvironmentSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathenvironmentSid = pathenvironmentSid; + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { - String path = - "/v1/Services/{ServiceSid}/Environments/{EnvironmentSid}/Variables/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = - path.replace( - "{" + "EnvironmentSid" + "}", - this.pathEnvironmentSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/v1/Services/{ServiceSid}/Environments/{EnvironmentSid}/Variables/{Sid}"; + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "EnvironmentSid" + "}", this.pathenvironmentSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.SERVERLESS.toString(), - path + HttpMethod.DELETE, + Domains.SERVERLESS.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Variable delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("Variable delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/serverless/v1/service/environment/VariableFetcher.java b/src/main/java/com/twilio/rest/serverless/v1/service/environment/VariableFetcher.java index 6181f1bad9..7886574ee4 100644 --- a/src/main/java/com/twilio/rest/serverless/v1/service/environment/VariableFetcher.java +++ b/src/main/java/com/twilio/rest/serverless/v1/service/environment/VariableFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.serverless.v1.service.environment; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,66 +26,47 @@ public class VariableFetcher extends Fetcher { - private String pathServiceSid; - private String pathEnvironmentSid; - private String pathSid; + private String pathserviceSid; + private String pathenvironmentSid; + private String pathsid; - public VariableFetcher( - final String pathServiceSid, - final String pathEnvironmentSid, - final String pathSid - ) { - this.pathServiceSid = pathServiceSid; - this.pathEnvironmentSid = pathEnvironmentSid; - this.pathSid = pathSid; + public VariableFetcher(final String pathserviceSid, final String pathenvironmentSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathenvironmentSid = pathenvironmentSid; + this.pathsid = pathsid; } + @Override public Variable fetch(final TwilioRestClient client) { - String path = - "/v1/Services/{ServiceSid}/Environments/{EnvironmentSid}/Variables/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = - path.replace( - "{" + "EnvironmentSid" + "}", - this.pathEnvironmentSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/v1/Services/{ServiceSid}/Environments/{EnvironmentSid}/Variables/{Sid}"; + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "EnvironmentSid" + "}", this.pathenvironmentSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.SERVERLESS.toString(), - path + HttpMethod.GET, + Domains.SERVERLESS.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Variable fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Variable fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return Variable.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Variable.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/serverless/v1/service/environment/VariableReader.java b/src/main/java/com/twilio/rest/serverless/v1/service/environment/VariableReader.java index 5af0a36532..e2924fdcf0 100644 --- a/src/main/java/com/twilio/rest/serverless/v1/service/environment/VariableReader.java +++ b/src/main/java/com/twilio/rest/serverless/v1/service/environment/VariableReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,126 +30,91 @@ public class VariableReader extends Reader { - private String pathServiceSid; - private String pathEnvironmentSid; + private String pathserviceSid; + private String pathenvironmentSid; private Long pageSize; - public VariableReader( - final String pathServiceSid, - final String pathEnvironmentSid - ) { - this.pathServiceSid = pathServiceSid; - this.pathEnvironmentSid = pathEnvironmentSid; + public VariableReader(final String pathserviceSid, final String pathenvironmentSid) { + this.pathserviceSid = pathserviceSid; + this.pathenvironmentSid = pathenvironmentSid; } + public VariableReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { - String path = - "/v1/Services/{ServiceSid}/Environments/{EnvironmentSid}/Variables"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = - path.replace( - "{" + "EnvironmentSid" + "}", - this.pathEnvironmentSid.toString() - ); + + String path = "/v1/Services/{ServiceSid}/Environments/{EnvironmentSid}/Variables"; + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "EnvironmentSid" + "}", this.pathenvironmentSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.SERVERLESS.toString(), - path + HttpMethod.GET, + Domains.SERVERLESS.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Variable read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Variable read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "variables", - response.getContent(), - Variable.class, - client.getObjectMapper() - ); + "variables", + response.getContent(), + Variable.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.SERVERLESS.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.SERVERLESS.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/serverless/v1/service/environment/VariableUpdater.java b/src/main/java/com/twilio/rest/serverless/v1/service/environment/VariableUpdater.java index 20885bebfe..acbe9ec6dd 100644 --- a/src/main/java/com/twilio/rest/serverless/v1/service/environment/VariableUpdater.java +++ b/src/main/java/com/twilio/rest/serverless/v1/service/environment/VariableUpdater.java @@ -16,6 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -26,88 +28,78 @@ import com.twilio.rest.Domains; public class VariableUpdater extends Updater { - - private String pathServiceSid; - private String pathEnvironmentSid; - private String pathSid; + private String pathserviceSid; + private String pathenvironmentSid; + private String pathsid; private String key; private String value; - public VariableUpdater( - final String pathServiceSid, - final String pathEnvironmentSid, - final String pathSid - ) { - this.pathServiceSid = pathServiceSid; - this.pathEnvironmentSid = pathEnvironmentSid; - this.pathSid = pathSid; + public VariableUpdater(final String pathserviceSid, final String pathenvironmentSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathenvironmentSid = pathenvironmentSid; + this.pathsid = pathsid; } + public VariableUpdater setKey(final String key) { this.key = key; return this; } + public VariableUpdater setValue(final String value) { this.value = value; return this; } + @Override public Variable update(final TwilioRestClient client) { - String path = - "/v1/Services/{ServiceSid}/Environments/{EnvironmentSid}/Variables/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = - path.replace( - "{" + "EnvironmentSid" + "}", - this.pathEnvironmentSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/v1/Services/{ServiceSid}/Environments/{EnvironmentSid}/Variables/{Sid}"; + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "EnvironmentSid" + "}", this.pathenvironmentSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.SERVERLESS.toString(), - path + HttpMethod.POST, + Domains.SERVERLESS.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Variable update failed: Unable to connect to server" - ); + throw new ApiConnectionException("Variable update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Variable.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Variable.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (key != null) { - request.addPostParam("Key", key); + Serializer.toString(request, "Key", key, ParameterType.URLENCODED); } + + if (value != null) { - request.addPostParam("Value", value); + Serializer.toString(request, "Value", value, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/serverless/v1/service/function/FunctionVersion.java b/src/main/java/com/twilio/rest/serverless/v1/service/function/FunctionVersion.java index af9004b2c4..bd40e1829c 100644 --- a/src/main/java/com/twilio/rest/serverless/v1/service/function/FunctionVersion.java +++ b/src/main/java/com/twilio/rest/serverless/v1/service/function/FunctionVersion.java @@ -18,59 +18,73 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class FunctionVersion extends Resource { - private static final long serialVersionUID = 85534066966494L; - public static FunctionVersionFetcher fetcher( - final String pathServiceSid, - final String pathFunctionSid, - final String pathSid - ) { + public static FunctionVersionFetcher fetcher(final String pathserviceSid, final String pathfunctionSid, final String pathsid) { return new FunctionVersionFetcher( - pathServiceSid, - pathFunctionSid, - pathSid + pathserviceSid, pathfunctionSid, pathsid ); } - public static FunctionVersionReader reader( - final String pathServiceSid, - final String pathFunctionSid - ) { - return new FunctionVersionReader(pathServiceSid, pathFunctionSid); + + public static FunctionVersionReader reader(final String pathserviceSid, final String pathfunctionSid) { + return new FunctionVersionReader( + pathserviceSid, pathfunctionSid + ); + } + + + public enum Visibility { + PUBLIC("public"), + PRIVATE("private"), + PROTECTED("protected"); + + private final String value; + + private Visibility(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static Visibility forValue(final String value) { + return Promoter.enumFromString(value, Visibility.values()); + } } + /** * Converts a JSON String into a FunctionVersion object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return FunctionVersion object represented by the provided JSON */ - public static FunctionVersion fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static FunctionVersion fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, FunctionVersion.class); @@ -85,14 +99,11 @@ public static FunctionVersion fromJson( * Converts a JSON InputStream into a FunctionVersion object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return FunctionVersion object represented by the provided JSON */ - public static FunctionVersion fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static FunctionVersion fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, FunctionVersion.class); @@ -103,73 +114,60 @@ public static FunctionVersion fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String serviceSid; + @Getter + private final ZonedDateTime dateCreated; + @Getter private final String functionSid; + @Getter + private final Map links; + @Getter private final String path; - private final FunctionVersion.Visibility visibility; - private final ZonedDateTime dateCreated; + @Getter + private final String serviceSid; + @Getter + private final String sid; + @Getter private final URI url; - private final Map links; + @Getter + private final FunctionVersion.Visibility visibility; @JsonCreator private FunctionVersion( - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("service_sid") final String serviceSid, - @JsonProperty("function_sid") final String functionSid, - @JsonProperty("path") final String path, - @JsonProperty("visibility") final FunctionVersion.Visibility visibility, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("url") final URI url, - @JsonProperty("links") final Map links + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("function_sid") final String functionSid, + @JsonProperty("links") final Map links, + @JsonProperty("path") final String path, + @JsonProperty("service_sid") final String serviceSid, + @JsonProperty("sid") final String sid, + @JsonProperty("url") final URI url, + @JsonProperty("visibility") final FunctionVersion.Visibility visibility ) { - this.sid = sid; this.accountSid = accountSid; - this.serviceSid = serviceSid; + this.dateCreated = dateCreated; this.functionSid = functionSid; + this.links = links; this.path = path; - this.visibility = visibility; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); + this.serviceSid = serviceSid; + this.sid = sid; this.url = url; - this.links = links; - } - - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getServiceSid() { - return this.serviceSid; - } - - public final String getFunctionSid() { - return this.functionSid; - } - - public final String getPath() { - return this.path; - } - - public final FunctionVersion.Visibility getVisibility() { - return this.visibility; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final URI getUrl() { - return this.url; - } - - public final Map getLinks() { - return this.links; + this.visibility = visibility; } @Override @@ -183,53 +181,34 @@ public boolean equals(final Object o) { } FunctionVersion other = (FunctionVersion) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(serviceSid, other.serviceSid) && - Objects.equals(functionSid, other.functionSid) && - Objects.equals(path, other.path) && - Objects.equals(visibility, other.visibility) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(url, other.url) && - Objects.equals(links, other.links) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(functionSid, other.functionSid) && + Objects.equals(links, other.links) && + Objects.equals(path, other.path) && + Objects.equals(serviceSid, other.serviceSid) && + Objects.equals(sid, other.sid) && + Objects.equals(url, other.url) && + Objects.equals(visibility, other.visibility) ); } @Override public int hashCode() { return Objects.hash( - sid, - accountSid, - serviceSid, - functionSid, - path, - visibility, - dateCreated, - url, - links + accountSid, + dateCreated, + functionSid, + links, + path, + serviceSid, + sid, + url, + visibility ); } - public enum Visibility { - PUBLIC("public"), - PRIVATE("private"), - PROTECTED("protected"); - - private final String value; - private Visibility(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static Visibility forValue(final String value) { - return Promoter.enumFromString(value, Visibility.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/serverless/v1/service/function/FunctionVersionFetcher.java b/src/main/java/com/twilio/rest/serverless/v1/service/function/FunctionVersionFetcher.java index f8af261155..acae28dc3a 100644 --- a/src/main/java/com/twilio/rest/serverless/v1/service/function/FunctionVersionFetcher.java +++ b/src/main/java/com/twilio/rest/serverless/v1/service/function/FunctionVersionFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.serverless.v1.service.function; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,66 +26,47 @@ public class FunctionVersionFetcher extends Fetcher { - private String pathServiceSid; - private String pathFunctionSid; - private String pathSid; + private String pathserviceSid; + private String pathfunctionSid; + private String pathsid; - public FunctionVersionFetcher( - final String pathServiceSid, - final String pathFunctionSid, - final String pathSid - ) { - this.pathServiceSid = pathServiceSid; - this.pathFunctionSid = pathFunctionSid; - this.pathSid = pathSid; + public FunctionVersionFetcher(final String pathserviceSid, final String pathfunctionSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathfunctionSid = pathfunctionSid; + this.pathsid = pathsid; } + @Override public FunctionVersion fetch(final TwilioRestClient client) { - String path = - "/v1/Services/{ServiceSid}/Functions/{FunctionSid}/Versions/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = - path.replace( - "{" + "FunctionSid" + "}", - this.pathFunctionSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/v1/Services/{ServiceSid}/Functions/{FunctionSid}/Versions/{Sid}"; + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "FunctionSid" + "}", this.pathfunctionSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.SERVERLESS.toString(), - path + HttpMethod.GET, + Domains.SERVERLESS.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "FunctionVersion fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("FunctionVersion fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return FunctionVersion.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return FunctionVersion.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/serverless/v1/service/function/FunctionVersionReader.java b/src/main/java/com/twilio/rest/serverless/v1/service/function/FunctionVersionReader.java index f8919e8d89..aa9dcba69b 100644 --- a/src/main/java/com/twilio/rest/serverless/v1/service/function/FunctionVersionReader.java +++ b/src/main/java/com/twilio/rest/serverless/v1/service/function/FunctionVersionReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,126 +30,91 @@ public class FunctionVersionReader extends Reader { - private String pathServiceSid; - private String pathFunctionSid; + private String pathserviceSid; + private String pathfunctionSid; private Long pageSize; - public FunctionVersionReader( - final String pathServiceSid, - final String pathFunctionSid - ) { - this.pathServiceSid = pathServiceSid; - this.pathFunctionSid = pathFunctionSid; + public FunctionVersionReader(final String pathserviceSid, final String pathfunctionSid) { + this.pathserviceSid = pathserviceSid; + this.pathfunctionSid = pathfunctionSid; } + public FunctionVersionReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { - String path = - "/v1/Services/{ServiceSid}/Functions/{FunctionSid}/Versions"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = - path.replace( - "{" + "FunctionSid" + "}", - this.pathFunctionSid.toString() - ); + + String path = "/v1/Services/{ServiceSid}/Functions/{FunctionSid}/Versions"; + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "FunctionSid" + "}", this.pathfunctionSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.SERVERLESS.toString(), - path + HttpMethod.GET, + Domains.SERVERLESS.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "FunctionVersion read failed: Unable to connect to server" - ); + throw new ApiConnectionException("FunctionVersion read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "function_versions", - response.getContent(), - FunctionVersion.class, - client.getObjectMapper() - ); + "function_versions", + response.getContent(), + FunctionVersion.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.SERVERLESS.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.SERVERLESS.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/serverless/v1/service/function/functionversion/FunctionVersionContent.java b/src/main/java/com/twilio/rest/serverless/v1/service/function/functionversion/FunctionVersionContent.java index c668e1abcc..37c965b556 100644 --- a/src/main/java/com/twilio/rest/serverless/v1/service/function/functionversion/FunctionVersionContent.java +++ b/src/main/java/com/twilio/rest/serverless/v1/service/function/functionversion/FunctionVersionContent.java @@ -18,47 +18,40 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class FunctionVersionContent extends Resource { - private static final long serialVersionUID = 208000590885959L; - public static FunctionVersionContentFetcher fetcher( - final String pathServiceSid, - final String pathFunctionSid, - final String pathSid - ) { + public static FunctionVersionContentFetcher fetcher(final String pathserviceSid, final String pathfunctionSid, final String pathsid) { return new FunctionVersionContentFetcher( - pathServiceSid, - pathFunctionSid, - pathSid + pathserviceSid, pathfunctionSid, pathsid ); } + /** * Converts a JSON String into a FunctionVersionContent object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return FunctionVersionContent object represented by the provided JSON */ - public static FunctionVersionContent fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static FunctionVersionContent fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, FunctionVersionContent.class); @@ -73,14 +66,11 @@ public static FunctionVersionContent fromJson( * Converts a JSON InputStream into a FunctionVersionContent object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return FunctionVersionContent object represented by the provided JSON */ - public static FunctionVersionContent fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static FunctionVersionContent fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, FunctionVersionContent.class); @@ -91,54 +81,49 @@ public static FunctionVersionContent fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String serviceSid; - private final String functionSid; + @Getter private final String content; + @Getter + private final String functionSid; + @Getter + private final String serviceSid; + @Getter + private final String sid; + @Getter private final URI url; @JsonCreator private FunctionVersionContent( - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("service_sid") final String serviceSid, - @JsonProperty("function_sid") final String functionSid, - @JsonProperty("content") final String content, - @JsonProperty("url") final URI url + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("content") final String content, + @JsonProperty("function_sid") final String functionSid, + @JsonProperty("service_sid") final String serviceSid, + @JsonProperty("sid") final String sid, + @JsonProperty("url") final URI url ) { - this.sid = sid; this.accountSid = accountSid; - this.serviceSid = serviceSid; - this.functionSid = functionSid; this.content = content; + this.functionSid = functionSid; + this.serviceSid = serviceSid; + this.sid = sid; this.url = url; } - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getServiceSid() { - return this.serviceSid; - } - - public final String getFunctionSid() { - return this.functionSid; - } - - public final String getContent() { - return this.content; - } - - public final URI getUrl() { - return this.url; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -150,26 +135,28 @@ public boolean equals(final Object o) { } FunctionVersionContent other = (FunctionVersionContent) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(serviceSid, other.serviceSid) && - Objects.equals(functionSid, other.functionSid) && - Objects.equals(content, other.content) && - Objects.equals(url, other.url) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(content, other.content) && + Objects.equals(functionSid, other.functionSid) && + Objects.equals(serviceSid, other.serviceSid) && + Objects.equals(sid, other.sid) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - sid, - accountSid, - serviceSid, - functionSid, - content, - url + accountSid, + content, + functionSid, + serviceSid, + sid, + url ); } + + } + diff --git a/src/main/java/com/twilio/rest/serverless/v1/service/function/functionversion/FunctionVersionContentFetcher.java b/src/main/java/com/twilio/rest/serverless/v1/service/function/functionversion/FunctionVersionContentFetcher.java index 6bc792d46c..ded29f5aa0 100644 --- a/src/main/java/com/twilio/rest/serverless/v1/service/function/functionversion/FunctionVersionContentFetcher.java +++ b/src/main/java/com/twilio/rest/serverless/v1/service/function/functionversion/FunctionVersionContentFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.serverless.v1.service.function.functionversion; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,69 +24,49 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class FunctionVersionContentFetcher - extends Fetcher { +public class FunctionVersionContentFetcher extends Fetcher { - private String pathServiceSid; - private String pathFunctionSid; - private String pathSid; + private String pathserviceSid; + private String pathfunctionSid; + private String pathsid; - public FunctionVersionContentFetcher( - final String pathServiceSid, - final String pathFunctionSid, - final String pathSid - ) { - this.pathServiceSid = pathServiceSid; - this.pathFunctionSid = pathFunctionSid; - this.pathSid = pathSid; + public FunctionVersionContentFetcher(final String pathserviceSid, final String pathfunctionSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathfunctionSid = pathfunctionSid; + this.pathsid = pathsid; } + @Override public FunctionVersionContent fetch(final TwilioRestClient client) { - String path = - "/v1/Services/{ServiceSid}/Functions/{FunctionSid}/Versions/{Sid}/Content"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = - path.replace( - "{" + "FunctionSid" + "}", - this.pathFunctionSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/v1/Services/{ServiceSid}/Functions/{FunctionSid}/Versions/{Sid}/Content"; + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "FunctionSid" + "}", this.pathfunctionSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.SERVERLESS.toString(), - path + HttpMethod.GET, + Domains.SERVERLESS.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "FunctionVersionContent fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("FunctionVersionContent fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return FunctionVersionContent.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return FunctionVersionContent.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/studio/v1/Flow.java b/src/main/java/com/twilio/rest/studio/v1/Flow.java index e54921d904..402969f78f 100644 --- a/src/main/java/com/twilio/rest/studio/v1/Flow.java +++ b/src/main/java/com/twilio/rest/studio/v1/Flow.java @@ -18,52 +18,79 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Flow extends Resource { - private static final long serialVersionUID = 8879052558661L; - public static FlowDeleter deleter(final String pathSid) { - return new FlowDeleter(pathSid); + public static FlowDeleter deleter(final String pathsid) { + return new FlowDeleter( + pathsid + ); } - public static FlowFetcher fetcher(final String pathSid) { - return new FlowFetcher(pathSid); + + public static FlowFetcher fetcher(final String pathsid) { + return new FlowFetcher( + pathsid + ); } + public static FlowReader reader() { - return new FlowReader(); + return new FlowReader( + + ); } + + public enum Status { + DRAFT("draft"), + PUBLISHED("published"); + + private final String value; + + private Status(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static Status forValue(final String value) { + return Promoter.enumFromString(value, Status.values()); + } + } + + /** * Converts a JSON String into a Flow object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Flow object represented by the provided JSON */ - public static Flow fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Flow fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Flow.class); @@ -78,14 +105,11 @@ public static Flow fromJson( * Converts a JSON InputStream into a Flow object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Flow object represented by the provided JSON */ - public static Flow fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Flow fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Flow.class); @@ -96,73 +120,61 @@ public static Flow fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String friendlyName; - private final Flow.Status status; - private final Integer version; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; - private final URI url; + @Getter + private final String friendlyName; + @Getter private final Map links; + @Getter + private final String sid; + @Getter + private final Flow.Status status; + @Getter + private final URI url; + @Getter + private final Integer version; @JsonCreator private Flow( - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("status") final Flow.Status status, - @JsonProperty("version") final Integer version, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("url") final URI url, - @JsonProperty("links") final Map links + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("links") final Map links, + @JsonProperty("sid") final String sid, + @JsonProperty("status") final Flow.Status status, + @JsonProperty("url") final URI url, + @JsonProperty("version") final Integer version ) { - this.sid = sid; this.accountSid = accountSid; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.friendlyName = friendlyName; + this.links = links; + this.sid = sid; this.status = status; - this.version = version; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); this.url = url; - this.links = links; - } - - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final Flow.Status getStatus() { - return this.status; - } - - public final Integer getVersion() { - return this.version; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final URI getUrl() { - return this.url; - } - - public final Map getLinks() { - return this.links; + this.version = version; } @Override @@ -176,52 +188,34 @@ public boolean equals(final Object o) { } Flow other = (Flow) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(status, other.status) && - Objects.equals(version, other.version) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(url, other.url) && - Objects.equals(links, other.links) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(links, other.links) && + Objects.equals(sid, other.sid) && + Objects.equals(status, other.status) && + Objects.equals(url, other.url) && + Objects.equals(version, other.version) ); } @Override public int hashCode() { return Objects.hash( - sid, - accountSid, - friendlyName, - status, - version, - dateCreated, - dateUpdated, - url, - links + accountSid, + dateCreated, + dateUpdated, + friendlyName, + links, + sid, + status, + url, + version ); } - public enum Status { - DRAFT("draft"), - PUBLISHED("published"); - - private final String value; - - private Status(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - @JsonCreator - public static Status forValue(final String value) { - return Promoter.enumFromString(value, Status.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/studio/v1/FlowDeleter.java b/src/main/java/com/twilio/rest/studio/v1/FlowDeleter.java index 9bc65db1bf..f64ba13db8 100644 --- a/src/main/java/com/twilio/rest/studio/v1/FlowDeleter.java +++ b/src/main/java/com/twilio/rest/studio/v1/FlowDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.studio.v1; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,40 +26,38 @@ public class FlowDeleter extends Deleter { - private String pathSid; + private String pathsid; - public FlowDeleter(final String pathSid) { - this.pathSid = pathSid; + public FlowDeleter(final String pathsid) { + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/v1/Flows/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.STUDIO.toString(), - path + HttpMethod.DELETE, + Domains.STUDIO.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Flow delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("Flow delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/studio/v1/FlowFetcher.java b/src/main/java/com/twilio/rest/studio/v1/FlowFetcher.java index 11c3b15d9e..0f207831c3 100644 --- a/src/main/java/com/twilio/rest/studio/v1/FlowFetcher.java +++ b/src/main/java/com/twilio/rest/studio/v1/FlowFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.studio.v1; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,44 +26,41 @@ public class FlowFetcher extends Fetcher { - private String pathSid; + private String pathsid; - public FlowFetcher(final String pathSid) { - this.pathSid = pathSid; + public FlowFetcher(final String pathsid) { + this.pathsid = pathsid; } + @Override public Flow fetch(final TwilioRestClient client) { + String path = "/v1/Flows/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.STUDIO.toString(), - path + HttpMethod.GET, + Domains.STUDIO.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Flow fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Flow fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Flow.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/studio/v1/FlowReader.java b/src/main/java/com/twilio/rest/studio/v1/FlowReader.java index bb04f4a074..2a9ac3a356 100644 --- a/src/main/java/com/twilio/rest/studio/v1/FlowReader.java +++ b/src/main/java/com/twilio/rest/studio/v1/FlowReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -31,105 +32,83 @@ public class FlowReader extends Reader { private Long pageSize; - public FlowReader() {} + public FlowReader() { + } + public FlowReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/Flows"; + Request request = new Request( - HttpMethod.GET, - Domains.STUDIO.toString(), - path + HttpMethod.GET, + Domains.STUDIO.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Flow read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Flow read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "flows", - response.getContent(), - Flow.class, - client.getObjectMapper() - ); + "flows", + response.getContent(), + Flow.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.STUDIO.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.STUDIO.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/studio/v1/flow/Engagement.java b/src/main/java/com/twilio/rest/studio/v1/flow/Engagement.java index 1b5c29b55b..edef89f122 100644 --- a/src/main/java/com/twilio/rest/studio/v1/flow/Engagement.java +++ b/src/main/java/com/twilio/rest/studio/v1/flow/Engagement.java @@ -18,66 +18,86 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Engagement extends Resource { - private static final long serialVersionUID = 71723617578664L; - public static EngagementCreator creator( - final String pathFlowSid, - final com.twilio.type.PhoneNumber to, - final com.twilio.type.PhoneNumber from - ) { - return new EngagementCreator(pathFlowSid, to, from); + public static EngagementCreator creator(final String pathflowSid, final com.twilio.type.PhoneNumber to, final com.twilio.type.PhoneNumber from) { + return new EngagementCreator( + pathflowSid, to, from + ); } - public static EngagementDeleter deleter( - final String pathFlowSid, - final String pathSid - ) { - return new EngagementDeleter(pathFlowSid, pathSid); + + public static EngagementDeleter deleter(final String pathflowSid, final String pathsid) { + return new EngagementDeleter( + pathflowSid, pathsid + ); } - public static EngagementFetcher fetcher( - final String pathFlowSid, - final String pathSid - ) { - return new EngagementFetcher(pathFlowSid, pathSid); + + public static EngagementFetcher fetcher(final String pathflowSid, final String pathsid) { + return new EngagementFetcher( + pathflowSid, pathsid + ); } - public static EngagementReader reader(final String pathFlowSid) { - return new EngagementReader(pathFlowSid); + + public static EngagementReader reader(final String pathflowSid) { + return new EngagementReader( + pathflowSid + ); } + + public enum Status { + ACTIVE("active"), + ENDED("ended"); + + private final String value; + + private Status(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static Status forValue(final String value) { + return Promoter.enumFromString(value, Status.values()); + } + } + + /** * Converts a JSON String into a Engagement object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Engagement object represented by the provided JSON */ - public static Engagement fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Engagement fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Engagement.class); @@ -92,14 +112,11 @@ public static Engagement fromJson( * Converts a JSON InputStream into a Engagement object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Engagement object represented by the provided JSON */ - public static Engagement fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Engagement fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Engagement.class); @@ -110,89 +127,69 @@ public static Engagement fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String flowSid; - private final String contactSid; + @Getter private final String contactChannelAddress; - private final Map context; - private final Engagement.Status status; + @Getter + private final String contactSid; + @Getter + private final Object context; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; - private final URI url; + @Getter + private final String flowSid; + @Getter private final Map links; + @Getter + private final String sid; + @Getter + private final Engagement.Status status; + @Getter + private final URI url; @JsonCreator private Engagement( - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("flow_sid") final String flowSid, - @JsonProperty("contact_sid") final String contactSid, - @JsonProperty( - "contact_channel_address" - ) final String contactChannelAddress, - @JsonProperty("context") final Map context, - @JsonProperty("status") final Engagement.Status status, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("url") final URI url, - @JsonProperty("links") final Map links + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("contact_channel_address") final String contactChannelAddress, + @JsonProperty("contact_sid") final String contactSid, + @JsonProperty("context") final Object context, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("flow_sid") final String flowSid, + @JsonProperty("links") final Map links, + @JsonProperty("sid") final String sid, + @JsonProperty("status") final Engagement.Status status, + @JsonProperty("url") final URI url ) { - this.sid = sid; this.accountSid = accountSid; - this.flowSid = flowSid; - this.contactSid = contactSid; this.contactChannelAddress = contactChannelAddress; + this.contactSid = contactSid; this.context = context; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; + this.flowSid = flowSid; + this.links = links; + this.sid = sid; this.status = status; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); this.url = url; - this.links = links; - } - - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getFlowSid() { - return this.flowSid; - } - - public final String getContactSid() { - return this.contactSid; - } - - public final String getContactChannelAddress() { - return this.contactChannelAddress; - } - - public final Map getContext() { - return this.context; - } - - public final Engagement.Status getStatus() { - return this.status; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final URI getUrl() { - return this.url; - } - - public final Map getLinks() { - return this.links; } @Override @@ -206,59 +203,38 @@ public boolean equals(final Object o) { } Engagement other = (Engagement) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(flowSid, other.flowSid) && - Objects.equals(contactSid, other.contactSid) && - Objects.equals( - contactChannelAddress, - other.contactChannelAddress - ) && - Objects.equals(context, other.context) && - Objects.equals(status, other.status) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(url, other.url) && - Objects.equals(links, other.links) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(contactChannelAddress, other.contactChannelAddress) && + Objects.equals(contactSid, other.contactSid) && + Objects.equals(context, other.context) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(flowSid, other.flowSid) && + Objects.equals(links, other.links) && + Objects.equals(sid, other.sid) && + Objects.equals(status, other.status) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - sid, - accountSid, - flowSid, - contactSid, - contactChannelAddress, - context, - status, - dateCreated, - dateUpdated, - url, - links + accountSid, + contactChannelAddress, + contactSid, + context, + dateCreated, + dateUpdated, + flowSid, + links, + sid, + status, + url ); } - public enum Status { - ACTIVE("active"), - ENDED("ended"); - private final String value; - - private Status(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static Status forValue(final String value) { - return Promoter.enumFromString(value, Status.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/studio/v1/flow/EngagementCreator.java b/src/main/java/com/twilio/rest/studio/v1/flow/EngagementCreator.java index 65b09c1a3c..fb770093d3 100644 --- a/src/main/java/com/twilio/rest/studio/v1/flow/EngagementCreator.java +++ b/src/main/java/com/twilio/rest/studio/v1/flow/EngagementCreator.java @@ -14,11 +14,12 @@ package com.twilio.rest.studio.v1.flow; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; -import com.twilio.converter.Converter; -import com.twilio.converter.Converter; +import com.twilio.constant.EnumConstants.ParameterType; import com.twilio.converter.Promoter; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -30,21 +31,18 @@ public class EngagementCreator extends Creator { - private String pathFlowSid; + private String pathflowSid; private com.twilio.type.PhoneNumber to; private com.twilio.type.PhoneNumber from; private Object parameters; - public EngagementCreator( - final String pathFlowSid, - final com.twilio.type.PhoneNumber to, - final com.twilio.type.PhoneNumber from - ) { - this.pathFlowSid = pathFlowSid; + public EngagementCreator(final String pathflowSid, final com.twilio.type.PhoneNumber to, final com.twilio.type.PhoneNumber from) { + this.pathflowSid = pathflowSid; this.to = to; this.from = from; } + public EngagementCreator setTo(final com.twilio.type.PhoneNumber to) { this.to = to; return this; @@ -68,58 +66,57 @@ public EngagementCreator setParameters(final Object parameters) { return this; } + @Override public Engagement create(final TwilioRestClient client) { + String path = "/v1/Flows/{FlowSid}/Engagements"; - path = path.replace("{" + "FlowSid" + "}", this.pathFlowSid.toString()); - path = path.replace("{" + "To" + "}", this.to.toString()); - path = path.replace("{" + "From" + "}", this.from.toString()); + path = path.replace("{" + "FlowSid" + "}", this.pathflowSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.STUDIO.toString(), - path + HttpMethod.POST, + Domains.STUDIO.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Engagement creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("Engagement creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Engagement.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Engagement.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (to != null) { - request.addPostParam("To", to.toString()); + Serializer.toString(request, "To", to, ParameterType.URLENCODED); } + + if (from != null) { - request.addPostParam("From", from.toString()); + Serializer.toString(request, "From", from, ParameterType.URLENCODED); } + + if (parameters != null) { - request.addPostParam( - "Parameters", - Converter.objectToJson(parameters) - ); + Serializer.toString(request, "Parameters", parameters, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/studio/v1/flow/EngagementDeleter.java b/src/main/java/com/twilio/rest/studio/v1/flow/EngagementDeleter.java index 5b0bab2292..225b4effb3 100644 --- a/src/main/java/com/twilio/rest/studio/v1/flow/EngagementDeleter.java +++ b/src/main/java/com/twilio/rest/studio/v1/flow/EngagementDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.studio.v1.flow; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,43 +26,41 @@ public class EngagementDeleter extends Deleter { - private String pathFlowSid; - private String pathSid; + private String pathflowSid; + private String pathsid; - public EngagementDeleter(final String pathFlowSid, final String pathSid) { - this.pathFlowSid = pathFlowSid; - this.pathSid = pathSid; + public EngagementDeleter(final String pathflowSid, final String pathsid) { + this.pathflowSid = pathflowSid; + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/v1/Flows/{FlowSid}/Engagements/{Sid}"; - path = path.replace("{" + "FlowSid" + "}", this.pathFlowSid.toString()); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "FlowSid" + "}", this.pathflowSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.STUDIO.toString(), - path + HttpMethod.DELETE, + Domains.STUDIO.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Engagement delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("Engagement delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/studio/v1/flow/EngagementFetcher.java b/src/main/java/com/twilio/rest/studio/v1/flow/EngagementFetcher.java index e046a9df93..03c8c2996a 100644 --- a/src/main/java/com/twilio/rest/studio/v1/flow/EngagementFetcher.java +++ b/src/main/java/com/twilio/rest/studio/v1/flow/EngagementFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.studio.v1.flow; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,50 +26,44 @@ public class EngagementFetcher extends Fetcher { - private String pathFlowSid; - private String pathSid; + private String pathflowSid; + private String pathsid; - public EngagementFetcher(final String pathFlowSid, final String pathSid) { - this.pathFlowSid = pathFlowSid; - this.pathSid = pathSid; + public EngagementFetcher(final String pathflowSid, final String pathsid) { + this.pathflowSid = pathflowSid; + this.pathsid = pathsid; } + @Override public Engagement fetch(final TwilioRestClient client) { + String path = "/v1/Flows/{FlowSid}/Engagements/{Sid}"; - path = path.replace("{" + "FlowSid" + "}", this.pathFlowSid.toString()); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "FlowSid" + "}", this.pathflowSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.STUDIO.toString(), - path + HttpMethod.GET, + Domains.STUDIO.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Engagement fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Engagement fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return Engagement.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Engagement.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/studio/v1/flow/EngagementReader.java b/src/main/java/com/twilio/rest/studio/v1/flow/EngagementReader.java index c415019e02..c1aac6cb99 100644 --- a/src/main/java/com/twilio/rest/studio/v1/flow/EngagementReader.java +++ b/src/main/java/com/twilio/rest/studio/v1/flow/EngagementReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,111 +30,88 @@ public class EngagementReader extends Reader { - private String pathFlowSid; + private String pathflowSid; private Long pageSize; - public EngagementReader(final String pathFlowSid) { - this.pathFlowSid = pathFlowSid; + public EngagementReader(final String pathflowSid) { + this.pathflowSid = pathflowSid; } + public EngagementReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/Flows/{FlowSid}/Engagements"; - path = path.replace("{" + "FlowSid" + "}", this.pathFlowSid.toString()); + + path = path.replace("{" + "FlowSid" + "}", this.pathflowSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.STUDIO.toString(), - path + HttpMethod.GET, + Domains.STUDIO.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Engagement read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Engagement read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "engagements", - response.getContent(), - Engagement.class, - client.getObjectMapper() - ); + "engagements", + response.getContent(), + Engagement.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.STUDIO.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.STUDIO.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/studio/v1/flow/Execution.java b/src/main/java/com/twilio/rest/studio/v1/flow/Execution.java index 7806f0e36d..7cad30f67d 100644 --- a/src/main/java/com/twilio/rest/studio/v1/flow/Execution.java +++ b/src/main/java/com/twilio/rest/studio/v1/flow/Execution.java @@ -18,74 +18,93 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Execution extends Resource { - private static final long serialVersionUID = 221370387280625L; - public static ExecutionCreator creator( - final String pathFlowSid, - final com.twilio.type.PhoneNumber to, - final com.twilio.type.PhoneNumber from - ) { - return new ExecutionCreator(pathFlowSid, to, from); + public static ExecutionCreator creator(final String pathflowSid, final com.twilio.type.PhoneNumber to, final com.twilio.type.PhoneNumber from) { + return new ExecutionCreator( + pathflowSid, to, from + ); } - public static ExecutionDeleter deleter( - final String pathFlowSid, - final String pathSid - ) { - return new ExecutionDeleter(pathFlowSid, pathSid); + + public static ExecutionDeleter deleter(final String pathflowSid, final String pathsid) { + return new ExecutionDeleter( + pathflowSid, pathsid + ); } - public static ExecutionFetcher fetcher( - final String pathFlowSid, - final String pathSid - ) { - return new ExecutionFetcher(pathFlowSid, pathSid); + + public static ExecutionFetcher fetcher(final String pathflowSid, final String pathsid) { + return new ExecutionFetcher( + pathflowSid, pathsid + ); } - public static ExecutionReader reader(final String pathFlowSid) { - return new ExecutionReader(pathFlowSid); + + public static ExecutionReader reader(final String pathflowSid) { + return new ExecutionReader( + pathflowSid + ); } - public static ExecutionUpdater updater( - final String pathFlowSid, - final String pathSid, - final Execution.Status status - ) { - return new ExecutionUpdater(pathFlowSid, pathSid, status); + + public static ExecutionUpdater updater(final String pathflowSid, final String pathsid, final Execution.Status status) { + return new ExecutionUpdater( + pathflowSid, pathsid, status + ); } + + public enum Status { + ACTIVE("active"), + ENDED("ended"); + + private final String value; + + private Status(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static Status forValue(final String value) { + return Promoter.enumFromString(value, Status.values()); + } + } + + /** * Converts a JSON String into a Execution object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Execution object represented by the provided JSON */ - public static Execution fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Execution fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Execution.class); @@ -100,14 +119,11 @@ public static Execution fromJson( * Converts a JSON InputStream into a Execution object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Execution object represented by the provided JSON */ - public static Execution fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Execution fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Execution.class); @@ -118,89 +134,69 @@ public static Execution fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String flowSid; - private final String contactSid; + @Getter private final String contactChannelAddress; - private final Map context; - private final Execution.Status status; + @Getter + private final String contactSid; + @Getter + private final Object context; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; - private final URI url; + @Getter + private final String flowSid; + @Getter private final Map links; + @Getter + private final String sid; + @Getter + private final Execution.Status status; + @Getter + private final URI url; @JsonCreator private Execution( - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("flow_sid") final String flowSid, - @JsonProperty("contact_sid") final String contactSid, - @JsonProperty( - "contact_channel_address" - ) final String contactChannelAddress, - @JsonProperty("context") final Map context, - @JsonProperty("status") final Execution.Status status, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("url") final URI url, - @JsonProperty("links") final Map links + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("contact_channel_address") final String contactChannelAddress, + @JsonProperty("contact_sid") final String contactSid, + @JsonProperty("context") final Object context, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("flow_sid") final String flowSid, + @JsonProperty("links") final Map links, + @JsonProperty("sid") final String sid, + @JsonProperty("status") final Execution.Status status, + @JsonProperty("url") final URI url ) { - this.sid = sid; this.accountSid = accountSid; - this.flowSid = flowSid; - this.contactSid = contactSid; this.contactChannelAddress = contactChannelAddress; + this.contactSid = contactSid; this.context = context; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; + this.flowSid = flowSid; + this.links = links; + this.sid = sid; this.status = status; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); this.url = url; - this.links = links; - } - - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getFlowSid() { - return this.flowSid; - } - - public final String getContactSid() { - return this.contactSid; - } - - public final String getContactChannelAddress() { - return this.contactChannelAddress; - } - - public final Map getContext() { - return this.context; - } - - public final Execution.Status getStatus() { - return this.status; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final URI getUrl() { - return this.url; - } - - public final Map getLinks() { - return this.links; } @Override @@ -214,59 +210,38 @@ public boolean equals(final Object o) { } Execution other = (Execution) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(flowSid, other.flowSid) && - Objects.equals(contactSid, other.contactSid) && - Objects.equals( - contactChannelAddress, - other.contactChannelAddress - ) && - Objects.equals(context, other.context) && - Objects.equals(status, other.status) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(url, other.url) && - Objects.equals(links, other.links) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(contactChannelAddress, other.contactChannelAddress) && + Objects.equals(contactSid, other.contactSid) && + Objects.equals(context, other.context) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(flowSid, other.flowSid) && + Objects.equals(links, other.links) && + Objects.equals(sid, other.sid) && + Objects.equals(status, other.status) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - sid, - accountSid, - flowSid, - contactSid, - contactChannelAddress, - context, - status, - dateCreated, - dateUpdated, - url, - links + accountSid, + contactChannelAddress, + contactSid, + context, + dateCreated, + dateUpdated, + flowSid, + links, + sid, + status, + url ); } - public enum Status { - ACTIVE("active"), - ENDED("ended"); - - private final String value; - - private Status(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - @JsonCreator - public static Status forValue(final String value) { - return Promoter.enumFromString(value, Status.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/studio/v1/flow/ExecutionCreator.java b/src/main/java/com/twilio/rest/studio/v1/flow/ExecutionCreator.java index bdc96dd0a3..843619b113 100644 --- a/src/main/java/com/twilio/rest/studio/v1/flow/ExecutionCreator.java +++ b/src/main/java/com/twilio/rest/studio/v1/flow/ExecutionCreator.java @@ -14,11 +14,12 @@ package com.twilio.rest.studio.v1.flow; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; -import com.twilio.converter.Converter; -import com.twilio.converter.Converter; +import com.twilio.constant.EnumConstants.ParameterType; import com.twilio.converter.Promoter; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -30,21 +31,18 @@ public class ExecutionCreator extends Creator { - private String pathFlowSid; + private String pathflowSid; private com.twilio.type.PhoneNumber to; private com.twilio.type.PhoneNumber from; private Object parameters; - public ExecutionCreator( - final String pathFlowSid, - final com.twilio.type.PhoneNumber to, - final com.twilio.type.PhoneNumber from - ) { - this.pathFlowSid = pathFlowSid; + public ExecutionCreator(final String pathflowSid, final com.twilio.type.PhoneNumber to, final com.twilio.type.PhoneNumber from) { + this.pathflowSid = pathflowSid; this.to = to; this.from = from; } + public ExecutionCreator setTo(final com.twilio.type.PhoneNumber to) { this.to = to; return this; @@ -68,58 +66,57 @@ public ExecutionCreator setParameters(final Object parameters) { return this; } + @Override public Execution create(final TwilioRestClient client) { + String path = "/v1/Flows/{FlowSid}/Executions"; - path = path.replace("{" + "FlowSid" + "}", this.pathFlowSid.toString()); - path = path.replace("{" + "To" + "}", this.to.toString()); - path = path.replace("{" + "From" + "}", this.from.toString()); + path = path.replace("{" + "FlowSid" + "}", this.pathflowSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.STUDIO.toString(), - path + HttpMethod.POST, + Domains.STUDIO.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Execution creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("Execution creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Execution.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Execution.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (to != null) { - request.addPostParam("To", to.toString()); + Serializer.toString(request, "To", to, ParameterType.URLENCODED); } + + if (from != null) { - request.addPostParam("From", from.toString()); + Serializer.toString(request, "From", from, ParameterType.URLENCODED); } + + if (parameters != null) { - request.addPostParam( - "Parameters", - Converter.objectToJson(parameters) - ); + Serializer.toString(request, "Parameters", parameters, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/studio/v1/flow/ExecutionDeleter.java b/src/main/java/com/twilio/rest/studio/v1/flow/ExecutionDeleter.java index 45e7e51c53..b5ebda7bcb 100644 --- a/src/main/java/com/twilio/rest/studio/v1/flow/ExecutionDeleter.java +++ b/src/main/java/com/twilio/rest/studio/v1/flow/ExecutionDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.studio.v1.flow; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,43 +26,41 @@ public class ExecutionDeleter extends Deleter { - private String pathFlowSid; - private String pathSid; + private String pathflowSid; + private String pathsid; - public ExecutionDeleter(final String pathFlowSid, final String pathSid) { - this.pathFlowSid = pathFlowSid; - this.pathSid = pathSid; + public ExecutionDeleter(final String pathflowSid, final String pathsid) { + this.pathflowSid = pathflowSid; + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/v1/Flows/{FlowSid}/Executions/{Sid}"; - path = path.replace("{" + "FlowSid" + "}", this.pathFlowSid.toString()); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "FlowSid" + "}", this.pathflowSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.STUDIO.toString(), - path + HttpMethod.DELETE, + Domains.STUDIO.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Execution delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("Execution delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/studio/v1/flow/ExecutionFetcher.java b/src/main/java/com/twilio/rest/studio/v1/flow/ExecutionFetcher.java index 5df60a61ad..3f4ed0ccbb 100644 --- a/src/main/java/com/twilio/rest/studio/v1/flow/ExecutionFetcher.java +++ b/src/main/java/com/twilio/rest/studio/v1/flow/ExecutionFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.studio.v1.flow; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,50 +26,44 @@ public class ExecutionFetcher extends Fetcher { - private String pathFlowSid; - private String pathSid; + private String pathflowSid; + private String pathsid; - public ExecutionFetcher(final String pathFlowSid, final String pathSid) { - this.pathFlowSid = pathFlowSid; - this.pathSid = pathSid; + public ExecutionFetcher(final String pathflowSid, final String pathsid) { + this.pathflowSid = pathflowSid; + this.pathsid = pathsid; } + @Override public Execution fetch(final TwilioRestClient client) { + String path = "/v1/Flows/{FlowSid}/Executions/{Sid}"; - path = path.replace("{" + "FlowSid" + "}", this.pathFlowSid.toString()); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "FlowSid" + "}", this.pathflowSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.STUDIO.toString(), - path + HttpMethod.GET, + Domains.STUDIO.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Execution fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Execution fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return Execution.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Execution.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/studio/v1/flow/ExecutionReader.java b/src/main/java/com/twilio/rest/studio/v1/flow/ExecutionReader.java index 78dfa8a55b..f3ce08018d 100644 --- a/src/main/java/com/twilio/rest/studio/v1/flow/ExecutionReader.java +++ b/src/main/java/com/twilio/rest/studio/v1/flow/ExecutionReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -26,143 +27,117 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.time.ZonedDateTime; public class ExecutionReader extends Reader { - private String pathFlowSid; + private String pathflowSid; private ZonedDateTime dateCreatedFrom; private ZonedDateTime dateCreatedTo; private Long pageSize; - public ExecutionReader(final String pathFlowSid) { - this.pathFlowSid = pathFlowSid; + public ExecutionReader(final String pathflowSid) { + this.pathflowSid = pathflowSid; } - public ExecutionReader setDateCreatedFrom( - final ZonedDateTime dateCreatedFrom - ) { + + public ExecutionReader setDateCreatedFrom(final ZonedDateTime dateCreatedFrom) { this.dateCreatedFrom = dateCreatedFrom; return this; } + public ExecutionReader setDateCreatedTo(final ZonedDateTime dateCreatedTo) { this.dateCreatedTo = dateCreatedTo; return this; } + public ExecutionReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/Flows/{FlowSid}/Executions"; - path = path.replace("{" + "FlowSid" + "}", this.pathFlowSid.toString()); + + path = path.replace("{" + "FlowSid" + "}", this.pathflowSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.STUDIO.toString(), - path + HttpMethod.GET, + Domains.STUDIO.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Execution read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Execution read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "executions", - response.getContent(), - Execution.class, - client.getObjectMapper() - ); + "executions", + response.getContent(), + Execution.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.STUDIO.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.STUDIO.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (dateCreatedFrom != null) { - request.addQueryParam( - "DateCreatedFrom", - dateCreatedFrom.toInstant().toString() - ); + Serializer.toString(request, "DateCreatedFrom", dateCreatedFrom, ParameterType.QUERY); } + if (dateCreatedTo != null) { - request.addQueryParam( - "DateCreatedTo", - dateCreatedTo.toInstant().toString() - ); + Serializer.toString(request, "DateCreatedTo", dateCreatedTo, ParameterType.QUERY); } + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/studio/v1/flow/ExecutionUpdater.java b/src/main/java/com/twilio/rest/studio/v1/flow/ExecutionUpdater.java index fced332b23..afe87ccaac 100644 --- a/src/main/java/com/twilio/rest/studio/v1/flow/ExecutionUpdater.java +++ b/src/main/java/com/twilio/rest/studio/v1/flow/ExecutionUpdater.java @@ -16,6 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -26,69 +28,64 @@ import com.twilio.rest.Domains; public class ExecutionUpdater extends Updater { - - private String pathFlowSid; - private String pathSid; + private String pathflowSid; + private String pathsid; private Execution.Status status; - public ExecutionUpdater( - final String pathFlowSid, - final String pathSid, - final Execution.Status status - ) { - this.pathFlowSid = pathFlowSid; - this.pathSid = pathSid; + public ExecutionUpdater(final String pathflowSid, final String pathsid, final Execution.Status status) { + this.pathflowSid = pathflowSid; + this.pathsid = pathsid; this.status = status; } + public ExecutionUpdater setStatus(final Execution.Status status) { this.status = status; return this; } + @Override public Execution update(final TwilioRestClient client) { + String path = "/v1/Flows/{FlowSid}/Executions/{Sid}"; - path = path.replace("{" + "FlowSid" + "}", this.pathFlowSid.toString()); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); - path = path.replace("{" + "Status" + "}", this.status.toString()); + path = path.replace("{" + "FlowSid" + "}", this.pathflowSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.STUDIO.toString(), - path + HttpMethod.POST, + Domains.STUDIO.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Execution update failed: Unable to connect to server" - ); + throw new ApiConnectionException("Execution update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Execution.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Execution.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (status != null) { - request.addPostParam("Status", status.toString()); + Serializer.toString(request, "Status", status, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/studio/v1/flow/engagement/EngagementContext.java b/src/main/java/com/twilio/rest/studio/v1/flow/engagement/EngagementContext.java index 45ed628e3b..d1ee139726 100644 --- a/src/main/java/com/twilio/rest/studio/v1/flow/engagement/EngagementContext.java +++ b/src/main/java/com/twilio/rest/studio/v1/flow/engagement/EngagementContext.java @@ -18,44 +18,40 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; -import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class EngagementContext extends Resource { - private static final long serialVersionUID = 182363461244967L; - public static EngagementContextFetcher fetcher( - final String pathFlowSid, - final String pathEngagementSid - ) { - return new EngagementContextFetcher(pathFlowSid, pathEngagementSid); + public static EngagementContextFetcher fetcher(final String pathflowSid, final String pathengagementSid) { + return new EngagementContextFetcher( + pathflowSid, pathengagementSid + ); } + /** * Converts a JSON String into a EngagementContext object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return EngagementContext object represented by the provided JSON */ - public static EngagementContext fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static EngagementContext fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, EngagementContext.class); @@ -70,14 +66,11 @@ public static EngagementContext fromJson( * Converts a JSON InputStream into a EngagementContext object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return EngagementContext object represented by the provided JSON */ - public static EngagementContext fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static EngagementContext fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, EngagementContext.class); @@ -88,19 +81,37 @@ public static EngagementContext fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final Map context; + @Getter + private final Object context; + @Getter private final String engagementSid; + @Getter private final String flowSid; + @Getter private final URI url; @JsonCreator private EngagementContext( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("context") final Map context, - @JsonProperty("engagement_sid") final String engagementSid, - @JsonProperty("flow_sid") final String flowSid, - @JsonProperty("url") final URI url + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("context") final Object context, + @JsonProperty("engagement_sid") final String engagementSid, + @JsonProperty("flow_sid") final String flowSid, + @JsonProperty("url") final URI url ) { this.accountSid = accountSid; this.context = context; @@ -109,26 +120,6 @@ private EngagementContext( this.url = url; } - public final String getAccountSid() { - return this.accountSid; - } - - public final Map getContext() { - return this.context; - } - - public final String getEngagementSid() { - return this.engagementSid; - } - - public final String getFlowSid() { - return this.flowSid; - } - - public final URI getUrl() { - return this.url; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -140,18 +131,26 @@ public boolean equals(final Object o) { } EngagementContext other = (EngagementContext) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(context, other.context) && - Objects.equals(engagementSid, other.engagementSid) && - Objects.equals(flowSid, other.flowSid) && - Objects.equals(url, other.url) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(context, other.context) && + Objects.equals(engagementSid, other.engagementSid) && + Objects.equals(flowSid, other.flowSid) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { - return Objects.hash(accountSid, context, engagementSid, flowSid, url); + return Objects.hash( + accountSid, + context, + engagementSid, + flowSid, + url + ); } + + } + diff --git a/src/main/java/com/twilio/rest/studio/v1/flow/engagement/EngagementContextFetcher.java b/src/main/java/com/twilio/rest/studio/v1/flow/engagement/EngagementContextFetcher.java index b7aa8c9991..5c2853945a 100644 --- a/src/main/java/com/twilio/rest/studio/v1/flow/engagement/EngagementContextFetcher.java +++ b/src/main/java/com/twilio/rest/studio/v1/flow/engagement/EngagementContextFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.studio.v1.flow.engagement; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,57 +26,44 @@ public class EngagementContextFetcher extends Fetcher { - private String pathFlowSid; - private String pathEngagementSid; + private String pathflowSid; + private String pathengagementSid; - public EngagementContextFetcher( - final String pathFlowSid, - final String pathEngagementSid - ) { - this.pathFlowSid = pathFlowSid; - this.pathEngagementSid = pathEngagementSid; + public EngagementContextFetcher(final String pathflowSid, final String pathengagementSid) { + this.pathflowSid = pathflowSid; + this.pathengagementSid = pathengagementSid; } + @Override public EngagementContext fetch(final TwilioRestClient client) { + String path = "/v1/Flows/{FlowSid}/Engagements/{EngagementSid}/Context"; - path = path.replace("{" + "FlowSid" + "}", this.pathFlowSid.toString()); - path = - path.replace( - "{" + "EngagementSid" + "}", - this.pathEngagementSid.toString() - ); + path = path.replace("{" + "FlowSid" + "}", this.pathflowSid.toString()); + path = path.replace("{" + "EngagementSid" + "}", this.pathengagementSid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.STUDIO.toString(), - path + HttpMethod.GET, + Domains.STUDIO.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "EngagementContext fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("EngagementContext fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return EngagementContext.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return EngagementContext.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/studio/v1/flow/engagement/Step.java b/src/main/java/com/twilio/rest/studio/v1/flow/engagement/Step.java index 6420719f71..be2a260214 100644 --- a/src/main/java/com/twilio/rest/studio/v1/flow/engagement/Step.java +++ b/src/main/java/com/twilio/rest/studio/v1/flow/engagement/Step.java @@ -18,54 +18,50 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Step extends Resource { - private static final long serialVersionUID = 119488428044573L; - public static StepFetcher fetcher( - final String pathFlowSid, - final String pathEngagementSid, - final String pathSid - ) { - return new StepFetcher(pathFlowSid, pathEngagementSid, pathSid); + public static StepFetcher fetcher(final String pathflowSid, final String pathengagementSid, final String pathsid) { + return new StepFetcher( + pathflowSid, pathengagementSid, pathsid + ); } - public static StepReader reader( - final String pathFlowSid, - final String pathEngagementSid - ) { - return new StepReader(pathFlowSid, pathEngagementSid); + + public static StepReader reader(final String pathflowSid, final String pathengagementSid) { + return new StepReader( + pathflowSid, pathengagementSid + ); } + /** * Converts a JSON String into a Step object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Step object represented by the provided JSON */ - public static Step fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Step fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Step.class); @@ -80,14 +76,11 @@ public static Step fromJson( * Converts a JSON InputStream into a Step object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Step object represented by the provided JSON */ - public static Step fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Step fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Step.class); @@ -98,108 +91,81 @@ public static Step fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String flowSid; + @Getter + private final Object context; + @Getter + private final ZonedDateTime dateCreated; + @Getter + private final ZonedDateTime dateUpdated; + @Getter private final String engagementSid; + @Getter + private final String flowSid; + @Getter + private final Map links; + @Getter private final String name; - private final Map context; + @Getter private final String parentStepSid; + @Getter + private final String sid; + @Getter private final String transitionedFrom; + @Getter private final String transitionedTo; + @Getter private final String type; - private final ZonedDateTime dateCreated; - private final ZonedDateTime dateUpdated; + @Getter private final URI url; - private final Map links; @JsonCreator private Step( - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("flow_sid") final String flowSid, - @JsonProperty("engagement_sid") final String engagementSid, - @JsonProperty("name") final String name, - @JsonProperty("context") final Map context, - @JsonProperty("parent_step_sid") final String parentStepSid, - @JsonProperty("transitioned_from") final String transitionedFrom, - @JsonProperty("transitioned_to") final String transitionedTo, - @JsonProperty("type") final String type, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("url") final URI url, - @JsonProperty("links") final Map links + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("context") final Object context, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("engagement_sid") final String engagementSid, + @JsonProperty("flow_sid") final String flowSid, + @JsonProperty("links") final Map links, + @JsonProperty("name") final String name, + @JsonProperty("parent_step_sid") final String parentStepSid, + @JsonProperty("sid") final String sid, + @JsonProperty("transitioned_from") final String transitionedFrom, + @JsonProperty("transitioned_to") final String transitionedTo, + @JsonProperty("type") final String type, + @JsonProperty("url") final URI url ) { - this.sid = sid; this.accountSid = accountSid; - this.flowSid = flowSid; + this.context = context; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.engagementSid = engagementSid; + this.flowSid = flowSid; + this.links = links; this.name = name; - this.context = context; this.parentStepSid = parentStepSid; + this.sid = sid; this.transitionedFrom = transitionedFrom; this.transitionedTo = transitionedTo; this.type = type; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); this.url = url; - this.links = links; - } - - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getFlowSid() { - return this.flowSid; - } - - public final String getEngagementSid() { - return this.engagementSid; - } - - public final String getName() { - return this.name; - } - - public final Map getContext() { - return this.context; - } - - public final String getParentStepSid() { - return this.parentStepSid; - } - - public final String getTransitionedFrom() { - return this.transitionedFrom; - } - - public final String getTransitionedTo() { - return this.transitionedTo; - } - - public final String getType() { - return this.type; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final URI getUrl() { - return this.url; - } - - public final Map getLinks() { - return this.links; } @Override @@ -213,42 +179,44 @@ public boolean equals(final Object o) { } Step other = (Step) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(flowSid, other.flowSid) && - Objects.equals(engagementSid, other.engagementSid) && - Objects.equals(name, other.name) && - Objects.equals(context, other.context) && - Objects.equals(parentStepSid, other.parentStepSid) && - Objects.equals(transitionedFrom, other.transitionedFrom) && - Objects.equals(transitionedTo, other.transitionedTo) && - Objects.equals(type, other.type) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(url, other.url) && - Objects.equals(links, other.links) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(context, other.context) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(engagementSid, other.engagementSid) && + Objects.equals(flowSid, other.flowSid) && + Objects.equals(links, other.links) && + Objects.equals(name, other.name) && + Objects.equals(parentStepSid, other.parentStepSid) && + Objects.equals(sid, other.sid) && + Objects.equals(transitionedFrom, other.transitionedFrom) && + Objects.equals(transitionedTo, other.transitionedTo) && + Objects.equals(type, other.type) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - sid, - accountSid, - flowSid, - engagementSid, - name, - context, - parentStepSid, - transitionedFrom, - transitionedTo, - type, - dateCreated, - dateUpdated, - url, - links + accountSid, + context, + dateCreated, + dateUpdated, + engagementSid, + flowSid, + links, + name, + parentStepSid, + sid, + transitionedFrom, + transitionedTo, + type, + url ); } + + } + diff --git a/src/main/java/com/twilio/rest/studio/v1/flow/engagement/StepFetcher.java b/src/main/java/com/twilio/rest/studio/v1/flow/engagement/StepFetcher.java index 86d2d3df5b..5dd108562c 100644 --- a/src/main/java/com/twilio/rest/studio/v1/flow/engagement/StepFetcher.java +++ b/src/main/java/com/twilio/rest/studio/v1/flow/engagement/StepFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.studio.v1.flow.engagement; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,59 +26,47 @@ public class StepFetcher extends Fetcher { - private String pathFlowSid; - private String pathEngagementSid; - private String pathSid; + private String pathflowSid; + private String pathengagementSid; + private String pathsid; - public StepFetcher( - final String pathFlowSid, - final String pathEngagementSid, - final String pathSid - ) { - this.pathFlowSid = pathFlowSid; - this.pathEngagementSid = pathEngagementSid; - this.pathSid = pathSid; + public StepFetcher(final String pathflowSid, final String pathengagementSid, final String pathsid) { + this.pathflowSid = pathflowSid; + this.pathengagementSid = pathengagementSid; + this.pathsid = pathsid; } + @Override public Step fetch(final TwilioRestClient client) { - String path = - "/v1/Flows/{FlowSid}/Engagements/{EngagementSid}/Steps/{Sid}"; - path = path.replace("{" + "FlowSid" + "}", this.pathFlowSid.toString()); - path = - path.replace( - "{" + "EngagementSid" + "}", - this.pathEngagementSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/v1/Flows/{FlowSid}/Engagements/{EngagementSid}/Steps/{Sid}"; + + path = path.replace("{" + "FlowSid" + "}", this.pathflowSid.toString()); + path = path.replace("{" + "EngagementSid" + "}", this.pathengagementSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.STUDIO.toString(), - path + HttpMethod.GET, + Domains.STUDIO.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Step fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Step fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Step.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/studio/v1/flow/engagement/StepReader.java b/src/main/java/com/twilio/rest/studio/v1/flow/engagement/StepReader.java index f8f672a827..f0d45faf03 100644 --- a/src/main/java/com/twilio/rest/studio/v1/flow/engagement/StepReader.java +++ b/src/main/java/com/twilio/rest/studio/v1/flow/engagement/StepReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,121 +30,91 @@ public class StepReader extends Reader { - private String pathFlowSid; - private String pathEngagementSid; + private String pathflowSid; + private String pathengagementSid; private Long pageSize; - public StepReader( - final String pathFlowSid, - final String pathEngagementSid - ) { - this.pathFlowSid = pathFlowSid; - this.pathEngagementSid = pathEngagementSid; + public StepReader(final String pathflowSid, final String pathengagementSid) { + this.pathflowSid = pathflowSid; + this.pathengagementSid = pathengagementSid; } + public StepReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/Flows/{FlowSid}/Engagements/{EngagementSid}/Steps"; - path = path.replace("{" + "FlowSid" + "}", this.pathFlowSid.toString()); - path = - path.replace( - "{" + "EngagementSid" + "}", - this.pathEngagementSid.toString() - ); + + path = path.replace("{" + "FlowSid" + "}", this.pathflowSid.toString()); + path = path.replace("{" + "EngagementSid" + "}", this.pathengagementSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.STUDIO.toString(), - path + HttpMethod.GET, + Domains.STUDIO.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Step read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Step read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "steps", - response.getContent(), - Step.class, - client.getObjectMapper() - ); + "steps", + response.getContent(), + Step.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.STUDIO.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.STUDIO.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/studio/v1/flow/engagement/step/StepContext.java b/src/main/java/com/twilio/rest/studio/v1/flow/engagement/step/StepContext.java index b3f8a40bf4..f21550b3c2 100644 --- a/src/main/java/com/twilio/rest/studio/v1/flow/engagement/step/StepContext.java +++ b/src/main/java/com/twilio/rest/studio/v1/flow/engagement/step/StepContext.java @@ -18,49 +18,40 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; -import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class StepContext extends Resource { - private static final long serialVersionUID = 81685274380880L; - public static StepContextFetcher fetcher( - final String pathFlowSid, - final String pathEngagementSid, - final String pathStepSid - ) { + public static StepContextFetcher fetcher(final String pathflowSid, final String pathengagementSid, final String pathstepSid) { return new StepContextFetcher( - pathFlowSid, - pathEngagementSid, - pathStepSid + pathflowSid, pathengagementSid, pathstepSid ); } + /** * Converts a JSON String into a StepContext object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return StepContext object represented by the provided JSON */ - public static StepContext fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static StepContext fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, StepContext.class); @@ -75,14 +66,11 @@ public static StepContext fromJson( * Converts a JSON InputStream into a StepContext object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return StepContext object represented by the provided JSON */ - public static StepContext fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static StepContext fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, StepContext.class); @@ -93,21 +81,40 @@ public static StepContext fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final Map context; + @Getter + private final Object context; + @Getter private final String engagementSid; + @Getter private final String flowSid; + @Getter private final String stepSid; + @Getter private final URI url; @JsonCreator private StepContext( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("context") final Map context, - @JsonProperty("engagement_sid") final String engagementSid, - @JsonProperty("flow_sid") final String flowSid, - @JsonProperty("step_sid") final String stepSid, - @JsonProperty("url") final URI url + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("context") final Object context, + @JsonProperty("engagement_sid") final String engagementSid, + @JsonProperty("flow_sid") final String flowSid, + @JsonProperty("step_sid") final String stepSid, + @JsonProperty("url") final URI url ) { this.accountSid = accountSid; this.context = context; @@ -117,30 +124,6 @@ private StepContext( this.url = url; } - public final String getAccountSid() { - return this.accountSid; - } - - public final Map getContext() { - return this.context; - } - - public final String getEngagementSid() { - return this.engagementSid; - } - - public final String getFlowSid() { - return this.flowSid; - } - - public final String getStepSid() { - return this.stepSid; - } - - public final URI getUrl() { - return this.url; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -152,26 +135,28 @@ public boolean equals(final Object o) { } StepContext other = (StepContext) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(context, other.context) && - Objects.equals(engagementSid, other.engagementSid) && - Objects.equals(flowSid, other.flowSid) && - Objects.equals(stepSid, other.stepSid) && - Objects.equals(url, other.url) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(context, other.context) && + Objects.equals(engagementSid, other.engagementSid) && + Objects.equals(flowSid, other.flowSid) && + Objects.equals(stepSid, other.stepSid) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - accountSid, - context, - engagementSid, - flowSid, - stepSid, - url + accountSid, + context, + engagementSid, + flowSid, + stepSid, + url ); } + + } + diff --git a/src/main/java/com/twilio/rest/studio/v1/flow/engagement/step/StepContextFetcher.java b/src/main/java/com/twilio/rest/studio/v1/flow/engagement/step/StepContextFetcher.java index 27516972e7..b8207d51e0 100644 --- a/src/main/java/com/twilio/rest/studio/v1/flow/engagement/step/StepContextFetcher.java +++ b/src/main/java/com/twilio/rest/studio/v1/flow/engagement/step/StepContextFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.studio.v1.flow.engagement.step; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,62 +26,47 @@ public class StepContextFetcher extends Fetcher { - private String pathFlowSid; - private String pathEngagementSid; - private String pathStepSid; + private String pathflowSid; + private String pathengagementSid; + private String pathstepSid; - public StepContextFetcher( - final String pathFlowSid, - final String pathEngagementSid, - final String pathStepSid - ) { - this.pathFlowSid = pathFlowSid; - this.pathEngagementSid = pathEngagementSid; - this.pathStepSid = pathStepSid; + public StepContextFetcher(final String pathflowSid, final String pathengagementSid, final String pathstepSid) { + this.pathflowSid = pathflowSid; + this.pathengagementSid = pathengagementSid; + this.pathstepSid = pathstepSid; } + @Override public StepContext fetch(final TwilioRestClient client) { - String path = - "/v1/Flows/{FlowSid}/Engagements/{EngagementSid}/Steps/{StepSid}/Context"; - path = path.replace("{" + "FlowSid" + "}", this.pathFlowSid.toString()); - path = - path.replace( - "{" + "EngagementSid" + "}", - this.pathEngagementSid.toString() - ); - path = path.replace("{" + "StepSid" + "}", this.pathStepSid.toString()); + String path = "/v1/Flows/{FlowSid}/Engagements/{EngagementSid}/Steps/{StepSid}/Context"; + + path = path.replace("{" + "FlowSid" + "}", this.pathflowSid.toString()); + path = path.replace("{" + "EngagementSid" + "}", this.pathengagementSid.toString()); + path = path.replace("{" + "StepSid" + "}", this.pathstepSid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.STUDIO.toString(), - path + HttpMethod.GET, + Domains.STUDIO.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "StepContext fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("StepContext fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return StepContext.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return StepContext.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/studio/v1/flow/execution/ExecutionContext.java b/src/main/java/com/twilio/rest/studio/v1/flow/execution/ExecutionContext.java index 74e99241f0..f66ce63e87 100644 --- a/src/main/java/com/twilio/rest/studio/v1/flow/execution/ExecutionContext.java +++ b/src/main/java/com/twilio/rest/studio/v1/flow/execution/ExecutionContext.java @@ -18,44 +18,40 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; -import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class ExecutionContext extends Resource { - private static final long serialVersionUID = 48761390116247L; - public static ExecutionContextFetcher fetcher( - final String pathFlowSid, - final String pathExecutionSid - ) { - return new ExecutionContextFetcher(pathFlowSid, pathExecutionSid); + public static ExecutionContextFetcher fetcher(final String pathflowSid, final String pathexecutionSid) { + return new ExecutionContextFetcher( + pathflowSid, pathexecutionSid + ); } + /** * Converts a JSON String into a ExecutionContext object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return ExecutionContext object represented by the provided JSON */ - public static ExecutionContext fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static ExecutionContext fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, ExecutionContext.class); @@ -70,14 +66,11 @@ public static ExecutionContext fromJson( * Converts a JSON InputStream into a ExecutionContext object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return ExecutionContext object represented by the provided JSON */ - public static ExecutionContext fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static ExecutionContext fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, ExecutionContext.class); @@ -88,47 +81,45 @@ public static ExecutionContext fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final Map context; - private final String flowSid; + @Getter + private final Object context; + @Getter private final String executionSid; + @Getter + private final String flowSid; + @Getter private final URI url; @JsonCreator private ExecutionContext( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("context") final Map context, - @JsonProperty("flow_sid") final String flowSid, - @JsonProperty("execution_sid") final String executionSid, - @JsonProperty("url") final URI url + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("context") final Object context, + @JsonProperty("execution_sid") final String executionSid, + @JsonProperty("flow_sid") final String flowSid, + @JsonProperty("url") final URI url ) { this.accountSid = accountSid; this.context = context; - this.flowSid = flowSid; this.executionSid = executionSid; + this.flowSid = flowSid; this.url = url; } - public final String getAccountSid() { - return this.accountSid; - } - - public final Map getContext() { - return this.context; - } - - public final String getFlowSid() { - return this.flowSid; - } - - public final String getExecutionSid() { - return this.executionSid; - } - - public final URI getUrl() { - return this.url; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -140,18 +131,26 @@ public boolean equals(final Object o) { } ExecutionContext other = (ExecutionContext) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(context, other.context) && - Objects.equals(flowSid, other.flowSid) && - Objects.equals(executionSid, other.executionSid) && - Objects.equals(url, other.url) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(context, other.context) && + Objects.equals(executionSid, other.executionSid) && + Objects.equals(flowSid, other.flowSid) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { - return Objects.hash(accountSid, context, flowSid, executionSid, url); + return Objects.hash( + accountSid, + context, + executionSid, + flowSid, + url + ); } + + } + diff --git a/src/main/java/com/twilio/rest/studio/v1/flow/execution/ExecutionContextFetcher.java b/src/main/java/com/twilio/rest/studio/v1/flow/execution/ExecutionContextFetcher.java index 5b508d48d3..40bfeba361 100644 --- a/src/main/java/com/twilio/rest/studio/v1/flow/execution/ExecutionContextFetcher.java +++ b/src/main/java/com/twilio/rest/studio/v1/flow/execution/ExecutionContextFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.studio.v1.flow.execution; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,57 +26,44 @@ public class ExecutionContextFetcher extends Fetcher { - private String pathFlowSid; - private String pathExecutionSid; + private String pathflowSid; + private String pathexecutionSid; - public ExecutionContextFetcher( - final String pathFlowSid, - final String pathExecutionSid - ) { - this.pathFlowSid = pathFlowSid; - this.pathExecutionSid = pathExecutionSid; + public ExecutionContextFetcher(final String pathflowSid, final String pathexecutionSid) { + this.pathflowSid = pathflowSid; + this.pathexecutionSid = pathexecutionSid; } + @Override public ExecutionContext fetch(final TwilioRestClient client) { + String path = "/v1/Flows/{FlowSid}/Executions/{ExecutionSid}/Context"; - path = path.replace("{" + "FlowSid" + "}", this.pathFlowSid.toString()); - path = - path.replace( - "{" + "ExecutionSid" + "}", - this.pathExecutionSid.toString() - ); + path = path.replace("{" + "FlowSid" + "}", this.pathflowSid.toString()); + path = path.replace("{" + "ExecutionSid" + "}", this.pathexecutionSid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.STUDIO.toString(), - path + HttpMethod.GET, + Domains.STUDIO.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "ExecutionContext fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("ExecutionContext fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return ExecutionContext.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return ExecutionContext.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/studio/v1/flow/execution/ExecutionStep.java b/src/main/java/com/twilio/rest/studio/v1/flow/execution/ExecutionStep.java index 3666d1e5b5..4fc4cee890 100644 --- a/src/main/java/com/twilio/rest/studio/v1/flow/execution/ExecutionStep.java +++ b/src/main/java/com/twilio/rest/studio/v1/flow/execution/ExecutionStep.java @@ -18,54 +18,50 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class ExecutionStep extends Resource { - private static final long serialVersionUID = 221887175359099L; - public static ExecutionStepFetcher fetcher( - final String pathFlowSid, - final String pathExecutionSid, - final String pathSid - ) { - return new ExecutionStepFetcher(pathFlowSid, pathExecutionSid, pathSid); + public static ExecutionStepFetcher fetcher(final String pathflowSid, final String pathexecutionSid, final String pathsid) { + return new ExecutionStepFetcher( + pathflowSid, pathexecutionSid, pathsid + ); } - public static ExecutionStepReader reader( - final String pathFlowSid, - final String pathExecutionSid - ) { - return new ExecutionStepReader(pathFlowSid, pathExecutionSid); + + public static ExecutionStepReader reader(final String pathflowSid, final String pathexecutionSid) { + return new ExecutionStepReader( + pathflowSid, pathexecutionSid + ); } + /** * Converts a JSON String into a ExecutionStep object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return ExecutionStep object represented by the provided JSON */ - public static ExecutionStep fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static ExecutionStep fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, ExecutionStep.class); @@ -80,14 +76,11 @@ public static ExecutionStep fromJson( * Converts a JSON InputStream into a ExecutionStep object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return ExecutionStep object represented by the provided JSON */ - public static ExecutionStep fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static ExecutionStep fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, ExecutionStep.class); @@ -98,108 +91,81 @@ public static ExecutionStep fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String flowSid; + @Getter + private final Object context; + @Getter + private final ZonedDateTime dateCreated; + @Getter + private final ZonedDateTime dateUpdated; + @Getter private final String executionSid; - private final String parentStepSid; + @Getter + private final String flowSid; + @Getter + private final Map links; + @Getter private final String name; - private final Map context; + @Getter + private final String parentStepSid; + @Getter + private final String sid; + @Getter private final String transitionedFrom; + @Getter private final String transitionedTo; + @Getter private final String type; - private final ZonedDateTime dateCreated; - private final ZonedDateTime dateUpdated; + @Getter private final URI url; - private final Map links; @JsonCreator private ExecutionStep( - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("flow_sid") final String flowSid, - @JsonProperty("execution_sid") final String executionSid, - @JsonProperty("parent_step_sid") final String parentStepSid, - @JsonProperty("name") final String name, - @JsonProperty("context") final Map context, - @JsonProperty("transitioned_from") final String transitionedFrom, - @JsonProperty("transitioned_to") final String transitionedTo, - @JsonProperty("type") final String type, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("url") final URI url, - @JsonProperty("links") final Map links + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("context") final Object context, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("execution_sid") final String executionSid, + @JsonProperty("flow_sid") final String flowSid, + @JsonProperty("links") final Map links, + @JsonProperty("name") final String name, + @JsonProperty("parent_step_sid") final String parentStepSid, + @JsonProperty("sid") final String sid, + @JsonProperty("transitioned_from") final String transitionedFrom, + @JsonProperty("transitioned_to") final String transitionedTo, + @JsonProperty("type") final String type, + @JsonProperty("url") final URI url ) { - this.sid = sid; this.accountSid = accountSid; - this.flowSid = flowSid; + this.context = context; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.executionSid = executionSid; - this.parentStepSid = parentStepSid; + this.flowSid = flowSid; + this.links = links; this.name = name; - this.context = context; + this.parentStepSid = parentStepSid; + this.sid = sid; this.transitionedFrom = transitionedFrom; this.transitionedTo = transitionedTo; this.type = type; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); this.url = url; - this.links = links; - } - - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getFlowSid() { - return this.flowSid; - } - - public final String getExecutionSid() { - return this.executionSid; - } - - public final String getParentStepSid() { - return this.parentStepSid; - } - - public final String getName() { - return this.name; - } - - public final Map getContext() { - return this.context; - } - - public final String getTransitionedFrom() { - return this.transitionedFrom; - } - - public final String getTransitionedTo() { - return this.transitionedTo; - } - - public final String getType() { - return this.type; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final URI getUrl() { - return this.url; - } - - public final Map getLinks() { - return this.links; } @Override @@ -213,42 +179,44 @@ public boolean equals(final Object o) { } ExecutionStep other = (ExecutionStep) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(flowSid, other.flowSid) && - Objects.equals(executionSid, other.executionSid) && - Objects.equals(parentStepSid, other.parentStepSid) && - Objects.equals(name, other.name) && - Objects.equals(context, other.context) && - Objects.equals(transitionedFrom, other.transitionedFrom) && - Objects.equals(transitionedTo, other.transitionedTo) && - Objects.equals(type, other.type) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(url, other.url) && - Objects.equals(links, other.links) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(context, other.context) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(executionSid, other.executionSid) && + Objects.equals(flowSid, other.flowSid) && + Objects.equals(links, other.links) && + Objects.equals(name, other.name) && + Objects.equals(parentStepSid, other.parentStepSid) && + Objects.equals(sid, other.sid) && + Objects.equals(transitionedFrom, other.transitionedFrom) && + Objects.equals(transitionedTo, other.transitionedTo) && + Objects.equals(type, other.type) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - sid, - accountSid, - flowSid, - executionSid, - parentStepSid, - name, - context, - transitionedFrom, - transitionedTo, - type, - dateCreated, - dateUpdated, - url, - links + accountSid, + context, + dateCreated, + dateUpdated, + executionSid, + flowSid, + links, + name, + parentStepSid, + sid, + transitionedFrom, + transitionedTo, + type, + url ); } + + } + diff --git a/src/main/java/com/twilio/rest/studio/v1/flow/execution/ExecutionStepFetcher.java b/src/main/java/com/twilio/rest/studio/v1/flow/execution/ExecutionStepFetcher.java index b9adf34a92..555fbfe2c5 100644 --- a/src/main/java/com/twilio/rest/studio/v1/flow/execution/ExecutionStepFetcher.java +++ b/src/main/java/com/twilio/rest/studio/v1/flow/execution/ExecutionStepFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.studio.v1.flow.execution; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,62 +26,47 @@ public class ExecutionStepFetcher extends Fetcher { - private String pathFlowSid; - private String pathExecutionSid; - private String pathSid; + private String pathflowSid; + private String pathexecutionSid; + private String pathsid; - public ExecutionStepFetcher( - final String pathFlowSid, - final String pathExecutionSid, - final String pathSid - ) { - this.pathFlowSid = pathFlowSid; - this.pathExecutionSid = pathExecutionSid; - this.pathSid = pathSid; + public ExecutionStepFetcher(final String pathflowSid, final String pathexecutionSid, final String pathsid) { + this.pathflowSid = pathflowSid; + this.pathexecutionSid = pathexecutionSid; + this.pathsid = pathsid; } + @Override public ExecutionStep fetch(final TwilioRestClient client) { - String path = - "/v1/Flows/{FlowSid}/Executions/{ExecutionSid}/Steps/{Sid}"; - path = path.replace("{" + "FlowSid" + "}", this.pathFlowSid.toString()); - path = - path.replace( - "{" + "ExecutionSid" + "}", - this.pathExecutionSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/v1/Flows/{FlowSid}/Executions/{ExecutionSid}/Steps/{Sid}"; + + path = path.replace("{" + "FlowSid" + "}", this.pathflowSid.toString()); + path = path.replace("{" + "ExecutionSid" + "}", this.pathexecutionSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.STUDIO.toString(), - path + HttpMethod.GET, + Domains.STUDIO.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "ExecutionStep fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("ExecutionStep fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return ExecutionStep.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return ExecutionStep.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/studio/v1/flow/execution/ExecutionStepReader.java b/src/main/java/com/twilio/rest/studio/v1/flow/execution/ExecutionStepReader.java index 16b89a01d4..620b8bfe75 100644 --- a/src/main/java/com/twilio/rest/studio/v1/flow/execution/ExecutionStepReader.java +++ b/src/main/java/com/twilio/rest/studio/v1/flow/execution/ExecutionStepReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,121 +30,91 @@ public class ExecutionStepReader extends Reader { - private String pathFlowSid; - private String pathExecutionSid; + private String pathflowSid; + private String pathexecutionSid; private Long pageSize; - public ExecutionStepReader( - final String pathFlowSid, - final String pathExecutionSid - ) { - this.pathFlowSid = pathFlowSid; - this.pathExecutionSid = pathExecutionSid; + public ExecutionStepReader(final String pathflowSid, final String pathexecutionSid) { + this.pathflowSid = pathflowSid; + this.pathexecutionSid = pathexecutionSid; } + public ExecutionStepReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/Flows/{FlowSid}/Executions/{ExecutionSid}/Steps"; - path = path.replace("{" + "FlowSid" + "}", this.pathFlowSid.toString()); - path = - path.replace( - "{" + "ExecutionSid" + "}", - this.pathExecutionSid.toString() - ); + + path = path.replace("{" + "FlowSid" + "}", this.pathflowSid.toString()); + path = path.replace("{" + "ExecutionSid" + "}", this.pathexecutionSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.STUDIO.toString(), - path + HttpMethod.GET, + Domains.STUDIO.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "ExecutionStep read failed: Unable to connect to server" - ); + throw new ApiConnectionException("ExecutionStep read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "steps", - response.getContent(), - ExecutionStep.class, - client.getObjectMapper() - ); + "steps", + response.getContent(), + ExecutionStep.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.STUDIO.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.STUDIO.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/studio/v1/flow/execution/executionstep/ExecutionStepContext.java b/src/main/java/com/twilio/rest/studio/v1/flow/execution/executionstep/ExecutionStepContext.java index 487d379a2f..a50b553132 100644 --- a/src/main/java/com/twilio/rest/studio/v1/flow/execution/executionstep/ExecutionStepContext.java +++ b/src/main/java/com/twilio/rest/studio/v1/flow/execution/executionstep/ExecutionStepContext.java @@ -18,49 +18,40 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; -import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class ExecutionStepContext extends Resource { - private static final long serialVersionUID = 28705359719021L; - public static ExecutionStepContextFetcher fetcher( - final String pathFlowSid, - final String pathExecutionSid, - final String pathStepSid - ) { + public static ExecutionStepContextFetcher fetcher(final String pathflowSid, final String pathexecutionSid, final String pathstepSid) { return new ExecutionStepContextFetcher( - pathFlowSid, - pathExecutionSid, - pathStepSid + pathflowSid, pathexecutionSid, pathstepSid ); } + /** * Converts a JSON String into a ExecutionStepContext object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return ExecutionStepContext object represented by the provided JSON */ - public static ExecutionStepContext fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static ExecutionStepContext fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, ExecutionStepContext.class); @@ -75,14 +66,11 @@ public static ExecutionStepContext fromJson( * Converts a JSON InputStream into a ExecutionStepContext object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return ExecutionStepContext object represented by the provided JSON */ - public static ExecutionStepContext fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static ExecutionStepContext fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, ExecutionStepContext.class); @@ -93,21 +81,40 @@ public static ExecutionStepContext fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final Map context; + @Getter + private final Object context; + @Getter private final String executionSid; + @Getter private final String flowSid; + @Getter private final String stepSid; + @Getter private final URI url; @JsonCreator private ExecutionStepContext( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("context") final Map context, - @JsonProperty("execution_sid") final String executionSid, - @JsonProperty("flow_sid") final String flowSid, - @JsonProperty("step_sid") final String stepSid, - @JsonProperty("url") final URI url + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("context") final Object context, + @JsonProperty("execution_sid") final String executionSid, + @JsonProperty("flow_sid") final String flowSid, + @JsonProperty("step_sid") final String stepSid, + @JsonProperty("url") final URI url ) { this.accountSid = accountSid; this.context = context; @@ -117,30 +124,6 @@ private ExecutionStepContext( this.url = url; } - public final String getAccountSid() { - return this.accountSid; - } - - public final Map getContext() { - return this.context; - } - - public final String getExecutionSid() { - return this.executionSid; - } - - public final String getFlowSid() { - return this.flowSid; - } - - public final String getStepSid() { - return this.stepSid; - } - - public final URI getUrl() { - return this.url; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -152,26 +135,28 @@ public boolean equals(final Object o) { } ExecutionStepContext other = (ExecutionStepContext) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(context, other.context) && - Objects.equals(executionSid, other.executionSid) && - Objects.equals(flowSid, other.flowSid) && - Objects.equals(stepSid, other.stepSid) && - Objects.equals(url, other.url) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(context, other.context) && + Objects.equals(executionSid, other.executionSid) && + Objects.equals(flowSid, other.flowSid) && + Objects.equals(stepSid, other.stepSid) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - accountSid, - context, - executionSid, - flowSid, - stepSid, - url + accountSid, + context, + executionSid, + flowSid, + stepSid, + url ); } + + } + diff --git a/src/main/java/com/twilio/rest/studio/v1/flow/execution/executionstep/ExecutionStepContextFetcher.java b/src/main/java/com/twilio/rest/studio/v1/flow/execution/executionstep/ExecutionStepContextFetcher.java index 10a71d06cf..09ea731b13 100644 --- a/src/main/java/com/twilio/rest/studio/v1/flow/execution/executionstep/ExecutionStepContextFetcher.java +++ b/src/main/java/com/twilio/rest/studio/v1/flow/execution/executionstep/ExecutionStepContextFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.studio.v1.flow.execution.executionstep; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,62 +26,47 @@ public class ExecutionStepContextFetcher extends Fetcher { - private String pathFlowSid; - private String pathExecutionSid; - private String pathStepSid; + private String pathflowSid; + private String pathexecutionSid; + private String pathstepSid; - public ExecutionStepContextFetcher( - final String pathFlowSid, - final String pathExecutionSid, - final String pathStepSid - ) { - this.pathFlowSid = pathFlowSid; - this.pathExecutionSid = pathExecutionSid; - this.pathStepSid = pathStepSid; + public ExecutionStepContextFetcher(final String pathflowSid, final String pathexecutionSid, final String pathstepSid) { + this.pathflowSid = pathflowSid; + this.pathexecutionSid = pathexecutionSid; + this.pathstepSid = pathstepSid; } + @Override public ExecutionStepContext fetch(final TwilioRestClient client) { - String path = - "/v1/Flows/{FlowSid}/Executions/{ExecutionSid}/Steps/{StepSid}/Context"; - path = path.replace("{" + "FlowSid" + "}", this.pathFlowSid.toString()); - path = - path.replace( - "{" + "ExecutionSid" + "}", - this.pathExecutionSid.toString() - ); - path = path.replace("{" + "StepSid" + "}", this.pathStepSid.toString()); + String path = "/v1/Flows/{FlowSid}/Executions/{ExecutionSid}/Steps/{StepSid}/Context"; + + path = path.replace("{" + "FlowSid" + "}", this.pathflowSid.toString()); + path = path.replace("{" + "ExecutionSid" + "}", this.pathexecutionSid.toString()); + path = path.replace("{" + "StepSid" + "}", this.pathstepSid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.STUDIO.toString(), - path + HttpMethod.GET, + Domains.STUDIO.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "ExecutionStepContext fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("ExecutionStepContext fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return ExecutionStepContext.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return ExecutionStepContext.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/studio/v2/Flow.java b/src/main/java/com/twilio/rest/studio/v2/Flow.java index 989e733f30..e6d2300e0a 100644 --- a/src/main/java/com/twilio/rest/studio/v2/Flow.java +++ b/src/main/java/com/twilio/rest/studio/v2/Flow.java @@ -18,68 +18,94 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.List; import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Flow extends Resource { - private static final long serialVersionUID = 951890745581L; - public static FlowCreator creator( - final String friendlyName, - final Flow.Status status, - final Object definition - ) { - return new FlowCreator(friendlyName, status, definition); + public static FlowCreator creator(final String friendlyName, final Flow.Status status, final Object definition) { + return new FlowCreator( + friendlyName, status, definition + ); } - public static FlowDeleter deleter(final String pathSid) { - return new FlowDeleter(pathSid); + + public static FlowDeleter deleter(final String pathsid) { + return new FlowDeleter( + pathsid + ); } - public static FlowFetcher fetcher(final String pathSid) { - return new FlowFetcher(pathSid); + + public static FlowFetcher fetcher(final String pathsid) { + return new FlowFetcher( + pathsid + ); } + public static FlowReader reader() { - return new FlowReader(); + return new FlowReader( + + ); } - public static FlowUpdater updater( - final String pathSid, - final Flow.Status status - ) { - return new FlowUpdater(pathSid, status); + + public static FlowUpdater updater(final String pathsid, final Flow.Status status) { + return new FlowUpdater( + pathsid, status + ); + } + + + public enum Status { + DRAFT("draft"), + PUBLISHED("published"); + + private final String value; + + private Status(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static Status forValue(final String value) { + return Promoter.enumFromString(value, Status.values()); + } } + /** * Converts a JSON String into a Flow object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Flow object represented by the provided JSON */ - public static Flow fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Flow fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Flow.class); @@ -94,14 +120,11 @@ public static Flow fromJson( * Converts a JSON InputStream into a Flow object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Flow object represented by the provided JSON */ - public static Flow fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Flow fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Flow.class); @@ -112,115 +135,85 @@ public static Flow fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String friendlyName; - private final Map definition; - private final Flow.Status status; - private final Integer revision; + @Getter private final String commitMessage; - private final Boolean valid; - private final List> errors; - private final List> warnings; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; - private final URI webhookUrl; - private final URI url; + @Getter + private final Object definition; + @Getter + private final List errors; + @Getter + private final String friendlyName; + @Getter private final Map links; + @Getter + private final Integer revision; + @Getter + private final String sid; + @Getter + private final Flow.Status status; + @Getter + private final URI url; + @Getter + private final Boolean valid; + @Getter + private final List warnings; + @Getter + private final URI webhookUrl; @JsonCreator private Flow( - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("definition") final Map definition, - @JsonProperty("status") final Flow.Status status, - @JsonProperty("revision") final Integer revision, - @JsonProperty("commit_message") final String commitMessage, - @JsonProperty("valid") final Boolean valid, - @JsonProperty("errors") final List> errors, - @JsonProperty("warnings") final List> warnings, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("webhook_url") final URI webhookUrl, - @JsonProperty("url") final URI url, - @JsonProperty("links") final Map links + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("commit_message") final String commitMessage, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("definition") final Object definition, + @JsonProperty("errors") final List errors, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("links") final Map links, + @JsonProperty("revision") final Integer revision, + @JsonProperty("sid") final String sid, + @JsonProperty("status") final Flow.Status status, + @JsonProperty("url") final URI url, + @JsonProperty("valid") final Boolean valid, + @JsonProperty("warnings") final List warnings, + @JsonProperty("webhook_url") final URI webhookUrl ) { - this.sid = sid; this.accountSid = accountSid; - this.friendlyName = friendlyName; + this.commitMessage = commitMessage; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.definition = definition; - this.status = status; + this.errors = errors; + this.friendlyName = friendlyName; + this.links = links; this.revision = revision; - this.commitMessage = commitMessage; + this.sid = sid; + this.status = status; + this.url = url; this.valid = valid; - this.errors = errors; this.warnings = warnings; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); this.webhookUrl = webhookUrl; - this.url = url; - this.links = links; - } - - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final Map getDefinition() { - return this.definition; - } - - public final Flow.Status getStatus() { - return this.status; - } - - public final Integer getRevision() { - return this.revision; - } - - public final String getCommitMessage() { - return this.commitMessage; - } - - public final Boolean getValid() { - return this.valid; - } - - public final List> getErrors() { - return this.errors; - } - - public final List> getWarnings() { - return this.warnings; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final URI getWebhookUrl() { - return this.webhookUrl; - } - - public final URI getUrl() { - return this.url; - } - - public final Map getLinks() { - return this.links; } @Override @@ -234,64 +227,46 @@ public boolean equals(final Object o) { } Flow other = (Flow) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(definition, other.definition) && - Objects.equals(status, other.status) && - Objects.equals(revision, other.revision) && - Objects.equals(commitMessage, other.commitMessage) && - Objects.equals(valid, other.valid) && - Objects.equals(errors, other.errors) && - Objects.equals(warnings, other.warnings) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(webhookUrl, other.webhookUrl) && - Objects.equals(url, other.url) && - Objects.equals(links, other.links) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(commitMessage, other.commitMessage) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(definition, other.definition) && + Objects.equals(errors, other.errors) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(links, other.links) && + Objects.equals(revision, other.revision) && + Objects.equals(sid, other.sid) && + Objects.equals(status, other.status) && + Objects.equals(url, other.url) && + Objects.equals(valid, other.valid) && + Objects.equals(warnings, other.warnings) && + Objects.equals(webhookUrl, other.webhookUrl) ); } @Override public int hashCode() { return Objects.hash( - sid, - accountSid, - friendlyName, - definition, - status, - revision, - commitMessage, - valid, - errors, - warnings, - dateCreated, - dateUpdated, - webhookUrl, - url, - links + accountSid, + commitMessage, + dateCreated, + dateUpdated, + definition, + errors, + friendlyName, + links, + revision, + sid, + status, + url, + valid, + warnings, + webhookUrl ); } - public enum Status { - DRAFT("draft"), - PUBLISHED("published"); - - private final String value; - - private Status(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - @JsonCreator - public static Status forValue(final String value) { - return Promoter.enumFromString(value, Status.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/studio/v2/FlowCreator.java b/src/main/java/com/twilio/rest/studio/v2/FlowCreator.java index 9ae445c987..9d658f4ce6 100644 --- a/src/main/java/com/twilio/rest/studio/v2/FlowCreator.java +++ b/src/main/java/com/twilio/rest/studio/v2/FlowCreator.java @@ -14,10 +14,11 @@ package com.twilio.rest.studio.v2; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; -import com.twilio.converter.Converter; -import com.twilio.converter.Converter; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -34,71 +35,62 @@ public class FlowCreator extends Creator { private Object definition; private String commitMessage; - public FlowCreator( - final String friendlyName, - final Flow.Status status, - final Object definition - ) { + public FlowCreator(final String friendlyName, final Flow.Status status, final Object definition) { this.friendlyName = friendlyName; this.status = status; this.definition = definition; } + public FlowCreator setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + public FlowCreator setStatus(final Flow.Status status) { this.status = status; return this; } + public FlowCreator setDefinition(final Object definition) { this.definition = definition; return this; } + public FlowCreator setCommitMessage(final String commitMessage) { this.commitMessage = commitMessage; return this; } + @Override public Flow create(final TwilioRestClient client) { + String path = "/v2/Flows"; - path = - path.replace( - "{" + "FriendlyName" + "}", - this.friendlyName.toString() - ); - path = path.replace("{" + "Status" + "}", this.status.toString()); - path = - path.replace("{" + "Definition" + "}", this.definition.toString()); Request request = new Request( - HttpMethod.POST, - Domains.STUDIO.toString(), - path + HttpMethod.POST, + Domains.STUDIO.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Flow creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("Flow creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -107,20 +99,26 @@ public Flow create(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + if (status != null) { - request.addPostParam("Status", status.toString()); + Serializer.toString(request, "Status", status, ParameterType.URLENCODED); } + + if (definition != null) { - request.addPostParam( - "Definition", - Converter.objectToJson(definition) - ); + Serializer.toString(request, "Definition", definition, ParameterType.URLENCODED); } + + if (commitMessage != null) { - request.addPostParam("CommitMessage", commitMessage); + Serializer.toString(request, "CommitMessage", commitMessage, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/studio/v2/FlowDeleter.java b/src/main/java/com/twilio/rest/studio/v2/FlowDeleter.java index 6383b2295e..6ba0581851 100644 --- a/src/main/java/com/twilio/rest/studio/v2/FlowDeleter.java +++ b/src/main/java/com/twilio/rest/studio/v2/FlowDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.studio.v2; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,40 +26,38 @@ public class FlowDeleter extends Deleter { - private String pathSid; + private String pathsid; - public FlowDeleter(final String pathSid) { - this.pathSid = pathSid; + public FlowDeleter(final String pathsid) { + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/v2/Flows/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.STUDIO.toString(), - path + HttpMethod.DELETE, + Domains.STUDIO.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Flow delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("Flow delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/studio/v2/FlowFetcher.java b/src/main/java/com/twilio/rest/studio/v2/FlowFetcher.java index ce6abb6af8..22391fb850 100644 --- a/src/main/java/com/twilio/rest/studio/v2/FlowFetcher.java +++ b/src/main/java/com/twilio/rest/studio/v2/FlowFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.studio.v2; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,44 +26,41 @@ public class FlowFetcher extends Fetcher { - private String pathSid; + private String pathsid; - public FlowFetcher(final String pathSid) { - this.pathSid = pathSid; + public FlowFetcher(final String pathsid) { + this.pathsid = pathsid; } + @Override public Flow fetch(final TwilioRestClient client) { + String path = "/v2/Flows/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.STUDIO.toString(), - path + HttpMethod.GET, + Domains.STUDIO.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Flow fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Flow fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Flow.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/studio/v2/FlowReader.java b/src/main/java/com/twilio/rest/studio/v2/FlowReader.java index 18bef34d4e..37ff984bdf 100644 --- a/src/main/java/com/twilio/rest/studio/v2/FlowReader.java +++ b/src/main/java/com/twilio/rest/studio/v2/FlowReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -31,105 +32,83 @@ public class FlowReader extends Reader { private Long pageSize; - public FlowReader() {} + public FlowReader() { + } + public FlowReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v2/Flows"; + Request request = new Request( - HttpMethod.GET, - Domains.STUDIO.toString(), - path + HttpMethod.GET, + Domains.STUDIO.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Flow read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Flow read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "flows", - response.getContent(), - Flow.class, - client.getObjectMapper() - ); + "flows", + response.getContent(), + Flow.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.STUDIO.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.STUDIO.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/studio/v2/FlowUpdater.java b/src/main/java/com/twilio/rest/studio/v2/FlowUpdater.java index 6d625f2a21..0c80669025 100644 --- a/src/main/java/com/twilio/rest/studio/v2/FlowUpdater.java +++ b/src/main/java/com/twilio/rest/studio/v2/FlowUpdater.java @@ -16,7 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; -import com.twilio.converter.Converter; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,67 +28,69 @@ import com.twilio.rest.Domains; public class FlowUpdater extends Updater { - - private String pathSid; + private String pathsid; private Flow.Status status; private String friendlyName; private Object definition; private String commitMessage; - public FlowUpdater(final String pathSid, final Flow.Status status) { - this.pathSid = pathSid; + public FlowUpdater(final String pathsid, final Flow.Status status) { + this.pathsid = pathsid; this.status = status; } + public FlowUpdater setStatus(final Flow.Status status) { this.status = status; return this; } + public FlowUpdater setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + public FlowUpdater setDefinition(final Object definition) { this.definition = definition; return this; } + public FlowUpdater setCommitMessage(final String commitMessage) { this.commitMessage = commitMessage; return this; } + @Override public Flow update(final TwilioRestClient client) { + String path = "/v2/Flows/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); - path = path.replace("{" + "Status" + "}", this.status.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.STUDIO.toString(), - path + HttpMethod.POST, + Domains.STUDIO.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Flow update failed: Unable to connect to server" - ); + throw new ApiConnectionException("Flow update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -96,20 +99,26 @@ public Flow update(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (status != null) { - request.addPostParam("Status", status.toString()); + Serializer.toString(request, "Status", status, ParameterType.URLENCODED); } + + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + if (definition != null) { - request.addPostParam( - "Definition", - Converter.objectToJson(definition) - ); + Serializer.toString(request, "Definition", definition, ParameterType.URLENCODED); } + + if (commitMessage != null) { - request.addPostParam("CommitMessage", commitMessage); + Serializer.toString(request, "CommitMessage", commitMessage, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/studio/v2/FlowValidate.java b/src/main/java/com/twilio/rest/studio/v2/FlowValidate.java index 6eba3f66e9..8fcf40fc90 100644 --- a/src/main/java/com/twilio/rest/studio/v2/FlowValidate.java +++ b/src/main/java/com/twilio/rest/studio/v2/FlowValidate.java @@ -18,43 +18,61 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class FlowValidate extends Resource { - private static final long serialVersionUID = 128242236604078L; - public static FlowValidateUpdater updater( - final String friendlyName, - final FlowValidate.Status status, - final Object definition - ) { - return new FlowValidateUpdater(friendlyName, status, definition); + public static FlowValidateUpdater updater(final String friendlyName, final FlowValidate.Status status, final Object definition) { + return new FlowValidateUpdater( + friendlyName, status, definition + ); } + + public enum Status { + DRAFT("draft"), + PUBLISHED("published"); + + private final String value; + + private Status(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static Status forValue(final String value) { + return Promoter.enumFromString(value, Status.values()); + } + } + + /** * Converts a JSON String into a FlowValidate object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return FlowValidate object represented by the provided JSON */ - public static FlowValidate fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static FlowValidate fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, FlowValidate.class); @@ -69,14 +87,11 @@ public static FlowValidate fromJson( * Converts a JSON InputStream into a FlowValidate object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return FlowValidate object represented by the provided JSON */ - public static FlowValidate fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static FlowValidate fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, FlowValidate.class); @@ -87,17 +102,29 @@ public static FlowValidate fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final Boolean valid; @JsonCreator - private FlowValidate(@JsonProperty("valid") final Boolean valid) { + private FlowValidate( + @JsonProperty("valid") final Boolean valid + ) { this.valid = valid; } - public final Boolean getValid() { - return this.valid; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -109,32 +136,18 @@ public boolean equals(final Object o) { } FlowValidate other = (FlowValidate) o; - - return Objects.equals(valid, other.valid); + return ( + Objects.equals(valid, other.valid) + ); } @Override public int hashCode() { - return Objects.hash(valid); + return Objects.hash( + valid + ); } - public enum Status { - DRAFT("draft"), - PUBLISHED("published"); - - private final String value; - - private Status(final String value) { - this.value = value; - } - public String toString() { - return value; - } - - @JsonCreator - public static Status forValue(final String value) { - return Promoter.enumFromString(value, Status.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/studio/v2/FlowValidateUpdater.java b/src/main/java/com/twilio/rest/studio/v2/FlowValidateUpdater.java index 954245fd2a..d831857519 100644 --- a/src/main/java/com/twilio/rest/studio/v2/FlowValidateUpdater.java +++ b/src/main/java/com/twilio/rest/studio/v2/FlowValidateUpdater.java @@ -16,7 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; -import com.twilio.converter.Converter; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,102 +28,95 @@ import com.twilio.rest.Domains; public class FlowValidateUpdater extends Updater { - private String friendlyName; private FlowValidate.Status status; private Object definition; private String commitMessage; - public FlowValidateUpdater( - final String friendlyName, - final FlowValidate.Status status, - final Object definition - ) { + public FlowValidateUpdater(final String friendlyName, final FlowValidate.Status status, final Object definition) { this.friendlyName = friendlyName; this.status = status; this.definition = definition; } + public FlowValidateUpdater setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + public FlowValidateUpdater setStatus(final FlowValidate.Status status) { this.status = status; return this; } + public FlowValidateUpdater setDefinition(final Object definition) { this.definition = definition; return this; } + public FlowValidateUpdater setCommitMessage(final String commitMessage) { this.commitMessage = commitMessage; return this; } + @Override public FlowValidate update(final TwilioRestClient client) { + String path = "/v2/Flows/Validate"; - path = - path.replace( - "{" + "FriendlyName" + "}", - this.friendlyName.toString() - ); - path = path.replace("{" + "Status" + "}", this.status.toString()); - path = - path.replace("{" + "Definition" + "}", this.definition.toString()); Request request = new Request( - HttpMethod.POST, - Domains.STUDIO.toString(), - path + HttpMethod.POST, + Domains.STUDIO.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "FlowValidate update failed: Unable to connect to server" - ); + throw new ApiConnectionException("FlowValidate update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return FlowValidate.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return FlowValidate.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + if (status != null) { - request.addPostParam("Status", status.toString()); + Serializer.toString(request, "Status", status, ParameterType.URLENCODED); } + + if (definition != null) { - request.addPostParam( - "Definition", - Converter.objectToJson(definition) - ); + Serializer.toString(request, "Definition", definition, ParameterType.URLENCODED); } + + if (commitMessage != null) { - request.addPostParam("CommitMessage", commitMessage); + Serializer.toString(request, "CommitMessage", commitMessage, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/studio/v2/flow/Execution.java b/src/main/java/com/twilio/rest/studio/v2/flow/Execution.java index a39e679402..b2fe16e489 100644 --- a/src/main/java/com/twilio/rest/studio/v2/flow/Execution.java +++ b/src/main/java/com/twilio/rest/studio/v2/flow/Execution.java @@ -18,74 +18,93 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Execution extends Resource { - private static final long serialVersionUID = 276284150060496L; - public static ExecutionCreator creator( - final String pathFlowSid, - final com.twilio.type.PhoneNumber to, - final com.twilio.type.PhoneNumber from - ) { - return new ExecutionCreator(pathFlowSid, to, from); + public static ExecutionCreator creator(final String pathflowSid, final com.twilio.type.PhoneNumber to, final com.twilio.type.PhoneNumber from) { + return new ExecutionCreator( + pathflowSid, to, from + ); } - public static ExecutionDeleter deleter( - final String pathFlowSid, - final String pathSid - ) { - return new ExecutionDeleter(pathFlowSid, pathSid); + + public static ExecutionDeleter deleter(final String pathflowSid, final String pathsid) { + return new ExecutionDeleter( + pathflowSid, pathsid + ); } - public static ExecutionFetcher fetcher( - final String pathFlowSid, - final String pathSid - ) { - return new ExecutionFetcher(pathFlowSid, pathSid); + + public static ExecutionFetcher fetcher(final String pathflowSid, final String pathsid) { + return new ExecutionFetcher( + pathflowSid, pathsid + ); } - public static ExecutionReader reader(final String pathFlowSid) { - return new ExecutionReader(pathFlowSid); + + public static ExecutionReader reader(final String pathflowSid) { + return new ExecutionReader( + pathflowSid + ); } - public static ExecutionUpdater updater( - final String pathFlowSid, - final String pathSid, - final Execution.Status status - ) { - return new ExecutionUpdater(pathFlowSid, pathSid, status); + + public static ExecutionUpdater updater(final String pathflowSid, final String pathsid, final Execution.Status status) { + return new ExecutionUpdater( + pathflowSid, pathsid, status + ); + } + + + public enum Status { + ACTIVE("active"), + ENDED("ended"); + + private final String value; + + private Status(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static Status forValue(final String value) { + return Promoter.enumFromString(value, Status.values()); + } } + /** * Converts a JSON String into a Execution object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Execution object represented by the provided JSON */ - public static Execution fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Execution fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Execution.class); @@ -100,14 +119,11 @@ public static Execution fromJson( * Converts a JSON InputStream into a Execution object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Execution object represented by the provided JSON */ - public static Execution fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Execution fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Execution.class); @@ -118,82 +134,65 @@ public static Execution fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String flowSid; + @Getter private final String contactChannelAddress; - private final Map context; - private final Execution.Status status; + @Getter + private final Object context; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; - private final URI url; + @Getter + private final String flowSid; + @Getter private final Map links; + @Getter + private final String sid; + @Getter + private final Execution.Status status; + @Getter + private final URI url; @JsonCreator private Execution( - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("flow_sid") final String flowSid, - @JsonProperty( - "contact_channel_address" - ) final String contactChannelAddress, - @JsonProperty("context") final Map context, - @JsonProperty("status") final Execution.Status status, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("url") final URI url, - @JsonProperty("links") final Map links + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("contact_channel_address") final String contactChannelAddress, + @JsonProperty("context") final Object context, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("flow_sid") final String flowSid, + @JsonProperty("links") final Map links, + @JsonProperty("sid") final String sid, + @JsonProperty("status") final Execution.Status status, + @JsonProperty("url") final URI url ) { - this.sid = sid; this.accountSid = accountSid; - this.flowSid = flowSid; this.contactChannelAddress = contactChannelAddress; this.context = context; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; + this.flowSid = flowSid; + this.links = links; + this.sid = sid; this.status = status; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); this.url = url; - this.links = links; - } - - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getFlowSid() { - return this.flowSid; - } - - public final String getContactChannelAddress() { - return this.contactChannelAddress; - } - - public final Map getContext() { - return this.context; - } - - public final Execution.Status getStatus() { - return this.status; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final URI getUrl() { - return this.url; - } - - public final Map getLinks() { - return this.links; } @Override @@ -207,57 +206,36 @@ public boolean equals(final Object o) { } Execution other = (Execution) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(flowSid, other.flowSid) && - Objects.equals( - contactChannelAddress, - other.contactChannelAddress - ) && - Objects.equals(context, other.context) && - Objects.equals(status, other.status) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(url, other.url) && - Objects.equals(links, other.links) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(contactChannelAddress, other.contactChannelAddress) && + Objects.equals(context, other.context) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(flowSid, other.flowSid) && + Objects.equals(links, other.links) && + Objects.equals(sid, other.sid) && + Objects.equals(status, other.status) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - sid, - accountSid, - flowSid, - contactChannelAddress, - context, - status, - dateCreated, - dateUpdated, - url, - links + accountSid, + contactChannelAddress, + context, + dateCreated, + dateUpdated, + flowSid, + links, + sid, + status, + url ); } - public enum Status { - ACTIVE("active"), - ENDED("ended"); - - private final String value; - - private Status(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - @JsonCreator - public static Status forValue(final String value) { - return Promoter.enumFromString(value, Status.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/studio/v2/flow/ExecutionCreator.java b/src/main/java/com/twilio/rest/studio/v2/flow/ExecutionCreator.java index df95407644..04328a7e6c 100644 --- a/src/main/java/com/twilio/rest/studio/v2/flow/ExecutionCreator.java +++ b/src/main/java/com/twilio/rest/studio/v2/flow/ExecutionCreator.java @@ -14,11 +14,12 @@ package com.twilio.rest.studio.v2.flow; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; -import com.twilio.converter.Converter; -import com.twilio.converter.Converter; +import com.twilio.constant.EnumConstants.ParameterType; import com.twilio.converter.Promoter; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -30,21 +31,18 @@ public class ExecutionCreator extends Creator { - private String pathFlowSid; + private String pathflowSid; private com.twilio.type.PhoneNumber to; private com.twilio.type.PhoneNumber from; private Object parameters; - public ExecutionCreator( - final String pathFlowSid, - final com.twilio.type.PhoneNumber to, - final com.twilio.type.PhoneNumber from - ) { - this.pathFlowSid = pathFlowSid; + public ExecutionCreator(final String pathflowSid, final com.twilio.type.PhoneNumber to, final com.twilio.type.PhoneNumber from) { + this.pathflowSid = pathflowSid; this.to = to; this.from = from; } + public ExecutionCreator setTo(final com.twilio.type.PhoneNumber to) { this.to = to; return this; @@ -68,58 +66,57 @@ public ExecutionCreator setParameters(final Object parameters) { return this; } + @Override public Execution create(final TwilioRestClient client) { + String path = "/v2/Flows/{FlowSid}/Executions"; - path = path.replace("{" + "FlowSid" + "}", this.pathFlowSid.toString()); - path = path.replace("{" + "To" + "}", this.to.toString()); - path = path.replace("{" + "From" + "}", this.from.toString()); + path = path.replace("{" + "FlowSid" + "}", this.pathflowSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.STUDIO.toString(), - path + HttpMethod.POST, + Domains.STUDIO.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Execution creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("Execution creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Execution.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Execution.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (to != null) { - request.addPostParam("To", to.toString()); + Serializer.toString(request, "To", to, ParameterType.URLENCODED); } + + if (from != null) { - request.addPostParam("From", from.toString()); + Serializer.toString(request, "From", from, ParameterType.URLENCODED); } + + if (parameters != null) { - request.addPostParam( - "Parameters", - Converter.objectToJson(parameters) - ); + Serializer.toString(request, "Parameters", parameters, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/studio/v2/flow/ExecutionDeleter.java b/src/main/java/com/twilio/rest/studio/v2/flow/ExecutionDeleter.java index f3e1c3dfe2..b0f9aa405d 100644 --- a/src/main/java/com/twilio/rest/studio/v2/flow/ExecutionDeleter.java +++ b/src/main/java/com/twilio/rest/studio/v2/flow/ExecutionDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.studio.v2.flow; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,43 +26,41 @@ public class ExecutionDeleter extends Deleter { - private String pathFlowSid; - private String pathSid; + private String pathflowSid; + private String pathsid; - public ExecutionDeleter(final String pathFlowSid, final String pathSid) { - this.pathFlowSid = pathFlowSid; - this.pathSid = pathSid; + public ExecutionDeleter(final String pathflowSid, final String pathsid) { + this.pathflowSid = pathflowSid; + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/v2/Flows/{FlowSid}/Executions/{Sid}"; - path = path.replace("{" + "FlowSid" + "}", this.pathFlowSid.toString()); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "FlowSid" + "}", this.pathflowSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.STUDIO.toString(), - path + HttpMethod.DELETE, + Domains.STUDIO.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Execution delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("Execution delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/studio/v2/flow/ExecutionFetcher.java b/src/main/java/com/twilio/rest/studio/v2/flow/ExecutionFetcher.java index 9f0c774947..71e7fd65ea 100644 --- a/src/main/java/com/twilio/rest/studio/v2/flow/ExecutionFetcher.java +++ b/src/main/java/com/twilio/rest/studio/v2/flow/ExecutionFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.studio.v2.flow; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,50 +26,44 @@ public class ExecutionFetcher extends Fetcher { - private String pathFlowSid; - private String pathSid; + private String pathflowSid; + private String pathsid; - public ExecutionFetcher(final String pathFlowSid, final String pathSid) { - this.pathFlowSid = pathFlowSid; - this.pathSid = pathSid; + public ExecutionFetcher(final String pathflowSid, final String pathsid) { + this.pathflowSid = pathflowSid; + this.pathsid = pathsid; } + @Override public Execution fetch(final TwilioRestClient client) { + String path = "/v2/Flows/{FlowSid}/Executions/{Sid}"; - path = path.replace("{" + "FlowSid" + "}", this.pathFlowSid.toString()); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "FlowSid" + "}", this.pathflowSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.STUDIO.toString(), - path + HttpMethod.GET, + Domains.STUDIO.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Execution fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Execution fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return Execution.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Execution.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/studio/v2/flow/ExecutionReader.java b/src/main/java/com/twilio/rest/studio/v2/flow/ExecutionReader.java index e08cfbb0ab..e157eb4fb5 100644 --- a/src/main/java/com/twilio/rest/studio/v2/flow/ExecutionReader.java +++ b/src/main/java/com/twilio/rest/studio/v2/flow/ExecutionReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -26,143 +27,117 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.time.ZonedDateTime; public class ExecutionReader extends Reader { - private String pathFlowSid; + private String pathflowSid; private ZonedDateTime dateCreatedFrom; private ZonedDateTime dateCreatedTo; private Long pageSize; - public ExecutionReader(final String pathFlowSid) { - this.pathFlowSid = pathFlowSid; + public ExecutionReader(final String pathflowSid) { + this.pathflowSid = pathflowSid; } - public ExecutionReader setDateCreatedFrom( - final ZonedDateTime dateCreatedFrom - ) { + + public ExecutionReader setDateCreatedFrom(final ZonedDateTime dateCreatedFrom) { this.dateCreatedFrom = dateCreatedFrom; return this; } + public ExecutionReader setDateCreatedTo(final ZonedDateTime dateCreatedTo) { this.dateCreatedTo = dateCreatedTo; return this; } + public ExecutionReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v2/Flows/{FlowSid}/Executions"; - path = path.replace("{" + "FlowSid" + "}", this.pathFlowSid.toString()); + + path = path.replace("{" + "FlowSid" + "}", this.pathflowSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.STUDIO.toString(), - path + HttpMethod.GET, + Domains.STUDIO.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Execution read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Execution read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "executions", - response.getContent(), - Execution.class, - client.getObjectMapper() - ); + "executions", + response.getContent(), + Execution.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.STUDIO.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.STUDIO.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (dateCreatedFrom != null) { - request.addQueryParam( - "DateCreatedFrom", - dateCreatedFrom.toInstant().toString() - ); + Serializer.toString(request, "DateCreatedFrom", dateCreatedFrom, ParameterType.QUERY); } + if (dateCreatedTo != null) { - request.addQueryParam( - "DateCreatedTo", - dateCreatedTo.toInstant().toString() - ); + Serializer.toString(request, "DateCreatedTo", dateCreatedTo, ParameterType.QUERY); } + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/studio/v2/flow/ExecutionUpdater.java b/src/main/java/com/twilio/rest/studio/v2/flow/ExecutionUpdater.java index 43eecc9296..6dc32f5684 100644 --- a/src/main/java/com/twilio/rest/studio/v2/flow/ExecutionUpdater.java +++ b/src/main/java/com/twilio/rest/studio/v2/flow/ExecutionUpdater.java @@ -16,6 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -26,69 +28,64 @@ import com.twilio.rest.Domains; public class ExecutionUpdater extends Updater { - - private String pathFlowSid; - private String pathSid; + private String pathflowSid; + private String pathsid; private Execution.Status status; - public ExecutionUpdater( - final String pathFlowSid, - final String pathSid, - final Execution.Status status - ) { - this.pathFlowSid = pathFlowSid; - this.pathSid = pathSid; + public ExecutionUpdater(final String pathflowSid, final String pathsid, final Execution.Status status) { + this.pathflowSid = pathflowSid; + this.pathsid = pathsid; this.status = status; } + public ExecutionUpdater setStatus(final Execution.Status status) { this.status = status; return this; } + @Override public Execution update(final TwilioRestClient client) { + String path = "/v2/Flows/{FlowSid}/Executions/{Sid}"; - path = path.replace("{" + "FlowSid" + "}", this.pathFlowSid.toString()); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); - path = path.replace("{" + "Status" + "}", this.status.toString()); + path = path.replace("{" + "FlowSid" + "}", this.pathflowSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.STUDIO.toString(), - path + HttpMethod.POST, + Domains.STUDIO.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Execution update failed: Unable to connect to server" - ); + throw new ApiConnectionException("Execution update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Execution.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Execution.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (status != null) { - request.addPostParam("Status", status.toString()); + Serializer.toString(request, "Status", status, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/studio/v2/flow/FlowRevision.java b/src/main/java/com/twilio/rest/studio/v2/flow/FlowRevision.java index c92a4d7238..b2b76481c2 100644 --- a/src/main/java/com/twilio/rest/studio/v2/flow/FlowRevision.java +++ b/src/main/java/com/twilio/rest/studio/v2/flow/FlowRevision.java @@ -18,52 +18,72 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.List; -import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class FlowRevision extends Resource { - private static final long serialVersionUID = 84648223923809L; - public static FlowRevisionFetcher fetcher( - final String pathSid, - final String pathRevision - ) { - return new FlowRevisionFetcher(pathSid, pathRevision); + public static FlowRevisionFetcher fetcher(final String pathsid, final String pathrevision) { + return new FlowRevisionFetcher( + pathsid, pathrevision + ); + } + + + public static FlowRevisionReader reader(final String pathsid) { + return new FlowRevisionReader( + pathsid + ); } - public static FlowRevisionReader reader(final String pathSid) { - return new FlowRevisionReader(pathSid); + + public enum Status { + DRAFT("draft"), + PUBLISHED("published"); + + private final String value; + + private Status(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static Status forValue(final String value) { + return Promoter.enumFromString(value, Status.values()); + } } + /** * Converts a JSON String into a FlowRevision object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return FlowRevision object represented by the provided JSON */ - public static FlowRevision fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static FlowRevision fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, FlowRevision.class); @@ -78,14 +98,11 @@ public static FlowRevision fromJson( * Converts a JSON InputStream into a FlowRevision object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return FlowRevision object represented by the provided JSON */ - public static FlowRevision fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static FlowRevision fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, FlowRevision.class); @@ -96,94 +113,73 @@ public static FlowRevision fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String friendlyName; - private final Map definition; - private final FlowRevision.Status status; - private final Integer revision; + @Getter private final String commitMessage; - private final Boolean valid; - private final List> errors; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; + @Getter + private final Object definition; + @Getter + private final List errors; + @Getter + private final String friendlyName; + @Getter + private final Integer revision; + @Getter + private final String sid; + @Getter + private final FlowRevision.Status status; + @Getter private final URI url; + @Getter + private final Boolean valid; @JsonCreator private FlowRevision( - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("definition") final Map definition, - @JsonProperty("status") final FlowRevision.Status status, - @JsonProperty("revision") final Integer revision, - @JsonProperty("commit_message") final String commitMessage, - @JsonProperty("valid") final Boolean valid, - @JsonProperty("errors") final List> errors, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("url") final URI url + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("commit_message") final String commitMessage, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("definition") final Object definition, + @JsonProperty("errors") final List errors, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("revision") final Integer revision, + @JsonProperty("sid") final String sid, + @JsonProperty("status") final FlowRevision.Status status, + @JsonProperty("url") final URI url, + @JsonProperty("valid") final Boolean valid ) { - this.sid = sid; this.accountSid = accountSid; - this.friendlyName = friendlyName; - this.definition = definition; - this.status = status; - this.revision = revision; this.commitMessage = commitMessage; - this.valid = valid; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; + this.definition = definition; this.errors = errors; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); + this.friendlyName = friendlyName; + this.revision = revision; + this.sid = sid; + this.status = status; this.url = url; - } - - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final Map getDefinition() { - return this.definition; - } - - public final FlowRevision.Status getStatus() { - return this.status; - } - - public final Integer getRevision() { - return this.revision; - } - - public final String getCommitMessage() { - return this.commitMessage; - } - - public final Boolean getValid() { - return this.valid; - } - - public final List> getErrors() { - return this.errors; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final URI getUrl() { - return this.url; + this.valid = valid; } @Override @@ -197,58 +193,40 @@ public boolean equals(final Object o) { } FlowRevision other = (FlowRevision) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(definition, other.definition) && - Objects.equals(status, other.status) && - Objects.equals(revision, other.revision) && - Objects.equals(commitMessage, other.commitMessage) && - Objects.equals(valid, other.valid) && - Objects.equals(errors, other.errors) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(url, other.url) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(commitMessage, other.commitMessage) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(definition, other.definition) && + Objects.equals(errors, other.errors) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(revision, other.revision) && + Objects.equals(sid, other.sid) && + Objects.equals(status, other.status) && + Objects.equals(url, other.url) && + Objects.equals(valid, other.valid) ); } @Override public int hashCode() { return Objects.hash( - sid, - accountSid, - friendlyName, - definition, - status, - revision, - commitMessage, - valid, - errors, - dateCreated, - dateUpdated, - url + accountSid, + commitMessage, + dateCreated, + dateUpdated, + definition, + errors, + friendlyName, + revision, + sid, + status, + url, + valid ); } - public enum Status { - DRAFT("draft"), - PUBLISHED("published"); - - private final String value; - - private Status(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - @JsonCreator - public static Status forValue(final String value) { - return Promoter.enumFromString(value, Status.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/studio/v2/flow/FlowRevisionFetcher.java b/src/main/java/com/twilio/rest/studio/v2/flow/FlowRevisionFetcher.java index c21aa82abe..07176c8c35 100644 --- a/src/main/java/com/twilio/rest/studio/v2/flow/FlowRevisionFetcher.java +++ b/src/main/java/com/twilio/rest/studio/v2/flow/FlowRevisionFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.studio.v2.flow; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,54 +26,44 @@ public class FlowRevisionFetcher extends Fetcher { - private String pathSid; - private String pathRevision; + private String pathsid; + private String pathrevision; - public FlowRevisionFetcher( - final String pathSid, - final String pathRevision - ) { - this.pathSid = pathSid; - this.pathRevision = pathRevision; + public FlowRevisionFetcher(final String pathsid, final String pathrevision) { + this.pathsid = pathsid; + this.pathrevision = pathrevision; } + @Override public FlowRevision fetch(final TwilioRestClient client) { + String path = "/v2/Flows/{Sid}/Revisions/{Revision}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); - path = - path.replace("{" + "Revision" + "}", this.pathRevision.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + path = path.replace("{" + "Revision" + "}", this.pathrevision.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.STUDIO.toString(), - path + HttpMethod.GET, + Domains.STUDIO.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "FlowRevision fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("FlowRevision fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return FlowRevision.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return FlowRevision.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/studio/v2/flow/FlowRevisionReader.java b/src/main/java/com/twilio/rest/studio/v2/flow/FlowRevisionReader.java index c6a712fb1f..b47f40e7c0 100644 --- a/src/main/java/com/twilio/rest/studio/v2/flow/FlowRevisionReader.java +++ b/src/main/java/com/twilio/rest/studio/v2/flow/FlowRevisionReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,111 +30,88 @@ public class FlowRevisionReader extends Reader { - private String pathSid; + private String pathsid; private Long pageSize; - public FlowRevisionReader(final String pathSid) { - this.pathSid = pathSid; + public FlowRevisionReader(final String pathsid) { + this.pathsid = pathsid; } + public FlowRevisionReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v2/Flows/{Sid}/Revisions"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.STUDIO.toString(), - path + HttpMethod.GET, + Domains.STUDIO.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "FlowRevision read failed: Unable to connect to server" - ); + throw new ApiConnectionException("FlowRevision read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "revisions", - response.getContent(), - FlowRevision.class, - client.getObjectMapper() - ); + "revisions", + response.getContent(), + FlowRevision.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.STUDIO.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.STUDIO.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/studio/v2/flow/FlowTestUser.java b/src/main/java/com/twilio/rest/studio/v2/flow/FlowTestUser.java index ebd2459378..1b4d07837e 100644 --- a/src/main/java/com/twilio/rest/studio/v2/flow/FlowTestUser.java +++ b/src/main/java/com/twilio/rest/studio/v2/flow/FlowTestUser.java @@ -18,47 +18,48 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.util.List; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class FlowTestUser extends Resource { - private static final long serialVersionUID = 221844198208701L; - public static FlowTestUserFetcher fetcher(final String pathSid) { - return new FlowTestUserFetcher(pathSid); + public static FlowTestUserFetcher fetcher(final String pathsid) { + return new FlowTestUserFetcher( + pathsid + ); } - public static FlowTestUserUpdater updater( - final String pathSid, - final List testUsers - ) { - return new FlowTestUserUpdater(pathSid, testUsers); + + public static FlowTestUserUpdater updater(final String pathsid, final List testUsers) { + return new FlowTestUserUpdater( + pathsid, testUsers + ); } + /** * Converts a JSON String into a FlowTestUser object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return FlowTestUser object represented by the provided JSON */ - public static FlowTestUser fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static FlowTestUser fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, FlowTestUser.class); @@ -73,14 +74,11 @@ public static FlowTestUser fromJson( * Converts a JSON InputStream into a FlowTestUser object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return FlowTestUser object represented by the provided JSON */ - public static FlowTestUser fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static FlowTestUser fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, FlowTestUser.class); @@ -91,33 +89,37 @@ public static FlowTestUser fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String sid; + @Getter private final List testUsers; + @Getter private final URI url; @JsonCreator private FlowTestUser( - @JsonProperty("sid") final String sid, - @JsonProperty("test_users") final List testUsers, - @JsonProperty("url") final URI url + @JsonProperty("sid") final String sid, + @JsonProperty("test_users") final List testUsers, + @JsonProperty("url") final URI url ) { this.sid = sid; this.testUsers = testUsers; this.url = url; } - public final String getSid() { - return this.sid; - } - - public final List getTestUsers() { - return this.testUsers; - } - - public final URI getUrl() { - return this.url; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -129,16 +131,22 @@ public boolean equals(final Object o) { } FlowTestUser other = (FlowTestUser) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(testUsers, other.testUsers) && - Objects.equals(url, other.url) + Objects.equals(sid, other.sid) && + Objects.equals(testUsers, other.testUsers) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { - return Objects.hash(sid, testUsers, url); + return Objects.hash( + sid, + testUsers, + url + ); } + + } + diff --git a/src/main/java/com/twilio/rest/studio/v2/flow/FlowTestUserFetcher.java b/src/main/java/com/twilio/rest/studio/v2/flow/FlowTestUserFetcher.java index 118a438ffa..f550834835 100644 --- a/src/main/java/com/twilio/rest/studio/v2/flow/FlowTestUserFetcher.java +++ b/src/main/java/com/twilio/rest/studio/v2/flow/FlowTestUserFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.studio.v2.flow; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,47 +26,41 @@ public class FlowTestUserFetcher extends Fetcher { - private String pathSid; + private String pathsid; - public FlowTestUserFetcher(final String pathSid) { - this.pathSid = pathSid; + public FlowTestUserFetcher(final String pathsid) { + this.pathsid = pathsid; } + @Override public FlowTestUser fetch(final TwilioRestClient client) { + String path = "/v2/Flows/{Sid}/TestUsers"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.STUDIO.toString(), - path + HttpMethod.GET, + Domains.STUDIO.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "FlowTestUser fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("FlowTestUser fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return FlowTestUser.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return FlowTestUser.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/studio/v2/flow/FlowTestUserUpdater.java b/src/main/java/com/twilio/rest/studio/v2/flow/FlowTestUserUpdater.java index 2c4f2eb5fc..0817168f59 100644 --- a/src/main/java/com/twilio/rest/studio/v2/flow/FlowTestUserUpdater.java +++ b/src/main/java/com/twilio/rest/studio/v2/flow/FlowTestUserUpdater.java @@ -16,7 +16,9 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; import com.twilio.converter.Promoter; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,21 +27,19 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.util.List; public class FlowTestUserUpdater extends Updater { - - private String pathSid; + private String pathsid; private List testUsers; - public FlowTestUserUpdater( - final String pathSid, - final List testUsers - ) { - this.pathSid = pathSid; + public FlowTestUserUpdater(final String pathsid, final List testUsers) { + this.pathsid = pathsid; this.testUsers = testUsers; } + public FlowTestUserUpdater setTestUsers(final List testUsers) { this.testUsers = testUsers; return this; @@ -51,48 +51,46 @@ public FlowTestUserUpdater setTestUsers(final String testUsers) { @Override public FlowTestUser update(final TwilioRestClient client) { + String path = "/v2/Flows/{Sid}/TestUsers"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); - path = path.replace("{" + "TestUsers" + "}", this.testUsers.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.STUDIO.toString(), - path + HttpMethod.POST, + Domains.STUDIO.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "FlowTestUser update failed: Unable to connect to server" - ); + throw new ApiConnectionException("FlowTestUser update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return FlowTestUser.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return FlowTestUser.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + + if (testUsers != null) { - for (String prop : testUsers) { - request.addPostParam("TestUsers", prop); + for (String param : testUsers) { + Serializer.toString(request, "TestUsers", param, ParameterType.URLENCODED); } } + } } diff --git a/src/main/java/com/twilio/rest/studio/v2/flow/execution/ExecutionContext.java b/src/main/java/com/twilio/rest/studio/v2/flow/execution/ExecutionContext.java index 1e48c85839..a1ba25784a 100644 --- a/src/main/java/com/twilio/rest/studio/v2/flow/execution/ExecutionContext.java +++ b/src/main/java/com/twilio/rest/studio/v2/flow/execution/ExecutionContext.java @@ -18,44 +18,40 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; -import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class ExecutionContext extends Resource { - private static final long serialVersionUID = 48761390116247L; - public static ExecutionContextFetcher fetcher( - final String pathFlowSid, - final String pathExecutionSid - ) { - return new ExecutionContextFetcher(pathFlowSid, pathExecutionSid); + public static ExecutionContextFetcher fetcher(final String pathflowSid, final String pathexecutionSid) { + return new ExecutionContextFetcher( + pathflowSid, pathexecutionSid + ); } + /** * Converts a JSON String into a ExecutionContext object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return ExecutionContext object represented by the provided JSON */ - public static ExecutionContext fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static ExecutionContext fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, ExecutionContext.class); @@ -70,14 +66,11 @@ public static ExecutionContext fromJson( * Converts a JSON InputStream into a ExecutionContext object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return ExecutionContext object represented by the provided JSON */ - public static ExecutionContext fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static ExecutionContext fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, ExecutionContext.class); @@ -88,47 +81,45 @@ public static ExecutionContext fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final Map context; - private final String flowSid; + @Getter + private final Object context; + @Getter private final String executionSid; + @Getter + private final String flowSid; + @Getter private final URI url; @JsonCreator private ExecutionContext( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("context") final Map context, - @JsonProperty("flow_sid") final String flowSid, - @JsonProperty("execution_sid") final String executionSid, - @JsonProperty("url") final URI url + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("context") final Object context, + @JsonProperty("execution_sid") final String executionSid, + @JsonProperty("flow_sid") final String flowSid, + @JsonProperty("url") final URI url ) { this.accountSid = accountSid; this.context = context; - this.flowSid = flowSid; this.executionSid = executionSid; + this.flowSid = flowSid; this.url = url; } - public final String getAccountSid() { - return this.accountSid; - } - - public final Map getContext() { - return this.context; - } - - public final String getFlowSid() { - return this.flowSid; - } - - public final String getExecutionSid() { - return this.executionSid; - } - - public final URI getUrl() { - return this.url; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -140,18 +131,26 @@ public boolean equals(final Object o) { } ExecutionContext other = (ExecutionContext) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(context, other.context) && - Objects.equals(flowSid, other.flowSid) && - Objects.equals(executionSid, other.executionSid) && - Objects.equals(url, other.url) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(context, other.context) && + Objects.equals(executionSid, other.executionSid) && + Objects.equals(flowSid, other.flowSid) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { - return Objects.hash(accountSid, context, flowSid, executionSid, url); + return Objects.hash( + accountSid, + context, + executionSid, + flowSid, + url + ); } + + } + diff --git a/src/main/java/com/twilio/rest/studio/v2/flow/execution/ExecutionContextFetcher.java b/src/main/java/com/twilio/rest/studio/v2/flow/execution/ExecutionContextFetcher.java index 94941a7d21..4840753335 100644 --- a/src/main/java/com/twilio/rest/studio/v2/flow/execution/ExecutionContextFetcher.java +++ b/src/main/java/com/twilio/rest/studio/v2/flow/execution/ExecutionContextFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.studio.v2.flow.execution; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,57 +26,44 @@ public class ExecutionContextFetcher extends Fetcher { - private String pathFlowSid; - private String pathExecutionSid; + private String pathflowSid; + private String pathexecutionSid; - public ExecutionContextFetcher( - final String pathFlowSid, - final String pathExecutionSid - ) { - this.pathFlowSid = pathFlowSid; - this.pathExecutionSid = pathExecutionSid; + public ExecutionContextFetcher(final String pathflowSid, final String pathexecutionSid) { + this.pathflowSid = pathflowSid; + this.pathexecutionSid = pathexecutionSid; } + @Override public ExecutionContext fetch(final TwilioRestClient client) { + String path = "/v2/Flows/{FlowSid}/Executions/{ExecutionSid}/Context"; - path = path.replace("{" + "FlowSid" + "}", this.pathFlowSid.toString()); - path = - path.replace( - "{" + "ExecutionSid" + "}", - this.pathExecutionSid.toString() - ); + path = path.replace("{" + "FlowSid" + "}", this.pathflowSid.toString()); + path = path.replace("{" + "ExecutionSid" + "}", this.pathexecutionSid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.STUDIO.toString(), - path + HttpMethod.GET, + Domains.STUDIO.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "ExecutionContext fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("ExecutionContext fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return ExecutionContext.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return ExecutionContext.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/studio/v2/flow/execution/ExecutionStep.java b/src/main/java/com/twilio/rest/studio/v2/flow/execution/ExecutionStep.java index 48c1ebd0de..7c7571ccb2 100644 --- a/src/main/java/com/twilio/rest/studio/v2/flow/execution/ExecutionStep.java +++ b/src/main/java/com/twilio/rest/studio/v2/flow/execution/ExecutionStep.java @@ -18,54 +18,50 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class ExecutionStep extends Resource { - private static final long serialVersionUID = 221887175359099L; - public static ExecutionStepFetcher fetcher( - final String pathFlowSid, - final String pathExecutionSid, - final String pathSid - ) { - return new ExecutionStepFetcher(pathFlowSid, pathExecutionSid, pathSid); + public static ExecutionStepFetcher fetcher(final String pathflowSid, final String pathexecutionSid, final String pathsid) { + return new ExecutionStepFetcher( + pathflowSid, pathexecutionSid, pathsid + ); } - public static ExecutionStepReader reader( - final String pathFlowSid, - final String pathExecutionSid - ) { - return new ExecutionStepReader(pathFlowSid, pathExecutionSid); + + public static ExecutionStepReader reader(final String pathflowSid, final String pathexecutionSid) { + return new ExecutionStepReader( + pathflowSid, pathexecutionSid + ); } + /** * Converts a JSON String into a ExecutionStep object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return ExecutionStep object represented by the provided JSON */ - public static ExecutionStep fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static ExecutionStep fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, ExecutionStep.class); @@ -80,14 +76,11 @@ public static ExecutionStep fromJson( * Converts a JSON InputStream into a ExecutionStep object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return ExecutionStep object represented by the provided JSON */ - public static ExecutionStep fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static ExecutionStep fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, ExecutionStep.class); @@ -98,108 +91,81 @@ public static ExecutionStep fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String flowSid; + @Getter + private final Object context; + @Getter + private final ZonedDateTime dateCreated; + @Getter + private final ZonedDateTime dateUpdated; + @Getter private final String executionSid; - private final String parentStepSid; + @Getter + private final String flowSid; + @Getter + private final Map links; + @Getter private final String name; - private final Map context; + @Getter + private final String parentStepSid; + @Getter + private final String sid; + @Getter private final String transitionedFrom; + @Getter private final String transitionedTo; + @Getter private final String type; - private final ZonedDateTime dateCreated; - private final ZonedDateTime dateUpdated; + @Getter private final URI url; - private final Map links; @JsonCreator private ExecutionStep( - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("flow_sid") final String flowSid, - @JsonProperty("execution_sid") final String executionSid, - @JsonProperty("parent_step_sid") final String parentStepSid, - @JsonProperty("name") final String name, - @JsonProperty("context") final Map context, - @JsonProperty("transitioned_from") final String transitionedFrom, - @JsonProperty("transitioned_to") final String transitionedTo, - @JsonProperty("type") final String type, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("url") final URI url, - @JsonProperty("links") final Map links + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("context") final Object context, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("execution_sid") final String executionSid, + @JsonProperty("flow_sid") final String flowSid, + @JsonProperty("links") final Map links, + @JsonProperty("name") final String name, + @JsonProperty("parent_step_sid") final String parentStepSid, + @JsonProperty("sid") final String sid, + @JsonProperty("transitioned_from") final String transitionedFrom, + @JsonProperty("transitioned_to") final String transitionedTo, + @JsonProperty("type") final String type, + @JsonProperty("url") final URI url ) { - this.sid = sid; this.accountSid = accountSid; - this.flowSid = flowSid; + this.context = context; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.executionSid = executionSid; - this.parentStepSid = parentStepSid; + this.flowSid = flowSid; + this.links = links; this.name = name; - this.context = context; + this.parentStepSid = parentStepSid; + this.sid = sid; this.transitionedFrom = transitionedFrom; this.transitionedTo = transitionedTo; this.type = type; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); this.url = url; - this.links = links; - } - - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getFlowSid() { - return this.flowSid; - } - - public final String getExecutionSid() { - return this.executionSid; - } - - public final String getParentStepSid() { - return this.parentStepSid; - } - - public final String getName() { - return this.name; - } - - public final Map getContext() { - return this.context; - } - - public final String getTransitionedFrom() { - return this.transitionedFrom; - } - - public final String getTransitionedTo() { - return this.transitionedTo; - } - - public final String getType() { - return this.type; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final URI getUrl() { - return this.url; - } - - public final Map getLinks() { - return this.links; } @Override @@ -213,42 +179,44 @@ public boolean equals(final Object o) { } ExecutionStep other = (ExecutionStep) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(flowSid, other.flowSid) && - Objects.equals(executionSid, other.executionSid) && - Objects.equals(parentStepSid, other.parentStepSid) && - Objects.equals(name, other.name) && - Objects.equals(context, other.context) && - Objects.equals(transitionedFrom, other.transitionedFrom) && - Objects.equals(transitionedTo, other.transitionedTo) && - Objects.equals(type, other.type) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(url, other.url) && - Objects.equals(links, other.links) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(context, other.context) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(executionSid, other.executionSid) && + Objects.equals(flowSid, other.flowSid) && + Objects.equals(links, other.links) && + Objects.equals(name, other.name) && + Objects.equals(parentStepSid, other.parentStepSid) && + Objects.equals(sid, other.sid) && + Objects.equals(transitionedFrom, other.transitionedFrom) && + Objects.equals(transitionedTo, other.transitionedTo) && + Objects.equals(type, other.type) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - sid, - accountSid, - flowSid, - executionSid, - parentStepSid, - name, - context, - transitionedFrom, - transitionedTo, - type, - dateCreated, - dateUpdated, - url, - links + accountSid, + context, + dateCreated, + dateUpdated, + executionSid, + flowSid, + links, + name, + parentStepSid, + sid, + transitionedFrom, + transitionedTo, + type, + url ); } + + } + diff --git a/src/main/java/com/twilio/rest/studio/v2/flow/execution/ExecutionStepFetcher.java b/src/main/java/com/twilio/rest/studio/v2/flow/execution/ExecutionStepFetcher.java index e8502006b0..6e91d0dcc0 100644 --- a/src/main/java/com/twilio/rest/studio/v2/flow/execution/ExecutionStepFetcher.java +++ b/src/main/java/com/twilio/rest/studio/v2/flow/execution/ExecutionStepFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.studio.v2.flow.execution; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,62 +26,47 @@ public class ExecutionStepFetcher extends Fetcher { - private String pathFlowSid; - private String pathExecutionSid; - private String pathSid; + private String pathflowSid; + private String pathexecutionSid; + private String pathsid; - public ExecutionStepFetcher( - final String pathFlowSid, - final String pathExecutionSid, - final String pathSid - ) { - this.pathFlowSid = pathFlowSid; - this.pathExecutionSid = pathExecutionSid; - this.pathSid = pathSid; + public ExecutionStepFetcher(final String pathflowSid, final String pathexecutionSid, final String pathsid) { + this.pathflowSid = pathflowSid; + this.pathexecutionSid = pathexecutionSid; + this.pathsid = pathsid; } + @Override public ExecutionStep fetch(final TwilioRestClient client) { - String path = - "/v2/Flows/{FlowSid}/Executions/{ExecutionSid}/Steps/{Sid}"; - path = path.replace("{" + "FlowSid" + "}", this.pathFlowSid.toString()); - path = - path.replace( - "{" + "ExecutionSid" + "}", - this.pathExecutionSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/v2/Flows/{FlowSid}/Executions/{ExecutionSid}/Steps/{Sid}"; + + path = path.replace("{" + "FlowSid" + "}", this.pathflowSid.toString()); + path = path.replace("{" + "ExecutionSid" + "}", this.pathexecutionSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.STUDIO.toString(), - path + HttpMethod.GET, + Domains.STUDIO.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "ExecutionStep fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("ExecutionStep fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return ExecutionStep.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return ExecutionStep.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/studio/v2/flow/execution/ExecutionStepReader.java b/src/main/java/com/twilio/rest/studio/v2/flow/execution/ExecutionStepReader.java index ae4f268574..2e89b84231 100644 --- a/src/main/java/com/twilio/rest/studio/v2/flow/execution/ExecutionStepReader.java +++ b/src/main/java/com/twilio/rest/studio/v2/flow/execution/ExecutionStepReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,121 +30,91 @@ public class ExecutionStepReader extends Reader { - private String pathFlowSid; - private String pathExecutionSid; + private String pathflowSid; + private String pathexecutionSid; private Long pageSize; - public ExecutionStepReader( - final String pathFlowSid, - final String pathExecutionSid - ) { - this.pathFlowSid = pathFlowSid; - this.pathExecutionSid = pathExecutionSid; + public ExecutionStepReader(final String pathflowSid, final String pathexecutionSid) { + this.pathflowSid = pathflowSid; + this.pathexecutionSid = pathexecutionSid; } + public ExecutionStepReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v2/Flows/{FlowSid}/Executions/{ExecutionSid}/Steps"; - path = path.replace("{" + "FlowSid" + "}", this.pathFlowSid.toString()); - path = - path.replace( - "{" + "ExecutionSid" + "}", - this.pathExecutionSid.toString() - ); + + path = path.replace("{" + "FlowSid" + "}", this.pathflowSid.toString()); + path = path.replace("{" + "ExecutionSid" + "}", this.pathexecutionSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.STUDIO.toString(), - path + HttpMethod.GET, + Domains.STUDIO.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "ExecutionStep read failed: Unable to connect to server" - ); + throw new ApiConnectionException("ExecutionStep read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "steps", - response.getContent(), - ExecutionStep.class, - client.getObjectMapper() - ); + "steps", + response.getContent(), + ExecutionStep.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.STUDIO.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.STUDIO.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/studio/v2/flow/execution/executionstep/ExecutionStepContext.java b/src/main/java/com/twilio/rest/studio/v2/flow/execution/executionstep/ExecutionStepContext.java index 384675effe..4b0e576437 100644 --- a/src/main/java/com/twilio/rest/studio/v2/flow/execution/executionstep/ExecutionStepContext.java +++ b/src/main/java/com/twilio/rest/studio/v2/flow/execution/executionstep/ExecutionStepContext.java @@ -18,49 +18,40 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; -import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class ExecutionStepContext extends Resource { - private static final long serialVersionUID = 28705359719021L; - public static ExecutionStepContextFetcher fetcher( - final String pathFlowSid, - final String pathExecutionSid, - final String pathStepSid - ) { + public static ExecutionStepContextFetcher fetcher(final String pathflowSid, final String pathexecutionSid, final String pathstepSid) { return new ExecutionStepContextFetcher( - pathFlowSid, - pathExecutionSid, - pathStepSid + pathflowSid, pathexecutionSid, pathstepSid ); } + /** * Converts a JSON String into a ExecutionStepContext object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return ExecutionStepContext object represented by the provided JSON */ - public static ExecutionStepContext fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static ExecutionStepContext fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, ExecutionStepContext.class); @@ -75,14 +66,11 @@ public static ExecutionStepContext fromJson( * Converts a JSON InputStream into a ExecutionStepContext object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return ExecutionStepContext object represented by the provided JSON */ - public static ExecutionStepContext fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static ExecutionStepContext fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, ExecutionStepContext.class); @@ -93,21 +81,40 @@ public static ExecutionStepContext fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final Map context; + @Getter + private final Object context; + @Getter private final String executionSid; + @Getter private final String flowSid; + @Getter private final String stepSid; + @Getter private final URI url; @JsonCreator private ExecutionStepContext( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("context") final Map context, - @JsonProperty("execution_sid") final String executionSid, - @JsonProperty("flow_sid") final String flowSid, - @JsonProperty("step_sid") final String stepSid, - @JsonProperty("url") final URI url + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("context") final Object context, + @JsonProperty("execution_sid") final String executionSid, + @JsonProperty("flow_sid") final String flowSid, + @JsonProperty("step_sid") final String stepSid, + @JsonProperty("url") final URI url ) { this.accountSid = accountSid; this.context = context; @@ -117,30 +124,6 @@ private ExecutionStepContext( this.url = url; } - public final String getAccountSid() { - return this.accountSid; - } - - public final Map getContext() { - return this.context; - } - - public final String getExecutionSid() { - return this.executionSid; - } - - public final String getFlowSid() { - return this.flowSid; - } - - public final String getStepSid() { - return this.stepSid; - } - - public final URI getUrl() { - return this.url; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -152,26 +135,28 @@ public boolean equals(final Object o) { } ExecutionStepContext other = (ExecutionStepContext) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(context, other.context) && - Objects.equals(executionSid, other.executionSid) && - Objects.equals(flowSid, other.flowSid) && - Objects.equals(stepSid, other.stepSid) && - Objects.equals(url, other.url) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(context, other.context) && + Objects.equals(executionSid, other.executionSid) && + Objects.equals(flowSid, other.flowSid) && + Objects.equals(stepSid, other.stepSid) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - accountSid, - context, - executionSid, - flowSid, - stepSid, - url + accountSid, + context, + executionSid, + flowSid, + stepSid, + url ); } + + } + diff --git a/src/main/java/com/twilio/rest/studio/v2/flow/execution/executionstep/ExecutionStepContextFetcher.java b/src/main/java/com/twilio/rest/studio/v2/flow/execution/executionstep/ExecutionStepContextFetcher.java index be9e3b7852..31f2fda862 100644 --- a/src/main/java/com/twilio/rest/studio/v2/flow/execution/executionstep/ExecutionStepContextFetcher.java +++ b/src/main/java/com/twilio/rest/studio/v2/flow/execution/executionstep/ExecutionStepContextFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.studio.v2.flow.execution.executionstep; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,62 +26,47 @@ public class ExecutionStepContextFetcher extends Fetcher { - private String pathFlowSid; - private String pathExecutionSid; - private String pathStepSid; + private String pathflowSid; + private String pathexecutionSid; + private String pathstepSid; - public ExecutionStepContextFetcher( - final String pathFlowSid, - final String pathExecutionSid, - final String pathStepSid - ) { - this.pathFlowSid = pathFlowSid; - this.pathExecutionSid = pathExecutionSid; - this.pathStepSid = pathStepSid; + public ExecutionStepContextFetcher(final String pathflowSid, final String pathexecutionSid, final String pathstepSid) { + this.pathflowSid = pathflowSid; + this.pathexecutionSid = pathexecutionSid; + this.pathstepSid = pathstepSid; } + @Override public ExecutionStepContext fetch(final TwilioRestClient client) { - String path = - "/v2/Flows/{FlowSid}/Executions/{ExecutionSid}/Steps/{StepSid}/Context"; - path = path.replace("{" + "FlowSid" + "}", this.pathFlowSid.toString()); - path = - path.replace( - "{" + "ExecutionSid" + "}", - this.pathExecutionSid.toString() - ); - path = path.replace("{" + "StepSid" + "}", this.pathStepSid.toString()); + String path = "/v2/Flows/{FlowSid}/Executions/{ExecutionSid}/Steps/{StepSid}/Context"; + + path = path.replace("{" + "FlowSid" + "}", this.pathflowSid.toString()); + path = path.replace("{" + "ExecutionSid" + "}", this.pathexecutionSid.toString()); + path = path.replace("{" + "StepSid" + "}", this.pathstepSid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.STUDIO.toString(), - path + HttpMethod.GET, + Domains.STUDIO.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "ExecutionStepContext fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("ExecutionStepContext fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return ExecutionStepContext.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return ExecutionStepContext.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/supersim/v1/EsimProfile.java b/src/main/java/com/twilio/rest/supersim/v1/EsimProfile.java index 5d3e1b08eb..f02b68a582 100644 --- a/src/main/java/com/twilio/rest/supersim/v1/EsimProfile.java +++ b/src/main/java/com/twilio/rest/supersim/v1/EsimProfile.java @@ -18,50 +18,82 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class EsimProfile extends Resource { - private static final long serialVersionUID = 165735118410901L; public static EsimProfileCreator creator() { - return new EsimProfileCreator(); + return new EsimProfileCreator( + + ); } - public static EsimProfileFetcher fetcher(final String pathSid) { - return new EsimProfileFetcher(pathSid); + + public static EsimProfileFetcher fetcher(final String pathsid) { + return new EsimProfileFetcher( + pathsid + ); } + public static EsimProfileReader reader() { - return new EsimProfileReader(); + return new EsimProfileReader( + + ); + } + + + public enum Status { + NEW("new"), + RESERVING("reserving"), + AVAILABLE("available"), + DOWNLOADED("downloaded"), + INSTALLED("installed"), + FAILED("failed"); + + private final String value; + + private Status(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static Status forValue(final String value) { + return Promoter.enumFromString(value, Status.values()); + } } + /** * Converts a JSON String into a EsimProfile object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return EsimProfile object represented by the provided JSON */ - public static EsimProfile fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static EsimProfile fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, EsimProfile.class); @@ -76,14 +108,11 @@ public static EsimProfile fromJson( * Converts a JSON InputStream into a EsimProfile object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return EsimProfile object represented by the provided JSON */ - public static EsimProfile fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static EsimProfile fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, EsimProfile.class); @@ -94,110 +123,83 @@ public static EsimProfile fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String iccid; - private final String simSid; - private final EsimProfile.Status status; - private final String eid; - private final URI smdpPlusAddress; - private final String matchingId; + @Getter private final String activationCode; - private final String errorCode; - private final String errorMessage; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; + @Getter + private final String eid; + @Getter + private final String errorCode; + @Getter + private final String errorMessage; + @Getter + private final String iccid; + @Getter + private final String matchingId; + @Getter + private final String sid; + @Getter + private final String simSid; + @Getter + private final URI smdpPlusAddress; + @Getter + private final EsimProfile.Status status; + @Getter private final URI url; @JsonCreator private EsimProfile( - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("iccid") final String iccid, - @JsonProperty("sim_sid") final String simSid, - @JsonProperty("status") final EsimProfile.Status status, - @JsonProperty("eid") final String eid, - @JsonProperty("smdp_plus_address") final URI smdpPlusAddress, - @JsonProperty("matching_id") final String matchingId, - @JsonProperty("activation_code") final String activationCode, - @JsonProperty("error_code") final String errorCode, - @JsonProperty("error_message") final String errorMessage, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("url") final URI url + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("activation_code") final String activationCode, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("eid") final String eid, + @JsonProperty("error_code") final String errorCode, + @JsonProperty("error_message") final String errorMessage, + @JsonProperty("iccid") final String iccid, + @JsonProperty("matching_id") final String matchingId, + @JsonProperty("sid") final String sid, + @JsonProperty("sim_sid") final String simSid, + @JsonProperty("smdp_plus_address") final URI smdpPlusAddress, + @JsonProperty("status") final EsimProfile.Status status, + @JsonProperty("url") final URI url ) { - this.sid = sid; this.accountSid = accountSid; - this.iccid = iccid; - this.simSid = simSid; - this.status = status; - this.eid = eid; - this.smdpPlusAddress = smdpPlusAddress; - this.matchingId = matchingId; this.activationCode = activationCode; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; + this.eid = eid; this.errorCode = errorCode; this.errorMessage = errorMessage; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); + this.iccid = iccid; + this.matchingId = matchingId; + this.sid = sid; + this.simSid = simSid; + this.smdpPlusAddress = smdpPlusAddress; + this.status = status; this.url = url; } - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getIccid() { - return this.iccid; - } - - public final String getSimSid() { - return this.simSid; - } - - public final EsimProfile.Status getStatus() { - return this.status; - } - - public final String getEid() { - return this.eid; - } - - public final URI getSmdpPlusAddress() { - return this.smdpPlusAddress; - } - - public final String getMatchingId() { - return this.matchingId; - } - - public final String getActivationCode() { - return this.activationCode; - } - - public final String getErrorCode() { - return this.errorCode; - } - - public final String getErrorMessage() { - return this.errorMessage; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final URI getUrl() { - return this.url; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -209,66 +211,44 @@ public boolean equals(final Object o) { } EsimProfile other = (EsimProfile) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(iccid, other.iccid) && - Objects.equals(simSid, other.simSid) && - Objects.equals(status, other.status) && - Objects.equals(eid, other.eid) && - Objects.equals(smdpPlusAddress, other.smdpPlusAddress) && - Objects.equals(matchingId, other.matchingId) && - Objects.equals(activationCode, other.activationCode) && - Objects.equals(errorCode, other.errorCode) && - Objects.equals(errorMessage, other.errorMessage) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(url, other.url) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(activationCode, other.activationCode) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(eid, other.eid) && + Objects.equals(errorCode, other.errorCode) && + Objects.equals(errorMessage, other.errorMessage) && + Objects.equals(iccid, other.iccid) && + Objects.equals(matchingId, other.matchingId) && + Objects.equals(sid, other.sid) && + Objects.equals(simSid, other.simSid) && + Objects.equals(smdpPlusAddress, other.smdpPlusAddress) && + Objects.equals(status, other.status) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - sid, - accountSid, - iccid, - simSid, - status, - eid, - smdpPlusAddress, - matchingId, - activationCode, - errorCode, - errorMessage, - dateCreated, - dateUpdated, - url + accountSid, + activationCode, + dateCreated, + dateUpdated, + eid, + errorCode, + errorMessage, + iccid, + matchingId, + sid, + simSid, + smdpPlusAddress, + status, + url ); } - public enum Status { - NEW("new"), - RESERVING("reserving"), - AVAILABLE("available"), - DOWNLOADED("downloaded"), - INSTALLED("installed"), - FAILED("failed"); - private final String value; - - private Status(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static Status forValue(final String value) { - return Promoter.enumFromString(value, Status.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/supersim/v1/EsimProfileCreator.java b/src/main/java/com/twilio/rest/supersim/v1/EsimProfileCreator.java index 5c712be413..6003387626 100644 --- a/src/main/java/com/twilio/rest/supersim/v1/EsimProfileCreator.java +++ b/src/main/java/com/twilio/rest/supersim/v1/EsimProfileCreator.java @@ -14,8 +14,11 @@ package com.twilio.rest.supersim.v1; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -32,83 +35,87 @@ public class EsimProfileCreator extends Creator { private Boolean generateMatchingId; private String eid; - public EsimProfileCreator() {} + public EsimProfileCreator() { + } + public EsimProfileCreator setCallbackUrl(final String callbackUrl) { this.callbackUrl = callbackUrl; return this; } - public EsimProfileCreator setCallbackMethod( - final HttpMethod callbackMethod - ) { + + public EsimProfileCreator setCallbackMethod(final HttpMethod callbackMethod) { this.callbackMethod = callbackMethod; return this; } - public EsimProfileCreator setGenerateMatchingId( - final Boolean generateMatchingId - ) { + + public EsimProfileCreator setGenerateMatchingId(final Boolean generateMatchingId) { this.generateMatchingId = generateMatchingId; return this; } + public EsimProfileCreator setEid(final String eid) { this.eid = eid; return this; } + @Override public EsimProfile create(final TwilioRestClient client) { + String path = "/v1/ESimProfiles"; + Request request = new Request( - HttpMethod.POST, - Domains.SUPERSIM.toString(), - path + HttpMethod.POST, + Domains.SUPERSIM.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "EsimProfile creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("EsimProfile creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return EsimProfile.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return EsimProfile.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (callbackUrl != null) { - request.addPostParam("CallbackUrl", callbackUrl); + Serializer.toString(request, "CallbackUrl", callbackUrl, ParameterType.URLENCODED); } + + if (callbackMethod != null) { - request.addPostParam("CallbackMethod", callbackMethod.toString()); + Serializer.toString(request, "CallbackMethod", callbackMethod, ParameterType.URLENCODED); } + + if (generateMatchingId != null) { - request.addPostParam( - "GenerateMatchingId", - generateMatchingId.toString() - ); + Serializer.toString(request, "GenerateMatchingId", generateMatchingId, ParameterType.URLENCODED); } + + if (eid != null) { - request.addPostParam("Eid", eid); + Serializer.toString(request, "Eid", eid, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/supersim/v1/EsimProfileFetcher.java b/src/main/java/com/twilio/rest/supersim/v1/EsimProfileFetcher.java index 5a6e46a637..da433d4715 100644 --- a/src/main/java/com/twilio/rest/supersim/v1/EsimProfileFetcher.java +++ b/src/main/java/com/twilio/rest/supersim/v1/EsimProfileFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.supersim.v1; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,47 +26,41 @@ public class EsimProfileFetcher extends Fetcher { - private String pathSid; + private String pathsid; - public EsimProfileFetcher(final String pathSid) { - this.pathSid = pathSid; + public EsimProfileFetcher(final String pathsid) { + this.pathsid = pathsid; } + @Override public EsimProfile fetch(final TwilioRestClient client) { + String path = "/v1/ESimProfiles/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.SUPERSIM.toString(), - path + HttpMethod.GET, + Domains.SUPERSIM.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "EsimProfile fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("EsimProfile fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return EsimProfile.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return EsimProfile.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/supersim/v1/EsimProfileReader.java b/src/main/java/com/twilio/rest/supersim/v1/EsimProfileReader.java index 9ff34229c0..4580de7d92 100644 --- a/src/main/java/com/twilio/rest/supersim/v1/EsimProfileReader.java +++ b/src/main/java/com/twilio/rest/supersim/v1/EsimProfileReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -34,129 +35,116 @@ public class EsimProfileReader extends Reader { private EsimProfile.Status status; private Long pageSize; - public EsimProfileReader() {} + public EsimProfileReader() { + } + public EsimProfileReader setEid(final String eid) { this.eid = eid; return this; } + public EsimProfileReader setSimSid(final String simSid) { this.simSid = simSid; return this; } + public EsimProfileReader setStatus(final EsimProfile.Status status) { this.status = status; return this; } + public EsimProfileReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/ESimProfiles"; + Request request = new Request( - HttpMethod.GET, - Domains.SUPERSIM.toString(), - path + HttpMethod.GET, + Domains.SUPERSIM.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "EsimProfile read failed: Unable to connect to server" - ); + throw new ApiConnectionException("EsimProfile read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "esim_profiles", - response.getContent(), - EsimProfile.class, - client.getObjectMapper() - ); + "esim_profiles", + response.getContent(), + EsimProfile.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.SUPERSIM.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.SUPERSIM.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (eid != null) { - request.addQueryParam("Eid", eid); + Serializer.toString(request, "Eid", eid, ParameterType.QUERY); } + + if (simSid != null) { - request.addQueryParam("SimSid", simSid); + Serializer.toString(request, "SimSid", simSid, ParameterType.QUERY); } + + if (status != null) { - request.addQueryParam("Status", status.toString()); + Serializer.toString(request, "Status", status, ParameterType.QUERY); } + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/supersim/v1/Fleet.java b/src/main/java/com/twilio/rest/supersim/v1/Fleet.java index 19c54502b2..c3f3b72778 100644 --- a/src/main/java/com/twilio/rest/supersim/v1/Fleet.java +++ b/src/main/java/com/twilio/rest/supersim/v1/Fleet.java @@ -18,55 +18,85 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.http.HttpMethod; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Fleet extends Resource { - private static final long serialVersionUID = 74063802547191L; public static FleetCreator creator(final String networkAccessProfile) { - return new FleetCreator(networkAccessProfile); + return new FleetCreator( + networkAccessProfile + ); } - public static FleetFetcher fetcher(final String pathSid) { - return new FleetFetcher(pathSid); + + public static FleetFetcher fetcher(final String pathsid) { + return new FleetFetcher( + pathsid + ); } + public static FleetReader reader() { - return new FleetReader(); + return new FleetReader( + + ); + } + + + public static FleetUpdater updater(final String pathsid) { + return new FleetUpdater( + pathsid + ); } - public static FleetUpdater updater(final String pathSid) { - return new FleetUpdater(pathSid); + + public enum DataMetering { + PAYG("payg"); + + private final String value; + + private DataMetering(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static DataMetering forValue(final String value) { + return Promoter.enumFromString(value, DataMetering.values()); + } } + /** * Converts a JSON String into a Fleet object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Fleet object represented by the provided JSON */ - public static Fleet fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Fleet fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Fleet.class); @@ -81,14 +111,11 @@ public static Fleet fromJson( * Converts a JSON InputStream into a Fleet object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Fleet object represented by the provided JSON */ - public static Fleet fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Fleet fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Fleet.class); @@ -99,117 +126,85 @@ public static Fleet fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String sid; - private final String uniqueName; - private final ZonedDateTime dateCreated; - private final ZonedDateTime dateUpdated; - private final URI url; + @Getter private final Boolean dataEnabled; + @Getter private final Integer dataLimit; + @Getter private final Fleet.DataMetering dataMetering; + @Getter + private final ZonedDateTime dateCreated; + @Getter + private final ZonedDateTime dateUpdated; + @Getter + private final HttpMethod ipCommandsMethod; + @Getter + private final URI ipCommandsUrl; + @Getter + private final String networkAccessProfileSid; + @Getter + private final String sid; + @Getter private final Boolean smsCommandsEnabled; - private final URI smsCommandsUrl; + @Getter private final HttpMethod smsCommandsMethod; - private final String networkAccessProfileSid; - private final URI ipCommandsUrl; - private final HttpMethod ipCommandsMethod; + @Getter + private final URI smsCommandsUrl; + @Getter + private final String uniqueName; + @Getter + private final URI url; @JsonCreator private Fleet( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("sid") final String sid, - @JsonProperty("unique_name") final String uniqueName, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("url") final URI url, - @JsonProperty("data_enabled") final Boolean dataEnabled, - @JsonProperty("data_limit") final Integer dataLimit, - @JsonProperty("data_metering") final Fleet.DataMetering dataMetering, - @JsonProperty("sms_commands_enabled") final Boolean smsCommandsEnabled, - @JsonProperty("sms_commands_url") final URI smsCommandsUrl, - @JsonProperty("sms_commands_method") final HttpMethod smsCommandsMethod, - @JsonProperty( - "network_access_profile_sid" - ) final String networkAccessProfileSid, - @JsonProperty("ip_commands_url") final URI ipCommandsUrl, - @JsonProperty("ip_commands_method") final HttpMethod ipCommandsMethod + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("data_enabled") final Boolean dataEnabled, + @JsonProperty("data_limit") final Integer dataLimit, + @JsonProperty("data_metering") final Fleet.DataMetering dataMetering, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("ip_commands_method") final HttpMethod ipCommandsMethod, + @JsonProperty("ip_commands_url") final URI ipCommandsUrl, + @JsonProperty("network_access_profile_sid") final String networkAccessProfileSid, + @JsonProperty("sid") final String sid, + @JsonProperty("sms_commands_enabled") final Boolean smsCommandsEnabled, + @JsonProperty("sms_commands_method") final HttpMethod smsCommandsMethod, + @JsonProperty("sms_commands_url") final URI smsCommandsUrl, + @JsonProperty("unique_name") final String uniqueName, + @JsonProperty("url") final URI url ) { this.accountSid = accountSid; - this.sid = sid; - this.uniqueName = uniqueName; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); - this.url = url; this.dataEnabled = dataEnabled; this.dataLimit = dataLimit; this.dataMetering = dataMetering; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; + this.ipCommandsMethod = ipCommandsMethod; + this.ipCommandsUrl = ipCommandsUrl; + this.networkAccessProfileSid = networkAccessProfileSid; + this.sid = sid; this.smsCommandsEnabled = smsCommandsEnabled; - this.smsCommandsUrl = smsCommandsUrl; this.smsCommandsMethod = smsCommandsMethod; - this.networkAccessProfileSid = networkAccessProfileSid; - this.ipCommandsUrl = ipCommandsUrl; - this.ipCommandsMethod = ipCommandsMethod; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getSid() { - return this.sid; - } - - public final String getUniqueName() { - return this.uniqueName; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final URI getUrl() { - return this.url; - } - - public final Boolean getDataEnabled() { - return this.dataEnabled; - } - - public final Integer getDataLimit() { - return this.dataLimit; - } - - public final Fleet.DataMetering getDataMetering() { - return this.dataMetering; - } - - public final Boolean getSmsCommandsEnabled() { - return this.smsCommandsEnabled; - } - - public final URI getSmsCommandsUrl() { - return this.smsCommandsUrl; - } - - public final HttpMethod getSmsCommandsMethod() { - return this.smsCommandsMethod; - } - - public final String getNetworkAccessProfileSid() { - return this.networkAccessProfileSid; - } - - public final URI getIpCommandsUrl() { - return this.ipCommandsUrl; - } - - public final HttpMethod getIpCommandsMethod() { - return this.ipCommandsMethod; + this.smsCommandsUrl = smsCommandsUrl; + this.uniqueName = uniqueName; + this.url = url; } @Override @@ -223,66 +218,46 @@ public boolean equals(final Object o) { } Fleet other = (Fleet) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(sid, other.sid) && - Objects.equals(uniqueName, other.uniqueName) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(url, other.url) && - Objects.equals(dataEnabled, other.dataEnabled) && - Objects.equals(dataLimit, other.dataLimit) && - Objects.equals(dataMetering, other.dataMetering) && - Objects.equals(smsCommandsEnabled, other.smsCommandsEnabled) && - Objects.equals(smsCommandsUrl, other.smsCommandsUrl) && - Objects.equals(smsCommandsMethod, other.smsCommandsMethod) && - Objects.equals( - networkAccessProfileSid, - other.networkAccessProfileSid - ) && - Objects.equals(ipCommandsUrl, other.ipCommandsUrl) && - Objects.equals(ipCommandsMethod, other.ipCommandsMethod) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(dataEnabled, other.dataEnabled) && + Objects.equals(dataLimit, other.dataLimit) && + Objects.equals(dataMetering, other.dataMetering) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(ipCommandsMethod, other.ipCommandsMethod) && + Objects.equals(ipCommandsUrl, other.ipCommandsUrl) && + Objects.equals(networkAccessProfileSid, other.networkAccessProfileSid) && + Objects.equals(sid, other.sid) && + Objects.equals(smsCommandsEnabled, other.smsCommandsEnabled) && + Objects.equals(smsCommandsMethod, other.smsCommandsMethod) && + Objects.equals(smsCommandsUrl, other.smsCommandsUrl) && + Objects.equals(uniqueName, other.uniqueName) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - accountSid, - sid, - uniqueName, - dateCreated, - dateUpdated, - url, - dataEnabled, - dataLimit, - dataMetering, - smsCommandsEnabled, - smsCommandsUrl, - smsCommandsMethod, - networkAccessProfileSid, - ipCommandsUrl, - ipCommandsMethod + accountSid, + dataEnabled, + dataLimit, + dataMetering, + dateCreated, + dateUpdated, + ipCommandsMethod, + ipCommandsUrl, + networkAccessProfileSid, + sid, + smsCommandsEnabled, + smsCommandsMethod, + smsCommandsUrl, + uniqueName, + url ); } - public enum DataMetering { - PAYG("payg"); - private final String value; - - private DataMetering(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static DataMetering forValue(final String value) { - return Promoter.enumFromString(value, DataMetering.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/supersim/v1/FleetCreator.java b/src/main/java/com/twilio/rest/supersim/v1/FleetCreator.java index 098b48946c..f6f6dc3bc2 100644 --- a/src/main/java/com/twilio/rest/supersim/v1/FleetCreator.java +++ b/src/main/java/com/twilio/rest/supersim/v1/FleetCreator.java @@ -14,9 +14,11 @@ package com.twilio.rest.supersim.v1; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; -import com.twilio.converter.Promoter; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,7 +27,7 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -import java.net.URI; + import java.net.URI; public class FleetCreator extends Creator { @@ -44,97 +46,86 @@ public FleetCreator(final String networkAccessProfile) { this.networkAccessProfile = networkAccessProfile; } - public FleetCreator setNetworkAccessProfile( - final String networkAccessProfile - ) { + + public FleetCreator setNetworkAccessProfile(final String networkAccessProfile) { this.networkAccessProfile = networkAccessProfile; return this; } + public FleetCreator setUniqueName(final String uniqueName) { this.uniqueName = uniqueName; return this; } + public FleetCreator setDataEnabled(final Boolean dataEnabled) { this.dataEnabled = dataEnabled; return this; } + public FleetCreator setDataLimit(final Integer dataLimit) { this.dataLimit = dataLimit; return this; } + public FleetCreator setIpCommandsUrl(final URI ipCommandsUrl) { this.ipCommandsUrl = ipCommandsUrl; return this; } - public FleetCreator setIpCommandsUrl(final String ipCommandsUrl) { - return setIpCommandsUrl(Promoter.uriFromString(ipCommandsUrl)); - } public FleetCreator setIpCommandsMethod(final HttpMethod ipCommandsMethod) { this.ipCommandsMethod = ipCommandsMethod; return this; } - public FleetCreator setSmsCommandsEnabled( - final Boolean smsCommandsEnabled - ) { + + public FleetCreator setSmsCommandsEnabled(final Boolean smsCommandsEnabled) { this.smsCommandsEnabled = smsCommandsEnabled; return this; } + public FleetCreator setSmsCommandsUrl(final URI smsCommandsUrl) { this.smsCommandsUrl = smsCommandsUrl; return this; } - public FleetCreator setSmsCommandsUrl(final String smsCommandsUrl) { - return setSmsCommandsUrl(Promoter.uriFromString(smsCommandsUrl)); - } - public FleetCreator setSmsCommandsMethod( - final HttpMethod smsCommandsMethod - ) { + public FleetCreator setSmsCommandsMethod(final HttpMethod smsCommandsMethod) { this.smsCommandsMethod = smsCommandsMethod; return this; } + @Override public Fleet create(final TwilioRestClient client) { + String path = "/v1/Fleets"; - path = - path.replace( - "{" + "NetworkAccessProfile" + "}", - this.networkAccessProfile.toString() - ); Request request = new Request( - HttpMethod.POST, - Domains.SUPERSIM.toString(), - path + HttpMethod.POST, + Domains.SUPERSIM.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Fleet creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("Fleet creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -143,41 +134,51 @@ public Fleet create(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (networkAccessProfile != null) { - request.addPostParam("NetworkAccessProfile", networkAccessProfile); + Serializer.toString(request, "NetworkAccessProfile", networkAccessProfile, ParameterType.URLENCODED); } + + if (uniqueName != null) { - request.addPostParam("UniqueName", uniqueName); + Serializer.toString(request, "UniqueName", uniqueName, ParameterType.URLENCODED); } + + if (dataEnabled != null) { - request.addPostParam("DataEnabled", dataEnabled.toString()); + Serializer.toString(request, "DataEnabled", dataEnabled, ParameterType.URLENCODED); } + + if (dataLimit != null) { - request.addPostParam("DataLimit", dataLimit.toString()); + Serializer.toString(request, "DataLimit", dataLimit, ParameterType.URLENCODED); } + + if (ipCommandsUrl != null) { - request.addPostParam("IpCommandsUrl", ipCommandsUrl.toString()); + Serializer.toString(request, "IpCommandsUrl", ipCommandsUrl, ParameterType.URLENCODED); } + + if (ipCommandsMethod != null) { - request.addPostParam( - "IpCommandsMethod", - ipCommandsMethod.toString() - ); + Serializer.toString(request, "IpCommandsMethod", ipCommandsMethod, ParameterType.URLENCODED); } + + if (smsCommandsEnabled != null) { - request.addPostParam( - "SmsCommandsEnabled", - smsCommandsEnabled.toString() - ); + Serializer.toString(request, "SmsCommandsEnabled", smsCommandsEnabled, ParameterType.URLENCODED); } + + if (smsCommandsUrl != null) { - request.addPostParam("SmsCommandsUrl", smsCommandsUrl.toString()); + Serializer.toString(request, "SmsCommandsUrl", smsCommandsUrl, ParameterType.URLENCODED); } + + if (smsCommandsMethod != null) { - request.addPostParam( - "SmsCommandsMethod", - smsCommandsMethod.toString() - ); + Serializer.toString(request, "SmsCommandsMethod", smsCommandsMethod, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/supersim/v1/FleetFetcher.java b/src/main/java/com/twilio/rest/supersim/v1/FleetFetcher.java index c705348569..f14e443ab5 100644 --- a/src/main/java/com/twilio/rest/supersim/v1/FleetFetcher.java +++ b/src/main/java/com/twilio/rest/supersim/v1/FleetFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.supersim.v1; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,44 +26,41 @@ public class FleetFetcher extends Fetcher { - private String pathSid; + private String pathsid; - public FleetFetcher(final String pathSid) { - this.pathSid = pathSid; + public FleetFetcher(final String pathsid) { + this.pathsid = pathsid; } + @Override public Fleet fetch(final TwilioRestClient client) { + String path = "/v1/Fleets/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.SUPERSIM.toString(), - path + HttpMethod.GET, + Domains.SUPERSIM.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Fleet fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Fleet fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Fleet.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/supersim/v1/FleetReader.java b/src/main/java/com/twilio/rest/supersim/v1/FleetReader.java index 6a7428d0f8..d392ffc888 100644 --- a/src/main/java/com/twilio/rest/supersim/v1/FleetReader.java +++ b/src/main/java/com/twilio/rest/supersim/v1/FleetReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -32,115 +33,94 @@ public class FleetReader extends Reader { private String networkAccessProfile; private Long pageSize; - public FleetReader() {} + public FleetReader() { + } + - public FleetReader setNetworkAccessProfile( - final String networkAccessProfile - ) { + public FleetReader setNetworkAccessProfile(final String networkAccessProfile) { this.networkAccessProfile = networkAccessProfile; return this; } + public FleetReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/Fleets"; + Request request = new Request( - HttpMethod.GET, - Domains.SUPERSIM.toString(), - path + HttpMethod.GET, + Domains.SUPERSIM.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Fleet read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Fleet read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "fleets", - response.getContent(), - Fleet.class, - client.getObjectMapper() - ); + "fleets", + response.getContent(), + Fleet.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.SUPERSIM.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.SUPERSIM.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (networkAccessProfile != null) { - request.addQueryParam("NetworkAccessProfile", networkAccessProfile); + Serializer.toString(request, "NetworkAccessProfile", networkAccessProfile, ParameterType.QUERY); } + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/supersim/v1/FleetUpdater.java b/src/main/java/com/twilio/rest/supersim/v1/FleetUpdater.java index dc498ec1d8..234ccb06c2 100644 --- a/src/main/java/com/twilio/rest/supersim/v1/FleetUpdater.java +++ b/src/main/java/com/twilio/rest/supersim/v1/FleetUpdater.java @@ -16,7 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; -import com.twilio.converter.Promoter; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,11 +26,11 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.net.URI; public class FleetUpdater extends Updater { - - private String pathSid; + private String pathsid; private String uniqueName; private String networkAccessProfile; private URI ipCommandsUrl; @@ -38,85 +39,80 @@ public class FleetUpdater extends Updater { private HttpMethod smsCommandsMethod; private Integer dataLimit; - public FleetUpdater(final String pathSid) { - this.pathSid = pathSid; + public FleetUpdater(final String pathsid) { + this.pathsid = pathsid; } + public FleetUpdater setUniqueName(final String uniqueName) { this.uniqueName = uniqueName; return this; } - public FleetUpdater setNetworkAccessProfile( - final String networkAccessProfile - ) { + + public FleetUpdater setNetworkAccessProfile(final String networkAccessProfile) { this.networkAccessProfile = networkAccessProfile; return this; } + public FleetUpdater setIpCommandsUrl(final URI ipCommandsUrl) { this.ipCommandsUrl = ipCommandsUrl; return this; } - public FleetUpdater setIpCommandsUrl(final String ipCommandsUrl) { - return setIpCommandsUrl(Promoter.uriFromString(ipCommandsUrl)); - } public FleetUpdater setIpCommandsMethod(final HttpMethod ipCommandsMethod) { this.ipCommandsMethod = ipCommandsMethod; return this; } + public FleetUpdater setSmsCommandsUrl(final URI smsCommandsUrl) { this.smsCommandsUrl = smsCommandsUrl; return this; } - public FleetUpdater setSmsCommandsUrl(final String smsCommandsUrl) { - return setSmsCommandsUrl(Promoter.uriFromString(smsCommandsUrl)); - } - public FleetUpdater setSmsCommandsMethod( - final HttpMethod smsCommandsMethod - ) { + public FleetUpdater setSmsCommandsMethod(final HttpMethod smsCommandsMethod) { this.smsCommandsMethod = smsCommandsMethod; return this; } + public FleetUpdater setDataLimit(final Integer dataLimit) { this.dataLimit = dataLimit; return this; } + @Override public Fleet update(final TwilioRestClient client) { + String path = "/v1/Fleets/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.SUPERSIM.toString(), - path + HttpMethod.POST, + Domains.SUPERSIM.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Fleet update failed: Unable to connect to server" - ); + throw new ApiConnectionException("Fleet update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -125,32 +121,41 @@ public Fleet update(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (uniqueName != null) { - request.addPostParam("UniqueName", uniqueName); + Serializer.toString(request, "UniqueName", uniqueName, ParameterType.URLENCODED); } + + if (networkAccessProfile != null) { - request.addPostParam("NetworkAccessProfile", networkAccessProfile); + Serializer.toString(request, "NetworkAccessProfile", networkAccessProfile, ParameterType.URLENCODED); } + + if (ipCommandsUrl != null) { - request.addPostParam("IpCommandsUrl", ipCommandsUrl.toString()); + Serializer.toString(request, "IpCommandsUrl", ipCommandsUrl, ParameterType.URLENCODED); } + + if (ipCommandsMethod != null) { - request.addPostParam( - "IpCommandsMethod", - ipCommandsMethod.toString() - ); + Serializer.toString(request, "IpCommandsMethod", ipCommandsMethod, ParameterType.URLENCODED); } + + if (smsCommandsUrl != null) { - request.addPostParam("SmsCommandsUrl", smsCommandsUrl.toString()); + Serializer.toString(request, "SmsCommandsUrl", smsCommandsUrl, ParameterType.URLENCODED); } + + if (smsCommandsMethod != null) { - request.addPostParam( - "SmsCommandsMethod", - smsCommandsMethod.toString() - ); + Serializer.toString(request, "SmsCommandsMethod", smsCommandsMethod, ParameterType.URLENCODED); } + + if (dataLimit != null) { - request.addPostParam("DataLimit", dataLimit.toString()); + Serializer.toString(request, "DataLimit", dataLimit, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/supersim/v1/IpCommand.java b/src/main/java/com/twilio/rest/supersim/v1/IpCommand.java index da34f019a3..b04a3a53de 100644 --- a/src/main/java/com/twilio/rest/supersim/v1/IpCommand.java +++ b/src/main/java/com/twilio/rest/supersim/v1/IpCommand.java @@ -18,54 +18,120 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class IpCommand extends Resource { - private static final long serialVersionUID = 232445526954174L; - public static IpCommandCreator creator( - final String sim, - final String payload, - final Integer devicePort - ) { - return new IpCommandCreator(sim, payload, devicePort); + public static IpCommandCreator creator(final String sim, final String payload, final Integer devicePort) { + return new IpCommandCreator( + sim, payload, devicePort + ); } - public static IpCommandFetcher fetcher(final String pathSid) { - return new IpCommandFetcher(pathSid); + + public static IpCommandFetcher fetcher(final String pathsid) { + return new IpCommandFetcher( + pathsid + ); } + public static IpCommandReader reader() { - return new IpCommandReader(); + return new IpCommandReader( + + ); } + + public enum Status { + QUEUED("queued"), + SENT("sent"), + RECEIVED("received"), + FAILED("failed"); + + private final String value; + + private Status(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static Status forValue(final String value) { + return Promoter.enumFromString(value, Status.values()); + } + } + + public enum Direction { + TO_SIM("to_sim"), + FROM_SIM("from_sim"); + + private final String value; + + private Direction(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static Direction forValue(final String value) { + return Promoter.enumFromString(value, Direction.values()); + } + } + + public enum PayloadType { + TEXT("text"), + BINARY("binary"); + + private final String value; + + private PayloadType(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static PayloadType forValue(final String value) { + return Promoter.enumFromString(value, PayloadType.values()); + } + } + + /** * Converts a JSON String into a IpCommand object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return IpCommand object represented by the provided JSON */ - public static IpCommand fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static IpCommand fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, IpCommand.class); @@ -80,14 +146,11 @@ public static IpCommand fromJson( * Converts a JSON InputStream into a IpCommand object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return IpCommand object represented by the provided JSON */ - public static IpCommand fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static IpCommand fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, IpCommand.class); @@ -98,103 +161,79 @@ public static IpCommand fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String simSid; - private final String simIccid; - private final IpCommand.Status status; - private final IpCommand.Direction direction; + @Getter + private final ZonedDateTime dateCreated; + @Getter + private final ZonedDateTime dateUpdated; + @Getter private final String deviceIp; + @Getter private final Integer devicePort; - private final IpCommand.PayloadType payloadType; + @Getter + private final IpCommand.Direction direction; + @Getter private final String payload; - private final ZonedDateTime dateCreated; - private final ZonedDateTime dateUpdated; + @Getter + private final IpCommand.PayloadType payloadType; + @Getter + private final String sid; + @Getter + private final String simIccid; + @Getter + private final String simSid; + @Getter + private final IpCommand.Status status; + @Getter private final URI url; @JsonCreator private IpCommand( - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("sim_sid") final String simSid, - @JsonProperty("sim_iccid") final String simIccid, - @JsonProperty("status") final IpCommand.Status status, - @JsonProperty("direction") final IpCommand.Direction direction, - @JsonProperty("device_ip") final String deviceIp, - @JsonProperty("device_port") final Integer devicePort, - @JsonProperty("payload_type") final IpCommand.PayloadType payloadType, - @JsonProperty("payload") final String payload, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("url") final URI url + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("device_ip") final String deviceIp, + @JsonProperty("device_port") final Integer devicePort, + @JsonProperty("direction") final IpCommand.Direction direction, + @JsonProperty("payload") final String payload, + @JsonProperty("payload_type") final IpCommand.PayloadType payloadType, + @JsonProperty("sid") final String sid, + @JsonProperty("sim_iccid") final String simIccid, + @JsonProperty("sim_sid") final String simSid, + @JsonProperty("status") final IpCommand.Status status, + @JsonProperty("url") final URI url ) { - this.sid = sid; this.accountSid = accountSid; - this.simSid = simSid; - this.simIccid = simIccid; - this.status = status; - this.direction = direction; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.deviceIp = deviceIp; this.devicePort = devicePort; - this.payloadType = payloadType; + this.direction = direction; this.payload = payload; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); + this.payloadType = payloadType; + this.sid = sid; + this.simIccid = simIccid; + this.simSid = simSid; + this.status = status; this.url = url; } - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getSimSid() { - return this.simSid; - } - - public final String getSimIccid() { - return this.simIccid; - } - - public final IpCommand.Status getStatus() { - return this.status; - } - - public final IpCommand.Direction getDirection() { - return this.direction; - } - - public final String getDeviceIp() { - return this.deviceIp; - } - - public final Integer getDevicePort() { - return this.devicePort; - } - - public final IpCommand.PayloadType getPayloadType() { - return this.payloadType; - } - - public final String getPayload() { - return this.payload; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final URI getUrl() { - return this.url; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -206,102 +245,42 @@ public boolean equals(final Object o) { } IpCommand other = (IpCommand) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(simSid, other.simSid) && - Objects.equals(simIccid, other.simIccid) && - Objects.equals(status, other.status) && - Objects.equals(direction, other.direction) && - Objects.equals(deviceIp, other.deviceIp) && - Objects.equals(devicePort, other.devicePort) && - Objects.equals(payloadType, other.payloadType) && - Objects.equals(payload, other.payload) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(url, other.url) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(deviceIp, other.deviceIp) && + Objects.equals(devicePort, other.devicePort) && + Objects.equals(direction, other.direction) && + Objects.equals(payload, other.payload) && + Objects.equals(payloadType, other.payloadType) && + Objects.equals(sid, other.sid) && + Objects.equals(simIccid, other.simIccid) && + Objects.equals(simSid, other.simSid) && + Objects.equals(status, other.status) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - sid, - accountSid, - simSid, - simIccid, - status, - direction, - deviceIp, - devicePort, - payloadType, - payload, - dateCreated, - dateUpdated, - url + accountSid, + dateCreated, + dateUpdated, + deviceIp, + devicePort, + direction, + payload, + payloadType, + sid, + simIccid, + simSid, + status, + url ); } - public enum PayloadType { - TEXT("text"), - BINARY("binary"); - - private final String value; - - private PayloadType(final String value) { - this.value = value; - } - public String toString() { - return value; - } - - @JsonCreator - public static PayloadType forValue(final String value) { - return Promoter.enumFromString(value, PayloadType.values()); - } - } - - public enum Status { - QUEUED("queued"), - SENT("sent"), - RECEIVED("received"), - FAILED("failed"); - - private final String value; - - private Status(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static Status forValue(final String value) { - return Promoter.enumFromString(value, Status.values()); - } - } - - public enum Direction { - TO_SIM("to_sim"), - FROM_SIM("from_sim"); - - private final String value; - - private Direction(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static Direction forValue(final String value) { - return Promoter.enumFromString(value, Direction.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/supersim/v1/IpCommandCreator.java b/src/main/java/com/twilio/rest/supersim/v1/IpCommandCreator.java index d6311fa0ac..2f14fa6468 100644 --- a/src/main/java/com/twilio/rest/supersim/v1/IpCommandCreator.java +++ b/src/main/java/com/twilio/rest/supersim/v1/IpCommandCreator.java @@ -14,9 +14,11 @@ package com.twilio.rest.supersim.v1; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; -import com.twilio.converter.Promoter; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,7 +27,7 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -import java.net.URI; + import java.net.URI; public class IpCommandCreator extends Creator { @@ -37,111 +39,112 @@ public class IpCommandCreator extends Creator { private URI callbackUrl; private HttpMethod callbackMethod; - public IpCommandCreator( - final String sim, - final String payload, - final Integer devicePort - ) { + public IpCommandCreator(final String sim, final String payload, final Integer devicePort) { this.sim = sim; this.payload = payload; this.devicePort = devicePort; } + public IpCommandCreator setSim(final String sim) { this.sim = sim; return this; } + public IpCommandCreator setPayload(final String payload) { this.payload = payload; return this; } + public IpCommandCreator setDevicePort(final Integer devicePort) { this.devicePort = devicePort; return this; } - public IpCommandCreator setPayloadType( - final IpCommand.PayloadType payloadType - ) { + + public IpCommandCreator setPayloadType(final IpCommand.PayloadType payloadType) { this.payloadType = payloadType; return this; } + public IpCommandCreator setCallbackUrl(final URI callbackUrl) { this.callbackUrl = callbackUrl; return this; } - public IpCommandCreator setCallbackUrl(final String callbackUrl) { - return setCallbackUrl(Promoter.uriFromString(callbackUrl)); - } public IpCommandCreator setCallbackMethod(final HttpMethod callbackMethod) { this.callbackMethod = callbackMethod; return this; } + @Override public IpCommand create(final TwilioRestClient client) { + String path = "/v1/IpCommands"; - path = path.replace("{" + "Sim" + "}", this.sim.toString()); - path = path.replace("{" + "Payload" + "}", this.payload.toString()); - path = - path.replace("{" + "DevicePort" + "}", this.devicePort.toString()); Request request = new Request( - HttpMethod.POST, - Domains.SUPERSIM.toString(), - path + HttpMethod.POST, + Domains.SUPERSIM.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "IpCommand creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("IpCommand creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return IpCommand.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return IpCommand.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (sim != null) { - request.addPostParam("Sim", sim); + Serializer.toString(request, "Sim", sim, ParameterType.URLENCODED); } + + if (payload != null) { - request.addPostParam("Payload", payload); + Serializer.toString(request, "Payload", payload, ParameterType.URLENCODED); } + + if (devicePort != null) { - request.addPostParam("DevicePort", devicePort.toString()); + Serializer.toString(request, "DevicePort", devicePort, ParameterType.URLENCODED); } + + if (payloadType != null) { - request.addPostParam("PayloadType", payloadType.toString()); + Serializer.toString(request, "PayloadType", payloadType, ParameterType.URLENCODED); } + + if (callbackUrl != null) { - request.addPostParam("CallbackUrl", callbackUrl.toString()); + Serializer.toString(request, "CallbackUrl", callbackUrl, ParameterType.URLENCODED); } + + if (callbackMethod != null) { - request.addPostParam("CallbackMethod", callbackMethod.toString()); + Serializer.toString(request, "CallbackMethod", callbackMethod, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/supersim/v1/IpCommandFetcher.java b/src/main/java/com/twilio/rest/supersim/v1/IpCommandFetcher.java index ae327abb38..17a437965f 100644 --- a/src/main/java/com/twilio/rest/supersim/v1/IpCommandFetcher.java +++ b/src/main/java/com/twilio/rest/supersim/v1/IpCommandFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.supersim.v1; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,47 +26,41 @@ public class IpCommandFetcher extends Fetcher { - private String pathSid; + private String pathsid; - public IpCommandFetcher(final String pathSid) { - this.pathSid = pathSid; + public IpCommandFetcher(final String pathsid) { + this.pathsid = pathsid; } + @Override public IpCommand fetch(final TwilioRestClient client) { + String path = "/v1/IpCommands/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.SUPERSIM.toString(), - path + HttpMethod.GET, + Domains.SUPERSIM.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "IpCommand fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("IpCommand fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return IpCommand.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return IpCommand.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/supersim/v1/IpCommandReader.java b/src/main/java/com/twilio/rest/supersim/v1/IpCommandReader.java index 8a7eea0817..ba3556cef4 100644 --- a/src/main/java/com/twilio/rest/supersim/v1/IpCommandReader.java +++ b/src/main/java/com/twilio/rest/supersim/v1/IpCommandReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -35,137 +36,127 @@ public class IpCommandReader extends Reader { private IpCommand.Direction direction; private Long pageSize; - public IpCommandReader() {} + public IpCommandReader() { + } + public IpCommandReader setSim(final String sim) { this.sim = sim; return this; } + public IpCommandReader setSimIccid(final String simIccid) { this.simIccid = simIccid; return this; } + public IpCommandReader setStatus(final IpCommand.Status status) { this.status = status; return this; } + public IpCommandReader setDirection(final IpCommand.Direction direction) { this.direction = direction; return this; } + public IpCommandReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/IpCommands"; + Request request = new Request( - HttpMethod.GET, - Domains.SUPERSIM.toString(), - path + HttpMethod.GET, + Domains.SUPERSIM.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "IpCommand read failed: Unable to connect to server" - ); + throw new ApiConnectionException("IpCommand read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "ip_commands", - response.getContent(), - IpCommand.class, - client.getObjectMapper() - ); + "ip_commands", + response.getContent(), + IpCommand.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.SUPERSIM.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.SUPERSIM.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (sim != null) { - request.addQueryParam("Sim", sim); + Serializer.toString(request, "Sim", sim, ParameterType.QUERY); } + + if (simIccid != null) { - request.addQueryParam("SimIccid", simIccid); + Serializer.toString(request, "SimIccid", simIccid, ParameterType.QUERY); } + + if (status != null) { - request.addQueryParam("Status", status.toString()); + Serializer.toString(request, "Status", status, ParameterType.QUERY); } + + if (direction != null) { - request.addQueryParam("Direction", direction.toString()); + Serializer.toString(request, "Direction", direction, ParameterType.QUERY); } + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/supersim/v1/Network.java b/src/main/java/com/twilio/rest/supersim/v1/Network.java index 3b01f564d8..d5fb6aa0b1 100644 --- a/src/main/java/com/twilio/rest/supersim/v1/Network.java +++ b/src/main/java/com/twilio/rest/supersim/v1/Network.java @@ -18,46 +18,48 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.util.List; -import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Network extends Resource { - private static final long serialVersionUID = 225839080791216L; - public static NetworkFetcher fetcher(final String pathSid) { - return new NetworkFetcher(pathSid); + public static NetworkFetcher fetcher(final String pathsid) { + return new NetworkFetcher( + pathsid + ); } + public static NetworkReader reader() { - return new NetworkReader(); + return new NetworkReader( + + ); } + /** * Converts a JSON String into a Network object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Network object represented by the provided JSON */ - public static Network fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Network fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Network.class); @@ -72,14 +74,11 @@ public static Network fromJson( * Converts a JSON InputStream into a Network object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Network object represented by the provided JSON */ - public static Network fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Network fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Network.class); @@ -90,45 +89,43 @@ public static Network fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String friendlyName; - private final URI url; + @Getter + private final List identifiers; + @Getter private final String isoCountry; - private final List> identifiers; + @Getter + private final String sid; + @Getter + private final URI url; @JsonCreator private Network( - @JsonProperty("sid") final String sid, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("url") final URI url, - @JsonProperty("iso_country") final String isoCountry, - @JsonProperty("identifiers") final List> identifiers + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("identifiers") final List identifiers, + @JsonProperty("iso_country") final String isoCountry, + @JsonProperty("sid") final String sid, + @JsonProperty("url") final URI url ) { - this.sid = sid; this.friendlyName = friendlyName; - this.url = url; - this.isoCountry = isoCountry; this.identifiers = identifiers; - } - - public final String getSid() { - return this.sid; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final URI getUrl() { - return this.url; - } - - public final String getIsoCountry() { - return this.isoCountry; - } - - public final List> getIdentifiers() { - return this.identifiers; + this.isoCountry = isoCountry; + this.sid = sid; + this.url = url; } @Override @@ -142,18 +139,26 @@ public boolean equals(final Object o) { } Network other = (Network) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(url, other.url) && - Objects.equals(isoCountry, other.isoCountry) && - Objects.equals(identifiers, other.identifiers) + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(identifiers, other.identifiers) && + Objects.equals(isoCountry, other.isoCountry) && + Objects.equals(sid, other.sid) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { - return Objects.hash(sid, friendlyName, url, isoCountry, identifiers); + return Objects.hash( + friendlyName, + identifiers, + isoCountry, + sid, + url + ); } + + } + diff --git a/src/main/java/com/twilio/rest/supersim/v1/NetworkAccessProfile.java b/src/main/java/com/twilio/rest/supersim/v1/NetworkAccessProfile.java index 75ea177302..50074ec02a 100644 --- a/src/main/java/com/twilio/rest/supersim/v1/NetworkAccessProfile.java +++ b/src/main/java/com/twilio/rest/supersim/v1/NetworkAccessProfile.java @@ -18,55 +18,64 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class NetworkAccessProfile extends Resource { - private static final long serialVersionUID = 19374980019913L; public static NetworkAccessProfileCreator creator() { - return new NetworkAccessProfileCreator(); + return new NetworkAccessProfileCreator( + + ); } - public static NetworkAccessProfileFetcher fetcher(final String pathSid) { - return new NetworkAccessProfileFetcher(pathSid); + + public static NetworkAccessProfileFetcher fetcher(final String pathsid) { + return new NetworkAccessProfileFetcher( + pathsid + ); } + public static NetworkAccessProfileReader reader() { - return new NetworkAccessProfileReader(); + return new NetworkAccessProfileReader( + + ); } - public static NetworkAccessProfileUpdater updater(final String pathSid) { - return new NetworkAccessProfileUpdater(pathSid); + + public static NetworkAccessProfileUpdater updater(final String pathsid) { + return new NetworkAccessProfileUpdater( + pathsid + ); } + /** * Converts a JSON String into a NetworkAccessProfile object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return NetworkAccessProfile object represented by the provided JSON */ - public static NetworkAccessProfile fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static NetworkAccessProfile fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, NetworkAccessProfile.class); @@ -81,14 +90,11 @@ public static NetworkAccessProfile fromJson( * Converts a JSON InputStream into a NetworkAccessProfile object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return NetworkAccessProfile object represented by the provided JSON */ - public static NetworkAccessProfile fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static NetworkAccessProfile fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, NetworkAccessProfile.class); @@ -99,59 +105,53 @@ public static NetworkAccessProfile fromJson( } } - private final String sid; - private final String uniqueName; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; - private final URI url; + @Getter private final Map links; + @Getter + private final String sid; + @Getter + private final String uniqueName; + @Getter + private final URI url; @JsonCreator private NetworkAccessProfile( - @JsonProperty("sid") final String sid, - @JsonProperty("unique_name") final String uniqueName, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("url") final URI url, - @JsonProperty("links") final Map links + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("links") final Map links, + @JsonProperty("sid") final String sid, + @JsonProperty("unique_name") final String uniqueName, + @JsonProperty("url") final URI url ) { + this.accountSid = accountSid; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; + this.links = links; this.sid = sid; this.uniqueName = uniqueName; - this.accountSid = accountSid; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); this.url = url; - this.links = links; - } - - public final String getSid() { - return this.sid; - } - - public final String getUniqueName() { - return this.uniqueName; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final URI getUrl() { - return this.url; - } - - public final Map getLinks() { - return this.links; } @Override @@ -165,28 +165,30 @@ public boolean equals(final Object o) { } NetworkAccessProfile other = (NetworkAccessProfile) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(uniqueName, other.uniqueName) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(url, other.url) && - Objects.equals(links, other.links) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(links, other.links) && + Objects.equals(sid, other.sid) && + Objects.equals(uniqueName, other.uniqueName) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - sid, - uniqueName, - accountSid, - dateCreated, - dateUpdated, - url, - links + accountSid, + dateCreated, + dateUpdated, + links, + sid, + uniqueName, + url ); } + + } + diff --git a/src/main/java/com/twilio/rest/supersim/v1/NetworkAccessProfileCreator.java b/src/main/java/com/twilio/rest/supersim/v1/NetworkAccessProfileCreator.java index 14da70ab36..aef373b704 100644 --- a/src/main/java/com/twilio/rest/supersim/v1/NetworkAccessProfileCreator.java +++ b/src/main/java/com/twilio/rest/supersim/v1/NetworkAccessProfileCreator.java @@ -14,9 +14,12 @@ package com.twilio.rest.supersim.v1; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; import com.twilio.converter.Promoter; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,7 +28,7 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -import java.util.List; + import java.util.List; public class NetworkAccessProfileCreator extends Creator { @@ -33,16 +36,17 @@ public class NetworkAccessProfileCreator extends Creator { private String uniqueName; private List networks; - public NetworkAccessProfileCreator() {} + public NetworkAccessProfileCreator() { + } + public NetworkAccessProfileCreator setUniqueName(final String uniqueName) { this.uniqueName = uniqueName; return this; } - public NetworkAccessProfileCreator setNetworks( - final List networks - ) { + + public NetworkAccessProfileCreator setNetworks(final List networks) { this.networks = networks; return this; } @@ -53,48 +57,48 @@ public NetworkAccessProfileCreator setNetworks(final String networks) { @Override public NetworkAccessProfile create(final TwilioRestClient client) { + String path = "/v1/NetworkAccessProfiles"; + Request request = new Request( - HttpMethod.POST, - Domains.SUPERSIM.toString(), - path + HttpMethod.POST, + Domains.SUPERSIM.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "NetworkAccessProfile creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("NetworkAccessProfile creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return NetworkAccessProfile.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return NetworkAccessProfile.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (uniqueName != null) { - request.addPostParam("UniqueName", uniqueName); + Serializer.toString(request, "UniqueName", uniqueName, ParameterType.URLENCODED); } + + if (networks != null) { - for (String prop : networks) { - request.addPostParam("Networks", prop); + for (String param : networks) { + Serializer.toString(request, "Networks", param, ParameterType.URLENCODED); } } + } } diff --git a/src/main/java/com/twilio/rest/supersim/v1/NetworkAccessProfileFetcher.java b/src/main/java/com/twilio/rest/supersim/v1/NetworkAccessProfileFetcher.java index 9a4b05b300..7a49b2b36c 100644 --- a/src/main/java/com/twilio/rest/supersim/v1/NetworkAccessProfileFetcher.java +++ b/src/main/java/com/twilio/rest/supersim/v1/NetworkAccessProfileFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.supersim.v1; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,47 +26,41 @@ public class NetworkAccessProfileFetcher extends Fetcher { - private String pathSid; + private String pathsid; - public NetworkAccessProfileFetcher(final String pathSid) { - this.pathSid = pathSid; + public NetworkAccessProfileFetcher(final String pathsid) { + this.pathsid = pathsid; } + @Override public NetworkAccessProfile fetch(final TwilioRestClient client) { + String path = "/v1/NetworkAccessProfiles/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.SUPERSIM.toString(), - path + HttpMethod.GET, + Domains.SUPERSIM.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "NetworkAccessProfile fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("NetworkAccessProfile fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return NetworkAccessProfile.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return NetworkAccessProfile.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/supersim/v1/NetworkAccessProfileReader.java b/src/main/java/com/twilio/rest/supersim/v1/NetworkAccessProfileReader.java index 6c8c762f17..6852868dbc 100644 --- a/src/main/java/com/twilio/rest/supersim/v1/NetworkAccessProfileReader.java +++ b/src/main/java/com/twilio/rest/supersim/v1/NetworkAccessProfileReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -31,107 +32,83 @@ public class NetworkAccessProfileReader extends Reader { private Long pageSize; - public NetworkAccessProfileReader() {} + public NetworkAccessProfileReader() { + } + public NetworkAccessProfileReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override - public ResourceSet read( - final TwilioRestClient client - ) { + public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/NetworkAccessProfiles"; + Request request = new Request( - HttpMethod.GET, - Domains.SUPERSIM.toString(), - path + HttpMethod.GET, + Domains.SUPERSIM.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "NetworkAccessProfile read failed: Unable to connect to server" - ); + throw new ApiConnectionException("NetworkAccessProfile read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "network_access_profiles", - response.getContent(), - NetworkAccessProfile.class, - client.getObjectMapper() - ); + "network_access_profiles", + response.getContent(), + NetworkAccessProfile.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.SUPERSIM.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.SUPERSIM.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/supersim/v1/NetworkAccessProfileUpdater.java b/src/main/java/com/twilio/rest/supersim/v1/NetworkAccessProfileUpdater.java index e09633acd3..cdca6d470b 100644 --- a/src/main/java/com/twilio/rest/supersim/v1/NetworkAccessProfileUpdater.java +++ b/src/main/java/com/twilio/rest/supersim/v1/NetworkAccessProfileUpdater.java @@ -16,6 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -26,60 +28,60 @@ import com.twilio.rest.Domains; public class NetworkAccessProfileUpdater extends Updater { - - private String pathSid; + private String pathsid; private String uniqueName; - public NetworkAccessProfileUpdater(final String pathSid) { - this.pathSid = pathSid; + public NetworkAccessProfileUpdater(final String pathsid) { + this.pathsid = pathsid; } + public NetworkAccessProfileUpdater setUniqueName(final String uniqueName) { this.uniqueName = uniqueName; return this; } + @Override public NetworkAccessProfile update(final TwilioRestClient client) { + String path = "/v1/NetworkAccessProfiles/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.SUPERSIM.toString(), - path + HttpMethod.POST, + Domains.SUPERSIM.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "NetworkAccessProfile update failed: Unable to connect to server" - ); + throw new ApiConnectionException("NetworkAccessProfile update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return NetworkAccessProfile.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return NetworkAccessProfile.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (uniqueName != null) { - request.addPostParam("UniqueName", uniqueName); + Serializer.toString(request, "UniqueName", uniqueName, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/supersim/v1/NetworkFetcher.java b/src/main/java/com/twilio/rest/supersim/v1/NetworkFetcher.java index f15813e829..0dae6bce69 100644 --- a/src/main/java/com/twilio/rest/supersim/v1/NetworkFetcher.java +++ b/src/main/java/com/twilio/rest/supersim/v1/NetworkFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.supersim.v1; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,44 +26,41 @@ public class NetworkFetcher extends Fetcher { - private String pathSid; + private String pathsid; - public NetworkFetcher(final String pathSid) { - this.pathSid = pathSid; + public NetworkFetcher(final String pathsid) { + this.pathsid = pathsid; } + @Override public Network fetch(final TwilioRestClient client) { + String path = "/v1/Networks/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.SUPERSIM.toString(), - path + HttpMethod.GET, + Domains.SUPERSIM.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Network fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Network fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Network.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/supersim/v1/NetworkReader.java b/src/main/java/com/twilio/rest/supersim/v1/NetworkReader.java index 157e8cf687..f1124c4e3c 100644 --- a/src/main/java/com/twilio/rest/supersim/v1/NetworkReader.java +++ b/src/main/java/com/twilio/rest/supersim/v1/NetworkReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -34,129 +35,116 @@ public class NetworkReader extends Reader { private String mnc; private Long pageSize; - public NetworkReader() {} + public NetworkReader() { + } + public NetworkReader setIsoCountry(final String isoCountry) { this.isoCountry = isoCountry; return this; } + public NetworkReader setMcc(final String mcc) { this.mcc = mcc; return this; } + public NetworkReader setMnc(final String mnc) { this.mnc = mnc; return this; } + public NetworkReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/Networks"; + Request request = new Request( - HttpMethod.GET, - Domains.SUPERSIM.toString(), - path + HttpMethod.GET, + Domains.SUPERSIM.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Network read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Network read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "networks", - response.getContent(), - Network.class, - client.getObjectMapper() - ); + "networks", + response.getContent(), + Network.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.SUPERSIM.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.SUPERSIM.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (isoCountry != null) { - request.addQueryParam("IsoCountry", isoCountry); + Serializer.toString(request, "IsoCountry", isoCountry, ParameterType.QUERY); } + + if (mcc != null) { - request.addQueryParam("Mcc", mcc); + Serializer.toString(request, "Mcc", mcc, ParameterType.QUERY); } + + if (mnc != null) { - request.addQueryParam("Mnc", mnc); + Serializer.toString(request, "Mnc", mnc, ParameterType.QUERY); } + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/supersim/v1/SettingsUpdate.java b/src/main/java/com/twilio/rest/supersim/v1/SettingsUpdate.java index 4d3dbc2f17..ebecba6a3d 100644 --- a/src/main/java/com/twilio/rest/supersim/v1/SettingsUpdate.java +++ b/src/main/java/com/twilio/rest/supersim/v1/SettingsUpdate.java @@ -18,44 +18,66 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.time.ZonedDateTime; import java.util.List; -import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class SettingsUpdate extends Resource { - private static final long serialVersionUID = 126256874693410L; public static SettingsUpdateReader reader() { - return new SettingsUpdateReader(); + return new SettingsUpdateReader( + + ); + } + + + public enum Status { + SCHEDULED("scheduled"), + IN_PROGRESS("in-progress"), + SUCCESSFUL("successful"), + FAILED("failed"); + + private final String value; + + private Status(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static Status forValue(final String value) { + return Promoter.enumFromString(value, Status.values()); + } } + /** * Converts a JSON String into a SettingsUpdate object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return SettingsUpdate object represented by the provided JSON */ - public static SettingsUpdate fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static SettingsUpdate fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, SettingsUpdate.class); @@ -70,14 +92,11 @@ public static SettingsUpdate fromJson( * Converts a JSON InputStream into a SettingsUpdate object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return SettingsUpdate object represented by the provided JSON */ - public static SettingsUpdate fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static SettingsUpdate fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, SettingsUpdate.class); @@ -88,67 +107,58 @@ public static SettingsUpdate fromJson( } } - private final String sid; - private final String iccid; - private final String simSid; - private final SettingsUpdate.Status status; - private final List> packages; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final ZonedDateTime dateCompleted; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; + @Getter + private final String iccid; + @Getter + private final List packages; + @Getter + private final String sid; + @Getter + private final String simSid; + @Getter + private final SettingsUpdate.Status status; @JsonCreator private SettingsUpdate( - @JsonProperty("sid") final String sid, - @JsonProperty("iccid") final String iccid, - @JsonProperty("sim_sid") final String simSid, - @JsonProperty("status") final SettingsUpdate.Status status, - @JsonProperty("packages") final List> packages, - @JsonProperty("date_completed") final String dateCompleted, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated + @JsonProperty("date_completed") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCompleted, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("iccid") final String iccid, + @JsonProperty("packages") final List packages, + @JsonProperty("sid") final String sid, + @JsonProperty("sim_sid") final String simSid, + @JsonProperty("status") final SettingsUpdate.Status status ) { - this.sid = sid; + this.dateCompleted = dateCompleted; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.iccid = iccid; + this.packages = packages; + this.sid = sid; this.simSid = simSid; this.status = status; - this.packages = packages; - this.dateCompleted = - DateConverter.iso8601DateTimeFromString(dateCompleted); - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); - } - - public final String getSid() { - return this.sid; - } - - public final String getIccid() { - return this.iccid; - } - - public final String getSimSid() { - return this.simSid; - } - - public final SettingsUpdate.Status getStatus() { - return this.status; - } - - public final List> getPackages() { - return this.packages; - } - - public final ZonedDateTime getDateCompleted() { - return this.dateCompleted; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; } @Override @@ -162,52 +172,32 @@ public boolean equals(final Object o) { } SettingsUpdate other = (SettingsUpdate) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(iccid, other.iccid) && - Objects.equals(simSid, other.simSid) && - Objects.equals(status, other.status) && - Objects.equals(packages, other.packages) && - Objects.equals(dateCompleted, other.dateCompleted) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) + Objects.equals(dateCompleted, other.dateCompleted) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(iccid, other.iccid) && + Objects.equals(packages, other.packages) && + Objects.equals(sid, other.sid) && + Objects.equals(simSid, other.simSid) && + Objects.equals(status, other.status) ); } @Override public int hashCode() { return Objects.hash( - sid, - iccid, - simSid, - status, - packages, - dateCompleted, - dateCreated, - dateUpdated + dateCompleted, + dateCreated, + dateUpdated, + iccid, + packages, + sid, + simSid, + status ); } - public enum Status { - SCHEDULED("scheduled"), - IN_PROGRESS("in-progress"), - SUCCESSFUL("successful"), - FAILED("failed"); - - private final String value; - - private Status(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - @JsonCreator - public static Status forValue(final String value) { - return Promoter.enumFromString(value, Status.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/supersim/v1/SettingsUpdateReader.java b/src/main/java/com/twilio/rest/supersim/v1/SettingsUpdateReader.java index 4dc6e65a44..7422166539 100644 --- a/src/main/java/com/twilio/rest/supersim/v1/SettingsUpdateReader.java +++ b/src/main/java/com/twilio/rest/supersim/v1/SettingsUpdateReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -33,121 +34,105 @@ public class SettingsUpdateReader extends Reader { private SettingsUpdate.Status status; private Long pageSize; - public SettingsUpdateReader() {} + public SettingsUpdateReader() { + } + public SettingsUpdateReader setSim(final String sim) { this.sim = sim; return this; } + public SettingsUpdateReader setStatus(final SettingsUpdate.Status status) { this.status = status; return this; } + public SettingsUpdateReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/SettingsUpdates"; + Request request = new Request( - HttpMethod.GET, - Domains.SUPERSIM.toString(), - path + HttpMethod.GET, + Domains.SUPERSIM.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "SettingsUpdate read failed: Unable to connect to server" - ); + throw new ApiConnectionException("SettingsUpdate read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "settings_updates", - response.getContent(), - SettingsUpdate.class, - client.getObjectMapper() - ); + "settings_updates", + response.getContent(), + SettingsUpdate.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.SUPERSIM.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.SUPERSIM.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (sim != null) { - request.addQueryParam("Sim", sim); + Serializer.toString(request, "Sim", sim, ParameterType.QUERY); } + + if (status != null) { - request.addQueryParam("Status", status.toString()); + Serializer.toString(request, "Status", status, ParameterType.QUERY); } + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/supersim/v1/Sim.java b/src/main/java/com/twilio/rest/supersim/v1/Sim.java index 072e1815fb..3c6e542691 100644 --- a/src/main/java/com/twilio/rest/supersim/v1/Sim.java +++ b/src/main/java/com/twilio/rest/supersim/v1/Sim.java @@ -18,59 +18,110 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Sim extends Resource { - private static final long serialVersionUID = 28875728882839L; - public static SimCreator creator( - final String iccid, - final String registrationCode - ) { - return new SimCreator(iccid, registrationCode); + public static SimCreator creator(final String iccid, final String registrationCode) { + return new SimCreator( + iccid, registrationCode + ); } - public static SimFetcher fetcher(final String pathSid) { - return new SimFetcher(pathSid); + + public static SimFetcher fetcher(final String pathsid) { + return new SimFetcher( + pathsid + ); } + public static SimReader reader() { - return new SimReader(); + return new SimReader( + + ); + } + + + public static SimUpdater updater(final String pathsid) { + return new SimUpdater( + pathsid + ); + } + + + public enum Status { + NEW("new"), + READY("ready"), + ACTIVE("active"), + INACTIVE("inactive"), + SCHEDULED("scheduled"); + + private final String value; + + private Status(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static Status forValue(final String value) { + return Promoter.enumFromString(value, Status.values()); + } } - public static SimUpdater updater(final String pathSid) { - return new SimUpdater(pathSid); + public enum StatusUpdate { + READY("ready"), + ACTIVE("active"), + INACTIVE("inactive"); + + private final String value; + + private StatusUpdate(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static StatusUpdate forValue(final String value) { + return Promoter.enumFromString(value, StatusUpdate.values()); + } } + /** * Converts a JSON String into a Sim object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Sim object represented by the provided JSON */ - public static Sim fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Sim fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Sim.class); @@ -85,14 +136,11 @@ public static Sim fromJson( * Converts a JSON InputStream into a Sim object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Sim object represented by the provided JSON */ - public static Sim fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Sim fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Sim.class); @@ -103,80 +151,65 @@ public static Sim fromJson( } } - private final String sid; - private final String uniqueName; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String iccid; - private final Sim.Status status; - private final String fleetSid; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; - private final URI url; + @Getter + private final String fleetSid; + @Getter + private final String iccid; + @Getter private final Map links; + @Getter + private final String sid; + @Getter + private final Sim.Status status; + @Getter + private final String uniqueName; + @Getter + private final URI url; @JsonCreator private Sim( - @JsonProperty("sid") final String sid, - @JsonProperty("unique_name") final String uniqueName, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("iccid") final String iccid, - @JsonProperty("status") final Sim.Status status, - @JsonProperty("fleet_sid") final String fleetSid, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("url") final URI url, - @JsonProperty("links") final Map links + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("fleet_sid") final String fleetSid, + @JsonProperty("iccid") final String iccid, + @JsonProperty("links") final Map links, + @JsonProperty("sid") final String sid, + @JsonProperty("status") final Sim.Status status, + @JsonProperty("unique_name") final String uniqueName, + @JsonProperty("url") final URI url ) { - this.sid = sid; - this.uniqueName = uniqueName; this.accountSid = accountSid; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; + this.fleetSid = fleetSid; this.iccid = iccid; + this.links = links; + this.sid = sid; this.status = status; - this.fleetSid = fleetSid; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); + this.uniqueName = uniqueName; this.url = url; - this.links = links; - } - - public final String getSid() { - return this.sid; - } - - public final String getUniqueName() { - return this.uniqueName; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getIccid() { - return this.iccid; - } - - public final Sim.Status getStatus() { - return this.status; - } - - public final String getFleetSid() { - return this.fleetSid; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final URI getUrl() { - return this.url; - } - - public final Map getLinks() { - return this.links; } @Override @@ -190,78 +223,36 @@ public boolean equals(final Object o) { } Sim other = (Sim) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(uniqueName, other.uniqueName) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(iccid, other.iccid) && - Objects.equals(status, other.status) && - Objects.equals(fleetSid, other.fleetSid) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(url, other.url) && - Objects.equals(links, other.links) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(fleetSid, other.fleetSid) && + Objects.equals(iccid, other.iccid) && + Objects.equals(links, other.links) && + Objects.equals(sid, other.sid) && + Objects.equals(status, other.status) && + Objects.equals(uniqueName, other.uniqueName) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - sid, - uniqueName, - accountSid, - iccid, - status, - fleetSid, - dateCreated, - dateUpdated, - url, - links + accountSid, + dateCreated, + dateUpdated, + fleetSid, + iccid, + links, + sid, + status, + uniqueName, + url ); } - public enum Status { - NEW("new"), - READY("ready"), - ACTIVE("active"), - INACTIVE("inactive"), - SCHEDULED("scheduled"); - - private final String value; - - private Status(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static Status forValue(final String value) { - return Promoter.enumFromString(value, Status.values()); - } - } - - public enum StatusUpdate { - READY("ready"), - ACTIVE("active"), - INACTIVE("inactive"); - - private final String value; - private StatusUpdate(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static StatusUpdate forValue(final String value) { - return Promoter.enumFromString(value, StatusUpdate.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/supersim/v1/SimCreator.java b/src/main/java/com/twilio/rest/supersim/v1/SimCreator.java index 037a3b5f4c..7d9580d995 100644 --- a/src/main/java/com/twilio/rest/supersim/v1/SimCreator.java +++ b/src/main/java/com/twilio/rest/supersim/v1/SimCreator.java @@ -14,8 +14,11 @@ package com.twilio.rest.supersim.v1; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -35,49 +38,44 @@ public SimCreator(final String iccid, final String registrationCode) { this.registrationCode = registrationCode; } + public SimCreator setIccid(final String iccid) { this.iccid = iccid; return this; } + public SimCreator setRegistrationCode(final String registrationCode) { this.registrationCode = registrationCode; return this; } + @Override public Sim create(final TwilioRestClient client) { + String path = "/v1/Sims"; - path = path.replace("{" + "Iccid" + "}", this.iccid.toString()); - path = - path.replace( - "{" + "RegistrationCode" + "}", - this.registrationCode.toString() - ); Request request = new Request( - HttpMethod.POST, - Domains.SUPERSIM.toString(), - path + HttpMethod.POST, + Domains.SUPERSIM.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Sim creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("Sim creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -86,11 +84,16 @@ public Sim create(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (iccid != null) { - request.addPostParam("Iccid", iccid); + Serializer.toString(request, "Iccid", iccid, ParameterType.URLENCODED); } + + if (registrationCode != null) { - request.addPostParam("RegistrationCode", registrationCode); + Serializer.toString(request, "RegistrationCode", registrationCode, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/supersim/v1/SimFetcher.java b/src/main/java/com/twilio/rest/supersim/v1/SimFetcher.java index 177a96b88a..1a27c90879 100644 --- a/src/main/java/com/twilio/rest/supersim/v1/SimFetcher.java +++ b/src/main/java/com/twilio/rest/supersim/v1/SimFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.supersim.v1; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,44 +26,41 @@ public class SimFetcher extends Fetcher { - private String pathSid; + private String pathsid; - public SimFetcher(final String pathSid) { - this.pathSid = pathSid; + public SimFetcher(final String pathsid) { + this.pathsid = pathsid; } + @Override public Sim fetch(final TwilioRestClient client) { + String path = "/v1/Sims/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.SUPERSIM.toString(), - path + HttpMethod.GET, + Domains.SUPERSIM.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Sim fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Sim fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Sim.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/supersim/v1/SimReader.java b/src/main/java/com/twilio/rest/supersim/v1/SimReader.java index e8917995e7..2256e79cc3 100644 --- a/src/main/java/com/twilio/rest/supersim/v1/SimReader.java +++ b/src/main/java/com/twilio/rest/supersim/v1/SimReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -34,129 +35,116 @@ public class SimReader extends Reader { private String iccid; private Long pageSize; - public SimReader() {} + public SimReader() { + } + public SimReader setStatus(final Sim.Status status) { this.status = status; return this; } + public SimReader setFleet(final String fleet) { this.fleet = fleet; return this; } + public SimReader setIccid(final String iccid) { this.iccid = iccid; return this; } + public SimReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/Sims"; + Request request = new Request( - HttpMethod.GET, - Domains.SUPERSIM.toString(), - path + HttpMethod.GET, + Domains.SUPERSIM.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Sim read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Sim read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "sims", - response.getContent(), - Sim.class, - client.getObjectMapper() - ); + "sims", + response.getContent(), + Sim.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.SUPERSIM.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.SUPERSIM.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (status != null) { - request.addQueryParam("Status", status.toString()); + Serializer.toString(request, "Status", status, ParameterType.QUERY); } + + if (fleet != null) { - request.addQueryParam("Fleet", fleet); + Serializer.toString(request, "Fleet", fleet, ParameterType.QUERY); } + + if (iccid != null) { - request.addQueryParam("Iccid", iccid); + Serializer.toString(request, "Iccid", iccid, ParameterType.QUERY); } + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/supersim/v1/SimUpdater.java b/src/main/java/com/twilio/rest/supersim/v1/SimUpdater.java index 6cc1268050..8b28640215 100644 --- a/src/main/java/com/twilio/rest/supersim/v1/SimUpdater.java +++ b/src/main/java/com/twilio/rest/supersim/v1/SimUpdater.java @@ -16,7 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; -import com.twilio.converter.Promoter; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,11 +26,11 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.net.URI; public class SimUpdater extends Updater { - - private String pathSid; + private String pathsid; private String uniqueName; private Sim.StatusUpdate status; private String fleet; @@ -37,72 +38,74 @@ public class SimUpdater extends Updater { private HttpMethod callbackMethod; private String accountSid; - public SimUpdater(final String pathSid) { - this.pathSid = pathSid; + public SimUpdater(final String pathsid) { + this.pathsid = pathsid; } + public SimUpdater setUniqueName(final String uniqueName) { this.uniqueName = uniqueName; return this; } + public SimUpdater setStatus(final Sim.StatusUpdate status) { this.status = status; return this; } + public SimUpdater setFleet(final String fleet) { this.fleet = fleet; return this; } + public SimUpdater setCallbackUrl(final URI callbackUrl) { this.callbackUrl = callbackUrl; return this; } - public SimUpdater setCallbackUrl(final String callbackUrl) { - return setCallbackUrl(Promoter.uriFromString(callbackUrl)); - } public SimUpdater setCallbackMethod(final HttpMethod callbackMethod) { this.callbackMethod = callbackMethod; return this; } + public SimUpdater setAccountSid(final String accountSid) { this.accountSid = accountSid; return this; } + @Override public Sim update(final TwilioRestClient client) { + String path = "/v1/Sims/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.SUPERSIM.toString(), - path + HttpMethod.POST, + Domains.SUPERSIM.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Sim update failed: Unable to connect to server" - ); + throw new ApiConnectionException("Sim update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -111,23 +114,36 @@ public Sim update(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (uniqueName != null) { - request.addPostParam("UniqueName", uniqueName); + Serializer.toString(request, "UniqueName", uniqueName, ParameterType.URLENCODED); } + + if (status != null) { - request.addPostParam("Status", status.toString()); + Serializer.toString(request, "Status", status, ParameterType.URLENCODED); } + + if (fleet != null) { - request.addPostParam("Fleet", fleet); + Serializer.toString(request, "Fleet", fleet, ParameterType.URLENCODED); } + + if (callbackUrl != null) { - request.addPostParam("CallbackUrl", callbackUrl.toString()); + Serializer.toString(request, "CallbackUrl", callbackUrl, ParameterType.URLENCODED); } + + if (callbackMethod != null) { - request.addPostParam("CallbackMethod", callbackMethod.toString()); + Serializer.toString(request, "CallbackMethod", callbackMethod, ParameterType.URLENCODED); } + + if (accountSid != null) { - request.addPostParam("AccountSid", accountSid); + Serializer.toString(request, "AccountSid", accountSid, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/supersim/v1/SmsCommand.java b/src/main/java/com/twilio/rest/supersim/v1/SmsCommand.java index ab1c698aa7..b59ef70ec5 100644 --- a/src/main/java/com/twilio/rest/supersim/v1/SmsCommand.java +++ b/src/main/java/com/twilio/rest/supersim/v1/SmsCommand.java @@ -18,53 +18,101 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class SmsCommand extends Resource { - private static final long serialVersionUID = 38007963555299L; - public static SmsCommandCreator creator( - final String sim, - final String payload - ) { - return new SmsCommandCreator(sim, payload); + public static SmsCommandCreator creator(final String sim, final String payload) { + return new SmsCommandCreator( + sim, payload + ); } - public static SmsCommandFetcher fetcher(final String pathSid) { - return new SmsCommandFetcher(pathSid); + + public static SmsCommandFetcher fetcher(final String pathsid) { + return new SmsCommandFetcher( + pathsid + ); } + public static SmsCommandReader reader() { - return new SmsCommandReader(); + return new SmsCommandReader( + + ); + } + + + public enum Status { + QUEUED("queued"), + SENT("sent"), + DELIVERED("delivered"), + RECEIVED("received"), + FAILED("failed"); + + private final String value; + + private Status(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static Status forValue(final String value) { + return Promoter.enumFromString(value, Status.values()); + } + } + + public enum Direction { + TO_SIM("to_sim"), + FROM_SIM("from_sim"); + + private final String value; + + private Direction(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static Direction forValue(final String value) { + return Promoter.enumFromString(value, Direction.values()); + } } + /** * Converts a JSON String into a SmsCommand object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return SmsCommand object represented by the provided JSON */ - public static SmsCommand fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static SmsCommand fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, SmsCommand.class); @@ -79,14 +127,11 @@ public static SmsCommand fromJson( * Converts a JSON InputStream into a SmsCommand object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return SmsCommand object represented by the provided JSON */ - public static SmsCommand fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static SmsCommand fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, SmsCommand.class); @@ -97,75 +142,63 @@ public static SmsCommand fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String simSid; - private final String payload; - private final SmsCommand.Status status; - private final SmsCommand.Direction direction; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; + @Getter + private final SmsCommand.Direction direction; + @Getter + private final String payload; + @Getter + private final String sid; + @Getter + private final String simSid; + @Getter + private final SmsCommand.Status status; + @Getter private final URI url; @JsonCreator private SmsCommand( - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("sim_sid") final String simSid, - @JsonProperty("payload") final String payload, - @JsonProperty("status") final SmsCommand.Status status, - @JsonProperty("direction") final SmsCommand.Direction direction, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("url") final URI url + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("direction") final SmsCommand.Direction direction, + @JsonProperty("payload") final String payload, + @JsonProperty("sid") final String sid, + @JsonProperty("sim_sid") final String simSid, + @JsonProperty("status") final SmsCommand.Status status, + @JsonProperty("url") final URI url ) { - this.sid = sid; this.accountSid = accountSid; - this.simSid = simSid; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; + this.direction = direction; this.payload = payload; + this.sid = sid; + this.simSid = simSid; this.status = status; - this.direction = direction; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); this.url = url; } - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getSimSid() { - return this.simSid; - } - - public final String getPayload() { - return this.payload; - } - - public final SmsCommand.Status getStatus() { - return this.status; - } - - public final SmsCommand.Direction getDirection() { - return this.direction; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final URI getUrl() { - return this.url; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -177,75 +210,34 @@ public boolean equals(final Object o) { } SmsCommand other = (SmsCommand) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(simSid, other.simSid) && - Objects.equals(payload, other.payload) && - Objects.equals(status, other.status) && - Objects.equals(direction, other.direction) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(url, other.url) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(direction, other.direction) && + Objects.equals(payload, other.payload) && + Objects.equals(sid, other.sid) && + Objects.equals(simSid, other.simSid) && + Objects.equals(status, other.status) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - sid, - accountSid, - simSid, - payload, - status, - direction, - dateCreated, - dateUpdated, - url + accountSid, + dateCreated, + dateUpdated, + direction, + payload, + sid, + simSid, + status, + url ); } - public enum Direction { - TO_SIM("to_sim"), - FROM_SIM("from_sim"); - - private final String value; - - private Direction(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static Direction forValue(final String value) { - return Promoter.enumFromString(value, Direction.values()); - } - } - - public enum Status { - QUEUED("queued"), - SENT("sent"), - DELIVERED("delivered"), - RECEIVED("received"), - FAILED("failed"); - - private final String value; - - private Status(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - @JsonCreator - public static Status forValue(final String value) { - return Promoter.enumFromString(value, Status.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/supersim/v1/SmsCommandCreator.java b/src/main/java/com/twilio/rest/supersim/v1/SmsCommandCreator.java index d93dae3e85..5a4a0babdf 100644 --- a/src/main/java/com/twilio/rest/supersim/v1/SmsCommandCreator.java +++ b/src/main/java/com/twilio/rest/supersim/v1/SmsCommandCreator.java @@ -14,9 +14,11 @@ package com.twilio.rest.supersim.v1; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; -import com.twilio.converter.Promoter; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,7 +27,7 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -import java.net.URI; + import java.net.URI; public class SmsCommandCreator extends Creator { @@ -40,83 +42,84 @@ public SmsCommandCreator(final String sim, final String payload) { this.payload = payload; } + public SmsCommandCreator setSim(final String sim) { this.sim = sim; return this; } + public SmsCommandCreator setPayload(final String payload) { this.payload = payload; return this; } - public SmsCommandCreator setCallbackMethod( - final HttpMethod callbackMethod - ) { + + public SmsCommandCreator setCallbackMethod(final HttpMethod callbackMethod) { this.callbackMethod = callbackMethod; return this; } + public SmsCommandCreator setCallbackUrl(final URI callbackUrl) { this.callbackUrl = callbackUrl; return this; } - public SmsCommandCreator setCallbackUrl(final String callbackUrl) { - return setCallbackUrl(Promoter.uriFromString(callbackUrl)); - } @Override public SmsCommand create(final TwilioRestClient client) { + String path = "/v1/SmsCommands"; - path = path.replace("{" + "Sim" + "}", this.sim.toString()); - path = path.replace("{" + "Payload" + "}", this.payload.toString()); Request request = new Request( - HttpMethod.POST, - Domains.SUPERSIM.toString(), - path + HttpMethod.POST, + Domains.SUPERSIM.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "SmsCommand creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("SmsCommand creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return SmsCommand.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return SmsCommand.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (sim != null) { - request.addPostParam("Sim", sim); + Serializer.toString(request, "Sim", sim, ParameterType.URLENCODED); } + + if (payload != null) { - request.addPostParam("Payload", payload); + Serializer.toString(request, "Payload", payload, ParameterType.URLENCODED); } + + if (callbackMethod != null) { - request.addPostParam("CallbackMethod", callbackMethod.toString()); + Serializer.toString(request, "CallbackMethod", callbackMethod, ParameterType.URLENCODED); } + + if (callbackUrl != null) { - request.addPostParam("CallbackUrl", callbackUrl.toString()); + Serializer.toString(request, "CallbackUrl", callbackUrl, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/supersim/v1/SmsCommandFetcher.java b/src/main/java/com/twilio/rest/supersim/v1/SmsCommandFetcher.java index c45e02943a..ab2bdb6c9c 100644 --- a/src/main/java/com/twilio/rest/supersim/v1/SmsCommandFetcher.java +++ b/src/main/java/com/twilio/rest/supersim/v1/SmsCommandFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.supersim.v1; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,47 +26,41 @@ public class SmsCommandFetcher extends Fetcher { - private String pathSid; + private String pathsid; - public SmsCommandFetcher(final String pathSid) { - this.pathSid = pathSid; + public SmsCommandFetcher(final String pathsid) { + this.pathsid = pathsid; } + @Override public SmsCommand fetch(final TwilioRestClient client) { + String path = "/v1/SmsCommands/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.SUPERSIM.toString(), - path + HttpMethod.GET, + Domains.SUPERSIM.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "SmsCommand fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("SmsCommand fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return SmsCommand.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return SmsCommand.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/supersim/v1/SmsCommandReader.java b/src/main/java/com/twilio/rest/supersim/v1/SmsCommandReader.java index 8f6d89ef9f..16f6c82e8c 100644 --- a/src/main/java/com/twilio/rest/supersim/v1/SmsCommandReader.java +++ b/src/main/java/com/twilio/rest/supersim/v1/SmsCommandReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -34,129 +35,116 @@ public class SmsCommandReader extends Reader { private SmsCommand.Direction direction; private Long pageSize; - public SmsCommandReader() {} + public SmsCommandReader() { + } + public SmsCommandReader setSim(final String sim) { this.sim = sim; return this; } + public SmsCommandReader setStatus(final SmsCommand.Status status) { this.status = status; return this; } + public SmsCommandReader setDirection(final SmsCommand.Direction direction) { this.direction = direction; return this; } + public SmsCommandReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/SmsCommands"; + Request request = new Request( - HttpMethod.GET, - Domains.SUPERSIM.toString(), - path + HttpMethod.GET, + Domains.SUPERSIM.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "SmsCommand read failed: Unable to connect to server" - ); + throw new ApiConnectionException("SmsCommand read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "sms_commands", - response.getContent(), - SmsCommand.class, - client.getObjectMapper() - ); + "sms_commands", + response.getContent(), + SmsCommand.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.SUPERSIM.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.SUPERSIM.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (sim != null) { - request.addQueryParam("Sim", sim); + Serializer.toString(request, "Sim", sim, ParameterType.QUERY); } + + if (status != null) { - request.addQueryParam("Status", status.toString()); + Serializer.toString(request, "Status", status, ParameterType.QUERY); } + + if (direction != null) { - request.addQueryParam("Direction", direction.toString()); + Serializer.toString(request, "Direction", direction, ParameterType.QUERY); } + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/supersim/v1/UsageRecord.java b/src/main/java/com/twilio/rest/supersim/v1/UsageRecord.java index 2b7510e170..6715f27993 100644 --- a/src/main/java/com/twilio/rest/supersim/v1/UsageRecord.java +++ b/src/main/java/com/twilio/rest/supersim/v1/UsageRecord.java @@ -18,45 +18,87 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.CurrencyDeserializer; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.math.BigDecimal; import java.util.Currency; -import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class UsageRecord extends Resource { - private static final long serialVersionUID = 269766941607639L; public static UsageRecordReader reader() { - return new UsageRecordReader(); + return new UsageRecordReader( + + ); + } + + + public enum Group { + SIM("sim"), + FLEET("fleet"), + NETWORK("network"), + ISO_COUNTRY("isoCountry"); + + private final String value; + + private Group(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static Group forValue(final String value) { + return Promoter.enumFromString(value, Group.values()); + } + } + + public enum Granularity { + HOUR("hour"), + DAY("day"), + ALL("all"); + + private final String value; + + private Granularity(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static Granularity forValue(final String value) { + return Promoter.enumFromString(value, Granularity.values()); + } } + /** * Converts a JSON String into a UsageRecord object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return UsageRecord object represented by the provided JSON */ - public static UsageRecord fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static UsageRecord fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, UsageRecord.class); @@ -71,14 +113,11 @@ public static UsageRecord fromJson( * Converts a JSON InputStream into a UsageRecord object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return UsageRecord object represented by the provided JSON */ - public static UsageRecord fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static UsageRecord fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, UsageRecord.class); @@ -89,89 +128,68 @@ public static UsageRecord fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String simSid; - private final String networkSid; - private final String fleetSid; - private final String isoCountry; - private final Map period; - private final Long dataUpload; + @Getter + private final Currency billedUnit; + @Getter private final Long dataDownload; + @Getter private final Long dataTotal; + @Getter private final BigDecimal dataTotalBilled; - private final Currency billedUnit; + @Getter + private final Long dataUpload; + @Getter + private final String fleetSid; + @Getter + private final String isoCountry; + @Getter + private final String networkSid; + @Getter + private final Object period; + @Getter + private final String simSid; @JsonCreator private UsageRecord( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("sim_sid") final String simSid, - @JsonProperty("network_sid") final String networkSid, - @JsonProperty("fleet_sid") final String fleetSid, - @JsonProperty("iso_country") final String isoCountry, - @JsonProperty("period") final Map period, - @JsonProperty("data_upload") final Long dataUpload, - @JsonProperty("data_download") final Long dataDownload, - @JsonProperty("data_total") final Long dataTotal, - @JsonProperty("data_total_billed") final BigDecimal dataTotalBilled, - @JsonProperty("billed_unit") @JsonDeserialize( - using = com.twilio.converter.CurrencyDeserializer.class - ) final Currency billedUnit + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("billed_unit") + @JsonDeserialize(using = com.twilio.converter.CurrencyDeserializer.class) final Currency billedUnit, + @JsonProperty("data_download") final Long dataDownload, + @JsonProperty("data_total") final Long dataTotal, + @JsonProperty("data_total_billed") final BigDecimal dataTotalBilled, + @JsonProperty("data_upload") final Long dataUpload, + @JsonProperty("fleet_sid") final String fleetSid, + @JsonProperty("iso_country") final String isoCountry, + @JsonProperty("network_sid") final String networkSid, + @JsonProperty("period") final Object period, + @JsonProperty("sim_sid") final String simSid ) { this.accountSid = accountSid; - this.simSid = simSid; - this.networkSid = networkSid; - this.fleetSid = fleetSid; - this.isoCountry = isoCountry; - this.period = period; - this.dataUpload = dataUpload; + this.billedUnit = billedUnit; this.dataDownload = dataDownload; this.dataTotal = dataTotal; this.dataTotalBilled = dataTotalBilled; - this.billedUnit = billedUnit; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getSimSid() { - return this.simSid; - } - - public final String getNetworkSid() { - return this.networkSid; - } - - public final String getFleetSid() { - return this.fleetSid; - } - - public final String getIsoCountry() { - return this.isoCountry; - } - - public final Map getPeriod() { - return this.period; - } - - public final Long getDataUpload() { - return this.dataUpload; - } - - public final Long getDataDownload() { - return this.dataDownload; - } - - public final Long getDataTotal() { - return this.dataTotal; - } - - public final BigDecimal getDataTotalBilled() { - return this.dataTotalBilled; - } - - public final Currency getBilledUnit() { - return this.billedUnit; + this.dataUpload = dataUpload; + this.fleetSid = fleetSid; + this.isoCountry = isoCountry; + this.networkSid = networkSid; + this.period = period; + this.simSid = simSid; } @Override @@ -185,79 +203,38 @@ public boolean equals(final Object o) { } UsageRecord other = (UsageRecord) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(simSid, other.simSid) && - Objects.equals(networkSid, other.networkSid) && - Objects.equals(fleetSid, other.fleetSid) && - Objects.equals(isoCountry, other.isoCountry) && - Objects.equals(period, other.period) && - Objects.equals(dataUpload, other.dataUpload) && - Objects.equals(dataDownload, other.dataDownload) && - Objects.equals(dataTotal, other.dataTotal) && - Objects.equals(dataTotalBilled, other.dataTotalBilled) && - Objects.equals(billedUnit, other.billedUnit) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(billedUnit, other.billedUnit) && + Objects.equals(dataDownload, other.dataDownload) && + Objects.equals(dataTotal, other.dataTotal) && + Objects.equals(dataTotalBilled, other.dataTotalBilled) && + Objects.equals(dataUpload, other.dataUpload) && + Objects.equals(fleetSid, other.fleetSid) && + Objects.equals(isoCountry, other.isoCountry) && + Objects.equals(networkSid, other.networkSid) && + Objects.equals(period, other.period) && + Objects.equals(simSid, other.simSid) ); } @Override public int hashCode() { return Objects.hash( - accountSid, - simSid, - networkSid, - fleetSid, - isoCountry, - period, - dataUpload, - dataDownload, - dataTotal, - dataTotalBilled, - billedUnit + accountSid, + billedUnit, + dataDownload, + dataTotal, + dataTotalBilled, + dataUpload, + fleetSid, + isoCountry, + networkSid, + period, + simSid ); } - public enum Group { - SIM("sim"), - FLEET("fleet"), - NETWORK("network"), - ISOCOUNTRY("isoCountry"); - private final String value; - - private Group(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static Group forValue(final String value) { - return Promoter.enumFromString(value, Group.values()); - } - } - - public enum Granularity { - HOUR("hour"), - DAY("day"), - ALL("all"); - - private final String value; - - private Granularity(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static Granularity forValue(final String value) { - return Promoter.enumFromString(value, Granularity.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/supersim/v1/UsageRecordReader.java b/src/main/java/com/twilio/rest/supersim/v1/UsageRecordReader.java index 657d503aa2..811bceb14e 100644 --- a/src/main/java/com/twilio/rest/supersim/v1/UsageRecordReader.java +++ b/src/main/java/com/twilio/rest/supersim/v1/UsageRecordReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -26,6 +27,7 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.time.ZonedDateTime; public class UsageRecordReader extends Reader { @@ -40,176 +42,171 @@ public class UsageRecordReader extends Reader { private ZonedDateTime endTime; private Long pageSize; - public UsageRecordReader() {} + public UsageRecordReader() { + } + public UsageRecordReader setSim(final String sim) { this.sim = sim; return this; } + public UsageRecordReader setFleet(final String fleet) { this.fleet = fleet; return this; } + public UsageRecordReader setNetwork(final String network) { this.network = network; return this; } + public UsageRecordReader setIsoCountry(final String isoCountry) { this.isoCountry = isoCountry; return this; } + public UsageRecordReader setGroup(final UsageRecord.Group group) { this.group = group; return this; } - public UsageRecordReader setGranularity( - final UsageRecord.Granularity granularity - ) { + + public UsageRecordReader setGranularity(final UsageRecord.Granularity granularity) { this.granularity = granularity; return this; } + public UsageRecordReader setStartTime(final ZonedDateTime startTime) { this.startTime = startTime; return this; } + public UsageRecordReader setEndTime(final ZonedDateTime endTime) { this.endTime = endTime; return this; } + public UsageRecordReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/UsageRecords"; + Request request = new Request( - HttpMethod.GET, - Domains.SUPERSIM.toString(), - path + HttpMethod.GET, + Domains.SUPERSIM.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "UsageRecord read failed: Unable to connect to server" - ); + throw new ApiConnectionException("UsageRecord read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "usage_records", - response.getContent(), - UsageRecord.class, - client.getObjectMapper() - ); + "usage_records", + response.getContent(), + UsageRecord.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.SUPERSIM.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.SUPERSIM.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (sim != null) { - request.addQueryParam("Sim", sim); + Serializer.toString(request, "Sim", sim, ParameterType.QUERY); } + + if (fleet != null) { - request.addQueryParam("Fleet", fleet); + Serializer.toString(request, "Fleet", fleet, ParameterType.QUERY); } + + if (network != null) { - request.addQueryParam("Network", network); + Serializer.toString(request, "Network", network, ParameterType.QUERY); } + + if (isoCountry != null) { - request.addQueryParam("IsoCountry", isoCountry); + Serializer.toString(request, "IsoCountry", isoCountry, ParameterType.QUERY); } + + if (group != null) { - request.addQueryParam("Group", group.toString()); + Serializer.toString(request, "Group", group, ParameterType.QUERY); } + + if (granularity != null) { - request.addQueryParam("Granularity", granularity.toString()); + Serializer.toString(request, "Granularity", granularity, ParameterType.QUERY); } + + if (startTime != null) { - request.addQueryParam( - "StartTime", - startTime.toInstant().toString() - ); + Serializer.toString(request, "StartTime", startTime, ParameterType.QUERY); } + if (endTime != null) { - request.addQueryParam("EndTime", endTime.toInstant().toString()); + Serializer.toString(request, "EndTime", endTime, ParameterType.QUERY); } + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/supersim/v1/networkaccessprofile/NetworkAccessProfileNetwork.java b/src/main/java/com/twilio/rest/supersim/v1/networkaccessprofile/NetworkAccessProfileNetwork.java index 7b89f7fa02..8c8baad062 100644 --- a/src/main/java/com/twilio/rest/supersim/v1/networkaccessprofile/NetworkAccessProfileNetwork.java +++ b/src/main/java/com/twilio/rest/supersim/v1/networkaccessprofile/NetworkAccessProfileNetwork.java @@ -18,82 +18,65 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.util.List; -import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class NetworkAccessProfileNetwork extends Resource { - private static final long serialVersionUID = 187162547019967L; - public static NetworkAccessProfileNetworkCreator creator( - final String pathNetworkAccessProfileSid, - final String network - ) { + public static NetworkAccessProfileNetworkCreator creator(final String pathnetworkAccessProfileSid, final String network) { return new NetworkAccessProfileNetworkCreator( - pathNetworkAccessProfileSid, - network + pathnetworkAccessProfileSid, network ); } - public static NetworkAccessProfileNetworkDeleter deleter( - final String pathNetworkAccessProfileSid, - final String pathSid - ) { + + public static NetworkAccessProfileNetworkDeleter deleter(final String pathnetworkAccessProfileSid, final String pathsid) { return new NetworkAccessProfileNetworkDeleter( - pathNetworkAccessProfileSid, - pathSid + pathnetworkAccessProfileSid, pathsid ); } - public static NetworkAccessProfileNetworkFetcher fetcher( - final String pathNetworkAccessProfileSid, - final String pathSid - ) { + + public static NetworkAccessProfileNetworkFetcher fetcher(final String pathnetworkAccessProfileSid, final String pathsid) { return new NetworkAccessProfileNetworkFetcher( - pathNetworkAccessProfileSid, - pathSid + pathnetworkAccessProfileSid, pathsid ); } - public static NetworkAccessProfileNetworkReader reader( - final String pathNetworkAccessProfileSid - ) { + + public static NetworkAccessProfileNetworkReader reader(final String pathnetworkAccessProfileSid) { return new NetworkAccessProfileNetworkReader( - pathNetworkAccessProfileSid + pathnetworkAccessProfileSid ); } + /** * Converts a JSON String into a NetworkAccessProfileNetwork object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return NetworkAccessProfileNetwork object represented by the provided JSON */ - public static NetworkAccessProfileNetwork fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static NetworkAccessProfileNetwork fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { - return objectMapper.readValue( - json, - NetworkAccessProfileNetwork.class - ); + return objectMapper.readValue(json, NetworkAccessProfileNetwork.class); } catch (final JsonMappingException | JsonParseException e) { throw new ApiException(e.getMessage(), e); } catch (final IOException e) { @@ -105,20 +88,14 @@ public static NetworkAccessProfileNetwork fromJson( * Converts a JSON InputStream into a NetworkAccessProfileNetwork object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return NetworkAccessProfileNetwork object represented by the provided JSON */ - public static NetworkAccessProfileNetwork fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static NetworkAccessProfileNetwork fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { - return objectMapper.readValue( - json, - NetworkAccessProfileNetwork.class - ); + return objectMapper.readValue(json, NetworkAccessProfileNetwork.class); } catch (final JsonMappingException | JsonParseException e) { throw new ApiException(e.getMessage(), e); } catch (final IOException e) { @@ -126,58 +103,49 @@ public static NetworkAccessProfileNetwork fromJson( } } - private final String sid; - private final String networkAccessProfileSid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String friendlyName; + @Getter + private final List identifiers; + @Getter private final String isoCountry; - private final List> identifiers; + @Getter + private final String networkAccessProfileSid; + @Getter + private final String sid; + @Getter private final URI url; @JsonCreator private NetworkAccessProfileNetwork( - @JsonProperty("sid") final String sid, - @JsonProperty( - "network_access_profile_sid" - ) final String networkAccessProfileSid, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("iso_country") final String isoCountry, - @JsonProperty("identifiers") final List< - Map - > identifiers, - @JsonProperty("url") final URI url + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("identifiers") final List identifiers, + @JsonProperty("iso_country") final String isoCountry, + @JsonProperty("network_access_profile_sid") final String networkAccessProfileSid, + @JsonProperty("sid") final String sid, + @JsonProperty("url") final URI url ) { - this.sid = sid; - this.networkAccessProfileSid = networkAccessProfileSid; this.friendlyName = friendlyName; - this.isoCountry = isoCountry; this.identifiers = identifiers; + this.isoCountry = isoCountry; + this.networkAccessProfileSid = networkAccessProfileSid; + this.sid = sid; this.url = url; } - public final String getSid() { - return this.sid; - } - - public final String getNetworkAccessProfileSid() { - return this.networkAccessProfileSid; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final String getIsoCountry() { - return this.isoCountry; - } - - public final List> getIdentifiers() { - return this.identifiers; - } - - public final URI getUrl() { - return this.url; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -189,29 +157,28 @@ public boolean equals(final Object o) { } NetworkAccessProfileNetwork other = (NetworkAccessProfileNetwork) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals( - networkAccessProfileSid, - other.networkAccessProfileSid - ) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(isoCountry, other.isoCountry) && - Objects.equals(identifiers, other.identifiers) && - Objects.equals(url, other.url) + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(identifiers, other.identifiers) && + Objects.equals(isoCountry, other.isoCountry) && + Objects.equals(networkAccessProfileSid, other.networkAccessProfileSid) && + Objects.equals(sid, other.sid) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - sid, - networkAccessProfileSid, - friendlyName, - isoCountry, - identifiers, - url + friendlyName, + identifiers, + isoCountry, + networkAccessProfileSid, + sid, + url ); } + + } + diff --git a/src/main/java/com/twilio/rest/supersim/v1/networkaccessprofile/NetworkAccessProfileNetworkCreator.java b/src/main/java/com/twilio/rest/supersim/v1/networkaccessprofile/NetworkAccessProfileNetworkCreator.java index 26a84c07b0..b3e7b0c35d 100644 --- a/src/main/java/com/twilio/rest/supersim/v1/networkaccessprofile/NetworkAccessProfileNetworkCreator.java +++ b/src/main/java/com/twilio/rest/supersim/v1/networkaccessprofile/NetworkAccessProfileNetworkCreator.java @@ -14,8 +14,11 @@ package com.twilio.rest.supersim.v1.networkaccessprofile; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,72 +28,63 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class NetworkAccessProfileNetworkCreator - extends Creator { +public class NetworkAccessProfileNetworkCreator extends Creator { - private String pathNetworkAccessProfileSid; + private String pathnetworkAccessProfileSid; private String network; - public NetworkAccessProfileNetworkCreator( - final String pathNetworkAccessProfileSid, - final String network - ) { - this.pathNetworkAccessProfileSid = pathNetworkAccessProfileSid; + public NetworkAccessProfileNetworkCreator(final String pathnetworkAccessProfileSid, final String network) { + this.pathnetworkAccessProfileSid = pathnetworkAccessProfileSid; this.network = network; } + public NetworkAccessProfileNetworkCreator setNetwork(final String network) { this.network = network; return this; } + @Override public NetworkAccessProfileNetwork create(final TwilioRestClient client) { - String path = - "/v1/NetworkAccessProfiles/{NetworkAccessProfileSid}/Networks"; - path = - path.replace( - "{" + "NetworkAccessProfileSid" + "}", - this.pathNetworkAccessProfileSid.toString() - ); - path = path.replace("{" + "Network" + "}", this.network.toString()); + String path = "/v1/NetworkAccessProfiles/{NetworkAccessProfileSid}/Networks"; + + path = path.replace("{" + "NetworkAccessProfileSid" + "}", this.pathnetworkAccessProfileSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.SUPERSIM.toString(), - path + HttpMethod.POST, + Domains.SUPERSIM.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "NetworkAccessProfileNetwork creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("NetworkAccessProfileNetwork creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return NetworkAccessProfileNetwork.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return NetworkAccessProfileNetwork.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (network != null) { - request.addPostParam("Network", network); + Serializer.toString(request, "Network", network, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/supersim/v1/networkaccessprofile/NetworkAccessProfileNetworkDeleter.java b/src/main/java/com/twilio/rest/supersim/v1/networkaccessprofile/NetworkAccessProfileNetworkDeleter.java index 098fca61ce..f5e5bb8b91 100644 --- a/src/main/java/com/twilio/rest/supersim/v1/networkaccessprofile/NetworkAccessProfileNetworkDeleter.java +++ b/src/main/java/com/twilio/rest/supersim/v1/networkaccessprofile/NetworkAccessProfileNetworkDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.supersim.v1.networkaccessprofile; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,54 +24,43 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class NetworkAccessProfileNetworkDeleter - extends Deleter { +public class NetworkAccessProfileNetworkDeleter extends Deleter { - private String pathNetworkAccessProfileSid; - private String pathSid; + private String pathnetworkAccessProfileSid; + private String pathsid; - public NetworkAccessProfileNetworkDeleter( - final String pathNetworkAccessProfileSid, - final String pathSid - ) { - this.pathNetworkAccessProfileSid = pathNetworkAccessProfileSid; - this.pathSid = pathSid; + public NetworkAccessProfileNetworkDeleter(final String pathnetworkAccessProfileSid, final String pathsid) { + this.pathnetworkAccessProfileSid = pathnetworkAccessProfileSid; + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { - String path = - "/v1/NetworkAccessProfiles/{NetworkAccessProfileSid}/Networks/{Sid}"; - path = - path.replace( - "{" + "NetworkAccessProfileSid" + "}", - this.pathNetworkAccessProfileSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/v1/NetworkAccessProfiles/{NetworkAccessProfileSid}/Networks/{Sid}"; + + path = path.replace("{" + "NetworkAccessProfileSid" + "}", this.pathnetworkAccessProfileSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.SUPERSIM.toString(), - path + HttpMethod.DELETE, + Domains.SUPERSIM.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "NetworkAccessProfileNetwork delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("NetworkAccessProfileNetwork delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/supersim/v1/networkaccessprofile/NetworkAccessProfileNetworkFetcher.java b/src/main/java/com/twilio/rest/supersim/v1/networkaccessprofile/NetworkAccessProfileNetworkFetcher.java index 78de615cbd..cb7c48a60e 100644 --- a/src/main/java/com/twilio/rest/supersim/v1/networkaccessprofile/NetworkAccessProfileNetworkFetcher.java +++ b/src/main/java/com/twilio/rest/supersim/v1/networkaccessprofile/NetworkAccessProfileNetworkFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.supersim.v1.networkaccessprofile; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,61 +24,46 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class NetworkAccessProfileNetworkFetcher - extends Fetcher { +public class NetworkAccessProfileNetworkFetcher extends Fetcher { - private String pathNetworkAccessProfileSid; - private String pathSid; + private String pathnetworkAccessProfileSid; + private String pathsid; - public NetworkAccessProfileNetworkFetcher( - final String pathNetworkAccessProfileSid, - final String pathSid - ) { - this.pathNetworkAccessProfileSid = pathNetworkAccessProfileSid; - this.pathSid = pathSid; + public NetworkAccessProfileNetworkFetcher(final String pathnetworkAccessProfileSid, final String pathsid) { + this.pathnetworkAccessProfileSid = pathnetworkAccessProfileSid; + this.pathsid = pathsid; } + @Override public NetworkAccessProfileNetwork fetch(final TwilioRestClient client) { - String path = - "/v1/NetworkAccessProfiles/{NetworkAccessProfileSid}/Networks/{Sid}"; - path = - path.replace( - "{" + "NetworkAccessProfileSid" + "}", - this.pathNetworkAccessProfileSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/v1/NetworkAccessProfiles/{NetworkAccessProfileSid}/Networks/{Sid}"; + + path = path.replace("{" + "NetworkAccessProfileSid" + "}", this.pathnetworkAccessProfileSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.SUPERSIM.toString(), - path + HttpMethod.GET, + Domains.SUPERSIM.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "NetworkAccessProfileNetwork fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("NetworkAccessProfileNetwork fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return NetworkAccessProfileNetwork.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return NetworkAccessProfileNetwork.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/supersim/v1/networkaccessprofile/NetworkAccessProfileNetworkReader.java b/src/main/java/com/twilio/rest/supersim/v1/networkaccessprofile/NetworkAccessProfileNetworkReader.java index 98342c6b28..0e9a267330 100644 --- a/src/main/java/com/twilio/rest/supersim/v1/networkaccessprofile/NetworkAccessProfileNetworkReader.java +++ b/src/main/java/com/twilio/rest/supersim/v1/networkaccessprofile/NetworkAccessProfileNetworkReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,125 +28,90 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class NetworkAccessProfileNetworkReader - extends Reader { +public class NetworkAccessProfileNetworkReader extends Reader { - private String pathNetworkAccessProfileSid; + private String pathnetworkAccessProfileSid; private Long pageSize; - public NetworkAccessProfileNetworkReader( - final String pathNetworkAccessProfileSid - ) { - this.pathNetworkAccessProfileSid = pathNetworkAccessProfileSid; + public NetworkAccessProfileNetworkReader(final String pathnetworkAccessProfileSid) { + this.pathnetworkAccessProfileSid = pathnetworkAccessProfileSid; } + public NetworkAccessProfileNetworkReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override - public ResourceSet read( - final TwilioRestClient client - ) { + public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } - public Page firstPage( - final TwilioRestClient client - ) { - String path = - "/v1/NetworkAccessProfiles/{NetworkAccessProfileSid}/Networks"; - path = - path.replace( - "{" + "NetworkAccessProfileSid" + "}", - this.pathNetworkAccessProfileSid.toString() - ); + public Page firstPage(final TwilioRestClient client) { + + String path = "/v1/NetworkAccessProfiles/{NetworkAccessProfileSid}/Networks"; + + path = path.replace("{" + "NetworkAccessProfileSid" + "}", this.pathnetworkAccessProfileSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.SUPERSIM.toString(), - path + HttpMethod.GET, + Domains.SUPERSIM.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "NetworkAccessProfileNetwork read failed: Unable to connect to server" - ); + throw new ApiConnectionException("NetworkAccessProfileNetwork read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "networks", - response.getContent(), - NetworkAccessProfileNetwork.class, - client.getObjectMapper() - ); + "networks", + response.getContent(), + NetworkAccessProfileNetwork.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.SUPERSIM.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.SUPERSIM.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/supersim/v1/sim/BillingPeriod.java b/src/main/java/com/twilio/rest/supersim/v1/sim/BillingPeriod.java index d73822c5b7..0651103af5 100644 --- a/src/main/java/com/twilio/rest/supersim/v1/sim/BillingPeriod.java +++ b/src/main/java/com/twilio/rest/supersim/v1/sim/BillingPeriod.java @@ -18,41 +18,63 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.time.ZonedDateTime; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class BillingPeriod extends Resource { - private static final long serialVersionUID = 154829037650501L; - public static BillingPeriodReader reader(final String pathSimSid) { - return new BillingPeriodReader(pathSimSid); + public static BillingPeriodReader reader(final String pathsimSid) { + return new BillingPeriodReader( + pathsimSid + ); + } + + + public enum BpType { + READY("ready"), + ACTIVE("active"); + + private final String value; + + private BpType(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static BpType forValue(final String value) { + return Promoter.enumFromString(value, BpType.values()); + } } + /** * Converts a JSON String into a BillingPeriod object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return BillingPeriod object represented by the provided JSON */ - public static BillingPeriod fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static BillingPeriod fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, BillingPeriod.class); @@ -67,14 +89,11 @@ public static BillingPeriod fromJson( * Converts a JSON InputStream into a BillingPeriod object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return BillingPeriod object represented by the provided JSON */ - public static BillingPeriod fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static BillingPeriod fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, BillingPeriod.class); @@ -85,66 +104,59 @@ public static BillingPeriod fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String simSid; - private final ZonedDateTime startTime; - private final ZonedDateTime endTime; - private final BillingPeriod.BpType periodType; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; + @Getter + private final ZonedDateTime endTime; + @Getter + private final BillingPeriod.BpType periodType; + @Getter + private final String sid; + @Getter + private final String simSid; + @Getter + private final ZonedDateTime startTime; @JsonCreator private BillingPeriod( - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("sim_sid") final String simSid, - @JsonProperty("start_time") final String startTime, - @JsonProperty("end_time") final String endTime, - @JsonProperty("period_type") final BillingPeriod.BpType periodType, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("end_time") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime endTime, + @JsonProperty("period_type") final BillingPeriod.BpType periodType, + @JsonProperty("sid") final String sid, + @JsonProperty("sim_sid") final String simSid, + @JsonProperty("start_time") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime startTime ) { - this.sid = sid; this.accountSid = accountSid; - this.simSid = simSid; - this.startTime = DateConverter.iso8601DateTimeFromString(startTime); - this.endTime = DateConverter.iso8601DateTimeFromString(endTime); + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; + this.endTime = endTime; this.periodType = periodType; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); - } - - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getSimSid() { - return this.simSid; - } - - public final ZonedDateTime getStartTime() { - return this.startTime; - } - - public final ZonedDateTime getEndTime() { - return this.endTime; - } - - public final BillingPeriod.BpType getPeriodType() { - return this.periodType; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; + this.sid = sid; + this.simSid = simSid; + this.startTime = startTime; } @Override @@ -158,50 +170,32 @@ public boolean equals(final Object o) { } BillingPeriod other = (BillingPeriod) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(simSid, other.simSid) && - Objects.equals(startTime, other.startTime) && - Objects.equals(endTime, other.endTime) && - Objects.equals(periodType, other.periodType) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(endTime, other.endTime) && + Objects.equals(periodType, other.periodType) && + Objects.equals(sid, other.sid) && + Objects.equals(simSid, other.simSid) && + Objects.equals(startTime, other.startTime) ); } @Override public int hashCode() { return Objects.hash( - sid, - accountSid, - simSid, - startTime, - endTime, - periodType, - dateCreated, - dateUpdated + accountSid, + dateCreated, + dateUpdated, + endTime, + periodType, + sid, + simSid, + startTime ); } - public enum BpType { - READY("ready"), - ACTIVE("active"); - - private final String value; - - private BpType(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - @JsonCreator - public static BpType forValue(final String value) { - return Promoter.enumFromString(value, BpType.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/supersim/v1/sim/BillingPeriodReader.java b/src/main/java/com/twilio/rest/supersim/v1/sim/BillingPeriodReader.java index 77f4709612..756eea9b87 100644 --- a/src/main/java/com/twilio/rest/supersim/v1/sim/BillingPeriodReader.java +++ b/src/main/java/com/twilio/rest/supersim/v1/sim/BillingPeriodReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,111 +30,88 @@ public class BillingPeriodReader extends Reader { - private String pathSimSid; + private String pathsimSid; private Long pageSize; - public BillingPeriodReader(final String pathSimSid) { - this.pathSimSid = pathSimSid; + public BillingPeriodReader(final String pathsimSid) { + this.pathsimSid = pathsimSid; } + public BillingPeriodReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/Sims/{SimSid}/BillingPeriods"; - path = path.replace("{" + "SimSid" + "}", this.pathSimSid.toString()); + + path = path.replace("{" + "SimSid" + "}", this.pathsimSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.SUPERSIM.toString(), - path + HttpMethod.GET, + Domains.SUPERSIM.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "BillingPeriod read failed: Unable to connect to server" - ); + throw new ApiConnectionException("BillingPeriod read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "billing_periods", - response.getContent(), - BillingPeriod.class, - client.getObjectMapper() - ); + "billing_periods", + response.getContent(), + BillingPeriod.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.SUPERSIM.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.SUPERSIM.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/supersim/v1/sim/SimIpAddress.java b/src/main/java/com/twilio/rest/supersim/v1/sim/SimIpAddress.java index 2983f71ba4..a3ccd623b8 100644 --- a/src/main/java/com/twilio/rest/supersim/v1/sim/SimIpAddress.java +++ b/src/main/java/com/twilio/rest/supersim/v1/sim/SimIpAddress.java @@ -18,39 +18,61 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class SimIpAddress extends Resource { - private static final long serialVersionUID = 180616107351268L; - public static SimIpAddressReader reader(final String pathSimSid) { - return new SimIpAddressReader(pathSimSid); + public static SimIpAddressReader reader(final String pathsimSid) { + return new SimIpAddressReader( + pathsimSid + ); + } + + + public enum IpAddressVersion { + I_PV4("IPv4"), + I_PV6("IPv6"); + + private final String value; + + private IpAddressVersion(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static IpAddressVersion forValue(final String value) { + return Promoter.enumFromString(value, IpAddressVersion.values()); + } } + /** * Converts a JSON String into a SimIpAddress object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return SimIpAddress object represented by the provided JSON */ - public static SimIpAddress fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static SimIpAddress fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, SimIpAddress.class); @@ -65,14 +87,11 @@ public static SimIpAddress fromJson( * Converts a JSON InputStream into a SimIpAddress object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return SimIpAddress object represented by the provided JSON */ - public static SimIpAddress fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static SimIpAddress fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, SimIpAddress.class); @@ -83,28 +102,33 @@ public static SimIpAddress fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String ipAddress; + @Getter private final SimIpAddress.IpAddressVersion ipAddressVersion; @JsonCreator private SimIpAddress( - @JsonProperty("ip_address") final String ipAddress, - @JsonProperty( - "ip_address_version" - ) final SimIpAddress.IpAddressVersion ipAddressVersion + @JsonProperty("ip_address") final String ipAddress, + @JsonProperty("ip_address_version") final SimIpAddress.IpAddressVersion ipAddressVersion ) { this.ipAddress = ipAddress; this.ipAddressVersion = ipAddressVersion; } - public final String getIpAddress() { - return this.ipAddress; - } - - public final SimIpAddress.IpAddressVersion getIpAddressVersion() { - return this.ipAddressVersion; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -116,35 +140,20 @@ public boolean equals(final Object o) { } SimIpAddress other = (SimIpAddress) o; - return ( - Objects.equals(ipAddress, other.ipAddress) && - Objects.equals(ipAddressVersion, other.ipAddressVersion) + Objects.equals(ipAddress, other.ipAddress) && + Objects.equals(ipAddressVersion, other.ipAddressVersion) ); } @Override public int hashCode() { - return Objects.hash(ipAddress, ipAddressVersion); + return Objects.hash( + ipAddress, + ipAddressVersion + ); } - public enum IpAddressVersion { - IPV4("IPv4"), - IPV6("IPv6"); - - private final String value; - private IpAddressVersion(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static IpAddressVersion forValue(final String value) { - return Promoter.enumFromString(value, IpAddressVersion.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/supersim/v1/sim/SimIpAddressReader.java b/src/main/java/com/twilio/rest/supersim/v1/sim/SimIpAddressReader.java index 958714d6f2..67e82a389f 100644 --- a/src/main/java/com/twilio/rest/supersim/v1/sim/SimIpAddressReader.java +++ b/src/main/java/com/twilio/rest/supersim/v1/sim/SimIpAddressReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,111 +30,88 @@ public class SimIpAddressReader extends Reader { - private String pathSimSid; + private String pathsimSid; private Long pageSize; - public SimIpAddressReader(final String pathSimSid) { - this.pathSimSid = pathSimSid; + public SimIpAddressReader(final String pathsimSid) { + this.pathsimSid = pathsimSid; } + public SimIpAddressReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/Sims/{SimSid}/IpAddresses"; - path = path.replace("{" + "SimSid" + "}", this.pathSimSid.toString()); + + path = path.replace("{" + "SimSid" + "}", this.pathsimSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.SUPERSIM.toString(), - path + HttpMethod.GET, + Domains.SUPERSIM.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "SimIpAddress read failed: Unable to connect to server" - ); + throw new ApiConnectionException("SimIpAddress read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "ip_addresses", - response.getContent(), - SimIpAddress.class, - client.getObjectMapper() - ); + "ip_addresses", + response.getContent(), + SimIpAddress.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.SUPERSIM.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.SUPERSIM.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/sync/v1/Service.java b/src/main/java/com/twilio/rest/sync/v1/Service.java index e18c5dccdc..11aa5bcd0a 100644 --- a/src/main/java/com/twilio/rest/sync/v1/Service.java +++ b/src/main/java/com/twilio/rest/sync/v1/Service.java @@ -18,59 +18,71 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Service extends Resource { - private static final long serialVersionUID = 61347848648189L; public static ServiceCreator creator() { - return new ServiceCreator(); + return new ServiceCreator( + + ); } - public static ServiceDeleter deleter(final String pathSid) { - return new ServiceDeleter(pathSid); + + public static ServiceDeleter deleter(final String pathsid) { + return new ServiceDeleter( + pathsid + ); } - public static ServiceFetcher fetcher(final String pathSid) { - return new ServiceFetcher(pathSid); + + public static ServiceFetcher fetcher(final String pathsid) { + return new ServiceFetcher( + pathsid + ); } + public static ServiceReader reader() { - return new ServiceReader(); + return new ServiceReader( + + ); } - public static ServiceUpdater updater(final String pathSid) { - return new ServiceUpdater(pathSid); + + public static ServiceUpdater updater(final String pathsid) { + return new ServiceUpdater( + pathsid + ); } + /** * Converts a JSON String into a Service object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Service object represented by the provided JSON */ - public static Service fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Service fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Service.class); @@ -85,14 +97,11 @@ public static Service fromJson( * Converts a JSON InputStream into a Service object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Service object represented by the provided JSON */ - public static Service fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Service fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Service.class); @@ -103,116 +112,81 @@ public static Service fromJson( } } - private final String sid; - private final String uniqueName; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String friendlyName; + @Getter + private final Boolean aclEnabled; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; + @Getter + private final String friendlyName; + @Getter + private final Map links; + @Getter + private final Boolean reachabilityDebouncingEnabled; + @Getter + private final Integer reachabilityDebouncingWindow; + @Getter + private final Boolean reachabilityWebhooksEnabled; + @Getter + private final String sid; + @Getter + private final String uniqueName; + @Getter private final URI url; + @Getter private final URI webhookUrl; + @Getter private final Boolean webhooksFromRestEnabled; - private final Boolean reachabilityWebhooksEnabled; - private final Boolean aclEnabled; - private final Boolean reachabilityDebouncingEnabled; - private final Integer reachabilityDebouncingWindow; - private final Map links; @JsonCreator private Service( - @JsonProperty("sid") final String sid, - @JsonProperty("unique_name") final String uniqueName, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("url") final URI url, - @JsonProperty("webhook_url") final URI webhookUrl, - @JsonProperty( - "webhooks_from_rest_enabled" - ) final Boolean webhooksFromRestEnabled, - @JsonProperty( - "reachability_webhooks_enabled" - ) final Boolean reachabilityWebhooksEnabled, - @JsonProperty("acl_enabled") final Boolean aclEnabled, - @JsonProperty( - "reachability_debouncing_enabled" - ) final Boolean reachabilityDebouncingEnabled, - @JsonProperty( - "reachability_debouncing_window" - ) final Integer reachabilityDebouncingWindow, - @JsonProperty("links") final Map links + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("acl_enabled") final Boolean aclEnabled, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("links") final Map links, + @JsonProperty("reachability_debouncing_enabled") final Boolean reachabilityDebouncingEnabled, + @JsonProperty("reachability_debouncing_window") final Integer reachabilityDebouncingWindow, + @JsonProperty("reachability_webhooks_enabled") final Boolean reachabilityWebhooksEnabled, + @JsonProperty("sid") final String sid, + @JsonProperty("unique_name") final String uniqueName, + @JsonProperty("url") final URI url, + @JsonProperty("webhook_url") final URI webhookUrl, + @JsonProperty("webhooks_from_rest_enabled") final Boolean webhooksFromRestEnabled ) { - this.sid = sid; - this.uniqueName = uniqueName; this.accountSid = accountSid; + this.aclEnabled = aclEnabled; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.friendlyName = friendlyName; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); + this.links = links; + this.reachabilityDebouncingEnabled = reachabilityDebouncingEnabled; + this.reachabilityDebouncingWindow = reachabilityDebouncingWindow; + this.reachabilityWebhooksEnabled = reachabilityWebhooksEnabled; + this.sid = sid; + this.uniqueName = uniqueName; this.url = url; this.webhookUrl = webhookUrl; this.webhooksFromRestEnabled = webhooksFromRestEnabled; - this.reachabilityWebhooksEnabled = reachabilityWebhooksEnabled; - this.aclEnabled = aclEnabled; - this.reachabilityDebouncingEnabled = reachabilityDebouncingEnabled; - this.reachabilityDebouncingWindow = reachabilityDebouncingWindow; - this.links = links; - } - - public final String getSid() { - return this.sid; - } - - public final String getUniqueName() { - return this.uniqueName; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final URI getUrl() { - return this.url; - } - - public final URI getWebhookUrl() { - return this.webhookUrl; - } - - public final Boolean getWebhooksFromRestEnabled() { - return this.webhooksFromRestEnabled; - } - - public final Boolean getReachabilityWebhooksEnabled() { - return this.reachabilityWebhooksEnabled; - } - - public final Boolean getAclEnabled() { - return this.aclEnabled; - } - - public final Boolean getReachabilityDebouncingEnabled() { - return this.reachabilityDebouncingEnabled; - } - - public final Integer getReachabilityDebouncingWindow() { - return this.reachabilityDebouncingWindow; - } - - public final Map getLinks() { - return this.links; } @Override @@ -226,54 +200,44 @@ public boolean equals(final Object o) { } Service other = (Service) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(uniqueName, other.uniqueName) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(url, other.url) && - Objects.equals(webhookUrl, other.webhookUrl) && - Objects.equals( - webhooksFromRestEnabled, - other.webhooksFromRestEnabled - ) && - Objects.equals( - reachabilityWebhooksEnabled, - other.reachabilityWebhooksEnabled - ) && - Objects.equals(aclEnabled, other.aclEnabled) && - Objects.equals( - reachabilityDebouncingEnabled, - other.reachabilityDebouncingEnabled - ) && - Objects.equals( - reachabilityDebouncingWindow, - other.reachabilityDebouncingWindow - ) && - Objects.equals(links, other.links) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(aclEnabled, other.aclEnabled) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(links, other.links) && + Objects.equals(reachabilityDebouncingEnabled, other.reachabilityDebouncingEnabled) && + Objects.equals(reachabilityDebouncingWindow, other.reachabilityDebouncingWindow) && + Objects.equals(reachabilityWebhooksEnabled, other.reachabilityWebhooksEnabled) && + Objects.equals(sid, other.sid) && + Objects.equals(uniqueName, other.uniqueName) && + Objects.equals(url, other.url) && + Objects.equals(webhookUrl, other.webhookUrl) && + Objects.equals(webhooksFromRestEnabled, other.webhooksFromRestEnabled) ); } @Override public int hashCode() { return Objects.hash( - sid, - uniqueName, - accountSid, - friendlyName, - dateCreated, - dateUpdated, - url, - webhookUrl, - webhooksFromRestEnabled, - reachabilityWebhooksEnabled, - aclEnabled, - reachabilityDebouncingEnabled, - reachabilityDebouncingWindow, - links + accountSid, + aclEnabled, + dateCreated, + dateUpdated, + friendlyName, + links, + reachabilityDebouncingEnabled, + reachabilityDebouncingWindow, + reachabilityWebhooksEnabled, + sid, + uniqueName, + url, + webhookUrl, + webhooksFromRestEnabled ); } + + } + diff --git a/src/main/java/com/twilio/rest/sync/v1/ServiceCreator.java b/src/main/java/com/twilio/rest/sync/v1/ServiceCreator.java index 88e9d2702a..47743fccf0 100644 --- a/src/main/java/com/twilio/rest/sync/v1/ServiceCreator.java +++ b/src/main/java/com/twilio/rest/sync/v1/ServiceCreator.java @@ -14,9 +14,11 @@ package com.twilio.rest.sync.v1; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; -import com.twilio.converter.Promoter; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,7 +27,7 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -import java.net.URI; + import java.net.URI; public class ServiceCreator extends Creator { @@ -38,81 +40,77 @@ public class ServiceCreator extends Creator { private Integer reachabilityDebouncingWindow; private Boolean webhooksFromRestEnabled; - public ServiceCreator() {} + public ServiceCreator() { + } + public ServiceCreator setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + public ServiceCreator setWebhookUrl(final URI webhookUrl) { this.webhookUrl = webhookUrl; return this; } - public ServiceCreator setWebhookUrl(final String webhookUrl) { - return setWebhookUrl(Promoter.uriFromString(webhookUrl)); - } - public ServiceCreator setReachabilityWebhooksEnabled( - final Boolean reachabilityWebhooksEnabled - ) { + public ServiceCreator setReachabilityWebhooksEnabled(final Boolean reachabilityWebhooksEnabled) { this.reachabilityWebhooksEnabled = reachabilityWebhooksEnabled; return this; } + public ServiceCreator setAclEnabled(final Boolean aclEnabled) { this.aclEnabled = aclEnabled; return this; } - public ServiceCreator setReachabilityDebouncingEnabled( - final Boolean reachabilityDebouncingEnabled - ) { + + public ServiceCreator setReachabilityDebouncingEnabled(final Boolean reachabilityDebouncingEnabled) { this.reachabilityDebouncingEnabled = reachabilityDebouncingEnabled; return this; } - public ServiceCreator setReachabilityDebouncingWindow( - final Integer reachabilityDebouncingWindow - ) { + + public ServiceCreator setReachabilityDebouncingWindow(final Integer reachabilityDebouncingWindow) { this.reachabilityDebouncingWindow = reachabilityDebouncingWindow; return this; } - public ServiceCreator setWebhooksFromRestEnabled( - final Boolean webhooksFromRestEnabled - ) { + + public ServiceCreator setWebhooksFromRestEnabled(final Boolean webhooksFromRestEnabled) { this.webhooksFromRestEnabled = webhooksFromRestEnabled; return this; } + @Override public Service create(final TwilioRestClient client) { + String path = "/v1/Services"; + Request request = new Request( - HttpMethod.POST, - Domains.SYNC.toString(), - path + HttpMethod.POST, + Domains.SYNC.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Service creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("Service creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -121,38 +119,41 @@ public Service create(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + if (webhookUrl != null) { - request.addPostParam("WebhookUrl", webhookUrl.toString()); + Serializer.toString(request, "WebhookUrl", webhookUrl, ParameterType.URLENCODED); } + + if (reachabilityWebhooksEnabled != null) { - request.addPostParam( - "ReachabilityWebhooksEnabled", - reachabilityWebhooksEnabled.toString() - ); + Serializer.toString(request, "ReachabilityWebhooksEnabled", reachabilityWebhooksEnabled, ParameterType.URLENCODED); } + + if (aclEnabled != null) { - request.addPostParam("AclEnabled", aclEnabled.toString()); + Serializer.toString(request, "AclEnabled", aclEnabled, ParameterType.URLENCODED); } + + if (reachabilityDebouncingEnabled != null) { - request.addPostParam( - "ReachabilityDebouncingEnabled", - reachabilityDebouncingEnabled.toString() - ); + Serializer.toString(request, "ReachabilityDebouncingEnabled", reachabilityDebouncingEnabled, ParameterType.URLENCODED); } + + if (reachabilityDebouncingWindow != null) { - request.addPostParam( - "ReachabilityDebouncingWindow", - reachabilityDebouncingWindow.toString() - ); + Serializer.toString(request, "ReachabilityDebouncingWindow", reachabilityDebouncingWindow, ParameterType.URLENCODED); } + + if (webhooksFromRestEnabled != null) { - request.addPostParam( - "WebhooksFromRestEnabled", - webhooksFromRestEnabled.toString() - ); + Serializer.toString(request, "WebhooksFromRestEnabled", webhooksFromRestEnabled, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/sync/v1/ServiceDeleter.java b/src/main/java/com/twilio/rest/sync/v1/ServiceDeleter.java index d8c5c5dead..7bd755f44f 100644 --- a/src/main/java/com/twilio/rest/sync/v1/ServiceDeleter.java +++ b/src/main/java/com/twilio/rest/sync/v1/ServiceDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.sync.v1; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,40 +26,38 @@ public class ServiceDeleter extends Deleter { - private String pathSid; + private String pathsid; - public ServiceDeleter(final String pathSid) { - this.pathSid = pathSid; + public ServiceDeleter(final String pathsid) { + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/v1/Services/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.SYNC.toString(), - path + HttpMethod.DELETE, + Domains.SYNC.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Service delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("Service delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/sync/v1/ServiceFetcher.java b/src/main/java/com/twilio/rest/sync/v1/ServiceFetcher.java index fb3fe21dfa..87cf8bf18f 100644 --- a/src/main/java/com/twilio/rest/sync/v1/ServiceFetcher.java +++ b/src/main/java/com/twilio/rest/sync/v1/ServiceFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.sync.v1; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,44 +26,41 @@ public class ServiceFetcher extends Fetcher { - private String pathSid; + private String pathsid; - public ServiceFetcher(final String pathSid) { - this.pathSid = pathSid; + public ServiceFetcher(final String pathsid) { + this.pathsid = pathsid; } + @Override public Service fetch(final TwilioRestClient client) { + String path = "/v1/Services/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.SYNC.toString(), - path + HttpMethod.GET, + Domains.SYNC.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Service fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Service fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Service.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/sync/v1/ServiceReader.java b/src/main/java/com/twilio/rest/sync/v1/ServiceReader.java index ef82cee003..b2fe175886 100644 --- a/src/main/java/com/twilio/rest/sync/v1/ServiceReader.java +++ b/src/main/java/com/twilio/rest/sync/v1/ServiceReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -31,105 +32,83 @@ public class ServiceReader extends Reader { private Long pageSize; - public ServiceReader() {} + public ServiceReader() { + } + public ServiceReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/Services"; + Request request = new Request( - HttpMethod.GET, - Domains.SYNC.toString(), - path + HttpMethod.GET, + Domains.SYNC.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Service read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Service read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "services", - response.getContent(), - Service.class, - client.getObjectMapper() - ); + "services", + response.getContent(), + Service.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.SYNC.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.SYNC.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/sync/v1/ServiceUpdater.java b/src/main/java/com/twilio/rest/sync/v1/ServiceUpdater.java index 647a6a26e9..acc60cc64d 100644 --- a/src/main/java/com/twilio/rest/sync/v1/ServiceUpdater.java +++ b/src/main/java/com/twilio/rest/sync/v1/ServiceUpdater.java @@ -16,7 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; -import com.twilio.converter.Promoter; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,11 +26,11 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.net.URI; public class ServiceUpdater extends Updater { - - private String pathSid; + private String pathsid; private URI webhookUrl; private String friendlyName; private Boolean reachabilityWebhooksEnabled; @@ -38,85 +39,80 @@ public class ServiceUpdater extends Updater { private Integer reachabilityDebouncingWindow; private Boolean webhooksFromRestEnabled; - public ServiceUpdater(final String pathSid) { - this.pathSid = pathSid; + public ServiceUpdater(final String pathsid) { + this.pathsid = pathsid; } + public ServiceUpdater setWebhookUrl(final URI webhookUrl) { this.webhookUrl = webhookUrl; return this; } - public ServiceUpdater setWebhookUrl(final String webhookUrl) { - return setWebhookUrl(Promoter.uriFromString(webhookUrl)); - } public ServiceUpdater setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } - public ServiceUpdater setReachabilityWebhooksEnabled( - final Boolean reachabilityWebhooksEnabled - ) { + + public ServiceUpdater setReachabilityWebhooksEnabled(final Boolean reachabilityWebhooksEnabled) { this.reachabilityWebhooksEnabled = reachabilityWebhooksEnabled; return this; } + public ServiceUpdater setAclEnabled(final Boolean aclEnabled) { this.aclEnabled = aclEnabled; return this; } - public ServiceUpdater setReachabilityDebouncingEnabled( - final Boolean reachabilityDebouncingEnabled - ) { + + public ServiceUpdater setReachabilityDebouncingEnabled(final Boolean reachabilityDebouncingEnabled) { this.reachabilityDebouncingEnabled = reachabilityDebouncingEnabled; return this; } - public ServiceUpdater setReachabilityDebouncingWindow( - final Integer reachabilityDebouncingWindow - ) { + + public ServiceUpdater setReachabilityDebouncingWindow(final Integer reachabilityDebouncingWindow) { this.reachabilityDebouncingWindow = reachabilityDebouncingWindow; return this; } - public ServiceUpdater setWebhooksFromRestEnabled( - final Boolean webhooksFromRestEnabled - ) { + + public ServiceUpdater setWebhooksFromRestEnabled(final Boolean webhooksFromRestEnabled) { this.webhooksFromRestEnabled = webhooksFromRestEnabled; return this; } + @Override public Service update(final TwilioRestClient client) { + String path = "/v1/Services/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.SYNC.toString(), - path + HttpMethod.POST, + Domains.SYNC.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Service update failed: Unable to connect to server" - ); + throw new ApiConnectionException("Service update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -125,38 +121,41 @@ public Service update(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (webhookUrl != null) { - request.addPostParam("WebhookUrl", webhookUrl.toString()); + Serializer.toString(request, "WebhookUrl", webhookUrl, ParameterType.URLENCODED); } + + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + if (reachabilityWebhooksEnabled != null) { - request.addPostParam( - "ReachabilityWebhooksEnabled", - reachabilityWebhooksEnabled.toString() - ); + Serializer.toString(request, "ReachabilityWebhooksEnabled", reachabilityWebhooksEnabled, ParameterType.URLENCODED); } + + if (aclEnabled != null) { - request.addPostParam("AclEnabled", aclEnabled.toString()); + Serializer.toString(request, "AclEnabled", aclEnabled, ParameterType.URLENCODED); } + + if (reachabilityDebouncingEnabled != null) { - request.addPostParam( - "ReachabilityDebouncingEnabled", - reachabilityDebouncingEnabled.toString() - ); + Serializer.toString(request, "ReachabilityDebouncingEnabled", reachabilityDebouncingEnabled, ParameterType.URLENCODED); } + + if (reachabilityDebouncingWindow != null) { - request.addPostParam( - "ReachabilityDebouncingWindow", - reachabilityDebouncingWindow.toString() - ); + Serializer.toString(request, "ReachabilityDebouncingWindow", reachabilityDebouncingWindow, ParameterType.URLENCODED); } + + if (webhooksFromRestEnabled != null) { - request.addPostParam( - "WebhooksFromRestEnabled", - webhooksFromRestEnabled.toString() - ); + Serializer.toString(request, "WebhooksFromRestEnabled", webhooksFromRestEnabled, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/sync/v1/service/Document.java b/src/main/java/com/twilio/rest/sync/v1/service/Document.java index e6b087729b..def15b491c 100644 --- a/src/main/java/com/twilio/rest/sync/v1/service/Document.java +++ b/src/main/java/com/twilio/rest/sync/v1/service/Document.java @@ -18,68 +18,71 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Document extends Resource { - private static final long serialVersionUID = 221157207950751L; - public static DocumentCreator creator(final String pathServiceSid) { - return new DocumentCreator(pathServiceSid); + public static DocumentCreator creator(final String pathserviceSid) { + return new DocumentCreator( + pathserviceSid + ); } - public static DocumentDeleter deleter( - final String pathServiceSid, - final String pathSid - ) { - return new DocumentDeleter(pathServiceSid, pathSid); + + public static DocumentDeleter deleter(final String pathserviceSid, final String pathsid) { + return new DocumentDeleter( + pathserviceSid, pathsid + ); } - public static DocumentFetcher fetcher( - final String pathServiceSid, - final String pathSid - ) { - return new DocumentFetcher(pathServiceSid, pathSid); + + public static DocumentFetcher fetcher(final String pathserviceSid, final String pathsid) { + return new DocumentFetcher( + pathserviceSid, pathsid + ); } - public static DocumentReader reader(final String pathServiceSid) { - return new DocumentReader(pathServiceSid); + + public static DocumentReader reader(final String pathserviceSid) { + return new DocumentReader( + pathserviceSid + ); } - public static DocumentUpdater updater( - final String pathServiceSid, - final String pathSid - ) { - return new DocumentUpdater(pathServiceSid, pathSid); + + public static DocumentUpdater updater(final String pathserviceSid, final String pathsid) { + return new DocumentUpdater( + pathserviceSid, pathsid + ); } + /** * Converts a JSON String into a Document object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Document object represented by the provided JSON */ - public static Document fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Document fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Document.class); @@ -94,14 +97,11 @@ public static Document fromJson( * Converts a JSON InputStream into a Document object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Document object represented by the provided JSON */ - public static Document fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Document fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Document.class); @@ -112,94 +112,74 @@ public static Document fromJson( } } - private final String sid; - private final String uniqueName; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String serviceSid; - private final URI url; - private final Map links; - private final String revision; - private final Map data; - private final ZonedDateTime dateExpires; + @Getter + private final String createdBy; + @Getter + private final Object data; + @Getter private final ZonedDateTime dateCreated; + @Getter + private final ZonedDateTime dateExpires; + @Getter private final ZonedDateTime dateUpdated; - private final String createdBy; + @Getter + private final Map links; + @Getter + private final String revision; + @Getter + private final String serviceSid; + @Getter + private final String sid; + @Getter + private final String uniqueName; + @Getter + private final URI url; @JsonCreator private Document( - @JsonProperty("sid") final String sid, - @JsonProperty("unique_name") final String uniqueName, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("service_sid") final String serviceSid, - @JsonProperty("url") final URI url, - @JsonProperty("links") final Map links, - @JsonProperty("revision") final String revision, - @JsonProperty("data") final Map data, - @JsonProperty("date_expires") final String dateExpires, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("created_by") final String createdBy + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("created_by") final String createdBy, + @JsonProperty("data") final Object data, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_expires") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateExpires, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("links") final Map links, + @JsonProperty("revision") final String revision, + @JsonProperty("service_sid") final String serviceSid, + @JsonProperty("sid") final String sid, + @JsonProperty("unique_name") final String uniqueName, + @JsonProperty("url") final URI url ) { - this.sid = sid; - this.uniqueName = uniqueName; this.accountSid = accountSid; - this.serviceSid = serviceSid; - this.url = url; + this.createdBy = createdBy; + this.data = data; + this.dateCreated = dateCreated; + this.dateExpires = dateExpires; + this.dateUpdated = dateUpdated; this.links = links; this.revision = revision; - this.data = data; - this.dateExpires = DateConverter.iso8601DateTimeFromString(dateExpires); - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); - this.createdBy = createdBy; - } - - public final String getSid() { - return this.sid; - } - - public final String getUniqueName() { - return this.uniqueName; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getServiceSid() { - return this.serviceSid; - } - - public final URI getUrl() { - return this.url; - } - - public final Map getLinks() { - return this.links; - } - - public final String getRevision() { - return this.revision; - } - - public final Map getData() { - return this.data; - } - - public final ZonedDateTime getDateExpires() { - return this.dateExpires; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final String getCreatedBy() { - return this.createdBy; + this.serviceSid = serviceSid; + this.sid = sid; + this.uniqueName = uniqueName; + this.url = url; } @Override @@ -213,38 +193,40 @@ public boolean equals(final Object o) { } Document other = (Document) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(uniqueName, other.uniqueName) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(serviceSid, other.serviceSid) && - Objects.equals(url, other.url) && - Objects.equals(links, other.links) && - Objects.equals(revision, other.revision) && - Objects.equals(data, other.data) && - Objects.equals(dateExpires, other.dateExpires) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(createdBy, other.createdBy) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(createdBy, other.createdBy) && + Objects.equals(data, other.data) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateExpires, other.dateExpires) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(links, other.links) && + Objects.equals(revision, other.revision) && + Objects.equals(serviceSid, other.serviceSid) && + Objects.equals(sid, other.sid) && + Objects.equals(uniqueName, other.uniqueName) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - sid, - uniqueName, - accountSid, - serviceSid, - url, - links, - revision, - data, - dateExpires, - dateCreated, - dateUpdated, - createdBy + accountSid, + createdBy, + data, + dateCreated, + dateExpires, + dateUpdated, + links, + revision, + serviceSid, + sid, + uniqueName, + url ); } + + } + diff --git a/src/main/java/com/twilio/rest/sync/v1/service/DocumentCreator.java b/src/main/java/com/twilio/rest/sync/v1/service/DocumentCreator.java index 3ad46deab0..39302a1cb5 100644 --- a/src/main/java/com/twilio/rest/sync/v1/service/DocumentCreator.java +++ b/src/main/java/com/twilio/rest/sync/v1/service/DocumentCreator.java @@ -14,10 +14,11 @@ package com.twilio.rest.sync.v1.service; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; -import com.twilio.converter.Converter; -import com.twilio.converter.Converter; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,81 +30,84 @@ public class DocumentCreator extends Creator { - private String pathServiceSid; + private String pathserviceSid; private String uniqueName; private Object data; private Integer ttl; - public DocumentCreator(final String pathServiceSid) { - this.pathServiceSid = pathServiceSid; + public DocumentCreator(final String pathserviceSid) { + this.pathserviceSid = pathserviceSid; } + public DocumentCreator setUniqueName(final String uniqueName) { this.uniqueName = uniqueName; return this; } + public DocumentCreator setData(final Object data) { this.data = data; return this; } + public DocumentCreator setTtl(final Integer ttl) { this.ttl = ttl; return this; } + @Override public Document create(final TwilioRestClient client) { + String path = "/v1/Services/{ServiceSid}/Documents"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.SYNC.toString(), - path + HttpMethod.POST, + Domains.SYNC.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Document creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("Document creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Document.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Document.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (uniqueName != null) { - request.addPostParam("UniqueName", uniqueName); + Serializer.toString(request, "UniqueName", uniqueName, ParameterType.URLENCODED); } + + if (data != null) { - request.addPostParam("Data", Converter.objectToJson(data)); + Serializer.toString(request, "Data", data, ParameterType.URLENCODED); } + + if (ttl != null) { - request.addPostParam("Ttl", ttl.toString()); + Serializer.toString(request, "Ttl", ttl, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/sync/v1/service/DocumentDeleter.java b/src/main/java/com/twilio/rest/sync/v1/service/DocumentDeleter.java index 184396ed13..217b359762 100644 --- a/src/main/java/com/twilio/rest/sync/v1/service/DocumentDeleter.java +++ b/src/main/java/com/twilio/rest/sync/v1/service/DocumentDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.sync.v1.service; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,47 +26,41 @@ public class DocumentDeleter extends Deleter { - private String pathServiceSid; - private String pathSid; + private String pathserviceSid; + private String pathsid; - public DocumentDeleter(final String pathServiceSid, final String pathSid) { - this.pathServiceSid = pathServiceSid; - this.pathSid = pathSid; + public DocumentDeleter(final String pathserviceSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/v1/Services/{ServiceSid}/Documents/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.SYNC.toString(), - path + HttpMethod.DELETE, + Domains.SYNC.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Document delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("Document delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/sync/v1/service/DocumentFetcher.java b/src/main/java/com/twilio/rest/sync/v1/service/DocumentFetcher.java index bbf4e97ebf..12c3562f42 100644 --- a/src/main/java/com/twilio/rest/sync/v1/service/DocumentFetcher.java +++ b/src/main/java/com/twilio/rest/sync/v1/service/DocumentFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.sync.v1.service; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,54 +26,44 @@ public class DocumentFetcher extends Fetcher { - private String pathServiceSid; - private String pathSid; + private String pathserviceSid; + private String pathsid; - public DocumentFetcher(final String pathServiceSid, final String pathSid) { - this.pathServiceSid = pathServiceSid; - this.pathSid = pathSid; + public DocumentFetcher(final String pathserviceSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathsid = pathsid; } + @Override public Document fetch(final TwilioRestClient client) { + String path = "/v1/Services/{ServiceSid}/Documents/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.SYNC.toString(), - path + HttpMethod.GET, + Domains.SYNC.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Document fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Document fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return Document.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Document.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/sync/v1/service/DocumentReader.java b/src/main/java/com/twilio/rest/sync/v1/service/DocumentReader.java index 745e5ca1c8..a3f09ac926 100644 --- a/src/main/java/com/twilio/rest/sync/v1/service/DocumentReader.java +++ b/src/main/java/com/twilio/rest/sync/v1/service/DocumentReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,115 +30,88 @@ public class DocumentReader extends Reader { - private String pathServiceSid; + private String pathserviceSid; private Long pageSize; - public DocumentReader(final String pathServiceSid) { - this.pathServiceSid = pathServiceSid; + public DocumentReader(final String pathserviceSid) { + this.pathserviceSid = pathserviceSid; } + public DocumentReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/Services/{ServiceSid}/Documents"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.SYNC.toString(), - path + HttpMethod.GET, + Domains.SYNC.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Document read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Document read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "documents", - response.getContent(), - Document.class, - client.getObjectMapper() - ); + "documents", + response.getContent(), + Document.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.SYNC.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.SYNC.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/sync/v1/service/DocumentUpdater.java b/src/main/java/com/twilio/rest/sync/v1/service/DocumentUpdater.java index 8c4bb058d5..b7031f1603 100644 --- a/src/main/java/com/twilio/rest/sync/v1/service/DocumentUpdater.java +++ b/src/main/java/com/twilio/rest/sync/v1/service/DocumentUpdater.java @@ -16,7 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; -import com.twilio.converter.Converter; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,89 +28,91 @@ import com.twilio.rest.Domains; public class DocumentUpdater extends Updater { - - private String pathServiceSid; - private String pathSid; + private String pathserviceSid; + private String pathsid; private String ifMatch; private Object data; private Integer ttl; - public DocumentUpdater(final String pathServiceSid, final String pathSid) { - this.pathServiceSid = pathServiceSid; - this.pathSid = pathSid; + public DocumentUpdater(final String pathserviceSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathsid = pathsid; } - public DocumentUpdater setIfMatch(final String ifMatch) { - this.ifMatch = ifMatch; - return this; - } public DocumentUpdater setData(final Object data) { this.data = data; return this; } + public DocumentUpdater setTtl(final Integer ttl) { this.ttl = ttl; return this; } + + public DocumentUpdater setIfMatch(final String ifMatch) { + this.ifMatch = ifMatch; + return this; + } + + @Override public Document update(final TwilioRestClient client) { + String path = "/v1/Services/{ServiceSid}/Documents/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.SYNC.toString(), - path + HttpMethod.POST, + Domains.SYNC.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); - addPostParams(request); addHeaderParams(request); + addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Document update failed: Unable to connect to server" - ); + throw new ApiConnectionException("Document update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Document.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Document.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (data != null) { - request.addPostParam("Data", Converter.objectToJson(data)); + Serializer.toString(request, "Data", data, ParameterType.URLENCODED); } + + if (ttl != null) { - request.addPostParam("Ttl", ttl.toString()); + Serializer.toString(request, "Ttl", ttl, ParameterType.URLENCODED); } + + } private void addHeaderParams(final Request request) { + if (ifMatch != null) { - request.addHeaderParam("If-Match", ifMatch); + Serializer.toString(request, "If-Match", ifMatch, ParameterType.HEADER); } + } } diff --git a/src/main/java/com/twilio/rest/sync/v1/service/SyncList.java b/src/main/java/com/twilio/rest/sync/v1/service/SyncList.java index 33c65b1a69..c2e2ee3fae 100644 --- a/src/main/java/com/twilio/rest/sync/v1/service/SyncList.java +++ b/src/main/java/com/twilio/rest/sync/v1/service/SyncList.java @@ -18,68 +18,71 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class SyncList extends Resource { - private static final long serialVersionUID = 91785924752769L; - public static SyncListCreator creator(final String pathServiceSid) { - return new SyncListCreator(pathServiceSid); + public static SyncListCreator creator(final String pathserviceSid) { + return new SyncListCreator( + pathserviceSid + ); } - public static SyncListDeleter deleter( - final String pathServiceSid, - final String pathSid - ) { - return new SyncListDeleter(pathServiceSid, pathSid); + + public static SyncListDeleter deleter(final String pathserviceSid, final String pathsid) { + return new SyncListDeleter( + pathserviceSid, pathsid + ); } - public static SyncListFetcher fetcher( - final String pathServiceSid, - final String pathSid - ) { - return new SyncListFetcher(pathServiceSid, pathSid); + + public static SyncListFetcher fetcher(final String pathserviceSid, final String pathsid) { + return new SyncListFetcher( + pathserviceSid, pathsid + ); } - public static SyncListReader reader(final String pathServiceSid) { - return new SyncListReader(pathServiceSid); + + public static SyncListReader reader(final String pathserviceSid) { + return new SyncListReader( + pathserviceSid + ); } - public static SyncListUpdater updater( - final String pathServiceSid, - final String pathSid - ) { - return new SyncListUpdater(pathServiceSid, pathSid); + + public static SyncListUpdater updater(final String pathserviceSid, final String pathsid) { + return new SyncListUpdater( + pathserviceSid, pathsid + ); } + /** * Converts a JSON String into a SyncList object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return SyncList object represented by the provided JSON */ - public static SyncList fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static SyncList fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, SyncList.class); @@ -94,14 +97,11 @@ public static SyncList fromJson( * Converts a JSON InputStream into a SyncList object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return SyncList object represented by the provided JSON */ - public static SyncList fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static SyncList fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, SyncList.class); @@ -112,87 +112,70 @@ public static SyncList fromJson( } } - private final String sid; - private final String uniqueName; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String serviceSid; - private final URI url; - private final Map links; - private final String revision; - private final ZonedDateTime dateExpires; + @Getter + private final String createdBy; + @Getter private final ZonedDateTime dateCreated; + @Getter + private final ZonedDateTime dateExpires; + @Getter private final ZonedDateTime dateUpdated; - private final String createdBy; + @Getter + private final Map links; + @Getter + private final String revision; + @Getter + private final String serviceSid; + @Getter + private final String sid; + @Getter + private final String uniqueName; + @Getter + private final URI url; @JsonCreator private SyncList( - @JsonProperty("sid") final String sid, - @JsonProperty("unique_name") final String uniqueName, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("service_sid") final String serviceSid, - @JsonProperty("url") final URI url, - @JsonProperty("links") final Map links, - @JsonProperty("revision") final String revision, - @JsonProperty("date_expires") final String dateExpires, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("created_by") final String createdBy + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("created_by") final String createdBy, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_expires") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateExpires, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("links") final Map links, + @JsonProperty("revision") final String revision, + @JsonProperty("service_sid") final String serviceSid, + @JsonProperty("sid") final String sid, + @JsonProperty("unique_name") final String uniqueName, + @JsonProperty("url") final URI url ) { - this.sid = sid; - this.uniqueName = uniqueName; this.accountSid = accountSid; - this.serviceSid = serviceSid; - this.url = url; + this.createdBy = createdBy; + this.dateCreated = dateCreated; + this.dateExpires = dateExpires; + this.dateUpdated = dateUpdated; this.links = links; this.revision = revision; - this.dateExpires = DateConverter.iso8601DateTimeFromString(dateExpires); - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); - this.createdBy = createdBy; - } - - public final String getSid() { - return this.sid; - } - - public final String getUniqueName() { - return this.uniqueName; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getServiceSid() { - return this.serviceSid; - } - - public final URI getUrl() { - return this.url; - } - - public final Map getLinks() { - return this.links; - } - - public final String getRevision() { - return this.revision; - } - - public final ZonedDateTime getDateExpires() { - return this.dateExpires; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final String getCreatedBy() { - return this.createdBy; + this.serviceSid = serviceSid; + this.sid = sid; + this.uniqueName = uniqueName; + this.url = url; } @Override @@ -206,36 +189,38 @@ public boolean equals(final Object o) { } SyncList other = (SyncList) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(uniqueName, other.uniqueName) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(serviceSid, other.serviceSid) && - Objects.equals(url, other.url) && - Objects.equals(links, other.links) && - Objects.equals(revision, other.revision) && - Objects.equals(dateExpires, other.dateExpires) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(createdBy, other.createdBy) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(createdBy, other.createdBy) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateExpires, other.dateExpires) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(links, other.links) && + Objects.equals(revision, other.revision) && + Objects.equals(serviceSid, other.serviceSid) && + Objects.equals(sid, other.sid) && + Objects.equals(uniqueName, other.uniqueName) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - sid, - uniqueName, - accountSid, - serviceSid, - url, - links, - revision, - dateExpires, - dateCreated, - dateUpdated, - createdBy + accountSid, + createdBy, + dateCreated, + dateExpires, + dateUpdated, + links, + revision, + serviceSid, + sid, + uniqueName, + url ); } + + } + diff --git a/src/main/java/com/twilio/rest/sync/v1/service/SyncListCreator.java b/src/main/java/com/twilio/rest/sync/v1/service/SyncListCreator.java index d8ce7b943c..e053922d0a 100644 --- a/src/main/java/com/twilio/rest/sync/v1/service/SyncListCreator.java +++ b/src/main/java/com/twilio/rest/sync/v1/service/SyncListCreator.java @@ -14,8 +14,11 @@ package com.twilio.rest.sync.v1.service; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,81 +30,84 @@ public class SyncListCreator extends Creator { - private String pathServiceSid; + private String pathserviceSid; private String uniqueName; private Integer ttl; private Integer collectionTtl; - public SyncListCreator(final String pathServiceSid) { - this.pathServiceSid = pathServiceSid; + public SyncListCreator(final String pathserviceSid) { + this.pathserviceSid = pathserviceSid; } + public SyncListCreator setUniqueName(final String uniqueName) { this.uniqueName = uniqueName; return this; } + public SyncListCreator setTtl(final Integer ttl) { this.ttl = ttl; return this; } + public SyncListCreator setCollectionTtl(final Integer collectionTtl) { this.collectionTtl = collectionTtl; return this; } + @Override public SyncList create(final TwilioRestClient client) { + String path = "/v1/Services/{ServiceSid}/Lists"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.SYNC.toString(), - path + HttpMethod.POST, + Domains.SYNC.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "SyncList creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("SyncList creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return SyncList.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return SyncList.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (uniqueName != null) { - request.addPostParam("UniqueName", uniqueName); + Serializer.toString(request, "UniqueName", uniqueName, ParameterType.URLENCODED); } + + if (ttl != null) { - request.addPostParam("Ttl", ttl.toString()); + Serializer.toString(request, "Ttl", ttl, ParameterType.URLENCODED); } + + if (collectionTtl != null) { - request.addPostParam("CollectionTtl", collectionTtl.toString()); + Serializer.toString(request, "CollectionTtl", collectionTtl, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/sync/v1/service/SyncListDeleter.java b/src/main/java/com/twilio/rest/sync/v1/service/SyncListDeleter.java index 7e8c3d24c0..2a639fea84 100644 --- a/src/main/java/com/twilio/rest/sync/v1/service/SyncListDeleter.java +++ b/src/main/java/com/twilio/rest/sync/v1/service/SyncListDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.sync.v1.service; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,47 +26,41 @@ public class SyncListDeleter extends Deleter { - private String pathServiceSid; - private String pathSid; + private String pathserviceSid; + private String pathsid; - public SyncListDeleter(final String pathServiceSid, final String pathSid) { - this.pathServiceSid = pathServiceSid; - this.pathSid = pathSid; + public SyncListDeleter(final String pathserviceSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/v1/Services/{ServiceSid}/Lists/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.SYNC.toString(), - path + HttpMethod.DELETE, + Domains.SYNC.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "SyncList delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("SyncList delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/sync/v1/service/SyncListFetcher.java b/src/main/java/com/twilio/rest/sync/v1/service/SyncListFetcher.java index 2b68e46671..dd67a1c61d 100644 --- a/src/main/java/com/twilio/rest/sync/v1/service/SyncListFetcher.java +++ b/src/main/java/com/twilio/rest/sync/v1/service/SyncListFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.sync.v1.service; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,54 +26,44 @@ public class SyncListFetcher extends Fetcher { - private String pathServiceSid; - private String pathSid; + private String pathserviceSid; + private String pathsid; - public SyncListFetcher(final String pathServiceSid, final String pathSid) { - this.pathServiceSid = pathServiceSid; - this.pathSid = pathSid; + public SyncListFetcher(final String pathserviceSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathsid = pathsid; } + @Override public SyncList fetch(final TwilioRestClient client) { + String path = "/v1/Services/{ServiceSid}/Lists/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.SYNC.toString(), - path + HttpMethod.GET, + Domains.SYNC.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "SyncList fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("SyncList fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return SyncList.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return SyncList.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/sync/v1/service/SyncListReader.java b/src/main/java/com/twilio/rest/sync/v1/service/SyncListReader.java index d0783d0a6f..7a9b777f1c 100644 --- a/src/main/java/com/twilio/rest/sync/v1/service/SyncListReader.java +++ b/src/main/java/com/twilio/rest/sync/v1/service/SyncListReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,115 +30,88 @@ public class SyncListReader extends Reader { - private String pathServiceSid; + private String pathserviceSid; private Long pageSize; - public SyncListReader(final String pathServiceSid) { - this.pathServiceSid = pathServiceSid; + public SyncListReader(final String pathserviceSid) { + this.pathserviceSid = pathserviceSid; } + public SyncListReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/Services/{ServiceSid}/Lists"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.SYNC.toString(), - path + HttpMethod.GET, + Domains.SYNC.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "SyncList read failed: Unable to connect to server" - ); + throw new ApiConnectionException("SyncList read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "lists", - response.getContent(), - SyncList.class, - client.getObjectMapper() - ); + "lists", + response.getContent(), + SyncList.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.SYNC.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.SYNC.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/sync/v1/service/SyncListUpdater.java b/src/main/java/com/twilio/rest/sync/v1/service/SyncListUpdater.java index 17ca6d6588..b274b29432 100644 --- a/src/main/java/com/twilio/rest/sync/v1/service/SyncListUpdater.java +++ b/src/main/java/com/twilio/rest/sync/v1/service/SyncListUpdater.java @@ -16,6 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -26,76 +28,75 @@ import com.twilio.rest.Domains; public class SyncListUpdater extends Updater { - - private String pathServiceSid; - private String pathSid; + private String pathserviceSid; + private String pathsid; private Integer ttl; private Integer collectionTtl; - public SyncListUpdater(final String pathServiceSid, final String pathSid) { - this.pathServiceSid = pathServiceSid; - this.pathSid = pathSid; + public SyncListUpdater(final String pathserviceSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathsid = pathsid; } + public SyncListUpdater setTtl(final Integer ttl) { this.ttl = ttl; return this; } + public SyncListUpdater setCollectionTtl(final Integer collectionTtl) { this.collectionTtl = collectionTtl; return this; } + @Override public SyncList update(final TwilioRestClient client) { + String path = "/v1/Services/{ServiceSid}/Lists/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.SYNC.toString(), - path + HttpMethod.POST, + Domains.SYNC.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "SyncList update failed: Unable to connect to server" - ); + throw new ApiConnectionException("SyncList update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return SyncList.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return SyncList.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (ttl != null) { - request.addPostParam("Ttl", ttl.toString()); + Serializer.toString(request, "Ttl", ttl, ParameterType.URLENCODED); } + + if (collectionTtl != null) { - request.addPostParam("CollectionTtl", collectionTtl.toString()); + Serializer.toString(request, "CollectionTtl", collectionTtl, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/sync/v1/service/SyncMap.java b/src/main/java/com/twilio/rest/sync/v1/service/SyncMap.java index 03df2a049f..3b3d54dc21 100644 --- a/src/main/java/com/twilio/rest/sync/v1/service/SyncMap.java +++ b/src/main/java/com/twilio/rest/sync/v1/service/SyncMap.java @@ -18,68 +18,71 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class SyncMap extends Resource { - private static final long serialVersionUID = 91785924752769L; - public static SyncMapCreator creator(final String pathServiceSid) { - return new SyncMapCreator(pathServiceSid); + public static SyncMapCreator creator(final String pathserviceSid) { + return new SyncMapCreator( + pathserviceSid + ); } - public static SyncMapDeleter deleter( - final String pathServiceSid, - final String pathSid - ) { - return new SyncMapDeleter(pathServiceSid, pathSid); + + public static SyncMapDeleter deleter(final String pathserviceSid, final String pathsid) { + return new SyncMapDeleter( + pathserviceSid, pathsid + ); } - public static SyncMapFetcher fetcher( - final String pathServiceSid, - final String pathSid - ) { - return new SyncMapFetcher(pathServiceSid, pathSid); + + public static SyncMapFetcher fetcher(final String pathserviceSid, final String pathsid) { + return new SyncMapFetcher( + pathserviceSid, pathsid + ); } - public static SyncMapReader reader(final String pathServiceSid) { - return new SyncMapReader(pathServiceSid); + + public static SyncMapReader reader(final String pathserviceSid) { + return new SyncMapReader( + pathserviceSid + ); } - public static SyncMapUpdater updater( - final String pathServiceSid, - final String pathSid - ) { - return new SyncMapUpdater(pathServiceSid, pathSid); + + public static SyncMapUpdater updater(final String pathserviceSid, final String pathsid) { + return new SyncMapUpdater( + pathserviceSid, pathsid + ); } + /** * Converts a JSON String into a SyncMap object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return SyncMap object represented by the provided JSON */ - public static SyncMap fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static SyncMap fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, SyncMap.class); @@ -94,14 +97,11 @@ public static SyncMap fromJson( * Converts a JSON InputStream into a SyncMap object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return SyncMap object represented by the provided JSON */ - public static SyncMap fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static SyncMap fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, SyncMap.class); @@ -112,87 +112,70 @@ public static SyncMap fromJson( } } - private final String sid; - private final String uniqueName; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String serviceSid; - private final URI url; - private final Map links; - private final String revision; - private final ZonedDateTime dateExpires; + @Getter + private final String createdBy; + @Getter private final ZonedDateTime dateCreated; + @Getter + private final ZonedDateTime dateExpires; + @Getter private final ZonedDateTime dateUpdated; - private final String createdBy; + @Getter + private final Map links; + @Getter + private final String revision; + @Getter + private final String serviceSid; + @Getter + private final String sid; + @Getter + private final String uniqueName; + @Getter + private final URI url; @JsonCreator private SyncMap( - @JsonProperty("sid") final String sid, - @JsonProperty("unique_name") final String uniqueName, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("service_sid") final String serviceSid, - @JsonProperty("url") final URI url, - @JsonProperty("links") final Map links, - @JsonProperty("revision") final String revision, - @JsonProperty("date_expires") final String dateExpires, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("created_by") final String createdBy + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("created_by") final String createdBy, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_expires") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateExpires, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("links") final Map links, + @JsonProperty("revision") final String revision, + @JsonProperty("service_sid") final String serviceSid, + @JsonProperty("sid") final String sid, + @JsonProperty("unique_name") final String uniqueName, + @JsonProperty("url") final URI url ) { - this.sid = sid; - this.uniqueName = uniqueName; this.accountSid = accountSid; - this.serviceSid = serviceSid; - this.url = url; + this.createdBy = createdBy; + this.dateCreated = dateCreated; + this.dateExpires = dateExpires; + this.dateUpdated = dateUpdated; this.links = links; this.revision = revision; - this.dateExpires = DateConverter.iso8601DateTimeFromString(dateExpires); - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); - this.createdBy = createdBy; - } - - public final String getSid() { - return this.sid; - } - - public final String getUniqueName() { - return this.uniqueName; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getServiceSid() { - return this.serviceSid; - } - - public final URI getUrl() { - return this.url; - } - - public final Map getLinks() { - return this.links; - } - - public final String getRevision() { - return this.revision; - } - - public final ZonedDateTime getDateExpires() { - return this.dateExpires; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final String getCreatedBy() { - return this.createdBy; + this.serviceSid = serviceSid; + this.sid = sid; + this.uniqueName = uniqueName; + this.url = url; } @Override @@ -206,36 +189,38 @@ public boolean equals(final Object o) { } SyncMap other = (SyncMap) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(uniqueName, other.uniqueName) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(serviceSid, other.serviceSid) && - Objects.equals(url, other.url) && - Objects.equals(links, other.links) && - Objects.equals(revision, other.revision) && - Objects.equals(dateExpires, other.dateExpires) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(createdBy, other.createdBy) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(createdBy, other.createdBy) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateExpires, other.dateExpires) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(links, other.links) && + Objects.equals(revision, other.revision) && + Objects.equals(serviceSid, other.serviceSid) && + Objects.equals(sid, other.sid) && + Objects.equals(uniqueName, other.uniqueName) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - sid, - uniqueName, - accountSid, - serviceSid, - url, - links, - revision, - dateExpires, - dateCreated, - dateUpdated, - createdBy + accountSid, + createdBy, + dateCreated, + dateExpires, + dateUpdated, + links, + revision, + serviceSid, + sid, + uniqueName, + url ); } + + } + diff --git a/src/main/java/com/twilio/rest/sync/v1/service/SyncMapCreator.java b/src/main/java/com/twilio/rest/sync/v1/service/SyncMapCreator.java index a1b37fada7..eef5583ae1 100644 --- a/src/main/java/com/twilio/rest/sync/v1/service/SyncMapCreator.java +++ b/src/main/java/com/twilio/rest/sync/v1/service/SyncMapCreator.java @@ -14,8 +14,11 @@ package com.twilio.rest.sync.v1.service; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,62 +30,61 @@ public class SyncMapCreator extends Creator { - private String pathServiceSid; + private String pathserviceSid; private String uniqueName; private Integer ttl; private Integer collectionTtl; - public SyncMapCreator(final String pathServiceSid) { - this.pathServiceSid = pathServiceSid; + public SyncMapCreator(final String pathserviceSid) { + this.pathserviceSid = pathserviceSid; } + public SyncMapCreator setUniqueName(final String uniqueName) { this.uniqueName = uniqueName; return this; } + public SyncMapCreator setTtl(final Integer ttl) { this.ttl = ttl; return this; } + public SyncMapCreator setCollectionTtl(final Integer collectionTtl) { this.collectionTtl = collectionTtl; return this; } + @Override public SyncMap create(final TwilioRestClient client) { + String path = "/v1/Services/{ServiceSid}/Maps"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.SYNC.toString(), - path + HttpMethod.POST, + Domains.SYNC.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "SyncMap creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("SyncMap creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -91,14 +93,21 @@ public SyncMap create(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (uniqueName != null) { - request.addPostParam("UniqueName", uniqueName); + Serializer.toString(request, "UniqueName", uniqueName, ParameterType.URLENCODED); } + + if (ttl != null) { - request.addPostParam("Ttl", ttl.toString()); + Serializer.toString(request, "Ttl", ttl, ParameterType.URLENCODED); } + + if (collectionTtl != null) { - request.addPostParam("CollectionTtl", collectionTtl.toString()); + Serializer.toString(request, "CollectionTtl", collectionTtl, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/sync/v1/service/SyncMapDeleter.java b/src/main/java/com/twilio/rest/sync/v1/service/SyncMapDeleter.java index 4d95cbb19d..f2bde1b3be 100644 --- a/src/main/java/com/twilio/rest/sync/v1/service/SyncMapDeleter.java +++ b/src/main/java/com/twilio/rest/sync/v1/service/SyncMapDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.sync.v1.service; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,47 +26,41 @@ public class SyncMapDeleter extends Deleter { - private String pathServiceSid; - private String pathSid; + private String pathserviceSid; + private String pathsid; - public SyncMapDeleter(final String pathServiceSid, final String pathSid) { - this.pathServiceSid = pathServiceSid; - this.pathSid = pathSid; + public SyncMapDeleter(final String pathserviceSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/v1/Services/{ServiceSid}/Maps/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.SYNC.toString(), - path + HttpMethod.DELETE, + Domains.SYNC.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "SyncMap delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("SyncMap delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/sync/v1/service/SyncMapFetcher.java b/src/main/java/com/twilio/rest/sync/v1/service/SyncMapFetcher.java index fd60528756..9e4f8336bb 100644 --- a/src/main/java/com/twilio/rest/sync/v1/service/SyncMapFetcher.java +++ b/src/main/java/com/twilio/rest/sync/v1/service/SyncMapFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.sync.v1.service; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,51 +26,44 @@ public class SyncMapFetcher extends Fetcher { - private String pathServiceSid; - private String pathSid; + private String pathserviceSid; + private String pathsid; - public SyncMapFetcher(final String pathServiceSid, final String pathSid) { - this.pathServiceSid = pathServiceSid; - this.pathSid = pathSid; + public SyncMapFetcher(final String pathserviceSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathsid = pathsid; } + @Override public SyncMap fetch(final TwilioRestClient client) { + String path = "/v1/Services/{ServiceSid}/Maps/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.SYNC.toString(), - path + HttpMethod.GET, + Domains.SYNC.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "SyncMap fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("SyncMap fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return SyncMap.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/sync/v1/service/SyncMapReader.java b/src/main/java/com/twilio/rest/sync/v1/service/SyncMapReader.java index 1bbf33ca64..fd6126d243 100644 --- a/src/main/java/com/twilio/rest/sync/v1/service/SyncMapReader.java +++ b/src/main/java/com/twilio/rest/sync/v1/service/SyncMapReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,115 +30,88 @@ public class SyncMapReader extends Reader { - private String pathServiceSid; + private String pathserviceSid; private Long pageSize; - public SyncMapReader(final String pathServiceSid) { - this.pathServiceSid = pathServiceSid; + public SyncMapReader(final String pathserviceSid) { + this.pathserviceSid = pathserviceSid; } + public SyncMapReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/Services/{ServiceSid}/Maps"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.SYNC.toString(), - path + HttpMethod.GET, + Domains.SYNC.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "SyncMap read failed: Unable to connect to server" - ); + throw new ApiConnectionException("SyncMap read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "maps", - response.getContent(), - SyncMap.class, - client.getObjectMapper() - ); + "maps", + response.getContent(), + SyncMap.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.SYNC.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.SYNC.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/sync/v1/service/SyncMapUpdater.java b/src/main/java/com/twilio/rest/sync/v1/service/SyncMapUpdater.java index 23e2dc3d65..5bd5d7f620 100644 --- a/src/main/java/com/twilio/rest/sync/v1/service/SyncMapUpdater.java +++ b/src/main/java/com/twilio/rest/sync/v1/service/SyncMapUpdater.java @@ -16,6 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -26,60 +28,57 @@ import com.twilio.rest.Domains; public class SyncMapUpdater extends Updater { - - private String pathServiceSid; - private String pathSid; + private String pathserviceSid; + private String pathsid; private Integer ttl; private Integer collectionTtl; - public SyncMapUpdater(final String pathServiceSid, final String pathSid) { - this.pathServiceSid = pathServiceSid; - this.pathSid = pathSid; + public SyncMapUpdater(final String pathserviceSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathsid = pathsid; } + public SyncMapUpdater setTtl(final Integer ttl) { this.ttl = ttl; return this; } + public SyncMapUpdater setCollectionTtl(final Integer collectionTtl) { this.collectionTtl = collectionTtl; return this; } + @Override public SyncMap update(final TwilioRestClient client) { + String path = "/v1/Services/{ServiceSid}/Maps/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.SYNC.toString(), - path + HttpMethod.POST, + Domains.SYNC.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "SyncMap update failed: Unable to connect to server" - ); + throw new ApiConnectionException("SyncMap update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -88,11 +87,16 @@ public SyncMap update(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (ttl != null) { - request.addPostParam("Ttl", ttl.toString()); + Serializer.toString(request, "Ttl", ttl, ParameterType.URLENCODED); } + + if (collectionTtl != null) { - request.addPostParam("CollectionTtl", collectionTtl.toString()); + Serializer.toString(request, "CollectionTtl", collectionTtl, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/sync/v1/service/SyncStream.java b/src/main/java/com/twilio/rest/sync/v1/service/SyncStream.java index 3a7c914b96..d487f9f5e2 100644 --- a/src/main/java/com/twilio/rest/sync/v1/service/SyncStream.java +++ b/src/main/java/com/twilio/rest/sync/v1/service/SyncStream.java @@ -18,68 +18,71 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class SyncStream extends Resource { - private static final long serialVersionUID = 122709874652370L; - public static SyncStreamCreator creator(final String pathServiceSid) { - return new SyncStreamCreator(pathServiceSid); + public static SyncStreamCreator creator(final String pathserviceSid) { + return new SyncStreamCreator( + pathserviceSid + ); } - public static SyncStreamDeleter deleter( - final String pathServiceSid, - final String pathSid - ) { - return new SyncStreamDeleter(pathServiceSid, pathSid); + + public static SyncStreamDeleter deleter(final String pathserviceSid, final String pathsid) { + return new SyncStreamDeleter( + pathserviceSid, pathsid + ); } - public static SyncStreamFetcher fetcher( - final String pathServiceSid, - final String pathSid - ) { - return new SyncStreamFetcher(pathServiceSid, pathSid); + + public static SyncStreamFetcher fetcher(final String pathserviceSid, final String pathsid) { + return new SyncStreamFetcher( + pathserviceSid, pathsid + ); } - public static SyncStreamReader reader(final String pathServiceSid) { - return new SyncStreamReader(pathServiceSid); + + public static SyncStreamReader reader(final String pathserviceSid) { + return new SyncStreamReader( + pathserviceSid + ); } - public static SyncStreamUpdater updater( - final String pathServiceSid, - final String pathSid - ) { - return new SyncStreamUpdater(pathServiceSid, pathSid); + + public static SyncStreamUpdater updater(final String pathserviceSid, final String pathsid) { + return new SyncStreamUpdater( + pathserviceSid, pathsid + ); } + /** * Converts a JSON String into a SyncStream object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return SyncStream object represented by the provided JSON */ - public static SyncStream fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static SyncStream fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, SyncStream.class); @@ -94,14 +97,11 @@ public static SyncStream fromJson( * Converts a JSON InputStream into a SyncStream object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return SyncStream object represented by the provided JSON */ - public static SyncStream fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static SyncStream fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, SyncStream.class); @@ -112,80 +112,66 @@ public static SyncStream fromJson( } } - private final String sid; - private final String uniqueName; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String serviceSid; - private final URI url; - private final Map links; - private final ZonedDateTime dateExpires; + @Getter + private final String createdBy; + @Getter private final ZonedDateTime dateCreated; + @Getter + private final ZonedDateTime dateExpires; + @Getter private final ZonedDateTime dateUpdated; - private final String createdBy; + @Getter + private final Map links; + @Getter + private final String serviceSid; + @Getter + private final String sid; + @Getter + private final String uniqueName; + @Getter + private final URI url; @JsonCreator private SyncStream( - @JsonProperty("sid") final String sid, - @JsonProperty("unique_name") final String uniqueName, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("service_sid") final String serviceSid, - @JsonProperty("url") final URI url, - @JsonProperty("links") final Map links, - @JsonProperty("date_expires") final String dateExpires, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("created_by") final String createdBy + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("created_by") final String createdBy, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_expires") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateExpires, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("links") final Map links, + @JsonProperty("service_sid") final String serviceSid, + @JsonProperty("sid") final String sid, + @JsonProperty("unique_name") final String uniqueName, + @JsonProperty("url") final URI url ) { - this.sid = sid; - this.uniqueName = uniqueName; this.accountSid = accountSid; + this.createdBy = createdBy; + this.dateCreated = dateCreated; + this.dateExpires = dateExpires; + this.dateUpdated = dateUpdated; + this.links = links; this.serviceSid = serviceSid; + this.sid = sid; + this.uniqueName = uniqueName; this.url = url; - this.links = links; - this.dateExpires = DateConverter.iso8601DateTimeFromString(dateExpires); - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); - this.createdBy = createdBy; - } - - public final String getSid() { - return this.sid; - } - - public final String getUniqueName() { - return this.uniqueName; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getServiceSid() { - return this.serviceSid; - } - - public final URI getUrl() { - return this.url; - } - - public final Map getLinks() { - return this.links; - } - - public final ZonedDateTime getDateExpires() { - return this.dateExpires; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final String getCreatedBy() { - return this.createdBy; } @Override @@ -199,34 +185,36 @@ public boolean equals(final Object o) { } SyncStream other = (SyncStream) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(uniqueName, other.uniqueName) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(serviceSid, other.serviceSid) && - Objects.equals(url, other.url) && - Objects.equals(links, other.links) && - Objects.equals(dateExpires, other.dateExpires) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(createdBy, other.createdBy) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(createdBy, other.createdBy) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateExpires, other.dateExpires) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(links, other.links) && + Objects.equals(serviceSid, other.serviceSid) && + Objects.equals(sid, other.sid) && + Objects.equals(uniqueName, other.uniqueName) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - sid, - uniqueName, - accountSid, - serviceSid, - url, - links, - dateExpires, - dateCreated, - dateUpdated, - createdBy + accountSid, + createdBy, + dateCreated, + dateExpires, + dateUpdated, + links, + serviceSid, + sid, + uniqueName, + url ); } + + } + diff --git a/src/main/java/com/twilio/rest/sync/v1/service/SyncStreamCreator.java b/src/main/java/com/twilio/rest/sync/v1/service/SyncStreamCreator.java index b0fa0670f7..dba516227e 100644 --- a/src/main/java/com/twilio/rest/sync/v1/service/SyncStreamCreator.java +++ b/src/main/java/com/twilio/rest/sync/v1/service/SyncStreamCreator.java @@ -14,8 +14,11 @@ package com.twilio.rest.sync.v1.service; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,72 +30,72 @@ public class SyncStreamCreator extends Creator { - private String pathServiceSid; + private String pathserviceSid; private String uniqueName; private Integer ttl; - public SyncStreamCreator(final String pathServiceSid) { - this.pathServiceSid = pathServiceSid; + public SyncStreamCreator(final String pathserviceSid) { + this.pathserviceSid = pathserviceSid; } + public SyncStreamCreator setUniqueName(final String uniqueName) { this.uniqueName = uniqueName; return this; } + public SyncStreamCreator setTtl(final Integer ttl) { this.ttl = ttl; return this; } + @Override public SyncStream create(final TwilioRestClient client) { + String path = "/v1/Services/{ServiceSid}/Streams"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.SYNC.toString(), - path + HttpMethod.POST, + Domains.SYNC.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "SyncStream creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("SyncStream creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return SyncStream.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return SyncStream.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (uniqueName != null) { - request.addPostParam("UniqueName", uniqueName); + Serializer.toString(request, "UniqueName", uniqueName, ParameterType.URLENCODED); } + + if (ttl != null) { - request.addPostParam("Ttl", ttl.toString()); + Serializer.toString(request, "Ttl", ttl, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/sync/v1/service/SyncStreamDeleter.java b/src/main/java/com/twilio/rest/sync/v1/service/SyncStreamDeleter.java index 383100a317..39b49155e5 100644 --- a/src/main/java/com/twilio/rest/sync/v1/service/SyncStreamDeleter.java +++ b/src/main/java/com/twilio/rest/sync/v1/service/SyncStreamDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.sync.v1.service; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,50 +26,41 @@ public class SyncStreamDeleter extends Deleter { - private String pathServiceSid; - private String pathSid; + private String pathserviceSid; + private String pathsid; - public SyncStreamDeleter( - final String pathServiceSid, - final String pathSid - ) { - this.pathServiceSid = pathServiceSid; - this.pathSid = pathSid; + public SyncStreamDeleter(final String pathserviceSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/v1/Services/{ServiceSid}/Streams/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.SYNC.toString(), - path + HttpMethod.DELETE, + Domains.SYNC.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "SyncStream delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("SyncStream delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/sync/v1/service/SyncStreamFetcher.java b/src/main/java/com/twilio/rest/sync/v1/service/SyncStreamFetcher.java index 9b7a206e64..c7249ec7d3 100644 --- a/src/main/java/com/twilio/rest/sync/v1/service/SyncStreamFetcher.java +++ b/src/main/java/com/twilio/rest/sync/v1/service/SyncStreamFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.sync.v1.service; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,57 +26,44 @@ public class SyncStreamFetcher extends Fetcher { - private String pathServiceSid; - private String pathSid; + private String pathserviceSid; + private String pathsid; - public SyncStreamFetcher( - final String pathServiceSid, - final String pathSid - ) { - this.pathServiceSid = pathServiceSid; - this.pathSid = pathSid; + public SyncStreamFetcher(final String pathserviceSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathsid = pathsid; } + @Override public SyncStream fetch(final TwilioRestClient client) { + String path = "/v1/Services/{ServiceSid}/Streams/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.SYNC.toString(), - path + HttpMethod.GET, + Domains.SYNC.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "SyncStream fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("SyncStream fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return SyncStream.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return SyncStream.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/sync/v1/service/SyncStreamReader.java b/src/main/java/com/twilio/rest/sync/v1/service/SyncStreamReader.java index 5101f9456b..fc862bb002 100644 --- a/src/main/java/com/twilio/rest/sync/v1/service/SyncStreamReader.java +++ b/src/main/java/com/twilio/rest/sync/v1/service/SyncStreamReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,115 +30,88 @@ public class SyncStreamReader extends Reader { - private String pathServiceSid; + private String pathserviceSid; private Long pageSize; - public SyncStreamReader(final String pathServiceSid) { - this.pathServiceSid = pathServiceSid; + public SyncStreamReader(final String pathserviceSid) { + this.pathserviceSid = pathserviceSid; } + public SyncStreamReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/Services/{ServiceSid}/Streams"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.SYNC.toString(), - path + HttpMethod.GET, + Domains.SYNC.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "SyncStream read failed: Unable to connect to server" - ); + throw new ApiConnectionException("SyncStream read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "streams", - response.getContent(), - SyncStream.class, - client.getObjectMapper() - ); + "streams", + response.getContent(), + SyncStream.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.SYNC.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.SYNC.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/sync/v1/service/SyncStreamUpdater.java b/src/main/java/com/twilio/rest/sync/v1/service/SyncStreamUpdater.java index 7ede505170..d4948084e4 100644 --- a/src/main/java/com/twilio/rest/sync/v1/service/SyncStreamUpdater.java +++ b/src/main/java/com/twilio/rest/sync/v1/service/SyncStreamUpdater.java @@ -16,6 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -26,70 +28,63 @@ import com.twilio.rest.Domains; public class SyncStreamUpdater extends Updater { - - private String pathServiceSid; - private String pathSid; + private String pathserviceSid; + private String pathsid; private Integer ttl; - public SyncStreamUpdater( - final String pathServiceSid, - final String pathSid - ) { - this.pathServiceSid = pathServiceSid; - this.pathSid = pathSid; + public SyncStreamUpdater(final String pathserviceSid, final String pathsid) { + this.pathserviceSid = pathserviceSid; + this.pathsid = pathsid; } + public SyncStreamUpdater setTtl(final Integer ttl) { this.ttl = ttl; return this; } + @Override public SyncStream update(final TwilioRestClient client) { + String path = "/v1/Services/{ServiceSid}/Streams/{Sid}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.SYNC.toString(), - path + HttpMethod.POST, + Domains.SYNC.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "SyncStream update failed: Unable to connect to server" - ); + throw new ApiConnectionException("SyncStream update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return SyncStream.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return SyncStream.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (ttl != null) { - request.addPostParam("Ttl", ttl.toString()); + Serializer.toString(request, "Ttl", ttl, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/sync/v1/service/document/DocumentPermission.java b/src/main/java/com/twilio/rest/sync/v1/service/document/DocumentPermission.java index a54ffa47b6..561ceb9f46 100644 --- a/src/main/java/com/twilio/rest/sync/v1/service/document/DocumentPermission.java +++ b/src/main/java/com/twilio/rest/sync/v1/service/document/DocumentPermission.java @@ -18,84 +18,61 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class DocumentPermission extends Resource { - private static final long serialVersionUID = 90173038651529L; - public static DocumentPermissionDeleter deleter( - final String pathServiceSid, - final String pathDocumentSid, - final String pathIdentity - ) { + public static DocumentPermissionDeleter deleter(final String pathserviceSid, final String pathdocumentSid, final String pathidentity) { return new DocumentPermissionDeleter( - pathServiceSid, - pathDocumentSid, - pathIdentity + pathserviceSid, pathdocumentSid, pathidentity ); } - public static DocumentPermissionFetcher fetcher( - final String pathServiceSid, - final String pathDocumentSid, - final String pathIdentity - ) { + + public static DocumentPermissionFetcher fetcher(final String pathserviceSid, final String pathdocumentSid, final String pathidentity) { return new DocumentPermissionFetcher( - pathServiceSid, - pathDocumentSid, - pathIdentity + pathserviceSid, pathdocumentSid, pathidentity ); } - public static DocumentPermissionReader reader( - final String pathServiceSid, - final String pathDocumentSid - ) { - return new DocumentPermissionReader(pathServiceSid, pathDocumentSid); + + public static DocumentPermissionReader reader(final String pathserviceSid, final String pathdocumentSid) { + return new DocumentPermissionReader( + pathserviceSid, pathdocumentSid + ); } - public static DocumentPermissionUpdater updater( - final String pathServiceSid, - final String pathDocumentSid, - final String pathIdentity, - final Boolean read, - final Boolean write, - final Boolean manage - ) { + + public static DocumentPermissionUpdater updater(final String pathserviceSid, final String pathdocumentSid, final String pathidentity, final Boolean read, final Boolean write, final Boolean manage) { return new DocumentPermissionUpdater( - pathServiceSid, - pathDocumentSid, - pathIdentity, - read, - write, - manage + pathserviceSid, pathdocumentSid, pathidentity, read, write, manage ); } + /** * Converts a JSON String into a DocumentPermission object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return DocumentPermission object represented by the provided JSON */ - public static DocumentPermission fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static DocumentPermission fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, DocumentPermission.class); @@ -110,14 +87,11 @@ public static DocumentPermission fromJson( * Converts a JSON InputStream into a DocumentPermission object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return DocumentPermission object represented by the provided JSON */ - public static DocumentPermission fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static DocumentPermission fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, DocumentPermission.class); @@ -128,66 +102,55 @@ public static DocumentPermission fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String serviceSid; + @Getter private final String documentSid; + @Getter private final String identity; - private final Boolean read; - private final Boolean write; + @Getter private final Boolean manage; + @Getter + private final Boolean read; + @Getter + private final String serviceSid; + @Getter private final URI url; + @Getter + private final Boolean write; @JsonCreator private DocumentPermission( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("service_sid") final String serviceSid, - @JsonProperty("document_sid") final String documentSid, - @JsonProperty("identity") final String identity, - @JsonProperty("read") final Boolean read, - @JsonProperty("write") final Boolean write, - @JsonProperty("manage") final Boolean manage, - @JsonProperty("url") final URI url + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("document_sid") final String documentSid, + @JsonProperty("identity") final String identity, + @JsonProperty("manage") final Boolean manage, + @JsonProperty("read") final Boolean read, + @JsonProperty("service_sid") final String serviceSid, + @JsonProperty("url") final URI url, + @JsonProperty("write") final Boolean write ) { this.accountSid = accountSid; - this.serviceSid = serviceSid; this.documentSid = documentSid; this.identity = identity; - this.read = read; - this.write = write; this.manage = manage; + this.read = read; + this.serviceSid = serviceSid; this.url = url; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getServiceSid() { - return this.serviceSid; - } - - public final String getDocumentSid() { - return this.documentSid; - } - - public final String getIdentity() { - return this.identity; - } - - public final Boolean getRead() { - return this.read; - } - - public final Boolean getWrite() { - return this.write; - } - - public final Boolean getManage() { - return this.manage; - } - - public final URI getUrl() { - return this.url; + this.write = write; } @Override @@ -201,30 +164,32 @@ public boolean equals(final Object o) { } DocumentPermission other = (DocumentPermission) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(serviceSid, other.serviceSid) && - Objects.equals(documentSid, other.documentSid) && - Objects.equals(identity, other.identity) && - Objects.equals(read, other.read) && - Objects.equals(write, other.write) && - Objects.equals(manage, other.manage) && - Objects.equals(url, other.url) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(documentSid, other.documentSid) && + Objects.equals(identity, other.identity) && + Objects.equals(manage, other.manage) && + Objects.equals(read, other.read) && + Objects.equals(serviceSid, other.serviceSid) && + Objects.equals(url, other.url) && + Objects.equals(write, other.write) ); } @Override public int hashCode() { return Objects.hash( - accountSid, - serviceSid, - documentSid, - identity, - read, - write, - manage, - url + accountSid, + documentSid, + identity, + manage, + read, + serviceSid, + url, + write ); } + + } + diff --git a/src/main/java/com/twilio/rest/sync/v1/service/document/DocumentPermissionDeleter.java b/src/main/java/com/twilio/rest/sync/v1/service/document/DocumentPermissionDeleter.java index 26b09aefd4..1a5b58229b 100644 --- a/src/main/java/com/twilio/rest/sync/v1/service/document/DocumentPermissionDeleter.java +++ b/src/main/java/com/twilio/rest/sync/v1/service/document/DocumentPermissionDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.sync.v1.service.document; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,60 +26,44 @@ public class DocumentPermissionDeleter extends Deleter { - private String pathServiceSid; - private String pathDocumentSid; - private String pathIdentity; + private String pathserviceSid; + private String pathdocumentSid; + private String pathidentity; - public DocumentPermissionDeleter( - final String pathServiceSid, - final String pathDocumentSid, - final String pathIdentity - ) { - this.pathServiceSid = pathServiceSid; - this.pathDocumentSid = pathDocumentSid; - this.pathIdentity = pathIdentity; + public DocumentPermissionDeleter(final String pathserviceSid, final String pathdocumentSid, final String pathidentity) { + this.pathserviceSid = pathserviceSid; + this.pathdocumentSid = pathdocumentSid; + this.pathidentity = pathidentity; } + @Override public boolean delete(final TwilioRestClient client) { - String path = - "/v1/Services/{ServiceSid}/Documents/{DocumentSid}/Permissions/{Identity}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = - path.replace( - "{" + "DocumentSid" + "}", - this.pathDocumentSid.toString() - ); - path = - path.replace("{" + "Identity" + "}", this.pathIdentity.toString()); + String path = "/v1/Services/{ServiceSid}/Documents/{DocumentSid}/Permissions/{Identity}"; + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "DocumentSid" + "}", this.pathdocumentSid.toString()); + path = path.replace("{" + "Identity" + "}", this.pathidentity.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.SYNC.toString(), - path + HttpMethod.DELETE, + Domains.SYNC.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "DocumentPermission delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("DocumentPermission delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/sync/v1/service/document/DocumentPermissionFetcher.java b/src/main/java/com/twilio/rest/sync/v1/service/document/DocumentPermissionFetcher.java index 6108356930..7c41a6ab23 100644 --- a/src/main/java/com/twilio/rest/sync/v1/service/document/DocumentPermissionFetcher.java +++ b/src/main/java/com/twilio/rest/sync/v1/service/document/DocumentPermissionFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.sync.v1.service.document; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,67 +26,47 @@ public class DocumentPermissionFetcher extends Fetcher { - private String pathServiceSid; - private String pathDocumentSid; - private String pathIdentity; + private String pathserviceSid; + private String pathdocumentSid; + private String pathidentity; - public DocumentPermissionFetcher( - final String pathServiceSid, - final String pathDocumentSid, - final String pathIdentity - ) { - this.pathServiceSid = pathServiceSid; - this.pathDocumentSid = pathDocumentSid; - this.pathIdentity = pathIdentity; + public DocumentPermissionFetcher(final String pathserviceSid, final String pathdocumentSid, final String pathidentity) { + this.pathserviceSid = pathserviceSid; + this.pathdocumentSid = pathdocumentSid; + this.pathidentity = pathidentity; } + @Override public DocumentPermission fetch(final TwilioRestClient client) { - String path = - "/v1/Services/{ServiceSid}/Documents/{DocumentSid}/Permissions/{Identity}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = - path.replace( - "{" + "DocumentSid" + "}", - this.pathDocumentSid.toString() - ); - path = - path.replace("{" + "Identity" + "}", this.pathIdentity.toString()); + String path = "/v1/Services/{ServiceSid}/Documents/{DocumentSid}/Permissions/{Identity}"; + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "DocumentSid" + "}", this.pathdocumentSid.toString()); + path = path.replace("{" + "Identity" + "}", this.pathidentity.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.SYNC.toString(), - path + HttpMethod.GET, + Domains.SYNC.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "DocumentPermission fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("DocumentPermission fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return DocumentPermission.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return DocumentPermission.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/sync/v1/service/document/DocumentPermissionReader.java b/src/main/java/com/twilio/rest/sync/v1/service/document/DocumentPermissionReader.java index 09df88e67a..92d52bef27 100644 --- a/src/main/java/com/twilio/rest/sync/v1/service/document/DocumentPermissionReader.java +++ b/src/main/java/com/twilio/rest/sync/v1/service/document/DocumentPermissionReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,126 +30,91 @@ public class DocumentPermissionReader extends Reader { - private String pathServiceSid; - private String pathDocumentSid; + private String pathserviceSid; + private String pathdocumentSid; private Long pageSize; - public DocumentPermissionReader( - final String pathServiceSid, - final String pathDocumentSid - ) { - this.pathServiceSid = pathServiceSid; - this.pathDocumentSid = pathDocumentSid; + public DocumentPermissionReader(final String pathserviceSid, final String pathdocumentSid) { + this.pathserviceSid = pathserviceSid; + this.pathdocumentSid = pathdocumentSid; } + public DocumentPermissionReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { - String path = - "/v1/Services/{ServiceSid}/Documents/{DocumentSid}/Permissions"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = - path.replace( - "{" + "DocumentSid" + "}", - this.pathDocumentSid.toString() - ); + + String path = "/v1/Services/{ServiceSid}/Documents/{DocumentSid}/Permissions"; + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "DocumentSid" + "}", this.pathdocumentSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.SYNC.toString(), - path + HttpMethod.GET, + Domains.SYNC.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "DocumentPermission read failed: Unable to connect to server" - ); + throw new ApiConnectionException("DocumentPermission read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "permissions", - response.getContent(), - DocumentPermission.class, - client.getObjectMapper() - ); + "permissions", + response.getContent(), + DocumentPermission.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.SYNC.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.SYNC.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/sync/v1/service/document/DocumentPermissionUpdater.java b/src/main/java/com/twilio/rest/sync/v1/service/document/DocumentPermissionUpdater.java index 25aa169610..dc4adc7eeb 100644 --- a/src/main/java/com/twilio/rest/sync/v1/service/document/DocumentPermissionUpdater.java +++ b/src/main/java/com/twilio/rest/sync/v1/service/document/DocumentPermissionUpdater.java @@ -16,6 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -26,107 +28,93 @@ import com.twilio.rest.Domains; public class DocumentPermissionUpdater extends Updater { - - private String pathServiceSid; - private String pathDocumentSid; - private String pathIdentity; + private String pathserviceSid; + private String pathdocumentSid; + private String pathidentity; private Boolean read; private Boolean write; private Boolean manage; - public DocumentPermissionUpdater( - final String pathServiceSid, - final String pathDocumentSid, - final String pathIdentity, - final Boolean read, - final Boolean write, - final Boolean manage - ) { - this.pathServiceSid = pathServiceSid; - this.pathDocumentSid = pathDocumentSid; - this.pathIdentity = pathIdentity; + public DocumentPermissionUpdater(final String pathserviceSid, final String pathdocumentSid, final String pathidentity, final Boolean read, final Boolean write, final Boolean manage) { + this.pathserviceSid = pathserviceSid; + this.pathdocumentSid = pathdocumentSid; + this.pathidentity = pathidentity; this.read = read; this.write = write; this.manage = manage; } + public DocumentPermissionUpdater setRead(final Boolean read) { this.read = read; return this; } + public DocumentPermissionUpdater setWrite(final Boolean write) { this.write = write; return this; } + public DocumentPermissionUpdater setManage(final Boolean manage) { this.manage = manage; return this; } + @Override public DocumentPermission update(final TwilioRestClient client) { - String path = - "/v1/Services/{ServiceSid}/Documents/{DocumentSid}/Permissions/{Identity}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = - path.replace( - "{" + "DocumentSid" + "}", - this.pathDocumentSid.toString() - ); - path = - path.replace("{" + "Identity" + "}", this.pathIdentity.toString()); - path = path.replace("{" + "Read" + "}", this.read.toString()); - path = path.replace("{" + "Write" + "}", this.write.toString()); - path = path.replace("{" + "Manage" + "}", this.manage.toString()); + String path = "/v1/Services/{ServiceSid}/Documents/{DocumentSid}/Permissions/{Identity}"; + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "DocumentSid" + "}", this.pathdocumentSid.toString()); + path = path.replace("{" + "Identity" + "}", this.pathidentity.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.SYNC.toString(), - path + HttpMethod.POST, + Domains.SYNC.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "DocumentPermission update failed: Unable to connect to server" - ); + throw new ApiConnectionException("DocumentPermission update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return DocumentPermission.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return DocumentPermission.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (read != null) { - request.addPostParam("Read", read.toString()); + Serializer.toString(request, "Read", read, ParameterType.URLENCODED); } + + if (write != null) { - request.addPostParam("Write", write.toString()); + Serializer.toString(request, "Write", write, ParameterType.URLENCODED); } + + if (manage != null) { - request.addPostParam("Manage", manage.toString()); + Serializer.toString(request, "Manage", manage, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/sync/v1/service/synclist/SyncListItem.java b/src/main/java/com/twilio/rest/sync/v1/service/synclist/SyncListItem.java index 00bbcafebd..28d05b3fa3 100644 --- a/src/main/java/com/twilio/rest/sync/v1/service/synclist/SyncListItem.java +++ b/src/main/java/com/twilio/rest/sync/v1/service/synclist/SyncListItem.java @@ -18,79 +18,112 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; -import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class SyncListItem extends Resource { - private static final long serialVersionUID = 92711713432732L; - public static SyncListItemCreator creator( - final String pathServiceSid, - final String pathListSid, - final Object data - ) { - return new SyncListItemCreator(pathServiceSid, pathListSid, data); + public static SyncListItemCreator creator(final String pathserviceSid, final String pathlistSid, final Object data) { + return new SyncListItemCreator( + pathserviceSid, pathlistSid, data + ); } - public static SyncListItemDeleter deleter( - final String pathServiceSid, - final String pathListSid, - final Integer pathIndex - ) { - return new SyncListItemDeleter(pathServiceSid, pathListSid, pathIndex); + + public static SyncListItemDeleter deleter(final String pathserviceSid, final String pathlistSid, final Integer pathindex) { + return new SyncListItemDeleter( + pathserviceSid, pathlistSid, pathindex + ); } - public static SyncListItemFetcher fetcher( - final String pathServiceSid, - final String pathListSid, - final Integer pathIndex - ) { - return new SyncListItemFetcher(pathServiceSid, pathListSid, pathIndex); + + public static SyncListItemFetcher fetcher(final String pathserviceSid, final String pathlistSid, final Integer pathindex) { + return new SyncListItemFetcher( + pathserviceSid, pathlistSid, pathindex + ); } - public static SyncListItemReader reader( - final String pathServiceSid, - final String pathListSid - ) { - return new SyncListItemReader(pathServiceSid, pathListSid); + + public static SyncListItemReader reader(final String pathserviceSid, final String pathlistSid) { + return new SyncListItemReader( + pathserviceSid, pathlistSid + ); } - public static SyncListItemUpdater updater( - final String pathServiceSid, - final String pathListSid, - final Integer pathIndex - ) { - return new SyncListItemUpdater(pathServiceSid, pathListSid, pathIndex); + + public static SyncListItemUpdater updater(final String pathserviceSid, final String pathlistSid, final Integer pathindex) { + return new SyncListItemUpdater( + pathserviceSid, pathlistSid, pathindex + ); + } + + + public enum QueryResultOrder { + ASC("asc"), + DESC("desc"); + + private final String value; + + private QueryResultOrder(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static QueryResultOrder forValue(final String value) { + return Promoter.enumFromString(value, QueryResultOrder.values()); + } } + public enum QueryFromBoundType { + INCLUSIVE("inclusive"), + EXCLUSIVE("exclusive"); + + private final String value; + + private QueryFromBoundType(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static QueryFromBoundType forValue(final String value) { + return Promoter.enumFromString(value, QueryFromBoundType.values()); + } + } + + /** * Converts a JSON String into a SyncListItem object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return SyncListItem object represented by the provided JSON */ - public static SyncListItem fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static SyncListItem fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, SyncListItem.class); @@ -105,14 +138,11 @@ public static SyncListItem fromJson( * Converts a JSON InputStream into a SyncListItem object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return SyncListItem object represented by the provided JSON */ - public static SyncListItem fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static SyncListItem fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, SyncListItem.class); @@ -123,87 +153,70 @@ public static SyncListItem fromJson( } } - private final Integer index; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String serviceSid; - private final String listSid; - private final URI url; - private final String revision; - private final Map data; - private final ZonedDateTime dateExpires; + @Getter + private final String createdBy; + @Getter + private final Object data; + @Getter private final ZonedDateTime dateCreated; + @Getter + private final ZonedDateTime dateExpires; + @Getter private final ZonedDateTime dateUpdated; - private final String createdBy; + @Getter + private final Integer index; + @Getter + private final String listSid; + @Getter + private final String revision; + @Getter + private final String serviceSid; + @Getter + private final URI url; @JsonCreator private SyncListItem( - @JsonProperty("index") final Integer index, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("service_sid") final String serviceSid, - @JsonProperty("list_sid") final String listSid, - @JsonProperty("url") final URI url, - @JsonProperty("revision") final String revision, - @JsonProperty("data") final Map data, - @JsonProperty("date_expires") final String dateExpires, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("created_by") final String createdBy + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("created_by") final String createdBy, + @JsonProperty("data") final Object data, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_expires") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateExpires, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("index") final Integer index, + @JsonProperty("list_sid") final String listSid, + @JsonProperty("revision") final String revision, + @JsonProperty("service_sid") final String serviceSid, + @JsonProperty("url") final URI url ) { - this.index = index; this.accountSid = accountSid; - this.serviceSid = serviceSid; + this.createdBy = createdBy; + this.data = data; + this.dateCreated = dateCreated; + this.dateExpires = dateExpires; + this.dateUpdated = dateUpdated; + this.index = index; this.listSid = listSid; - this.url = url; this.revision = revision; - this.data = data; - this.dateExpires = DateConverter.iso8601DateTimeFromString(dateExpires); - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); - this.createdBy = createdBy; - } - - public final Integer getIndex() { - return this.index; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getServiceSid() { - return this.serviceSid; - } - - public final String getListSid() { - return this.listSid; - } - - public final URI getUrl() { - return this.url; - } - - public final String getRevision() { - return this.revision; - } - - public final Map getData() { - return this.data; - } - - public final ZonedDateTime getDateExpires() { - return this.dateExpires; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final String getCreatedBy() { - return this.createdBy; + this.serviceSid = serviceSid; + this.url = url; } @Override @@ -217,76 +230,38 @@ public boolean equals(final Object o) { } SyncListItem other = (SyncListItem) o; - return ( - Objects.equals(index, other.index) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(serviceSid, other.serviceSid) && - Objects.equals(listSid, other.listSid) && - Objects.equals(url, other.url) && - Objects.equals(revision, other.revision) && - Objects.equals(data, other.data) && - Objects.equals(dateExpires, other.dateExpires) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(createdBy, other.createdBy) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(createdBy, other.createdBy) && + Objects.equals(data, other.data) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateExpires, other.dateExpires) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(index, other.index) && + Objects.equals(listSid, other.listSid) && + Objects.equals(revision, other.revision) && + Objects.equals(serviceSid, other.serviceSid) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - index, - accountSid, - serviceSid, - listSid, - url, - revision, - data, - dateExpires, - dateCreated, - dateUpdated, - createdBy + accountSid, + createdBy, + data, + dateCreated, + dateExpires, + dateUpdated, + index, + listSid, + revision, + serviceSid, + url ); } - public enum QueryResultOrder { - ASC("asc"), - DESC("desc"); - - private final String value; - - private QueryResultOrder(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static QueryResultOrder forValue(final String value) { - return Promoter.enumFromString(value, QueryResultOrder.values()); - } - } - public enum QueryFromBoundType { - INCLUSIVE("inclusive"), - EXCLUSIVE("exclusive"); - - private final String value; - - private QueryFromBoundType(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static QueryFromBoundType forValue(final String value) { - return Promoter.enumFromString(value, QueryFromBoundType.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/sync/v1/service/synclist/SyncListItemCreator.java b/src/main/java/com/twilio/rest/sync/v1/service/synclist/SyncListItemCreator.java index 4d8ac8f192..f64a4865fb 100644 --- a/src/main/java/com/twilio/rest/sync/v1/service/synclist/SyncListItemCreator.java +++ b/src/main/java/com/twilio/rest/sync/v1/service/synclist/SyncListItemCreator.java @@ -14,10 +14,11 @@ package com.twilio.rest.sync.v1.service.synclist; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; -import com.twilio.converter.Converter; -import com.twilio.converter.Converter; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,99 +30,100 @@ public class SyncListItemCreator extends Creator { - private String pathServiceSid; - private String pathListSid; + private String pathserviceSid; + private String pathlistSid; private Object data; private Integer ttl; private Integer itemTtl; private Integer collectionTtl; - public SyncListItemCreator( - final String pathServiceSid, - final String pathListSid, - final Object data - ) { - this.pathServiceSid = pathServiceSid; - this.pathListSid = pathListSid; + public SyncListItemCreator(final String pathserviceSid, final String pathlistSid, final Object data) { + this.pathserviceSid = pathserviceSid; + this.pathlistSid = pathlistSid; this.data = data; } + public SyncListItemCreator setData(final Object data) { this.data = data; return this; } + public SyncListItemCreator setTtl(final Integer ttl) { this.ttl = ttl; return this; } + public SyncListItemCreator setItemTtl(final Integer itemTtl) { this.itemTtl = itemTtl; return this; } + public SyncListItemCreator setCollectionTtl(final Integer collectionTtl) { this.collectionTtl = collectionTtl; return this; } + @Override public SyncListItem create(final TwilioRestClient client) { + String path = "/v1/Services/{ServiceSid}/Lists/{ListSid}/Items"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = path.replace("{" + "ListSid" + "}", this.pathListSid.toString()); - path = path.replace("{" + "Data" + "}", this.data.toString()); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "ListSid" + "}", this.pathlistSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.SYNC.toString(), - path + HttpMethod.POST, + Domains.SYNC.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "SyncListItem creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("SyncListItem creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return SyncListItem.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return SyncListItem.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (data != null) { - request.addPostParam("Data", Converter.objectToJson(data)); + Serializer.toString(request, "Data", data, ParameterType.URLENCODED); } + + if (ttl != null) { - request.addPostParam("Ttl", ttl.toString()); + Serializer.toString(request, "Ttl", ttl, ParameterType.URLENCODED); } + + if (itemTtl != null) { - request.addPostParam("ItemTtl", itemTtl.toString()); + Serializer.toString(request, "ItemTtl", itemTtl, ParameterType.URLENCODED); } + + if (collectionTtl != null) { - request.addPostParam("CollectionTtl", collectionTtl.toString()); + Serializer.toString(request, "CollectionTtl", collectionTtl, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/sync/v1/service/synclist/SyncListItemDeleter.java b/src/main/java/com/twilio/rest/sync/v1/service/synclist/SyncListItemDeleter.java index a31c49c060..9031fb76f6 100644 --- a/src/main/java/com/twilio/rest/sync/v1/service/synclist/SyncListItemDeleter.java +++ b/src/main/java/com/twilio/rest/sync/v1/service/synclist/SyncListItemDeleter.java @@ -15,7 +15,8 @@ package com.twilio.rest.sync.v1.service.synclist; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,61 +28,52 @@ public class SyncListItemDeleter extends Deleter { - private String pathServiceSid; - private String pathListSid; - private Integer pathIndex; + private String pathserviceSid; + private String pathlistSid; + private Integer pathindex; private String ifMatch; - public SyncListItemDeleter( - final String pathServiceSid, - final String pathListSid, - final Integer pathIndex - ) { - this.pathServiceSid = pathServiceSid; - this.pathListSid = pathListSid; - this.pathIndex = pathIndex; + public SyncListItemDeleter(final String pathserviceSid, final String pathlistSid, final Integer pathindex) { + this.pathserviceSid = pathserviceSid; + this.pathlistSid = pathlistSid; + this.pathindex = pathindex; } + public SyncListItemDeleter setIfMatch(final String ifMatch) { this.ifMatch = ifMatch; return this; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/v1/Services/{ServiceSid}/Lists/{ListSid}/Items/{Index}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = path.replace("{" + "ListSid" + "}", this.pathListSid.toString()); - path = path.replace("{" + "Index" + "}", this.pathIndex.toString()); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "ListSid" + "}", this.pathlistSid.toString()); + path = path.replace("{" + "Index" + "}", this.pathindex.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.SYNC.toString(), - path + HttpMethod.DELETE, + Domains.SYNC.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addHeaderParams(request); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "SyncListItem delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("SyncListItem delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -89,8 +81,10 @@ public boolean delete(final TwilioRestClient client) { } private void addHeaderParams(final Request request) { + if (ifMatch != null) { - request.addHeaderParam("If-Match", ifMatch); + Serializer.toString(request, "If-Match", ifMatch, ParameterType.HEADER); } + } } diff --git a/src/main/java/com/twilio/rest/sync/v1/service/synclist/SyncListItemFetcher.java b/src/main/java/com/twilio/rest/sync/v1/service/synclist/SyncListItemFetcher.java index 6e5467f15e..08c383d791 100644 --- a/src/main/java/com/twilio/rest/sync/v1/service/synclist/SyncListItemFetcher.java +++ b/src/main/java/com/twilio/rest/sync/v1/service/synclist/SyncListItemFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.sync.v1.service.synclist; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,61 +26,47 @@ public class SyncListItemFetcher extends Fetcher { - private String pathServiceSid; - private String pathListSid; - private Integer pathIndex; + private String pathserviceSid; + private String pathlistSid; + private Integer pathindex; - public SyncListItemFetcher( - final String pathServiceSid, - final String pathListSid, - final Integer pathIndex - ) { - this.pathServiceSid = pathServiceSid; - this.pathListSid = pathListSid; - this.pathIndex = pathIndex; + public SyncListItemFetcher(final String pathserviceSid, final String pathlistSid, final Integer pathindex) { + this.pathserviceSid = pathserviceSid; + this.pathlistSid = pathlistSid; + this.pathindex = pathindex; } + @Override public SyncListItem fetch(final TwilioRestClient client) { + String path = "/v1/Services/{ServiceSid}/Lists/{ListSid}/Items/{Index}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = path.replace("{" + "ListSid" + "}", this.pathListSid.toString()); - path = path.replace("{" + "Index" + "}", this.pathIndex.toString()); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "ListSid" + "}", this.pathlistSid.toString()); + path = path.replace("{" + "Index" + "}", this.pathindex.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.SYNC.toString(), - path + HttpMethod.GET, + Domains.SYNC.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "SyncListItem fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("SyncListItem fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return SyncListItem.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return SyncListItem.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/sync/v1/service/synclist/SyncListItemReader.java b/src/main/java/com/twilio/rest/sync/v1/service/synclist/SyncListItemReader.java index 61e72ea52f..b186badfeb 100644 --- a/src/main/java/com/twilio/rest/sync/v1/service/synclist/SyncListItemReader.java +++ b/src/main/java/com/twilio/rest/sync/v1/service/synclist/SyncListItemReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,152 +30,127 @@ public class SyncListItemReader extends Reader { - private String pathServiceSid; - private String pathListSid; + private String pathserviceSid; + private String pathlistSid; private SyncListItem.QueryResultOrder order; private String from; private SyncListItem.QueryFromBoundType bounds; private Long pageSize; - public SyncListItemReader( - final String pathServiceSid, - final String pathListSid - ) { - this.pathServiceSid = pathServiceSid; - this.pathListSid = pathListSid; + public SyncListItemReader(final String pathserviceSid, final String pathlistSid) { + this.pathserviceSid = pathserviceSid; + this.pathlistSid = pathlistSid; } - public SyncListItemReader setOrder( - final SyncListItem.QueryResultOrder order - ) { + + public SyncListItemReader setOrder(final SyncListItem.QueryResultOrder order) { this.order = order; return this; } + public SyncListItemReader setFrom(final String from) { this.from = from; return this; } - public SyncListItemReader setBounds( - final SyncListItem.QueryFromBoundType bounds - ) { + + public SyncListItemReader setBounds(final SyncListItem.QueryFromBoundType bounds) { this.bounds = bounds; return this; } + public SyncListItemReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/Services/{ServiceSid}/Lists/{ListSid}/Items"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = path.replace("{" + "ListSid" + "}", this.pathListSid.toString()); + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "ListSid" + "}", this.pathlistSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.SYNC.toString(), - path + HttpMethod.GET, + Domains.SYNC.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "SyncListItem read failed: Unable to connect to server" - ); + throw new ApiConnectionException("SyncListItem read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "items", - response.getContent(), - SyncListItem.class, - client.getObjectMapper() - ); + "items", + response.getContent(), + SyncListItem.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.SYNC.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.SYNC.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (order != null) { - request.addQueryParam("Order", order.toString()); + Serializer.toString(request, "Order", order, ParameterType.QUERY); } + + if (from != null) { - request.addQueryParam("From", from); + Serializer.toString(request, "From", from, ParameterType.QUERY); } + + if (bounds != null) { - request.addQueryParam("Bounds", bounds.toString()); + Serializer.toString(request, "Bounds", bounds, ParameterType.QUERY); } + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/sync/v1/service/synclist/SyncListItemUpdater.java b/src/main/java/com/twilio/rest/sync/v1/service/synclist/SyncListItemUpdater.java index 24dde562ca..bdd86dc67c 100644 --- a/src/main/java/com/twilio/rest/sync/v1/service/synclist/SyncListItemUpdater.java +++ b/src/main/java/com/twilio/rest/sync/v1/service/synclist/SyncListItemUpdater.java @@ -16,7 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; -import com.twilio.converter.Converter; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,114 +28,118 @@ import com.twilio.rest.Domains; public class SyncListItemUpdater extends Updater { - - private String pathServiceSid; - private String pathListSid; - private Integer pathIndex; + private String pathserviceSid; + private String pathlistSid; + private Integer pathindex; private String ifMatch; private Object data; private Integer ttl; private Integer itemTtl; private Integer collectionTtl; - public SyncListItemUpdater( - final String pathServiceSid, - final String pathListSid, - final Integer pathIndex - ) { - this.pathServiceSid = pathServiceSid; - this.pathListSid = pathListSid; - this.pathIndex = pathIndex; + public SyncListItemUpdater(final String pathserviceSid, final String pathlistSid, final Integer pathindex) { + this.pathserviceSid = pathserviceSid; + this.pathlistSid = pathlistSid; + this.pathindex = pathindex; } - public SyncListItemUpdater setIfMatch(final String ifMatch) { - this.ifMatch = ifMatch; - return this; - } public SyncListItemUpdater setData(final Object data) { this.data = data; return this; } + public SyncListItemUpdater setTtl(final Integer ttl) { this.ttl = ttl; return this; } + public SyncListItemUpdater setItemTtl(final Integer itemTtl) { this.itemTtl = itemTtl; return this; } + public SyncListItemUpdater setCollectionTtl(final Integer collectionTtl) { this.collectionTtl = collectionTtl; return this; } + + public SyncListItemUpdater setIfMatch(final String ifMatch) { + this.ifMatch = ifMatch; + return this; + } + + @Override public SyncListItem update(final TwilioRestClient client) { + String path = "/v1/Services/{ServiceSid}/Lists/{ListSid}/Items/{Index}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = path.replace("{" + "ListSid" + "}", this.pathListSid.toString()); - path = path.replace("{" + "Index" + "}", this.pathIndex.toString()); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "ListSid" + "}", this.pathlistSid.toString()); + path = path.replace("{" + "Index" + "}", this.pathindex.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.SYNC.toString(), - path + HttpMethod.POST, + Domains.SYNC.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); - addPostParams(request); addHeaderParams(request); + addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "SyncListItem update failed: Unable to connect to server" - ); + throw new ApiConnectionException("SyncListItem update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return SyncListItem.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return SyncListItem.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (data != null) { - request.addPostParam("Data", Converter.objectToJson(data)); + Serializer.toString(request, "Data", data, ParameterType.URLENCODED); } + + if (ttl != null) { - request.addPostParam("Ttl", ttl.toString()); + Serializer.toString(request, "Ttl", ttl, ParameterType.URLENCODED); } + + if (itemTtl != null) { - request.addPostParam("ItemTtl", itemTtl.toString()); + Serializer.toString(request, "ItemTtl", itemTtl, ParameterType.URLENCODED); } + + if (collectionTtl != null) { - request.addPostParam("CollectionTtl", collectionTtl.toString()); + Serializer.toString(request, "CollectionTtl", collectionTtl, ParameterType.URLENCODED); } + + } private void addHeaderParams(final Request request) { + if (ifMatch != null) { - request.addHeaderParam("If-Match", ifMatch); + Serializer.toString(request, "If-Match", ifMatch, ParameterType.HEADER); } + } } diff --git a/src/main/java/com/twilio/rest/sync/v1/service/synclist/SyncListPermission.java b/src/main/java/com/twilio/rest/sync/v1/service/synclist/SyncListPermission.java index fb68a96e40..eba0b912a3 100644 --- a/src/main/java/com/twilio/rest/sync/v1/service/synclist/SyncListPermission.java +++ b/src/main/java/com/twilio/rest/sync/v1/service/synclist/SyncListPermission.java @@ -18,84 +18,61 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class SyncListPermission extends Resource { - private static final long serialVersionUID = 225550881347017L; - public static SyncListPermissionDeleter deleter( - final String pathServiceSid, - final String pathListSid, - final String pathIdentity - ) { + public static SyncListPermissionDeleter deleter(final String pathserviceSid, final String pathlistSid, final String pathidentity) { return new SyncListPermissionDeleter( - pathServiceSid, - pathListSid, - pathIdentity + pathserviceSid, pathlistSid, pathidentity ); } - public static SyncListPermissionFetcher fetcher( - final String pathServiceSid, - final String pathListSid, - final String pathIdentity - ) { + + public static SyncListPermissionFetcher fetcher(final String pathserviceSid, final String pathlistSid, final String pathidentity) { return new SyncListPermissionFetcher( - pathServiceSid, - pathListSid, - pathIdentity + pathserviceSid, pathlistSid, pathidentity ); } - public static SyncListPermissionReader reader( - final String pathServiceSid, - final String pathListSid - ) { - return new SyncListPermissionReader(pathServiceSid, pathListSid); + + public static SyncListPermissionReader reader(final String pathserviceSid, final String pathlistSid) { + return new SyncListPermissionReader( + pathserviceSid, pathlistSid + ); } - public static SyncListPermissionUpdater updater( - final String pathServiceSid, - final String pathListSid, - final String pathIdentity, - final Boolean read, - final Boolean write, - final Boolean manage - ) { + + public static SyncListPermissionUpdater updater(final String pathserviceSid, final String pathlistSid, final String pathidentity, final Boolean read, final Boolean write, final Boolean manage) { return new SyncListPermissionUpdater( - pathServiceSid, - pathListSid, - pathIdentity, - read, - write, - manage + pathserviceSid, pathlistSid, pathidentity, read, write, manage ); } + /** * Converts a JSON String into a SyncListPermission object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return SyncListPermission object represented by the provided JSON */ - public static SyncListPermission fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static SyncListPermission fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, SyncListPermission.class); @@ -110,14 +87,11 @@ public static SyncListPermission fromJson( * Converts a JSON InputStream into a SyncListPermission object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return SyncListPermission object represented by the provided JSON */ - public static SyncListPermission fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static SyncListPermission fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, SyncListPermission.class); @@ -128,66 +102,55 @@ public static SyncListPermission fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String serviceSid; - private final String listSid; + @Getter private final String identity; - private final Boolean read; - private final Boolean write; + @Getter + private final String listSid; + @Getter private final Boolean manage; + @Getter + private final Boolean read; + @Getter + private final String serviceSid; + @Getter private final URI url; + @Getter + private final Boolean write; @JsonCreator private SyncListPermission( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("service_sid") final String serviceSid, - @JsonProperty("list_sid") final String listSid, - @JsonProperty("identity") final String identity, - @JsonProperty("read") final Boolean read, - @JsonProperty("write") final Boolean write, - @JsonProperty("manage") final Boolean manage, - @JsonProperty("url") final URI url + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("identity") final String identity, + @JsonProperty("list_sid") final String listSid, + @JsonProperty("manage") final Boolean manage, + @JsonProperty("read") final Boolean read, + @JsonProperty("service_sid") final String serviceSid, + @JsonProperty("url") final URI url, + @JsonProperty("write") final Boolean write ) { this.accountSid = accountSid; - this.serviceSid = serviceSid; - this.listSid = listSid; this.identity = identity; - this.read = read; - this.write = write; + this.listSid = listSid; this.manage = manage; + this.read = read; + this.serviceSid = serviceSid; this.url = url; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getServiceSid() { - return this.serviceSid; - } - - public final String getListSid() { - return this.listSid; - } - - public final String getIdentity() { - return this.identity; - } - - public final Boolean getRead() { - return this.read; - } - - public final Boolean getWrite() { - return this.write; - } - - public final Boolean getManage() { - return this.manage; - } - - public final URI getUrl() { - return this.url; + this.write = write; } @Override @@ -201,30 +164,32 @@ public boolean equals(final Object o) { } SyncListPermission other = (SyncListPermission) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(serviceSid, other.serviceSid) && - Objects.equals(listSid, other.listSid) && - Objects.equals(identity, other.identity) && - Objects.equals(read, other.read) && - Objects.equals(write, other.write) && - Objects.equals(manage, other.manage) && - Objects.equals(url, other.url) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(identity, other.identity) && + Objects.equals(listSid, other.listSid) && + Objects.equals(manage, other.manage) && + Objects.equals(read, other.read) && + Objects.equals(serviceSid, other.serviceSid) && + Objects.equals(url, other.url) && + Objects.equals(write, other.write) ); } @Override public int hashCode() { return Objects.hash( - accountSid, - serviceSid, - listSid, - identity, - read, - write, - manage, - url + accountSid, + identity, + listSid, + manage, + read, + serviceSid, + url, + write ); } + + } + diff --git a/src/main/java/com/twilio/rest/sync/v1/service/synclist/SyncListPermissionDeleter.java b/src/main/java/com/twilio/rest/sync/v1/service/synclist/SyncListPermissionDeleter.java index 59abd3b580..6626eb8cba 100644 --- a/src/main/java/com/twilio/rest/sync/v1/service/synclist/SyncListPermissionDeleter.java +++ b/src/main/java/com/twilio/rest/sync/v1/service/synclist/SyncListPermissionDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.sync.v1.service.synclist; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,56 +26,44 @@ public class SyncListPermissionDeleter extends Deleter { - private String pathServiceSid; - private String pathListSid; - private String pathIdentity; + private String pathserviceSid; + private String pathlistSid; + private String pathidentity; - public SyncListPermissionDeleter( - final String pathServiceSid, - final String pathListSid, - final String pathIdentity - ) { - this.pathServiceSid = pathServiceSid; - this.pathListSid = pathListSid; - this.pathIdentity = pathIdentity; + public SyncListPermissionDeleter(final String pathserviceSid, final String pathlistSid, final String pathidentity) { + this.pathserviceSid = pathserviceSid; + this.pathlistSid = pathlistSid; + this.pathidentity = pathidentity; } + @Override public boolean delete(final TwilioRestClient client) { - String path = - "/v1/Services/{ServiceSid}/Lists/{ListSid}/Permissions/{Identity}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = path.replace("{" + "ListSid" + "}", this.pathListSid.toString()); - path = - path.replace("{" + "Identity" + "}", this.pathIdentity.toString()); + String path = "/v1/Services/{ServiceSid}/Lists/{ListSid}/Permissions/{Identity}"; + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "ListSid" + "}", this.pathlistSid.toString()); + path = path.replace("{" + "Identity" + "}", this.pathidentity.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.SYNC.toString(), - path + HttpMethod.DELETE, + Domains.SYNC.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "SyncListPermission delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("SyncListPermission delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/sync/v1/service/synclist/SyncListPermissionFetcher.java b/src/main/java/com/twilio/rest/sync/v1/service/synclist/SyncListPermissionFetcher.java index 37439d737b..8ba39ddd72 100644 --- a/src/main/java/com/twilio/rest/sync/v1/service/synclist/SyncListPermissionFetcher.java +++ b/src/main/java/com/twilio/rest/sync/v1/service/synclist/SyncListPermissionFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.sync.v1.service.synclist; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,63 +26,47 @@ public class SyncListPermissionFetcher extends Fetcher { - private String pathServiceSid; - private String pathListSid; - private String pathIdentity; + private String pathserviceSid; + private String pathlistSid; + private String pathidentity; - public SyncListPermissionFetcher( - final String pathServiceSid, - final String pathListSid, - final String pathIdentity - ) { - this.pathServiceSid = pathServiceSid; - this.pathListSid = pathListSid; - this.pathIdentity = pathIdentity; + public SyncListPermissionFetcher(final String pathserviceSid, final String pathlistSid, final String pathidentity) { + this.pathserviceSid = pathserviceSid; + this.pathlistSid = pathlistSid; + this.pathidentity = pathidentity; } + @Override public SyncListPermission fetch(final TwilioRestClient client) { - String path = - "/v1/Services/{ServiceSid}/Lists/{ListSid}/Permissions/{Identity}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = path.replace("{" + "ListSid" + "}", this.pathListSid.toString()); - path = - path.replace("{" + "Identity" + "}", this.pathIdentity.toString()); + String path = "/v1/Services/{ServiceSid}/Lists/{ListSid}/Permissions/{Identity}"; + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "ListSid" + "}", this.pathlistSid.toString()); + path = path.replace("{" + "Identity" + "}", this.pathidentity.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.SYNC.toString(), - path + HttpMethod.GET, + Domains.SYNC.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "SyncListPermission fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("SyncListPermission fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return SyncListPermission.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return SyncListPermission.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/sync/v1/service/synclist/SyncListPermissionReader.java b/src/main/java/com/twilio/rest/sync/v1/service/synclist/SyncListPermissionReader.java index 7563b8e9d5..bc14d20b95 100644 --- a/src/main/java/com/twilio/rest/sync/v1/service/synclist/SyncListPermissionReader.java +++ b/src/main/java/com/twilio/rest/sync/v1/service/synclist/SyncListPermissionReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,121 +30,91 @@ public class SyncListPermissionReader extends Reader { - private String pathServiceSid; - private String pathListSid; + private String pathserviceSid; + private String pathlistSid; private Long pageSize; - public SyncListPermissionReader( - final String pathServiceSid, - final String pathListSid - ) { - this.pathServiceSid = pathServiceSid; - this.pathListSid = pathListSid; + public SyncListPermissionReader(final String pathserviceSid, final String pathlistSid) { + this.pathserviceSid = pathserviceSid; + this.pathlistSid = pathlistSid; } + public SyncListPermissionReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/Services/{ServiceSid}/Lists/{ListSid}/Permissions"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = path.replace("{" + "ListSid" + "}", this.pathListSid.toString()); + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "ListSid" + "}", this.pathlistSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.SYNC.toString(), - path + HttpMethod.GET, + Domains.SYNC.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "SyncListPermission read failed: Unable to connect to server" - ); + throw new ApiConnectionException("SyncListPermission read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "permissions", - response.getContent(), - SyncListPermission.class, - client.getObjectMapper() - ); + "permissions", + response.getContent(), + SyncListPermission.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.SYNC.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.SYNC.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/sync/v1/service/synclist/SyncListPermissionUpdater.java b/src/main/java/com/twilio/rest/sync/v1/service/synclist/SyncListPermissionUpdater.java index 16ddbe178e..de7bb9be2a 100644 --- a/src/main/java/com/twilio/rest/sync/v1/service/synclist/SyncListPermissionUpdater.java +++ b/src/main/java/com/twilio/rest/sync/v1/service/synclist/SyncListPermissionUpdater.java @@ -16,6 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -26,103 +28,93 @@ import com.twilio.rest.Domains; public class SyncListPermissionUpdater extends Updater { - - private String pathServiceSid; - private String pathListSid; - private String pathIdentity; + private String pathserviceSid; + private String pathlistSid; + private String pathidentity; private Boolean read; private Boolean write; private Boolean manage; - public SyncListPermissionUpdater( - final String pathServiceSid, - final String pathListSid, - final String pathIdentity, - final Boolean read, - final Boolean write, - final Boolean manage - ) { - this.pathServiceSid = pathServiceSid; - this.pathListSid = pathListSid; - this.pathIdentity = pathIdentity; + public SyncListPermissionUpdater(final String pathserviceSid, final String pathlistSid, final String pathidentity, final Boolean read, final Boolean write, final Boolean manage) { + this.pathserviceSid = pathserviceSid; + this.pathlistSid = pathlistSid; + this.pathidentity = pathidentity; this.read = read; this.write = write; this.manage = manage; } + public SyncListPermissionUpdater setRead(final Boolean read) { this.read = read; return this; } + public SyncListPermissionUpdater setWrite(final Boolean write) { this.write = write; return this; } + public SyncListPermissionUpdater setManage(final Boolean manage) { this.manage = manage; return this; } + @Override public SyncListPermission update(final TwilioRestClient client) { - String path = - "/v1/Services/{ServiceSid}/Lists/{ListSid}/Permissions/{Identity}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = path.replace("{" + "ListSid" + "}", this.pathListSid.toString()); - path = - path.replace("{" + "Identity" + "}", this.pathIdentity.toString()); - path = path.replace("{" + "Read" + "}", this.read.toString()); - path = path.replace("{" + "Write" + "}", this.write.toString()); - path = path.replace("{" + "Manage" + "}", this.manage.toString()); + String path = "/v1/Services/{ServiceSid}/Lists/{ListSid}/Permissions/{Identity}"; + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "ListSid" + "}", this.pathlistSid.toString()); + path = path.replace("{" + "Identity" + "}", this.pathidentity.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.SYNC.toString(), - path + HttpMethod.POST, + Domains.SYNC.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "SyncListPermission update failed: Unable to connect to server" - ); + throw new ApiConnectionException("SyncListPermission update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return SyncListPermission.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return SyncListPermission.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (read != null) { - request.addPostParam("Read", read.toString()); + Serializer.toString(request, "Read", read, ParameterType.URLENCODED); } + + if (write != null) { - request.addPostParam("Write", write.toString()); + Serializer.toString(request, "Write", write, ParameterType.URLENCODED); } + + if (manage != null) { - request.addPostParam("Manage", manage.toString()); + Serializer.toString(request, "Manage", manage, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/sync/v1/service/syncmap/SyncMapItem.java b/src/main/java/com/twilio/rest/sync/v1/service/syncmap/SyncMapItem.java index f134d6fb0c..5d0800dee4 100644 --- a/src/main/java/com/twilio/rest/sync/v1/service/syncmap/SyncMapItem.java +++ b/src/main/java/com/twilio/rest/sync/v1/service/syncmap/SyncMapItem.java @@ -18,80 +18,112 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; -import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class SyncMapItem extends Resource { - private static final long serialVersionUID = 156890229646336L; - public static SyncMapItemCreator creator( - final String pathServiceSid, - final String pathMapSid, - final String key, - final Object data - ) { - return new SyncMapItemCreator(pathServiceSid, pathMapSid, key, data); + public static SyncMapItemCreator creator(final String pathserviceSid, final String pathmapSid, final String key, final Object data) { + return new SyncMapItemCreator( + pathserviceSid, pathmapSid, key, data + ); } - public static SyncMapItemDeleter deleter( - final String pathServiceSid, - final String pathMapSid, - final String pathKey - ) { - return new SyncMapItemDeleter(pathServiceSid, pathMapSid, pathKey); + + public static SyncMapItemDeleter deleter(final String pathserviceSid, final String pathmapSid, final String pathkey) { + return new SyncMapItemDeleter( + pathserviceSid, pathmapSid, pathkey + ); } - public static SyncMapItemFetcher fetcher( - final String pathServiceSid, - final String pathMapSid, - final String pathKey - ) { - return new SyncMapItemFetcher(pathServiceSid, pathMapSid, pathKey); + + public static SyncMapItemFetcher fetcher(final String pathserviceSid, final String pathmapSid, final String pathkey) { + return new SyncMapItemFetcher( + pathserviceSid, pathmapSid, pathkey + ); } - public static SyncMapItemReader reader( - final String pathServiceSid, - final String pathMapSid - ) { - return new SyncMapItemReader(pathServiceSid, pathMapSid); + + public static SyncMapItemReader reader(final String pathserviceSid, final String pathmapSid) { + return new SyncMapItemReader( + pathserviceSid, pathmapSid + ); } - public static SyncMapItemUpdater updater( - final String pathServiceSid, - final String pathMapSid, - final String pathKey - ) { - return new SyncMapItemUpdater(pathServiceSid, pathMapSid, pathKey); + + public static SyncMapItemUpdater updater(final String pathserviceSid, final String pathmapSid, final String pathkey) { + return new SyncMapItemUpdater( + pathserviceSid, pathmapSid, pathkey + ); + } + + + public enum QueryResultOrder { + ASC("asc"), + DESC("desc"); + + private final String value; + + private QueryResultOrder(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static QueryResultOrder forValue(final String value) { + return Promoter.enumFromString(value, QueryResultOrder.values()); + } } + public enum QueryFromBoundType { + INCLUSIVE("inclusive"), + EXCLUSIVE("exclusive"); + + private final String value; + + private QueryFromBoundType(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static QueryFromBoundType forValue(final String value) { + return Promoter.enumFromString(value, QueryFromBoundType.values()); + } + } + + /** * Converts a JSON String into a SyncMapItem object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return SyncMapItem object represented by the provided JSON */ - public static SyncMapItem fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static SyncMapItem fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, SyncMapItem.class); @@ -106,14 +138,11 @@ public static SyncMapItem fromJson( * Converts a JSON InputStream into a SyncMapItem object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return SyncMapItem object represented by the provided JSON */ - public static SyncMapItem fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static SyncMapItem fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, SyncMapItem.class); @@ -124,87 +153,70 @@ public static SyncMapItem fromJson( } } - private final String key; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String serviceSid; - private final String mapSid; - private final URI url; - private final String revision; - private final Map data; - private final ZonedDateTime dateExpires; + @Getter + private final String createdBy; + @Getter + private final Object data; + @Getter private final ZonedDateTime dateCreated; + @Getter + private final ZonedDateTime dateExpires; + @Getter private final ZonedDateTime dateUpdated; - private final String createdBy; + @Getter + private final String key; + @Getter + private final String mapSid; + @Getter + private final String revision; + @Getter + private final String serviceSid; + @Getter + private final URI url; @JsonCreator private SyncMapItem( - @JsonProperty("key") final String key, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("service_sid") final String serviceSid, - @JsonProperty("map_sid") final String mapSid, - @JsonProperty("url") final URI url, - @JsonProperty("revision") final String revision, - @JsonProperty("data") final Map data, - @JsonProperty("date_expires") final String dateExpires, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("created_by") final String createdBy + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("created_by") final String createdBy, + @JsonProperty("data") final Object data, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_expires") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateExpires, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("key") final String key, + @JsonProperty("map_sid") final String mapSid, + @JsonProperty("revision") final String revision, + @JsonProperty("service_sid") final String serviceSid, + @JsonProperty("url") final URI url ) { - this.key = key; this.accountSid = accountSid; - this.serviceSid = serviceSid; + this.createdBy = createdBy; + this.data = data; + this.dateCreated = dateCreated; + this.dateExpires = dateExpires; + this.dateUpdated = dateUpdated; + this.key = key; this.mapSid = mapSid; - this.url = url; this.revision = revision; - this.data = data; - this.dateExpires = DateConverter.iso8601DateTimeFromString(dateExpires); - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); - this.createdBy = createdBy; - } - - public final String getKey() { - return this.key; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getServiceSid() { - return this.serviceSid; - } - - public final String getMapSid() { - return this.mapSid; - } - - public final URI getUrl() { - return this.url; - } - - public final String getRevision() { - return this.revision; - } - - public final Map getData() { - return this.data; - } - - public final ZonedDateTime getDateExpires() { - return this.dateExpires; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final String getCreatedBy() { - return this.createdBy; + this.serviceSid = serviceSid; + this.url = url; } @Override @@ -218,76 +230,38 @@ public boolean equals(final Object o) { } SyncMapItem other = (SyncMapItem) o; - return ( - Objects.equals(key, other.key) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(serviceSid, other.serviceSid) && - Objects.equals(mapSid, other.mapSid) && - Objects.equals(url, other.url) && - Objects.equals(revision, other.revision) && - Objects.equals(data, other.data) && - Objects.equals(dateExpires, other.dateExpires) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(createdBy, other.createdBy) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(createdBy, other.createdBy) && + Objects.equals(data, other.data) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateExpires, other.dateExpires) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(key, other.key) && + Objects.equals(mapSid, other.mapSid) && + Objects.equals(revision, other.revision) && + Objects.equals(serviceSid, other.serviceSid) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - key, - accountSid, - serviceSid, - mapSid, - url, - revision, - data, - dateExpires, - dateCreated, - dateUpdated, - createdBy + accountSid, + createdBy, + data, + dateCreated, + dateExpires, + dateUpdated, + key, + mapSid, + revision, + serviceSid, + url ); } - public enum QueryFromBoundType { - INCLUSIVE("inclusive"), - EXCLUSIVE("exclusive"); - - private final String value; - - private QueryFromBoundType(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static QueryFromBoundType forValue(final String value) { - return Promoter.enumFromString(value, QueryFromBoundType.values()); - } - } - public enum QueryResultOrder { - ASC("asc"), - DESC("desc"); - - private final String value; - - private QueryResultOrder(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static QueryResultOrder forValue(final String value) { - return Promoter.enumFromString(value, QueryResultOrder.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/sync/v1/service/syncmap/SyncMapItemCreator.java b/src/main/java/com/twilio/rest/sync/v1/service/syncmap/SyncMapItemCreator.java index c85bdbfeb9..01a1937eef 100644 --- a/src/main/java/com/twilio/rest/sync/v1/service/syncmap/SyncMapItemCreator.java +++ b/src/main/java/com/twilio/rest/sync/v1/service/syncmap/SyncMapItemCreator.java @@ -14,10 +14,11 @@ package com.twilio.rest.sync.v1.service.syncmap; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; -import com.twilio.converter.Converter; -import com.twilio.converter.Converter; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,111 +30,113 @@ public class SyncMapItemCreator extends Creator { - private String pathServiceSid; - private String pathMapSid; + private String pathserviceSid; + private String pathmapSid; private String key; private Object data; private Integer ttl; private Integer itemTtl; private Integer collectionTtl; - public SyncMapItemCreator( - final String pathServiceSid, - final String pathMapSid, - final String key, - final Object data - ) { - this.pathServiceSid = pathServiceSid; - this.pathMapSid = pathMapSid; + public SyncMapItemCreator(final String pathserviceSid, final String pathmapSid, final String key, final Object data) { + this.pathserviceSid = pathserviceSid; + this.pathmapSid = pathmapSid; this.key = key; this.data = data; } + public SyncMapItemCreator setKey(final String key) { this.key = key; return this; } + public SyncMapItemCreator setData(final Object data) { this.data = data; return this; } + public SyncMapItemCreator setTtl(final Integer ttl) { this.ttl = ttl; return this; } + public SyncMapItemCreator setItemTtl(final Integer itemTtl) { this.itemTtl = itemTtl; return this; } + public SyncMapItemCreator setCollectionTtl(final Integer collectionTtl) { this.collectionTtl = collectionTtl; return this; } + @Override public SyncMapItem create(final TwilioRestClient client) { + String path = "/v1/Services/{ServiceSid}/Maps/{MapSid}/Items"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = path.replace("{" + "MapSid" + "}", this.pathMapSid.toString()); - path = path.replace("{" + "Key" + "}", this.key.toString()); - path = path.replace("{" + "Data" + "}", this.data.toString()); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "MapSid" + "}", this.pathmapSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.SYNC.toString(), - path + HttpMethod.POST, + Domains.SYNC.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "SyncMapItem creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("SyncMapItem creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return SyncMapItem.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return SyncMapItem.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (key != null) { - request.addPostParam("Key", key); + Serializer.toString(request, "Key", key, ParameterType.URLENCODED); } + + if (data != null) { - request.addPostParam("Data", Converter.objectToJson(data)); + Serializer.toString(request, "Data", data, ParameterType.URLENCODED); } + + if (ttl != null) { - request.addPostParam("Ttl", ttl.toString()); + Serializer.toString(request, "Ttl", ttl, ParameterType.URLENCODED); } + + if (itemTtl != null) { - request.addPostParam("ItemTtl", itemTtl.toString()); + Serializer.toString(request, "ItemTtl", itemTtl, ParameterType.URLENCODED); } + + if (collectionTtl != null) { - request.addPostParam("CollectionTtl", collectionTtl.toString()); + Serializer.toString(request, "CollectionTtl", collectionTtl, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/sync/v1/service/syncmap/SyncMapItemDeleter.java b/src/main/java/com/twilio/rest/sync/v1/service/syncmap/SyncMapItemDeleter.java index 785fa38406..9da84511ac 100644 --- a/src/main/java/com/twilio/rest/sync/v1/service/syncmap/SyncMapItemDeleter.java +++ b/src/main/java/com/twilio/rest/sync/v1/service/syncmap/SyncMapItemDeleter.java @@ -15,7 +15,8 @@ package com.twilio.rest.sync.v1.service.syncmap; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,61 +28,52 @@ public class SyncMapItemDeleter extends Deleter { - private String pathServiceSid; - private String pathMapSid; - private String pathKey; + private String pathserviceSid; + private String pathmapSid; + private String pathkey; private String ifMatch; - public SyncMapItemDeleter( - final String pathServiceSid, - final String pathMapSid, - final String pathKey - ) { - this.pathServiceSid = pathServiceSid; - this.pathMapSid = pathMapSid; - this.pathKey = pathKey; + public SyncMapItemDeleter(final String pathserviceSid, final String pathmapSid, final String pathkey) { + this.pathserviceSid = pathserviceSid; + this.pathmapSid = pathmapSid; + this.pathkey = pathkey; } + public SyncMapItemDeleter setIfMatch(final String ifMatch) { this.ifMatch = ifMatch; return this; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/v1/Services/{ServiceSid}/Maps/{MapSid}/Items/{Key}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = path.replace("{" + "MapSid" + "}", this.pathMapSid.toString()); - path = path.replace("{" + "Key" + "}", this.pathKey.toString()); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "MapSid" + "}", this.pathmapSid.toString()); + path = path.replace("{" + "Key" + "}", this.pathkey.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.SYNC.toString(), - path + HttpMethod.DELETE, + Domains.SYNC.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addHeaderParams(request); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "SyncMapItem delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("SyncMapItem delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -89,8 +81,10 @@ public boolean delete(final TwilioRestClient client) { } private void addHeaderParams(final Request request) { + if (ifMatch != null) { - request.addHeaderParam("If-Match", ifMatch); + Serializer.toString(request, "If-Match", ifMatch, ParameterType.HEADER); } + } } diff --git a/src/main/java/com/twilio/rest/sync/v1/service/syncmap/SyncMapItemFetcher.java b/src/main/java/com/twilio/rest/sync/v1/service/syncmap/SyncMapItemFetcher.java index 102f0276cc..f751f3f806 100644 --- a/src/main/java/com/twilio/rest/sync/v1/service/syncmap/SyncMapItemFetcher.java +++ b/src/main/java/com/twilio/rest/sync/v1/service/syncmap/SyncMapItemFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.sync.v1.service.syncmap; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,61 +26,47 @@ public class SyncMapItemFetcher extends Fetcher { - private String pathServiceSid; - private String pathMapSid; - private String pathKey; + private String pathserviceSid; + private String pathmapSid; + private String pathkey; - public SyncMapItemFetcher( - final String pathServiceSid, - final String pathMapSid, - final String pathKey - ) { - this.pathServiceSid = pathServiceSid; - this.pathMapSid = pathMapSid; - this.pathKey = pathKey; + public SyncMapItemFetcher(final String pathserviceSid, final String pathmapSid, final String pathkey) { + this.pathserviceSid = pathserviceSid; + this.pathmapSid = pathmapSid; + this.pathkey = pathkey; } + @Override public SyncMapItem fetch(final TwilioRestClient client) { + String path = "/v1/Services/{ServiceSid}/Maps/{MapSid}/Items/{Key}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = path.replace("{" + "MapSid" + "}", this.pathMapSid.toString()); - path = path.replace("{" + "Key" + "}", this.pathKey.toString()); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "MapSid" + "}", this.pathmapSid.toString()); + path = path.replace("{" + "Key" + "}", this.pathkey.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.SYNC.toString(), - path + HttpMethod.GET, + Domains.SYNC.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "SyncMapItem fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("SyncMapItem fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return SyncMapItem.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return SyncMapItem.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/sync/v1/service/syncmap/SyncMapItemReader.java b/src/main/java/com/twilio/rest/sync/v1/service/syncmap/SyncMapItemReader.java index 1c2f76275c..7bfcb39809 100644 --- a/src/main/java/com/twilio/rest/sync/v1/service/syncmap/SyncMapItemReader.java +++ b/src/main/java/com/twilio/rest/sync/v1/service/syncmap/SyncMapItemReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,152 +30,127 @@ public class SyncMapItemReader extends Reader { - private String pathServiceSid; - private String pathMapSid; + private String pathserviceSid; + private String pathmapSid; private SyncMapItem.QueryResultOrder order; private String from; private SyncMapItem.QueryFromBoundType bounds; private Long pageSize; - public SyncMapItemReader( - final String pathServiceSid, - final String pathMapSid - ) { - this.pathServiceSid = pathServiceSid; - this.pathMapSid = pathMapSid; + public SyncMapItemReader(final String pathserviceSid, final String pathmapSid) { + this.pathserviceSid = pathserviceSid; + this.pathmapSid = pathmapSid; } - public SyncMapItemReader setOrder( - final SyncMapItem.QueryResultOrder order - ) { + + public SyncMapItemReader setOrder(final SyncMapItem.QueryResultOrder order) { this.order = order; return this; } + public SyncMapItemReader setFrom(final String from) { this.from = from; return this; } - public SyncMapItemReader setBounds( - final SyncMapItem.QueryFromBoundType bounds - ) { + + public SyncMapItemReader setBounds(final SyncMapItem.QueryFromBoundType bounds) { this.bounds = bounds; return this; } + public SyncMapItemReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/Services/{ServiceSid}/Maps/{MapSid}/Items"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = path.replace("{" + "MapSid" + "}", this.pathMapSid.toString()); + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "MapSid" + "}", this.pathmapSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.SYNC.toString(), - path + HttpMethod.GET, + Domains.SYNC.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "SyncMapItem read failed: Unable to connect to server" - ); + throw new ApiConnectionException("SyncMapItem read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "items", - response.getContent(), - SyncMapItem.class, - client.getObjectMapper() - ); + "items", + response.getContent(), + SyncMapItem.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.SYNC.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.SYNC.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (order != null) { - request.addQueryParam("Order", order.toString()); + Serializer.toString(request, "Order", order, ParameterType.QUERY); } + + if (from != null) { - request.addQueryParam("From", from); + Serializer.toString(request, "From", from, ParameterType.QUERY); } + + if (bounds != null) { - request.addQueryParam("Bounds", bounds.toString()); + Serializer.toString(request, "Bounds", bounds, ParameterType.QUERY); } + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/sync/v1/service/syncmap/SyncMapItemUpdater.java b/src/main/java/com/twilio/rest/sync/v1/service/syncmap/SyncMapItemUpdater.java index b0b1a151c0..5d5651f31c 100644 --- a/src/main/java/com/twilio/rest/sync/v1/service/syncmap/SyncMapItemUpdater.java +++ b/src/main/java/com/twilio/rest/sync/v1/service/syncmap/SyncMapItemUpdater.java @@ -16,7 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; -import com.twilio.converter.Converter; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,114 +28,118 @@ import com.twilio.rest.Domains; public class SyncMapItemUpdater extends Updater { - - private String pathServiceSid; - private String pathMapSid; - private String pathKey; + private String pathserviceSid; + private String pathmapSid; + private String pathkey; private String ifMatch; private Object data; private Integer ttl; private Integer itemTtl; private Integer collectionTtl; - public SyncMapItemUpdater( - final String pathServiceSid, - final String pathMapSid, - final String pathKey - ) { - this.pathServiceSid = pathServiceSid; - this.pathMapSid = pathMapSid; - this.pathKey = pathKey; + public SyncMapItemUpdater(final String pathserviceSid, final String pathmapSid, final String pathkey) { + this.pathserviceSid = pathserviceSid; + this.pathmapSid = pathmapSid; + this.pathkey = pathkey; } - public SyncMapItemUpdater setIfMatch(final String ifMatch) { - this.ifMatch = ifMatch; - return this; - } public SyncMapItemUpdater setData(final Object data) { this.data = data; return this; } + public SyncMapItemUpdater setTtl(final Integer ttl) { this.ttl = ttl; return this; } + public SyncMapItemUpdater setItemTtl(final Integer itemTtl) { this.itemTtl = itemTtl; return this; } + public SyncMapItemUpdater setCollectionTtl(final Integer collectionTtl) { this.collectionTtl = collectionTtl; return this; } + + public SyncMapItemUpdater setIfMatch(final String ifMatch) { + this.ifMatch = ifMatch; + return this; + } + + @Override public SyncMapItem update(final TwilioRestClient client) { + String path = "/v1/Services/{ServiceSid}/Maps/{MapSid}/Items/{Key}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = path.replace("{" + "MapSid" + "}", this.pathMapSid.toString()); - path = path.replace("{" + "Key" + "}", this.pathKey.toString()); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "MapSid" + "}", this.pathmapSid.toString()); + path = path.replace("{" + "Key" + "}", this.pathkey.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.SYNC.toString(), - path + HttpMethod.POST, + Domains.SYNC.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); - addPostParams(request); addHeaderParams(request); + addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "SyncMapItem update failed: Unable to connect to server" - ); + throw new ApiConnectionException("SyncMapItem update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return SyncMapItem.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return SyncMapItem.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (data != null) { - request.addPostParam("Data", Converter.objectToJson(data)); + Serializer.toString(request, "Data", data, ParameterType.URLENCODED); } + + if (ttl != null) { - request.addPostParam("Ttl", ttl.toString()); + Serializer.toString(request, "Ttl", ttl, ParameterType.URLENCODED); } + + if (itemTtl != null) { - request.addPostParam("ItemTtl", itemTtl.toString()); + Serializer.toString(request, "ItemTtl", itemTtl, ParameterType.URLENCODED); } + + if (collectionTtl != null) { - request.addPostParam("CollectionTtl", collectionTtl.toString()); + Serializer.toString(request, "CollectionTtl", collectionTtl, ParameterType.URLENCODED); } + + } private void addHeaderParams(final Request request) { + if (ifMatch != null) { - request.addHeaderParam("If-Match", ifMatch); + Serializer.toString(request, "If-Match", ifMatch, ParameterType.HEADER); } + } } diff --git a/src/main/java/com/twilio/rest/sync/v1/service/syncmap/SyncMapPermission.java b/src/main/java/com/twilio/rest/sync/v1/service/syncmap/SyncMapPermission.java index 013b9d4b9e..1652b54a3f 100644 --- a/src/main/java/com/twilio/rest/sync/v1/service/syncmap/SyncMapPermission.java +++ b/src/main/java/com/twilio/rest/sync/v1/service/syncmap/SyncMapPermission.java @@ -18,84 +18,61 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class SyncMapPermission extends Resource { - private static final long serialVersionUID = 55149075645678L; - public static SyncMapPermissionDeleter deleter( - final String pathServiceSid, - final String pathMapSid, - final String pathIdentity - ) { + public static SyncMapPermissionDeleter deleter(final String pathserviceSid, final String pathmapSid, final String pathidentity) { return new SyncMapPermissionDeleter( - pathServiceSid, - pathMapSid, - pathIdentity + pathserviceSid, pathmapSid, pathidentity ); } - public static SyncMapPermissionFetcher fetcher( - final String pathServiceSid, - final String pathMapSid, - final String pathIdentity - ) { + + public static SyncMapPermissionFetcher fetcher(final String pathserviceSid, final String pathmapSid, final String pathidentity) { return new SyncMapPermissionFetcher( - pathServiceSid, - pathMapSid, - pathIdentity + pathserviceSid, pathmapSid, pathidentity ); } - public static SyncMapPermissionReader reader( - final String pathServiceSid, - final String pathMapSid - ) { - return new SyncMapPermissionReader(pathServiceSid, pathMapSid); + + public static SyncMapPermissionReader reader(final String pathserviceSid, final String pathmapSid) { + return new SyncMapPermissionReader( + pathserviceSid, pathmapSid + ); } - public static SyncMapPermissionUpdater updater( - final String pathServiceSid, - final String pathMapSid, - final String pathIdentity, - final Boolean read, - final Boolean write, - final Boolean manage - ) { + + public static SyncMapPermissionUpdater updater(final String pathserviceSid, final String pathmapSid, final String pathidentity, final Boolean read, final Boolean write, final Boolean manage) { return new SyncMapPermissionUpdater( - pathServiceSid, - pathMapSid, - pathIdentity, - read, - write, - manage + pathserviceSid, pathmapSid, pathidentity, read, write, manage ); } + /** * Converts a JSON String into a SyncMapPermission object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return SyncMapPermission object represented by the provided JSON */ - public static SyncMapPermission fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static SyncMapPermission fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, SyncMapPermission.class); @@ -110,14 +87,11 @@ public static SyncMapPermission fromJson( * Converts a JSON InputStream into a SyncMapPermission object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return SyncMapPermission object represented by the provided JSON */ - public static SyncMapPermission fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static SyncMapPermission fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, SyncMapPermission.class); @@ -128,66 +102,55 @@ public static SyncMapPermission fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String serviceSid; - private final String mapSid; + @Getter private final String identity; - private final Boolean read; - private final Boolean write; + @Getter private final Boolean manage; + @Getter + private final String mapSid; + @Getter + private final Boolean read; + @Getter + private final String serviceSid; + @Getter private final URI url; + @Getter + private final Boolean write; @JsonCreator private SyncMapPermission( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("service_sid") final String serviceSid, - @JsonProperty("map_sid") final String mapSid, - @JsonProperty("identity") final String identity, - @JsonProperty("read") final Boolean read, - @JsonProperty("write") final Boolean write, - @JsonProperty("manage") final Boolean manage, - @JsonProperty("url") final URI url + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("identity") final String identity, + @JsonProperty("manage") final Boolean manage, + @JsonProperty("map_sid") final String mapSid, + @JsonProperty("read") final Boolean read, + @JsonProperty("service_sid") final String serviceSid, + @JsonProperty("url") final URI url, + @JsonProperty("write") final Boolean write ) { this.accountSid = accountSid; - this.serviceSid = serviceSid; - this.mapSid = mapSid; this.identity = identity; - this.read = read; - this.write = write; this.manage = manage; + this.mapSid = mapSid; + this.read = read; + this.serviceSid = serviceSid; this.url = url; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getServiceSid() { - return this.serviceSid; - } - - public final String getMapSid() { - return this.mapSid; - } - - public final String getIdentity() { - return this.identity; - } - - public final Boolean getRead() { - return this.read; - } - - public final Boolean getWrite() { - return this.write; - } - - public final Boolean getManage() { - return this.manage; - } - - public final URI getUrl() { - return this.url; + this.write = write; } @Override @@ -201,30 +164,32 @@ public boolean equals(final Object o) { } SyncMapPermission other = (SyncMapPermission) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(serviceSid, other.serviceSid) && - Objects.equals(mapSid, other.mapSid) && - Objects.equals(identity, other.identity) && - Objects.equals(read, other.read) && - Objects.equals(write, other.write) && - Objects.equals(manage, other.manage) && - Objects.equals(url, other.url) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(identity, other.identity) && + Objects.equals(manage, other.manage) && + Objects.equals(mapSid, other.mapSid) && + Objects.equals(read, other.read) && + Objects.equals(serviceSid, other.serviceSid) && + Objects.equals(url, other.url) && + Objects.equals(write, other.write) ); } @Override public int hashCode() { return Objects.hash( - accountSid, - serviceSid, - mapSid, - identity, - read, - write, - manage, - url + accountSid, + identity, + manage, + mapSid, + read, + serviceSid, + url, + write ); } + + } + diff --git a/src/main/java/com/twilio/rest/sync/v1/service/syncmap/SyncMapPermissionDeleter.java b/src/main/java/com/twilio/rest/sync/v1/service/syncmap/SyncMapPermissionDeleter.java index f599ba5b1f..08f93d859f 100644 --- a/src/main/java/com/twilio/rest/sync/v1/service/syncmap/SyncMapPermissionDeleter.java +++ b/src/main/java/com/twilio/rest/sync/v1/service/syncmap/SyncMapPermissionDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.sync.v1.service.syncmap; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,56 +26,44 @@ public class SyncMapPermissionDeleter extends Deleter { - private String pathServiceSid; - private String pathMapSid; - private String pathIdentity; + private String pathserviceSid; + private String pathmapSid; + private String pathidentity; - public SyncMapPermissionDeleter( - final String pathServiceSid, - final String pathMapSid, - final String pathIdentity - ) { - this.pathServiceSid = pathServiceSid; - this.pathMapSid = pathMapSid; - this.pathIdentity = pathIdentity; + public SyncMapPermissionDeleter(final String pathserviceSid, final String pathmapSid, final String pathidentity) { + this.pathserviceSid = pathserviceSid; + this.pathmapSid = pathmapSid; + this.pathidentity = pathidentity; } + @Override public boolean delete(final TwilioRestClient client) { - String path = - "/v1/Services/{ServiceSid}/Maps/{MapSid}/Permissions/{Identity}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = path.replace("{" + "MapSid" + "}", this.pathMapSid.toString()); - path = - path.replace("{" + "Identity" + "}", this.pathIdentity.toString()); + String path = "/v1/Services/{ServiceSid}/Maps/{MapSid}/Permissions/{Identity}"; + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "MapSid" + "}", this.pathmapSid.toString()); + path = path.replace("{" + "Identity" + "}", this.pathidentity.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.SYNC.toString(), - path + HttpMethod.DELETE, + Domains.SYNC.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "SyncMapPermission delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("SyncMapPermission delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/sync/v1/service/syncmap/SyncMapPermissionFetcher.java b/src/main/java/com/twilio/rest/sync/v1/service/syncmap/SyncMapPermissionFetcher.java index b719e4ee3d..48089b5797 100644 --- a/src/main/java/com/twilio/rest/sync/v1/service/syncmap/SyncMapPermissionFetcher.java +++ b/src/main/java/com/twilio/rest/sync/v1/service/syncmap/SyncMapPermissionFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.sync.v1.service.syncmap; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,63 +26,47 @@ public class SyncMapPermissionFetcher extends Fetcher { - private String pathServiceSid; - private String pathMapSid; - private String pathIdentity; + private String pathserviceSid; + private String pathmapSid; + private String pathidentity; - public SyncMapPermissionFetcher( - final String pathServiceSid, - final String pathMapSid, - final String pathIdentity - ) { - this.pathServiceSid = pathServiceSid; - this.pathMapSid = pathMapSid; - this.pathIdentity = pathIdentity; + public SyncMapPermissionFetcher(final String pathserviceSid, final String pathmapSid, final String pathidentity) { + this.pathserviceSid = pathserviceSid; + this.pathmapSid = pathmapSid; + this.pathidentity = pathidentity; } + @Override public SyncMapPermission fetch(final TwilioRestClient client) { - String path = - "/v1/Services/{ServiceSid}/Maps/{MapSid}/Permissions/{Identity}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = path.replace("{" + "MapSid" + "}", this.pathMapSid.toString()); - path = - path.replace("{" + "Identity" + "}", this.pathIdentity.toString()); + String path = "/v1/Services/{ServiceSid}/Maps/{MapSid}/Permissions/{Identity}"; + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "MapSid" + "}", this.pathmapSid.toString()); + path = path.replace("{" + "Identity" + "}", this.pathidentity.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.SYNC.toString(), - path + HttpMethod.GET, + Domains.SYNC.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "SyncMapPermission fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("SyncMapPermission fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return SyncMapPermission.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return SyncMapPermission.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/sync/v1/service/syncmap/SyncMapPermissionReader.java b/src/main/java/com/twilio/rest/sync/v1/service/syncmap/SyncMapPermissionReader.java index cd3dff5df2..9ea1a63194 100644 --- a/src/main/java/com/twilio/rest/sync/v1/service/syncmap/SyncMapPermissionReader.java +++ b/src/main/java/com/twilio/rest/sync/v1/service/syncmap/SyncMapPermissionReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,121 +30,91 @@ public class SyncMapPermissionReader extends Reader { - private String pathServiceSid; - private String pathMapSid; + private String pathserviceSid; + private String pathmapSid; private Long pageSize; - public SyncMapPermissionReader( - final String pathServiceSid, - final String pathMapSid - ) { - this.pathServiceSid = pathServiceSid; - this.pathMapSid = pathMapSid; + public SyncMapPermissionReader(final String pathserviceSid, final String pathmapSid) { + this.pathserviceSid = pathserviceSid; + this.pathmapSid = pathmapSid; } + public SyncMapPermissionReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/Services/{ServiceSid}/Maps/{MapSid}/Permissions"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = path.replace("{" + "MapSid" + "}", this.pathMapSid.toString()); + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "MapSid" + "}", this.pathmapSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.SYNC.toString(), - path + HttpMethod.GET, + Domains.SYNC.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "SyncMapPermission read failed: Unable to connect to server" - ); + throw new ApiConnectionException("SyncMapPermission read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "permissions", - response.getContent(), - SyncMapPermission.class, - client.getObjectMapper() - ); + "permissions", + response.getContent(), + SyncMapPermission.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.SYNC.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.SYNC.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/sync/v1/service/syncmap/SyncMapPermissionUpdater.java b/src/main/java/com/twilio/rest/sync/v1/service/syncmap/SyncMapPermissionUpdater.java index d834551eba..81ab9197ee 100644 --- a/src/main/java/com/twilio/rest/sync/v1/service/syncmap/SyncMapPermissionUpdater.java +++ b/src/main/java/com/twilio/rest/sync/v1/service/syncmap/SyncMapPermissionUpdater.java @@ -16,6 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -26,103 +28,93 @@ import com.twilio.rest.Domains; public class SyncMapPermissionUpdater extends Updater { - - private String pathServiceSid; - private String pathMapSid; - private String pathIdentity; + private String pathserviceSid; + private String pathmapSid; + private String pathidentity; private Boolean read; private Boolean write; private Boolean manage; - public SyncMapPermissionUpdater( - final String pathServiceSid, - final String pathMapSid, - final String pathIdentity, - final Boolean read, - final Boolean write, - final Boolean manage - ) { - this.pathServiceSid = pathServiceSid; - this.pathMapSid = pathMapSid; - this.pathIdentity = pathIdentity; + public SyncMapPermissionUpdater(final String pathserviceSid, final String pathmapSid, final String pathidentity, final Boolean read, final Boolean write, final Boolean manage) { + this.pathserviceSid = pathserviceSid; + this.pathmapSid = pathmapSid; + this.pathidentity = pathidentity; this.read = read; this.write = write; this.manage = manage; } + public SyncMapPermissionUpdater setRead(final Boolean read) { this.read = read; return this; } + public SyncMapPermissionUpdater setWrite(final Boolean write) { this.write = write; return this; } + public SyncMapPermissionUpdater setManage(final Boolean manage) { this.manage = manage; return this; } + @Override public SyncMapPermission update(final TwilioRestClient client) { - String path = - "/v1/Services/{ServiceSid}/Maps/{MapSid}/Permissions/{Identity}"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = path.replace("{" + "MapSid" + "}", this.pathMapSid.toString()); - path = - path.replace("{" + "Identity" + "}", this.pathIdentity.toString()); - path = path.replace("{" + "Read" + "}", this.read.toString()); - path = path.replace("{" + "Write" + "}", this.write.toString()); - path = path.replace("{" + "Manage" + "}", this.manage.toString()); + String path = "/v1/Services/{ServiceSid}/Maps/{MapSid}/Permissions/{Identity}"; + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "MapSid" + "}", this.pathmapSid.toString()); + path = path.replace("{" + "Identity" + "}", this.pathidentity.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.SYNC.toString(), - path + HttpMethod.POST, + Domains.SYNC.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "SyncMapPermission update failed: Unable to connect to server" - ); + throw new ApiConnectionException("SyncMapPermission update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return SyncMapPermission.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return SyncMapPermission.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (read != null) { - request.addPostParam("Read", read.toString()); + Serializer.toString(request, "Read", read, ParameterType.URLENCODED); } + + if (write != null) { - request.addPostParam("Write", write.toString()); + Serializer.toString(request, "Write", write, ParameterType.URLENCODED); } + + if (manage != null) { - request.addPostParam("Manage", manage.toString()); + Serializer.toString(request, "Manage", manage, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/sync/v1/service/syncstream/StreamMessage.java b/src/main/java/com/twilio/rest/sync/v1/service/syncstream/StreamMessage.java index b787e9d5a1..a1c59a9041 100644 --- a/src/main/java/com/twilio/rest/sync/v1/service/syncstream/StreamMessage.java +++ b/src/main/java/com/twilio/rest/sync/v1/service/syncstream/StreamMessage.java @@ -18,44 +18,39 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; -import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class StreamMessage extends Resource { - private static final long serialVersionUID = 233477236246646L; - public static StreamMessageCreator creator( - final String pathServiceSid, - final String pathStreamSid, - final Object data - ) { - return new StreamMessageCreator(pathServiceSid, pathStreamSid, data); + public static StreamMessageCreator creator(final String pathserviceSid, final String pathstreamSid, final Object data) { + return new StreamMessageCreator( + pathserviceSid, pathstreamSid, data + ); } + /** * Converts a JSON String into a StreamMessage object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return StreamMessage object represented by the provided JSON */ - public static StreamMessage fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static StreamMessage fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, StreamMessage.class); @@ -70,14 +65,11 @@ public static StreamMessage fromJson( * Converts a JSON InputStream into a StreamMessage object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return StreamMessage object represented by the provided JSON */ - public static StreamMessage fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static StreamMessage fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, StreamMessage.class); @@ -88,24 +80,31 @@ public static StreamMessage fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter + private final Object data; + @Getter private final String sid; - private final Map data; @JsonCreator private StreamMessage( - @JsonProperty("sid") final String sid, - @JsonProperty("data") final Map data + @JsonProperty("data") final Object data, + @JsonProperty("sid") final String sid ) { - this.sid = sid; this.data = data; - } - - public final String getSid() { - return this.sid; - } - - public final Map getData() { - return this.data; + this.sid = sid; } @Override @@ -119,14 +118,20 @@ public boolean equals(final Object o) { } StreamMessage other = (StreamMessage) o; - return ( - Objects.equals(sid, other.sid) && Objects.equals(data, other.data) + Objects.equals(data, other.data) && + Objects.equals(sid, other.sid) ); } @Override public int hashCode() { - return Objects.hash(sid, data); + return Objects.hash( + data, + sid + ); } + + } + diff --git a/src/main/java/com/twilio/rest/sync/v1/service/syncstream/StreamMessageCreator.java b/src/main/java/com/twilio/rest/sync/v1/service/syncstream/StreamMessageCreator.java index 015002f303..c71f2e6e24 100644 --- a/src/main/java/com/twilio/rest/sync/v1/service/syncstream/StreamMessageCreator.java +++ b/src/main/java/com/twilio/rest/sync/v1/service/syncstream/StreamMessageCreator.java @@ -14,10 +14,11 @@ package com.twilio.rest.sync.v1.service.syncstream; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; -import com.twilio.converter.Converter; -import com.twilio.converter.Converter; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,76 +30,64 @@ public class StreamMessageCreator extends Creator { - private String pathServiceSid; - private String pathStreamSid; + private String pathserviceSid; + private String pathstreamSid; private Object data; - public StreamMessageCreator( - final String pathServiceSid, - final String pathStreamSid, - final Object data - ) { - this.pathServiceSid = pathServiceSid; - this.pathStreamSid = pathStreamSid; + public StreamMessageCreator(final String pathserviceSid, final String pathstreamSid, final Object data) { + this.pathserviceSid = pathserviceSid; + this.pathstreamSid = pathstreamSid; this.data = data; } + public StreamMessageCreator setData(final Object data) { this.data = data; return this; } + @Override public StreamMessage create(final TwilioRestClient client) { + String path = "/v1/Services/{ServiceSid}/Streams/{StreamSid}/Messages"; - path = - path.replace( - "{" + "ServiceSid" + "}", - this.pathServiceSid.toString() - ); - path = - path.replace( - "{" + "StreamSid" + "}", - this.pathStreamSid.toString() - ); - path = path.replace("{" + "Data" + "}", this.data.toString()); + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + path = path.replace("{" + "StreamSid" + "}", this.pathstreamSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.SYNC.toString(), - path + HttpMethod.POST, + Domains.SYNC.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "StreamMessage creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("StreamMessage creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return StreamMessage.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return StreamMessage.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (data != null) { - request.addPostParam("Data", Converter.objectToJson(data)); + Serializer.toString(request, "Data", data, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/taskrouter/v1/Workspace.java b/src/main/java/com/twilio/rest/taskrouter/v1/Workspace.java index 4ab41a8013..fd4eb3dbae 100644 --- a/src/main/java/com/twilio/rest/taskrouter/v1/Workspace.java +++ b/src/main/java/com/twilio/rest/taskrouter/v1/Workspace.java @@ -18,60 +18,93 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Workspace extends Resource { - private static final long serialVersionUID = 259156582462753L; public static WorkspaceCreator creator(final String friendlyName) { - return new WorkspaceCreator(friendlyName); + return new WorkspaceCreator( + friendlyName + ); } - public static WorkspaceDeleter deleter(final String pathSid) { - return new WorkspaceDeleter(pathSid); + + public static WorkspaceDeleter deleter(final String pathsid) { + return new WorkspaceDeleter( + pathsid + ); } - public static WorkspaceFetcher fetcher(final String pathSid) { - return new WorkspaceFetcher(pathSid); + + public static WorkspaceFetcher fetcher(final String pathsid) { + return new WorkspaceFetcher( + pathsid + ); } + public static WorkspaceReader reader() { - return new WorkspaceReader(); + return new WorkspaceReader( + + ); } - public static WorkspaceUpdater updater(final String pathSid) { - return new WorkspaceUpdater(pathSid); + + public static WorkspaceUpdater updater(final String pathsid) { + return new WorkspaceUpdater( + pathsid + ); } + + public enum QueueOrder { + FIFO("FIFO"), + LIFO("LIFO"); + + private final String value; + + private QueueOrder(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static QueueOrder forValue(final String value) { + return Promoter.enumFromString(value, QueueOrder.values()); + } + } + + /** * Converts a JSON String into a Workspace object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Workspace object represented by the provided JSON */ - public static Workspace fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Workspace fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Workspace.class); @@ -86,14 +119,11 @@ public static Workspace fromJson( * Converts a JSON InputStream into a Workspace object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Workspace object represented by the provided JSON */ - public static Workspace fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Workspace fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Workspace.class); @@ -104,117 +134,85 @@ public static Workspace fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; + @Getter private final String defaultActivityName; + @Getter private final String defaultActivitySid; + @Getter private final URI eventCallbackUrl; + @Getter private final String eventsFilter; + @Getter private final String friendlyName; + @Getter + private final Map links; + @Getter private final Boolean multiTaskEnabled; + @Getter + private final Workspace.QueueOrder prioritizeQueueOrder; + @Getter private final String sid; + @Getter private final String timeoutActivityName; + @Getter private final String timeoutActivitySid; - private final Workspace.QueueOrder prioritizeQueueOrder; + @Getter private final URI url; - private final Map links; @JsonCreator private Workspace( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("default_activity_name") final String defaultActivityName, - @JsonProperty("default_activity_sid") final String defaultActivitySid, - @JsonProperty("event_callback_url") final URI eventCallbackUrl, - @JsonProperty("events_filter") final String eventsFilter, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("multi_task_enabled") final Boolean multiTaskEnabled, - @JsonProperty("sid") final String sid, - @JsonProperty("timeout_activity_name") final String timeoutActivityName, - @JsonProperty("timeout_activity_sid") final String timeoutActivitySid, - @JsonProperty( - "prioritize_queue_order" - ) final Workspace.QueueOrder prioritizeQueueOrder, - @JsonProperty("url") final URI url, - @JsonProperty("links") final Map links + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("default_activity_name") final String defaultActivityName, + @JsonProperty("default_activity_sid") final String defaultActivitySid, + @JsonProperty("event_callback_url") final URI eventCallbackUrl, + @JsonProperty("events_filter") final String eventsFilter, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("links") final Map links, + @JsonProperty("multi_task_enabled") final Boolean multiTaskEnabled, + @JsonProperty("prioritize_queue_order") final Workspace.QueueOrder prioritizeQueueOrder, + @JsonProperty("sid") final String sid, + @JsonProperty("timeout_activity_name") final String timeoutActivityName, + @JsonProperty("timeout_activity_sid") final String timeoutActivitySid, + @JsonProperty("url") final URI url ) { this.accountSid = accountSid; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.defaultActivityName = defaultActivityName; this.defaultActivitySid = defaultActivitySid; this.eventCallbackUrl = eventCallbackUrl; this.eventsFilter = eventsFilter; this.friendlyName = friendlyName; + this.links = links; this.multiTaskEnabled = multiTaskEnabled; + this.prioritizeQueueOrder = prioritizeQueueOrder; this.sid = sid; this.timeoutActivityName = timeoutActivityName; this.timeoutActivitySid = timeoutActivitySid; - this.prioritizeQueueOrder = prioritizeQueueOrder; this.url = url; - this.links = links; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final String getDefaultActivityName() { - return this.defaultActivityName; - } - - public final String getDefaultActivitySid() { - return this.defaultActivitySid; - } - - public final URI getEventCallbackUrl() { - return this.eventCallbackUrl; - } - - public final String getEventsFilter() { - return this.eventsFilter; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final Boolean getMultiTaskEnabled() { - return this.multiTaskEnabled; - } - - public final String getSid() { - return this.sid; - } - - public final String getTimeoutActivityName() { - return this.timeoutActivityName; - } - - public final String getTimeoutActivitySid() { - return this.timeoutActivitySid; - } - - public final Workspace.QueueOrder getPrioritizeQueueOrder() { - return this.prioritizeQueueOrder; - } - - public final URI getUrl() { - return this.url; - } - - public final Map getLinks() { - return this.links; } @Override @@ -228,64 +226,46 @@ public boolean equals(final Object o) { } Workspace other = (Workspace) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(defaultActivityName, other.defaultActivityName) && - Objects.equals(defaultActivitySid, other.defaultActivitySid) && - Objects.equals(eventCallbackUrl, other.eventCallbackUrl) && - Objects.equals(eventsFilter, other.eventsFilter) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(multiTaskEnabled, other.multiTaskEnabled) && - Objects.equals(sid, other.sid) && - Objects.equals(timeoutActivityName, other.timeoutActivityName) && - Objects.equals(timeoutActivitySid, other.timeoutActivitySid) && - Objects.equals(prioritizeQueueOrder, other.prioritizeQueueOrder) && - Objects.equals(url, other.url) && - Objects.equals(links, other.links) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(defaultActivityName, other.defaultActivityName) && + Objects.equals(defaultActivitySid, other.defaultActivitySid) && + Objects.equals(eventCallbackUrl, other.eventCallbackUrl) && + Objects.equals(eventsFilter, other.eventsFilter) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(links, other.links) && + Objects.equals(multiTaskEnabled, other.multiTaskEnabled) && + Objects.equals(prioritizeQueueOrder, other.prioritizeQueueOrder) && + Objects.equals(sid, other.sid) && + Objects.equals(timeoutActivityName, other.timeoutActivityName) && + Objects.equals(timeoutActivitySid, other.timeoutActivitySid) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - accountSid, - dateCreated, - dateUpdated, - defaultActivityName, - defaultActivitySid, - eventCallbackUrl, - eventsFilter, - friendlyName, - multiTaskEnabled, - sid, - timeoutActivityName, - timeoutActivitySid, - prioritizeQueueOrder, - url, - links + accountSid, + dateCreated, + dateUpdated, + defaultActivityName, + defaultActivitySid, + eventCallbackUrl, + eventsFilter, + friendlyName, + links, + multiTaskEnabled, + prioritizeQueueOrder, + sid, + timeoutActivityName, + timeoutActivitySid, + url ); } - public enum QueueOrder { - FIFO("FIFO"), - LIFO("LIFO"); - - private final String value; - - private QueueOrder(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - @JsonCreator - public static QueueOrder forValue(final String value) { - return Promoter.enumFromString(value, QueueOrder.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/taskrouter/v1/WorkspaceCreator.java b/src/main/java/com/twilio/rest/taskrouter/v1/WorkspaceCreator.java index 3c0067d543..461d0efb14 100644 --- a/src/main/java/com/twilio/rest/taskrouter/v1/WorkspaceCreator.java +++ b/src/main/java/com/twilio/rest/taskrouter/v1/WorkspaceCreator.java @@ -14,9 +14,11 @@ package com.twilio.rest.taskrouter.v1; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; -import com.twilio.converter.Promoter; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,7 +27,7 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -import java.net.URI; + import java.net.URI; public class WorkspaceCreator extends Creator { @@ -41,113 +43,106 @@ public WorkspaceCreator(final String friendlyName) { this.friendlyName = friendlyName; } + public WorkspaceCreator setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + public WorkspaceCreator setEventCallbackUrl(final URI eventCallbackUrl) { this.eventCallbackUrl = eventCallbackUrl; return this; } - public WorkspaceCreator setEventCallbackUrl(final String eventCallbackUrl) { - return setEventCallbackUrl(Promoter.uriFromString(eventCallbackUrl)); - } public WorkspaceCreator setEventsFilter(final String eventsFilter) { this.eventsFilter = eventsFilter; return this; } - public WorkspaceCreator setMultiTaskEnabled( - final Boolean multiTaskEnabled - ) { + + public WorkspaceCreator setMultiTaskEnabled(final Boolean multiTaskEnabled) { this.multiTaskEnabled = multiTaskEnabled; return this; } + public WorkspaceCreator setTemplate(final String template) { this.template = template; return this; } - public WorkspaceCreator setPrioritizeQueueOrder( - final Workspace.QueueOrder prioritizeQueueOrder - ) { + + public WorkspaceCreator setPrioritizeQueueOrder(final Workspace.QueueOrder prioritizeQueueOrder) { this.prioritizeQueueOrder = prioritizeQueueOrder; return this; } + @Override public Workspace create(final TwilioRestClient client) { + String path = "/v1/Workspaces"; - path = - path.replace( - "{" + "FriendlyName" + "}", - this.friendlyName.toString() - ); Request request = new Request( - HttpMethod.POST, - Domains.TASKROUTER.toString(), - path + HttpMethod.POST, + Domains.TASKROUTER.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Workspace creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("Workspace creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Workspace.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Workspace.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + if (eventCallbackUrl != null) { - request.addPostParam( - "EventCallbackUrl", - eventCallbackUrl.toString() - ); + Serializer.toString(request, "EventCallbackUrl", eventCallbackUrl, ParameterType.URLENCODED); } + + if (eventsFilter != null) { - request.addPostParam("EventsFilter", eventsFilter); + Serializer.toString(request, "EventsFilter", eventsFilter, ParameterType.URLENCODED); } + + if (multiTaskEnabled != null) { - request.addPostParam( - "MultiTaskEnabled", - multiTaskEnabled.toString() - ); + Serializer.toString(request, "MultiTaskEnabled", multiTaskEnabled, ParameterType.URLENCODED); } + + if (template != null) { - request.addPostParam("Template", template); + Serializer.toString(request, "Template", template, ParameterType.URLENCODED); } + + if (prioritizeQueueOrder != null) { - request.addPostParam( - "PrioritizeQueueOrder", - prioritizeQueueOrder.toString() - ); + Serializer.toString(request, "PrioritizeQueueOrder", prioritizeQueueOrder, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/taskrouter/v1/WorkspaceDeleter.java b/src/main/java/com/twilio/rest/taskrouter/v1/WorkspaceDeleter.java index 0b8100d345..47c7c64955 100644 --- a/src/main/java/com/twilio/rest/taskrouter/v1/WorkspaceDeleter.java +++ b/src/main/java/com/twilio/rest/taskrouter/v1/WorkspaceDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.taskrouter.v1; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,40 +26,38 @@ public class WorkspaceDeleter extends Deleter { - private String pathSid; + private String pathsid; - public WorkspaceDeleter(final String pathSid) { - this.pathSid = pathSid; + public WorkspaceDeleter(final String pathsid) { + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/v1/Workspaces/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.TASKROUTER.toString(), - path + HttpMethod.DELETE, + Domains.TASKROUTER.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Workspace delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("Workspace delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/taskrouter/v1/WorkspaceFetcher.java b/src/main/java/com/twilio/rest/taskrouter/v1/WorkspaceFetcher.java index 0d8797a592..2ece1d4d8a 100644 --- a/src/main/java/com/twilio/rest/taskrouter/v1/WorkspaceFetcher.java +++ b/src/main/java/com/twilio/rest/taskrouter/v1/WorkspaceFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.taskrouter.v1; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,47 +26,41 @@ public class WorkspaceFetcher extends Fetcher { - private String pathSid; + private String pathsid; - public WorkspaceFetcher(final String pathSid) { - this.pathSid = pathSid; + public WorkspaceFetcher(final String pathsid) { + this.pathsid = pathsid; } + @Override public Workspace fetch(final TwilioRestClient client) { + String path = "/v1/Workspaces/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.TASKROUTER.toString(), - path + HttpMethod.GET, + Domains.TASKROUTER.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Workspace fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Workspace fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return Workspace.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Workspace.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/taskrouter/v1/WorkspaceReader.java b/src/main/java/com/twilio/rest/taskrouter/v1/WorkspaceReader.java index 3dbcb0e045..4cd0881b7f 100644 --- a/src/main/java/com/twilio/rest/taskrouter/v1/WorkspaceReader.java +++ b/src/main/java/com/twilio/rest/taskrouter/v1/WorkspaceReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -32,113 +33,94 @@ public class WorkspaceReader extends Reader { private String friendlyName; private Long pageSize; - public WorkspaceReader() {} + public WorkspaceReader() { + } + public WorkspaceReader setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + public WorkspaceReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/Workspaces"; + Request request = new Request( - HttpMethod.GET, - Domains.TASKROUTER.toString(), - path + HttpMethod.GET, + Domains.TASKROUTER.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Workspace read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Workspace read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "workspaces", - response.getContent(), - Workspace.class, - client.getObjectMapper() - ); + "workspaces", + response.getContent(), + Workspace.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.TASKROUTER.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.TASKROUTER.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (friendlyName != null) { - request.addQueryParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.QUERY); } + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/taskrouter/v1/WorkspaceUpdater.java b/src/main/java/com/twilio/rest/taskrouter/v1/WorkspaceUpdater.java index b448d55d8b..fa9f958fd6 100644 --- a/src/main/java/com/twilio/rest/taskrouter/v1/WorkspaceUpdater.java +++ b/src/main/java/com/twilio/rest/taskrouter/v1/WorkspaceUpdater.java @@ -16,7 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; -import com.twilio.converter.Promoter; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,11 +26,11 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.net.URI; public class WorkspaceUpdater extends Updater { - - private String pathSid; + private String pathsid; private String defaultActivitySid; private URI eventCallbackUrl; private String eventsFilter; @@ -38,125 +39,123 @@ public class WorkspaceUpdater extends Updater { private String timeoutActivitySid; private Workspace.QueueOrder prioritizeQueueOrder; - public WorkspaceUpdater(final String pathSid) { - this.pathSid = pathSid; + public WorkspaceUpdater(final String pathsid) { + this.pathsid = pathsid; } - public WorkspaceUpdater setDefaultActivitySid( - final String defaultActivitySid - ) { + + public WorkspaceUpdater setDefaultActivitySid(final String defaultActivitySid) { this.defaultActivitySid = defaultActivitySid; return this; } + public WorkspaceUpdater setEventCallbackUrl(final URI eventCallbackUrl) { this.eventCallbackUrl = eventCallbackUrl; return this; } - public WorkspaceUpdater setEventCallbackUrl(final String eventCallbackUrl) { - return setEventCallbackUrl(Promoter.uriFromString(eventCallbackUrl)); - } public WorkspaceUpdater setEventsFilter(final String eventsFilter) { this.eventsFilter = eventsFilter; return this; } + public WorkspaceUpdater setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } - public WorkspaceUpdater setMultiTaskEnabled( - final Boolean multiTaskEnabled - ) { + + public WorkspaceUpdater setMultiTaskEnabled(final Boolean multiTaskEnabled) { this.multiTaskEnabled = multiTaskEnabled; return this; } - public WorkspaceUpdater setTimeoutActivitySid( - final String timeoutActivitySid - ) { + + public WorkspaceUpdater setTimeoutActivitySid(final String timeoutActivitySid) { this.timeoutActivitySid = timeoutActivitySid; return this; } - public WorkspaceUpdater setPrioritizeQueueOrder( - final Workspace.QueueOrder prioritizeQueueOrder - ) { + + public WorkspaceUpdater setPrioritizeQueueOrder(final Workspace.QueueOrder prioritizeQueueOrder) { this.prioritizeQueueOrder = prioritizeQueueOrder; return this; } + @Override public Workspace update(final TwilioRestClient client) { + String path = "/v1/Workspaces/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.TASKROUTER.toString(), - path + HttpMethod.POST, + Domains.TASKROUTER.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Workspace update failed: Unable to connect to server" - ); + throw new ApiConnectionException("Workspace update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Workspace.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Workspace.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (defaultActivitySid != null) { - request.addPostParam("DefaultActivitySid", defaultActivitySid); + Serializer.toString(request, "DefaultActivitySid", defaultActivitySid, ParameterType.URLENCODED); } + + if (eventCallbackUrl != null) { - request.addPostParam( - "EventCallbackUrl", - eventCallbackUrl.toString() - ); + Serializer.toString(request, "EventCallbackUrl", eventCallbackUrl, ParameterType.URLENCODED); } + + if (eventsFilter != null) { - request.addPostParam("EventsFilter", eventsFilter); + Serializer.toString(request, "EventsFilter", eventsFilter, ParameterType.URLENCODED); } + + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + if (multiTaskEnabled != null) { - request.addPostParam( - "MultiTaskEnabled", - multiTaskEnabled.toString() - ); + Serializer.toString(request, "MultiTaskEnabled", multiTaskEnabled, ParameterType.URLENCODED); } + + if (timeoutActivitySid != null) { - request.addPostParam("TimeoutActivitySid", timeoutActivitySid); + Serializer.toString(request, "TimeoutActivitySid", timeoutActivitySid, ParameterType.URLENCODED); } + + if (prioritizeQueueOrder != null) { - request.addPostParam( - "PrioritizeQueueOrder", - prioritizeQueueOrder.toString() - ); + Serializer.toString(request, "PrioritizeQueueOrder", prioritizeQueueOrder, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/Activity.java b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/Activity.java index 93ff3f6239..e777ec5cff 100644 --- a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/Activity.java +++ b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/Activity.java @@ -18,71 +18,71 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Activity extends Resource { - private static final long serialVersionUID = 20275383236164L; - public static ActivityCreator creator( - final String pathWorkspaceSid, - final String friendlyName - ) { - return new ActivityCreator(pathWorkspaceSid, friendlyName); + public static ActivityCreator creator(final String pathworkspaceSid, final String friendlyName) { + return new ActivityCreator( + pathworkspaceSid, friendlyName + ); } - public static ActivityDeleter deleter( - final String pathWorkspaceSid, - final String pathSid - ) { - return new ActivityDeleter(pathWorkspaceSid, pathSid); + + public static ActivityDeleter deleter(final String pathworkspaceSid, final String pathsid) { + return new ActivityDeleter( + pathworkspaceSid, pathsid + ); } - public static ActivityFetcher fetcher( - final String pathWorkspaceSid, - final String pathSid - ) { - return new ActivityFetcher(pathWorkspaceSid, pathSid); + + public static ActivityFetcher fetcher(final String pathworkspaceSid, final String pathsid) { + return new ActivityFetcher( + pathworkspaceSid, pathsid + ); } - public static ActivityReader reader(final String pathWorkspaceSid) { - return new ActivityReader(pathWorkspaceSid); + + public static ActivityReader reader(final String pathworkspaceSid) { + return new ActivityReader( + pathworkspaceSid + ); } - public static ActivityUpdater updater( - final String pathWorkspaceSid, - final String pathSid - ) { - return new ActivityUpdater(pathWorkspaceSid, pathSid); + + public static ActivityUpdater updater(final String pathworkspaceSid, final String pathsid) { + return new ActivityUpdater( + pathworkspaceSid, pathsid + ); } + /** * Converts a JSON String into a Activity object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Activity object represented by the provided JSON */ - public static Activity fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Activity fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Activity.class); @@ -97,14 +97,11 @@ public static Activity fromJson( * Converts a JSON InputStream into a Activity object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Activity object represented by the provided JSON */ - public static Activity fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Activity fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Activity.class); @@ -115,73 +112,61 @@ public static Activity fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; + @Getter private final Boolean available; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; + @Getter private final String friendlyName; + @Getter + private final Map links; + @Getter private final String sid; - private final String workspaceSid; + @Getter private final URI url; - private final Map links; + @Getter + private final String workspaceSid; @JsonCreator private Activity( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("available") final Boolean available, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("sid") final String sid, - @JsonProperty("workspace_sid") final String workspaceSid, - @JsonProperty("url") final URI url, - @JsonProperty("links") final Map links + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("available") final Boolean available, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("links") final Map links, + @JsonProperty("sid") final String sid, + @JsonProperty("url") final URI url, + @JsonProperty("workspace_sid") final String workspaceSid ) { this.accountSid = accountSid; this.available = available; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.friendlyName = friendlyName; + this.links = links; this.sid = sid; - this.workspaceSid = workspaceSid; this.url = url; - this.links = links; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final Boolean getAvailable() { - return this.available; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final String getSid() { - return this.sid; - } - - public final String getWorkspaceSid() { - return this.workspaceSid; - } - - public final URI getUrl() { - return this.url; - } - - public final Map getLinks() { - return this.links; + this.workspaceSid = workspaceSid; } @Override @@ -195,32 +180,34 @@ public boolean equals(final Object o) { } Activity other = (Activity) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(available, other.available) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(sid, other.sid) && - Objects.equals(workspaceSid, other.workspaceSid) && - Objects.equals(url, other.url) && - Objects.equals(links, other.links) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(available, other.available) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(links, other.links) && + Objects.equals(sid, other.sid) && + Objects.equals(url, other.url) && + Objects.equals(workspaceSid, other.workspaceSid) ); } @Override public int hashCode() { return Objects.hash( - accountSid, - available, - dateCreated, - dateUpdated, - friendlyName, - sid, - workspaceSid, - url, - links + accountSid, + available, + dateCreated, + dateUpdated, + friendlyName, + links, + sid, + url, + workspaceSid ); } + + } + diff --git a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/ActivityCreator.java b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/ActivityCreator.java index db781a655a..5284157d40 100644 --- a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/ActivityCreator.java +++ b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/ActivityCreator.java @@ -14,8 +14,11 @@ package com.twilio.rest.taskrouter.v1.workspace; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,81 +30,73 @@ public class ActivityCreator extends Creator { - private String pathWorkspaceSid; + private String pathworkspaceSid; private String friendlyName; private Boolean available; - public ActivityCreator( - final String pathWorkspaceSid, - final String friendlyName - ) { - this.pathWorkspaceSid = pathWorkspaceSid; + public ActivityCreator(final String pathworkspaceSid, final String friendlyName) { + this.pathworkspaceSid = pathworkspaceSid; this.friendlyName = friendlyName; } + public ActivityCreator setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + public ActivityCreator setAvailable(final Boolean available) { this.available = available; return this; } + @Override public Activity create(final TwilioRestClient client) { + String path = "/v1/Workspaces/{WorkspaceSid}/Activities"; - path = - path.replace( - "{" + "WorkspaceSid" + "}", - this.pathWorkspaceSid.toString() - ); - path = - path.replace( - "{" + "FriendlyName" + "}", - this.friendlyName.toString() - ); + path = path.replace("{" + "WorkspaceSid" + "}", this.pathworkspaceSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.TASKROUTER.toString(), - path + HttpMethod.POST, + Domains.TASKROUTER.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Activity creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("Activity creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Activity.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Activity.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + if (available != null) { - request.addPostParam("Available", available.toString()); + Serializer.toString(request, "Available", available, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/ActivityDeleter.java b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/ActivityDeleter.java index d616b1c0b3..93c5c5add6 100644 --- a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/ActivityDeleter.java +++ b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/ActivityDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.taskrouter.v1.workspace; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,50 +26,41 @@ public class ActivityDeleter extends Deleter { - private String pathWorkspaceSid; - private String pathSid; + private String pathworkspaceSid; + private String pathsid; - public ActivityDeleter( - final String pathWorkspaceSid, - final String pathSid - ) { - this.pathWorkspaceSid = pathWorkspaceSid; - this.pathSid = pathSid; + public ActivityDeleter(final String pathworkspaceSid, final String pathsid) { + this.pathworkspaceSid = pathworkspaceSid; + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/v1/Workspaces/{WorkspaceSid}/Activities/{Sid}"; - path = - path.replace( - "{" + "WorkspaceSid" + "}", - this.pathWorkspaceSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "WorkspaceSid" + "}", this.pathworkspaceSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.TASKROUTER.toString(), - path + HttpMethod.DELETE, + Domains.TASKROUTER.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Activity delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("Activity delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/ActivityFetcher.java b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/ActivityFetcher.java index 40795d0915..674fa8f97e 100644 --- a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/ActivityFetcher.java +++ b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/ActivityFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.taskrouter.v1.workspace; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,57 +26,44 @@ public class ActivityFetcher extends Fetcher { - private String pathWorkspaceSid; - private String pathSid; + private String pathworkspaceSid; + private String pathsid; - public ActivityFetcher( - final String pathWorkspaceSid, - final String pathSid - ) { - this.pathWorkspaceSid = pathWorkspaceSid; - this.pathSid = pathSid; + public ActivityFetcher(final String pathworkspaceSid, final String pathsid) { + this.pathworkspaceSid = pathworkspaceSid; + this.pathsid = pathsid; } + @Override public Activity fetch(final TwilioRestClient client) { + String path = "/v1/Workspaces/{WorkspaceSid}/Activities/{Sid}"; - path = - path.replace( - "{" + "WorkspaceSid" + "}", - this.pathWorkspaceSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "WorkspaceSid" + "}", this.pathworkspaceSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.TASKROUTER.toString(), - path + HttpMethod.GET, + Domains.TASKROUTER.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Activity fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Activity fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return Activity.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Activity.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/ActivityReader.java b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/ActivityReader.java index c4c279f092..becb502f76 100644 --- a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/ActivityReader.java +++ b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/ActivityReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,133 +30,112 @@ public class ActivityReader extends Reader { - private String pathWorkspaceSid; + private String pathworkspaceSid; private String friendlyName; private String available; private Long pageSize; - public ActivityReader(final String pathWorkspaceSid) { - this.pathWorkspaceSid = pathWorkspaceSid; + public ActivityReader(final String pathworkspaceSid) { + this.pathworkspaceSid = pathworkspaceSid; } + public ActivityReader setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + public ActivityReader setAvailable(final String available) { this.available = available; return this; } + public ActivityReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/Workspaces/{WorkspaceSid}/Activities"; - path = - path.replace( - "{" + "WorkspaceSid" + "}", - this.pathWorkspaceSid.toString() - ); + + path = path.replace("{" + "WorkspaceSid" + "}", this.pathworkspaceSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.TASKROUTER.toString(), - path + HttpMethod.GET, + Domains.TASKROUTER.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Activity read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Activity read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "activities", - response.getContent(), - Activity.class, - client.getObjectMapper() - ); + "activities", + response.getContent(), + Activity.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.TASKROUTER.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.TASKROUTER.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (friendlyName != null) { - request.addQueryParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.QUERY); } + + if (available != null) { - request.addQueryParam("Available", available); + Serializer.toString(request, "Available", available, ParameterType.QUERY); } + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/ActivityUpdater.java b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/ActivityUpdater.java index ee86c36783..9cac2f5835 100644 --- a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/ActivityUpdater.java +++ b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/ActivityUpdater.java @@ -16,6 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -26,70 +28,63 @@ import com.twilio.rest.Domains; public class ActivityUpdater extends Updater { - - private String pathWorkspaceSid; - private String pathSid; + private String pathworkspaceSid; + private String pathsid; private String friendlyName; - public ActivityUpdater( - final String pathWorkspaceSid, - final String pathSid - ) { - this.pathWorkspaceSid = pathWorkspaceSid; - this.pathSid = pathSid; + public ActivityUpdater(final String pathworkspaceSid, final String pathsid) { + this.pathworkspaceSid = pathworkspaceSid; + this.pathsid = pathsid; } + public ActivityUpdater setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + @Override public Activity update(final TwilioRestClient client) { + String path = "/v1/Workspaces/{WorkspaceSid}/Activities/{Sid}"; - path = - path.replace( - "{" + "WorkspaceSid" + "}", - this.pathWorkspaceSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "WorkspaceSid" + "}", this.pathworkspaceSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.TASKROUTER.toString(), - path + HttpMethod.POST, + Domains.TASKROUTER.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Activity update failed: Unable to connect to server" - ); + throw new ApiConnectionException("Activity update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Activity.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Activity.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/Event.java b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/Event.java index 93c3ae139a..cc405b7e73 100644 --- a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/Event.java +++ b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/Event.java @@ -18,50 +18,49 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; -import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Event extends Resource { - private static final long serialVersionUID = 215026832174382L; - public static EventFetcher fetcher( - final String pathWorkspaceSid, - final String pathSid - ) { - return new EventFetcher(pathWorkspaceSid, pathSid); + public static EventFetcher fetcher(final String pathworkspaceSid, final String pathsid) { + return new EventFetcher( + pathworkspaceSid, pathsid + ); } - public static EventReader reader(final String pathWorkspaceSid) { - return new EventReader(pathWorkspaceSid); + + public static EventReader reader(final String pathworkspaceSid) { + return new EventReader( + pathworkspaceSid + ); } + /** * Converts a JSON String into a Event object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Event object represented by the provided JSON */ - public static Event fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Event fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Event.class); @@ -76,14 +75,11 @@ public static Event fromJson( * Converts a JSON InputStream into a Event object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Event object represented by the provided JSON */ - public static Event fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Event fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Event.class); @@ -94,43 +90,74 @@ public static Event fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; + @Getter private final String actorSid; + @Getter private final String actorType; + @Getter private final URI actorUrl; + @Getter private final String description; - private final Map eventData; + @Getter + private final Object eventData; + @Getter private final ZonedDateTime eventDate; + @Getter private final Long eventDateMs; + @Getter private final String eventType; + @Getter private final String resourceSid; + @Getter private final String resourceType; + @Getter private final URI resourceUrl; + @Getter private final String sid; + @Getter private final String source; + @Getter private final String sourceIpAddress; + @Getter private final URI url; + @Getter private final String workspaceSid; @JsonCreator private Event( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("actor_sid") final String actorSid, - @JsonProperty("actor_type") final String actorType, - @JsonProperty("actor_url") final URI actorUrl, - @JsonProperty("description") final String description, - @JsonProperty("event_data") final Map eventData, - @JsonProperty("event_date") final String eventDate, - @JsonProperty("event_date_ms") final Long eventDateMs, - @JsonProperty("event_type") final String eventType, - @JsonProperty("resource_sid") final String resourceSid, - @JsonProperty("resource_type") final String resourceType, - @JsonProperty("resource_url") final URI resourceUrl, - @JsonProperty("sid") final String sid, - @JsonProperty("source") final String source, - @JsonProperty("source_ip_address") final String sourceIpAddress, - @JsonProperty("url") final URI url, - @JsonProperty("workspace_sid") final String workspaceSid + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("actor_sid") final String actorSid, + @JsonProperty("actor_type") final String actorType, + @JsonProperty("actor_url") final URI actorUrl, + @JsonProperty("description") final String description, + @JsonProperty("event_data") final Object eventData, + @JsonProperty("event_date") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime eventDate, + @JsonProperty("event_date_ms") final Long eventDateMs, + @JsonProperty("event_type") final String eventType, + @JsonProperty("resource_sid") final String resourceSid, + @JsonProperty("resource_type") final String resourceType, + @JsonProperty("resource_url") final URI resourceUrl, + @JsonProperty("sid") final String sid, + @JsonProperty("source") final String source, + @JsonProperty("source_ip_address") final String sourceIpAddress, + @JsonProperty("url") final URI url, + @JsonProperty("workspace_sid") final String workspaceSid ) { this.accountSid = accountSid; this.actorSid = actorSid; @@ -138,7 +165,7 @@ private Event( this.actorUrl = actorUrl; this.description = description; this.eventData = eventData; - this.eventDate = DateConverter.iso8601DateTimeFromString(eventDate); + this.eventDate = eventDate; this.eventDateMs = eventDateMs; this.eventType = eventType; this.resourceSid = resourceSid; @@ -151,74 +178,6 @@ private Event( this.workspaceSid = workspaceSid; } - public final String getAccountSid() { - return this.accountSid; - } - - public final String getActorSid() { - return this.actorSid; - } - - public final String getActorType() { - return this.actorType; - } - - public final URI getActorUrl() { - return this.actorUrl; - } - - public final String getDescription() { - return this.description; - } - - public final Map getEventData() { - return this.eventData; - } - - public final ZonedDateTime getEventDate() { - return this.eventDate; - } - - public final Long getEventDateMs() { - return this.eventDateMs; - } - - public final String getEventType() { - return this.eventType; - } - - public final String getResourceSid() { - return this.resourceSid; - } - - public final String getResourceType() { - return this.resourceType; - } - - public final URI getResourceUrl() { - return this.resourceUrl; - } - - public final String getSid() { - return this.sid; - } - - public final String getSource() { - return this.source; - } - - public final String getSourceIpAddress() { - return this.sourceIpAddress; - } - - public final URI getUrl() { - return this.url; - } - - public final String getWorkspaceSid() { - return this.workspaceSid; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -230,48 +189,50 @@ public boolean equals(final Object o) { } Event other = (Event) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(actorSid, other.actorSid) && - Objects.equals(actorType, other.actorType) && - Objects.equals(actorUrl, other.actorUrl) && - Objects.equals(description, other.description) && - Objects.equals(eventData, other.eventData) && - Objects.equals(eventDate, other.eventDate) && - Objects.equals(eventDateMs, other.eventDateMs) && - Objects.equals(eventType, other.eventType) && - Objects.equals(resourceSid, other.resourceSid) && - Objects.equals(resourceType, other.resourceType) && - Objects.equals(resourceUrl, other.resourceUrl) && - Objects.equals(sid, other.sid) && - Objects.equals(source, other.source) && - Objects.equals(sourceIpAddress, other.sourceIpAddress) && - Objects.equals(url, other.url) && - Objects.equals(workspaceSid, other.workspaceSid) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(actorSid, other.actorSid) && + Objects.equals(actorType, other.actorType) && + Objects.equals(actorUrl, other.actorUrl) && + Objects.equals(description, other.description) && + Objects.equals(eventData, other.eventData) && + Objects.equals(eventDate, other.eventDate) && + Objects.equals(eventDateMs, other.eventDateMs) && + Objects.equals(eventType, other.eventType) && + Objects.equals(resourceSid, other.resourceSid) && + Objects.equals(resourceType, other.resourceType) && + Objects.equals(resourceUrl, other.resourceUrl) && + Objects.equals(sid, other.sid) && + Objects.equals(source, other.source) && + Objects.equals(sourceIpAddress, other.sourceIpAddress) && + Objects.equals(url, other.url) && + Objects.equals(workspaceSid, other.workspaceSid) ); } @Override public int hashCode() { return Objects.hash( - accountSid, - actorSid, - actorType, - actorUrl, - description, - eventData, - eventDate, - eventDateMs, - eventType, - resourceSid, - resourceType, - resourceUrl, - sid, - source, - sourceIpAddress, - url, - workspaceSid + accountSid, + actorSid, + actorType, + actorUrl, + description, + eventData, + eventDate, + eventDateMs, + eventType, + resourceSid, + resourceType, + resourceUrl, + sid, + source, + sourceIpAddress, + url, + workspaceSid ); } + + } + diff --git a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/EventFetcher.java b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/EventFetcher.java index f92f15fed7..dab32c9816 100644 --- a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/EventFetcher.java +++ b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/EventFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.taskrouter.v1.workspace; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,51 +26,44 @@ public class EventFetcher extends Fetcher { - private String pathWorkspaceSid; - private String pathSid; + private String pathworkspaceSid; + private String pathsid; - public EventFetcher(final String pathWorkspaceSid, final String pathSid) { - this.pathWorkspaceSid = pathWorkspaceSid; - this.pathSid = pathSid; + public EventFetcher(final String pathworkspaceSid, final String pathsid) { + this.pathworkspaceSid = pathworkspaceSid; + this.pathsid = pathsid; } + @Override public Event fetch(final TwilioRestClient client) { + String path = "/v1/Workspaces/{WorkspaceSid}/Events/{Sid}"; - path = - path.replace( - "{" + "WorkspaceSid" + "}", - this.pathWorkspaceSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "WorkspaceSid" + "}", this.pathworkspaceSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.TASKROUTER.toString(), - path + HttpMethod.GET, + Domains.TASKROUTER.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Event fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Event fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Event.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/EventReader.java b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/EventReader.java index 7d1c818619..e282ac2c51 100644 --- a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/EventReader.java +++ b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/EventReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -26,11 +27,12 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.time.ZonedDateTime; public class EventReader extends Reader { - private String pathWorkspaceSid; + private String pathworkspaceSid; private ZonedDateTime endDate; private String eventType; private Integer minutes; @@ -44,205 +46,206 @@ public class EventReader extends Reader { private String sid; private Long pageSize; - public EventReader(final String pathWorkspaceSid) { - this.pathWorkspaceSid = pathWorkspaceSid; + public EventReader(final String pathworkspaceSid) { + this.pathworkspaceSid = pathworkspaceSid; } + public EventReader setEndDate(final ZonedDateTime endDate) { this.endDate = endDate; return this; } + public EventReader setEventType(final String eventType) { this.eventType = eventType; return this; } + public EventReader setMinutes(final Integer minutes) { this.minutes = minutes; return this; } + public EventReader setReservationSid(final String reservationSid) { this.reservationSid = reservationSid; return this; } + public EventReader setStartDate(final ZonedDateTime startDate) { this.startDate = startDate; return this; } + public EventReader setTaskQueueSid(final String taskQueueSid) { this.taskQueueSid = taskQueueSid; return this; } + public EventReader setTaskSid(final String taskSid) { this.taskSid = taskSid; return this; } + public EventReader setWorkerSid(final String workerSid) { this.workerSid = workerSid; return this; } + public EventReader setWorkflowSid(final String workflowSid) { this.workflowSid = workflowSid; return this; } + public EventReader setTaskChannel(final String taskChannel) { this.taskChannel = taskChannel; return this; } + public EventReader setSid(final String sid) { this.sid = sid; return this; } + public EventReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/Workspaces/{WorkspaceSid}/Events"; - path = - path.replace( - "{" + "WorkspaceSid" + "}", - this.pathWorkspaceSid.toString() - ); + + path = path.replace("{" + "WorkspaceSid" + "}", this.pathworkspaceSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.TASKROUTER.toString(), - path + HttpMethod.GET, + Domains.TASKROUTER.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Event read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Event read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "events", - response.getContent(), - Event.class, - client.getObjectMapper() - ); + "events", + response.getContent(), + Event.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.TASKROUTER.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.TASKROUTER.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (endDate != null) { - request.addQueryParam("EndDate", endDate.toInstant().toString()); + Serializer.toString(request, "EndDate", endDate, ParameterType.QUERY); } + if (eventType != null) { - request.addQueryParam("EventType", eventType); + Serializer.toString(request, "EventType", eventType, ParameterType.QUERY); } + + if (minutes != null) { - request.addQueryParam("Minutes", minutes.toString()); + Serializer.toString(request, "Minutes", minutes, ParameterType.QUERY); } + + if (reservationSid != null) { - request.addQueryParam("ReservationSid", reservationSid); + Serializer.toString(request, "ReservationSid", reservationSid, ParameterType.QUERY); } + + if (startDate != null) { - request.addQueryParam( - "StartDate", - startDate.toInstant().toString() - ); + Serializer.toString(request, "StartDate", startDate, ParameterType.QUERY); } + if (taskQueueSid != null) { - request.addQueryParam("TaskQueueSid", taskQueueSid); + Serializer.toString(request, "TaskQueueSid", taskQueueSid, ParameterType.QUERY); } + + if (taskSid != null) { - request.addQueryParam("TaskSid", taskSid); + Serializer.toString(request, "TaskSid", taskSid, ParameterType.QUERY); } + + if (workerSid != null) { - request.addQueryParam("WorkerSid", workerSid); + Serializer.toString(request, "WorkerSid", workerSid, ParameterType.QUERY); } + + if (workflowSid != null) { - request.addQueryParam("WorkflowSid", workflowSid); + Serializer.toString(request, "WorkflowSid", workflowSid, ParameterType.QUERY); } + + if (taskChannel != null) { - request.addQueryParam("TaskChannel", taskChannel); + Serializer.toString(request, "TaskChannel", taskChannel, ParameterType.QUERY); } + + if (sid != null) { - request.addQueryParam("Sid", sid); + Serializer.toString(request, "Sid", sid, ParameterType.QUERY); } + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/Task.java b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/Task.java index 5179bf0053..1a9aafd992 100644 --- a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/Task.java +++ b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/Task.java @@ -18,69 +18,97 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Task extends Resource { - private static final long serialVersionUID = 142315153829007L; - public static TaskCreator creator(final String pathWorkspaceSid) { - return new TaskCreator(pathWorkspaceSid); + public static TaskCreator creator(final String pathworkspaceSid) { + return new TaskCreator( + pathworkspaceSid + ); } - public static TaskDeleter deleter( - final String pathWorkspaceSid, - final String pathSid - ) { - return new TaskDeleter(pathWorkspaceSid, pathSid); + + public static TaskDeleter deleter(final String pathworkspaceSid, final String pathsid) { + return new TaskDeleter( + pathworkspaceSid, pathsid + ); } - public static TaskFetcher fetcher( - final String pathWorkspaceSid, - final String pathSid - ) { - return new TaskFetcher(pathWorkspaceSid, pathSid); + + public static TaskFetcher fetcher(final String pathworkspaceSid, final String pathsid) { + return new TaskFetcher( + pathworkspaceSid, pathsid + ); } - public static TaskReader reader(final String pathWorkspaceSid) { - return new TaskReader(pathWorkspaceSid); + + public static TaskReader reader(final String pathworkspaceSid) { + return new TaskReader( + pathworkspaceSid + ); } - public static TaskUpdater updater( - final String pathWorkspaceSid, - final String pathSid - ) { - return new TaskUpdater(pathWorkspaceSid, pathSid); + + public static TaskUpdater updater(final String pathworkspaceSid, final String pathsid) { + return new TaskUpdater( + pathworkspaceSid, pathsid + ); + } + + + public enum Status { + PENDING("pending"), + RESERVED("reserved"), + ASSIGNED("assigned"), + CANCELED("canceled"), + COMPLETED("completed"), + WRAPPING("wrapping"); + + private final String value; + + private Status(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static Status forValue(final String value) { + return Promoter.enumFromString(value, Status.values()); + } } + /** * Converts a JSON String into a Task object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Task object represented by the provided JSON */ - public static Task fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Task fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Task.class); @@ -95,14 +123,11 @@ public static Task fromJson( * Converts a JSON InputStream into a Task object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Task object represented by the provided JSON */ - public static Task fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Task fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Task.class); @@ -113,188 +138,123 @@ public static Task fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; + @Getter + private final String addons; + @Getter private final Integer age; + @Getter private final Task.Status assignmentStatus; + @Getter private final String attributes; - private final String addons; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; - private final ZonedDateTime taskQueueEnteredDate; + @Getter + private final Boolean ignoreCapacity; + @Getter + private final Map links; + @Getter private final Integer priority; + @Getter private final String reason; + @Getter + private final String routingTarget; + @Getter private final String sid; - private final String taskQueueSid; - private final String taskQueueFriendlyName; + @Getter private final String taskChannelSid; + @Getter private final String taskChannelUniqueName; + @Getter + private final ZonedDateTime taskQueueEnteredDate; + @Getter + private final String taskQueueFriendlyName; + @Getter + private final String taskQueueSid; + @Getter private final Integer timeout; - private final String workflowSid; - private final String workflowFriendlyName; - private final String workspaceSid; + @Getter private final URI url; - private final Map links; + @Getter private final ZonedDateTime virtualStartTime; - private final Boolean ignoreCapacity; - private final String routingTarget; + @Getter + private final String workflowFriendlyName; + @Getter + private final String workflowSid; + @Getter + private final String workspaceSid; @JsonCreator private Task( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("age") final Integer age, - @JsonProperty("assignment_status") final Task.Status assignmentStatus, - @JsonProperty("attributes") final String attributes, - @JsonProperty("addons") final String addons, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty( - "task_queue_entered_date" - ) final String taskQueueEnteredDate, - @JsonProperty("priority") final Integer priority, - @JsonProperty("reason") final String reason, - @JsonProperty("sid") final String sid, - @JsonProperty("task_queue_sid") final String taskQueueSid, - @JsonProperty( - "task_queue_friendly_name" - ) final String taskQueueFriendlyName, - @JsonProperty("task_channel_sid") final String taskChannelSid, - @JsonProperty( - "task_channel_unique_name" - ) final String taskChannelUniqueName, - @JsonProperty("timeout") final Integer timeout, - @JsonProperty("workflow_sid") final String workflowSid, - @JsonProperty( - "workflow_friendly_name" - ) final String workflowFriendlyName, - @JsonProperty("workspace_sid") final String workspaceSid, - @JsonProperty("url") final URI url, - @JsonProperty("links") final Map links, - @JsonProperty("virtual_start_time") final String virtualStartTime, - @JsonProperty("ignore_capacity") final Boolean ignoreCapacity, - @JsonProperty("routing_target") final String routingTarget + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("addons") final String addons, + @JsonProperty("age") final Integer age, + @JsonProperty("assignment_status") final Task.Status assignmentStatus, + @JsonProperty("attributes") final String attributes, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("ignore_capacity") final Boolean ignoreCapacity, + @JsonProperty("links") final Map links, + @JsonProperty("priority") final Integer priority, + @JsonProperty("reason") final String reason, + @JsonProperty("routing_target") final String routingTarget, + @JsonProperty("sid") final String sid, + @JsonProperty("task_channel_sid") final String taskChannelSid, + @JsonProperty("task_channel_unique_name") final String taskChannelUniqueName, + @JsonProperty("task_queue_entered_date") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime taskQueueEnteredDate, + @JsonProperty("task_queue_friendly_name") final String taskQueueFriendlyName, + @JsonProperty("task_queue_sid") final String taskQueueSid, + @JsonProperty("timeout") final Integer timeout, + @JsonProperty("url") final URI url, + @JsonProperty("virtual_start_time") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime virtualStartTime, + @JsonProperty("workflow_friendly_name") final String workflowFriendlyName, + @JsonProperty("workflow_sid") final String workflowSid, + @JsonProperty("workspace_sid") final String workspaceSid ) { this.accountSid = accountSid; + this.addons = addons; this.age = age; this.assignmentStatus = assignmentStatus; this.attributes = attributes; - this.addons = addons; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); - this.taskQueueEnteredDate = - DateConverter.iso8601DateTimeFromString(taskQueueEnteredDate); + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; + this.ignoreCapacity = ignoreCapacity; + this.links = links; this.priority = priority; this.reason = reason; + this.routingTarget = routingTarget; this.sid = sid; - this.taskQueueSid = taskQueueSid; - this.taskQueueFriendlyName = taskQueueFriendlyName; this.taskChannelSid = taskChannelSid; this.taskChannelUniqueName = taskChannelUniqueName; + this.taskQueueEnteredDate = taskQueueEnteredDate; + this.taskQueueFriendlyName = taskQueueFriendlyName; + this.taskQueueSid = taskQueueSid; this.timeout = timeout; - this.workflowSid = workflowSid; + this.url = url; + this.virtualStartTime = virtualStartTime; this.workflowFriendlyName = workflowFriendlyName; + this.workflowSid = workflowSid; this.workspaceSid = workspaceSid; - this.url = url; - this.links = links; - this.virtualStartTime = - DateConverter.iso8601DateTimeFromString(virtualStartTime); - this.ignoreCapacity = ignoreCapacity; - this.routingTarget = routingTarget; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final Integer getAge() { - return this.age; - } - - public final Task.Status getAssignmentStatus() { - return this.assignmentStatus; - } - - public final String getAttributes() { - return this.attributes; - } - - public final String getAddons() { - return this.addons; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final ZonedDateTime getTaskQueueEnteredDate() { - return this.taskQueueEnteredDate; - } - - public final Integer getPriority() { - return this.priority; - } - - public final String getReason() { - return this.reason; - } - - public final String getSid() { - return this.sid; - } - - public final String getTaskQueueSid() { - return this.taskQueueSid; - } - - public final String getTaskQueueFriendlyName() { - return this.taskQueueFriendlyName; - } - - public final String getTaskChannelSid() { - return this.taskChannelSid; - } - - public final String getTaskChannelUniqueName() { - return this.taskChannelUniqueName; - } - - public final Integer getTimeout() { - return this.timeout; - } - - public final String getWorkflowSid() { - return this.workflowSid; - } - - public final String getWorkflowFriendlyName() { - return this.workflowFriendlyName; - } - - public final String getWorkspaceSid() { - return this.workspaceSid; - } - - public final URI getUrl() { - return this.url; - } - - public final Map getLinks() { - return this.links; - } - - public final ZonedDateTime getVirtualStartTime() { - return this.virtualStartTime; - } - - public final Boolean getIgnoreCapacity() { - return this.ignoreCapacity; - } - - public final String getRoutingTarget() { - return this.routingTarget; } @Override @@ -308,92 +268,64 @@ public boolean equals(final Object o) { } Task other = (Task) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(age, other.age) && - Objects.equals(assignmentStatus, other.assignmentStatus) && - Objects.equals(attributes, other.attributes) && - Objects.equals(addons, other.addons) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(taskQueueEnteredDate, other.taskQueueEnteredDate) && - Objects.equals(priority, other.priority) && - Objects.equals(reason, other.reason) && - Objects.equals(sid, other.sid) && - Objects.equals(taskQueueSid, other.taskQueueSid) && - Objects.equals( - taskQueueFriendlyName, - other.taskQueueFriendlyName - ) && - Objects.equals(taskChannelSid, other.taskChannelSid) && - Objects.equals( - taskChannelUniqueName, - other.taskChannelUniqueName - ) && - Objects.equals(timeout, other.timeout) && - Objects.equals(workflowSid, other.workflowSid) && - Objects.equals(workflowFriendlyName, other.workflowFriendlyName) && - Objects.equals(workspaceSid, other.workspaceSid) && - Objects.equals(url, other.url) && - Objects.equals(links, other.links) && - Objects.equals(virtualStartTime, other.virtualStartTime) && - Objects.equals(ignoreCapacity, other.ignoreCapacity) && - Objects.equals(routingTarget, other.routingTarget) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(addons, other.addons) && + Objects.equals(age, other.age) && + Objects.equals(assignmentStatus, other.assignmentStatus) && + Objects.equals(attributes, other.attributes) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(ignoreCapacity, other.ignoreCapacity) && + Objects.equals(links, other.links) && + Objects.equals(priority, other.priority) && + Objects.equals(reason, other.reason) && + Objects.equals(routingTarget, other.routingTarget) && + Objects.equals(sid, other.sid) && + Objects.equals(taskChannelSid, other.taskChannelSid) && + Objects.equals(taskChannelUniqueName, other.taskChannelUniqueName) && + Objects.equals(taskQueueEnteredDate, other.taskQueueEnteredDate) && + Objects.equals(taskQueueFriendlyName, other.taskQueueFriendlyName) && + Objects.equals(taskQueueSid, other.taskQueueSid) && + Objects.equals(timeout, other.timeout) && + Objects.equals(url, other.url) && + Objects.equals(virtualStartTime, other.virtualStartTime) && + Objects.equals(workflowFriendlyName, other.workflowFriendlyName) && + Objects.equals(workflowSid, other.workflowSid) && + Objects.equals(workspaceSid, other.workspaceSid) ); } @Override public int hashCode() { return Objects.hash( - accountSid, - age, - assignmentStatus, - attributes, - addons, - dateCreated, - dateUpdated, - taskQueueEnteredDate, - priority, - reason, - sid, - taskQueueSid, - taskQueueFriendlyName, - taskChannelSid, - taskChannelUniqueName, - timeout, - workflowSid, - workflowFriendlyName, - workspaceSid, - url, - links, - virtualStartTime, - ignoreCapacity, - routingTarget + accountSid, + addons, + age, + assignmentStatus, + attributes, + dateCreated, + dateUpdated, + ignoreCapacity, + links, + priority, + reason, + routingTarget, + sid, + taskChannelSid, + taskChannelUniqueName, + taskQueueEnteredDate, + taskQueueFriendlyName, + taskQueueSid, + timeout, + url, + virtualStartTime, + workflowFriendlyName, + workflowSid, + workspaceSid ); } - public enum Status { - PENDING("pending"), - RESERVED("reserved"), - ASSIGNED("assigned"), - CANCELED("canceled"), - COMPLETED("completed"), - WRAPPING("wrapping"); - - private final String value; - - private Status(final String value) { - this.value = value; - } - public String toString() { - return value; - } - - @JsonCreator - public static Status forValue(final String value) { - return Promoter.enumFromString(value, Status.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/TaskChannel.java b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/TaskChannel.java index cc930c6237..61b6745401 100644 --- a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/TaskChannel.java +++ b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/TaskChannel.java @@ -18,76 +18,71 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class TaskChannel extends Resource { - private static final long serialVersionUID = 156990545444191L; - public static TaskChannelCreator creator( - final String pathWorkspaceSid, - final String friendlyName, - final String uniqueName - ) { + public static TaskChannelCreator creator(final String pathworkspaceSid, final String friendlyName, final String uniqueName) { return new TaskChannelCreator( - pathWorkspaceSid, - friendlyName, - uniqueName + pathworkspaceSid, friendlyName, uniqueName ); } - public static TaskChannelDeleter deleter( - final String pathWorkspaceSid, - final String pathSid - ) { - return new TaskChannelDeleter(pathWorkspaceSid, pathSid); + + public static TaskChannelDeleter deleter(final String pathworkspaceSid, final String pathsid) { + return new TaskChannelDeleter( + pathworkspaceSid, pathsid + ); } - public static TaskChannelFetcher fetcher( - final String pathWorkspaceSid, - final String pathSid - ) { - return new TaskChannelFetcher(pathWorkspaceSid, pathSid); + + public static TaskChannelFetcher fetcher(final String pathworkspaceSid, final String pathsid) { + return new TaskChannelFetcher( + pathworkspaceSid, pathsid + ); } - public static TaskChannelReader reader(final String pathWorkspaceSid) { - return new TaskChannelReader(pathWorkspaceSid); + + public static TaskChannelReader reader(final String pathworkspaceSid) { + return new TaskChannelReader( + pathworkspaceSid + ); } - public static TaskChannelUpdater updater( - final String pathWorkspaceSid, - final String pathSid - ) { - return new TaskChannelUpdater(pathWorkspaceSid, pathSid); + + public static TaskChannelUpdater updater(final String pathworkspaceSid, final String pathsid) { + return new TaskChannelUpdater( + pathworkspaceSid, pathsid + ); } + /** * Converts a JSON String into a TaskChannel object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return TaskChannel object represented by the provided JSON */ - public static TaskChannel fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static TaskChannel fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, TaskChannel.class); @@ -102,14 +97,11 @@ public static TaskChannel fromJson( * Converts a JSON InputStream into a TaskChannel object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return TaskChannel object represented by the provided JSON */ - public static TaskChannel fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static TaskChannel fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, TaskChannel.class); @@ -120,82 +112,65 @@ public static TaskChannel fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; + @Getter + private final Boolean channelOptimizedRouting; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; + @Getter private final String friendlyName; + @Getter + private final Map links; + @Getter private final String sid; + @Getter private final String uniqueName; - private final String workspaceSid; - private final Boolean channelOptimizedRouting; + @Getter private final URI url; - private final Map links; + @Getter + private final String workspaceSid; @JsonCreator private TaskChannel( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("sid") final String sid, - @JsonProperty("unique_name") final String uniqueName, - @JsonProperty("workspace_sid") final String workspaceSid, - @JsonProperty( - "channel_optimized_routing" - ) final Boolean channelOptimizedRouting, - @JsonProperty("url") final URI url, - @JsonProperty("links") final Map links + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("channel_optimized_routing") final Boolean channelOptimizedRouting, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("links") final Map links, + @JsonProperty("sid") final String sid, + @JsonProperty("unique_name") final String uniqueName, + @JsonProperty("url") final URI url, + @JsonProperty("workspace_sid") final String workspaceSid ) { this.accountSid = accountSid; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); + this.channelOptimizedRouting = channelOptimizedRouting; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.friendlyName = friendlyName; + this.links = links; this.sid = sid; this.uniqueName = uniqueName; - this.workspaceSid = workspaceSid; - this.channelOptimizedRouting = channelOptimizedRouting; this.url = url; - this.links = links; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final String getSid() { - return this.sid; - } - - public final String getUniqueName() { - return this.uniqueName; - } - - public final String getWorkspaceSid() { - return this.workspaceSid; - } - - public final Boolean getChannelOptimizedRouting() { - return this.channelOptimizedRouting; - } - - public final URI getUrl() { - return this.url; - } - - public final Map getLinks() { - return this.links; + this.workspaceSid = workspaceSid; } @Override @@ -209,37 +184,36 @@ public boolean equals(final Object o) { } TaskChannel other = (TaskChannel) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(sid, other.sid) && - Objects.equals(uniqueName, other.uniqueName) && - Objects.equals(workspaceSid, other.workspaceSid) && - Objects.equals( - channelOptimizedRouting, - other.channelOptimizedRouting - ) && - Objects.equals(url, other.url) && - Objects.equals(links, other.links) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(channelOptimizedRouting, other.channelOptimizedRouting) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(links, other.links) && + Objects.equals(sid, other.sid) && + Objects.equals(uniqueName, other.uniqueName) && + Objects.equals(url, other.url) && + Objects.equals(workspaceSid, other.workspaceSid) ); } @Override public int hashCode() { return Objects.hash( - accountSid, - dateCreated, - dateUpdated, - friendlyName, - sid, - uniqueName, - workspaceSid, - channelOptimizedRouting, - url, - links + accountSid, + channelOptimizedRouting, + dateCreated, + dateUpdated, + friendlyName, + links, + sid, + uniqueName, + url, + workspaceSid ); } + + } + diff --git a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/TaskChannelCreator.java b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/TaskChannelCreator.java index 9f5643aa4d..090e6a2f24 100644 --- a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/TaskChannelCreator.java +++ b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/TaskChannelCreator.java @@ -14,8 +14,11 @@ package com.twilio.rest.taskrouter.v1.workspace; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,99 +30,86 @@ public class TaskChannelCreator extends Creator { - private String pathWorkspaceSid; + private String pathworkspaceSid; private String friendlyName; private String uniqueName; private Boolean channelOptimizedRouting; - public TaskChannelCreator( - final String pathWorkspaceSid, - final String friendlyName, - final String uniqueName - ) { - this.pathWorkspaceSid = pathWorkspaceSid; + public TaskChannelCreator(final String pathworkspaceSid, final String friendlyName, final String uniqueName) { + this.pathworkspaceSid = pathworkspaceSid; this.friendlyName = friendlyName; this.uniqueName = uniqueName; } + public TaskChannelCreator setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + public TaskChannelCreator setUniqueName(final String uniqueName) { this.uniqueName = uniqueName; return this; } - public TaskChannelCreator setChannelOptimizedRouting( - final Boolean channelOptimizedRouting - ) { + + public TaskChannelCreator setChannelOptimizedRouting(final Boolean channelOptimizedRouting) { this.channelOptimizedRouting = channelOptimizedRouting; return this; } + @Override public TaskChannel create(final TwilioRestClient client) { + String path = "/v1/Workspaces/{WorkspaceSid}/TaskChannels"; - path = - path.replace( - "{" + "WorkspaceSid" + "}", - this.pathWorkspaceSid.toString() - ); - path = - path.replace( - "{" + "FriendlyName" + "}", - this.friendlyName.toString() - ); - path = - path.replace("{" + "UniqueName" + "}", this.uniqueName.toString()); + path = path.replace("{" + "WorkspaceSid" + "}", this.pathworkspaceSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.TASKROUTER.toString(), - path + HttpMethod.POST, + Domains.TASKROUTER.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "TaskChannel creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("TaskChannel creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return TaskChannel.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return TaskChannel.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + if (uniqueName != null) { - request.addPostParam("UniqueName", uniqueName); + Serializer.toString(request, "UniqueName", uniqueName, ParameterType.URLENCODED); } + + if (channelOptimizedRouting != null) { - request.addPostParam( - "ChannelOptimizedRouting", - channelOptimizedRouting.toString() - ); + Serializer.toString(request, "ChannelOptimizedRouting", channelOptimizedRouting, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/TaskChannelDeleter.java b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/TaskChannelDeleter.java index b03d3646dc..de81dc0e47 100644 --- a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/TaskChannelDeleter.java +++ b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/TaskChannelDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.taskrouter.v1.workspace; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,50 +26,41 @@ public class TaskChannelDeleter extends Deleter { - private String pathWorkspaceSid; - private String pathSid; + private String pathworkspaceSid; + private String pathsid; - public TaskChannelDeleter( - final String pathWorkspaceSid, - final String pathSid - ) { - this.pathWorkspaceSid = pathWorkspaceSid; - this.pathSid = pathSid; + public TaskChannelDeleter(final String pathworkspaceSid, final String pathsid) { + this.pathworkspaceSid = pathworkspaceSid; + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/v1/Workspaces/{WorkspaceSid}/TaskChannels/{Sid}"; - path = - path.replace( - "{" + "WorkspaceSid" + "}", - this.pathWorkspaceSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "WorkspaceSid" + "}", this.pathworkspaceSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.TASKROUTER.toString(), - path + HttpMethod.DELETE, + Domains.TASKROUTER.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "TaskChannel delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("TaskChannel delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/TaskChannelFetcher.java b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/TaskChannelFetcher.java index 9c8c0d7893..4fdc97481c 100644 --- a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/TaskChannelFetcher.java +++ b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/TaskChannelFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.taskrouter.v1.workspace; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,57 +26,44 @@ public class TaskChannelFetcher extends Fetcher { - private String pathWorkspaceSid; - private String pathSid; + private String pathworkspaceSid; + private String pathsid; - public TaskChannelFetcher( - final String pathWorkspaceSid, - final String pathSid - ) { - this.pathWorkspaceSid = pathWorkspaceSid; - this.pathSid = pathSid; + public TaskChannelFetcher(final String pathworkspaceSid, final String pathsid) { + this.pathworkspaceSid = pathworkspaceSid; + this.pathsid = pathsid; } + @Override public TaskChannel fetch(final TwilioRestClient client) { + String path = "/v1/Workspaces/{WorkspaceSid}/TaskChannels/{Sid}"; - path = - path.replace( - "{" + "WorkspaceSid" + "}", - this.pathWorkspaceSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "WorkspaceSid" + "}", this.pathworkspaceSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.TASKROUTER.toString(), - path + HttpMethod.GET, + Domains.TASKROUTER.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "TaskChannel fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("TaskChannel fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return TaskChannel.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return TaskChannel.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/TaskChannelReader.java b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/TaskChannelReader.java index ac5fd49988..6678d7d3dd 100644 --- a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/TaskChannelReader.java +++ b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/TaskChannelReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,115 +30,88 @@ public class TaskChannelReader extends Reader { - private String pathWorkspaceSid; + private String pathworkspaceSid; private Long pageSize; - public TaskChannelReader(final String pathWorkspaceSid) { - this.pathWorkspaceSid = pathWorkspaceSid; + public TaskChannelReader(final String pathworkspaceSid) { + this.pathworkspaceSid = pathworkspaceSid; } + public TaskChannelReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/Workspaces/{WorkspaceSid}/TaskChannels"; - path = - path.replace( - "{" + "WorkspaceSid" + "}", - this.pathWorkspaceSid.toString() - ); + + path = path.replace("{" + "WorkspaceSid" + "}", this.pathworkspaceSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.TASKROUTER.toString(), - path + HttpMethod.GET, + Domains.TASKROUTER.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "TaskChannel read failed: Unable to connect to server" - ); + throw new ApiConnectionException("TaskChannel read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "channels", - response.getContent(), - TaskChannel.class, - client.getObjectMapper() - ); + "channels", + response.getContent(), + TaskChannel.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.TASKROUTER.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.TASKROUTER.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/TaskChannelUpdater.java b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/TaskChannelUpdater.java index a1d8713c17..b89bab49ac 100644 --- a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/TaskChannelUpdater.java +++ b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/TaskChannelUpdater.java @@ -16,6 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -26,84 +28,75 @@ import com.twilio.rest.Domains; public class TaskChannelUpdater extends Updater { - - private String pathWorkspaceSid; - private String pathSid; + private String pathworkspaceSid; + private String pathsid; private String friendlyName; private Boolean channelOptimizedRouting; - public TaskChannelUpdater( - final String pathWorkspaceSid, - final String pathSid - ) { - this.pathWorkspaceSid = pathWorkspaceSid; - this.pathSid = pathSid; + public TaskChannelUpdater(final String pathworkspaceSid, final String pathsid) { + this.pathworkspaceSid = pathworkspaceSid; + this.pathsid = pathsid; } + public TaskChannelUpdater setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } - public TaskChannelUpdater setChannelOptimizedRouting( - final Boolean channelOptimizedRouting - ) { + + public TaskChannelUpdater setChannelOptimizedRouting(final Boolean channelOptimizedRouting) { this.channelOptimizedRouting = channelOptimizedRouting; return this; } + @Override public TaskChannel update(final TwilioRestClient client) { + String path = "/v1/Workspaces/{WorkspaceSid}/TaskChannels/{Sid}"; - path = - path.replace( - "{" + "WorkspaceSid" + "}", - this.pathWorkspaceSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "WorkspaceSid" + "}", this.pathworkspaceSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.TASKROUTER.toString(), - path + HttpMethod.POST, + Domains.TASKROUTER.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "TaskChannel update failed: Unable to connect to server" - ); + throw new ApiConnectionException("TaskChannel update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return TaskChannel.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return TaskChannel.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + if (channelOptimizedRouting != null) { - request.addPostParam( - "ChannelOptimizedRouting", - channelOptimizedRouting.toString() - ); + Serializer.toString(request, "ChannelOptimizedRouting", channelOptimizedRouting, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/TaskCreator.java b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/TaskCreator.java index 1b2a1608cd..3d238f1145 100644 --- a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/TaskCreator.java +++ b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/TaskCreator.java @@ -14,8 +14,11 @@ package com.twilio.rest.taskrouter.v1.workspace; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -24,11 +27,12 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.time.ZonedDateTime; public class TaskCreator extends Creator { - private String pathWorkspaceSid; + private String pathworkspaceSid; private Integer timeout; private Integer priority; private String taskChannel; @@ -39,89 +43,92 @@ public class TaskCreator extends Creator { private String ignoreCapacity; private String taskQueueSid; - public TaskCreator(final String pathWorkspaceSid) { - this.pathWorkspaceSid = pathWorkspaceSid; + public TaskCreator(final String pathworkspaceSid) { + this.pathworkspaceSid = pathworkspaceSid; } + public TaskCreator setTimeout(final Integer timeout) { this.timeout = timeout; return this; } + public TaskCreator setPriority(final Integer priority) { this.priority = priority; return this; } + public TaskCreator setTaskChannel(final String taskChannel) { this.taskChannel = taskChannel; return this; } + public TaskCreator setWorkflowSid(final String workflowSid) { this.workflowSid = workflowSid; return this; } + public TaskCreator setAttributes(final String attributes) { this.attributes = attributes; return this; } - public TaskCreator setVirtualStartTime( - final ZonedDateTime virtualStartTime - ) { + + public TaskCreator setVirtualStartTime(final ZonedDateTime virtualStartTime) { this.virtualStartTime = virtualStartTime; return this; } + public TaskCreator setRoutingTarget(final String routingTarget) { this.routingTarget = routingTarget; return this; } + public TaskCreator setIgnoreCapacity(final String ignoreCapacity) { this.ignoreCapacity = ignoreCapacity; return this; } + public TaskCreator setTaskQueueSid(final String taskQueueSid) { this.taskQueueSid = taskQueueSid; return this; } + @Override public Task create(final TwilioRestClient client) { + String path = "/v1/Workspaces/{WorkspaceSid}/Tasks"; - path = - path.replace( - "{" + "WorkspaceSid" + "}", - this.pathWorkspaceSid.toString() - ); + path = path.replace("{" + "WorkspaceSid" + "}", this.pathworkspaceSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.TASKROUTER.toString(), - path + HttpMethod.POST, + Domains.TASKROUTER.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Task creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("Task creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -130,35 +137,51 @@ public Task create(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (timeout != null) { - request.addPostParam("Timeout", timeout.toString()); + Serializer.toString(request, "Timeout", timeout, ParameterType.URLENCODED); } + + if (priority != null) { - request.addPostParam("Priority", priority.toString()); + Serializer.toString(request, "Priority", priority, ParameterType.URLENCODED); } + + if (taskChannel != null) { - request.addPostParam("TaskChannel", taskChannel); + Serializer.toString(request, "TaskChannel", taskChannel, ParameterType.URLENCODED); } + + if (workflowSid != null) { - request.addPostParam("WorkflowSid", workflowSid); + Serializer.toString(request, "WorkflowSid", workflowSid, ParameterType.URLENCODED); } + + if (attributes != null) { - request.addPostParam("Attributes", attributes); + Serializer.toString(request, "Attributes", attributes, ParameterType.URLENCODED); } + + if (virtualStartTime != null) { - request.addPostParam( - "VirtualStartTime", - virtualStartTime.toInstant().toString() - ); + Serializer.toString(request, "VirtualStartTime", virtualStartTime, ParameterType.URLENCODED); } + + if (routingTarget != null) { - request.addPostParam("RoutingTarget", routingTarget); + Serializer.toString(request, "RoutingTarget", routingTarget, ParameterType.URLENCODED); } + + if (ignoreCapacity != null) { - request.addPostParam("IgnoreCapacity", ignoreCapacity); + Serializer.toString(request, "IgnoreCapacity", ignoreCapacity, ParameterType.URLENCODED); } + + if (taskQueueSid != null) { - request.addPostParam("TaskQueueSid", taskQueueSid); + Serializer.toString(request, "TaskQueueSid", taskQueueSid, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/TaskDeleter.java b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/TaskDeleter.java index bf49c09075..509d2e6174 100644 --- a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/TaskDeleter.java +++ b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/TaskDeleter.java @@ -15,7 +15,8 @@ package com.twilio.rest.taskrouter.v1.workspace; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,54 +28,49 @@ public class TaskDeleter extends Deleter { - private String pathWorkspaceSid; - private String pathSid; + private String pathworkspaceSid; + private String pathsid; private String ifMatch; - public TaskDeleter(final String pathWorkspaceSid, final String pathSid) { - this.pathWorkspaceSid = pathWorkspaceSid; - this.pathSid = pathSid; + public TaskDeleter(final String pathworkspaceSid, final String pathsid) { + this.pathworkspaceSid = pathworkspaceSid; + this.pathsid = pathsid; } + public TaskDeleter setIfMatch(final String ifMatch) { this.ifMatch = ifMatch; return this; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/v1/Workspaces/{WorkspaceSid}/Tasks/{Sid}"; - path = - path.replace( - "{" + "WorkspaceSid" + "}", - this.pathWorkspaceSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "WorkspaceSid" + "}", this.pathworkspaceSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.TASKROUTER.toString(), - path + HttpMethod.DELETE, + Domains.TASKROUTER.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addHeaderParams(request); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Task delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("Task delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -82,8 +78,10 @@ public boolean delete(final TwilioRestClient client) { } private void addHeaderParams(final Request request) { + if (ifMatch != null) { - request.addHeaderParam("If-Match", ifMatch); + Serializer.toString(request, "If-Match", ifMatch, ParameterType.HEADER); } + } } diff --git a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/TaskFetcher.java b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/TaskFetcher.java index b4fa7a5828..47ade5ece6 100644 --- a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/TaskFetcher.java +++ b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/TaskFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.taskrouter.v1.workspace; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,51 +26,44 @@ public class TaskFetcher extends Fetcher { - private String pathWorkspaceSid; - private String pathSid; + private String pathworkspaceSid; + private String pathsid; - public TaskFetcher(final String pathWorkspaceSid, final String pathSid) { - this.pathWorkspaceSid = pathWorkspaceSid; - this.pathSid = pathSid; + public TaskFetcher(final String pathworkspaceSid, final String pathsid) { + this.pathworkspaceSid = pathworkspaceSid; + this.pathsid = pathsid; } + @Override public Task fetch(final TwilioRestClient client) { + String path = "/v1/Workspaces/{WorkspaceSid}/Tasks/{Sid}"; - path = - path.replace( - "{" + "WorkspaceSid" + "}", - this.pathWorkspaceSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "WorkspaceSid" + "}", this.pathworkspaceSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.TASKROUTER.toString(), - path + HttpMethod.GET, + Domains.TASKROUTER.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Task fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Task fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Task.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/TaskQueue.java b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/TaskQueue.java index 15f1dfabef..e060cd16b2 100644 --- a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/TaskQueue.java +++ b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/TaskQueue.java @@ -18,72 +18,93 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class TaskQueue extends Resource { - private static final long serialVersionUID = 234230912116687L; - public static TaskQueueCreator creator( - final String pathWorkspaceSid, - final String friendlyName - ) { - return new TaskQueueCreator(pathWorkspaceSid, friendlyName); + public static TaskQueueCreator creator(final String pathworkspaceSid, final String friendlyName) { + return new TaskQueueCreator( + pathworkspaceSid, friendlyName + ); } - public static TaskQueueDeleter deleter( - final String pathWorkspaceSid, - final String pathSid - ) { - return new TaskQueueDeleter(pathWorkspaceSid, pathSid); + + public static TaskQueueDeleter deleter(final String pathworkspaceSid, final String pathsid) { + return new TaskQueueDeleter( + pathworkspaceSid, pathsid + ); } - public static TaskQueueFetcher fetcher( - final String pathWorkspaceSid, - final String pathSid - ) { - return new TaskQueueFetcher(pathWorkspaceSid, pathSid); + + public static TaskQueueFetcher fetcher(final String pathworkspaceSid, final String pathsid) { + return new TaskQueueFetcher( + pathworkspaceSid, pathsid + ); } - public static TaskQueueReader reader(final String pathWorkspaceSid) { - return new TaskQueueReader(pathWorkspaceSid); + + public static TaskQueueReader reader(final String pathworkspaceSid) { + return new TaskQueueReader( + pathworkspaceSid + ); } - public static TaskQueueUpdater updater( - final String pathWorkspaceSid, - final String pathSid - ) { - return new TaskQueueUpdater(pathWorkspaceSid, pathSid); + + public static TaskQueueUpdater updater(final String pathworkspaceSid, final String pathsid) { + return new TaskQueueUpdater( + pathworkspaceSid, pathsid + ); } + + public enum TaskOrder { + FIFO("FIFO"), + LIFO("LIFO"); + + private final String value; + + private TaskOrder(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static TaskOrder forValue(final String value) { + return Promoter.enumFromString(value, TaskOrder.values()); + } + } + + /** * Converts a JSON String into a TaskQueue object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return TaskQueue object represented by the provided JSON */ - public static TaskQueue fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static TaskQueue fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, TaskQueue.class); @@ -98,14 +119,11 @@ public static TaskQueue fromJson( * Converts a JSON InputStream into a TaskQueue object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return TaskQueue object represented by the provided JSON */ - public static TaskQueue fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static TaskQueue fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, TaskQueue.class); @@ -116,123 +134,85 @@ public static TaskQueue fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String assignmentActivitySid; + @Getter private final String assignmentActivityName; + @Getter + private final String assignmentActivitySid; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; + @Getter private final String friendlyName; + @Getter + private final Map links; + @Getter private final Integer maxReservedWorkers; - private final String reservationActivitySid; + @Getter private final String reservationActivityName; + @Getter + private final String reservationActivitySid; + @Getter private final String sid; + @Getter private final String targetWorkers; + @Getter private final TaskQueue.TaskOrder taskOrder; + @Getter private final URI url; + @Getter private final String workspaceSid; - private final Map links; @JsonCreator private TaskQueue( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty( - "assignment_activity_sid" - ) final String assignmentActivitySid, - @JsonProperty( - "assignment_activity_name" - ) final String assignmentActivityName, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("max_reserved_workers") final Integer maxReservedWorkers, - @JsonProperty( - "reservation_activity_sid" - ) final String reservationActivitySid, - @JsonProperty( - "reservation_activity_name" - ) final String reservationActivityName, - @JsonProperty("sid") final String sid, - @JsonProperty("target_workers") final String targetWorkers, - @JsonProperty("task_order") final TaskQueue.TaskOrder taskOrder, - @JsonProperty("url") final URI url, - @JsonProperty("workspace_sid") final String workspaceSid, - @JsonProperty("links") final Map links + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("assignment_activity_name") final String assignmentActivityName, + @JsonProperty("assignment_activity_sid") final String assignmentActivitySid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("links") final Map links, + @JsonProperty("max_reserved_workers") final Integer maxReservedWorkers, + @JsonProperty("reservation_activity_name") final String reservationActivityName, + @JsonProperty("reservation_activity_sid") final String reservationActivitySid, + @JsonProperty("sid") final String sid, + @JsonProperty("target_workers") final String targetWorkers, + @JsonProperty("task_order") final TaskQueue.TaskOrder taskOrder, + @JsonProperty("url") final URI url, + @JsonProperty("workspace_sid") final String workspaceSid ) { this.accountSid = accountSid; - this.assignmentActivitySid = assignmentActivitySid; this.assignmentActivityName = assignmentActivityName; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); + this.assignmentActivitySid = assignmentActivitySid; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.friendlyName = friendlyName; + this.links = links; this.maxReservedWorkers = maxReservedWorkers; - this.reservationActivitySid = reservationActivitySid; this.reservationActivityName = reservationActivityName; + this.reservationActivitySid = reservationActivitySid; this.sid = sid; this.targetWorkers = targetWorkers; this.taskOrder = taskOrder; this.url = url; this.workspaceSid = workspaceSid; - this.links = links; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getAssignmentActivitySid() { - return this.assignmentActivitySid; - } - - public final String getAssignmentActivityName() { - return this.assignmentActivityName; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final Integer getMaxReservedWorkers() { - return this.maxReservedWorkers; - } - - public final String getReservationActivitySid() { - return this.reservationActivitySid; - } - - public final String getReservationActivityName() { - return this.reservationActivityName; - } - - public final String getSid() { - return this.sid; - } - - public final String getTargetWorkers() { - return this.targetWorkers; - } - - public final TaskQueue.TaskOrder getTaskOrder() { - return this.taskOrder; - } - - public final URI getUrl() { - return this.url; - } - - public final String getWorkspaceSid() { - return this.workspaceSid; - } - - public final Map getLinks() { - return this.links; } @Override @@ -246,76 +226,46 @@ public boolean equals(final Object o) { } TaskQueue other = (TaskQueue) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals( - assignmentActivitySid, - other.assignmentActivitySid - ) && - Objects.equals( - assignmentActivityName, - other.assignmentActivityName - ) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(maxReservedWorkers, other.maxReservedWorkers) && - Objects.equals( - reservationActivitySid, - other.reservationActivitySid - ) && - Objects.equals( - reservationActivityName, - other.reservationActivityName - ) && - Objects.equals(sid, other.sid) && - Objects.equals(targetWorkers, other.targetWorkers) && - Objects.equals(taskOrder, other.taskOrder) && - Objects.equals(url, other.url) && - Objects.equals(workspaceSid, other.workspaceSid) && - Objects.equals(links, other.links) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(assignmentActivityName, other.assignmentActivityName) && + Objects.equals(assignmentActivitySid, other.assignmentActivitySid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(links, other.links) && + Objects.equals(maxReservedWorkers, other.maxReservedWorkers) && + Objects.equals(reservationActivityName, other.reservationActivityName) && + Objects.equals(reservationActivitySid, other.reservationActivitySid) && + Objects.equals(sid, other.sid) && + Objects.equals(targetWorkers, other.targetWorkers) && + Objects.equals(taskOrder, other.taskOrder) && + Objects.equals(url, other.url) && + Objects.equals(workspaceSid, other.workspaceSid) ); } @Override public int hashCode() { return Objects.hash( - accountSid, - assignmentActivitySid, - assignmentActivityName, - dateCreated, - dateUpdated, - friendlyName, - maxReservedWorkers, - reservationActivitySid, - reservationActivityName, - sid, - targetWorkers, - taskOrder, - url, - workspaceSid, - links + accountSid, + assignmentActivityName, + assignmentActivitySid, + dateCreated, + dateUpdated, + friendlyName, + links, + maxReservedWorkers, + reservationActivityName, + reservationActivitySid, + sid, + targetWorkers, + taskOrder, + url, + workspaceSid ); } - public enum TaskOrder { - FIFO("FIFO"), - LIFO("LIFO"); - - private final String value; - - private TaskOrder(final String value) { - this.value = value; - } - public String toString() { - return value; - } - - @JsonCreator - public static TaskOrder forValue(final String value) { - return Promoter.enumFromString(value, TaskOrder.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/TaskQueueCreator.java b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/TaskQueueCreator.java index 290fa1fb55..64f6afc381 100644 --- a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/TaskQueueCreator.java +++ b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/TaskQueueCreator.java @@ -14,8 +14,11 @@ package com.twilio.rest.taskrouter.v1.workspace; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,7 +30,7 @@ public class TaskQueueCreator extends Creator { - private String pathWorkspaceSid; + private String pathworkspaceSid; private String friendlyName; private String targetWorkers; private Integer maxReservedWorkers; @@ -35,124 +38,113 @@ public class TaskQueueCreator extends Creator { private String reservationActivitySid; private String assignmentActivitySid; - public TaskQueueCreator( - final String pathWorkspaceSid, - final String friendlyName - ) { - this.pathWorkspaceSid = pathWorkspaceSid; + public TaskQueueCreator(final String pathworkspaceSid, final String friendlyName) { + this.pathworkspaceSid = pathworkspaceSid; this.friendlyName = friendlyName; } + public TaskQueueCreator setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + public TaskQueueCreator setTargetWorkers(final String targetWorkers) { this.targetWorkers = targetWorkers; return this; } - public TaskQueueCreator setMaxReservedWorkers( - final Integer maxReservedWorkers - ) { + + public TaskQueueCreator setMaxReservedWorkers(final Integer maxReservedWorkers) { this.maxReservedWorkers = maxReservedWorkers; return this; } + public TaskQueueCreator setTaskOrder(final TaskQueue.TaskOrder taskOrder) { this.taskOrder = taskOrder; return this; } - public TaskQueueCreator setReservationActivitySid( - final String reservationActivitySid - ) { + + public TaskQueueCreator setReservationActivitySid(final String reservationActivitySid) { this.reservationActivitySid = reservationActivitySid; return this; } - public TaskQueueCreator setAssignmentActivitySid( - final String assignmentActivitySid - ) { + + public TaskQueueCreator setAssignmentActivitySid(final String assignmentActivitySid) { this.assignmentActivitySid = assignmentActivitySid; return this; } + @Override public TaskQueue create(final TwilioRestClient client) { + String path = "/v1/Workspaces/{WorkspaceSid}/TaskQueues"; - path = - path.replace( - "{" + "WorkspaceSid" + "}", - this.pathWorkspaceSid.toString() - ); - path = - path.replace( - "{" + "FriendlyName" + "}", - this.friendlyName.toString() - ); + path = path.replace("{" + "WorkspaceSid" + "}", this.pathworkspaceSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.TASKROUTER.toString(), - path + HttpMethod.POST, + Domains.TASKROUTER.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "TaskQueue creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("TaskQueue creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return TaskQueue.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return TaskQueue.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + if (targetWorkers != null) { - request.addPostParam("TargetWorkers", targetWorkers); + Serializer.toString(request, "TargetWorkers", targetWorkers, ParameterType.URLENCODED); } + + if (maxReservedWorkers != null) { - request.addPostParam( - "MaxReservedWorkers", - maxReservedWorkers.toString() - ); + Serializer.toString(request, "MaxReservedWorkers", maxReservedWorkers, ParameterType.URLENCODED); } + + if (taskOrder != null) { - request.addPostParam("TaskOrder", taskOrder.toString()); + Serializer.toString(request, "TaskOrder", taskOrder, ParameterType.URLENCODED); } + + if (reservationActivitySid != null) { - request.addPostParam( - "ReservationActivitySid", - reservationActivitySid - ); + Serializer.toString(request, "ReservationActivitySid", reservationActivitySid, ParameterType.URLENCODED); } + + if (assignmentActivitySid != null) { - request.addPostParam( - "AssignmentActivitySid", - assignmentActivitySid - ); + Serializer.toString(request, "AssignmentActivitySid", assignmentActivitySid, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/TaskQueueDeleter.java b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/TaskQueueDeleter.java index 38029947fd..75411a5646 100644 --- a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/TaskQueueDeleter.java +++ b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/TaskQueueDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.taskrouter.v1.workspace; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,50 +26,41 @@ public class TaskQueueDeleter extends Deleter { - private String pathWorkspaceSid; - private String pathSid; + private String pathworkspaceSid; + private String pathsid; - public TaskQueueDeleter( - final String pathWorkspaceSid, - final String pathSid - ) { - this.pathWorkspaceSid = pathWorkspaceSid; - this.pathSid = pathSid; + public TaskQueueDeleter(final String pathworkspaceSid, final String pathsid) { + this.pathworkspaceSid = pathworkspaceSid; + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/v1/Workspaces/{WorkspaceSid}/TaskQueues/{Sid}"; - path = - path.replace( - "{" + "WorkspaceSid" + "}", - this.pathWorkspaceSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "WorkspaceSid" + "}", this.pathworkspaceSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.TASKROUTER.toString(), - path + HttpMethod.DELETE, + Domains.TASKROUTER.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "TaskQueue delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("TaskQueue delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/TaskQueueFetcher.java b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/TaskQueueFetcher.java index ed266dace2..54bd9a7334 100644 --- a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/TaskQueueFetcher.java +++ b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/TaskQueueFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.taskrouter.v1.workspace; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,57 +26,44 @@ public class TaskQueueFetcher extends Fetcher { - private String pathWorkspaceSid; - private String pathSid; + private String pathworkspaceSid; + private String pathsid; - public TaskQueueFetcher( - final String pathWorkspaceSid, - final String pathSid - ) { - this.pathWorkspaceSid = pathWorkspaceSid; - this.pathSid = pathSid; + public TaskQueueFetcher(final String pathworkspaceSid, final String pathsid) { + this.pathworkspaceSid = pathworkspaceSid; + this.pathsid = pathsid; } + @Override public TaskQueue fetch(final TwilioRestClient client) { + String path = "/v1/Workspaces/{WorkspaceSid}/TaskQueues/{Sid}"; - path = - path.replace( - "{" + "WorkspaceSid" + "}", - this.pathWorkspaceSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "WorkspaceSid" + "}", this.pathworkspaceSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.TASKROUTER.toString(), - path + HttpMethod.GET, + Domains.TASKROUTER.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "TaskQueue fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("TaskQueue fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return TaskQueue.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return TaskQueue.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/TaskQueueReader.java b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/TaskQueueReader.java index 818c9d595e..4fb95c4dde 100644 --- a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/TaskQueueReader.java +++ b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/TaskQueueReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,156 +30,136 @@ public class TaskQueueReader extends Reader { - private String pathWorkspaceSid; + private String pathworkspaceSid; private String friendlyName; private String evaluateWorkerAttributes; private String workerSid; private String ordering; private Long pageSize; - public TaskQueueReader(final String pathWorkspaceSid) { - this.pathWorkspaceSid = pathWorkspaceSid; + public TaskQueueReader(final String pathworkspaceSid) { + this.pathworkspaceSid = pathworkspaceSid; } + public TaskQueueReader setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } - public TaskQueueReader setEvaluateWorkerAttributes( - final String evaluateWorkerAttributes - ) { + + public TaskQueueReader setEvaluateWorkerAttributes(final String evaluateWorkerAttributes) { this.evaluateWorkerAttributes = evaluateWorkerAttributes; return this; } + public TaskQueueReader setWorkerSid(final String workerSid) { this.workerSid = workerSid; return this; } + public TaskQueueReader setOrdering(final String ordering) { this.ordering = ordering; return this; } + public TaskQueueReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/Workspaces/{WorkspaceSid}/TaskQueues"; - path = - path.replace( - "{" + "WorkspaceSid" + "}", - this.pathWorkspaceSid.toString() - ); + + path = path.replace("{" + "WorkspaceSid" + "}", this.pathworkspaceSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.TASKROUTER.toString(), - path + HttpMethod.GET, + Domains.TASKROUTER.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "TaskQueue read failed: Unable to connect to server" - ); + throw new ApiConnectionException("TaskQueue read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "task_queues", - response.getContent(), - TaskQueue.class, - client.getObjectMapper() - ); + "task_queues", + response.getContent(), + TaskQueue.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.TASKROUTER.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.TASKROUTER.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (friendlyName != null) { - request.addQueryParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.QUERY); } + + if (evaluateWorkerAttributes != null) { - request.addQueryParam( - "EvaluateWorkerAttributes", - evaluateWorkerAttributes - ); + Serializer.toString(request, "EvaluateWorkerAttributes", evaluateWorkerAttributes, ParameterType.QUERY); } + + if (workerSid != null) { - request.addQueryParam("WorkerSid", workerSid); + Serializer.toString(request, "WorkerSid", workerSid, ParameterType.QUERY); } + + if (ordering != null) { - request.addQueryParam("Ordering", ordering); + Serializer.toString(request, "Ordering", ordering, ParameterType.QUERY); } + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/TaskQueueUpdater.java b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/TaskQueueUpdater.java index 13dd1cec8a..49dce60ead 100644 --- a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/TaskQueueUpdater.java +++ b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/TaskQueueUpdater.java @@ -16,6 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -26,9 +28,8 @@ import com.twilio.rest.Domains; public class TaskQueueUpdater extends Updater { - - private String pathWorkspaceSid; - private String pathSid; + private String pathworkspaceSid; + private String pathsid; private String friendlyName; private String targetWorkers; private String reservationActivitySid; @@ -36,120 +37,114 @@ public class TaskQueueUpdater extends Updater { private Integer maxReservedWorkers; private TaskQueue.TaskOrder taskOrder; - public TaskQueueUpdater( - final String pathWorkspaceSid, - final String pathSid - ) { - this.pathWorkspaceSid = pathWorkspaceSid; - this.pathSid = pathSid; + public TaskQueueUpdater(final String pathworkspaceSid, final String pathsid) { + this.pathworkspaceSid = pathworkspaceSid; + this.pathsid = pathsid; } + public TaskQueueUpdater setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + public TaskQueueUpdater setTargetWorkers(final String targetWorkers) { this.targetWorkers = targetWorkers; return this; } - public TaskQueueUpdater setReservationActivitySid( - final String reservationActivitySid - ) { + + public TaskQueueUpdater setReservationActivitySid(final String reservationActivitySid) { this.reservationActivitySid = reservationActivitySid; return this; } - public TaskQueueUpdater setAssignmentActivitySid( - final String assignmentActivitySid - ) { + + public TaskQueueUpdater setAssignmentActivitySid(final String assignmentActivitySid) { this.assignmentActivitySid = assignmentActivitySid; return this; } - public TaskQueueUpdater setMaxReservedWorkers( - final Integer maxReservedWorkers - ) { + + public TaskQueueUpdater setMaxReservedWorkers(final Integer maxReservedWorkers) { this.maxReservedWorkers = maxReservedWorkers; return this; } + public TaskQueueUpdater setTaskOrder(final TaskQueue.TaskOrder taskOrder) { this.taskOrder = taskOrder; return this; } + @Override public TaskQueue update(final TwilioRestClient client) { + String path = "/v1/Workspaces/{WorkspaceSid}/TaskQueues/{Sid}"; - path = - path.replace( - "{" + "WorkspaceSid" + "}", - this.pathWorkspaceSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "WorkspaceSid" + "}", this.pathworkspaceSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.TASKROUTER.toString(), - path + HttpMethod.POST, + Domains.TASKROUTER.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "TaskQueue update failed: Unable to connect to server" - ); + throw new ApiConnectionException("TaskQueue update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return TaskQueue.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return TaskQueue.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + if (targetWorkers != null) { - request.addPostParam("TargetWorkers", targetWorkers); + Serializer.toString(request, "TargetWorkers", targetWorkers, ParameterType.URLENCODED); } + + if (reservationActivitySid != null) { - request.addPostParam( - "ReservationActivitySid", - reservationActivitySid - ); + Serializer.toString(request, "ReservationActivitySid", reservationActivitySid, ParameterType.URLENCODED); } + + if (assignmentActivitySid != null) { - request.addPostParam( - "AssignmentActivitySid", - assignmentActivitySid - ); + Serializer.toString(request, "AssignmentActivitySid", assignmentActivitySid, ParameterType.URLENCODED); } + + if (maxReservedWorkers != null) { - request.addPostParam( - "MaxReservedWorkers", - maxReservedWorkers.toString() - ); + Serializer.toString(request, "MaxReservedWorkers", maxReservedWorkers, ParameterType.URLENCODED); } + + if (taskOrder != null) { - request.addPostParam("TaskOrder", taskOrder.toString()); + Serializer.toString(request, "TaskOrder", taskOrder, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/TaskReader.java b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/TaskReader.java index 7ce9ca723a..b689e041e0 100644 --- a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/TaskReader.java +++ b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/TaskReader.java @@ -17,8 +17,9 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; import com.twilio.converter.Promoter; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,11 +28,12 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.util.List; public class TaskReader extends Reader { - private String pathWorkspaceSid; + private String pathworkspaceSid; private Integer priority; private List assignmentStatus; private String workflowSid; @@ -44,15 +46,17 @@ public class TaskReader extends Reader { private Boolean hasAddons; private Long pageSize; - public TaskReader(final String pathWorkspaceSid) { - this.pathWorkspaceSid = pathWorkspaceSid; + public TaskReader(final String pathworkspaceSid) { + this.pathworkspaceSid = pathworkspaceSid; } + public TaskReader setPriority(final Integer priority) { this.priority = priority; return this; } + public TaskReader setAssignmentStatus(final List assignmentStatus) { this.assignmentStatus = assignmentStatus; return this; @@ -67,180 +71,175 @@ public TaskReader setWorkflowSid(final String workflowSid) { return this; } + public TaskReader setWorkflowName(final String workflowName) { this.workflowName = workflowName; return this; } + public TaskReader setTaskQueueSid(final String taskQueueSid) { this.taskQueueSid = taskQueueSid; return this; } + public TaskReader setTaskQueueName(final String taskQueueName) { this.taskQueueName = taskQueueName; return this; } - public TaskReader setEvaluateTaskAttributes( - final String evaluateTaskAttributes - ) { + + public TaskReader setEvaluateTaskAttributes(final String evaluateTaskAttributes) { this.evaluateTaskAttributes = evaluateTaskAttributes; return this; } + public TaskReader setRoutingTarget(final String routingTarget) { this.routingTarget = routingTarget; return this; } + public TaskReader setOrdering(final String ordering) { this.ordering = ordering; return this; } + public TaskReader setHasAddons(final Boolean hasAddons) { this.hasAddons = hasAddons; return this; } + public TaskReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/Workspaces/{WorkspaceSid}/Tasks"; - path = - path.replace( - "{" + "WorkspaceSid" + "}", - this.pathWorkspaceSid.toString() - ); + + path = path.replace("{" + "WorkspaceSid" + "}", this.pathworkspaceSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.TASKROUTER.toString(), - path + HttpMethod.GET, + Domains.TASKROUTER.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Task read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Task read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "tasks", - response.getContent(), - Task.class, - client.getObjectMapper() - ); + "tasks", + response.getContent(), + Task.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.TASKROUTER.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.TASKROUTER.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (priority != null) { - request.addQueryParam("Priority", priority.toString()); + Serializer.toString(request, "Priority", priority, ParameterType.QUERY); } + + if (assignmentStatus != null) { - for (String prop : assignmentStatus) { - request.addQueryParam("AssignmentStatus", prop); + for (String param : assignmentStatus) { + Serializer.toString(request, "AssignmentStatus", param, ParameterType.QUERY); } } + + if (workflowSid != null) { - request.addQueryParam("WorkflowSid", workflowSid); + Serializer.toString(request, "WorkflowSid", workflowSid, ParameterType.QUERY); } + + if (workflowName != null) { - request.addQueryParam("WorkflowName", workflowName); + Serializer.toString(request, "WorkflowName", workflowName, ParameterType.QUERY); } + + if (taskQueueSid != null) { - request.addQueryParam("TaskQueueSid", taskQueueSid); + Serializer.toString(request, "TaskQueueSid", taskQueueSid, ParameterType.QUERY); } + + if (taskQueueName != null) { - request.addQueryParam("TaskQueueName", taskQueueName); + Serializer.toString(request, "TaskQueueName", taskQueueName, ParameterType.QUERY); } + + if (evaluateTaskAttributes != null) { - request.addQueryParam( - "EvaluateTaskAttributes", - evaluateTaskAttributes - ); + Serializer.toString(request, "EvaluateTaskAttributes", evaluateTaskAttributes, ParameterType.QUERY); } + + if (routingTarget != null) { - request.addQueryParam("RoutingTarget", routingTarget); + Serializer.toString(request, "RoutingTarget", routingTarget, ParameterType.QUERY); } + + if (ordering != null) { - request.addQueryParam("Ordering", ordering); + Serializer.toString(request, "Ordering", ordering, ParameterType.QUERY); } + + if (hasAddons != null) { - request.addQueryParam("HasAddons", hasAddons.toString()); + Serializer.toString(request, "HasAddons", hasAddons, ParameterType.QUERY); } + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/TaskUpdater.java b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/TaskUpdater.java index 8f7fbbb812..8b85cd49f4 100644 --- a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/TaskUpdater.java +++ b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/TaskUpdater.java @@ -16,6 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -24,12 +26,12 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.time.ZonedDateTime; public class TaskUpdater extends Updater { - - private String pathWorkspaceSid; - private String pathSid; + private String pathworkspaceSid; + private String pathsid; private String ifMatch; private String attributes; private Task.Status assignmentStatus; @@ -38,82 +40,83 @@ public class TaskUpdater extends Updater { private String taskChannel; private ZonedDateTime virtualStartTime; - public TaskUpdater(final String pathWorkspaceSid, final String pathSid) { - this.pathWorkspaceSid = pathWorkspaceSid; - this.pathSid = pathSid; + public TaskUpdater(final String pathworkspaceSid, final String pathsid) { + this.pathworkspaceSid = pathworkspaceSid; + this.pathsid = pathsid; } - public TaskUpdater setIfMatch(final String ifMatch) { - this.ifMatch = ifMatch; - return this; - } public TaskUpdater setAttributes(final String attributes) { this.attributes = attributes; return this; } + public TaskUpdater setAssignmentStatus(final Task.Status assignmentStatus) { this.assignmentStatus = assignmentStatus; return this; } + public TaskUpdater setReason(final String reason) { this.reason = reason; return this; } + public TaskUpdater setPriority(final Integer priority) { this.priority = priority; return this; } + public TaskUpdater setTaskChannel(final String taskChannel) { this.taskChannel = taskChannel; return this; } - public TaskUpdater setVirtualStartTime( - final ZonedDateTime virtualStartTime - ) { + + public TaskUpdater setVirtualStartTime(final ZonedDateTime virtualStartTime) { this.virtualStartTime = virtualStartTime; return this; } + + public TaskUpdater setIfMatch(final String ifMatch) { + this.ifMatch = ifMatch; + return this; + } + + @Override public Task update(final TwilioRestClient client) { + String path = "/v1/Workspaces/{WorkspaceSid}/Tasks/{Sid}"; - path = - path.replace( - "{" + "WorkspaceSid" + "}", - this.pathWorkspaceSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "WorkspaceSid" + "}", this.pathworkspaceSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.TASKROUTER.toString(), - path + HttpMethod.POST, + Domains.TASKROUTER.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); - addPostParams(request); addHeaderParams(request); + addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Task update failed: Unable to connect to server" - ); + throw new ApiConnectionException("Task update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -122,35 +125,44 @@ public Task update(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (attributes != null) { - request.addPostParam("Attributes", attributes); + Serializer.toString(request, "Attributes", attributes, ParameterType.URLENCODED); } + + if (assignmentStatus != null) { - request.addPostParam( - "AssignmentStatus", - assignmentStatus.toString() - ); + Serializer.toString(request, "AssignmentStatus", assignmentStatus, ParameterType.URLENCODED); } + + if (reason != null) { - request.addPostParam("Reason", reason); + Serializer.toString(request, "Reason", reason, ParameterType.URLENCODED); } + + if (priority != null) { - request.addPostParam("Priority", priority.toString()); + Serializer.toString(request, "Priority", priority, ParameterType.URLENCODED); } + + if (taskChannel != null) { - request.addPostParam("TaskChannel", taskChannel); + Serializer.toString(request, "TaskChannel", taskChannel, ParameterType.URLENCODED); } + + if (virtualStartTime != null) { - request.addPostParam( - "VirtualStartTime", - virtualStartTime.toInstant().toString() - ); + Serializer.toString(request, "VirtualStartTime", virtualStartTime, ParameterType.URLENCODED); } + + } private void addHeaderParams(final Request request) { + if (ifMatch != null) { - request.addHeaderParam("If-Match", ifMatch); + Serializer.toString(request, "If-Match", ifMatch, ParameterType.HEADER); } + } } diff --git a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/Worker.java b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/Worker.java index 9c7b7cfee7..ccbf1c96dc 100644 --- a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/Worker.java +++ b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/Worker.java @@ -18,71 +18,71 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Worker extends Resource { - private static final long serialVersionUID = 110824061154379L; - public static WorkerCreator creator( - final String pathWorkspaceSid, - final String friendlyName - ) { - return new WorkerCreator(pathWorkspaceSid, friendlyName); + public static WorkerCreator creator(final String pathworkspaceSid, final String friendlyName) { + return new WorkerCreator( + pathworkspaceSid, friendlyName + ); } - public static WorkerDeleter deleter( - final String pathWorkspaceSid, - final String pathSid - ) { - return new WorkerDeleter(pathWorkspaceSid, pathSid); + + public static WorkerDeleter deleter(final String pathworkspaceSid, final String pathsid) { + return new WorkerDeleter( + pathworkspaceSid, pathsid + ); } - public static WorkerFetcher fetcher( - final String pathWorkspaceSid, - final String pathSid - ) { - return new WorkerFetcher(pathWorkspaceSid, pathSid); + + public static WorkerFetcher fetcher(final String pathworkspaceSid, final String pathsid) { + return new WorkerFetcher( + pathworkspaceSid, pathsid + ); } - public static WorkerReader reader(final String pathWorkspaceSid) { - return new WorkerReader(pathWorkspaceSid); + + public static WorkerReader reader(final String pathworkspaceSid) { + return new WorkerReader( + pathworkspaceSid + ); } - public static WorkerUpdater updater( - final String pathWorkspaceSid, - final String pathSid - ) { - return new WorkerUpdater(pathWorkspaceSid, pathSid); + + public static WorkerUpdater updater(final String pathworkspaceSid, final String pathsid) { + return new WorkerUpdater( + pathworkspaceSid, pathsid + ); } + /** * Converts a JSON String into a Worker object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Worker object represented by the provided JSON */ - public static Worker fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Worker fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Worker.class); @@ -97,14 +97,11 @@ public static Worker fromJson( * Converts a JSON InputStream into a Worker object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Worker object represented by the provided JSON */ - public static Worker fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Worker fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Worker.class); @@ -115,102 +112,78 @@ public static Worker fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; + @Getter private final String activityName; + @Getter private final String activitySid; + @Getter private final String attributes; + @Getter private final Boolean available; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateStatusChanged; + @Getter private final ZonedDateTime dateUpdated; + @Getter private final String friendlyName; + @Getter + private final Map links; + @Getter private final String sid; - private final String workspaceSid; + @Getter private final URI url; - private final Map links; + @Getter + private final String workspaceSid; @JsonCreator private Worker( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("activity_name") final String activityName, - @JsonProperty("activity_sid") final String activitySid, - @JsonProperty("attributes") final String attributes, - @JsonProperty("available") final Boolean available, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_status_changed") final String dateStatusChanged, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("sid") final String sid, - @JsonProperty("workspace_sid") final String workspaceSid, - @JsonProperty("url") final URI url, - @JsonProperty("links") final Map links + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("activity_name") final String activityName, + @JsonProperty("activity_sid") final String activitySid, + @JsonProperty("attributes") final String attributes, + @JsonProperty("available") final Boolean available, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_status_changed") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateStatusChanged, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("links") final Map links, + @JsonProperty("sid") final String sid, + @JsonProperty("url") final URI url, + @JsonProperty("workspace_sid") final String workspaceSid ) { this.accountSid = accountSid; this.activityName = activityName; this.activitySid = activitySid; this.attributes = attributes; this.available = available; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateStatusChanged = - DateConverter.iso8601DateTimeFromString(dateStatusChanged); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); + this.dateCreated = dateCreated; + this.dateStatusChanged = dateStatusChanged; + this.dateUpdated = dateUpdated; this.friendlyName = friendlyName; + this.links = links; this.sid = sid; - this.workspaceSid = workspaceSid; this.url = url; - this.links = links; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getActivityName() { - return this.activityName; - } - - public final String getActivitySid() { - return this.activitySid; - } - - public final String getAttributes() { - return this.attributes; - } - - public final Boolean getAvailable() { - return this.available; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateStatusChanged() { - return this.dateStatusChanged; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final String getSid() { - return this.sid; - } - - public final String getWorkspaceSid() { - return this.workspaceSid; - } - - public final URI getUrl() { - return this.url; - } - - public final Map getLinks() { - return this.links; + this.workspaceSid = workspaceSid; } @Override @@ -224,40 +197,42 @@ public boolean equals(final Object o) { } Worker other = (Worker) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(activityName, other.activityName) && - Objects.equals(activitySid, other.activitySid) && - Objects.equals(attributes, other.attributes) && - Objects.equals(available, other.available) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateStatusChanged, other.dateStatusChanged) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(sid, other.sid) && - Objects.equals(workspaceSid, other.workspaceSid) && - Objects.equals(url, other.url) && - Objects.equals(links, other.links) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(activityName, other.activityName) && + Objects.equals(activitySid, other.activitySid) && + Objects.equals(attributes, other.attributes) && + Objects.equals(available, other.available) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateStatusChanged, other.dateStatusChanged) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(links, other.links) && + Objects.equals(sid, other.sid) && + Objects.equals(url, other.url) && + Objects.equals(workspaceSid, other.workspaceSid) ); } @Override public int hashCode() { return Objects.hash( - accountSid, - activityName, - activitySid, - attributes, - available, - dateCreated, - dateStatusChanged, - dateUpdated, - friendlyName, - sid, - workspaceSid, - url, - links + accountSid, + activityName, + activitySid, + attributes, + available, + dateCreated, + dateStatusChanged, + dateUpdated, + friendlyName, + links, + sid, + url, + workspaceSid ); } + + } + diff --git a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/WorkerCreator.java b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/WorkerCreator.java index ea36c83796..817afb0aab 100644 --- a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/WorkerCreator.java +++ b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/WorkerCreator.java @@ -14,8 +14,11 @@ package com.twilio.rest.taskrouter.v1.workspace; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,71 +30,62 @@ public class WorkerCreator extends Creator { - private String pathWorkspaceSid; + private String pathworkspaceSid; private String friendlyName; private String activitySid; private String attributes; - public WorkerCreator( - final String pathWorkspaceSid, - final String friendlyName - ) { - this.pathWorkspaceSid = pathWorkspaceSid; + public WorkerCreator(final String pathworkspaceSid, final String friendlyName) { + this.pathworkspaceSid = pathworkspaceSid; this.friendlyName = friendlyName; } + public WorkerCreator setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + public WorkerCreator setActivitySid(final String activitySid) { this.activitySid = activitySid; return this; } + public WorkerCreator setAttributes(final String attributes) { this.attributes = attributes; return this; } + @Override public Worker create(final TwilioRestClient client) { + String path = "/v1/Workspaces/{WorkspaceSid}/Workers"; - path = - path.replace( - "{" + "WorkspaceSid" + "}", - this.pathWorkspaceSid.toString() - ); - path = - path.replace( - "{" + "FriendlyName" + "}", - this.friendlyName.toString() - ); + path = path.replace("{" + "WorkspaceSid" + "}", this.pathworkspaceSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.TASKROUTER.toString(), - path + HttpMethod.POST, + Domains.TASKROUTER.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Worker creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("Worker creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -100,14 +94,21 @@ public Worker create(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + if (activitySid != null) { - request.addPostParam("ActivitySid", activitySid); + Serializer.toString(request, "ActivitySid", activitySid, ParameterType.URLENCODED); } + + if (attributes != null) { - request.addPostParam("Attributes", attributes); + Serializer.toString(request, "Attributes", attributes, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/WorkerDeleter.java b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/WorkerDeleter.java index 701e6d8483..7d2766de10 100644 --- a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/WorkerDeleter.java +++ b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/WorkerDeleter.java @@ -15,7 +15,8 @@ package com.twilio.rest.taskrouter.v1.workspace; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,54 +28,49 @@ public class WorkerDeleter extends Deleter { - private String pathWorkspaceSid; - private String pathSid; + private String pathworkspaceSid; + private String pathsid; private String ifMatch; - public WorkerDeleter(final String pathWorkspaceSid, final String pathSid) { - this.pathWorkspaceSid = pathWorkspaceSid; - this.pathSid = pathSid; + public WorkerDeleter(final String pathworkspaceSid, final String pathsid) { + this.pathworkspaceSid = pathworkspaceSid; + this.pathsid = pathsid; } + public WorkerDeleter setIfMatch(final String ifMatch) { this.ifMatch = ifMatch; return this; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/v1/Workspaces/{WorkspaceSid}/Workers/{Sid}"; - path = - path.replace( - "{" + "WorkspaceSid" + "}", - this.pathWorkspaceSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "WorkspaceSid" + "}", this.pathworkspaceSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.TASKROUTER.toString(), - path + HttpMethod.DELETE, + Domains.TASKROUTER.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addHeaderParams(request); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Worker delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("Worker delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -82,8 +78,10 @@ public boolean delete(final TwilioRestClient client) { } private void addHeaderParams(final Request request) { + if (ifMatch != null) { - request.addHeaderParam("If-Match", ifMatch); + Serializer.toString(request, "If-Match", ifMatch, ParameterType.HEADER); } + } } diff --git a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/WorkerFetcher.java b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/WorkerFetcher.java index d6f44a3e46..eb2e15de1c 100644 --- a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/WorkerFetcher.java +++ b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/WorkerFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.taskrouter.v1.workspace; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,51 +26,44 @@ public class WorkerFetcher extends Fetcher { - private String pathWorkspaceSid; - private String pathSid; + private String pathworkspaceSid; + private String pathsid; - public WorkerFetcher(final String pathWorkspaceSid, final String pathSid) { - this.pathWorkspaceSid = pathWorkspaceSid; - this.pathSid = pathSid; + public WorkerFetcher(final String pathworkspaceSid, final String pathsid) { + this.pathworkspaceSid = pathworkspaceSid; + this.pathsid = pathsid; } + @Override public Worker fetch(final TwilioRestClient client) { + String path = "/v1/Workspaces/{WorkspaceSid}/Workers/{Sid}"; - path = - path.replace( - "{" + "WorkspaceSid" + "}", - this.pathWorkspaceSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "WorkspaceSid" + "}", this.pathworkspaceSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.TASKROUTER.toString(), - path + HttpMethod.GET, + Domains.TASKROUTER.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Worker fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Worker fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Worker.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/WorkerReader.java b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/WorkerReader.java index 0e9f7092b0..2ef3b3bf05 100644 --- a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/WorkerReader.java +++ b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/WorkerReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,7 +30,7 @@ public class WorkerReader extends Reader { - private String pathWorkspaceSid; + private String pathworkspaceSid; private String activityName; private String activitySid; private String available; @@ -40,181 +41,173 @@ public class WorkerReader extends Reader { private String ordering; private Long pageSize; - public WorkerReader(final String pathWorkspaceSid) { - this.pathWorkspaceSid = pathWorkspaceSid; + public WorkerReader(final String pathworkspaceSid) { + this.pathworkspaceSid = pathworkspaceSid; } + public WorkerReader setActivityName(final String activityName) { this.activityName = activityName; return this; } + public WorkerReader setActivitySid(final String activitySid) { this.activitySid = activitySid; return this; } + public WorkerReader setAvailable(final String available) { this.available = available; return this; } + public WorkerReader setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } - public WorkerReader setTargetWorkersExpression( - final String targetWorkersExpression - ) { + + public WorkerReader setTargetWorkersExpression(final String targetWorkersExpression) { this.targetWorkersExpression = targetWorkersExpression; return this; } + public WorkerReader setTaskQueueName(final String taskQueueName) { this.taskQueueName = taskQueueName; return this; } + public WorkerReader setTaskQueueSid(final String taskQueueSid) { this.taskQueueSid = taskQueueSid; return this; } + public WorkerReader setOrdering(final String ordering) { this.ordering = ordering; return this; } + public WorkerReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/Workspaces/{WorkspaceSid}/Workers"; - path = - path.replace( - "{" + "WorkspaceSid" + "}", - this.pathWorkspaceSid.toString() - ); + + path = path.replace("{" + "WorkspaceSid" + "}", this.pathworkspaceSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.TASKROUTER.toString(), - path + HttpMethod.GET, + Domains.TASKROUTER.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Worker read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Worker read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "workers", - response.getContent(), - Worker.class, - client.getObjectMapper() - ); + "workers", + response.getContent(), + Worker.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.TASKROUTER.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.TASKROUTER.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (activityName != null) { - request.addQueryParam("ActivityName", activityName); + Serializer.toString(request, "ActivityName", activityName, ParameterType.QUERY); } + + if (activitySid != null) { - request.addQueryParam("ActivitySid", activitySid); + Serializer.toString(request, "ActivitySid", activitySid, ParameterType.QUERY); } + + if (available != null) { - request.addQueryParam("Available", available); + Serializer.toString(request, "Available", available, ParameterType.QUERY); } + + if (friendlyName != null) { - request.addQueryParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.QUERY); } + + if (targetWorkersExpression != null) { - request.addQueryParam( - "TargetWorkersExpression", - targetWorkersExpression - ); + Serializer.toString(request, "TargetWorkersExpression", targetWorkersExpression, ParameterType.QUERY); } + + if (taskQueueName != null) { - request.addQueryParam("TaskQueueName", taskQueueName); + Serializer.toString(request, "TaskQueueName", taskQueueName, ParameterType.QUERY); } + + if (taskQueueSid != null) { - request.addQueryParam("TaskQueueSid", taskQueueSid); + Serializer.toString(request, "TaskQueueSid", taskQueueSid, ParameterType.QUERY); } + + if (ordering != null) { - request.addQueryParam("Ordering", ordering); + Serializer.toString(request, "Ordering", ordering, ParameterType.QUERY); } + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/WorkerUpdater.java b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/WorkerUpdater.java index 30aa015581..47c0a366ad 100644 --- a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/WorkerUpdater.java +++ b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/WorkerUpdater.java @@ -16,6 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -26,81 +28,79 @@ import com.twilio.rest.Domains; public class WorkerUpdater extends Updater { - - private String pathWorkspaceSid; - private String pathSid; + private String pathworkspaceSid; + private String pathsid; private String ifMatch; private String activitySid; private String attributes; private String friendlyName; private Boolean rejectPendingReservations; - public WorkerUpdater(final String pathWorkspaceSid, final String pathSid) { - this.pathWorkspaceSid = pathWorkspaceSid; - this.pathSid = pathSid; + public WorkerUpdater(final String pathworkspaceSid, final String pathsid) { + this.pathworkspaceSid = pathworkspaceSid; + this.pathsid = pathsid; } - public WorkerUpdater setIfMatch(final String ifMatch) { - this.ifMatch = ifMatch; - return this; - } public WorkerUpdater setActivitySid(final String activitySid) { this.activitySid = activitySid; return this; } + public WorkerUpdater setAttributes(final String attributes) { this.attributes = attributes; return this; } + public WorkerUpdater setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } - public WorkerUpdater setRejectPendingReservations( - final Boolean rejectPendingReservations - ) { + + public WorkerUpdater setRejectPendingReservations(final Boolean rejectPendingReservations) { this.rejectPendingReservations = rejectPendingReservations; return this; } + + public WorkerUpdater setIfMatch(final String ifMatch) { + this.ifMatch = ifMatch; + return this; + } + + @Override public Worker update(final TwilioRestClient client) { + String path = "/v1/Workspaces/{WorkspaceSid}/Workers/{Sid}"; - path = - path.replace( - "{" + "WorkspaceSid" + "}", - this.pathWorkspaceSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "WorkspaceSid" + "}", this.pathworkspaceSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.TASKROUTER.toString(), - path + HttpMethod.POST, + Domains.TASKROUTER.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); - addPostParams(request); addHeaderParams(request); + addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Worker update failed: Unable to connect to server" - ); + throw new ApiConnectionException("Worker update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -109,26 +109,34 @@ public Worker update(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (activitySid != null) { - request.addPostParam("ActivitySid", activitySid); + Serializer.toString(request, "ActivitySid", activitySid, ParameterType.URLENCODED); } + + if (attributes != null) { - request.addPostParam("Attributes", attributes); + Serializer.toString(request, "Attributes", attributes, ParameterType.URLENCODED); } + + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + if (rejectPendingReservations != null) { - request.addPostParam( - "RejectPendingReservations", - rejectPendingReservations.toString() - ); + Serializer.toString(request, "RejectPendingReservations", rejectPendingReservations, ParameterType.URLENCODED); } + + } private void addHeaderParams(final Request request) { + if (ifMatch != null) { - request.addHeaderParam("If-Match", ifMatch); + Serializer.toString(request, "If-Match", ifMatch, ParameterType.HEADER); } + } } diff --git a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/Workflow.java b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/Workflow.java index 20ee3718b4..2bdce10f14 100644 --- a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/Workflow.java +++ b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/Workflow.java @@ -18,76 +18,71 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Workflow extends Resource { - private static final long serialVersionUID = 204168447451968L; - public static WorkflowCreator creator( - final String pathWorkspaceSid, - final String friendlyName, - final String configuration - ) { + public static WorkflowCreator creator(final String pathworkspaceSid, final String friendlyName, final String configuration) { return new WorkflowCreator( - pathWorkspaceSid, - friendlyName, - configuration + pathworkspaceSid, friendlyName, configuration ); } - public static WorkflowDeleter deleter( - final String pathWorkspaceSid, - final String pathSid - ) { - return new WorkflowDeleter(pathWorkspaceSid, pathSid); + + public static WorkflowDeleter deleter(final String pathworkspaceSid, final String pathsid) { + return new WorkflowDeleter( + pathworkspaceSid, pathsid + ); } - public static WorkflowFetcher fetcher( - final String pathWorkspaceSid, - final String pathSid - ) { - return new WorkflowFetcher(pathWorkspaceSid, pathSid); + + public static WorkflowFetcher fetcher(final String pathworkspaceSid, final String pathsid) { + return new WorkflowFetcher( + pathworkspaceSid, pathsid + ); } - public static WorkflowReader reader(final String pathWorkspaceSid) { - return new WorkflowReader(pathWorkspaceSid); + + public static WorkflowReader reader(final String pathworkspaceSid) { + return new WorkflowReader( + pathworkspaceSid + ); } - public static WorkflowUpdater updater( - final String pathWorkspaceSid, - final String pathSid - ) { - return new WorkflowUpdater(pathWorkspaceSid, pathSid); + + public static WorkflowUpdater updater(final String pathworkspaceSid, final String pathsid) { + return new WorkflowUpdater( + pathworkspaceSid, pathsid + ); } + /** * Converts a JSON String into a Workflow object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Workflow object represented by the provided JSON */ - public static Workflow fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Workflow fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Workflow.class); @@ -102,14 +97,11 @@ public static Workflow fromJson( * Converts a JSON InputStream into a Workflow object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Workflow object represented by the provided JSON */ - public static Workflow fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Workflow fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Workflow.class); @@ -120,107 +112,77 @@ public static Workflow fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; + @Getter private final URI assignmentCallbackUrl; + @Getter private final String configuration; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; + @Getter private final String documentContentType; + @Getter private final URI fallbackAssignmentCallbackUrl; + @Getter private final String friendlyName; + @Getter + private final Map links; + @Getter private final String sid; + @Getter private final Integer taskReservationTimeout; - private final String workspaceSid; + @Getter private final URI url; - private final Map links; + @Getter + private final String workspaceSid; @JsonCreator private Workflow( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty( - "assignment_callback_url" - ) final URI assignmentCallbackUrl, - @JsonProperty("configuration") final String configuration, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("document_content_type") final String documentContentType, - @JsonProperty( - "fallback_assignment_callback_url" - ) final URI fallbackAssignmentCallbackUrl, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("sid") final String sid, - @JsonProperty( - "task_reservation_timeout" - ) final Integer taskReservationTimeout, - @JsonProperty("workspace_sid") final String workspaceSid, - @JsonProperty("url") final URI url, - @JsonProperty("links") final Map links + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("assignment_callback_url") final URI assignmentCallbackUrl, + @JsonProperty("configuration") final String configuration, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("document_content_type") final String documentContentType, + @JsonProperty("fallback_assignment_callback_url") final URI fallbackAssignmentCallbackUrl, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("links") final Map links, + @JsonProperty("sid") final String sid, + @JsonProperty("task_reservation_timeout") final Integer taskReservationTimeout, + @JsonProperty("url") final URI url, + @JsonProperty("workspace_sid") final String workspaceSid ) { this.accountSid = accountSid; this.assignmentCallbackUrl = assignmentCallbackUrl; this.configuration = configuration; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.documentContentType = documentContentType; this.fallbackAssignmentCallbackUrl = fallbackAssignmentCallbackUrl; this.friendlyName = friendlyName; + this.links = links; this.sid = sid; this.taskReservationTimeout = taskReservationTimeout; - this.workspaceSid = workspaceSid; this.url = url; - this.links = links; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final URI getAssignmentCallbackUrl() { - return this.assignmentCallbackUrl; - } - - public final String getConfiguration() { - return this.configuration; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final String getDocumentContentType() { - return this.documentContentType; - } - - public final URI getFallbackAssignmentCallbackUrl() { - return this.fallbackAssignmentCallbackUrl; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final String getSid() { - return this.sid; - } - - public final Integer getTaskReservationTimeout() { - return this.taskReservationTimeout; - } - - public final String getWorkspaceSid() { - return this.workspaceSid; - } - - public final URI getUrl() { - return this.url; - } - - public final Map getLinks() { - return this.links; + this.workspaceSid = workspaceSid; } @Override @@ -234,49 +196,42 @@ public boolean equals(final Object o) { } Workflow other = (Workflow) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals( - assignmentCallbackUrl, - other.assignmentCallbackUrl - ) && - Objects.equals(configuration, other.configuration) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(documentContentType, other.documentContentType) && - Objects.equals( - fallbackAssignmentCallbackUrl, - other.fallbackAssignmentCallbackUrl - ) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(sid, other.sid) && - Objects.equals( - taskReservationTimeout, - other.taskReservationTimeout - ) && - Objects.equals(workspaceSid, other.workspaceSid) && - Objects.equals(url, other.url) && - Objects.equals(links, other.links) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(assignmentCallbackUrl, other.assignmentCallbackUrl) && + Objects.equals(configuration, other.configuration) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(documentContentType, other.documentContentType) && + Objects.equals(fallbackAssignmentCallbackUrl, other.fallbackAssignmentCallbackUrl) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(links, other.links) && + Objects.equals(sid, other.sid) && + Objects.equals(taskReservationTimeout, other.taskReservationTimeout) && + Objects.equals(url, other.url) && + Objects.equals(workspaceSid, other.workspaceSid) ); } @Override public int hashCode() { return Objects.hash( - accountSid, - assignmentCallbackUrl, - configuration, - dateCreated, - dateUpdated, - documentContentType, - fallbackAssignmentCallbackUrl, - friendlyName, - sid, - taskReservationTimeout, - workspaceSid, - url, - links + accountSid, + assignmentCallbackUrl, + configuration, + dateCreated, + dateUpdated, + documentContentType, + fallbackAssignmentCallbackUrl, + friendlyName, + links, + sid, + taskReservationTimeout, + url, + workspaceSid ); } + + } + diff --git a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/WorkflowCreator.java b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/WorkflowCreator.java index 95869e496a..1ccb4e9575 100644 --- a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/WorkflowCreator.java +++ b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/WorkflowCreator.java @@ -14,9 +14,11 @@ package com.twilio.rest.taskrouter.v1.workspace; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; -import com.twilio.converter.Promoter; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,151 +27,115 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -import java.net.URI; + import java.net.URI; public class WorkflowCreator extends Creator { - private String pathWorkspaceSid; + private String pathworkspaceSid; private String friendlyName; private String configuration; private URI assignmentCallbackUrl; private URI fallbackAssignmentCallbackUrl; private Integer taskReservationTimeout; - public WorkflowCreator( - final String pathWorkspaceSid, - final String friendlyName, - final String configuration - ) { - this.pathWorkspaceSid = pathWorkspaceSid; + public WorkflowCreator(final String pathworkspaceSid, final String friendlyName, final String configuration) { + this.pathworkspaceSid = pathworkspaceSid; this.friendlyName = friendlyName; this.configuration = configuration; } + public WorkflowCreator setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + public WorkflowCreator setConfiguration(final String configuration) { this.configuration = configuration; return this; } - public WorkflowCreator setAssignmentCallbackUrl( - final URI assignmentCallbackUrl - ) { + + public WorkflowCreator setAssignmentCallbackUrl(final URI assignmentCallbackUrl) { this.assignmentCallbackUrl = assignmentCallbackUrl; return this; } - public WorkflowCreator setAssignmentCallbackUrl( - final String assignmentCallbackUrl - ) { - return setAssignmentCallbackUrl( - Promoter.uriFromString(assignmentCallbackUrl) - ); - } - public WorkflowCreator setFallbackAssignmentCallbackUrl( - final URI fallbackAssignmentCallbackUrl - ) { + public WorkflowCreator setFallbackAssignmentCallbackUrl(final URI fallbackAssignmentCallbackUrl) { this.fallbackAssignmentCallbackUrl = fallbackAssignmentCallbackUrl; return this; } - public WorkflowCreator setFallbackAssignmentCallbackUrl( - final String fallbackAssignmentCallbackUrl - ) { - return setFallbackAssignmentCallbackUrl( - Promoter.uriFromString(fallbackAssignmentCallbackUrl) - ); - } - public WorkflowCreator setTaskReservationTimeout( - final Integer taskReservationTimeout - ) { + public WorkflowCreator setTaskReservationTimeout(final Integer taskReservationTimeout) { this.taskReservationTimeout = taskReservationTimeout; return this; } + @Override public Workflow create(final TwilioRestClient client) { + String path = "/v1/Workspaces/{WorkspaceSid}/Workflows"; - path = - path.replace( - "{" + "WorkspaceSid" + "}", - this.pathWorkspaceSid.toString() - ); - path = - path.replace( - "{" + "FriendlyName" + "}", - this.friendlyName.toString() - ); - path = - path.replace( - "{" + "Configuration" + "}", - this.configuration.toString() - ); + path = path.replace("{" + "WorkspaceSid" + "}", this.pathworkspaceSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.TASKROUTER.toString(), - path + HttpMethod.POST, + Domains.TASKROUTER.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Workflow creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("Workflow creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Workflow.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Workflow.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + if (configuration != null) { - request.addPostParam("Configuration", configuration); + Serializer.toString(request, "Configuration", configuration, ParameterType.URLENCODED); } + + if (assignmentCallbackUrl != null) { - request.addPostParam( - "AssignmentCallbackUrl", - assignmentCallbackUrl.toString() - ); + Serializer.toString(request, "AssignmentCallbackUrl", assignmentCallbackUrl, ParameterType.URLENCODED); } + + if (fallbackAssignmentCallbackUrl != null) { - request.addPostParam( - "FallbackAssignmentCallbackUrl", - fallbackAssignmentCallbackUrl.toString() - ); + Serializer.toString(request, "FallbackAssignmentCallbackUrl", fallbackAssignmentCallbackUrl, ParameterType.URLENCODED); } + + if (taskReservationTimeout != null) { - request.addPostParam( - "TaskReservationTimeout", - taskReservationTimeout.toString() - ); + Serializer.toString(request, "TaskReservationTimeout", taskReservationTimeout, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/WorkflowDeleter.java b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/WorkflowDeleter.java index 889961f6d7..8e4e387d8b 100644 --- a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/WorkflowDeleter.java +++ b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/WorkflowDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.taskrouter.v1.workspace; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,50 +26,41 @@ public class WorkflowDeleter extends Deleter { - private String pathWorkspaceSid; - private String pathSid; + private String pathworkspaceSid; + private String pathsid; - public WorkflowDeleter( - final String pathWorkspaceSid, - final String pathSid - ) { - this.pathWorkspaceSid = pathWorkspaceSid; - this.pathSid = pathSid; + public WorkflowDeleter(final String pathworkspaceSid, final String pathsid) { + this.pathworkspaceSid = pathworkspaceSid; + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/v1/Workspaces/{WorkspaceSid}/Workflows/{Sid}"; - path = - path.replace( - "{" + "WorkspaceSid" + "}", - this.pathWorkspaceSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "WorkspaceSid" + "}", this.pathworkspaceSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.TASKROUTER.toString(), - path + HttpMethod.DELETE, + Domains.TASKROUTER.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Workflow delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("Workflow delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/WorkflowFetcher.java b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/WorkflowFetcher.java index 41d31a5922..989590dd20 100644 --- a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/WorkflowFetcher.java +++ b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/WorkflowFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.taskrouter.v1.workspace; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,57 +26,44 @@ public class WorkflowFetcher extends Fetcher { - private String pathWorkspaceSid; - private String pathSid; + private String pathworkspaceSid; + private String pathsid; - public WorkflowFetcher( - final String pathWorkspaceSid, - final String pathSid - ) { - this.pathWorkspaceSid = pathWorkspaceSid; - this.pathSid = pathSid; + public WorkflowFetcher(final String pathworkspaceSid, final String pathsid) { + this.pathworkspaceSid = pathworkspaceSid; + this.pathsid = pathsid; } + @Override public Workflow fetch(final TwilioRestClient client) { + String path = "/v1/Workspaces/{WorkspaceSid}/Workflows/{Sid}"; - path = - path.replace( - "{" + "WorkspaceSid" + "}", - this.pathWorkspaceSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "WorkspaceSid" + "}", this.pathworkspaceSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.TASKROUTER.toString(), - path + HttpMethod.GET, + Domains.TASKROUTER.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Workflow fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Workflow fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return Workflow.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Workflow.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/WorkflowReader.java b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/WorkflowReader.java index f0a679ceb6..3e06586068 100644 --- a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/WorkflowReader.java +++ b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/WorkflowReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,124 +30,100 @@ public class WorkflowReader extends Reader { - private String pathWorkspaceSid; + private String pathworkspaceSid; private String friendlyName; private Long pageSize; - public WorkflowReader(final String pathWorkspaceSid) { - this.pathWorkspaceSid = pathWorkspaceSid; + public WorkflowReader(final String pathworkspaceSid) { + this.pathworkspaceSid = pathworkspaceSid; } + public WorkflowReader setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + public WorkflowReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/Workspaces/{WorkspaceSid}/Workflows"; - path = - path.replace( - "{" + "WorkspaceSid" + "}", - this.pathWorkspaceSid.toString() - ); + + path = path.replace("{" + "WorkspaceSid" + "}", this.pathworkspaceSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.TASKROUTER.toString(), - path + HttpMethod.GET, + Domains.TASKROUTER.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Workflow read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Workflow read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "workflows", - response.getContent(), - Workflow.class, - client.getObjectMapper() - ); + "workflows", + response.getContent(), + Workflow.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.TASKROUTER.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.TASKROUTER.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (friendlyName != null) { - request.addQueryParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.QUERY); } + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/WorkflowUpdater.java b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/WorkflowUpdater.java index 2e9315cc0c..a696d290c8 100644 --- a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/WorkflowUpdater.java +++ b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/WorkflowUpdater.java @@ -16,7 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; -import com.twilio.converter.Promoter; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,12 +26,12 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.net.URI; public class WorkflowUpdater extends Updater { - - private String pathWorkspaceSid; - private String pathSid; + private String pathworkspaceSid; + private String pathsid; private String friendlyName; private URI assignmentCallbackUrl; private URI fallbackAssignmentCallbackUrl; @@ -38,136 +39,114 @@ public class WorkflowUpdater extends Updater { private Integer taskReservationTimeout; private String reEvaluateTasks; - public WorkflowUpdater( - final String pathWorkspaceSid, - final String pathSid - ) { - this.pathWorkspaceSid = pathWorkspaceSid; - this.pathSid = pathSid; + public WorkflowUpdater(final String pathworkspaceSid, final String pathsid) { + this.pathworkspaceSid = pathworkspaceSid; + this.pathsid = pathsid; } + public WorkflowUpdater setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } - public WorkflowUpdater setAssignmentCallbackUrl( - final URI assignmentCallbackUrl - ) { + + public WorkflowUpdater setAssignmentCallbackUrl(final URI assignmentCallbackUrl) { this.assignmentCallbackUrl = assignmentCallbackUrl; return this; } - public WorkflowUpdater setAssignmentCallbackUrl( - final String assignmentCallbackUrl - ) { - return setAssignmentCallbackUrl( - Promoter.uriFromString(assignmentCallbackUrl) - ); - } - public WorkflowUpdater setFallbackAssignmentCallbackUrl( - final URI fallbackAssignmentCallbackUrl - ) { + public WorkflowUpdater setFallbackAssignmentCallbackUrl(final URI fallbackAssignmentCallbackUrl) { this.fallbackAssignmentCallbackUrl = fallbackAssignmentCallbackUrl; return this; } - public WorkflowUpdater setFallbackAssignmentCallbackUrl( - final String fallbackAssignmentCallbackUrl - ) { - return setFallbackAssignmentCallbackUrl( - Promoter.uriFromString(fallbackAssignmentCallbackUrl) - ); - } public WorkflowUpdater setConfiguration(final String configuration) { this.configuration = configuration; return this; } - public WorkflowUpdater setTaskReservationTimeout( - final Integer taskReservationTimeout - ) { + + public WorkflowUpdater setTaskReservationTimeout(final Integer taskReservationTimeout) { this.taskReservationTimeout = taskReservationTimeout; return this; } + public WorkflowUpdater setReEvaluateTasks(final String reEvaluateTasks) { this.reEvaluateTasks = reEvaluateTasks; return this; } + @Override public Workflow update(final TwilioRestClient client) { + String path = "/v1/Workspaces/{WorkspaceSid}/Workflows/{Sid}"; - path = - path.replace( - "{" + "WorkspaceSid" + "}", - this.pathWorkspaceSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "WorkspaceSid" + "}", this.pathworkspaceSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.TASKROUTER.toString(), - path + HttpMethod.POST, + Domains.TASKROUTER.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Workflow update failed: Unable to connect to server" - ); + throw new ApiConnectionException("Workflow update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Workflow.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Workflow.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + if (assignmentCallbackUrl != null) { - request.addPostParam( - "AssignmentCallbackUrl", - assignmentCallbackUrl.toString() - ); + Serializer.toString(request, "AssignmentCallbackUrl", assignmentCallbackUrl, ParameterType.URLENCODED); } + + if (fallbackAssignmentCallbackUrl != null) { - request.addPostParam( - "FallbackAssignmentCallbackUrl", - fallbackAssignmentCallbackUrl.toString() - ); + Serializer.toString(request, "FallbackAssignmentCallbackUrl", fallbackAssignmentCallbackUrl, ParameterType.URLENCODED); } + + if (configuration != null) { - request.addPostParam("Configuration", configuration); + Serializer.toString(request, "Configuration", configuration, ParameterType.URLENCODED); } + + if (taskReservationTimeout != null) { - request.addPostParam( - "TaskReservationTimeout", - taskReservationTimeout.toString() - ); + Serializer.toString(request, "TaskReservationTimeout", taskReservationTimeout, ParameterType.URLENCODED); } + + if (reEvaluateTasks != null) { - request.addPostParam("ReEvaluateTasks", reEvaluateTasks); + Serializer.toString(request, "ReEvaluateTasks", reEvaluateTasks, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/WorkspaceCumulativeStatistics.java b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/WorkspaceCumulativeStatistics.java index a87e16e142..c28395369d 100644 --- a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/WorkspaceCumulativeStatistics.java +++ b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/WorkspaceCumulativeStatistics.java @@ -18,51 +18,45 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; -import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class WorkspaceCumulativeStatistics extends Resource { - private static final long serialVersionUID = 84911824165722L; - public static WorkspaceCumulativeStatisticsFetcher fetcher( - final String pathWorkspaceSid - ) { - return new WorkspaceCumulativeStatisticsFetcher(pathWorkspaceSid); + public static WorkspaceCumulativeStatisticsFetcher fetcher(final String pathworkspaceSid) { + return new WorkspaceCumulativeStatisticsFetcher( + pathworkspaceSid + ); } + /** * Converts a JSON String into a WorkspaceCumulativeStatistics object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return WorkspaceCumulativeStatistics object represented by the provided JSON */ - public static WorkspaceCumulativeStatistics fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static WorkspaceCumulativeStatistics fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { - return objectMapper.readValue( - json, - WorkspaceCumulativeStatistics.class - ); + return objectMapper.readValue(json, WorkspaceCumulativeStatistics.class); } catch (final JsonMappingException | JsonParseException e) { throw new ApiException(e.getMessage(), e); } catch (final IOException e) { @@ -74,20 +68,14 @@ public static WorkspaceCumulativeStatistics fromJson( * Converts a JSON InputStream into a WorkspaceCumulativeStatistics object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return WorkspaceCumulativeStatistics object represented by the provided JSON */ - public static WorkspaceCumulativeStatistics fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static WorkspaceCumulativeStatistics fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { - return objectMapper.readValue( - json, - WorkspaceCumulativeStatistics.class - ); + return objectMapper.readValue(json, WorkspaceCumulativeStatistics.class); } catch (final JsonMappingException | JsonParseException e) { throw new ApiException(e.getMessage(), e); } catch (final IOException e) { @@ -95,180 +83,109 @@ public static WorkspaceCumulativeStatistics fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; + @Getter private final Integer avgTaskAcceptanceTime; - private final ZonedDateTime startTime; + @Getter private final ZonedDateTime endTime; - private final Integer reservationsCreated; + @Getter private final Integer reservationsAccepted; - private final Integer reservationsRejected; - private final Integer reservationsTimedOut; + @Getter private final Integer reservationsCanceled; + @Getter + private final Integer reservationsCreated; + @Getter + private final Integer reservationsRejected; + @Getter private final Integer reservationsRescinded; - private final Map splitByWaitTime; - private final Map waitDurationUntilAccepted; - private final Map waitDurationUntilCanceled; + @Getter + private final Integer reservationsTimedOut; + @Getter + private final Object splitByWaitTime; + @Getter + private final ZonedDateTime startTime; + @Getter private final Integer tasksCanceled; + @Getter private final Integer tasksCompleted; + @Getter private final Integer tasksCreated; + @Getter private final Integer tasksDeleted; + @Getter private final Integer tasksMoved; + @Getter private final Integer tasksTimedOutInWorkflow; - private final String workspaceSid; + @Getter private final URI url; + @Getter + private final Object waitDurationUntilAccepted; + @Getter + private final Object waitDurationUntilCanceled; + @Getter + private final String workspaceSid; @JsonCreator private WorkspaceCumulativeStatistics( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty( - "avg_task_acceptance_time" - ) final Integer avgTaskAcceptanceTime, - @JsonProperty("start_time") final String startTime, - @JsonProperty("end_time") final String endTime, - @JsonProperty("reservations_created") final Integer reservationsCreated, - @JsonProperty( - "reservations_accepted" - ) final Integer reservationsAccepted, - @JsonProperty( - "reservations_rejected" - ) final Integer reservationsRejected, - @JsonProperty( - "reservations_timed_out" - ) final Integer reservationsTimedOut, - @JsonProperty( - "reservations_canceled" - ) final Integer reservationsCanceled, - @JsonProperty( - "reservations_rescinded" - ) final Integer reservationsRescinded, - @JsonProperty("split_by_wait_time") final Map< - String, - Object - > splitByWaitTime, - @JsonProperty("wait_duration_until_accepted") final Map< - String, - Object - > waitDurationUntilAccepted, - @JsonProperty("wait_duration_until_canceled") final Map< - String, - Object - > waitDurationUntilCanceled, - @JsonProperty("tasks_canceled") final Integer tasksCanceled, - @JsonProperty("tasks_completed") final Integer tasksCompleted, - @JsonProperty("tasks_created") final Integer tasksCreated, - @JsonProperty("tasks_deleted") final Integer tasksDeleted, - @JsonProperty("tasks_moved") final Integer tasksMoved, - @JsonProperty( - "tasks_timed_out_in_workflow" - ) final Integer tasksTimedOutInWorkflow, - @JsonProperty("workspace_sid") final String workspaceSid, - @JsonProperty("url") final URI url + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("avg_task_acceptance_time") final Integer avgTaskAcceptanceTime, + @JsonProperty("end_time") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime endTime, + @JsonProperty("reservations_accepted") final Integer reservationsAccepted, + @JsonProperty("reservations_canceled") final Integer reservationsCanceled, + @JsonProperty("reservations_created") final Integer reservationsCreated, + @JsonProperty("reservations_rejected") final Integer reservationsRejected, + @JsonProperty("reservations_rescinded") final Integer reservationsRescinded, + @JsonProperty("reservations_timed_out") final Integer reservationsTimedOut, + @JsonProperty("split_by_wait_time") final Object splitByWaitTime, + @JsonProperty("start_time") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime startTime, + @JsonProperty("tasks_canceled") final Integer tasksCanceled, + @JsonProperty("tasks_completed") final Integer tasksCompleted, + @JsonProperty("tasks_created") final Integer tasksCreated, + @JsonProperty("tasks_deleted") final Integer tasksDeleted, + @JsonProperty("tasks_moved") final Integer tasksMoved, + @JsonProperty("tasks_timed_out_in_workflow") final Integer tasksTimedOutInWorkflow, + @JsonProperty("url") final URI url, + @JsonProperty("wait_duration_until_accepted") final Object waitDurationUntilAccepted, + @JsonProperty("wait_duration_until_canceled") final Object waitDurationUntilCanceled, + @JsonProperty("workspace_sid") final String workspaceSid ) { this.accountSid = accountSid; this.avgTaskAcceptanceTime = avgTaskAcceptanceTime; - this.startTime = DateConverter.iso8601DateTimeFromString(startTime); - this.endTime = DateConverter.iso8601DateTimeFromString(endTime); - this.reservationsCreated = reservationsCreated; + this.endTime = endTime; this.reservationsAccepted = reservationsAccepted; - this.reservationsRejected = reservationsRejected; - this.reservationsTimedOut = reservationsTimedOut; this.reservationsCanceled = reservationsCanceled; + this.reservationsCreated = reservationsCreated; + this.reservationsRejected = reservationsRejected; this.reservationsRescinded = reservationsRescinded; + this.reservationsTimedOut = reservationsTimedOut; this.splitByWaitTime = splitByWaitTime; - this.waitDurationUntilAccepted = waitDurationUntilAccepted; - this.waitDurationUntilCanceled = waitDurationUntilCanceled; + this.startTime = startTime; this.tasksCanceled = tasksCanceled; this.tasksCompleted = tasksCompleted; this.tasksCreated = tasksCreated; this.tasksDeleted = tasksDeleted; this.tasksMoved = tasksMoved; this.tasksTimedOutInWorkflow = tasksTimedOutInWorkflow; - this.workspaceSid = workspaceSid; this.url = url; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final Integer getAvgTaskAcceptanceTime() { - return this.avgTaskAcceptanceTime; - } - - public final ZonedDateTime getStartTime() { - return this.startTime; - } - - public final ZonedDateTime getEndTime() { - return this.endTime; - } - - public final Integer getReservationsCreated() { - return this.reservationsCreated; - } - - public final Integer getReservationsAccepted() { - return this.reservationsAccepted; - } - - public final Integer getReservationsRejected() { - return this.reservationsRejected; - } - - public final Integer getReservationsTimedOut() { - return this.reservationsTimedOut; - } - - public final Integer getReservationsCanceled() { - return this.reservationsCanceled; - } - - public final Integer getReservationsRescinded() { - return this.reservationsRescinded; - } - - public final Map getSplitByWaitTime() { - return this.splitByWaitTime; - } - - public final Map getWaitDurationUntilAccepted() { - return this.waitDurationUntilAccepted; - } - - public final Map getWaitDurationUntilCanceled() { - return this.waitDurationUntilCanceled; - } - - public final Integer getTasksCanceled() { - return this.tasksCanceled; - } - - public final Integer getTasksCompleted() { - return this.tasksCompleted; - } - - public final Integer getTasksCreated() { - return this.tasksCreated; - } - - public final Integer getTasksDeleted() { - return this.tasksDeleted; - } - - public final Integer getTasksMoved() { - return this.tasksMoved; - } - - public final Integer getTasksTimedOutInWorkflow() { - return this.tasksTimedOutInWorkflow; - } - - public final String getWorkspaceSid() { - return this.workspaceSid; - } - - public final URI getUrl() { - return this.url; + this.waitDurationUntilAccepted = waitDurationUntilAccepted; + this.waitDurationUntilCanceled = waitDurationUntilCanceled; + this.workspaceSid = workspaceSid; } @Override @@ -282,71 +199,58 @@ public boolean equals(final Object o) { } WorkspaceCumulativeStatistics other = (WorkspaceCumulativeStatistics) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals( - avgTaskAcceptanceTime, - other.avgTaskAcceptanceTime - ) && - Objects.equals(startTime, other.startTime) && - Objects.equals(endTime, other.endTime) && - Objects.equals(reservationsCreated, other.reservationsCreated) && - Objects.equals(reservationsAccepted, other.reservationsAccepted) && - Objects.equals(reservationsRejected, other.reservationsRejected) && - Objects.equals(reservationsTimedOut, other.reservationsTimedOut) && - Objects.equals(reservationsCanceled, other.reservationsCanceled) && - Objects.equals( - reservationsRescinded, - other.reservationsRescinded - ) && - Objects.equals(splitByWaitTime, other.splitByWaitTime) && - Objects.equals( - waitDurationUntilAccepted, - other.waitDurationUntilAccepted - ) && - Objects.equals( - waitDurationUntilCanceled, - other.waitDurationUntilCanceled - ) && - Objects.equals(tasksCanceled, other.tasksCanceled) && - Objects.equals(tasksCompleted, other.tasksCompleted) && - Objects.equals(tasksCreated, other.tasksCreated) && - Objects.equals(tasksDeleted, other.tasksDeleted) && - Objects.equals(tasksMoved, other.tasksMoved) && - Objects.equals( - tasksTimedOutInWorkflow, - other.tasksTimedOutInWorkflow - ) && - Objects.equals(workspaceSid, other.workspaceSid) && - Objects.equals(url, other.url) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(avgTaskAcceptanceTime, other.avgTaskAcceptanceTime) && + Objects.equals(endTime, other.endTime) && + Objects.equals(reservationsAccepted, other.reservationsAccepted) && + Objects.equals(reservationsCanceled, other.reservationsCanceled) && + Objects.equals(reservationsCreated, other.reservationsCreated) && + Objects.equals(reservationsRejected, other.reservationsRejected) && + Objects.equals(reservationsRescinded, other.reservationsRescinded) && + Objects.equals(reservationsTimedOut, other.reservationsTimedOut) && + Objects.equals(splitByWaitTime, other.splitByWaitTime) && + Objects.equals(startTime, other.startTime) && + Objects.equals(tasksCanceled, other.tasksCanceled) && + Objects.equals(tasksCompleted, other.tasksCompleted) && + Objects.equals(tasksCreated, other.tasksCreated) && + Objects.equals(tasksDeleted, other.tasksDeleted) && + Objects.equals(tasksMoved, other.tasksMoved) && + Objects.equals(tasksTimedOutInWorkflow, other.tasksTimedOutInWorkflow) && + Objects.equals(url, other.url) && + Objects.equals(waitDurationUntilAccepted, other.waitDurationUntilAccepted) && + Objects.equals(waitDurationUntilCanceled, other.waitDurationUntilCanceled) && + Objects.equals(workspaceSid, other.workspaceSid) ); } @Override public int hashCode() { return Objects.hash( - accountSid, - avgTaskAcceptanceTime, - startTime, - endTime, - reservationsCreated, - reservationsAccepted, - reservationsRejected, - reservationsTimedOut, - reservationsCanceled, - reservationsRescinded, - splitByWaitTime, - waitDurationUntilAccepted, - waitDurationUntilCanceled, - tasksCanceled, - tasksCompleted, - tasksCreated, - tasksDeleted, - tasksMoved, - tasksTimedOutInWorkflow, - workspaceSid, - url + accountSid, + avgTaskAcceptanceTime, + endTime, + reservationsAccepted, + reservationsCanceled, + reservationsCreated, + reservationsRejected, + reservationsRescinded, + reservationsTimedOut, + splitByWaitTime, + startTime, + tasksCanceled, + tasksCompleted, + tasksCreated, + tasksDeleted, + tasksMoved, + tasksTimedOutInWorkflow, + url, + waitDurationUntilAccepted, + waitDurationUntilCanceled, + workspaceSid ); } + + } + diff --git a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/WorkspaceCumulativeStatisticsFetcher.java b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/WorkspaceCumulativeStatisticsFetcher.java index fd54925267..f26b005582 100644 --- a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/WorkspaceCumulativeStatisticsFetcher.java +++ b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/WorkspaceCumulativeStatisticsFetcher.java @@ -15,7 +15,8 @@ package com.twilio.rest.taskrouter.v1.workspace; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -24,120 +25,112 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.time.ZonedDateTime; -public class WorkspaceCumulativeStatisticsFetcher - extends Fetcher { +public class WorkspaceCumulativeStatisticsFetcher extends Fetcher { - private String pathWorkspaceSid; + private String pathworkspaceSid; private ZonedDateTime endDate; private Integer minutes; private ZonedDateTime startDate; private String taskChannel; private String splitByWaitTime; - public WorkspaceCumulativeStatisticsFetcher(final String pathWorkspaceSid) { - this.pathWorkspaceSid = pathWorkspaceSid; + public WorkspaceCumulativeStatisticsFetcher(final String pathworkspaceSid) { + this.pathworkspaceSid = pathworkspaceSid; } - public WorkspaceCumulativeStatisticsFetcher setEndDate( - final ZonedDateTime endDate - ) { + + public WorkspaceCumulativeStatisticsFetcher setEndDate(final ZonedDateTime endDate) { this.endDate = endDate; return this; } - public WorkspaceCumulativeStatisticsFetcher setMinutes( - final Integer minutes - ) { + + public WorkspaceCumulativeStatisticsFetcher setMinutes(final Integer minutes) { this.minutes = minutes; return this; } - public WorkspaceCumulativeStatisticsFetcher setStartDate( - final ZonedDateTime startDate - ) { + + public WorkspaceCumulativeStatisticsFetcher setStartDate(final ZonedDateTime startDate) { this.startDate = startDate; return this; } - public WorkspaceCumulativeStatisticsFetcher setTaskChannel( - final String taskChannel - ) { + + public WorkspaceCumulativeStatisticsFetcher setTaskChannel(final String taskChannel) { this.taskChannel = taskChannel; return this; } - public WorkspaceCumulativeStatisticsFetcher setSplitByWaitTime( - final String splitByWaitTime - ) { + + public WorkspaceCumulativeStatisticsFetcher setSplitByWaitTime(final String splitByWaitTime) { this.splitByWaitTime = splitByWaitTime; return this; } + @Override public WorkspaceCumulativeStatistics fetch(final TwilioRestClient client) { + String path = "/v1/Workspaces/{WorkspaceSid}/CumulativeStatistics"; - path = - path.replace( - "{" + "WorkspaceSid" + "}", - this.pathWorkspaceSid.toString() - ); + path = path.replace("{" + "WorkspaceSid" + "}", this.pathworkspaceSid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.TASKROUTER.toString(), - path + HttpMethod.GET, + Domains.TASKROUTER.toString(), + path ); addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "WorkspaceCumulativeStatistics fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("WorkspaceCumulativeStatistics fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return WorkspaceCumulativeStatistics.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return WorkspaceCumulativeStatistics.fromJson(response.getStream(), client.getObjectMapper()); } private void addQueryParams(final Request request) { + + if (endDate != null) { - request.addQueryParam("EndDate", endDate.toInstant().toString()); + Serializer.toString(request, "EndDate", endDate, ParameterType.QUERY); } + if (minutes != null) { - request.addQueryParam("Minutes", minutes.toString()); + Serializer.toString(request, "Minutes", minutes, ParameterType.QUERY); } + + if (startDate != null) { - request.addQueryParam( - "StartDate", - startDate.toInstant().toString() - ); + Serializer.toString(request, "StartDate", startDate, ParameterType.QUERY); } + if (taskChannel != null) { - request.addQueryParam("TaskChannel", taskChannel); + Serializer.toString(request, "TaskChannel", taskChannel, ParameterType.QUERY); } + + if (splitByWaitTime != null) { - request.addQueryParam("SplitByWaitTime", splitByWaitTime); + Serializer.toString(request, "SplitByWaitTime", splitByWaitTime, ParameterType.QUERY); } + + } } diff --git a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/WorkspaceRealTimeStatistics.java b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/WorkspaceRealTimeStatistics.java index 0f327cf14a..ac8bdafb37 100644 --- a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/WorkspaceRealTimeStatistics.java +++ b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/WorkspaceRealTimeStatistics.java @@ -18,50 +18,44 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.util.List; -import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class WorkspaceRealTimeStatistics extends Resource { - private static final long serialVersionUID = 188768803928766L; - public static WorkspaceRealTimeStatisticsFetcher fetcher( - final String pathWorkspaceSid - ) { - return new WorkspaceRealTimeStatisticsFetcher(pathWorkspaceSid); + public static WorkspaceRealTimeStatisticsFetcher fetcher(final String pathworkspaceSid) { + return new WorkspaceRealTimeStatisticsFetcher( + pathworkspaceSid + ); } + /** * Converts a JSON String into a WorkspaceRealTimeStatistics object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return WorkspaceRealTimeStatistics object represented by the provided JSON */ - public static WorkspaceRealTimeStatistics fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static WorkspaceRealTimeStatistics fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { - return objectMapper.readValue( - json, - WorkspaceRealTimeStatistics.class - ); + return objectMapper.readValue(json, WorkspaceRealTimeStatistics.class); } catch (final JsonMappingException | JsonParseException e) { throw new ApiException(e.getMessage(), e); } catch (final IOException e) { @@ -73,20 +67,14 @@ public static WorkspaceRealTimeStatistics fromJson( * Converts a JSON InputStream into a WorkspaceRealTimeStatistics object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return WorkspaceRealTimeStatistics object represented by the provided JSON */ - public static WorkspaceRealTimeStatistics fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static WorkspaceRealTimeStatistics fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { - return objectMapper.readValue( - json, - WorkspaceRealTimeStatistics.class - ); + return objectMapper.readValue(json, WorkspaceRealTimeStatistics.class); } catch (final JsonMappingException | JsonParseException e) { throw new ApiException(e.getMessage(), e); } catch (final IOException e) { @@ -94,41 +82,52 @@ public static WorkspaceRealTimeStatistics fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final List> activityStatistics; + @Getter + private final List activityStatistics; + @Getter private final Integer longestTaskWaitingAge; + @Getter private final String longestTaskWaitingSid; - private final Map tasksByPriority; - private final Map tasksByStatus; + @Getter + private final Object tasksByPriority; + @Getter + private final Object tasksByStatus; + @Getter private final Integer totalTasks; + @Getter private final Integer totalWorkers; - private final String workspaceSid; + @Getter private final URI url; + @Getter + private final String workspaceSid; @JsonCreator private WorkspaceRealTimeStatistics( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("activity_statistics") final List< - Map - > activityStatistics, - @JsonProperty( - "longest_task_waiting_age" - ) final Integer longestTaskWaitingAge, - @JsonProperty( - "longest_task_waiting_sid" - ) final String longestTaskWaitingSid, - @JsonProperty("tasks_by_priority") final Map< - String, - Object - > tasksByPriority, - @JsonProperty("tasks_by_status") final Map< - String, - Object - > tasksByStatus, - @JsonProperty("total_tasks") final Integer totalTasks, - @JsonProperty("total_workers") final Integer totalWorkers, - @JsonProperty("workspace_sid") final String workspaceSid, - @JsonProperty("url") final URI url + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("activity_statistics") final List activityStatistics, + @JsonProperty("longest_task_waiting_age") final Integer longestTaskWaitingAge, + @JsonProperty("longest_task_waiting_sid") final String longestTaskWaitingSid, + @JsonProperty("tasks_by_priority") final Object tasksByPriority, + @JsonProperty("tasks_by_status") final Object tasksByStatus, + @JsonProperty("total_tasks") final Integer totalTasks, + @JsonProperty("total_workers") final Integer totalWorkers, + @JsonProperty("url") final URI url, + @JsonProperty("workspace_sid") final String workspaceSid ) { this.accountSid = accountSid; this.activityStatistics = activityStatistics; @@ -138,48 +137,8 @@ private WorkspaceRealTimeStatistics( this.tasksByStatus = tasksByStatus; this.totalTasks = totalTasks; this.totalWorkers = totalWorkers; - this.workspaceSid = workspaceSid; this.url = url; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final List> getActivityStatistics() { - return this.activityStatistics; - } - - public final Integer getLongestTaskWaitingAge() { - return this.longestTaskWaitingAge; - } - - public final String getLongestTaskWaitingSid() { - return this.longestTaskWaitingSid; - } - - public final Map getTasksByPriority() { - return this.tasksByPriority; - } - - public final Map getTasksByStatus() { - return this.tasksByStatus; - } - - public final Integer getTotalTasks() { - return this.totalTasks; - } - - public final Integer getTotalWorkers() { - return this.totalWorkers; - } - - public final String getWorkspaceSid() { - return this.workspaceSid; - } - - public final URI getUrl() { - return this.url; + this.workspaceSid = workspaceSid; } @Override @@ -193,40 +152,36 @@ public boolean equals(final Object o) { } WorkspaceRealTimeStatistics other = (WorkspaceRealTimeStatistics) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(activityStatistics, other.activityStatistics) && - Objects.equals( - longestTaskWaitingAge, - other.longestTaskWaitingAge - ) && - Objects.equals( - longestTaskWaitingSid, - other.longestTaskWaitingSid - ) && - Objects.equals(tasksByPriority, other.tasksByPriority) && - Objects.equals(tasksByStatus, other.tasksByStatus) && - Objects.equals(totalTasks, other.totalTasks) && - Objects.equals(totalWorkers, other.totalWorkers) && - Objects.equals(workspaceSid, other.workspaceSid) && - Objects.equals(url, other.url) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(activityStatistics, other.activityStatistics) && + Objects.equals(longestTaskWaitingAge, other.longestTaskWaitingAge) && + Objects.equals(longestTaskWaitingSid, other.longestTaskWaitingSid) && + Objects.equals(tasksByPriority, other.tasksByPriority) && + Objects.equals(tasksByStatus, other.tasksByStatus) && + Objects.equals(totalTasks, other.totalTasks) && + Objects.equals(totalWorkers, other.totalWorkers) && + Objects.equals(url, other.url) && + Objects.equals(workspaceSid, other.workspaceSid) ); } @Override public int hashCode() { return Objects.hash( - accountSid, - activityStatistics, - longestTaskWaitingAge, - longestTaskWaitingSid, - tasksByPriority, - tasksByStatus, - totalTasks, - totalWorkers, - workspaceSid, - url + accountSid, + activityStatistics, + longestTaskWaitingAge, + longestTaskWaitingSid, + tasksByPriority, + tasksByStatus, + totalTasks, + totalWorkers, + url, + workspaceSid ); } + + } + diff --git a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/WorkspaceRealTimeStatisticsFetcher.java b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/WorkspaceRealTimeStatisticsFetcher.java index 9b1409ab9f..019ffdd742 100644 --- a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/WorkspaceRealTimeStatisticsFetcher.java +++ b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/WorkspaceRealTimeStatisticsFetcher.java @@ -15,7 +15,8 @@ package com.twilio.rest.taskrouter.v1.workspace; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,69 +26,61 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class WorkspaceRealTimeStatisticsFetcher - extends Fetcher { +public class WorkspaceRealTimeStatisticsFetcher extends Fetcher { - private String pathWorkspaceSid; + private String pathworkspaceSid; private String taskChannel; - public WorkspaceRealTimeStatisticsFetcher(final String pathWorkspaceSid) { - this.pathWorkspaceSid = pathWorkspaceSid; + public WorkspaceRealTimeStatisticsFetcher(final String pathworkspaceSid) { + this.pathworkspaceSid = pathworkspaceSid; } - public WorkspaceRealTimeStatisticsFetcher setTaskChannel( - final String taskChannel - ) { + + public WorkspaceRealTimeStatisticsFetcher setTaskChannel(final String taskChannel) { this.taskChannel = taskChannel; return this; } + @Override public WorkspaceRealTimeStatistics fetch(final TwilioRestClient client) { + String path = "/v1/Workspaces/{WorkspaceSid}/RealTimeStatistics"; - path = - path.replace( - "{" + "WorkspaceSid" + "}", - this.pathWorkspaceSid.toString() - ); + path = path.replace("{" + "WorkspaceSid" + "}", this.pathworkspaceSid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.TASKROUTER.toString(), - path + HttpMethod.GET, + Domains.TASKROUTER.toString(), + path ); addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "WorkspaceRealTimeStatistics fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("WorkspaceRealTimeStatistics fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return WorkspaceRealTimeStatistics.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return WorkspaceRealTimeStatistics.fromJson(response.getStream(), client.getObjectMapper()); } private void addQueryParams(final Request request) { + + if (taskChannel != null) { - request.addQueryParam("TaskChannel", taskChannel); + Serializer.toString(request, "TaskChannel", taskChannel, ParameterType.QUERY); } + + } } diff --git a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/WorkspaceStatistics.java b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/WorkspaceStatistics.java index f6fd4dabee..b9fa542a55 100644 --- a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/WorkspaceStatistics.java +++ b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/WorkspaceStatistics.java @@ -18,43 +18,40 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; -import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class WorkspaceStatistics extends Resource { - private static final long serialVersionUID = 274987650256203L; - public static WorkspaceStatisticsFetcher fetcher( - final String pathWorkspaceSid - ) { - return new WorkspaceStatisticsFetcher(pathWorkspaceSid); + public static WorkspaceStatisticsFetcher fetcher(final String pathworkspaceSid) { + return new WorkspaceStatisticsFetcher( + pathworkspaceSid + ); } + /** * Converts a JSON String into a WorkspaceStatistics object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return WorkspaceStatistics object represented by the provided JSON */ - public static WorkspaceStatistics fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static WorkspaceStatistics fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, WorkspaceStatistics.class); @@ -69,14 +66,11 @@ public static WorkspaceStatistics fromJson( * Converts a JSON InputStream into a WorkspaceStatistics object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return WorkspaceStatistics object represented by the provided JSON */ - public static WorkspaceStatistics fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static WorkspaceStatistics fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, WorkspaceStatistics.class); @@ -87,45 +81,43 @@ public static WorkspaceStatistics fromJson( } } - private final Map realtime; - private final Map cumulative; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String workspaceSid; + @Getter + private final Object cumulative; + @Getter + private final Object realtime; + @Getter private final URI url; + @Getter + private final String workspaceSid; @JsonCreator private WorkspaceStatistics( - @JsonProperty("realtime") final Map realtime, - @JsonProperty("cumulative") final Map cumulative, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("workspace_sid") final String workspaceSid, - @JsonProperty("url") final URI url + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("cumulative") final Object cumulative, + @JsonProperty("realtime") final Object realtime, + @JsonProperty("url") final URI url, + @JsonProperty("workspace_sid") final String workspaceSid ) { - this.realtime = realtime; - this.cumulative = cumulative; this.accountSid = accountSid; - this.workspaceSid = workspaceSid; + this.cumulative = cumulative; + this.realtime = realtime; this.url = url; - } - - public final Map getRealtime() { - return this.realtime; - } - - public final Map getCumulative() { - return this.cumulative; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getWorkspaceSid() { - return this.workspaceSid; - } - - public final URI getUrl() { - return this.url; + this.workspaceSid = workspaceSid; } @Override @@ -139,24 +131,26 @@ public boolean equals(final Object o) { } WorkspaceStatistics other = (WorkspaceStatistics) o; - return ( - Objects.equals(realtime, other.realtime) && - Objects.equals(cumulative, other.cumulative) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(workspaceSid, other.workspaceSid) && - Objects.equals(url, other.url) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(cumulative, other.cumulative) && + Objects.equals(realtime, other.realtime) && + Objects.equals(url, other.url) && + Objects.equals(workspaceSid, other.workspaceSid) ); } @Override public int hashCode() { return Objects.hash( - realtime, - cumulative, - accountSid, - workspaceSid, - url + accountSid, + cumulative, + realtime, + url, + workspaceSid ); } + + } + diff --git a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/WorkspaceStatisticsFetcher.java b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/WorkspaceStatisticsFetcher.java index 4c5e751a5b..c2b1cb0a16 100644 --- a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/WorkspaceStatisticsFetcher.java +++ b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/WorkspaceStatisticsFetcher.java @@ -15,7 +15,8 @@ package com.twilio.rest.taskrouter.v1.workspace; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -24,113 +25,112 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.time.ZonedDateTime; public class WorkspaceStatisticsFetcher extends Fetcher { - private String pathWorkspaceSid; + private String pathworkspaceSid; private Integer minutes; private ZonedDateTime startDate; private ZonedDateTime endDate; private String taskChannel; private String splitByWaitTime; - public WorkspaceStatisticsFetcher(final String pathWorkspaceSid) { - this.pathWorkspaceSid = pathWorkspaceSid; + public WorkspaceStatisticsFetcher(final String pathworkspaceSid) { + this.pathworkspaceSid = pathworkspaceSid; } + public WorkspaceStatisticsFetcher setMinutes(final Integer minutes) { this.minutes = minutes; return this; } - public WorkspaceStatisticsFetcher setStartDate( - final ZonedDateTime startDate - ) { + + public WorkspaceStatisticsFetcher setStartDate(final ZonedDateTime startDate) { this.startDate = startDate; return this; } + public WorkspaceStatisticsFetcher setEndDate(final ZonedDateTime endDate) { this.endDate = endDate; return this; } + public WorkspaceStatisticsFetcher setTaskChannel(final String taskChannel) { this.taskChannel = taskChannel; return this; } - public WorkspaceStatisticsFetcher setSplitByWaitTime( - final String splitByWaitTime - ) { + + public WorkspaceStatisticsFetcher setSplitByWaitTime(final String splitByWaitTime) { this.splitByWaitTime = splitByWaitTime; return this; } + @Override public WorkspaceStatistics fetch(final TwilioRestClient client) { + String path = "/v1/Workspaces/{WorkspaceSid}/Statistics"; - path = - path.replace( - "{" + "WorkspaceSid" + "}", - this.pathWorkspaceSid.toString() - ); + path = path.replace("{" + "WorkspaceSid" + "}", this.pathworkspaceSid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.TASKROUTER.toString(), - path + HttpMethod.GET, + Domains.TASKROUTER.toString(), + path ); addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "WorkspaceStatistics fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("WorkspaceStatistics fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return WorkspaceStatistics.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return WorkspaceStatistics.fromJson(response.getStream(), client.getObjectMapper()); } private void addQueryParams(final Request request) { + + if (minutes != null) { - request.addQueryParam("Minutes", minutes.toString()); + Serializer.toString(request, "Minutes", minutes, ParameterType.QUERY); } + + if (startDate != null) { - request.addQueryParam( - "StartDate", - startDate.toInstant().toString() - ); + Serializer.toString(request, "StartDate", startDate, ParameterType.QUERY); } + if (endDate != null) { - request.addQueryParam("EndDate", endDate.toInstant().toString()); + Serializer.toString(request, "EndDate", endDate, ParameterType.QUERY); } + if (taskChannel != null) { - request.addQueryParam("TaskChannel", taskChannel); + Serializer.toString(request, "TaskChannel", taskChannel, ParameterType.QUERY); } + + if (splitByWaitTime != null) { - request.addQueryParam("SplitByWaitTime", splitByWaitTime); + Serializer.toString(request, "SplitByWaitTime", splitByWaitTime, ParameterType.QUERY); } + + } } diff --git a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/task/Reservation.java b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/task/Reservation.java index e3755218cc..88b366874e 100644 --- a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/task/Reservation.java +++ b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/task/Reservation.java @@ -18,222 +18,74 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Reservation extends Resource { - private static final long serialVersionUID = 88353198782173L; - - public static ReservationFetcher fetcher( - final String pathWorkspaceSid, - final String pathTaskSid, - final String pathSid - ) { - return new ReservationFetcher(pathWorkspaceSid, pathTaskSid, pathSid); - } - - public static ReservationReader reader( - final String pathWorkspaceSid, - final String pathTaskSid - ) { - return new ReservationReader(pathWorkspaceSid, pathTaskSid); - } - - public static ReservationUpdater updater( - final String pathWorkspaceSid, - final String pathTaskSid, - final String pathSid - ) { - return new ReservationUpdater(pathWorkspaceSid, pathTaskSid, pathSid); - } - - /** - * Converts a JSON String into a Reservation object using the provided ObjectMapper. - * - * @param json Raw JSON String - * @param objectMapper Jackson ObjectMapper - * @return Reservation object represented by the provided JSON - */ - public static Reservation fromJson( - final String json, - final ObjectMapper objectMapper - ) { - // Convert all checked exceptions to Runtime - try { - return objectMapper.readValue(json, Reservation.class); - } catch (final JsonMappingException | JsonParseException e) { - throw new ApiException(e.getMessage(), e); - } catch (final IOException e) { - throw new ApiConnectionException(e.getMessage(), e); - } - } - - /** - * Converts a JSON InputStream into a Reservation object using the provided - * ObjectMapper. - * - * @param json Raw JSON InputStream - * @param objectMapper Jackson ObjectMapper - * @return Reservation object represented by the provided JSON - */ - public static Reservation fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { - // Convert all checked exceptions to Runtime - try { - return objectMapper.readValue(json, Reservation.class); - } catch (final JsonMappingException | JsonParseException e) { - throw new ApiException(e.getMessage(), e); - } catch (final IOException e) { - throw new ApiConnectionException(e.getMessage(), e); - } - } - private final String accountSid; - private final ZonedDateTime dateCreated; - private final ZonedDateTime dateUpdated; - private final Reservation.Status reservationStatus; - private final String sid; - private final String taskSid; - private final String workerName; - private final String workerSid; - private final String workspaceSid; - private final URI url; - private final Map links; - - @JsonCreator - private Reservation( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty( - "reservation_status" - ) final Reservation.Status reservationStatus, - @JsonProperty("sid") final String sid, - @JsonProperty("task_sid") final String taskSid, - @JsonProperty("worker_name") final String workerName, - @JsonProperty("worker_sid") final String workerSid, - @JsonProperty("workspace_sid") final String workspaceSid, - @JsonProperty("url") final URI url, - @JsonProperty("links") final Map links - ) { - this.accountSid = accountSid; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); - this.reservationStatus = reservationStatus; - this.sid = sid; - this.taskSid = taskSid; - this.workerName = workerName; - this.workerSid = workerSid; - this.workspaceSid = workspaceSid; - this.url = url; - this.links = links; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final Reservation.Status getReservationStatus() { - return this.reservationStatus; + public static ReservationFetcher fetcher(final String pathworkspaceSid, final String pathtaskSid, final String pathsid) { + return new ReservationFetcher( + pathworkspaceSid, pathtaskSid, pathsid + ); } - public final String getSid() { - return this.sid; - } - public final String getTaskSid() { - return this.taskSid; + public static ReservationReader reader(final String pathworkspaceSid, final String pathtaskSid) { + return new ReservationReader( + pathworkspaceSid, pathtaskSid + ); } - public final String getWorkerName() { - return this.workerName; - } - public final String getWorkerSid() { - return this.workerSid; + public static ReservationUpdater updater(final String pathworkspaceSid, final String pathtaskSid, final String pathsid) { + return new ReservationUpdater( + pathworkspaceSid, pathtaskSid, pathsid + ); } - public final String getWorkspaceSid() { - return this.workspaceSid; - } - public final URI getUrl() { - return this.url; - } + public enum Status { + PENDING("pending"), + ACCEPTED("accepted"), + REJECTED("rejected"), + TIMEOUT("timeout"), + CANCELED("canceled"), + RESCINDED("rescinded"), + WRAPPING("wrapping"), + COMPLETED("completed"); - public final Map getLinks() { - return this.links; - } + private final String value; - @Override - public boolean equals(final Object o) { - if (this == o) { - return true; + private Status(final String value) { + this.value = value; } - if (o == null || getClass() != o.getClass()) { - return false; + public String toString() { + return value; } - Reservation other = (Reservation) o; - - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(reservationStatus, other.reservationStatus) && - Objects.equals(sid, other.sid) && - Objects.equals(taskSid, other.taskSid) && - Objects.equals(workerName, other.workerName) && - Objects.equals(workerSid, other.workerSid) && - Objects.equals(workspaceSid, other.workspaceSid) && - Objects.equals(url, other.url) && - Objects.equals(links, other.links) - ); - } - - @Override - public int hashCode() { - return Objects.hash( - accountSid, - dateCreated, - dateUpdated, - reservationStatus, - sid, - taskSid, - workerName, - workerSid, - workspaceSid, - url, - links - ); + @JsonCreator + public static Status forValue(final String value) { + return Promoter.enumFromString(value, Status.values()); + } } public enum SupervisorMode { @@ -257,19 +109,15 @@ public static SupervisorMode forValue(final String value) { } } - public enum Status { - PENDING("pending"), - ACCEPTED("accepted"), - REJECTED("rejected"), - TIMEOUT("timeout"), - CANCELED("canceled"), - RESCINDED("rescinded"), - WRAPPING("wrapping"), + public enum CallStatus { + INITIATED("initiated"), + RINGING("ringing"), + ANSWERED("answered"), COMPLETED("completed"); private final String value; - private Status(final String value) { + private CallStatus(final String value) { this.value = value; } @@ -278,8 +126,8 @@ public String toString() { } @JsonCreator - public static Status forValue(final String value) { - return Promoter.enumFromString(value, Status.values()); + public static CallStatus forValue(final String value) { + return Promoter.enumFromString(value, CallStatus.values()); } } @@ -308,25 +156,152 @@ public static ConferenceEvent forValue(final String value) { } } - public enum CallStatus { - INITIATED("initiated"), - RINGING("ringing"), - ANSWERED("answered"), - COMPLETED("completed"); - private final String value; + /** + * Converts a JSON String into a Reservation object using the provided ObjectMapper. + * + * @param json Raw JSON String + * @param objectMapper Jackson ObjectMapper + * @return Reservation object represented by the provided JSON + */ + public static Reservation fromJson(final String json, final ObjectMapper objectMapper) { + // Convert all checked exceptions to Runtime + try { + return objectMapper.readValue(json, Reservation.class); + } catch (final JsonMappingException | JsonParseException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } - private CallStatus(final String value) { - this.value = value; + /** + * Converts a JSON InputStream into a Reservation object using the provided + * ObjectMapper. + * + * @param json Raw JSON InputStream + * @param objectMapper Jackson ObjectMapper + * @return Reservation object represented by the provided JSON + */ + public static Reservation fromJson(final InputStream json, final ObjectMapper objectMapper) { + // Convert all checked exceptions to Runtime + try { + return objectMapper.readValue(json, Reservation.class); + } catch (final JsonMappingException | JsonParseException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); } + } - public String toString() { - return value; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); } + } - @JsonCreator - public static CallStatus forValue(final String value) { - return Promoter.enumFromString(value, CallStatus.values()); + + @Getter + private final String accountSid; + @Getter + private final ZonedDateTime dateCreated; + @Getter + private final ZonedDateTime dateUpdated; + @Getter + private final Map links; + @Getter + private final Reservation.Status reservationStatus; + @Getter + private final String sid; + @Getter + private final String taskSid; + @Getter + private final URI url; + @Getter + private final String workerName; + @Getter + private final String workerSid; + @Getter + private final String workspaceSid; + + @JsonCreator + private Reservation( + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("links") final Map links, + @JsonProperty("reservation_status") final Reservation.Status reservationStatus, + @JsonProperty("sid") final String sid, + @JsonProperty("task_sid") final String taskSid, + @JsonProperty("url") final URI url, + @JsonProperty("worker_name") final String workerName, + @JsonProperty("worker_sid") final String workerSid, + @JsonProperty("workspace_sid") final String workspaceSid + ) { + this.accountSid = accountSid; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; + this.links = links; + this.reservationStatus = reservationStatus; + this.sid = sid; + this.taskSid = taskSid; + this.url = url; + this.workerName = workerName; + this.workerSid = workerSid; + this.workspaceSid = workspaceSid; + } + + @Override + public boolean equals(final Object o) { + if (this == o) { + return true; } + + if (o == null || getClass() != o.getClass()) { + return false; + } + + Reservation other = (Reservation) o; + return ( + Objects.equals(accountSid, other.accountSid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(links, other.links) && + Objects.equals(reservationStatus, other.reservationStatus) && + Objects.equals(sid, other.sid) && + Objects.equals(taskSid, other.taskSid) && + Objects.equals(url, other.url) && + Objects.equals(workerName, other.workerName) && + Objects.equals(workerSid, other.workerSid) && + Objects.equals(workspaceSid, other.workspaceSid) + ); + } + + @Override + public int hashCode() { + return Objects.hash( + accountSid, + dateCreated, + dateUpdated, + links, + reservationStatus, + sid, + taskSid, + url, + workerName, + workerSid, + workspaceSid + ); } + + } + diff --git a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/task/ReservationFetcher.java b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/task/ReservationFetcher.java index 533d13aee5..7cff205cd3 100644 --- a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/task/ReservationFetcher.java +++ b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/task/ReservationFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.taskrouter.v1.workspace.task; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,62 +26,47 @@ public class ReservationFetcher extends Fetcher { - private String pathWorkspaceSid; - private String pathTaskSid; - private String pathSid; + private String pathworkspaceSid; + private String pathtaskSid; + private String pathsid; - public ReservationFetcher( - final String pathWorkspaceSid, - final String pathTaskSid, - final String pathSid - ) { - this.pathWorkspaceSid = pathWorkspaceSid; - this.pathTaskSid = pathTaskSid; - this.pathSid = pathSid; + public ReservationFetcher(final String pathworkspaceSid, final String pathtaskSid, final String pathsid) { + this.pathworkspaceSid = pathworkspaceSid; + this.pathtaskSid = pathtaskSid; + this.pathsid = pathsid; } + @Override public Reservation fetch(final TwilioRestClient client) { - String path = - "/v1/Workspaces/{WorkspaceSid}/Tasks/{TaskSid}/Reservations/{Sid}"; - path = - path.replace( - "{" + "WorkspaceSid" + "}", - this.pathWorkspaceSid.toString() - ); - path = path.replace("{" + "TaskSid" + "}", this.pathTaskSid.toString()); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/v1/Workspaces/{WorkspaceSid}/Tasks/{TaskSid}/Reservations/{Sid}"; + + path = path.replace("{" + "WorkspaceSid" + "}", this.pathworkspaceSid.toString()); + path = path.replace("{" + "TaskSid" + "}", this.pathtaskSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.TASKROUTER.toString(), - path + HttpMethod.GET, + Domains.TASKROUTER.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Reservation fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Reservation fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return Reservation.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Reservation.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/task/ReservationReader.java b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/task/ReservationReader.java index 0b921b4766..47df81512b 100644 --- a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/task/ReservationReader.java +++ b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/task/ReservationReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,145 +30,115 @@ public class ReservationReader extends Reader { - private String pathWorkspaceSid; - private String pathTaskSid; + private String pathworkspaceSid; + private String pathtaskSid; private Reservation.Status reservationStatus; private String workerSid; private Long pageSize; - public ReservationReader( - final String pathWorkspaceSid, - final String pathTaskSid - ) { - this.pathWorkspaceSid = pathWorkspaceSid; - this.pathTaskSid = pathTaskSid; + public ReservationReader(final String pathworkspaceSid, final String pathtaskSid) { + this.pathworkspaceSid = pathworkspaceSid; + this.pathtaskSid = pathtaskSid; } - public ReservationReader setReservationStatus( - final Reservation.Status reservationStatus - ) { + + public ReservationReader setReservationStatus(final Reservation.Status reservationStatus) { this.reservationStatus = reservationStatus; return this; } + public ReservationReader setWorkerSid(final String workerSid) { this.workerSid = workerSid; return this; } + public ReservationReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { - String path = - "/v1/Workspaces/{WorkspaceSid}/Tasks/{TaskSid}/Reservations"; - path = - path.replace( - "{" + "WorkspaceSid" + "}", - this.pathWorkspaceSid.toString() - ); - path = path.replace("{" + "TaskSid" + "}", this.pathTaskSid.toString()); + + String path = "/v1/Workspaces/{WorkspaceSid}/Tasks/{TaskSid}/Reservations"; + + path = path.replace("{" + "WorkspaceSid" + "}", this.pathworkspaceSid.toString()); + path = path.replace("{" + "TaskSid" + "}", this.pathtaskSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.TASKROUTER.toString(), - path + HttpMethod.GET, + Domains.TASKROUTER.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Reservation read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Reservation read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "reservations", - response.getContent(), - Reservation.class, - client.getObjectMapper() - ); + "reservations", + response.getContent(), + Reservation.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.TASKROUTER.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.TASKROUTER.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (reservationStatus != null) { - request.addQueryParam( - "ReservationStatus", - reservationStatus.toString() - ); + Serializer.toString(request, "ReservationStatus", reservationStatus, ParameterType.QUERY); } + + if (workerSid != null) { - request.addQueryParam("WorkerSid", workerSid); + Serializer.toString(request, "WorkerSid", workerSid, ParameterType.QUERY); } + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/task/ReservationUpdater.java b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/task/ReservationUpdater.java index 075580d6d9..3b485de643 100644 --- a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/task/ReservationUpdater.java +++ b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/task/ReservationUpdater.java @@ -16,7 +16,9 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; import com.twilio.converter.Promoter; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,14 +27,14 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.net.URI; import java.util.List; public class ReservationUpdater extends Updater { - - private String pathWorkspaceSid; - private String pathTaskSid; - private String pathSid; + private String pathworkspaceSid; + private String pathtaskSid; + private String pathsid; private String ifMatch; private Reservation.Status reservationStatus; private String workerActivitySid; @@ -89,186 +91,157 @@ public class ReservationUpdater extends Updater { private Boolean beepOnCustomerEntrance; private String jitterBufferSize; - public ReservationUpdater( - final String pathWorkspaceSid, - final String pathTaskSid, - final String pathSid - ) { - this.pathWorkspaceSid = pathWorkspaceSid; - this.pathTaskSid = pathTaskSid; - this.pathSid = pathSid; + public ReservationUpdater(final String pathworkspaceSid, final String pathtaskSid, final String pathsid) { + this.pathworkspaceSid = pathworkspaceSid; + this.pathtaskSid = pathtaskSid; + this.pathsid = pathsid; } - public ReservationUpdater setIfMatch(final String ifMatch) { - this.ifMatch = ifMatch; - return this; - } - public ReservationUpdater setReservationStatus( - final Reservation.Status reservationStatus - ) { + public ReservationUpdater setReservationStatus(final Reservation.Status reservationStatus) { this.reservationStatus = reservationStatus; return this; } - public ReservationUpdater setWorkerActivitySid( - final String workerActivitySid - ) { + + public ReservationUpdater setWorkerActivitySid(final String workerActivitySid) { this.workerActivitySid = workerActivitySid; return this; } + public ReservationUpdater setInstruction(final String instruction) { this.instruction = instruction; return this; } - public ReservationUpdater setDequeuePostWorkActivitySid( - final String dequeuePostWorkActivitySid - ) { + + public ReservationUpdater setDequeuePostWorkActivitySid(final String dequeuePostWorkActivitySid) { this.dequeuePostWorkActivitySid = dequeuePostWorkActivitySid; return this; } + public ReservationUpdater setDequeueFrom(final String dequeueFrom) { this.dequeueFrom = dequeueFrom; return this; } + public ReservationUpdater setDequeueRecord(final String dequeueRecord) { this.dequeueRecord = dequeueRecord; return this; } + public ReservationUpdater setDequeueTimeout(final Integer dequeueTimeout) { this.dequeueTimeout = dequeueTimeout; return this; } + public ReservationUpdater setDequeueTo(final String dequeueTo) { this.dequeueTo = dequeueTo; return this; } - public ReservationUpdater setDequeueStatusCallbackUrl( - final URI dequeueStatusCallbackUrl - ) { + + public ReservationUpdater setDequeueStatusCallbackUrl(final URI dequeueStatusCallbackUrl) { this.dequeueStatusCallbackUrl = dequeueStatusCallbackUrl; return this; } - public ReservationUpdater setDequeueStatusCallbackUrl( - final String dequeueStatusCallbackUrl - ) { - return setDequeueStatusCallbackUrl( - Promoter.uriFromString(dequeueStatusCallbackUrl) - ); - } public ReservationUpdater setCallFrom(final String callFrom) { this.callFrom = callFrom; return this; } + public ReservationUpdater setCallRecord(final String callRecord) { this.callRecord = callRecord; return this; } + public ReservationUpdater setCallTimeout(final Integer callTimeout) { this.callTimeout = callTimeout; return this; } + public ReservationUpdater setCallTo(final String callTo) { this.callTo = callTo; return this; } + public ReservationUpdater setCallUrl(final URI callUrl) { this.callUrl = callUrl; return this; } - public ReservationUpdater setCallUrl(final String callUrl) { - return setCallUrl(Promoter.uriFromString(callUrl)); - } - public ReservationUpdater setCallStatusCallbackUrl( - final URI callStatusCallbackUrl - ) { + public ReservationUpdater setCallStatusCallbackUrl(final URI callStatusCallbackUrl) { this.callStatusCallbackUrl = callStatusCallbackUrl; return this; } - public ReservationUpdater setCallStatusCallbackUrl( - final String callStatusCallbackUrl - ) { - return setCallStatusCallbackUrl( - Promoter.uriFromString(callStatusCallbackUrl) - ); - } public ReservationUpdater setCallAccept(final Boolean callAccept) { this.callAccept = callAccept; return this; } + public ReservationUpdater setRedirectCallSid(final String redirectCallSid) { this.redirectCallSid = redirectCallSid; return this; } + public ReservationUpdater setRedirectAccept(final Boolean redirectAccept) { this.redirectAccept = redirectAccept; return this; } + public ReservationUpdater setRedirectUrl(final URI redirectUrl) { this.redirectUrl = redirectUrl; return this; } - public ReservationUpdater setRedirectUrl(final String redirectUrl) { - return setRedirectUrl(Promoter.uriFromString(redirectUrl)); - } public ReservationUpdater setTo(final String to) { this.to = to; return this; } + public ReservationUpdater setFrom(final String from) { this.from = from; return this; } + public ReservationUpdater setStatusCallback(final URI statusCallback) { this.statusCallback = statusCallback; return this; } - public ReservationUpdater setStatusCallback(final String statusCallback) { - return setStatusCallback(Promoter.uriFromString(statusCallback)); - } - public ReservationUpdater setStatusCallbackMethod( - final HttpMethod statusCallbackMethod - ) { + public ReservationUpdater setStatusCallbackMethod(final HttpMethod statusCallbackMethod) { this.statusCallbackMethod = statusCallbackMethod; return this; } - public ReservationUpdater setStatusCallbackEvent( - final List statusCallbackEvent - ) { + + public ReservationUpdater setStatusCallbackEvent(final List statusCallbackEvent) { this.statusCallbackEvent = statusCallbackEvent; return this; } - public ReservationUpdater setStatusCallbackEvent( - final Reservation.CallStatus statusCallbackEvent - ) { + public ReservationUpdater setStatusCallbackEvent(final Reservation.CallStatus statusCallbackEvent) { return setStatusCallbackEvent(Promoter.listOfOne(statusCallbackEvent)); } @@ -277,501 +250,515 @@ public ReservationUpdater setTimeout(final Integer timeout) { return this; } + public ReservationUpdater setRecord(final Boolean record) { this.record = record; return this; } + public ReservationUpdater setMuted(final Boolean muted) { this.muted = muted; return this; } + public ReservationUpdater setBeep(final String beep) { this.beep = beep; return this; } - public ReservationUpdater setStartConferenceOnEnter( - final Boolean startConferenceOnEnter - ) { + + public ReservationUpdater setStartConferenceOnEnter(final Boolean startConferenceOnEnter) { this.startConferenceOnEnter = startConferenceOnEnter; return this; } - public ReservationUpdater setEndConferenceOnExit( - final Boolean endConferenceOnExit - ) { + + public ReservationUpdater setEndConferenceOnExit(final Boolean endConferenceOnExit) { this.endConferenceOnExit = endConferenceOnExit; return this; } + public ReservationUpdater setWaitUrl(final URI waitUrl) { this.waitUrl = waitUrl; return this; } - public ReservationUpdater setWaitUrl(final String waitUrl) { - return setWaitUrl(Promoter.uriFromString(waitUrl)); - } public ReservationUpdater setWaitMethod(final HttpMethod waitMethod) { this.waitMethod = waitMethod; return this; } + public ReservationUpdater setEarlyMedia(final Boolean earlyMedia) { this.earlyMedia = earlyMedia; return this; } - public ReservationUpdater setMaxParticipants( - final Integer maxParticipants - ) { + + public ReservationUpdater setMaxParticipants(final Integer maxParticipants) { this.maxParticipants = maxParticipants; return this; } - public ReservationUpdater setConferenceStatusCallback( - final URI conferenceStatusCallback - ) { + + public ReservationUpdater setConferenceStatusCallback(final URI conferenceStatusCallback) { this.conferenceStatusCallback = conferenceStatusCallback; return this; } - public ReservationUpdater setConferenceStatusCallback( - final String conferenceStatusCallback - ) { - return setConferenceStatusCallback( - Promoter.uriFromString(conferenceStatusCallback) - ); - } - public ReservationUpdater setConferenceStatusCallbackMethod( - final HttpMethod conferenceStatusCallbackMethod - ) { + public ReservationUpdater setConferenceStatusCallbackMethod(final HttpMethod conferenceStatusCallbackMethod) { this.conferenceStatusCallbackMethod = conferenceStatusCallbackMethod; return this; } - public ReservationUpdater setConferenceStatusCallbackEvent( - final List conferenceStatusCallbackEvent - ) { + + public ReservationUpdater setConferenceStatusCallbackEvent(final List conferenceStatusCallbackEvent) { this.conferenceStatusCallbackEvent = conferenceStatusCallbackEvent; return this; } - public ReservationUpdater setConferenceStatusCallbackEvent( - final Reservation.ConferenceEvent conferenceStatusCallbackEvent - ) { - return setConferenceStatusCallbackEvent( - Promoter.listOfOne(conferenceStatusCallbackEvent) - ); + public ReservationUpdater setConferenceStatusCallbackEvent(final Reservation.ConferenceEvent conferenceStatusCallbackEvent) { + return setConferenceStatusCallbackEvent(Promoter.listOfOne(conferenceStatusCallbackEvent)); } - public ReservationUpdater setConferenceRecord( - final String conferenceRecord - ) { + public ReservationUpdater setConferenceRecord(final String conferenceRecord) { this.conferenceRecord = conferenceRecord; return this; } + public ReservationUpdater setConferenceTrim(final String conferenceTrim) { this.conferenceTrim = conferenceTrim; return this; } - public ReservationUpdater setRecordingChannels( - final String recordingChannels - ) { + + public ReservationUpdater setRecordingChannels(final String recordingChannels) { this.recordingChannels = recordingChannels; return this; } - public ReservationUpdater setRecordingStatusCallback( - final URI recordingStatusCallback - ) { + + public ReservationUpdater setRecordingStatusCallback(final URI recordingStatusCallback) { this.recordingStatusCallback = recordingStatusCallback; return this; } - public ReservationUpdater setRecordingStatusCallback( - final String recordingStatusCallback - ) { - return setRecordingStatusCallback( - Promoter.uriFromString(recordingStatusCallback) - ); - } - public ReservationUpdater setRecordingStatusCallbackMethod( - final HttpMethod recordingStatusCallbackMethod - ) { + public ReservationUpdater setRecordingStatusCallbackMethod(final HttpMethod recordingStatusCallbackMethod) { this.recordingStatusCallbackMethod = recordingStatusCallbackMethod; return this; } - public ReservationUpdater setConferenceRecordingStatusCallback( - final URI conferenceRecordingStatusCallback - ) { - this.conferenceRecordingStatusCallback = - conferenceRecordingStatusCallback; + + public ReservationUpdater setConferenceRecordingStatusCallback(final URI conferenceRecordingStatusCallback) { + this.conferenceRecordingStatusCallback = conferenceRecordingStatusCallback; return this; } - public ReservationUpdater setConferenceRecordingStatusCallback( - final String conferenceRecordingStatusCallback - ) { - return setConferenceRecordingStatusCallback( - Promoter.uriFromString(conferenceRecordingStatusCallback) - ); - } - public ReservationUpdater setConferenceRecordingStatusCallbackMethod( - final HttpMethod conferenceRecordingStatusCallbackMethod - ) { - this.conferenceRecordingStatusCallbackMethod = - conferenceRecordingStatusCallbackMethod; + public ReservationUpdater setConferenceRecordingStatusCallbackMethod(final HttpMethod conferenceRecordingStatusCallbackMethod) { + this.conferenceRecordingStatusCallbackMethod = conferenceRecordingStatusCallbackMethod; return this; } + public ReservationUpdater setRegion(final String region) { this.region = region; return this; } + public ReservationUpdater setSipAuthUsername(final String sipAuthUsername) { this.sipAuthUsername = sipAuthUsername; return this; } + public ReservationUpdater setSipAuthPassword(final String sipAuthPassword) { this.sipAuthPassword = sipAuthPassword; return this; } - public ReservationUpdater setDequeueStatusCallbackEvent( - final List dequeueStatusCallbackEvent - ) { + + public ReservationUpdater setDequeueStatusCallbackEvent(final List dequeueStatusCallbackEvent) { this.dequeueStatusCallbackEvent = dequeueStatusCallbackEvent; return this; } - public ReservationUpdater setDequeueStatusCallbackEvent( - final String dequeueStatusCallbackEvent - ) { - return setDequeueStatusCallbackEvent( - Promoter.listOfOne(dequeueStatusCallbackEvent) - ); + public ReservationUpdater setDequeueStatusCallbackEvent(final String dequeueStatusCallbackEvent) { + return setDequeueStatusCallbackEvent(Promoter.listOfOne(dequeueStatusCallbackEvent)); } - public ReservationUpdater setPostWorkActivitySid( - final String postWorkActivitySid - ) { + public ReservationUpdater setPostWorkActivitySid(final String postWorkActivitySid) { this.postWorkActivitySid = postWorkActivitySid; return this; } - public ReservationUpdater setSupervisorMode( - final Reservation.SupervisorMode supervisorMode - ) { + + public ReservationUpdater setSupervisorMode(final Reservation.SupervisorMode supervisorMode) { this.supervisorMode = supervisorMode; return this; } + public ReservationUpdater setSupervisor(final String supervisor) { this.supervisor = supervisor; return this; } - public ReservationUpdater setEndConferenceOnCustomerExit( - final Boolean endConferenceOnCustomerExit - ) { + + public ReservationUpdater setEndConferenceOnCustomerExit(final Boolean endConferenceOnCustomerExit) { this.endConferenceOnCustomerExit = endConferenceOnCustomerExit; return this; } - public ReservationUpdater setBeepOnCustomerEntrance( - final Boolean beepOnCustomerEntrance - ) { + + public ReservationUpdater setBeepOnCustomerEntrance(final Boolean beepOnCustomerEntrance) { this.beepOnCustomerEntrance = beepOnCustomerEntrance; return this; } - public ReservationUpdater setJitterBufferSize( - final String jitterBufferSize - ) { + + public ReservationUpdater setJitterBufferSize(final String jitterBufferSize) { this.jitterBufferSize = jitterBufferSize; return this; } + + public ReservationUpdater setIfMatch(final String ifMatch) { + this.ifMatch = ifMatch; + return this; + } + + @Override public Reservation update(final TwilioRestClient client) { - String path = - "/v1/Workspaces/{WorkspaceSid}/Tasks/{TaskSid}/Reservations/{Sid}"; - path = - path.replace( - "{" + "WorkspaceSid" + "}", - this.pathWorkspaceSid.toString() - ); - path = path.replace("{" + "TaskSid" + "}", this.pathTaskSid.toString()); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/v1/Workspaces/{WorkspaceSid}/Tasks/{TaskSid}/Reservations/{Sid}"; + + path = path.replace("{" + "WorkspaceSid" + "}", this.pathworkspaceSid.toString()); + path = path.replace("{" + "TaskSid" + "}", this.pathtaskSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.TASKROUTER.toString(), - path + HttpMethod.POST, + Domains.TASKROUTER.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); - addPostParams(request); addHeaderParams(request); + addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Reservation update failed: Unable to connect to server" - ); + throw new ApiConnectionException("Reservation update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Reservation.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Reservation.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (reservationStatus != null) { - request.addPostParam( - "ReservationStatus", - reservationStatus.toString() - ); + Serializer.toString(request, "ReservationStatus", reservationStatus, ParameterType.URLENCODED); } + + if (workerActivitySid != null) { - request.addPostParam("WorkerActivitySid", workerActivitySid); + Serializer.toString(request, "WorkerActivitySid", workerActivitySid, ParameterType.URLENCODED); } + + if (instruction != null) { - request.addPostParam("Instruction", instruction); + Serializer.toString(request, "Instruction", instruction, ParameterType.URLENCODED); } + + if (dequeuePostWorkActivitySid != null) { - request.addPostParam( - "DequeuePostWorkActivitySid", - dequeuePostWorkActivitySid - ); + Serializer.toString(request, "DequeuePostWorkActivitySid", dequeuePostWorkActivitySid, ParameterType.URLENCODED); } + + if (dequeueFrom != null) { - request.addPostParam("DequeueFrom", dequeueFrom); + Serializer.toString(request, "DequeueFrom", dequeueFrom, ParameterType.URLENCODED); } + + if (dequeueRecord != null) { - request.addPostParam("DequeueRecord", dequeueRecord); + Serializer.toString(request, "DequeueRecord", dequeueRecord, ParameterType.URLENCODED); } + + if (dequeueTimeout != null) { - request.addPostParam("DequeueTimeout", dequeueTimeout.toString()); + Serializer.toString(request, "DequeueTimeout", dequeueTimeout, ParameterType.URLENCODED); } + + if (dequeueTo != null) { - request.addPostParam("DequeueTo", dequeueTo); + Serializer.toString(request, "DequeueTo", dequeueTo, ParameterType.URLENCODED); } + + if (dequeueStatusCallbackUrl != null) { - request.addPostParam( - "DequeueStatusCallbackUrl", - dequeueStatusCallbackUrl.toString() - ); + Serializer.toString(request, "DequeueStatusCallbackUrl", dequeueStatusCallbackUrl, ParameterType.URLENCODED); } + + if (callFrom != null) { - request.addPostParam("CallFrom", callFrom); + Serializer.toString(request, "CallFrom", callFrom, ParameterType.URLENCODED); } + + if (callRecord != null) { - request.addPostParam("CallRecord", callRecord); + Serializer.toString(request, "CallRecord", callRecord, ParameterType.URLENCODED); } + + if (callTimeout != null) { - request.addPostParam("CallTimeout", callTimeout.toString()); + Serializer.toString(request, "CallTimeout", callTimeout, ParameterType.URLENCODED); } + + if (callTo != null) { - request.addPostParam("CallTo", callTo); + Serializer.toString(request, "CallTo", callTo, ParameterType.URLENCODED); } + + if (callUrl != null) { - request.addPostParam("CallUrl", callUrl.toString()); + Serializer.toString(request, "CallUrl", callUrl, ParameterType.URLENCODED); } + + if (callStatusCallbackUrl != null) { - request.addPostParam( - "CallStatusCallbackUrl", - callStatusCallbackUrl.toString() - ); + Serializer.toString(request, "CallStatusCallbackUrl", callStatusCallbackUrl, ParameterType.URLENCODED); } + + if (callAccept != null) { - request.addPostParam("CallAccept", callAccept.toString()); + Serializer.toString(request, "CallAccept", callAccept, ParameterType.URLENCODED); } + + if (redirectCallSid != null) { - request.addPostParam("RedirectCallSid", redirectCallSid); + Serializer.toString(request, "RedirectCallSid", redirectCallSid, ParameterType.URLENCODED); } + + if (redirectAccept != null) { - request.addPostParam("RedirectAccept", redirectAccept.toString()); + Serializer.toString(request, "RedirectAccept", redirectAccept, ParameterType.URLENCODED); } + + if (redirectUrl != null) { - request.addPostParam("RedirectUrl", redirectUrl.toString()); + Serializer.toString(request, "RedirectUrl", redirectUrl, ParameterType.URLENCODED); } + + if (to != null) { - request.addPostParam("To", to); + Serializer.toString(request, "To", to, ParameterType.URLENCODED); } + + if (from != null) { - request.addPostParam("From", from); + Serializer.toString(request, "From", from, ParameterType.URLENCODED); } + + if (statusCallback != null) { - request.addPostParam("StatusCallback", statusCallback.toString()); + Serializer.toString(request, "StatusCallback", statusCallback, ParameterType.URLENCODED); } + + if (statusCallbackMethod != null) { - request.addPostParam( - "StatusCallbackMethod", - statusCallbackMethod.toString() - ); + Serializer.toString(request, "StatusCallbackMethod", statusCallbackMethod, ParameterType.URLENCODED); } + + if (statusCallbackEvent != null) { - for (Reservation.CallStatus prop : statusCallbackEvent) { - request.addPostParam("StatusCallbackEvent", prop.toString()); + for (Reservation.CallStatus param : statusCallbackEvent) { + Serializer.toString(request, "StatusCallbackEvent", param, ParameterType.URLENCODED); } } + + if (timeout != null) { - request.addPostParam("Timeout", timeout.toString()); + Serializer.toString(request, "Timeout", timeout, ParameterType.URLENCODED); } + + if (record != null) { - request.addPostParam("Record", record.toString()); + Serializer.toString(request, "Record", record, ParameterType.URLENCODED); } + + if (muted != null) { - request.addPostParam("Muted", muted.toString()); + Serializer.toString(request, "Muted", muted, ParameterType.URLENCODED); } + + if (beep != null) { - request.addPostParam("Beep", beep); + Serializer.toString(request, "Beep", beep, ParameterType.URLENCODED); } + + if (startConferenceOnEnter != null) { - request.addPostParam( - "StartConferenceOnEnter", - startConferenceOnEnter.toString() - ); + Serializer.toString(request, "StartConferenceOnEnter", startConferenceOnEnter, ParameterType.URLENCODED); } + + if (endConferenceOnExit != null) { - request.addPostParam( - "EndConferenceOnExit", - endConferenceOnExit.toString() - ); + Serializer.toString(request, "EndConferenceOnExit", endConferenceOnExit, ParameterType.URLENCODED); } + + if (waitUrl != null) { - request.addPostParam("WaitUrl", waitUrl.toString()); + Serializer.toString(request, "WaitUrl", waitUrl, ParameterType.URLENCODED); } + + if (waitMethod != null) { - request.addPostParam("WaitMethod", waitMethod.toString()); + Serializer.toString(request, "WaitMethod", waitMethod, ParameterType.URLENCODED); } + + if (earlyMedia != null) { - request.addPostParam("EarlyMedia", earlyMedia.toString()); + Serializer.toString(request, "EarlyMedia", earlyMedia, ParameterType.URLENCODED); } + + if (maxParticipants != null) { - request.addPostParam("MaxParticipants", maxParticipants.toString()); + Serializer.toString(request, "MaxParticipants", maxParticipants, ParameterType.URLENCODED); } + + if (conferenceStatusCallback != null) { - request.addPostParam( - "ConferenceStatusCallback", - conferenceStatusCallback.toString() - ); + Serializer.toString(request, "ConferenceStatusCallback", conferenceStatusCallback, ParameterType.URLENCODED); } + + if (conferenceStatusCallbackMethod != null) { - request.addPostParam( - "ConferenceStatusCallbackMethod", - conferenceStatusCallbackMethod.toString() - ); + Serializer.toString(request, "ConferenceStatusCallbackMethod", conferenceStatusCallbackMethod, ParameterType.URLENCODED); } + + if (conferenceStatusCallbackEvent != null) { - for (Reservation.ConferenceEvent prop : conferenceStatusCallbackEvent) { - request.addPostParam( - "ConferenceStatusCallbackEvent", - prop.toString() - ); + for (Reservation.ConferenceEvent param : conferenceStatusCallbackEvent) { + Serializer.toString(request, "ConferenceStatusCallbackEvent", param, ParameterType.URLENCODED); } } + + if (conferenceRecord != null) { - request.addPostParam("ConferenceRecord", conferenceRecord); + Serializer.toString(request, "ConferenceRecord", conferenceRecord, ParameterType.URLENCODED); } + + if (conferenceTrim != null) { - request.addPostParam("ConferenceTrim", conferenceTrim); + Serializer.toString(request, "ConferenceTrim", conferenceTrim, ParameterType.URLENCODED); } + + if (recordingChannels != null) { - request.addPostParam("RecordingChannels", recordingChannels); + Serializer.toString(request, "RecordingChannels", recordingChannels, ParameterType.URLENCODED); } + + if (recordingStatusCallback != null) { - request.addPostParam( - "RecordingStatusCallback", - recordingStatusCallback.toString() - ); + Serializer.toString(request, "RecordingStatusCallback", recordingStatusCallback, ParameterType.URLENCODED); } + + if (recordingStatusCallbackMethod != null) { - request.addPostParam( - "RecordingStatusCallbackMethod", - recordingStatusCallbackMethod.toString() - ); + Serializer.toString(request, "RecordingStatusCallbackMethod", recordingStatusCallbackMethod, ParameterType.URLENCODED); } + + if (conferenceRecordingStatusCallback != null) { - request.addPostParam( - "ConferenceRecordingStatusCallback", - conferenceRecordingStatusCallback.toString() - ); + Serializer.toString(request, "ConferenceRecordingStatusCallback", conferenceRecordingStatusCallback, ParameterType.URLENCODED); } + + if (conferenceRecordingStatusCallbackMethod != null) { - request.addPostParam( - "ConferenceRecordingStatusCallbackMethod", - conferenceRecordingStatusCallbackMethod.toString() - ); + Serializer.toString(request, "ConferenceRecordingStatusCallbackMethod", conferenceRecordingStatusCallbackMethod, ParameterType.URLENCODED); } + + if (region != null) { - request.addPostParam("Region", region); + Serializer.toString(request, "Region", region, ParameterType.URLENCODED); } + + if (sipAuthUsername != null) { - request.addPostParam("SipAuthUsername", sipAuthUsername); + Serializer.toString(request, "SipAuthUsername", sipAuthUsername, ParameterType.URLENCODED); } + + if (sipAuthPassword != null) { - request.addPostParam("SipAuthPassword", sipAuthPassword); + Serializer.toString(request, "SipAuthPassword", sipAuthPassword, ParameterType.URLENCODED); } + + if (dequeueStatusCallbackEvent != null) { - for (String prop : dequeueStatusCallbackEvent) { - request.addPostParam("DequeueStatusCallbackEvent", prop); + for (String param : dequeueStatusCallbackEvent) { + Serializer.toString(request, "DequeueStatusCallbackEvent", param, ParameterType.URLENCODED); } } + + if (postWorkActivitySid != null) { - request.addPostParam("PostWorkActivitySid", postWorkActivitySid); + Serializer.toString(request, "PostWorkActivitySid", postWorkActivitySid, ParameterType.URLENCODED); } + + if (supervisorMode != null) { - request.addPostParam("SupervisorMode", supervisorMode.toString()); + Serializer.toString(request, "SupervisorMode", supervisorMode, ParameterType.URLENCODED); } + + if (supervisor != null) { - request.addPostParam("Supervisor", supervisor); + Serializer.toString(request, "Supervisor", supervisor, ParameterType.URLENCODED); } + + if (endConferenceOnCustomerExit != null) { - request.addPostParam( - "EndConferenceOnCustomerExit", - endConferenceOnCustomerExit.toString() - ); + Serializer.toString(request, "EndConferenceOnCustomerExit", endConferenceOnCustomerExit, ParameterType.URLENCODED); } + + if (beepOnCustomerEntrance != null) { - request.addPostParam( - "BeepOnCustomerEntrance", - beepOnCustomerEntrance.toString() - ); + Serializer.toString(request, "BeepOnCustomerEntrance", beepOnCustomerEntrance, ParameterType.URLENCODED); } + + if (jitterBufferSize != null) { - request.addPostParam("JitterBufferSize", jitterBufferSize); + Serializer.toString(request, "JitterBufferSize", jitterBufferSize, ParameterType.URLENCODED); } + + } private void addHeaderParams(final Request request) { + if (ifMatch != null) { - request.addHeaderParam("If-Match", ifMatch); + Serializer.toString(request, "If-Match", ifMatch, ParameterType.HEADER); } + } } diff --git a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/taskqueue/TaskQueueBulkRealTimeStatistics.java b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/taskqueue/TaskQueueBulkRealTimeStatistics.java index 6ebf10c77a..de0d1ab7cc 100644 --- a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/taskqueue/TaskQueueBulkRealTimeStatistics.java +++ b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/taskqueue/TaskQueueBulkRealTimeStatistics.java @@ -24,45 +24,38 @@ import com.twilio.base.Resource; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.util.List; -import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class TaskQueueBulkRealTimeStatistics extends Resource { - private static final long serialVersionUID = 187525220896144L; - public static TaskQueueBulkRealTimeStatisticsCreator creator( - final String pathWorkspaceSid - ) { - return new TaskQueueBulkRealTimeStatisticsCreator(pathWorkspaceSid); + public static TaskQueueBulkRealTimeStatisticsCreator creator(final String pathworkspaceSid) { + return new TaskQueueBulkRealTimeStatisticsCreator( + pathworkspaceSid + ); } + /** * Converts a JSON String into a TaskQueueBulkRealTimeStatistics object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return TaskQueueBulkRealTimeStatistics object represented by the provided JSON */ - public static TaskQueueBulkRealTimeStatistics fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static TaskQueueBulkRealTimeStatistics fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { - return objectMapper.readValue( - json, - TaskQueueBulkRealTimeStatistics.class - ); + return objectMapper.readValue(json, TaskQueueBulkRealTimeStatistics.class); } catch (final JsonMappingException | JsonParseException e) { throw new ApiException(e.getMessage(), e); } catch (final IOException e) { @@ -74,20 +67,14 @@ public static TaskQueueBulkRealTimeStatistics fromJson( * Converts a JSON InputStream into a TaskQueueBulkRealTimeStatistics object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return TaskQueueBulkRealTimeStatistics object represented by the provided JSON */ - public static TaskQueueBulkRealTimeStatistics fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static TaskQueueBulkRealTimeStatistics fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { - return objectMapper.readValue( - json, - TaskQueueBulkRealTimeStatistics.class - ); + return objectMapper.readValue(json, TaskQueueBulkRealTimeStatistics.class); } catch (final JsonMappingException | JsonParseException e) { throw new ApiException(e.getMessage(), e); } catch (final IOException e) { @@ -107,49 +94,31 @@ public static String toJson(Object object, ObjectMapper mapper) { } } + + @Getter private final String accountSid; - private final String workspaceSid; - private final List> taskQueueData; + @Getter + private final List taskQueueData; + @Getter private final Integer taskQueueResponseCount; + @Getter private final URI url; + @Getter + private final String workspaceSid; @JsonCreator private TaskQueueBulkRealTimeStatistics( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("workspace_sid") final String workspaceSid, - @JsonProperty("task_queue_data") final List< - Map - > taskQueueData, - @JsonProperty( - "task_queue_response_count" - ) final Integer taskQueueResponseCount, - @JsonProperty("url") final URI url + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("task_queue_data") final List taskQueueData, + @JsonProperty("task_queue_response_count") final Integer taskQueueResponseCount, + @JsonProperty("url") final URI url, + @JsonProperty("workspace_sid") final String workspaceSid ) { this.accountSid = accountSid; - this.workspaceSid = workspaceSid; this.taskQueueData = taskQueueData; this.taskQueueResponseCount = taskQueueResponseCount; this.url = url; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getWorkspaceSid() { - return this.workspaceSid; - } - - public final List> getTaskQueueData() { - return this.taskQueueData; - } - - public final Integer getTaskQueueResponseCount() { - return this.taskQueueResponseCount; - } - - public final URI getUrl() { - return this.url; + this.workspaceSid = workspaceSid; } @Override @@ -162,29 +131,27 @@ public boolean equals(final Object o) { return false; } - TaskQueueBulkRealTimeStatistics other = - (TaskQueueBulkRealTimeStatistics) o; - + TaskQueueBulkRealTimeStatistics other = (TaskQueueBulkRealTimeStatistics) o; return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(workspaceSid, other.workspaceSid) && - Objects.equals(taskQueueData, other.taskQueueData) && - Objects.equals( - taskQueueResponseCount, - other.taskQueueResponseCount - ) && - Objects.equals(url, other.url) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(taskQueueData, other.taskQueueData) && + Objects.equals(taskQueueResponseCount, other.taskQueueResponseCount) && + Objects.equals(url, other.url) && + Objects.equals(workspaceSid, other.workspaceSid) ); } @Override public int hashCode() { return Objects.hash( - accountSid, - workspaceSid, - taskQueueData, - taskQueueResponseCount, - url + accountSid, + taskQueueData, + taskQueueResponseCount, + url, + workspaceSid ); } + + } + diff --git a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/taskqueue/TaskQueueBulkRealTimeStatisticsCreator.java b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/taskqueue/TaskQueueBulkRealTimeStatisticsCreator.java index 8b5de7846f..69d2b9a429 100644 --- a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/taskqueue/TaskQueueBulkRealTimeStatisticsCreator.java +++ b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/taskqueue/TaskQueueBulkRealTimeStatisticsCreator.java @@ -26,74 +26,60 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class TaskQueueBulkRealTimeStatisticsCreator - extends Creator { +public class TaskQueueBulkRealTimeStatisticsCreator extends Creator { - private String pathWorkspaceSid; + private String pathworkspaceSid; private Object body; - public TaskQueueBulkRealTimeStatisticsCreator( - final String pathWorkspaceSid - ) { - this.pathWorkspaceSid = pathWorkspaceSid; + public TaskQueueBulkRealTimeStatisticsCreator(final String pathworkspaceSid) { + this.pathworkspaceSid = pathworkspaceSid; } + public TaskQueueBulkRealTimeStatisticsCreator setBody(final Object body) { this.body = body; return this; } + @Override - public TaskQueueBulkRealTimeStatistics create( - final TwilioRestClient client - ) { - String path = - "/v1/Workspaces/{WorkspaceSid}/TaskQueues/RealTimeStatistics"; - - path = - path.replace( - "{" + "WorkspaceSid" + "}", - this.pathWorkspaceSid.toString() - ); + public TaskQueueBulkRealTimeStatistics create(final TwilioRestClient client) { + + String path = "/v1/Workspaces/{WorkspaceSid}/TaskQueues/RealTimeStatistics"; + + path = path.replace("{" + "WorkspaceSid" + "}", this.pathworkspaceSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.TASKROUTER.toString(), - path + HttpMethod.POST, + Domains.TASKROUTER.toString(), + path ); request.setContentType(EnumConstants.ContentType.JSON); addPostParams(request, client); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "TaskQueueBulkRealTimeStatistics creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("TaskQueueBulkRealTimeStatistics creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return TaskQueueBulkRealTimeStatistics.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return TaskQueueBulkRealTimeStatistics.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request, TwilioRestClient client) { ObjectMapper objectMapper = client.getObjectMapper(); if (body != null) { - request.setBody( - TaskQueueBulkRealTimeStatistics.toJson(body, objectMapper) - ); + request.setBody(TaskQueueBulkRealTimeStatistics.toJson(body, objectMapper)); } } } diff --git a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/taskqueue/TaskQueueCumulativeStatistics.java b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/taskqueue/TaskQueueCumulativeStatistics.java index 0adc19c917..c03170c4b6 100644 --- a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/taskqueue/TaskQueueCumulativeStatistics.java +++ b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/taskqueue/TaskQueueCumulativeStatistics.java @@ -18,55 +18,45 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; -import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class TaskQueueCumulativeStatistics extends Resource { - private static final long serialVersionUID = 113454189238794L; - public static TaskQueueCumulativeStatisticsFetcher fetcher( - final String pathWorkspaceSid, - final String pathTaskQueueSid - ) { + public static TaskQueueCumulativeStatisticsFetcher fetcher(final String pathworkspaceSid, final String pathtaskQueueSid) { return new TaskQueueCumulativeStatisticsFetcher( - pathWorkspaceSid, - pathTaskQueueSid + pathworkspaceSid, pathtaskQueueSid ); } + /** * Converts a JSON String into a TaskQueueCumulativeStatistics object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return TaskQueueCumulativeStatistics object represented by the provided JSON */ - public static TaskQueueCumulativeStatistics fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static TaskQueueCumulativeStatistics fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { - return objectMapper.readValue( - json, - TaskQueueCumulativeStatistics.class - ); + return objectMapper.readValue(json, TaskQueueCumulativeStatistics.class); } catch (final JsonMappingException | JsonParseException e) { throw new ApiException(e.getMessage(), e); } catch (final IOException e) { @@ -78,20 +68,14 @@ public static TaskQueueCumulativeStatistics fromJson( * Converts a JSON InputStream into a TaskQueueCumulativeStatistics object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return TaskQueueCumulativeStatistics object represented by the provided JSON */ - public static TaskQueueCumulativeStatistics fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static TaskQueueCumulativeStatistics fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { - return objectMapper.readValue( - json, - TaskQueueCumulativeStatistics.class - ); + return objectMapper.readValue(json, TaskQueueCumulativeStatistics.class); } catch (final JsonMappingException | JsonParseException e) { throw new ApiException(e.getMessage(), e); } catch (final IOException e) { @@ -99,189 +83,113 @@ public static TaskQueueCumulativeStatistics fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; + @Getter private final Integer avgTaskAcceptanceTime; - private final ZonedDateTime startTime; + @Getter private final ZonedDateTime endTime; - private final Integer reservationsCreated; + @Getter private final Integer reservationsAccepted; - private final Integer reservationsRejected; - private final Integer reservationsTimedOut; + @Getter private final Integer reservationsCanceled; + @Getter + private final Integer reservationsCreated; + @Getter + private final Integer reservationsRejected; + @Getter private final Integer reservationsRescinded; - private final Map splitByWaitTime; + @Getter + private final Integer reservationsTimedOut; + @Getter + private final Object splitByWaitTime; + @Getter + private final ZonedDateTime startTime; + @Getter private final String taskQueueSid; - private final Map waitDurationUntilAccepted; - private final Map waitDurationUntilCanceled; - private final Map waitDurationInQueueUntilAccepted; + @Getter private final Integer tasksCanceled; + @Getter private final Integer tasksCompleted; + @Getter private final Integer tasksDeleted; + @Getter private final Integer tasksEntered; + @Getter private final Integer tasksMoved; - private final String workspaceSid; + @Getter private final URI url; + @Getter + private final Object waitDurationInQueueUntilAccepted; + @Getter + private final Object waitDurationUntilAccepted; + @Getter + private final Object waitDurationUntilCanceled; + @Getter + private final String workspaceSid; @JsonCreator private TaskQueueCumulativeStatistics( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty( - "avg_task_acceptance_time" - ) final Integer avgTaskAcceptanceTime, - @JsonProperty("start_time") final String startTime, - @JsonProperty("end_time") final String endTime, - @JsonProperty("reservations_created") final Integer reservationsCreated, - @JsonProperty( - "reservations_accepted" - ) final Integer reservationsAccepted, - @JsonProperty( - "reservations_rejected" - ) final Integer reservationsRejected, - @JsonProperty( - "reservations_timed_out" - ) final Integer reservationsTimedOut, - @JsonProperty( - "reservations_canceled" - ) final Integer reservationsCanceled, - @JsonProperty( - "reservations_rescinded" - ) final Integer reservationsRescinded, - @JsonProperty("split_by_wait_time") final Map< - String, - Object - > splitByWaitTime, - @JsonProperty("task_queue_sid") final String taskQueueSid, - @JsonProperty("wait_duration_until_accepted") final Map< - String, - Object - > waitDurationUntilAccepted, - @JsonProperty("wait_duration_until_canceled") final Map< - String, - Object - > waitDurationUntilCanceled, - @JsonProperty("wait_duration_in_queue_until_accepted") final Map< - String, - Object - > waitDurationInQueueUntilAccepted, - @JsonProperty("tasks_canceled") final Integer tasksCanceled, - @JsonProperty("tasks_completed") final Integer tasksCompleted, - @JsonProperty("tasks_deleted") final Integer tasksDeleted, - @JsonProperty("tasks_entered") final Integer tasksEntered, - @JsonProperty("tasks_moved") final Integer tasksMoved, - @JsonProperty("workspace_sid") final String workspaceSid, - @JsonProperty("url") final URI url + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("avg_task_acceptance_time") final Integer avgTaskAcceptanceTime, + @JsonProperty("end_time") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime endTime, + @JsonProperty("reservations_accepted") final Integer reservationsAccepted, + @JsonProperty("reservations_canceled") final Integer reservationsCanceled, + @JsonProperty("reservations_created") final Integer reservationsCreated, + @JsonProperty("reservations_rejected") final Integer reservationsRejected, + @JsonProperty("reservations_rescinded") final Integer reservationsRescinded, + @JsonProperty("reservations_timed_out") final Integer reservationsTimedOut, + @JsonProperty("split_by_wait_time") final Object splitByWaitTime, + @JsonProperty("start_time") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime startTime, + @JsonProperty("task_queue_sid") final String taskQueueSid, + @JsonProperty("tasks_canceled") final Integer tasksCanceled, + @JsonProperty("tasks_completed") final Integer tasksCompleted, + @JsonProperty("tasks_deleted") final Integer tasksDeleted, + @JsonProperty("tasks_entered") final Integer tasksEntered, + @JsonProperty("tasks_moved") final Integer tasksMoved, + @JsonProperty("url") final URI url, + @JsonProperty("wait_duration_in_queue_until_accepted") final Object waitDurationInQueueUntilAccepted, + @JsonProperty("wait_duration_until_accepted") final Object waitDurationUntilAccepted, + @JsonProperty("wait_duration_until_canceled") final Object waitDurationUntilCanceled, + @JsonProperty("workspace_sid") final String workspaceSid ) { this.accountSid = accountSid; this.avgTaskAcceptanceTime = avgTaskAcceptanceTime; - this.startTime = DateConverter.iso8601DateTimeFromString(startTime); - this.endTime = DateConverter.iso8601DateTimeFromString(endTime); - this.reservationsCreated = reservationsCreated; + this.endTime = endTime; this.reservationsAccepted = reservationsAccepted; - this.reservationsRejected = reservationsRejected; - this.reservationsTimedOut = reservationsTimedOut; this.reservationsCanceled = reservationsCanceled; + this.reservationsCreated = reservationsCreated; + this.reservationsRejected = reservationsRejected; this.reservationsRescinded = reservationsRescinded; + this.reservationsTimedOut = reservationsTimedOut; this.splitByWaitTime = splitByWaitTime; + this.startTime = startTime; this.taskQueueSid = taskQueueSid; - this.waitDurationUntilAccepted = waitDurationUntilAccepted; - this.waitDurationUntilCanceled = waitDurationUntilCanceled; - this.waitDurationInQueueUntilAccepted = - waitDurationInQueueUntilAccepted; this.tasksCanceled = tasksCanceled; this.tasksCompleted = tasksCompleted; this.tasksDeleted = tasksDeleted; this.tasksEntered = tasksEntered; this.tasksMoved = tasksMoved; - this.workspaceSid = workspaceSid; this.url = url; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final Integer getAvgTaskAcceptanceTime() { - return this.avgTaskAcceptanceTime; - } - - public final ZonedDateTime getStartTime() { - return this.startTime; - } - - public final ZonedDateTime getEndTime() { - return this.endTime; - } - - public final Integer getReservationsCreated() { - return this.reservationsCreated; - } - - public final Integer getReservationsAccepted() { - return this.reservationsAccepted; - } - - public final Integer getReservationsRejected() { - return this.reservationsRejected; - } - - public final Integer getReservationsTimedOut() { - return this.reservationsTimedOut; - } - - public final Integer getReservationsCanceled() { - return this.reservationsCanceled; - } - - public final Integer getReservationsRescinded() { - return this.reservationsRescinded; - } - - public final Map getSplitByWaitTime() { - return this.splitByWaitTime; - } - - public final String getTaskQueueSid() { - return this.taskQueueSid; - } - - public final Map getWaitDurationUntilAccepted() { - return this.waitDurationUntilAccepted; - } - - public final Map getWaitDurationUntilCanceled() { - return this.waitDurationUntilCanceled; - } - - public final Map getWaitDurationInQueueUntilAccepted() { - return this.waitDurationInQueueUntilAccepted; - } - - public final Integer getTasksCanceled() { - return this.tasksCanceled; - } - - public final Integer getTasksCompleted() { - return this.tasksCompleted; - } - - public final Integer getTasksDeleted() { - return this.tasksDeleted; - } - - public final Integer getTasksEntered() { - return this.tasksEntered; - } - - public final Integer getTasksMoved() { - return this.tasksMoved; - } - - public final String getWorkspaceSid() { - return this.workspaceSid; - } - - public final URI getUrl() { - return this.url; + this.waitDurationInQueueUntilAccepted = waitDurationInQueueUntilAccepted; + this.waitDurationUntilAccepted = waitDurationUntilAccepted; + this.waitDurationUntilCanceled = waitDurationUntilCanceled; + this.workspaceSid = workspaceSid; } @Override @@ -295,73 +203,60 @@ public boolean equals(final Object o) { } TaskQueueCumulativeStatistics other = (TaskQueueCumulativeStatistics) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals( - avgTaskAcceptanceTime, - other.avgTaskAcceptanceTime - ) && - Objects.equals(startTime, other.startTime) && - Objects.equals(endTime, other.endTime) && - Objects.equals(reservationsCreated, other.reservationsCreated) && - Objects.equals(reservationsAccepted, other.reservationsAccepted) && - Objects.equals(reservationsRejected, other.reservationsRejected) && - Objects.equals(reservationsTimedOut, other.reservationsTimedOut) && - Objects.equals(reservationsCanceled, other.reservationsCanceled) && - Objects.equals( - reservationsRescinded, - other.reservationsRescinded - ) && - Objects.equals(splitByWaitTime, other.splitByWaitTime) && - Objects.equals(taskQueueSid, other.taskQueueSid) && - Objects.equals( - waitDurationUntilAccepted, - other.waitDurationUntilAccepted - ) && - Objects.equals( - waitDurationUntilCanceled, - other.waitDurationUntilCanceled - ) && - Objects.equals( - waitDurationInQueueUntilAccepted, - other.waitDurationInQueueUntilAccepted - ) && - Objects.equals(tasksCanceled, other.tasksCanceled) && - Objects.equals(tasksCompleted, other.tasksCompleted) && - Objects.equals(tasksDeleted, other.tasksDeleted) && - Objects.equals(tasksEntered, other.tasksEntered) && - Objects.equals(tasksMoved, other.tasksMoved) && - Objects.equals(workspaceSid, other.workspaceSid) && - Objects.equals(url, other.url) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(avgTaskAcceptanceTime, other.avgTaskAcceptanceTime) && + Objects.equals(endTime, other.endTime) && + Objects.equals(reservationsAccepted, other.reservationsAccepted) && + Objects.equals(reservationsCanceled, other.reservationsCanceled) && + Objects.equals(reservationsCreated, other.reservationsCreated) && + Objects.equals(reservationsRejected, other.reservationsRejected) && + Objects.equals(reservationsRescinded, other.reservationsRescinded) && + Objects.equals(reservationsTimedOut, other.reservationsTimedOut) && + Objects.equals(splitByWaitTime, other.splitByWaitTime) && + Objects.equals(startTime, other.startTime) && + Objects.equals(taskQueueSid, other.taskQueueSid) && + Objects.equals(tasksCanceled, other.tasksCanceled) && + Objects.equals(tasksCompleted, other.tasksCompleted) && + Objects.equals(tasksDeleted, other.tasksDeleted) && + Objects.equals(tasksEntered, other.tasksEntered) && + Objects.equals(tasksMoved, other.tasksMoved) && + Objects.equals(url, other.url) && + Objects.equals(waitDurationInQueueUntilAccepted, other.waitDurationInQueueUntilAccepted) && + Objects.equals(waitDurationUntilAccepted, other.waitDurationUntilAccepted) && + Objects.equals(waitDurationUntilCanceled, other.waitDurationUntilCanceled) && + Objects.equals(workspaceSid, other.workspaceSid) ); } @Override public int hashCode() { return Objects.hash( - accountSid, - avgTaskAcceptanceTime, - startTime, - endTime, - reservationsCreated, - reservationsAccepted, - reservationsRejected, - reservationsTimedOut, - reservationsCanceled, - reservationsRescinded, - splitByWaitTime, - taskQueueSid, - waitDurationUntilAccepted, - waitDurationUntilCanceled, - waitDurationInQueueUntilAccepted, - tasksCanceled, - tasksCompleted, - tasksDeleted, - tasksEntered, - tasksMoved, - workspaceSid, - url + accountSid, + avgTaskAcceptanceTime, + endTime, + reservationsAccepted, + reservationsCanceled, + reservationsCreated, + reservationsRejected, + reservationsRescinded, + reservationsTimedOut, + splitByWaitTime, + startTime, + taskQueueSid, + tasksCanceled, + tasksCompleted, + tasksDeleted, + tasksEntered, + tasksMoved, + url, + waitDurationInQueueUntilAccepted, + waitDurationUntilAccepted, + waitDurationUntilCanceled, + workspaceSid ); } + + } + diff --git a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/taskqueue/TaskQueueCumulativeStatisticsFetcher.java b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/taskqueue/TaskQueueCumulativeStatisticsFetcher.java index f275daa08e..241201a208 100644 --- a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/taskqueue/TaskQueueCumulativeStatisticsFetcher.java +++ b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/taskqueue/TaskQueueCumulativeStatisticsFetcher.java @@ -15,7 +15,8 @@ package com.twilio.rest.taskrouter.v1.workspace.taskqueue; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -24,131 +25,115 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.time.ZonedDateTime; -public class TaskQueueCumulativeStatisticsFetcher - extends Fetcher { +public class TaskQueueCumulativeStatisticsFetcher extends Fetcher { - private String pathWorkspaceSid; - private String pathTaskQueueSid; + private String pathworkspaceSid; + private String pathtaskQueueSid; private ZonedDateTime endDate; private Integer minutes; private ZonedDateTime startDate; private String taskChannel; private String splitByWaitTime; - public TaskQueueCumulativeStatisticsFetcher( - final String pathWorkspaceSid, - final String pathTaskQueueSid - ) { - this.pathWorkspaceSid = pathWorkspaceSid; - this.pathTaskQueueSid = pathTaskQueueSid; + public TaskQueueCumulativeStatisticsFetcher(final String pathworkspaceSid, final String pathtaskQueueSid) { + this.pathworkspaceSid = pathworkspaceSid; + this.pathtaskQueueSid = pathtaskQueueSid; } - public TaskQueueCumulativeStatisticsFetcher setEndDate( - final ZonedDateTime endDate - ) { + + public TaskQueueCumulativeStatisticsFetcher setEndDate(final ZonedDateTime endDate) { this.endDate = endDate; return this; } - public TaskQueueCumulativeStatisticsFetcher setMinutes( - final Integer minutes - ) { + + public TaskQueueCumulativeStatisticsFetcher setMinutes(final Integer minutes) { this.minutes = minutes; return this; } - public TaskQueueCumulativeStatisticsFetcher setStartDate( - final ZonedDateTime startDate - ) { + + public TaskQueueCumulativeStatisticsFetcher setStartDate(final ZonedDateTime startDate) { this.startDate = startDate; return this; } - public TaskQueueCumulativeStatisticsFetcher setTaskChannel( - final String taskChannel - ) { + + public TaskQueueCumulativeStatisticsFetcher setTaskChannel(final String taskChannel) { this.taskChannel = taskChannel; return this; } - public TaskQueueCumulativeStatisticsFetcher setSplitByWaitTime( - final String splitByWaitTime - ) { + + public TaskQueueCumulativeStatisticsFetcher setSplitByWaitTime(final String splitByWaitTime) { this.splitByWaitTime = splitByWaitTime; return this; } + @Override public TaskQueueCumulativeStatistics fetch(final TwilioRestClient client) { - String path = - "/v1/Workspaces/{WorkspaceSid}/TaskQueues/{TaskQueueSid}/CumulativeStatistics"; - path = - path.replace( - "{" + "WorkspaceSid" + "}", - this.pathWorkspaceSid.toString() - ); - path = - path.replace( - "{" + "TaskQueueSid" + "}", - this.pathTaskQueueSid.toString() - ); + String path = "/v1/Workspaces/{WorkspaceSid}/TaskQueues/{TaskQueueSid}/CumulativeStatistics"; + + path = path.replace("{" + "WorkspaceSid" + "}", this.pathworkspaceSid.toString()); + path = path.replace("{" + "TaskQueueSid" + "}", this.pathtaskQueueSid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.TASKROUTER.toString(), - path + HttpMethod.GET, + Domains.TASKROUTER.toString(), + path ); addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "TaskQueueCumulativeStatistics fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("TaskQueueCumulativeStatistics fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return TaskQueueCumulativeStatistics.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return TaskQueueCumulativeStatistics.fromJson(response.getStream(), client.getObjectMapper()); } private void addQueryParams(final Request request) { + + if (endDate != null) { - request.addQueryParam("EndDate", endDate.toInstant().toString()); + Serializer.toString(request, "EndDate", endDate, ParameterType.QUERY); } + if (minutes != null) { - request.addQueryParam("Minutes", minutes.toString()); + Serializer.toString(request, "Minutes", minutes, ParameterType.QUERY); } + + if (startDate != null) { - request.addQueryParam( - "StartDate", - startDate.toInstant().toString() - ); + Serializer.toString(request, "StartDate", startDate, ParameterType.QUERY); } + if (taskChannel != null) { - request.addQueryParam("TaskChannel", taskChannel); + Serializer.toString(request, "TaskChannel", taskChannel, ParameterType.QUERY); } + + if (splitByWaitTime != null) { - request.addQueryParam("SplitByWaitTime", splitByWaitTime); + Serializer.toString(request, "SplitByWaitTime", splitByWaitTime, ParameterType.QUERY); } + + } } diff --git a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/taskqueue/TaskQueueRealTimeStatistics.java b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/taskqueue/TaskQueueRealTimeStatistics.java index 48236ec0dc..94835d343e 100644 --- a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/taskqueue/TaskQueueRealTimeStatistics.java +++ b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/taskqueue/TaskQueueRealTimeStatistics.java @@ -18,54 +18,44 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.util.List; -import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class TaskQueueRealTimeStatistics extends Resource { - private static final long serialVersionUID = 59495775727482L; - public static TaskQueueRealTimeStatisticsFetcher fetcher( - final String pathWorkspaceSid, - final String pathTaskQueueSid - ) { + public static TaskQueueRealTimeStatisticsFetcher fetcher(final String pathworkspaceSid, final String pathtaskQueueSid) { return new TaskQueueRealTimeStatisticsFetcher( - pathWorkspaceSid, - pathTaskQueueSid + pathworkspaceSid, pathtaskQueueSid ); } + /** * Converts a JSON String into a TaskQueueRealTimeStatistics object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return TaskQueueRealTimeStatistics object represented by the provided JSON */ - public static TaskQueueRealTimeStatistics fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static TaskQueueRealTimeStatistics fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { - return objectMapper.readValue( - json, - TaskQueueRealTimeStatistics.class - ); + return objectMapper.readValue(json, TaskQueueRealTimeStatistics.class); } catch (final JsonMappingException | JsonParseException e) { throw new ApiException(e.getMessage(), e); } catch (final IOException e) { @@ -77,20 +67,14 @@ public static TaskQueueRealTimeStatistics fromJson( * Converts a JSON InputStream into a TaskQueueRealTimeStatistics object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return TaskQueueRealTimeStatistics object represented by the provided JSON */ - public static TaskQueueRealTimeStatistics fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static TaskQueueRealTimeStatistics fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { - return objectMapper.readValue( - json, - TaskQueueRealTimeStatistics.class - ); + return objectMapper.readValue(json, TaskQueueRealTimeStatistics.class); } catch (final JsonMappingException | JsonParseException e) { throw new ApiException(e.getMessage(), e); } catch (final IOException e) { @@ -98,128 +82,79 @@ public static TaskQueueRealTimeStatistics fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final List> activityStatistics; - private final Integer longestTaskWaitingAge; - private final String longestTaskWaitingSid; + @Getter + private final List activityStatistics; + @Getter private final Integer longestRelativeTaskAgeInQueue; + @Getter private final String longestRelativeTaskSidInQueue; + @Getter + private final Integer longestTaskWaitingAge; + @Getter + private final String longestTaskWaitingSid; + @Getter private final String taskQueueSid; - private final Map tasksByPriority; - private final Map tasksByStatus; + @Getter + private final Object tasksByPriority; + @Getter + private final Object tasksByStatus; + @Getter private final Integer totalAvailableWorkers; + @Getter private final Integer totalEligibleWorkers; + @Getter private final Integer totalTasks; - private final String workspaceSid; + @Getter private final URI url; + @Getter + private final String workspaceSid; @JsonCreator private TaskQueueRealTimeStatistics( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("activity_statistics") final List< - Map - > activityStatistics, - @JsonProperty( - "longest_task_waiting_age" - ) final Integer longestTaskWaitingAge, - @JsonProperty( - "longest_task_waiting_sid" - ) final String longestTaskWaitingSid, - @JsonProperty( - "longest_relative_task_age_in_queue" - ) final Integer longestRelativeTaskAgeInQueue, - @JsonProperty( - "longest_relative_task_sid_in_queue" - ) final String longestRelativeTaskSidInQueue, - @JsonProperty("task_queue_sid") final String taskQueueSid, - @JsonProperty("tasks_by_priority") final Map< - String, - Object - > tasksByPriority, - @JsonProperty("tasks_by_status") final Map< - String, - Object - > tasksByStatus, - @JsonProperty( - "total_available_workers" - ) final Integer totalAvailableWorkers, - @JsonProperty( - "total_eligible_workers" - ) final Integer totalEligibleWorkers, - @JsonProperty("total_tasks") final Integer totalTasks, - @JsonProperty("workspace_sid") final String workspaceSid, - @JsonProperty("url") final URI url + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("activity_statistics") final List activityStatistics, + @JsonProperty("longest_relative_task_age_in_queue") final Integer longestRelativeTaskAgeInQueue, + @JsonProperty("longest_relative_task_sid_in_queue") final String longestRelativeTaskSidInQueue, + @JsonProperty("longest_task_waiting_age") final Integer longestTaskWaitingAge, + @JsonProperty("longest_task_waiting_sid") final String longestTaskWaitingSid, + @JsonProperty("task_queue_sid") final String taskQueueSid, + @JsonProperty("tasks_by_priority") final Object tasksByPriority, + @JsonProperty("tasks_by_status") final Object tasksByStatus, + @JsonProperty("total_available_workers") final Integer totalAvailableWorkers, + @JsonProperty("total_eligible_workers") final Integer totalEligibleWorkers, + @JsonProperty("total_tasks") final Integer totalTasks, + @JsonProperty("url") final URI url, + @JsonProperty("workspace_sid") final String workspaceSid ) { this.accountSid = accountSid; this.activityStatistics = activityStatistics; - this.longestTaskWaitingAge = longestTaskWaitingAge; - this.longestTaskWaitingSid = longestTaskWaitingSid; this.longestRelativeTaskAgeInQueue = longestRelativeTaskAgeInQueue; this.longestRelativeTaskSidInQueue = longestRelativeTaskSidInQueue; + this.longestTaskWaitingAge = longestTaskWaitingAge; + this.longestTaskWaitingSid = longestTaskWaitingSid; this.taskQueueSid = taskQueueSid; this.tasksByPriority = tasksByPriority; this.tasksByStatus = tasksByStatus; this.totalAvailableWorkers = totalAvailableWorkers; this.totalEligibleWorkers = totalEligibleWorkers; this.totalTasks = totalTasks; - this.workspaceSid = workspaceSid; this.url = url; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final List> getActivityStatistics() { - return this.activityStatistics; - } - - public final Integer getLongestTaskWaitingAge() { - return this.longestTaskWaitingAge; - } - - public final String getLongestTaskWaitingSid() { - return this.longestTaskWaitingSid; - } - - public final Integer getLongestRelativeTaskAgeInQueue() { - return this.longestRelativeTaskAgeInQueue; - } - - public final String getLongestRelativeTaskSidInQueue() { - return this.longestRelativeTaskSidInQueue; - } - - public final String getTaskQueueSid() { - return this.taskQueueSid; - } - - public final Map getTasksByPriority() { - return this.tasksByPriority; - } - - public final Map getTasksByStatus() { - return this.tasksByStatus; - } - - public final Integer getTotalAvailableWorkers() { - return this.totalAvailableWorkers; - } - - public final Integer getTotalEligibleWorkers() { - return this.totalEligibleWorkers; - } - - public final Integer getTotalTasks() { - return this.totalTasks; - } - - public final String getWorkspaceSid() { - return this.workspaceSid; - } - - public final URI getUrl() { - return this.url; + this.workspaceSid = workspaceSid; } @Override @@ -233,57 +168,44 @@ public boolean equals(final Object o) { } TaskQueueRealTimeStatistics other = (TaskQueueRealTimeStatistics) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(activityStatistics, other.activityStatistics) && - Objects.equals( - longestTaskWaitingAge, - other.longestTaskWaitingAge - ) && - Objects.equals( - longestTaskWaitingSid, - other.longestTaskWaitingSid - ) && - Objects.equals( - longestRelativeTaskAgeInQueue, - other.longestRelativeTaskAgeInQueue - ) && - Objects.equals( - longestRelativeTaskSidInQueue, - other.longestRelativeTaskSidInQueue - ) && - Objects.equals(taskQueueSid, other.taskQueueSid) && - Objects.equals(tasksByPriority, other.tasksByPriority) && - Objects.equals(tasksByStatus, other.tasksByStatus) && - Objects.equals( - totalAvailableWorkers, - other.totalAvailableWorkers - ) && - Objects.equals(totalEligibleWorkers, other.totalEligibleWorkers) && - Objects.equals(totalTasks, other.totalTasks) && - Objects.equals(workspaceSid, other.workspaceSid) && - Objects.equals(url, other.url) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(activityStatistics, other.activityStatistics) && + Objects.equals(longestRelativeTaskAgeInQueue, other.longestRelativeTaskAgeInQueue) && + Objects.equals(longestRelativeTaskSidInQueue, other.longestRelativeTaskSidInQueue) && + Objects.equals(longestTaskWaitingAge, other.longestTaskWaitingAge) && + Objects.equals(longestTaskWaitingSid, other.longestTaskWaitingSid) && + Objects.equals(taskQueueSid, other.taskQueueSid) && + Objects.equals(tasksByPriority, other.tasksByPriority) && + Objects.equals(tasksByStatus, other.tasksByStatus) && + Objects.equals(totalAvailableWorkers, other.totalAvailableWorkers) && + Objects.equals(totalEligibleWorkers, other.totalEligibleWorkers) && + Objects.equals(totalTasks, other.totalTasks) && + Objects.equals(url, other.url) && + Objects.equals(workspaceSid, other.workspaceSid) ); } @Override public int hashCode() { return Objects.hash( - accountSid, - activityStatistics, - longestTaskWaitingAge, - longestTaskWaitingSid, - longestRelativeTaskAgeInQueue, - longestRelativeTaskSidInQueue, - taskQueueSid, - tasksByPriority, - tasksByStatus, - totalAvailableWorkers, - totalEligibleWorkers, - totalTasks, - workspaceSid, - url + accountSid, + activityStatistics, + longestRelativeTaskAgeInQueue, + longestRelativeTaskSidInQueue, + longestTaskWaitingAge, + longestTaskWaitingSid, + taskQueueSid, + tasksByPriority, + tasksByStatus, + totalAvailableWorkers, + totalEligibleWorkers, + totalTasks, + url, + workspaceSid ); } + + } + diff --git a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/taskqueue/TaskQueueRealTimeStatisticsFetcher.java b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/taskqueue/TaskQueueRealTimeStatisticsFetcher.java index 566a8824f1..6b7d64df21 100644 --- a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/taskqueue/TaskQueueRealTimeStatisticsFetcher.java +++ b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/taskqueue/TaskQueueRealTimeStatisticsFetcher.java @@ -15,7 +15,8 @@ package com.twilio.rest.taskrouter.v1.workspace.taskqueue; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,80 +26,64 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class TaskQueueRealTimeStatisticsFetcher - extends Fetcher { +public class TaskQueueRealTimeStatisticsFetcher extends Fetcher { - private String pathWorkspaceSid; - private String pathTaskQueueSid; + private String pathworkspaceSid; + private String pathtaskQueueSid; private String taskChannel; - public TaskQueueRealTimeStatisticsFetcher( - final String pathWorkspaceSid, - final String pathTaskQueueSid - ) { - this.pathWorkspaceSid = pathWorkspaceSid; - this.pathTaskQueueSid = pathTaskQueueSid; + public TaskQueueRealTimeStatisticsFetcher(final String pathworkspaceSid, final String pathtaskQueueSid) { + this.pathworkspaceSid = pathworkspaceSid; + this.pathtaskQueueSid = pathtaskQueueSid; } - public TaskQueueRealTimeStatisticsFetcher setTaskChannel( - final String taskChannel - ) { + + public TaskQueueRealTimeStatisticsFetcher setTaskChannel(final String taskChannel) { this.taskChannel = taskChannel; return this; } + @Override public TaskQueueRealTimeStatistics fetch(final TwilioRestClient client) { - String path = - "/v1/Workspaces/{WorkspaceSid}/TaskQueues/{TaskQueueSid}/RealTimeStatistics"; - path = - path.replace( - "{" + "WorkspaceSid" + "}", - this.pathWorkspaceSid.toString() - ); - path = - path.replace( - "{" + "TaskQueueSid" + "}", - this.pathTaskQueueSid.toString() - ); + String path = "/v1/Workspaces/{WorkspaceSid}/TaskQueues/{TaskQueueSid}/RealTimeStatistics"; + + path = path.replace("{" + "WorkspaceSid" + "}", this.pathworkspaceSid.toString()); + path = path.replace("{" + "TaskQueueSid" + "}", this.pathtaskQueueSid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.TASKROUTER.toString(), - path + HttpMethod.GET, + Domains.TASKROUTER.toString(), + path ); addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "TaskQueueRealTimeStatistics fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("TaskQueueRealTimeStatistics fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return TaskQueueRealTimeStatistics.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return TaskQueueRealTimeStatistics.fromJson(response.getStream(), client.getObjectMapper()); } private void addQueryParams(final Request request) { + + if (taskChannel != null) { - request.addQueryParam("TaskChannel", taskChannel); + Serializer.toString(request, "TaskChannel", taskChannel, ParameterType.QUERY); } + + } } diff --git a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/taskqueue/TaskQueueStatistics.java b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/taskqueue/TaskQueueStatistics.java index 03c1f13c85..fb5ed6daf0 100644 --- a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/taskqueue/TaskQueueStatistics.java +++ b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/taskqueue/TaskQueueStatistics.java @@ -18,47 +18,40 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; -import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class TaskQueueStatistics extends Resource { - private static final long serialVersionUID = 273955433542749L; - public static TaskQueueStatisticsFetcher fetcher( - final String pathWorkspaceSid, - final String pathTaskQueueSid - ) { + public static TaskQueueStatisticsFetcher fetcher(final String pathworkspaceSid, final String pathtaskQueueSid) { return new TaskQueueStatisticsFetcher( - pathWorkspaceSid, - pathTaskQueueSid + pathworkspaceSid, pathtaskQueueSid ); } + /** * Converts a JSON String into a TaskQueueStatistics object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return TaskQueueStatistics object represented by the provided JSON */ - public static TaskQueueStatistics fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static TaskQueueStatistics fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, TaskQueueStatistics.class); @@ -73,14 +66,11 @@ public static TaskQueueStatistics fromJson( * Converts a JSON InputStream into a TaskQueueStatistics object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return TaskQueueStatistics object represented by the provided JSON */ - public static TaskQueueStatistics fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static TaskQueueStatistics fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, TaskQueueStatistics.class); @@ -91,52 +81,47 @@ public static TaskQueueStatistics fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final Map cumulative; - private final Map realtime; + @Getter + private final Object cumulative; + @Getter + private final Object realtime; + @Getter private final String taskQueueSid; - private final String workspaceSid; + @Getter private final URI url; + @Getter + private final String workspaceSid; @JsonCreator private TaskQueueStatistics( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("cumulative") final Map cumulative, - @JsonProperty("realtime") final Map realtime, - @JsonProperty("task_queue_sid") final String taskQueueSid, - @JsonProperty("workspace_sid") final String workspaceSid, - @JsonProperty("url") final URI url + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("cumulative") final Object cumulative, + @JsonProperty("realtime") final Object realtime, + @JsonProperty("task_queue_sid") final String taskQueueSid, + @JsonProperty("url") final URI url, + @JsonProperty("workspace_sid") final String workspaceSid ) { this.accountSid = accountSid; this.cumulative = cumulative; this.realtime = realtime; this.taskQueueSid = taskQueueSid; - this.workspaceSid = workspaceSid; this.url = url; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final Map getCumulative() { - return this.cumulative; - } - - public final Map getRealtime() { - return this.realtime; - } - - public final String getTaskQueueSid() { - return this.taskQueueSid; - } - - public final String getWorkspaceSid() { - return this.workspaceSid; - } - - public final URI getUrl() { - return this.url; + this.workspaceSid = workspaceSid; } @Override @@ -150,26 +135,28 @@ public boolean equals(final Object o) { } TaskQueueStatistics other = (TaskQueueStatistics) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(cumulative, other.cumulative) && - Objects.equals(realtime, other.realtime) && - Objects.equals(taskQueueSid, other.taskQueueSid) && - Objects.equals(workspaceSid, other.workspaceSid) && - Objects.equals(url, other.url) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(cumulative, other.cumulative) && + Objects.equals(realtime, other.realtime) && + Objects.equals(taskQueueSid, other.taskQueueSid) && + Objects.equals(url, other.url) && + Objects.equals(workspaceSid, other.workspaceSid) ); } @Override public int hashCode() { return Objects.hash( - accountSid, - cumulative, - realtime, - taskQueueSid, - workspaceSid, - url + accountSid, + cumulative, + realtime, + taskQueueSid, + url, + workspaceSid ); } + + } + diff --git a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/taskqueue/TaskQueueStatisticsFetcher.java b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/taskqueue/TaskQueueStatisticsFetcher.java index fd523e3e15..529678d0f4 100644 --- a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/taskqueue/TaskQueueStatisticsFetcher.java +++ b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/taskqueue/TaskQueueStatisticsFetcher.java @@ -15,7 +15,8 @@ package com.twilio.rest.taskrouter.v1.workspace.taskqueue; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -24,124 +25,115 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.time.ZonedDateTime; public class TaskQueueStatisticsFetcher extends Fetcher { - private String pathWorkspaceSid; - private String pathTaskQueueSid; + private String pathworkspaceSid; + private String pathtaskQueueSid; private ZonedDateTime endDate; private Integer minutes; private ZonedDateTime startDate; private String taskChannel; private String splitByWaitTime; - public TaskQueueStatisticsFetcher( - final String pathWorkspaceSid, - final String pathTaskQueueSid - ) { - this.pathWorkspaceSid = pathWorkspaceSid; - this.pathTaskQueueSid = pathTaskQueueSid; + public TaskQueueStatisticsFetcher(final String pathworkspaceSid, final String pathtaskQueueSid) { + this.pathworkspaceSid = pathworkspaceSid; + this.pathtaskQueueSid = pathtaskQueueSid; } + public TaskQueueStatisticsFetcher setEndDate(final ZonedDateTime endDate) { this.endDate = endDate; return this; } + public TaskQueueStatisticsFetcher setMinutes(final Integer minutes) { this.minutes = minutes; return this; } - public TaskQueueStatisticsFetcher setStartDate( - final ZonedDateTime startDate - ) { + + public TaskQueueStatisticsFetcher setStartDate(final ZonedDateTime startDate) { this.startDate = startDate; return this; } + public TaskQueueStatisticsFetcher setTaskChannel(final String taskChannel) { this.taskChannel = taskChannel; return this; } - public TaskQueueStatisticsFetcher setSplitByWaitTime( - final String splitByWaitTime - ) { + + public TaskQueueStatisticsFetcher setSplitByWaitTime(final String splitByWaitTime) { this.splitByWaitTime = splitByWaitTime; return this; } + @Override public TaskQueueStatistics fetch(final TwilioRestClient client) { - String path = - "/v1/Workspaces/{WorkspaceSid}/TaskQueues/{TaskQueueSid}/Statistics"; - path = - path.replace( - "{" + "WorkspaceSid" + "}", - this.pathWorkspaceSid.toString() - ); - path = - path.replace( - "{" + "TaskQueueSid" + "}", - this.pathTaskQueueSid.toString() - ); + String path = "/v1/Workspaces/{WorkspaceSid}/TaskQueues/{TaskQueueSid}/Statistics"; + + path = path.replace("{" + "WorkspaceSid" + "}", this.pathworkspaceSid.toString()); + path = path.replace("{" + "TaskQueueSid" + "}", this.pathtaskQueueSid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.TASKROUTER.toString(), - path + HttpMethod.GET, + Domains.TASKROUTER.toString(), + path ); addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "TaskQueueStatistics fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("TaskQueueStatistics fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return TaskQueueStatistics.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return TaskQueueStatistics.fromJson(response.getStream(), client.getObjectMapper()); } private void addQueryParams(final Request request) { + + if (endDate != null) { - request.addQueryParam("EndDate", endDate.toInstant().toString()); + Serializer.toString(request, "EndDate", endDate, ParameterType.QUERY); } + if (minutes != null) { - request.addQueryParam("Minutes", minutes.toString()); + Serializer.toString(request, "Minutes", minutes, ParameterType.QUERY); } + + if (startDate != null) { - request.addQueryParam( - "StartDate", - startDate.toInstant().toString() - ); + Serializer.toString(request, "StartDate", startDate, ParameterType.QUERY); } + if (taskChannel != null) { - request.addQueryParam("TaskChannel", taskChannel); + Serializer.toString(request, "TaskChannel", taskChannel, ParameterType.QUERY); } + + if (splitByWaitTime != null) { - request.addQueryParam("SplitByWaitTime", splitByWaitTime); + Serializer.toString(request, "SplitByWaitTime", splitByWaitTime, ParameterType.QUERY); } + + } } diff --git a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/taskqueue/TaskQueuesStatistics.java b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/taskqueue/TaskQueuesStatistics.java index e11fe3b88e..a6d21e2d6a 100644 --- a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/taskqueue/TaskQueuesStatistics.java +++ b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/taskqueue/TaskQueuesStatistics.java @@ -18,42 +18,39 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; -import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class TaskQueuesStatistics extends Resource { - private static final long serialVersionUID = 167349245476595L; - public static TaskQueuesStatisticsReader reader( - final String pathWorkspaceSid - ) { - return new TaskQueuesStatisticsReader(pathWorkspaceSid); + public static TaskQueuesStatisticsReader reader(final String pathworkspaceSid) { + return new TaskQueuesStatisticsReader( + pathworkspaceSid + ); } + /** * Converts a JSON String into a TaskQueuesStatistics object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return TaskQueuesStatistics object represented by the provided JSON */ - public static TaskQueuesStatistics fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static TaskQueuesStatistics fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, TaskQueuesStatistics.class); @@ -68,14 +65,11 @@ public static TaskQueuesStatistics fromJson( * Converts a JSON InputStream into a TaskQueuesStatistics object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return TaskQueuesStatistics object represented by the provided JSON */ - public static TaskQueuesStatistics fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static TaskQueuesStatistics fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, TaskQueuesStatistics.class); @@ -86,19 +80,37 @@ public static TaskQueuesStatistics fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final Map cumulative; - private final Map realtime; + @Getter + private final Object cumulative; + @Getter + private final Object realtime; + @Getter private final String taskQueueSid; + @Getter private final String workspaceSid; @JsonCreator private TaskQueuesStatistics( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("cumulative") final Map cumulative, - @JsonProperty("realtime") final Map realtime, - @JsonProperty("task_queue_sid") final String taskQueueSid, - @JsonProperty("workspace_sid") final String workspaceSid + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("cumulative") final Object cumulative, + @JsonProperty("realtime") final Object realtime, + @JsonProperty("task_queue_sid") final String taskQueueSid, + @JsonProperty("workspace_sid") final String workspaceSid ) { this.accountSid = accountSid; this.cumulative = cumulative; @@ -107,26 +119,6 @@ private TaskQueuesStatistics( this.workspaceSid = workspaceSid; } - public final String getAccountSid() { - return this.accountSid; - } - - public final Map getCumulative() { - return this.cumulative; - } - - public final Map getRealtime() { - return this.realtime; - } - - public final String getTaskQueueSid() { - return this.taskQueueSid; - } - - public final String getWorkspaceSid() { - return this.workspaceSid; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -138,24 +130,26 @@ public boolean equals(final Object o) { } TaskQueuesStatistics other = (TaskQueuesStatistics) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(cumulative, other.cumulative) && - Objects.equals(realtime, other.realtime) && - Objects.equals(taskQueueSid, other.taskQueueSid) && - Objects.equals(workspaceSid, other.workspaceSid) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(cumulative, other.cumulative) && + Objects.equals(realtime, other.realtime) && + Objects.equals(taskQueueSid, other.taskQueueSid) && + Objects.equals(workspaceSid, other.workspaceSid) ); } @Override public int hashCode() { return Objects.hash( - accountSid, - cumulative, - realtime, - taskQueueSid, - workspaceSid + accountSid, + cumulative, + realtime, + taskQueueSid, + workspaceSid ); } + + } + diff --git a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/taskqueue/TaskQueuesStatisticsReader.java b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/taskqueue/TaskQueuesStatisticsReader.java index 517b1db629..cce351bd8a 100644 --- a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/taskqueue/TaskQueuesStatisticsReader.java +++ b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/taskqueue/TaskQueuesStatisticsReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -26,11 +27,12 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.time.ZonedDateTime; public class TaskQueuesStatisticsReader extends Reader { - private String pathWorkspaceSid; + private String pathworkspaceSid; private ZonedDateTime endDate; private String friendlyName; private Integer minutes; @@ -39,173 +41,151 @@ public class TaskQueuesStatisticsReader extends Reader { private String splitByWaitTime; private Long pageSize; - public TaskQueuesStatisticsReader(final String pathWorkspaceSid) { - this.pathWorkspaceSid = pathWorkspaceSid; + public TaskQueuesStatisticsReader(final String pathworkspaceSid) { + this.pathworkspaceSid = pathworkspaceSid; } + public TaskQueuesStatisticsReader setEndDate(final ZonedDateTime endDate) { this.endDate = endDate; return this; } - public TaskQueuesStatisticsReader setFriendlyName( - final String friendlyName - ) { + + public TaskQueuesStatisticsReader setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + public TaskQueuesStatisticsReader setMinutes(final Integer minutes) { this.minutes = minutes; return this; } - public TaskQueuesStatisticsReader setStartDate( - final ZonedDateTime startDate - ) { + + public TaskQueuesStatisticsReader setStartDate(final ZonedDateTime startDate) { this.startDate = startDate; return this; } + public TaskQueuesStatisticsReader setTaskChannel(final String taskChannel) { this.taskChannel = taskChannel; return this; } - public TaskQueuesStatisticsReader setSplitByWaitTime( - final String splitByWaitTime - ) { + + public TaskQueuesStatisticsReader setSplitByWaitTime(final String splitByWaitTime) { this.splitByWaitTime = splitByWaitTime; return this; } + public TaskQueuesStatisticsReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override - public ResourceSet read( - final TwilioRestClient client - ) { + public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/Workspaces/{WorkspaceSid}/TaskQueues/Statistics"; - path = - path.replace( - "{" + "WorkspaceSid" + "}", - this.pathWorkspaceSid.toString() - ); + + path = path.replace("{" + "WorkspaceSid" + "}", this.pathworkspaceSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.TASKROUTER.toString(), - path + HttpMethod.GET, + Domains.TASKROUTER.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "TaskQueuesStatistics read failed: Unable to connect to server" - ); + throw new ApiConnectionException("TaskQueuesStatistics read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "task_queues_statistics", - response.getContent(), - TaskQueuesStatistics.class, - client.getObjectMapper() - ); + "task_queues_statistics", + response.getContent(), + TaskQueuesStatistics.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.TASKROUTER.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.TASKROUTER.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (endDate != null) { - request.addQueryParam("EndDate", endDate.toInstant().toString()); + Serializer.toString(request, "EndDate", endDate, ParameterType.QUERY); } + if (friendlyName != null) { - request.addQueryParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.QUERY); } + + if (minutes != null) { - request.addQueryParam("Minutes", minutes.toString()); + Serializer.toString(request, "Minutes", minutes, ParameterType.QUERY); } + + if (startDate != null) { - request.addQueryParam( - "StartDate", - startDate.toInstant().toString() - ); + Serializer.toString(request, "StartDate", startDate, ParameterType.QUERY); } + if (taskChannel != null) { - request.addQueryParam("TaskChannel", taskChannel); + Serializer.toString(request, "TaskChannel", taskChannel, ParameterType.QUERY); } + + if (splitByWaitTime != null) { - request.addQueryParam("SplitByWaitTime", splitByWaitTime); + Serializer.toString(request, "SplitByWaitTime", splitByWaitTime, ParameterType.QUERY); } + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/worker/Reservation.java b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/worker/Reservation.java index 3c6c7d48d6..5138b753f6 100644 --- a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/worker/Reservation.java +++ b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/worker/Reservation.java @@ -18,63 +18,132 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Reservation extends Resource { - private static final long serialVersionUID = 88353198782173L; - public static ReservationFetcher fetcher( - final String pathWorkspaceSid, - final String pathWorkerSid, - final String pathSid - ) { - return new ReservationFetcher(pathWorkspaceSid, pathWorkerSid, pathSid); + public static ReservationFetcher fetcher(final String pathworkspaceSid, final String pathworkerSid, final String pathsid) { + return new ReservationFetcher( + pathworkspaceSid, pathworkerSid, pathsid + ); } - public static ReservationReader reader( - final String pathWorkspaceSid, - final String pathWorkerSid - ) { - return new ReservationReader(pathWorkspaceSid, pathWorkerSid); + + public static ReservationReader reader(final String pathworkspaceSid, final String pathworkerSid) { + return new ReservationReader( + pathworkspaceSid, pathworkerSid + ); } - public static ReservationUpdater updater( - final String pathWorkspaceSid, - final String pathWorkerSid, - final String pathSid - ) { - return new ReservationUpdater(pathWorkspaceSid, pathWorkerSid, pathSid); + + public static ReservationUpdater updater(final String pathworkspaceSid, final String pathworkerSid, final String pathsid) { + return new ReservationUpdater( + pathworkspaceSid, pathworkerSid, pathsid + ); } + + public enum Status { + PENDING("pending"), + ACCEPTED("accepted"), + REJECTED("rejected"), + TIMEOUT("timeout"), + CANCELED("canceled"), + RESCINDED("rescinded"), + WRAPPING("wrapping"), + COMPLETED("completed"); + + private final String value; + + private Status(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static Status forValue(final String value) { + return Promoter.enumFromString(value, Status.values()); + } + } + + public enum CallStatus { + INITIATED("initiated"), + RINGING("ringing"), + ANSWERED("answered"), + COMPLETED("completed"); + + private final String value; + + private CallStatus(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static CallStatus forValue(final String value) { + return Promoter.enumFromString(value, CallStatus.values()); + } + } + + public enum ConferenceEvent { + START("start"), + END("end"), + JOIN("join"), + LEAVE("leave"), + MUTE("mute"), + HOLD("hold"), + SPEAKER("speaker"); + + private final String value; + + private ConferenceEvent(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static ConferenceEvent forValue(final String value) { + return Promoter.enumFromString(value, ConferenceEvent.values()); + } + } + + /** * Converts a JSON String into a Reservation object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Reservation object represented by the provided JSON */ - public static Reservation fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Reservation fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Reservation.class); @@ -89,14 +158,11 @@ public static Reservation fromJson( * Converts a JSON InputStream into a Reservation object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Reservation object represented by the provided JSON */ - public static Reservation fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Reservation fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Reservation.class); @@ -107,89 +173,69 @@ public static Reservation fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; + @Getter + private final Map links; + @Getter private final Reservation.Status reservationStatus; + @Getter private final String sid; + @Getter private final String taskSid; + @Getter + private final URI url; + @Getter private final String workerName; + @Getter private final String workerSid; + @Getter private final String workspaceSid; - private final URI url; - private final Map links; @JsonCreator private Reservation( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty( - "reservation_status" - ) final Reservation.Status reservationStatus, - @JsonProperty("sid") final String sid, - @JsonProperty("task_sid") final String taskSid, - @JsonProperty("worker_name") final String workerName, - @JsonProperty("worker_sid") final String workerSid, - @JsonProperty("workspace_sid") final String workspaceSid, - @JsonProperty("url") final URI url, - @JsonProperty("links") final Map links + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("links") final Map links, + @JsonProperty("reservation_status") final Reservation.Status reservationStatus, + @JsonProperty("sid") final String sid, + @JsonProperty("task_sid") final String taskSid, + @JsonProperty("url") final URI url, + @JsonProperty("worker_name") final String workerName, + @JsonProperty("worker_sid") final String workerSid, + @JsonProperty("workspace_sid") final String workspaceSid ) { this.accountSid = accountSid; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; + this.links = links; this.reservationStatus = reservationStatus; this.sid = sid; this.taskSid = taskSid; + this.url = url; this.workerName = workerName; this.workerSid = workerSid; this.workspaceSid = workspaceSid; - this.url = url; - this.links = links; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final Reservation.Status getReservationStatus() { - return this.reservationStatus; - } - - public final String getSid() { - return this.sid; - } - - public final String getTaskSid() { - return this.taskSid; - } - - public final String getWorkerName() { - return this.workerName; - } - - public final String getWorkerSid() { - return this.workerSid; - } - - public final String getWorkspaceSid() { - return this.workspaceSid; - } - - public final URI getUrl() { - return this.url; - } - - public final Map getLinks() { - return this.links; } @Override @@ -203,109 +249,38 @@ public boolean equals(final Object o) { } Reservation other = (Reservation) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(reservationStatus, other.reservationStatus) && - Objects.equals(sid, other.sid) && - Objects.equals(taskSid, other.taskSid) && - Objects.equals(workerName, other.workerName) && - Objects.equals(workerSid, other.workerSid) && - Objects.equals(workspaceSid, other.workspaceSid) && - Objects.equals(url, other.url) && - Objects.equals(links, other.links) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(links, other.links) && + Objects.equals(reservationStatus, other.reservationStatus) && + Objects.equals(sid, other.sid) && + Objects.equals(taskSid, other.taskSid) && + Objects.equals(url, other.url) && + Objects.equals(workerName, other.workerName) && + Objects.equals(workerSid, other.workerSid) && + Objects.equals(workspaceSid, other.workspaceSid) ); } @Override public int hashCode() { return Objects.hash( - accountSid, - dateCreated, - dateUpdated, - reservationStatus, - sid, - taskSid, - workerName, - workerSid, - workspaceSid, - url, - links + accountSid, + dateCreated, + dateUpdated, + links, + reservationStatus, + sid, + taskSid, + url, + workerName, + workerSid, + workspaceSid ); } - public enum Status { - PENDING("pending"), - ACCEPTED("accepted"), - REJECTED("rejected"), - TIMEOUT("timeout"), - CANCELED("canceled"), - RESCINDED("rescinded"), - WRAPPING("wrapping"), - COMPLETED("completed"); - private final String value; - - private Status(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static Status forValue(final String value) { - return Promoter.enumFromString(value, Status.values()); - } - } - - public enum ConferenceEvent { - START("start"), - END("end"), - JOIN("join"), - LEAVE("leave"), - MUTE("mute"), - HOLD("hold"), - SPEAKER("speaker"); - - private final String value; - - private ConferenceEvent(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static ConferenceEvent forValue(final String value) { - return Promoter.enumFromString(value, ConferenceEvent.values()); - } - } - - public enum CallStatus { - INITIATED("initiated"), - RINGING("ringing"), - ANSWERED("answered"), - COMPLETED("completed"); - - private final String value; - - private CallStatus(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static CallStatus forValue(final String value) { - return Promoter.enumFromString(value, CallStatus.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/worker/ReservationFetcher.java b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/worker/ReservationFetcher.java index 6db4003e70..d534ddcd61 100644 --- a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/worker/ReservationFetcher.java +++ b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/worker/ReservationFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.taskrouter.v1.workspace.worker; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,66 +26,47 @@ public class ReservationFetcher extends Fetcher { - private String pathWorkspaceSid; - private String pathWorkerSid; - private String pathSid; + private String pathworkspaceSid; + private String pathworkerSid; + private String pathsid; - public ReservationFetcher( - final String pathWorkspaceSid, - final String pathWorkerSid, - final String pathSid - ) { - this.pathWorkspaceSid = pathWorkspaceSid; - this.pathWorkerSid = pathWorkerSid; - this.pathSid = pathSid; + public ReservationFetcher(final String pathworkspaceSid, final String pathworkerSid, final String pathsid) { + this.pathworkspaceSid = pathworkspaceSid; + this.pathworkerSid = pathworkerSid; + this.pathsid = pathsid; } + @Override public Reservation fetch(final TwilioRestClient client) { - String path = - "/v1/Workspaces/{WorkspaceSid}/Workers/{WorkerSid}/Reservations/{Sid}"; - path = - path.replace( - "{" + "WorkspaceSid" + "}", - this.pathWorkspaceSid.toString() - ); - path = - path.replace( - "{" + "WorkerSid" + "}", - this.pathWorkerSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/v1/Workspaces/{WorkspaceSid}/Workers/{WorkerSid}/Reservations/{Sid}"; + + path = path.replace("{" + "WorkspaceSid" + "}", this.pathworkspaceSid.toString()); + path = path.replace("{" + "WorkerSid" + "}", this.pathworkerSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.TASKROUTER.toString(), - path + HttpMethod.GET, + Domains.TASKROUTER.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Reservation fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Reservation fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return Reservation.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Reservation.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/worker/ReservationReader.java b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/worker/ReservationReader.java index e66fed433d..620f723f69 100644 --- a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/worker/ReservationReader.java +++ b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/worker/ReservationReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,140 +30,103 @@ public class ReservationReader extends Reader { - private String pathWorkspaceSid; - private String pathWorkerSid; + private String pathworkspaceSid; + private String pathworkerSid; private Reservation.Status reservationStatus; private Long pageSize; - public ReservationReader( - final String pathWorkspaceSid, - final String pathWorkerSid - ) { - this.pathWorkspaceSid = pathWorkspaceSid; - this.pathWorkerSid = pathWorkerSid; + public ReservationReader(final String pathworkspaceSid, final String pathworkerSid) { + this.pathworkspaceSid = pathworkspaceSid; + this.pathworkerSid = pathworkerSid; } - public ReservationReader setReservationStatus( - final Reservation.Status reservationStatus - ) { + + public ReservationReader setReservationStatus(final Reservation.Status reservationStatus) { this.reservationStatus = reservationStatus; return this; } + public ReservationReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { - String path = - "/v1/Workspaces/{WorkspaceSid}/Workers/{WorkerSid}/Reservations"; - path = - path.replace( - "{" + "WorkspaceSid" + "}", - this.pathWorkspaceSid.toString() - ); - path = - path.replace( - "{" + "WorkerSid" + "}", - this.pathWorkerSid.toString() - ); + + String path = "/v1/Workspaces/{WorkspaceSid}/Workers/{WorkerSid}/Reservations"; + + path = path.replace("{" + "WorkspaceSid" + "}", this.pathworkspaceSid.toString()); + path = path.replace("{" + "WorkerSid" + "}", this.pathworkerSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.TASKROUTER.toString(), - path + HttpMethod.GET, + Domains.TASKROUTER.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Reservation read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Reservation read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "reservations", - response.getContent(), - Reservation.class, - client.getObjectMapper() - ); + "reservations", + response.getContent(), + Reservation.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.TASKROUTER.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.TASKROUTER.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (reservationStatus != null) { - request.addQueryParam( - "ReservationStatus", - reservationStatus.toString() - ); + Serializer.toString(request, "ReservationStatus", reservationStatus, ParameterType.QUERY); } + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/worker/ReservationUpdater.java b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/worker/ReservationUpdater.java index cc45b5cdd8..8f95333e1a 100644 --- a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/worker/ReservationUpdater.java +++ b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/worker/ReservationUpdater.java @@ -16,7 +16,9 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; import com.twilio.converter.Promoter; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,14 +27,14 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.net.URI; import java.util.List; public class ReservationUpdater extends Updater { - - private String pathWorkspaceSid; - private String pathWorkerSid; - private String pathSid; + private String pathworkspaceSid; + private String pathworkerSid; + private String pathsid; private String ifMatch; private Reservation.Status reservationStatus; private String workerActivitySid; @@ -87,186 +89,157 @@ public class ReservationUpdater extends Updater { private Boolean beepOnCustomerEntrance; private String jitterBufferSize; - public ReservationUpdater( - final String pathWorkspaceSid, - final String pathWorkerSid, - final String pathSid - ) { - this.pathWorkspaceSid = pathWorkspaceSid; - this.pathWorkerSid = pathWorkerSid; - this.pathSid = pathSid; + public ReservationUpdater(final String pathworkspaceSid, final String pathworkerSid, final String pathsid) { + this.pathworkspaceSid = pathworkspaceSid; + this.pathworkerSid = pathworkerSid; + this.pathsid = pathsid; } - public ReservationUpdater setIfMatch(final String ifMatch) { - this.ifMatch = ifMatch; - return this; - } - public ReservationUpdater setReservationStatus( - final Reservation.Status reservationStatus - ) { + public ReservationUpdater setReservationStatus(final Reservation.Status reservationStatus) { this.reservationStatus = reservationStatus; return this; } - public ReservationUpdater setWorkerActivitySid( - final String workerActivitySid - ) { + + public ReservationUpdater setWorkerActivitySid(final String workerActivitySid) { this.workerActivitySid = workerActivitySid; return this; } + public ReservationUpdater setInstruction(final String instruction) { this.instruction = instruction; return this; } - public ReservationUpdater setDequeuePostWorkActivitySid( - final String dequeuePostWorkActivitySid - ) { + + public ReservationUpdater setDequeuePostWorkActivitySid(final String dequeuePostWorkActivitySid) { this.dequeuePostWorkActivitySid = dequeuePostWorkActivitySid; return this; } + public ReservationUpdater setDequeueFrom(final String dequeueFrom) { this.dequeueFrom = dequeueFrom; return this; } + public ReservationUpdater setDequeueRecord(final String dequeueRecord) { this.dequeueRecord = dequeueRecord; return this; } + public ReservationUpdater setDequeueTimeout(final Integer dequeueTimeout) { this.dequeueTimeout = dequeueTimeout; return this; } + public ReservationUpdater setDequeueTo(final String dequeueTo) { this.dequeueTo = dequeueTo; return this; } - public ReservationUpdater setDequeueStatusCallbackUrl( - final URI dequeueStatusCallbackUrl - ) { + + public ReservationUpdater setDequeueStatusCallbackUrl(final URI dequeueStatusCallbackUrl) { this.dequeueStatusCallbackUrl = dequeueStatusCallbackUrl; return this; } - public ReservationUpdater setDequeueStatusCallbackUrl( - final String dequeueStatusCallbackUrl - ) { - return setDequeueStatusCallbackUrl( - Promoter.uriFromString(dequeueStatusCallbackUrl) - ); - } public ReservationUpdater setCallFrom(final String callFrom) { this.callFrom = callFrom; return this; } + public ReservationUpdater setCallRecord(final String callRecord) { this.callRecord = callRecord; return this; } + public ReservationUpdater setCallTimeout(final Integer callTimeout) { this.callTimeout = callTimeout; return this; } + public ReservationUpdater setCallTo(final String callTo) { this.callTo = callTo; return this; } + public ReservationUpdater setCallUrl(final URI callUrl) { this.callUrl = callUrl; return this; } - public ReservationUpdater setCallUrl(final String callUrl) { - return setCallUrl(Promoter.uriFromString(callUrl)); - } - public ReservationUpdater setCallStatusCallbackUrl( - final URI callStatusCallbackUrl - ) { + public ReservationUpdater setCallStatusCallbackUrl(final URI callStatusCallbackUrl) { this.callStatusCallbackUrl = callStatusCallbackUrl; return this; } - public ReservationUpdater setCallStatusCallbackUrl( - final String callStatusCallbackUrl - ) { - return setCallStatusCallbackUrl( - Promoter.uriFromString(callStatusCallbackUrl) - ); - } public ReservationUpdater setCallAccept(final Boolean callAccept) { this.callAccept = callAccept; return this; } + public ReservationUpdater setRedirectCallSid(final String redirectCallSid) { this.redirectCallSid = redirectCallSid; return this; } + public ReservationUpdater setRedirectAccept(final Boolean redirectAccept) { this.redirectAccept = redirectAccept; return this; } + public ReservationUpdater setRedirectUrl(final URI redirectUrl) { this.redirectUrl = redirectUrl; return this; } - public ReservationUpdater setRedirectUrl(final String redirectUrl) { - return setRedirectUrl(Promoter.uriFromString(redirectUrl)); - } public ReservationUpdater setTo(final String to) { this.to = to; return this; } + public ReservationUpdater setFrom(final String from) { this.from = from; return this; } + public ReservationUpdater setStatusCallback(final URI statusCallback) { this.statusCallback = statusCallback; return this; } - public ReservationUpdater setStatusCallback(final String statusCallback) { - return setStatusCallback(Promoter.uriFromString(statusCallback)); - } - public ReservationUpdater setStatusCallbackMethod( - final HttpMethod statusCallbackMethod - ) { + public ReservationUpdater setStatusCallbackMethod(final HttpMethod statusCallbackMethod) { this.statusCallbackMethod = statusCallbackMethod; return this; } - public ReservationUpdater setStatusCallbackEvent( - final List statusCallbackEvent - ) { + + public ReservationUpdater setStatusCallbackEvent(final List statusCallbackEvent) { this.statusCallbackEvent = statusCallbackEvent; return this; } - public ReservationUpdater setStatusCallbackEvent( - final Reservation.CallStatus statusCallbackEvent - ) { + public ReservationUpdater setStatusCallbackEvent(final Reservation.CallStatus statusCallbackEvent) { return setStatusCallbackEvent(Promoter.listOfOne(statusCallbackEvent)); } @@ -275,487 +248,493 @@ public ReservationUpdater setTimeout(final Integer timeout) { return this; } + public ReservationUpdater setRecord(final Boolean record) { this.record = record; return this; } + public ReservationUpdater setMuted(final Boolean muted) { this.muted = muted; return this; } + public ReservationUpdater setBeep(final String beep) { this.beep = beep; return this; } - public ReservationUpdater setStartConferenceOnEnter( - final Boolean startConferenceOnEnter - ) { + + public ReservationUpdater setStartConferenceOnEnter(final Boolean startConferenceOnEnter) { this.startConferenceOnEnter = startConferenceOnEnter; return this; } - public ReservationUpdater setEndConferenceOnExit( - final Boolean endConferenceOnExit - ) { + + public ReservationUpdater setEndConferenceOnExit(final Boolean endConferenceOnExit) { this.endConferenceOnExit = endConferenceOnExit; return this; } + public ReservationUpdater setWaitUrl(final URI waitUrl) { this.waitUrl = waitUrl; return this; } - public ReservationUpdater setWaitUrl(final String waitUrl) { - return setWaitUrl(Promoter.uriFromString(waitUrl)); - } public ReservationUpdater setWaitMethod(final HttpMethod waitMethod) { this.waitMethod = waitMethod; return this; } + public ReservationUpdater setEarlyMedia(final Boolean earlyMedia) { this.earlyMedia = earlyMedia; return this; } - public ReservationUpdater setMaxParticipants( - final Integer maxParticipants - ) { + + public ReservationUpdater setMaxParticipants(final Integer maxParticipants) { this.maxParticipants = maxParticipants; return this; } - public ReservationUpdater setConferenceStatusCallback( - final URI conferenceStatusCallback - ) { + + public ReservationUpdater setConferenceStatusCallback(final URI conferenceStatusCallback) { this.conferenceStatusCallback = conferenceStatusCallback; return this; } - public ReservationUpdater setConferenceStatusCallback( - final String conferenceStatusCallback - ) { - return setConferenceStatusCallback( - Promoter.uriFromString(conferenceStatusCallback) - ); - } - public ReservationUpdater setConferenceStatusCallbackMethod( - final HttpMethod conferenceStatusCallbackMethod - ) { + public ReservationUpdater setConferenceStatusCallbackMethod(final HttpMethod conferenceStatusCallbackMethod) { this.conferenceStatusCallbackMethod = conferenceStatusCallbackMethod; return this; } - public ReservationUpdater setConferenceStatusCallbackEvent( - final List conferenceStatusCallbackEvent - ) { + + public ReservationUpdater setConferenceStatusCallbackEvent(final List conferenceStatusCallbackEvent) { this.conferenceStatusCallbackEvent = conferenceStatusCallbackEvent; return this; } - public ReservationUpdater setConferenceStatusCallbackEvent( - final Reservation.ConferenceEvent conferenceStatusCallbackEvent - ) { - return setConferenceStatusCallbackEvent( - Promoter.listOfOne(conferenceStatusCallbackEvent) - ); + public ReservationUpdater setConferenceStatusCallbackEvent(final Reservation.ConferenceEvent conferenceStatusCallbackEvent) { + return setConferenceStatusCallbackEvent(Promoter.listOfOne(conferenceStatusCallbackEvent)); } - public ReservationUpdater setConferenceRecord( - final String conferenceRecord - ) { + public ReservationUpdater setConferenceRecord(final String conferenceRecord) { this.conferenceRecord = conferenceRecord; return this; } + public ReservationUpdater setConferenceTrim(final String conferenceTrim) { this.conferenceTrim = conferenceTrim; return this; } - public ReservationUpdater setRecordingChannels( - final String recordingChannels - ) { + + public ReservationUpdater setRecordingChannels(final String recordingChannels) { this.recordingChannels = recordingChannels; return this; } - public ReservationUpdater setRecordingStatusCallback( - final URI recordingStatusCallback - ) { + + public ReservationUpdater setRecordingStatusCallback(final URI recordingStatusCallback) { this.recordingStatusCallback = recordingStatusCallback; return this; } - public ReservationUpdater setRecordingStatusCallback( - final String recordingStatusCallback - ) { - return setRecordingStatusCallback( - Promoter.uriFromString(recordingStatusCallback) - ); - } - public ReservationUpdater setRecordingStatusCallbackMethod( - final HttpMethod recordingStatusCallbackMethod - ) { + public ReservationUpdater setRecordingStatusCallbackMethod(final HttpMethod recordingStatusCallbackMethod) { this.recordingStatusCallbackMethod = recordingStatusCallbackMethod; return this; } - public ReservationUpdater setConferenceRecordingStatusCallback( - final URI conferenceRecordingStatusCallback - ) { - this.conferenceRecordingStatusCallback = - conferenceRecordingStatusCallback; + + public ReservationUpdater setConferenceRecordingStatusCallback(final URI conferenceRecordingStatusCallback) { + this.conferenceRecordingStatusCallback = conferenceRecordingStatusCallback; return this; } - public ReservationUpdater setConferenceRecordingStatusCallback( - final String conferenceRecordingStatusCallback - ) { - return setConferenceRecordingStatusCallback( - Promoter.uriFromString(conferenceRecordingStatusCallback) - ); - } - public ReservationUpdater setConferenceRecordingStatusCallbackMethod( - final HttpMethod conferenceRecordingStatusCallbackMethod - ) { - this.conferenceRecordingStatusCallbackMethod = - conferenceRecordingStatusCallbackMethod; + public ReservationUpdater setConferenceRecordingStatusCallbackMethod(final HttpMethod conferenceRecordingStatusCallbackMethod) { + this.conferenceRecordingStatusCallbackMethod = conferenceRecordingStatusCallbackMethod; return this; } + public ReservationUpdater setRegion(final String region) { this.region = region; return this; } + public ReservationUpdater setSipAuthUsername(final String sipAuthUsername) { this.sipAuthUsername = sipAuthUsername; return this; } + public ReservationUpdater setSipAuthPassword(final String sipAuthPassword) { this.sipAuthPassword = sipAuthPassword; return this; } - public ReservationUpdater setDequeueStatusCallbackEvent( - final List dequeueStatusCallbackEvent - ) { + + public ReservationUpdater setDequeueStatusCallbackEvent(final List dequeueStatusCallbackEvent) { this.dequeueStatusCallbackEvent = dequeueStatusCallbackEvent; return this; } - public ReservationUpdater setDequeueStatusCallbackEvent( - final String dequeueStatusCallbackEvent - ) { - return setDequeueStatusCallbackEvent( - Promoter.listOfOne(dequeueStatusCallbackEvent) - ); + public ReservationUpdater setDequeueStatusCallbackEvent(final String dequeueStatusCallbackEvent) { + return setDequeueStatusCallbackEvent(Promoter.listOfOne(dequeueStatusCallbackEvent)); } - public ReservationUpdater setPostWorkActivitySid( - final String postWorkActivitySid - ) { + public ReservationUpdater setPostWorkActivitySid(final String postWorkActivitySid) { this.postWorkActivitySid = postWorkActivitySid; return this; } - public ReservationUpdater setEndConferenceOnCustomerExit( - final Boolean endConferenceOnCustomerExit - ) { + + public ReservationUpdater setEndConferenceOnCustomerExit(final Boolean endConferenceOnCustomerExit) { this.endConferenceOnCustomerExit = endConferenceOnCustomerExit; return this; } - public ReservationUpdater setBeepOnCustomerEntrance( - final Boolean beepOnCustomerEntrance - ) { + + public ReservationUpdater setBeepOnCustomerEntrance(final Boolean beepOnCustomerEntrance) { this.beepOnCustomerEntrance = beepOnCustomerEntrance; return this; } - public ReservationUpdater setJitterBufferSize( - final String jitterBufferSize - ) { + + public ReservationUpdater setJitterBufferSize(final String jitterBufferSize) { this.jitterBufferSize = jitterBufferSize; return this; } + + public ReservationUpdater setIfMatch(final String ifMatch) { + this.ifMatch = ifMatch; + return this; + } + + @Override public Reservation update(final TwilioRestClient client) { - String path = - "/v1/Workspaces/{WorkspaceSid}/Workers/{WorkerSid}/Reservations/{Sid}"; - path = - path.replace( - "{" + "WorkspaceSid" + "}", - this.pathWorkspaceSid.toString() - ); - path = - path.replace( - "{" + "WorkerSid" + "}", - this.pathWorkerSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/v1/Workspaces/{WorkspaceSid}/Workers/{WorkerSid}/Reservations/{Sid}"; + + path = path.replace("{" + "WorkspaceSid" + "}", this.pathworkspaceSid.toString()); + path = path.replace("{" + "WorkerSid" + "}", this.pathworkerSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.TASKROUTER.toString(), - path + HttpMethod.POST, + Domains.TASKROUTER.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); - addPostParams(request); addHeaderParams(request); + addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Reservation update failed: Unable to connect to server" - ); + throw new ApiConnectionException("Reservation update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Reservation.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Reservation.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (reservationStatus != null) { - request.addPostParam( - "ReservationStatus", - reservationStatus.toString() - ); + Serializer.toString(request, "ReservationStatus", reservationStatus, ParameterType.URLENCODED); } + + if (workerActivitySid != null) { - request.addPostParam("WorkerActivitySid", workerActivitySid); + Serializer.toString(request, "WorkerActivitySid", workerActivitySid, ParameterType.URLENCODED); } + + if (instruction != null) { - request.addPostParam("Instruction", instruction); + Serializer.toString(request, "Instruction", instruction, ParameterType.URLENCODED); } + + if (dequeuePostWorkActivitySid != null) { - request.addPostParam( - "DequeuePostWorkActivitySid", - dequeuePostWorkActivitySid - ); + Serializer.toString(request, "DequeuePostWorkActivitySid", dequeuePostWorkActivitySid, ParameterType.URLENCODED); } + + if (dequeueFrom != null) { - request.addPostParam("DequeueFrom", dequeueFrom); + Serializer.toString(request, "DequeueFrom", dequeueFrom, ParameterType.URLENCODED); } + + if (dequeueRecord != null) { - request.addPostParam("DequeueRecord", dequeueRecord); + Serializer.toString(request, "DequeueRecord", dequeueRecord, ParameterType.URLENCODED); } + + if (dequeueTimeout != null) { - request.addPostParam("DequeueTimeout", dequeueTimeout.toString()); + Serializer.toString(request, "DequeueTimeout", dequeueTimeout, ParameterType.URLENCODED); } + + if (dequeueTo != null) { - request.addPostParam("DequeueTo", dequeueTo); + Serializer.toString(request, "DequeueTo", dequeueTo, ParameterType.URLENCODED); } + + if (dequeueStatusCallbackUrl != null) { - request.addPostParam( - "DequeueStatusCallbackUrl", - dequeueStatusCallbackUrl.toString() - ); + Serializer.toString(request, "DequeueStatusCallbackUrl", dequeueStatusCallbackUrl, ParameterType.URLENCODED); } + + if (callFrom != null) { - request.addPostParam("CallFrom", callFrom); + Serializer.toString(request, "CallFrom", callFrom, ParameterType.URLENCODED); } + + if (callRecord != null) { - request.addPostParam("CallRecord", callRecord); + Serializer.toString(request, "CallRecord", callRecord, ParameterType.URLENCODED); } + + if (callTimeout != null) { - request.addPostParam("CallTimeout", callTimeout.toString()); + Serializer.toString(request, "CallTimeout", callTimeout, ParameterType.URLENCODED); } + + if (callTo != null) { - request.addPostParam("CallTo", callTo); + Serializer.toString(request, "CallTo", callTo, ParameterType.URLENCODED); } + + if (callUrl != null) { - request.addPostParam("CallUrl", callUrl.toString()); + Serializer.toString(request, "CallUrl", callUrl, ParameterType.URLENCODED); } + + if (callStatusCallbackUrl != null) { - request.addPostParam( - "CallStatusCallbackUrl", - callStatusCallbackUrl.toString() - ); + Serializer.toString(request, "CallStatusCallbackUrl", callStatusCallbackUrl, ParameterType.URLENCODED); } + + if (callAccept != null) { - request.addPostParam("CallAccept", callAccept.toString()); + Serializer.toString(request, "CallAccept", callAccept, ParameterType.URLENCODED); } + + if (redirectCallSid != null) { - request.addPostParam("RedirectCallSid", redirectCallSid); + Serializer.toString(request, "RedirectCallSid", redirectCallSid, ParameterType.URLENCODED); } + + if (redirectAccept != null) { - request.addPostParam("RedirectAccept", redirectAccept.toString()); + Serializer.toString(request, "RedirectAccept", redirectAccept, ParameterType.URLENCODED); } + + if (redirectUrl != null) { - request.addPostParam("RedirectUrl", redirectUrl.toString()); + Serializer.toString(request, "RedirectUrl", redirectUrl, ParameterType.URLENCODED); } + + if (to != null) { - request.addPostParam("To", to); + Serializer.toString(request, "To", to, ParameterType.URLENCODED); } + + if (from != null) { - request.addPostParam("From", from); + Serializer.toString(request, "From", from, ParameterType.URLENCODED); } + + if (statusCallback != null) { - request.addPostParam("StatusCallback", statusCallback.toString()); + Serializer.toString(request, "StatusCallback", statusCallback, ParameterType.URLENCODED); } + + if (statusCallbackMethod != null) { - request.addPostParam( - "StatusCallbackMethod", - statusCallbackMethod.toString() - ); + Serializer.toString(request, "StatusCallbackMethod", statusCallbackMethod, ParameterType.URLENCODED); } + + if (statusCallbackEvent != null) { - for (Reservation.CallStatus prop : statusCallbackEvent) { - request.addPostParam("StatusCallbackEvent", prop.toString()); + for (Reservation.CallStatus param : statusCallbackEvent) { + Serializer.toString(request, "StatusCallbackEvent", param, ParameterType.URLENCODED); } } + + if (timeout != null) { - request.addPostParam("Timeout", timeout.toString()); + Serializer.toString(request, "Timeout", timeout, ParameterType.URLENCODED); } + + if (record != null) { - request.addPostParam("Record", record.toString()); + Serializer.toString(request, "Record", record, ParameterType.URLENCODED); } + + if (muted != null) { - request.addPostParam("Muted", muted.toString()); + Serializer.toString(request, "Muted", muted, ParameterType.URLENCODED); } + + if (beep != null) { - request.addPostParam("Beep", beep); + Serializer.toString(request, "Beep", beep, ParameterType.URLENCODED); } + + if (startConferenceOnEnter != null) { - request.addPostParam( - "StartConferenceOnEnter", - startConferenceOnEnter.toString() - ); + Serializer.toString(request, "StartConferenceOnEnter", startConferenceOnEnter, ParameterType.URLENCODED); } + + if (endConferenceOnExit != null) { - request.addPostParam( - "EndConferenceOnExit", - endConferenceOnExit.toString() - ); + Serializer.toString(request, "EndConferenceOnExit", endConferenceOnExit, ParameterType.URLENCODED); } + + if (waitUrl != null) { - request.addPostParam("WaitUrl", waitUrl.toString()); + Serializer.toString(request, "WaitUrl", waitUrl, ParameterType.URLENCODED); } + + if (waitMethod != null) { - request.addPostParam("WaitMethod", waitMethod.toString()); + Serializer.toString(request, "WaitMethod", waitMethod, ParameterType.URLENCODED); } + + if (earlyMedia != null) { - request.addPostParam("EarlyMedia", earlyMedia.toString()); + Serializer.toString(request, "EarlyMedia", earlyMedia, ParameterType.URLENCODED); } + + if (maxParticipants != null) { - request.addPostParam("MaxParticipants", maxParticipants.toString()); + Serializer.toString(request, "MaxParticipants", maxParticipants, ParameterType.URLENCODED); } + + if (conferenceStatusCallback != null) { - request.addPostParam( - "ConferenceStatusCallback", - conferenceStatusCallback.toString() - ); + Serializer.toString(request, "ConferenceStatusCallback", conferenceStatusCallback, ParameterType.URLENCODED); } + + if (conferenceStatusCallbackMethod != null) { - request.addPostParam( - "ConferenceStatusCallbackMethod", - conferenceStatusCallbackMethod.toString() - ); + Serializer.toString(request, "ConferenceStatusCallbackMethod", conferenceStatusCallbackMethod, ParameterType.URLENCODED); } + + if (conferenceStatusCallbackEvent != null) { - for (Reservation.ConferenceEvent prop : conferenceStatusCallbackEvent) { - request.addPostParam( - "ConferenceStatusCallbackEvent", - prop.toString() - ); + for (Reservation.ConferenceEvent param : conferenceStatusCallbackEvent) { + Serializer.toString(request, "ConferenceStatusCallbackEvent", param, ParameterType.URLENCODED); } } + + if (conferenceRecord != null) { - request.addPostParam("ConferenceRecord", conferenceRecord); + Serializer.toString(request, "ConferenceRecord", conferenceRecord, ParameterType.URLENCODED); } + + if (conferenceTrim != null) { - request.addPostParam("ConferenceTrim", conferenceTrim); + Serializer.toString(request, "ConferenceTrim", conferenceTrim, ParameterType.URLENCODED); } + + if (recordingChannels != null) { - request.addPostParam("RecordingChannels", recordingChannels); + Serializer.toString(request, "RecordingChannels", recordingChannels, ParameterType.URLENCODED); } + + if (recordingStatusCallback != null) { - request.addPostParam( - "RecordingStatusCallback", - recordingStatusCallback.toString() - ); + Serializer.toString(request, "RecordingStatusCallback", recordingStatusCallback, ParameterType.URLENCODED); } + + if (recordingStatusCallbackMethod != null) { - request.addPostParam( - "RecordingStatusCallbackMethod", - recordingStatusCallbackMethod.toString() - ); + Serializer.toString(request, "RecordingStatusCallbackMethod", recordingStatusCallbackMethod, ParameterType.URLENCODED); } + + if (conferenceRecordingStatusCallback != null) { - request.addPostParam( - "ConferenceRecordingStatusCallback", - conferenceRecordingStatusCallback.toString() - ); + Serializer.toString(request, "ConferenceRecordingStatusCallback", conferenceRecordingStatusCallback, ParameterType.URLENCODED); } + + if (conferenceRecordingStatusCallbackMethod != null) { - request.addPostParam( - "ConferenceRecordingStatusCallbackMethod", - conferenceRecordingStatusCallbackMethod.toString() - ); + Serializer.toString(request, "ConferenceRecordingStatusCallbackMethod", conferenceRecordingStatusCallbackMethod, ParameterType.URLENCODED); } + + if (region != null) { - request.addPostParam("Region", region); + Serializer.toString(request, "Region", region, ParameterType.URLENCODED); } + + if (sipAuthUsername != null) { - request.addPostParam("SipAuthUsername", sipAuthUsername); + Serializer.toString(request, "SipAuthUsername", sipAuthUsername, ParameterType.URLENCODED); } + + if (sipAuthPassword != null) { - request.addPostParam("SipAuthPassword", sipAuthPassword); + Serializer.toString(request, "SipAuthPassword", sipAuthPassword, ParameterType.URLENCODED); } + + if (dequeueStatusCallbackEvent != null) { - for (String prop : dequeueStatusCallbackEvent) { - request.addPostParam("DequeueStatusCallbackEvent", prop); + for (String param : dequeueStatusCallbackEvent) { + Serializer.toString(request, "DequeueStatusCallbackEvent", param, ParameterType.URLENCODED); } } + + if (postWorkActivitySid != null) { - request.addPostParam("PostWorkActivitySid", postWorkActivitySid); + Serializer.toString(request, "PostWorkActivitySid", postWorkActivitySid, ParameterType.URLENCODED); } + + if (endConferenceOnCustomerExit != null) { - request.addPostParam( - "EndConferenceOnCustomerExit", - endConferenceOnCustomerExit.toString() - ); + Serializer.toString(request, "EndConferenceOnCustomerExit", endConferenceOnCustomerExit, ParameterType.URLENCODED); } + + if (beepOnCustomerEntrance != null) { - request.addPostParam( - "BeepOnCustomerEntrance", - beepOnCustomerEntrance.toString() - ); + Serializer.toString(request, "BeepOnCustomerEntrance", beepOnCustomerEntrance, ParameterType.URLENCODED); } + + if (jitterBufferSize != null) { - request.addPostParam("JitterBufferSize", jitterBufferSize); + Serializer.toString(request, "JitterBufferSize", jitterBufferSize, ParameterType.URLENCODED); } + + } private void addHeaderParams(final Request request) { + if (ifMatch != null) { - request.addHeaderParam("If-Match", ifMatch); + Serializer.toString(request, "If-Match", ifMatch, ParameterType.HEADER); } + } } diff --git a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/worker/WorkerChannel.java b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/worker/WorkerChannel.java index 61728d5229..9fdcc72709 100644 --- a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/worker/WorkerChannel.java +++ b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/worker/WorkerChannel.java @@ -18,68 +18,56 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class WorkerChannel extends Resource { - private static final long serialVersionUID = 38376318052081L; - public static WorkerChannelFetcher fetcher( - final String pathWorkspaceSid, - final String pathWorkerSid, - final String pathSid - ) { + public static WorkerChannelFetcher fetcher(final String pathworkspaceSid, final String pathworkerSid, final String pathsid) { return new WorkerChannelFetcher( - pathWorkspaceSid, - pathWorkerSid, - pathSid + pathworkspaceSid, pathworkerSid, pathsid ); } - public static WorkerChannelReader reader( - final String pathWorkspaceSid, - final String pathWorkerSid - ) { - return new WorkerChannelReader(pathWorkspaceSid, pathWorkerSid); + + public static WorkerChannelReader reader(final String pathworkspaceSid, final String pathworkerSid) { + return new WorkerChannelReader( + pathworkspaceSid, pathworkerSid + ); } - public static WorkerChannelUpdater updater( - final String pathWorkspaceSid, - final String pathWorkerSid, - final String pathSid - ) { + + public static WorkerChannelUpdater updater(final String pathworkspaceSid, final String pathworkerSid, final String pathsid) { return new WorkerChannelUpdater( - pathWorkspaceSid, - pathWorkerSid, - pathSid + pathworkspaceSid, pathworkerSid, pathsid ); } + /** * Converts a JSON String into a WorkerChannel object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return WorkerChannel object represented by the provided JSON */ - public static WorkerChannel fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static WorkerChannel fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, WorkerChannel.class); @@ -94,14 +82,11 @@ public static WorkerChannel fromJson( * Converts a JSON InputStream into a WorkerChannel object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return WorkerChannel object represented by the provided JSON */ - public static WorkerChannel fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static WorkerChannel fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, WorkerChannel.class); @@ -112,105 +97,77 @@ public static WorkerChannel fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; + @Getter private final Integer assignedTasks; + @Getter private final Boolean available; + @Getter private final Integer availableCapacityPercentage; + @Getter private final Integer configuredCapacity; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; + @Getter private final String sid; + @Getter private final String taskChannelSid; + @Getter private final String taskChannelUniqueName; + @Getter + private final URI url; + @Getter private final String workerSid; + @Getter private final String workspaceSid; - private final URI url; @JsonCreator private WorkerChannel( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("assigned_tasks") final Integer assignedTasks, - @JsonProperty("available") final Boolean available, - @JsonProperty( - "available_capacity_percentage" - ) final Integer availableCapacityPercentage, - @JsonProperty("configured_capacity") final Integer configuredCapacity, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("sid") final String sid, - @JsonProperty("task_channel_sid") final String taskChannelSid, - @JsonProperty( - "task_channel_unique_name" - ) final String taskChannelUniqueName, - @JsonProperty("worker_sid") final String workerSid, - @JsonProperty("workspace_sid") final String workspaceSid, - @JsonProperty("url") final URI url + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("assigned_tasks") final Integer assignedTasks, + @JsonProperty("available") final Boolean available, + @JsonProperty("available_capacity_percentage") final Integer availableCapacityPercentage, + @JsonProperty("configured_capacity") final Integer configuredCapacity, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("sid") final String sid, + @JsonProperty("task_channel_sid") final String taskChannelSid, + @JsonProperty("task_channel_unique_name") final String taskChannelUniqueName, + @JsonProperty("url") final URI url, + @JsonProperty("worker_sid") final String workerSid, + @JsonProperty("workspace_sid") final String workspaceSid ) { this.accountSid = accountSid; this.assignedTasks = assignedTasks; this.available = available; this.availableCapacityPercentage = availableCapacityPercentage; this.configuredCapacity = configuredCapacity; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.sid = sid; this.taskChannelSid = taskChannelSid; this.taskChannelUniqueName = taskChannelUniqueName; + this.url = url; this.workerSid = workerSid; this.workspaceSid = workspaceSid; - this.url = url; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final Integer getAssignedTasks() { - return this.assignedTasks; - } - - public final Boolean getAvailable() { - return this.available; - } - - public final Integer getAvailableCapacityPercentage() { - return this.availableCapacityPercentage; - } - - public final Integer getConfiguredCapacity() { - return this.configuredCapacity; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final String getSid() { - return this.sid; - } - - public final String getTaskChannelSid() { - return this.taskChannelSid; - } - - public final String getTaskChannelUniqueName() { - return this.taskChannelUniqueName; - } - - public final String getWorkerSid() { - return this.workerSid; - } - - public final String getWorkspaceSid() { - return this.workspaceSid; - } - - public final URI getUrl() { - return this.url; } @Override @@ -224,46 +181,42 @@ public boolean equals(final Object o) { } WorkerChannel other = (WorkerChannel) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(assignedTasks, other.assignedTasks) && - Objects.equals(available, other.available) && - Objects.equals( - availableCapacityPercentage, - other.availableCapacityPercentage - ) && - Objects.equals(configuredCapacity, other.configuredCapacity) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(sid, other.sid) && - Objects.equals(taskChannelSid, other.taskChannelSid) && - Objects.equals( - taskChannelUniqueName, - other.taskChannelUniqueName - ) && - Objects.equals(workerSid, other.workerSid) && - Objects.equals(workspaceSid, other.workspaceSid) && - Objects.equals(url, other.url) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(assignedTasks, other.assignedTasks) && + Objects.equals(available, other.available) && + Objects.equals(availableCapacityPercentage, other.availableCapacityPercentage) && + Objects.equals(configuredCapacity, other.configuredCapacity) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(sid, other.sid) && + Objects.equals(taskChannelSid, other.taskChannelSid) && + Objects.equals(taskChannelUniqueName, other.taskChannelUniqueName) && + Objects.equals(url, other.url) && + Objects.equals(workerSid, other.workerSid) && + Objects.equals(workspaceSid, other.workspaceSid) ); } @Override public int hashCode() { return Objects.hash( - accountSid, - assignedTasks, - available, - availableCapacityPercentage, - configuredCapacity, - dateCreated, - dateUpdated, - sid, - taskChannelSid, - taskChannelUniqueName, - workerSid, - workspaceSid, - url + accountSid, + assignedTasks, + available, + availableCapacityPercentage, + configuredCapacity, + dateCreated, + dateUpdated, + sid, + taskChannelSid, + taskChannelUniqueName, + url, + workerSid, + workspaceSid ); } + + } + diff --git a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/worker/WorkerChannelFetcher.java b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/worker/WorkerChannelFetcher.java index db8dbbc150..fbdbbfdb4e 100644 --- a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/worker/WorkerChannelFetcher.java +++ b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/worker/WorkerChannelFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.taskrouter.v1.workspace.worker; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,66 +26,47 @@ public class WorkerChannelFetcher extends Fetcher { - private String pathWorkspaceSid; - private String pathWorkerSid; - private String pathSid; + private String pathworkspaceSid; + private String pathworkerSid; + private String pathsid; - public WorkerChannelFetcher( - final String pathWorkspaceSid, - final String pathWorkerSid, - final String pathSid - ) { - this.pathWorkspaceSid = pathWorkspaceSid; - this.pathWorkerSid = pathWorkerSid; - this.pathSid = pathSid; + public WorkerChannelFetcher(final String pathworkspaceSid, final String pathworkerSid, final String pathsid) { + this.pathworkspaceSid = pathworkspaceSid; + this.pathworkerSid = pathworkerSid; + this.pathsid = pathsid; } + @Override public WorkerChannel fetch(final TwilioRestClient client) { - String path = - "/v1/Workspaces/{WorkspaceSid}/Workers/{WorkerSid}/Channels/{Sid}"; - path = - path.replace( - "{" + "WorkspaceSid" + "}", - this.pathWorkspaceSid.toString() - ); - path = - path.replace( - "{" + "WorkerSid" + "}", - this.pathWorkerSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/v1/Workspaces/{WorkspaceSid}/Workers/{WorkerSid}/Channels/{Sid}"; + + path = path.replace("{" + "WorkspaceSid" + "}", this.pathworkspaceSid.toString()); + path = path.replace("{" + "WorkerSid" + "}", this.pathworkerSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.TASKROUTER.toString(), - path + HttpMethod.GET, + Domains.TASKROUTER.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "WorkerChannel fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("WorkerChannel fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return WorkerChannel.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return WorkerChannel.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/worker/WorkerChannelReader.java b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/worker/WorkerChannelReader.java index 10afb3e69f..f2b393fa2a 100644 --- a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/worker/WorkerChannelReader.java +++ b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/worker/WorkerChannelReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,126 +30,91 @@ public class WorkerChannelReader extends Reader { - private String pathWorkspaceSid; - private String pathWorkerSid; + private String pathworkspaceSid; + private String pathworkerSid; private Long pageSize; - public WorkerChannelReader( - final String pathWorkspaceSid, - final String pathWorkerSid - ) { - this.pathWorkspaceSid = pathWorkspaceSid; - this.pathWorkerSid = pathWorkerSid; + public WorkerChannelReader(final String pathworkspaceSid, final String pathworkerSid) { + this.pathworkspaceSid = pathworkspaceSid; + this.pathworkerSid = pathworkerSid; } + public WorkerChannelReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { - String path = - "/v1/Workspaces/{WorkspaceSid}/Workers/{WorkerSid}/Channels"; - path = - path.replace( - "{" + "WorkspaceSid" + "}", - this.pathWorkspaceSid.toString() - ); - path = - path.replace( - "{" + "WorkerSid" + "}", - this.pathWorkerSid.toString() - ); + + String path = "/v1/Workspaces/{WorkspaceSid}/Workers/{WorkerSid}/Channels"; + + path = path.replace("{" + "WorkspaceSid" + "}", this.pathworkspaceSid.toString()); + path = path.replace("{" + "WorkerSid" + "}", this.pathworkerSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.TASKROUTER.toString(), - path + HttpMethod.GET, + Domains.TASKROUTER.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "WorkerChannel read failed: Unable to connect to server" - ); + throw new ApiConnectionException("WorkerChannel read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "channels", - response.getContent(), - WorkerChannel.class, - client.getObjectMapper() - ); + "channels", + response.getContent(), + WorkerChannel.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.TASKROUTER.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.TASKROUTER.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/worker/WorkerChannelUpdater.java b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/worker/WorkerChannelUpdater.java index 73399fd434..8e8b495872 100644 --- a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/worker/WorkerChannelUpdater.java +++ b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/worker/WorkerChannelUpdater.java @@ -16,6 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -26,88 +28,78 @@ import com.twilio.rest.Domains; public class WorkerChannelUpdater extends Updater { - - private String pathWorkspaceSid; - private String pathWorkerSid; - private String pathSid; + private String pathworkspaceSid; + private String pathworkerSid; + private String pathsid; private Integer capacity; private Boolean available; - public WorkerChannelUpdater( - final String pathWorkspaceSid, - final String pathWorkerSid, - final String pathSid - ) { - this.pathWorkspaceSid = pathWorkspaceSid; - this.pathWorkerSid = pathWorkerSid; - this.pathSid = pathSid; + public WorkerChannelUpdater(final String pathworkspaceSid, final String pathworkerSid, final String pathsid) { + this.pathworkspaceSid = pathworkspaceSid; + this.pathworkerSid = pathworkerSid; + this.pathsid = pathsid; } + public WorkerChannelUpdater setCapacity(final Integer capacity) { this.capacity = capacity; return this; } + public WorkerChannelUpdater setAvailable(final Boolean available) { this.available = available; return this; } + @Override public WorkerChannel update(final TwilioRestClient client) { - String path = - "/v1/Workspaces/{WorkspaceSid}/Workers/{WorkerSid}/Channels/{Sid}"; - path = - path.replace( - "{" + "WorkspaceSid" + "}", - this.pathWorkspaceSid.toString() - ); - path = - path.replace( - "{" + "WorkerSid" + "}", - this.pathWorkerSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/v1/Workspaces/{WorkspaceSid}/Workers/{WorkerSid}/Channels/{Sid}"; + + path = path.replace("{" + "WorkspaceSid" + "}", this.pathworkspaceSid.toString()); + path = path.replace("{" + "WorkerSid" + "}", this.pathworkerSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.TASKROUTER.toString(), - path + HttpMethod.POST, + Domains.TASKROUTER.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "WorkerChannel update failed: Unable to connect to server" - ); + throw new ApiConnectionException("WorkerChannel update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return WorkerChannel.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return WorkerChannel.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (capacity != null) { - request.addPostParam("Capacity", capacity.toString()); + Serializer.toString(request, "Capacity", capacity, ParameterType.URLENCODED); } + + if (available != null) { - request.addPostParam("Available", available.toString()); + Serializer.toString(request, "Available", available, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/worker/WorkerStatistics.java b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/worker/WorkerStatistics.java index d2ab882d7d..c744097485 100644 --- a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/worker/WorkerStatistics.java +++ b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/worker/WorkerStatistics.java @@ -18,44 +18,40 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; -import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class WorkerStatistics extends Resource { - private static final long serialVersionUID = 54379371741662L; - public static WorkerStatisticsFetcher fetcher( - final String pathWorkspaceSid, - final String pathWorkerSid - ) { - return new WorkerStatisticsFetcher(pathWorkspaceSid, pathWorkerSid); + public static WorkerStatisticsFetcher fetcher(final String pathworkspaceSid, final String pathworkerSid) { + return new WorkerStatisticsFetcher( + pathworkspaceSid, pathworkerSid + ); } + /** * Converts a JSON String into a WorkerStatistics object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return WorkerStatistics object represented by the provided JSON */ - public static WorkerStatistics fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static WorkerStatistics fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, WorkerStatistics.class); @@ -70,14 +66,11 @@ public static WorkerStatistics fromJson( * Converts a JSON InputStream into a WorkerStatistics object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return WorkerStatistics object represented by the provided JSON */ - public static WorkerStatistics fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static WorkerStatistics fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, WorkerStatistics.class); @@ -88,45 +81,43 @@ public static WorkerStatistics fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final Map cumulative; + @Getter + private final Object cumulative; + @Getter + private final URI url; + @Getter private final String workerSid; + @Getter private final String workspaceSid; - private final URI url; @JsonCreator private WorkerStatistics( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("cumulative") final Map cumulative, - @JsonProperty("worker_sid") final String workerSid, - @JsonProperty("workspace_sid") final String workspaceSid, - @JsonProperty("url") final URI url + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("cumulative") final Object cumulative, + @JsonProperty("url") final URI url, + @JsonProperty("worker_sid") final String workerSid, + @JsonProperty("workspace_sid") final String workspaceSid ) { this.accountSid = accountSid; this.cumulative = cumulative; + this.url = url; this.workerSid = workerSid; this.workspaceSid = workspaceSid; - this.url = url; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final Map getCumulative() { - return this.cumulative; - } - - public final String getWorkerSid() { - return this.workerSid; - } - - public final String getWorkspaceSid() { - return this.workspaceSid; - } - - public final URI getUrl() { - return this.url; } @Override @@ -140,24 +131,26 @@ public boolean equals(final Object o) { } WorkerStatistics other = (WorkerStatistics) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(cumulative, other.cumulative) && - Objects.equals(workerSid, other.workerSid) && - Objects.equals(workspaceSid, other.workspaceSid) && - Objects.equals(url, other.url) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(cumulative, other.cumulative) && + Objects.equals(url, other.url) && + Objects.equals(workerSid, other.workerSid) && + Objects.equals(workspaceSid, other.workspaceSid) ); } @Override public int hashCode() { return Objects.hash( - accountSid, - cumulative, - workerSid, - workspaceSid, - url + accountSid, + cumulative, + url, + workerSid, + workspaceSid ); } + + } + diff --git a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/worker/WorkerStatisticsFetcher.java b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/worker/WorkerStatisticsFetcher.java index b3e9bce4e6..a309c6952b 100644 --- a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/worker/WorkerStatisticsFetcher.java +++ b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/worker/WorkerStatisticsFetcher.java @@ -15,7 +15,8 @@ package com.twilio.rest.taskrouter.v1.workspace.worker; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -24,111 +25,103 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.time.ZonedDateTime; public class WorkerStatisticsFetcher extends Fetcher { - private String pathWorkspaceSid; - private String pathWorkerSid; + private String pathworkspaceSid; + private String pathworkerSid; private Integer minutes; private ZonedDateTime startDate; private ZonedDateTime endDate; private String taskChannel; - public WorkerStatisticsFetcher( - final String pathWorkspaceSid, - final String pathWorkerSid - ) { - this.pathWorkspaceSid = pathWorkspaceSid; - this.pathWorkerSid = pathWorkerSid; + public WorkerStatisticsFetcher(final String pathworkspaceSid, final String pathworkerSid) { + this.pathworkspaceSid = pathworkspaceSid; + this.pathworkerSid = pathworkerSid; } + public WorkerStatisticsFetcher setMinutes(final Integer minutes) { this.minutes = minutes; return this; } + public WorkerStatisticsFetcher setStartDate(final ZonedDateTime startDate) { this.startDate = startDate; return this; } + public WorkerStatisticsFetcher setEndDate(final ZonedDateTime endDate) { this.endDate = endDate; return this; } + public WorkerStatisticsFetcher setTaskChannel(final String taskChannel) { this.taskChannel = taskChannel; return this; } + @Override public WorkerStatistics fetch(final TwilioRestClient client) { - String path = - "/v1/Workspaces/{WorkspaceSid}/Workers/{WorkerSid}/Statistics"; - path = - path.replace( - "{" + "WorkspaceSid" + "}", - this.pathWorkspaceSid.toString() - ); - path = - path.replace( - "{" + "WorkerSid" + "}", - this.pathWorkerSid.toString() - ); + String path = "/v1/Workspaces/{WorkspaceSid}/Workers/{WorkerSid}/Statistics"; + + path = path.replace("{" + "WorkspaceSid" + "}", this.pathworkspaceSid.toString()); + path = path.replace("{" + "WorkerSid" + "}", this.pathworkerSid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.TASKROUTER.toString(), - path + HttpMethod.GET, + Domains.TASKROUTER.toString(), + path ); addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "WorkerStatistics fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("WorkerStatistics fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return WorkerStatistics.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return WorkerStatistics.fromJson(response.getStream(), client.getObjectMapper()); } private void addQueryParams(final Request request) { + + if (minutes != null) { - request.addQueryParam("Minutes", minutes.toString()); + Serializer.toString(request, "Minutes", minutes, ParameterType.QUERY); } + + if (startDate != null) { - request.addQueryParam( - "StartDate", - startDate.toInstant().toString() - ); + Serializer.toString(request, "StartDate", startDate, ParameterType.QUERY); } + if (endDate != null) { - request.addQueryParam("EndDate", endDate.toInstant().toString()); + Serializer.toString(request, "EndDate", endDate, ParameterType.QUERY); } + if (taskChannel != null) { - request.addQueryParam("TaskChannel", taskChannel); + Serializer.toString(request, "TaskChannel", taskChannel, ParameterType.QUERY); } + + } } diff --git a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/worker/WorkersCumulativeStatistics.java b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/worker/WorkersCumulativeStatistics.java index 636829bfe2..010cbd44de 100644 --- a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/worker/WorkersCumulativeStatistics.java +++ b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/worker/WorkersCumulativeStatistics.java @@ -18,52 +18,46 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.List; -import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class WorkersCumulativeStatistics extends Resource { - private static final long serialVersionUID = 68159864681377L; - public static WorkersCumulativeStatisticsFetcher fetcher( - final String pathWorkspaceSid - ) { - return new WorkersCumulativeStatisticsFetcher(pathWorkspaceSid); + public static WorkersCumulativeStatisticsFetcher fetcher(final String pathworkspaceSid) { + return new WorkersCumulativeStatisticsFetcher( + pathworkspaceSid + ); } + /** * Converts a JSON String into a WorkersCumulativeStatistics object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return WorkersCumulativeStatistics object represented by the provided JSON */ - public static WorkersCumulativeStatistics fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static WorkersCumulativeStatistics fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { - return objectMapper.readValue( - json, - WorkersCumulativeStatistics.class - ); + return objectMapper.readValue(json, WorkersCumulativeStatistics.class); } catch (final JsonMappingException | JsonParseException e) { throw new ApiException(e.getMessage(), e); } catch (final IOException e) { @@ -75,20 +69,14 @@ public static WorkersCumulativeStatistics fromJson( * Converts a JSON InputStream into a WorkersCumulativeStatistics object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return WorkersCumulativeStatistics object represented by the provided JSON */ - public static WorkersCumulativeStatistics fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static WorkersCumulativeStatistics fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { - return objectMapper.readValue( - json, - WorkersCumulativeStatistics.class - ); + return objectMapper.readValue(json, WorkersCumulativeStatistics.class); } catch (final JsonMappingException | JsonParseException e) { throw new ApiException(e.getMessage(), e); } catch (final IOException e) { @@ -96,106 +84,73 @@ public static WorkersCumulativeStatistics fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final ZonedDateTime startTime; + @Getter + private final List activityDurations; + @Getter private final ZonedDateTime endTime; - private final List> activityDurations; - private final Integer reservationsCreated; + @Getter private final Integer reservationsAccepted; - private final Integer reservationsRejected; - private final Integer reservationsTimedOut; + @Getter private final Integer reservationsCanceled; + @Getter + private final Integer reservationsCreated; + @Getter + private final Integer reservationsRejected; + @Getter private final Integer reservationsRescinded; - private final String workspaceSid; + @Getter + private final Integer reservationsTimedOut; + @Getter + private final ZonedDateTime startTime; + @Getter private final URI url; + @Getter + private final String workspaceSid; @JsonCreator private WorkersCumulativeStatistics( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("start_time") final String startTime, - @JsonProperty("end_time") final String endTime, - @JsonProperty("activity_durations") final List< - Map - > activityDurations, - @JsonProperty("reservations_created") final Integer reservationsCreated, - @JsonProperty( - "reservations_accepted" - ) final Integer reservationsAccepted, - @JsonProperty( - "reservations_rejected" - ) final Integer reservationsRejected, - @JsonProperty( - "reservations_timed_out" - ) final Integer reservationsTimedOut, - @JsonProperty( - "reservations_canceled" - ) final Integer reservationsCanceled, - @JsonProperty( - "reservations_rescinded" - ) final Integer reservationsRescinded, - @JsonProperty("workspace_sid") final String workspaceSid, - @JsonProperty("url") final URI url + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("activity_durations") final List activityDurations, + @JsonProperty("end_time") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime endTime, + @JsonProperty("reservations_accepted") final Integer reservationsAccepted, + @JsonProperty("reservations_canceled") final Integer reservationsCanceled, + @JsonProperty("reservations_created") final Integer reservationsCreated, + @JsonProperty("reservations_rejected") final Integer reservationsRejected, + @JsonProperty("reservations_rescinded") final Integer reservationsRescinded, + @JsonProperty("reservations_timed_out") final Integer reservationsTimedOut, + @JsonProperty("start_time") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime startTime, + @JsonProperty("url") final URI url, + @JsonProperty("workspace_sid") final String workspaceSid ) { this.accountSid = accountSid; - this.startTime = DateConverter.iso8601DateTimeFromString(startTime); - this.endTime = DateConverter.iso8601DateTimeFromString(endTime); this.activityDurations = activityDurations; - this.reservationsCreated = reservationsCreated; + this.endTime = endTime; this.reservationsAccepted = reservationsAccepted; - this.reservationsRejected = reservationsRejected; - this.reservationsTimedOut = reservationsTimedOut; this.reservationsCanceled = reservationsCanceled; + this.reservationsCreated = reservationsCreated; + this.reservationsRejected = reservationsRejected; this.reservationsRescinded = reservationsRescinded; - this.workspaceSid = workspaceSid; + this.reservationsTimedOut = reservationsTimedOut; + this.startTime = startTime; this.url = url; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final ZonedDateTime getStartTime() { - return this.startTime; - } - - public final ZonedDateTime getEndTime() { - return this.endTime; - } - - public final List> getActivityDurations() { - return this.activityDurations; - } - - public final Integer getReservationsCreated() { - return this.reservationsCreated; - } - - public final Integer getReservationsAccepted() { - return this.reservationsAccepted; - } - - public final Integer getReservationsRejected() { - return this.reservationsRejected; - } - - public final Integer getReservationsTimedOut() { - return this.reservationsTimedOut; - } - - public final Integer getReservationsCanceled() { - return this.reservationsCanceled; - } - - public final Integer getReservationsRescinded() { - return this.reservationsRescinded; - } - - public final String getWorkspaceSid() { - return this.workspaceSid; - } - - public final URI getUrl() { - return this.url; + this.workspaceSid = workspaceSid; } @Override @@ -209,41 +164,40 @@ public boolean equals(final Object o) { } WorkersCumulativeStatistics other = (WorkersCumulativeStatistics) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(startTime, other.startTime) && - Objects.equals(endTime, other.endTime) && - Objects.equals(activityDurations, other.activityDurations) && - Objects.equals(reservationsCreated, other.reservationsCreated) && - Objects.equals(reservationsAccepted, other.reservationsAccepted) && - Objects.equals(reservationsRejected, other.reservationsRejected) && - Objects.equals(reservationsTimedOut, other.reservationsTimedOut) && - Objects.equals(reservationsCanceled, other.reservationsCanceled) && - Objects.equals( - reservationsRescinded, - other.reservationsRescinded - ) && - Objects.equals(workspaceSid, other.workspaceSid) && - Objects.equals(url, other.url) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(activityDurations, other.activityDurations) && + Objects.equals(endTime, other.endTime) && + Objects.equals(reservationsAccepted, other.reservationsAccepted) && + Objects.equals(reservationsCanceled, other.reservationsCanceled) && + Objects.equals(reservationsCreated, other.reservationsCreated) && + Objects.equals(reservationsRejected, other.reservationsRejected) && + Objects.equals(reservationsRescinded, other.reservationsRescinded) && + Objects.equals(reservationsTimedOut, other.reservationsTimedOut) && + Objects.equals(startTime, other.startTime) && + Objects.equals(url, other.url) && + Objects.equals(workspaceSid, other.workspaceSid) ); } @Override public int hashCode() { return Objects.hash( - accountSid, - startTime, - endTime, - activityDurations, - reservationsCreated, - reservationsAccepted, - reservationsRejected, - reservationsTimedOut, - reservationsCanceled, - reservationsRescinded, - workspaceSid, - url + accountSid, + activityDurations, + endTime, + reservationsAccepted, + reservationsCanceled, + reservationsCreated, + reservationsRejected, + reservationsRescinded, + reservationsTimedOut, + startTime, + url, + workspaceSid ); } + + } + diff --git a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/worker/WorkersCumulativeStatisticsFetcher.java b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/worker/WorkersCumulativeStatisticsFetcher.java index de9520bf76..9c07079c4c 100644 --- a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/worker/WorkersCumulativeStatisticsFetcher.java +++ b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/worker/WorkersCumulativeStatisticsFetcher.java @@ -15,7 +15,8 @@ package com.twilio.rest.taskrouter.v1.workspace.worker; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -24,110 +25,100 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.time.ZonedDateTime; -public class WorkersCumulativeStatisticsFetcher - extends Fetcher { +public class WorkersCumulativeStatisticsFetcher extends Fetcher { - private String pathWorkspaceSid; + private String pathworkspaceSid; private ZonedDateTime endDate; private Integer minutes; private ZonedDateTime startDate; private String taskChannel; - public WorkersCumulativeStatisticsFetcher(final String pathWorkspaceSid) { - this.pathWorkspaceSid = pathWorkspaceSid; + public WorkersCumulativeStatisticsFetcher(final String pathworkspaceSid) { + this.pathworkspaceSid = pathworkspaceSid; } - public WorkersCumulativeStatisticsFetcher setEndDate( - final ZonedDateTime endDate - ) { + + public WorkersCumulativeStatisticsFetcher setEndDate(final ZonedDateTime endDate) { this.endDate = endDate; return this; } - public WorkersCumulativeStatisticsFetcher setMinutes( - final Integer minutes - ) { + + public WorkersCumulativeStatisticsFetcher setMinutes(final Integer minutes) { this.minutes = minutes; return this; } - public WorkersCumulativeStatisticsFetcher setStartDate( - final ZonedDateTime startDate - ) { + + public WorkersCumulativeStatisticsFetcher setStartDate(final ZonedDateTime startDate) { this.startDate = startDate; return this; } - public WorkersCumulativeStatisticsFetcher setTaskChannel( - final String taskChannel - ) { + + public WorkersCumulativeStatisticsFetcher setTaskChannel(final String taskChannel) { this.taskChannel = taskChannel; return this; } + @Override public WorkersCumulativeStatistics fetch(final TwilioRestClient client) { - String path = - "/v1/Workspaces/{WorkspaceSid}/Workers/CumulativeStatistics"; - path = - path.replace( - "{" + "WorkspaceSid" + "}", - this.pathWorkspaceSid.toString() - ); + String path = "/v1/Workspaces/{WorkspaceSid}/Workers/CumulativeStatistics"; + + path = path.replace("{" + "WorkspaceSid" + "}", this.pathworkspaceSid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.TASKROUTER.toString(), - path + HttpMethod.GET, + Domains.TASKROUTER.toString(), + path ); addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "WorkersCumulativeStatistics fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("WorkersCumulativeStatistics fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return WorkersCumulativeStatistics.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return WorkersCumulativeStatistics.fromJson(response.getStream(), client.getObjectMapper()); } private void addQueryParams(final Request request) { + + if (endDate != null) { - request.addQueryParam("EndDate", endDate.toInstant().toString()); + Serializer.toString(request, "EndDate", endDate, ParameterType.QUERY); } + if (minutes != null) { - request.addQueryParam("Minutes", minutes.toString()); + Serializer.toString(request, "Minutes", minutes, ParameterType.QUERY); } + + if (startDate != null) { - request.addQueryParam( - "StartDate", - startDate.toInstant().toString() - ); + Serializer.toString(request, "StartDate", startDate, ParameterType.QUERY); } + if (taskChannel != null) { - request.addQueryParam("TaskChannel", taskChannel); + Serializer.toString(request, "TaskChannel", taskChannel, ParameterType.QUERY); } + + } } diff --git a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/worker/WorkersRealTimeStatistics.java b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/worker/WorkersRealTimeStatistics.java index 6f5eddbe73..3e3e40018b 100644 --- a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/worker/WorkersRealTimeStatistics.java +++ b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/worker/WorkersRealTimeStatistics.java @@ -18,50 +18,44 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.util.List; -import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class WorkersRealTimeStatistics extends Resource { - private static final long serialVersionUID = 209947407394347L; - public static WorkersRealTimeStatisticsFetcher fetcher( - final String pathWorkspaceSid - ) { - return new WorkersRealTimeStatisticsFetcher(pathWorkspaceSid); + public static WorkersRealTimeStatisticsFetcher fetcher(final String pathworkspaceSid) { + return new WorkersRealTimeStatisticsFetcher( + pathworkspaceSid + ); } + /** * Converts a JSON String into a WorkersRealTimeStatistics object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return WorkersRealTimeStatistics object represented by the provided JSON */ - public static WorkersRealTimeStatistics fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static WorkersRealTimeStatistics fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { - return objectMapper.readValue( - json, - WorkersRealTimeStatistics.class - ); + return objectMapper.readValue(json, WorkersRealTimeStatistics.class); } catch (final JsonMappingException | JsonParseException e) { throw new ApiException(e.getMessage(), e); } catch (final IOException e) { @@ -73,20 +67,14 @@ public static WorkersRealTimeStatistics fromJson( * Converts a JSON InputStream into a WorkersRealTimeStatistics object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return WorkersRealTimeStatistics object represented by the provided JSON */ - public static WorkersRealTimeStatistics fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static WorkersRealTimeStatistics fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { - return objectMapper.readValue( - json, - WorkersRealTimeStatistics.class - ); + return objectMapper.readValue(json, WorkersRealTimeStatistics.class); } catch (final JsonMappingException | JsonParseException e) { throw new ApiException(e.getMessage(), e); } catch (final IOException e) { @@ -94,47 +82,43 @@ public static WorkersRealTimeStatistics fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final List> activityStatistics; + @Getter + private final List activityStatistics; + @Getter private final Integer totalWorkers; - private final String workspaceSid; + @Getter private final URI url; + @Getter + private final String workspaceSid; @JsonCreator private WorkersRealTimeStatistics( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("activity_statistics") final List< - Map - > activityStatistics, - @JsonProperty("total_workers") final Integer totalWorkers, - @JsonProperty("workspace_sid") final String workspaceSid, - @JsonProperty("url") final URI url + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("activity_statistics") final List activityStatistics, + @JsonProperty("total_workers") final Integer totalWorkers, + @JsonProperty("url") final URI url, + @JsonProperty("workspace_sid") final String workspaceSid ) { this.accountSid = accountSid; this.activityStatistics = activityStatistics; this.totalWorkers = totalWorkers; - this.workspaceSid = workspaceSid; this.url = url; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final List> getActivityStatistics() { - return this.activityStatistics; - } - - public final Integer getTotalWorkers() { - return this.totalWorkers; - } - - public final String getWorkspaceSid() { - return this.workspaceSid; - } - - public final URI getUrl() { - return this.url; + this.workspaceSid = workspaceSid; } @Override @@ -148,24 +132,26 @@ public boolean equals(final Object o) { } WorkersRealTimeStatistics other = (WorkersRealTimeStatistics) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(activityStatistics, other.activityStatistics) && - Objects.equals(totalWorkers, other.totalWorkers) && - Objects.equals(workspaceSid, other.workspaceSid) && - Objects.equals(url, other.url) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(activityStatistics, other.activityStatistics) && + Objects.equals(totalWorkers, other.totalWorkers) && + Objects.equals(url, other.url) && + Objects.equals(workspaceSid, other.workspaceSid) ); } @Override public int hashCode() { return Objects.hash( - accountSid, - activityStatistics, - totalWorkers, - workspaceSid, - url + accountSid, + activityStatistics, + totalWorkers, + url, + workspaceSid ); } + + } + diff --git a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/worker/WorkersRealTimeStatisticsFetcher.java b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/worker/WorkersRealTimeStatisticsFetcher.java index 0f2a2c7951..fc53ab9778 100644 --- a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/worker/WorkersRealTimeStatisticsFetcher.java +++ b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/worker/WorkersRealTimeStatisticsFetcher.java @@ -15,7 +15,8 @@ package com.twilio.rest.taskrouter.v1.workspace.worker; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,70 +26,61 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class WorkersRealTimeStatisticsFetcher - extends Fetcher { +public class WorkersRealTimeStatisticsFetcher extends Fetcher { - private String pathWorkspaceSid; + private String pathworkspaceSid; private String taskChannel; - public WorkersRealTimeStatisticsFetcher(final String pathWorkspaceSid) { - this.pathWorkspaceSid = pathWorkspaceSid; + public WorkersRealTimeStatisticsFetcher(final String pathworkspaceSid) { + this.pathworkspaceSid = pathworkspaceSid; } - public WorkersRealTimeStatisticsFetcher setTaskChannel( - final String taskChannel - ) { + + public WorkersRealTimeStatisticsFetcher setTaskChannel(final String taskChannel) { this.taskChannel = taskChannel; return this; } + @Override public WorkersRealTimeStatistics fetch(final TwilioRestClient client) { - String path = - "/v1/Workspaces/{WorkspaceSid}/Workers/RealTimeStatistics"; - path = - path.replace( - "{" + "WorkspaceSid" + "}", - this.pathWorkspaceSid.toString() - ); + String path = "/v1/Workspaces/{WorkspaceSid}/Workers/RealTimeStatistics"; + + path = path.replace("{" + "WorkspaceSid" + "}", this.pathworkspaceSid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.TASKROUTER.toString(), - path + HttpMethod.GET, + Domains.TASKROUTER.toString(), + path ); addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "WorkersRealTimeStatistics fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("WorkersRealTimeStatistics fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return WorkersRealTimeStatistics.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return WorkersRealTimeStatistics.fromJson(response.getStream(), client.getObjectMapper()); } private void addQueryParams(final Request request) { + + if (taskChannel != null) { - request.addQueryParam("TaskChannel", taskChannel); + Serializer.toString(request, "TaskChannel", taskChannel, ParameterType.QUERY); } + + } } diff --git a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/worker/WorkersStatistics.java b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/worker/WorkersStatistics.java index 5b3ee1f9bd..1877d247ca 100644 --- a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/worker/WorkersStatistics.java +++ b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/worker/WorkersStatistics.java @@ -18,43 +18,40 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; -import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class WorkersStatistics extends Resource { - private static final long serialVersionUID = 274987650256203L; - public static WorkersStatisticsFetcher fetcher( - final String pathWorkspaceSid - ) { - return new WorkersStatisticsFetcher(pathWorkspaceSid); + public static WorkersStatisticsFetcher fetcher(final String pathworkspaceSid) { + return new WorkersStatisticsFetcher( + pathworkspaceSid + ); } + /** * Converts a JSON String into a WorkersStatistics object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return WorkersStatistics object represented by the provided JSON */ - public static WorkersStatistics fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static WorkersStatistics fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, WorkersStatistics.class); @@ -69,14 +66,11 @@ public static WorkersStatistics fromJson( * Converts a JSON InputStream into a WorkersStatistics object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return WorkersStatistics object represented by the provided JSON */ - public static WorkersStatistics fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static WorkersStatistics fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, WorkersStatistics.class); @@ -87,45 +81,43 @@ public static WorkersStatistics fromJson( } } - private final Map realtime; - private final Map cumulative; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String workspaceSid; + @Getter + private final Object cumulative; + @Getter + private final Object realtime; + @Getter private final URI url; + @Getter + private final String workspaceSid; @JsonCreator private WorkersStatistics( - @JsonProperty("realtime") final Map realtime, - @JsonProperty("cumulative") final Map cumulative, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("workspace_sid") final String workspaceSid, - @JsonProperty("url") final URI url + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("cumulative") final Object cumulative, + @JsonProperty("realtime") final Object realtime, + @JsonProperty("url") final URI url, + @JsonProperty("workspace_sid") final String workspaceSid ) { - this.realtime = realtime; - this.cumulative = cumulative; this.accountSid = accountSid; - this.workspaceSid = workspaceSid; + this.cumulative = cumulative; + this.realtime = realtime; this.url = url; - } - - public final Map getRealtime() { - return this.realtime; - } - - public final Map getCumulative() { - return this.cumulative; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getWorkspaceSid() { - return this.workspaceSid; - } - - public final URI getUrl() { - return this.url; + this.workspaceSid = workspaceSid; } @Override @@ -139,24 +131,26 @@ public boolean equals(final Object o) { } WorkersStatistics other = (WorkersStatistics) o; - return ( - Objects.equals(realtime, other.realtime) && - Objects.equals(cumulative, other.cumulative) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(workspaceSid, other.workspaceSid) && - Objects.equals(url, other.url) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(cumulative, other.cumulative) && + Objects.equals(realtime, other.realtime) && + Objects.equals(url, other.url) && + Objects.equals(workspaceSid, other.workspaceSid) ); } @Override public int hashCode() { return Objects.hash( - realtime, - cumulative, - accountSid, - workspaceSid, - url + accountSid, + cumulative, + realtime, + url, + workspaceSid ); } + + } + diff --git a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/worker/WorkersStatisticsFetcher.java b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/worker/WorkersStatisticsFetcher.java index 970837f721..48cba038a3 100644 --- a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/worker/WorkersStatisticsFetcher.java +++ b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/worker/WorkersStatisticsFetcher.java @@ -15,7 +15,8 @@ package com.twilio.rest.taskrouter.v1.workspace.worker; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -24,11 +25,12 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.time.ZonedDateTime; public class WorkersStatisticsFetcher extends Fetcher { - private String pathWorkspaceSid; + private String pathworkspaceSid; private Integer minutes; private ZonedDateTime startDate; private ZonedDateTime endDate; @@ -37,118 +39,122 @@ public class WorkersStatisticsFetcher extends Fetcher { private String friendlyName; private String taskChannel; - public WorkersStatisticsFetcher(final String pathWorkspaceSid) { - this.pathWorkspaceSid = pathWorkspaceSid; + public WorkersStatisticsFetcher(final String pathworkspaceSid) { + this.pathworkspaceSid = pathworkspaceSid; } + public WorkersStatisticsFetcher setMinutes(final Integer minutes) { this.minutes = minutes; return this; } - public WorkersStatisticsFetcher setStartDate( - final ZonedDateTime startDate - ) { + + public WorkersStatisticsFetcher setStartDate(final ZonedDateTime startDate) { this.startDate = startDate; return this; } + public WorkersStatisticsFetcher setEndDate(final ZonedDateTime endDate) { this.endDate = endDate; return this; } + public WorkersStatisticsFetcher setTaskQueueSid(final String taskQueueSid) { this.taskQueueSid = taskQueueSid; return this; } - public WorkersStatisticsFetcher setTaskQueueName( - final String taskQueueName - ) { + + public WorkersStatisticsFetcher setTaskQueueName(final String taskQueueName) { this.taskQueueName = taskQueueName; return this; } + public WorkersStatisticsFetcher setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + public WorkersStatisticsFetcher setTaskChannel(final String taskChannel) { this.taskChannel = taskChannel; return this; } + @Override public WorkersStatistics fetch(final TwilioRestClient client) { + String path = "/v1/Workspaces/{WorkspaceSid}/Workers/Statistics"; - path = - path.replace( - "{" + "WorkspaceSid" + "}", - this.pathWorkspaceSid.toString() - ); + path = path.replace("{" + "WorkspaceSid" + "}", this.pathworkspaceSid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.TASKROUTER.toString(), - path + HttpMethod.GET, + Domains.TASKROUTER.toString(), + path ); addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "WorkersStatistics fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("WorkersStatistics fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return WorkersStatistics.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return WorkersStatistics.fromJson(response.getStream(), client.getObjectMapper()); } private void addQueryParams(final Request request) { + + if (minutes != null) { - request.addQueryParam("Minutes", minutes.toString()); + Serializer.toString(request, "Minutes", minutes, ParameterType.QUERY); } + + if (startDate != null) { - request.addQueryParam( - "StartDate", - startDate.toInstant().toString() - ); + Serializer.toString(request, "StartDate", startDate, ParameterType.QUERY); } + if (endDate != null) { - request.addQueryParam("EndDate", endDate.toInstant().toString()); + Serializer.toString(request, "EndDate", endDate, ParameterType.QUERY); } + if (taskQueueSid != null) { - request.addQueryParam("TaskQueueSid", taskQueueSid); + Serializer.toString(request, "TaskQueueSid", taskQueueSid, ParameterType.QUERY); } + + if (taskQueueName != null) { - request.addQueryParam("TaskQueueName", taskQueueName); + Serializer.toString(request, "TaskQueueName", taskQueueName, ParameterType.QUERY); } + + if (friendlyName != null) { - request.addQueryParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.QUERY); } + + if (taskChannel != null) { - request.addQueryParam("TaskChannel", taskChannel); + Serializer.toString(request, "TaskChannel", taskChannel, ParameterType.QUERY); } + + } } diff --git a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/workflow/WorkflowCumulativeStatistics.java b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/workflow/WorkflowCumulativeStatistics.java index fc7e6e51e3..12ea5f3d8f 100644 --- a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/workflow/WorkflowCumulativeStatistics.java +++ b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/workflow/WorkflowCumulativeStatistics.java @@ -18,55 +18,45 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; -import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class WorkflowCumulativeStatistics extends Resource { - private static final long serialVersionUID = 209789504024863L; - public static WorkflowCumulativeStatisticsFetcher fetcher( - final String pathWorkspaceSid, - final String pathWorkflowSid - ) { + public static WorkflowCumulativeStatisticsFetcher fetcher(final String pathworkspaceSid, final String pathworkflowSid) { return new WorkflowCumulativeStatisticsFetcher( - pathWorkspaceSid, - pathWorkflowSid + pathworkspaceSid, pathworkflowSid ); } + /** * Converts a JSON String into a WorkflowCumulativeStatistics object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return WorkflowCumulativeStatistics object represented by the provided JSON */ - public static WorkflowCumulativeStatistics fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static WorkflowCumulativeStatistics fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { - return objectMapper.readValue( - json, - WorkflowCumulativeStatistics.class - ); + return objectMapper.readValue(json, WorkflowCumulativeStatistics.class); } catch (final JsonMappingException | JsonParseException e) { throw new ApiException(e.getMessage(), e); } catch (final IOException e) { @@ -78,20 +68,14 @@ public static WorkflowCumulativeStatistics fromJson( * Converts a JSON InputStream into a WorkflowCumulativeStatistics object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return WorkflowCumulativeStatistics object represented by the provided JSON */ - public static WorkflowCumulativeStatistics fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static WorkflowCumulativeStatistics fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { - return objectMapper.readValue( - json, - WorkflowCumulativeStatistics.class - ); + return objectMapper.readValue(json, WorkflowCumulativeStatistics.class); } catch (final JsonMappingException | JsonParseException e) { throw new ApiException(e.getMessage(), e); } catch (final IOException e) { @@ -99,187 +83,113 @@ public static WorkflowCumulativeStatistics fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; + @Getter private final Integer avgTaskAcceptanceTime; - private final ZonedDateTime startTime; + @Getter private final ZonedDateTime endTime; - private final Integer reservationsCreated; + @Getter private final Integer reservationsAccepted; - private final Integer reservationsRejected; - private final Integer reservationsTimedOut; + @Getter private final Integer reservationsCanceled; + @Getter + private final Integer reservationsCreated; + @Getter + private final Integer reservationsRejected; + @Getter private final Integer reservationsRescinded; - private final Map splitByWaitTime; - private final Map waitDurationUntilAccepted; - private final Map waitDurationUntilCanceled; + @Getter + private final Integer reservationsTimedOut; + @Getter + private final Object splitByWaitTime; + @Getter + private final ZonedDateTime startTime; + @Getter private final Integer tasksCanceled; + @Getter private final Integer tasksCompleted; - private final Integer tasksEntered; + @Getter private final Integer tasksDeleted; + @Getter + private final Integer tasksEntered; + @Getter private final Integer tasksMoved; + @Getter private final Integer tasksTimedOutInWorkflow; + @Getter + private final URI url; + @Getter + private final Object waitDurationUntilAccepted; + @Getter + private final Object waitDurationUntilCanceled; + @Getter private final String workflowSid; + @Getter private final String workspaceSid; - private final URI url; @JsonCreator private WorkflowCumulativeStatistics( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty( - "avg_task_acceptance_time" - ) final Integer avgTaskAcceptanceTime, - @JsonProperty("start_time") final String startTime, - @JsonProperty("end_time") final String endTime, - @JsonProperty("reservations_created") final Integer reservationsCreated, - @JsonProperty( - "reservations_accepted" - ) final Integer reservationsAccepted, - @JsonProperty( - "reservations_rejected" - ) final Integer reservationsRejected, - @JsonProperty( - "reservations_timed_out" - ) final Integer reservationsTimedOut, - @JsonProperty( - "reservations_canceled" - ) final Integer reservationsCanceled, - @JsonProperty( - "reservations_rescinded" - ) final Integer reservationsRescinded, - @JsonProperty("split_by_wait_time") final Map< - String, - Object - > splitByWaitTime, - @JsonProperty("wait_duration_until_accepted") final Map< - String, - Object - > waitDurationUntilAccepted, - @JsonProperty("wait_duration_until_canceled") final Map< - String, - Object - > waitDurationUntilCanceled, - @JsonProperty("tasks_canceled") final Integer tasksCanceled, - @JsonProperty("tasks_completed") final Integer tasksCompleted, - @JsonProperty("tasks_entered") final Integer tasksEntered, - @JsonProperty("tasks_deleted") final Integer tasksDeleted, - @JsonProperty("tasks_moved") final Integer tasksMoved, - @JsonProperty( - "tasks_timed_out_in_workflow" - ) final Integer tasksTimedOutInWorkflow, - @JsonProperty("workflow_sid") final String workflowSid, - @JsonProperty("workspace_sid") final String workspaceSid, - @JsonProperty("url") final URI url + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("avg_task_acceptance_time") final Integer avgTaskAcceptanceTime, + @JsonProperty("end_time") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime endTime, + @JsonProperty("reservations_accepted") final Integer reservationsAccepted, + @JsonProperty("reservations_canceled") final Integer reservationsCanceled, + @JsonProperty("reservations_created") final Integer reservationsCreated, + @JsonProperty("reservations_rejected") final Integer reservationsRejected, + @JsonProperty("reservations_rescinded") final Integer reservationsRescinded, + @JsonProperty("reservations_timed_out") final Integer reservationsTimedOut, + @JsonProperty("split_by_wait_time") final Object splitByWaitTime, + @JsonProperty("start_time") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime startTime, + @JsonProperty("tasks_canceled") final Integer tasksCanceled, + @JsonProperty("tasks_completed") final Integer tasksCompleted, + @JsonProperty("tasks_deleted") final Integer tasksDeleted, + @JsonProperty("tasks_entered") final Integer tasksEntered, + @JsonProperty("tasks_moved") final Integer tasksMoved, + @JsonProperty("tasks_timed_out_in_workflow") final Integer tasksTimedOutInWorkflow, + @JsonProperty("url") final URI url, + @JsonProperty("wait_duration_until_accepted") final Object waitDurationUntilAccepted, + @JsonProperty("wait_duration_until_canceled") final Object waitDurationUntilCanceled, + @JsonProperty("workflow_sid") final String workflowSid, + @JsonProperty("workspace_sid") final String workspaceSid ) { this.accountSid = accountSid; this.avgTaskAcceptanceTime = avgTaskAcceptanceTime; - this.startTime = DateConverter.iso8601DateTimeFromString(startTime); - this.endTime = DateConverter.iso8601DateTimeFromString(endTime); - this.reservationsCreated = reservationsCreated; + this.endTime = endTime; this.reservationsAccepted = reservationsAccepted; - this.reservationsRejected = reservationsRejected; - this.reservationsTimedOut = reservationsTimedOut; this.reservationsCanceled = reservationsCanceled; + this.reservationsCreated = reservationsCreated; + this.reservationsRejected = reservationsRejected; this.reservationsRescinded = reservationsRescinded; + this.reservationsTimedOut = reservationsTimedOut; this.splitByWaitTime = splitByWaitTime; - this.waitDurationUntilAccepted = waitDurationUntilAccepted; - this.waitDurationUntilCanceled = waitDurationUntilCanceled; + this.startTime = startTime; this.tasksCanceled = tasksCanceled; this.tasksCompleted = tasksCompleted; - this.tasksEntered = tasksEntered; this.tasksDeleted = tasksDeleted; + this.tasksEntered = tasksEntered; this.tasksMoved = tasksMoved; this.tasksTimedOutInWorkflow = tasksTimedOutInWorkflow; + this.url = url; + this.waitDurationUntilAccepted = waitDurationUntilAccepted; + this.waitDurationUntilCanceled = waitDurationUntilCanceled; this.workflowSid = workflowSid; this.workspaceSid = workspaceSid; - this.url = url; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final Integer getAvgTaskAcceptanceTime() { - return this.avgTaskAcceptanceTime; - } - - public final ZonedDateTime getStartTime() { - return this.startTime; - } - - public final ZonedDateTime getEndTime() { - return this.endTime; - } - - public final Integer getReservationsCreated() { - return this.reservationsCreated; - } - - public final Integer getReservationsAccepted() { - return this.reservationsAccepted; - } - - public final Integer getReservationsRejected() { - return this.reservationsRejected; - } - - public final Integer getReservationsTimedOut() { - return this.reservationsTimedOut; - } - - public final Integer getReservationsCanceled() { - return this.reservationsCanceled; - } - - public final Integer getReservationsRescinded() { - return this.reservationsRescinded; - } - - public final Map getSplitByWaitTime() { - return this.splitByWaitTime; - } - - public final Map getWaitDurationUntilAccepted() { - return this.waitDurationUntilAccepted; - } - - public final Map getWaitDurationUntilCanceled() { - return this.waitDurationUntilCanceled; - } - - public final Integer getTasksCanceled() { - return this.tasksCanceled; - } - - public final Integer getTasksCompleted() { - return this.tasksCompleted; - } - - public final Integer getTasksEntered() { - return this.tasksEntered; - } - - public final Integer getTasksDeleted() { - return this.tasksDeleted; - } - - public final Integer getTasksMoved() { - return this.tasksMoved; - } - - public final Integer getTasksTimedOutInWorkflow() { - return this.tasksTimedOutInWorkflow; - } - - public final String getWorkflowSid() { - return this.workflowSid; - } - - public final String getWorkspaceSid() { - return this.workspaceSid; - } - - public final URI getUrl() { - return this.url; } @Override @@ -293,73 +203,60 @@ public boolean equals(final Object o) { } WorkflowCumulativeStatistics other = (WorkflowCumulativeStatistics) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals( - avgTaskAcceptanceTime, - other.avgTaskAcceptanceTime - ) && - Objects.equals(startTime, other.startTime) && - Objects.equals(endTime, other.endTime) && - Objects.equals(reservationsCreated, other.reservationsCreated) && - Objects.equals(reservationsAccepted, other.reservationsAccepted) && - Objects.equals(reservationsRejected, other.reservationsRejected) && - Objects.equals(reservationsTimedOut, other.reservationsTimedOut) && - Objects.equals(reservationsCanceled, other.reservationsCanceled) && - Objects.equals( - reservationsRescinded, - other.reservationsRescinded - ) && - Objects.equals(splitByWaitTime, other.splitByWaitTime) && - Objects.equals( - waitDurationUntilAccepted, - other.waitDurationUntilAccepted - ) && - Objects.equals( - waitDurationUntilCanceled, - other.waitDurationUntilCanceled - ) && - Objects.equals(tasksCanceled, other.tasksCanceled) && - Objects.equals(tasksCompleted, other.tasksCompleted) && - Objects.equals(tasksEntered, other.tasksEntered) && - Objects.equals(tasksDeleted, other.tasksDeleted) && - Objects.equals(tasksMoved, other.tasksMoved) && - Objects.equals( - tasksTimedOutInWorkflow, - other.tasksTimedOutInWorkflow - ) && - Objects.equals(workflowSid, other.workflowSid) && - Objects.equals(workspaceSid, other.workspaceSid) && - Objects.equals(url, other.url) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(avgTaskAcceptanceTime, other.avgTaskAcceptanceTime) && + Objects.equals(endTime, other.endTime) && + Objects.equals(reservationsAccepted, other.reservationsAccepted) && + Objects.equals(reservationsCanceled, other.reservationsCanceled) && + Objects.equals(reservationsCreated, other.reservationsCreated) && + Objects.equals(reservationsRejected, other.reservationsRejected) && + Objects.equals(reservationsRescinded, other.reservationsRescinded) && + Objects.equals(reservationsTimedOut, other.reservationsTimedOut) && + Objects.equals(splitByWaitTime, other.splitByWaitTime) && + Objects.equals(startTime, other.startTime) && + Objects.equals(tasksCanceled, other.tasksCanceled) && + Objects.equals(tasksCompleted, other.tasksCompleted) && + Objects.equals(tasksDeleted, other.tasksDeleted) && + Objects.equals(tasksEntered, other.tasksEntered) && + Objects.equals(tasksMoved, other.tasksMoved) && + Objects.equals(tasksTimedOutInWorkflow, other.tasksTimedOutInWorkflow) && + Objects.equals(url, other.url) && + Objects.equals(waitDurationUntilAccepted, other.waitDurationUntilAccepted) && + Objects.equals(waitDurationUntilCanceled, other.waitDurationUntilCanceled) && + Objects.equals(workflowSid, other.workflowSid) && + Objects.equals(workspaceSid, other.workspaceSid) ); } @Override public int hashCode() { return Objects.hash( - accountSid, - avgTaskAcceptanceTime, - startTime, - endTime, - reservationsCreated, - reservationsAccepted, - reservationsRejected, - reservationsTimedOut, - reservationsCanceled, - reservationsRescinded, - splitByWaitTime, - waitDurationUntilAccepted, - waitDurationUntilCanceled, - tasksCanceled, - tasksCompleted, - tasksEntered, - tasksDeleted, - tasksMoved, - tasksTimedOutInWorkflow, - workflowSid, - workspaceSid, - url + accountSid, + avgTaskAcceptanceTime, + endTime, + reservationsAccepted, + reservationsCanceled, + reservationsCreated, + reservationsRejected, + reservationsRescinded, + reservationsTimedOut, + splitByWaitTime, + startTime, + tasksCanceled, + tasksCompleted, + tasksDeleted, + tasksEntered, + tasksMoved, + tasksTimedOutInWorkflow, + url, + waitDurationUntilAccepted, + waitDurationUntilCanceled, + workflowSid, + workspaceSid ); } + + } + diff --git a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/workflow/WorkflowCumulativeStatisticsFetcher.java b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/workflow/WorkflowCumulativeStatisticsFetcher.java index e01b45bc64..3fb70bc16b 100644 --- a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/workflow/WorkflowCumulativeStatisticsFetcher.java +++ b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/workflow/WorkflowCumulativeStatisticsFetcher.java @@ -15,7 +15,8 @@ package com.twilio.rest.taskrouter.v1.workspace.workflow; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -24,131 +25,115 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.time.ZonedDateTime; -public class WorkflowCumulativeStatisticsFetcher - extends Fetcher { +public class WorkflowCumulativeStatisticsFetcher extends Fetcher { - private String pathWorkspaceSid; - private String pathWorkflowSid; + private String pathworkspaceSid; + private String pathworkflowSid; private ZonedDateTime endDate; private Integer minutes; private ZonedDateTime startDate; private String taskChannel; private String splitByWaitTime; - public WorkflowCumulativeStatisticsFetcher( - final String pathWorkspaceSid, - final String pathWorkflowSid - ) { - this.pathWorkspaceSid = pathWorkspaceSid; - this.pathWorkflowSid = pathWorkflowSid; + public WorkflowCumulativeStatisticsFetcher(final String pathworkspaceSid, final String pathworkflowSid) { + this.pathworkspaceSid = pathworkspaceSid; + this.pathworkflowSid = pathworkflowSid; } - public WorkflowCumulativeStatisticsFetcher setEndDate( - final ZonedDateTime endDate - ) { + + public WorkflowCumulativeStatisticsFetcher setEndDate(final ZonedDateTime endDate) { this.endDate = endDate; return this; } - public WorkflowCumulativeStatisticsFetcher setMinutes( - final Integer minutes - ) { + + public WorkflowCumulativeStatisticsFetcher setMinutes(final Integer minutes) { this.minutes = minutes; return this; } - public WorkflowCumulativeStatisticsFetcher setStartDate( - final ZonedDateTime startDate - ) { + + public WorkflowCumulativeStatisticsFetcher setStartDate(final ZonedDateTime startDate) { this.startDate = startDate; return this; } - public WorkflowCumulativeStatisticsFetcher setTaskChannel( - final String taskChannel - ) { + + public WorkflowCumulativeStatisticsFetcher setTaskChannel(final String taskChannel) { this.taskChannel = taskChannel; return this; } - public WorkflowCumulativeStatisticsFetcher setSplitByWaitTime( - final String splitByWaitTime - ) { + + public WorkflowCumulativeStatisticsFetcher setSplitByWaitTime(final String splitByWaitTime) { this.splitByWaitTime = splitByWaitTime; return this; } + @Override public WorkflowCumulativeStatistics fetch(final TwilioRestClient client) { - String path = - "/v1/Workspaces/{WorkspaceSid}/Workflows/{WorkflowSid}/CumulativeStatistics"; - path = - path.replace( - "{" + "WorkspaceSid" + "}", - this.pathWorkspaceSid.toString() - ); - path = - path.replace( - "{" + "WorkflowSid" + "}", - this.pathWorkflowSid.toString() - ); + String path = "/v1/Workspaces/{WorkspaceSid}/Workflows/{WorkflowSid}/CumulativeStatistics"; + + path = path.replace("{" + "WorkspaceSid" + "}", this.pathworkspaceSid.toString()); + path = path.replace("{" + "WorkflowSid" + "}", this.pathworkflowSid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.TASKROUTER.toString(), - path + HttpMethod.GET, + Domains.TASKROUTER.toString(), + path ); addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "WorkflowCumulativeStatistics fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("WorkflowCumulativeStatistics fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return WorkflowCumulativeStatistics.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return WorkflowCumulativeStatistics.fromJson(response.getStream(), client.getObjectMapper()); } private void addQueryParams(final Request request) { + + if (endDate != null) { - request.addQueryParam("EndDate", endDate.toInstant().toString()); + Serializer.toString(request, "EndDate", endDate, ParameterType.QUERY); } + if (minutes != null) { - request.addQueryParam("Minutes", minutes.toString()); + Serializer.toString(request, "Minutes", minutes, ParameterType.QUERY); } + + if (startDate != null) { - request.addQueryParam( - "StartDate", - startDate.toInstant().toString() - ); + Serializer.toString(request, "StartDate", startDate, ParameterType.QUERY); } + if (taskChannel != null) { - request.addQueryParam("TaskChannel", taskChannel); + Serializer.toString(request, "TaskChannel", taskChannel, ParameterType.QUERY); } + + if (splitByWaitTime != null) { - request.addQueryParam("SplitByWaitTime", splitByWaitTime); + Serializer.toString(request, "SplitByWaitTime", splitByWaitTime, ParameterType.QUERY); } + + } } diff --git a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/workflow/WorkflowRealTimeStatistics.java b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/workflow/WorkflowRealTimeStatistics.java index 6718215f1e..bbfc9b19c9 100644 --- a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/workflow/WorkflowRealTimeStatistics.java +++ b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/workflow/WorkflowRealTimeStatistics.java @@ -18,53 +18,43 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; -import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class WorkflowRealTimeStatistics extends Resource { - private static final long serialVersionUID = 5030697729646L; - public static WorkflowRealTimeStatisticsFetcher fetcher( - final String pathWorkspaceSid, - final String pathWorkflowSid - ) { + public static WorkflowRealTimeStatisticsFetcher fetcher(final String pathworkspaceSid, final String pathworkflowSid) { return new WorkflowRealTimeStatisticsFetcher( - pathWorkspaceSid, - pathWorkflowSid + pathworkspaceSid, pathworkflowSid ); } + /** * Converts a JSON String into a WorkflowRealTimeStatistics object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return WorkflowRealTimeStatistics object represented by the provided JSON */ - public static WorkflowRealTimeStatistics fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static WorkflowRealTimeStatistics fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { - return objectMapper.readValue( - json, - WorkflowRealTimeStatistics.class - ); + return objectMapper.readValue(json, WorkflowRealTimeStatistics.class); } catch (final JsonMappingException | JsonParseException e) { throw new ApiException(e.getMessage(), e); } catch (final IOException e) { @@ -76,20 +66,14 @@ public static WorkflowRealTimeStatistics fromJson( * Converts a JSON InputStream into a WorkflowRealTimeStatistics object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return WorkflowRealTimeStatistics object represented by the provided JSON */ - public static WorkflowRealTimeStatistics fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static WorkflowRealTimeStatistics fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { - return objectMapper.readValue( - json, - WorkflowRealTimeStatistics.class - ); + return objectMapper.readValue(json, WorkflowRealTimeStatistics.class); } catch (final JsonMappingException | JsonParseException e) { throw new ApiException(e.getMessage(), e); } catch (final IOException e) { @@ -97,37 +81,49 @@ public static WorkflowRealTimeStatistics fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; + @Getter private final Integer longestTaskWaitingAge; + @Getter private final String longestTaskWaitingSid; - private final Map tasksByPriority; - private final Map tasksByStatus; + @Getter + private final Object tasksByPriority; + @Getter + private final Object tasksByStatus; + @Getter private final Integer totalTasks; + @Getter + private final URI url; + @Getter private final String workflowSid; + @Getter private final String workspaceSid; - private final URI url; @JsonCreator private WorkflowRealTimeStatistics( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty( - "longest_task_waiting_age" - ) final Integer longestTaskWaitingAge, - @JsonProperty( - "longest_task_waiting_sid" - ) final String longestTaskWaitingSid, - @JsonProperty("tasks_by_priority") final Map< - String, - Object - > tasksByPriority, - @JsonProperty("tasks_by_status") final Map< - String, - Object - > tasksByStatus, - @JsonProperty("total_tasks") final Integer totalTasks, - @JsonProperty("workflow_sid") final String workflowSid, - @JsonProperty("workspace_sid") final String workspaceSid, - @JsonProperty("url") final URI url + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("longest_task_waiting_age") final Integer longestTaskWaitingAge, + @JsonProperty("longest_task_waiting_sid") final String longestTaskWaitingSid, + @JsonProperty("tasks_by_priority") final Object tasksByPriority, + @JsonProperty("tasks_by_status") final Object tasksByStatus, + @JsonProperty("total_tasks") final Integer totalTasks, + @JsonProperty("url") final URI url, + @JsonProperty("workflow_sid") final String workflowSid, + @JsonProperty("workspace_sid") final String workspaceSid ) { this.accountSid = accountSid; this.longestTaskWaitingAge = longestTaskWaitingAge; @@ -135,45 +131,9 @@ private WorkflowRealTimeStatistics( this.tasksByPriority = tasksByPriority; this.tasksByStatus = tasksByStatus; this.totalTasks = totalTasks; + this.url = url; this.workflowSid = workflowSid; this.workspaceSid = workspaceSid; - this.url = url; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final Integer getLongestTaskWaitingAge() { - return this.longestTaskWaitingAge; - } - - public final String getLongestTaskWaitingSid() { - return this.longestTaskWaitingSid; - } - - public final Map getTasksByPriority() { - return this.tasksByPriority; - } - - public final Map getTasksByStatus() { - return this.tasksByStatus; - } - - public final Integer getTotalTasks() { - return this.totalTasks; - } - - public final String getWorkflowSid() { - return this.workflowSid; - } - - public final String getWorkspaceSid() { - return this.workspaceSid; - } - - public final URI getUrl() { - return this.url; } @Override @@ -187,38 +147,34 @@ public boolean equals(final Object o) { } WorkflowRealTimeStatistics other = (WorkflowRealTimeStatistics) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals( - longestTaskWaitingAge, - other.longestTaskWaitingAge - ) && - Objects.equals( - longestTaskWaitingSid, - other.longestTaskWaitingSid - ) && - Objects.equals(tasksByPriority, other.tasksByPriority) && - Objects.equals(tasksByStatus, other.tasksByStatus) && - Objects.equals(totalTasks, other.totalTasks) && - Objects.equals(workflowSid, other.workflowSid) && - Objects.equals(workspaceSid, other.workspaceSid) && - Objects.equals(url, other.url) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(longestTaskWaitingAge, other.longestTaskWaitingAge) && + Objects.equals(longestTaskWaitingSid, other.longestTaskWaitingSid) && + Objects.equals(tasksByPriority, other.tasksByPriority) && + Objects.equals(tasksByStatus, other.tasksByStatus) && + Objects.equals(totalTasks, other.totalTasks) && + Objects.equals(url, other.url) && + Objects.equals(workflowSid, other.workflowSid) && + Objects.equals(workspaceSid, other.workspaceSid) ); } @Override public int hashCode() { return Objects.hash( - accountSid, - longestTaskWaitingAge, - longestTaskWaitingSid, - tasksByPriority, - tasksByStatus, - totalTasks, - workflowSid, - workspaceSid, - url + accountSid, + longestTaskWaitingAge, + longestTaskWaitingSid, + tasksByPriority, + tasksByStatus, + totalTasks, + url, + workflowSid, + workspaceSid ); } + + } + diff --git a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/workflow/WorkflowRealTimeStatisticsFetcher.java b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/workflow/WorkflowRealTimeStatisticsFetcher.java index df766a95a6..335383b84a 100644 --- a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/workflow/WorkflowRealTimeStatisticsFetcher.java +++ b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/workflow/WorkflowRealTimeStatisticsFetcher.java @@ -15,7 +15,8 @@ package com.twilio.rest.taskrouter.v1.workspace.workflow; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,80 +26,64 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class WorkflowRealTimeStatisticsFetcher - extends Fetcher { +public class WorkflowRealTimeStatisticsFetcher extends Fetcher { - private String pathWorkspaceSid; - private String pathWorkflowSid; + private String pathworkspaceSid; + private String pathworkflowSid; private String taskChannel; - public WorkflowRealTimeStatisticsFetcher( - final String pathWorkspaceSid, - final String pathWorkflowSid - ) { - this.pathWorkspaceSid = pathWorkspaceSid; - this.pathWorkflowSid = pathWorkflowSid; + public WorkflowRealTimeStatisticsFetcher(final String pathworkspaceSid, final String pathworkflowSid) { + this.pathworkspaceSid = pathworkspaceSid; + this.pathworkflowSid = pathworkflowSid; } - public WorkflowRealTimeStatisticsFetcher setTaskChannel( - final String taskChannel - ) { + + public WorkflowRealTimeStatisticsFetcher setTaskChannel(final String taskChannel) { this.taskChannel = taskChannel; return this; } + @Override public WorkflowRealTimeStatistics fetch(final TwilioRestClient client) { - String path = - "/v1/Workspaces/{WorkspaceSid}/Workflows/{WorkflowSid}/RealTimeStatistics"; - path = - path.replace( - "{" + "WorkspaceSid" + "}", - this.pathWorkspaceSid.toString() - ); - path = - path.replace( - "{" + "WorkflowSid" + "}", - this.pathWorkflowSid.toString() - ); + String path = "/v1/Workspaces/{WorkspaceSid}/Workflows/{WorkflowSid}/RealTimeStatistics"; + + path = path.replace("{" + "WorkspaceSid" + "}", this.pathworkspaceSid.toString()); + path = path.replace("{" + "WorkflowSid" + "}", this.pathworkflowSid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.TASKROUTER.toString(), - path + HttpMethod.GET, + Domains.TASKROUTER.toString(), + path ); addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "WorkflowRealTimeStatistics fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("WorkflowRealTimeStatistics fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return WorkflowRealTimeStatistics.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return WorkflowRealTimeStatistics.fromJson(response.getStream(), client.getObjectMapper()); } private void addQueryParams(final Request request) { + + if (taskChannel != null) { - request.addQueryParam("TaskChannel", taskChannel); + Serializer.toString(request, "TaskChannel", taskChannel, ParameterType.QUERY); } + + } } diff --git a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/workflow/WorkflowStatistics.java b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/workflow/WorkflowStatistics.java index f651aaccf4..a82b63b112 100644 --- a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/workflow/WorkflowStatistics.java +++ b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/workflow/WorkflowStatistics.java @@ -18,44 +18,40 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; -import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class WorkflowStatistics extends Resource { - private static final long serialVersionUID = 124113751515927L; - public static WorkflowStatisticsFetcher fetcher( - final String pathWorkspaceSid, - final String pathWorkflowSid - ) { - return new WorkflowStatisticsFetcher(pathWorkspaceSid, pathWorkflowSid); + public static WorkflowStatisticsFetcher fetcher(final String pathworkspaceSid, final String pathworkflowSid) { + return new WorkflowStatisticsFetcher( + pathworkspaceSid, pathworkflowSid + ); } + /** * Converts a JSON String into a WorkflowStatistics object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return WorkflowStatistics object represented by the provided JSON */ - public static WorkflowStatistics fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static WorkflowStatistics fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, WorkflowStatistics.class); @@ -70,14 +66,11 @@ public static WorkflowStatistics fromJson( * Converts a JSON InputStream into a WorkflowStatistics object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return WorkflowStatistics object represented by the provided JSON */ - public static WorkflowStatistics fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static WorkflowStatistics fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, WorkflowStatistics.class); @@ -88,52 +81,47 @@ public static WorkflowStatistics fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final Map cumulative; - private final Map realtime; + @Getter + private final Object cumulative; + @Getter + private final Object realtime; + @Getter + private final URI url; + @Getter private final String workflowSid; + @Getter private final String workspaceSid; - private final URI url; @JsonCreator private WorkflowStatistics( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("cumulative") final Map cumulative, - @JsonProperty("realtime") final Map realtime, - @JsonProperty("workflow_sid") final String workflowSid, - @JsonProperty("workspace_sid") final String workspaceSid, - @JsonProperty("url") final URI url + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("cumulative") final Object cumulative, + @JsonProperty("realtime") final Object realtime, + @JsonProperty("url") final URI url, + @JsonProperty("workflow_sid") final String workflowSid, + @JsonProperty("workspace_sid") final String workspaceSid ) { this.accountSid = accountSid; this.cumulative = cumulative; this.realtime = realtime; + this.url = url; this.workflowSid = workflowSid; this.workspaceSid = workspaceSid; - this.url = url; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final Map getCumulative() { - return this.cumulative; - } - - public final Map getRealtime() { - return this.realtime; - } - - public final String getWorkflowSid() { - return this.workflowSid; - } - - public final String getWorkspaceSid() { - return this.workspaceSid; - } - - public final URI getUrl() { - return this.url; } @Override @@ -147,26 +135,28 @@ public boolean equals(final Object o) { } WorkflowStatistics other = (WorkflowStatistics) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(cumulative, other.cumulative) && - Objects.equals(realtime, other.realtime) && - Objects.equals(workflowSid, other.workflowSid) && - Objects.equals(workspaceSid, other.workspaceSid) && - Objects.equals(url, other.url) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(cumulative, other.cumulative) && + Objects.equals(realtime, other.realtime) && + Objects.equals(url, other.url) && + Objects.equals(workflowSid, other.workflowSid) && + Objects.equals(workspaceSid, other.workspaceSid) ); } @Override public int hashCode() { return Objects.hash( - accountSid, - cumulative, - realtime, - workflowSid, - workspaceSid, - url + accountSid, + cumulative, + realtime, + url, + workflowSid, + workspaceSid ); } + + } + diff --git a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/workflow/WorkflowStatisticsFetcher.java b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/workflow/WorkflowStatisticsFetcher.java index 848a1bd705..19f5b45ebc 100644 --- a/src/main/java/com/twilio/rest/taskrouter/v1/workspace/workflow/WorkflowStatisticsFetcher.java +++ b/src/main/java/com/twilio/rest/taskrouter/v1/workspace/workflow/WorkflowStatisticsFetcher.java @@ -15,7 +15,8 @@ package com.twilio.rest.taskrouter.v1.workspace.workflow; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -24,124 +25,115 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.time.ZonedDateTime; public class WorkflowStatisticsFetcher extends Fetcher { - private String pathWorkspaceSid; - private String pathWorkflowSid; + private String pathworkspaceSid; + private String pathworkflowSid; private Integer minutes; private ZonedDateTime startDate; private ZonedDateTime endDate; private String taskChannel; private String splitByWaitTime; - public WorkflowStatisticsFetcher( - final String pathWorkspaceSid, - final String pathWorkflowSid - ) { - this.pathWorkspaceSid = pathWorkspaceSid; - this.pathWorkflowSid = pathWorkflowSid; + public WorkflowStatisticsFetcher(final String pathworkspaceSid, final String pathworkflowSid) { + this.pathworkspaceSid = pathworkspaceSid; + this.pathworkflowSid = pathworkflowSid; } + public WorkflowStatisticsFetcher setMinutes(final Integer minutes) { this.minutes = minutes; return this; } - public WorkflowStatisticsFetcher setStartDate( - final ZonedDateTime startDate - ) { + + public WorkflowStatisticsFetcher setStartDate(final ZonedDateTime startDate) { this.startDate = startDate; return this; } + public WorkflowStatisticsFetcher setEndDate(final ZonedDateTime endDate) { this.endDate = endDate; return this; } + public WorkflowStatisticsFetcher setTaskChannel(final String taskChannel) { this.taskChannel = taskChannel; return this; } - public WorkflowStatisticsFetcher setSplitByWaitTime( - final String splitByWaitTime - ) { + + public WorkflowStatisticsFetcher setSplitByWaitTime(final String splitByWaitTime) { this.splitByWaitTime = splitByWaitTime; return this; } + @Override public WorkflowStatistics fetch(final TwilioRestClient client) { - String path = - "/v1/Workspaces/{WorkspaceSid}/Workflows/{WorkflowSid}/Statistics"; - path = - path.replace( - "{" + "WorkspaceSid" + "}", - this.pathWorkspaceSid.toString() - ); - path = - path.replace( - "{" + "WorkflowSid" + "}", - this.pathWorkflowSid.toString() - ); + String path = "/v1/Workspaces/{WorkspaceSid}/Workflows/{WorkflowSid}/Statistics"; + + path = path.replace("{" + "WorkspaceSid" + "}", this.pathworkspaceSid.toString()); + path = path.replace("{" + "WorkflowSid" + "}", this.pathworkflowSid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.TASKROUTER.toString(), - path + HttpMethod.GET, + Domains.TASKROUTER.toString(), + path ); addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "WorkflowStatistics fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("WorkflowStatistics fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return WorkflowStatistics.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return WorkflowStatistics.fromJson(response.getStream(), client.getObjectMapper()); } private void addQueryParams(final Request request) { + + if (minutes != null) { - request.addQueryParam("Minutes", minutes.toString()); + Serializer.toString(request, "Minutes", minutes, ParameterType.QUERY); } + + if (startDate != null) { - request.addQueryParam( - "StartDate", - startDate.toInstant().toString() - ); + Serializer.toString(request, "StartDate", startDate, ParameterType.QUERY); } + if (endDate != null) { - request.addQueryParam("EndDate", endDate.toInstant().toString()); + Serializer.toString(request, "EndDate", endDate, ParameterType.QUERY); } + if (taskChannel != null) { - request.addQueryParam("TaskChannel", taskChannel); + Serializer.toString(request, "TaskChannel", taskChannel, ParameterType.QUERY); } + + if (splitByWaitTime != null) { - request.addQueryParam("SplitByWaitTime", splitByWaitTime); + Serializer.toString(request, "SplitByWaitTime", splitByWaitTime, ParameterType.QUERY); } + + } } diff --git a/src/main/java/com/twilio/rest/trunking/v1/Trunk.java b/src/main/java/com/twilio/rest/trunking/v1/Trunk.java index 6ddece0cab..cbc5030b9d 100644 --- a/src/main/java/com/twilio/rest/trunking/v1/Trunk.java +++ b/src/main/java/com/twilio/rest/trunking/v1/Trunk.java @@ -18,62 +18,116 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.http.HttpMethod; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.List; import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Trunk extends Resource { - private static final long serialVersionUID = 232204827569278L; public static TrunkCreator creator() { - return new TrunkCreator(); + return new TrunkCreator( + + ); } - public static TrunkDeleter deleter(final String pathSid) { - return new TrunkDeleter(pathSid); + + public static TrunkDeleter deleter(final String pathsid) { + return new TrunkDeleter( + pathsid + ); } - public static TrunkFetcher fetcher(final String pathSid) { - return new TrunkFetcher(pathSid); + + public static TrunkFetcher fetcher(final String pathsid) { + return new TrunkFetcher( + pathsid + ); } + public static TrunkReader reader() { - return new TrunkReader(); + return new TrunkReader( + + ); + } + + + public static TrunkUpdater updater(final String pathsid) { + return new TrunkUpdater( + pathsid + ); } - public static TrunkUpdater updater(final String pathSid) { - return new TrunkUpdater(pathSid); + + public enum TransferSetting { + DISABLE_ALL("disable-all"), + ENABLE_ALL("enable-all"), + SIP_ONLY("sip-only"); + + private final String value; + + private TransferSetting(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static TransferSetting forValue(final String value) { + return Promoter.enumFromString(value, TransferSetting.values()); + } + } + + public enum TransferCallerId { + FROM_TRANSFEREE("from-transferee"), + FROM_TRANSFEROR("from-transferor"); + + private final String value; + + private TransferCallerId(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static TransferCallerId forValue(final String value) { + return Promoter.enumFromString(value, TransferCallerId.values()); + } } + /** * Converts a JSON String into a Trunk object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Trunk object represented by the provided JSON */ - public static Trunk fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Trunk fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Trunk.class); @@ -88,14 +142,11 @@ public static Trunk fromJson( * Converts a JSON InputStream into a Trunk object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Trunk object represented by the provided JSON */ - public static Trunk fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Trunk fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Trunk.class); @@ -106,142 +157,97 @@ public static Trunk fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String domainName; - private final HttpMethod disasterRecoveryMethod; - private final URI disasterRecoveryUrl; - private final String friendlyName; - private final Boolean secure; - private final Map recording; - private final Trunk.TransferSetting transferMode; - private final Trunk.TransferCallerId transferCallerId; - private final Boolean cnamLookupEnabled; + @Getter private final String authType; - private final Boolean symmetricRtpEnabled; + @Getter private final List authTypeSet; + @Getter + private final Boolean cnamLookupEnabled; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; + @Getter + private final HttpMethod disasterRecoveryMethod; + @Getter + private final URI disasterRecoveryUrl; + @Getter + private final String domainName; + @Getter + private final String friendlyName; + @Getter + private final Map links; + @Getter + private final Object recording; + @Getter + private final Boolean secure; + @Getter private final String sid; + @Getter + private final Boolean symmetricRtpEnabled; + @Getter + private final Trunk.TransferCallerId transferCallerId; + @Getter + private final Trunk.TransferSetting transferMode; + @Getter private final URI url; - private final Map links; @JsonCreator private Trunk( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("domain_name") final String domainName, - @JsonProperty( - "disaster_recovery_method" - ) final HttpMethod disasterRecoveryMethod, - @JsonProperty("disaster_recovery_url") final URI disasterRecoveryUrl, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("secure") final Boolean secure, - @JsonProperty("recording") final Map recording, - @JsonProperty("transfer_mode") final Trunk.TransferSetting transferMode, - @JsonProperty( - "transfer_caller_id" - ) final Trunk.TransferCallerId transferCallerId, - @JsonProperty("cnam_lookup_enabled") final Boolean cnamLookupEnabled, - @JsonProperty("auth_type") final String authType, - @JsonProperty( - "symmetric_rtp_enabled" - ) final Boolean symmetricRtpEnabled, - @JsonProperty("auth_type_set") final List authTypeSet, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("sid") final String sid, - @JsonProperty("url") final URI url, - @JsonProperty("links") final Map links + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("auth_type") final String authType, + @JsonProperty("auth_type_set") final List authTypeSet, + @JsonProperty("cnam_lookup_enabled") final Boolean cnamLookupEnabled, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("disaster_recovery_method") final HttpMethod disasterRecoveryMethod, + @JsonProperty("disaster_recovery_url") final URI disasterRecoveryUrl, + @JsonProperty("domain_name") final String domainName, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("links") final Map links, + @JsonProperty("recording") final Object recording, + @JsonProperty("secure") final Boolean secure, + @JsonProperty("sid") final String sid, + @JsonProperty("symmetric_rtp_enabled") final Boolean symmetricRtpEnabled, + @JsonProperty("transfer_caller_id") final Trunk.TransferCallerId transferCallerId, + @JsonProperty("transfer_mode") final Trunk.TransferSetting transferMode, + @JsonProperty("url") final URI url ) { this.accountSid = accountSid; - this.domainName = domainName; + this.authType = authType; + this.authTypeSet = authTypeSet; + this.cnamLookupEnabled = cnamLookupEnabled; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.disasterRecoveryMethod = disasterRecoveryMethod; this.disasterRecoveryUrl = disasterRecoveryUrl; + this.domainName = domainName; this.friendlyName = friendlyName; - this.secure = secure; + this.links = links; this.recording = recording; - this.transferMode = transferMode; - this.transferCallerId = transferCallerId; - this.cnamLookupEnabled = cnamLookupEnabled; - this.authType = authType; - this.symmetricRtpEnabled = symmetricRtpEnabled; - this.authTypeSet = authTypeSet; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); + this.secure = secure; this.sid = sid; + this.symmetricRtpEnabled = symmetricRtpEnabled; + this.transferCallerId = transferCallerId; + this.transferMode = transferMode; this.url = url; - this.links = links; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getDomainName() { - return this.domainName; - } - - public final HttpMethod getDisasterRecoveryMethod() { - return this.disasterRecoveryMethod; - } - - public final URI getDisasterRecoveryUrl() { - return this.disasterRecoveryUrl; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final Boolean getSecure() { - return this.secure; - } - - public final Map getRecording() { - return this.recording; - } - - public final Trunk.TransferSetting getTransferMode() { - return this.transferMode; - } - - public final Trunk.TransferCallerId getTransferCallerId() { - return this.transferCallerId; - } - - public final Boolean getCnamLookupEnabled() { - return this.cnamLookupEnabled; - } - - public final String getAuthType() { - return this.authType; - } - - public final Boolean getSymmetricRtpEnabled() { - return this.symmetricRtpEnabled; - } - - public final List getAuthTypeSet() { - return this.authTypeSet; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final String getSid() { - return this.sid; - } - - public final URI getUrl() { - return this.url; - } - - public final Map getLinks() { - return this.links; } @Override @@ -255,94 +261,52 @@ public boolean equals(final Object o) { } Trunk other = (Trunk) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(domainName, other.domainName) && - Objects.equals( - disasterRecoveryMethod, - other.disasterRecoveryMethod - ) && - Objects.equals(disasterRecoveryUrl, other.disasterRecoveryUrl) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(secure, other.secure) && - Objects.equals(recording, other.recording) && - Objects.equals(transferMode, other.transferMode) && - Objects.equals(transferCallerId, other.transferCallerId) && - Objects.equals(cnamLookupEnabled, other.cnamLookupEnabled) && - Objects.equals(authType, other.authType) && - Objects.equals(symmetricRtpEnabled, other.symmetricRtpEnabled) && - Objects.equals(authTypeSet, other.authTypeSet) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(sid, other.sid) && - Objects.equals(url, other.url) && - Objects.equals(links, other.links) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(authType, other.authType) && + Objects.equals(authTypeSet, other.authTypeSet) && + Objects.equals(cnamLookupEnabled, other.cnamLookupEnabled) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(disasterRecoveryMethod, other.disasterRecoveryMethod) && + Objects.equals(disasterRecoveryUrl, other.disasterRecoveryUrl) && + Objects.equals(domainName, other.domainName) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(links, other.links) && + Objects.equals(recording, other.recording) && + Objects.equals(secure, other.secure) && + Objects.equals(sid, other.sid) && + Objects.equals(symmetricRtpEnabled, other.symmetricRtpEnabled) && + Objects.equals(transferCallerId, other.transferCallerId) && + Objects.equals(transferMode, other.transferMode) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - accountSid, - domainName, - disasterRecoveryMethod, - disasterRecoveryUrl, - friendlyName, - secure, - recording, - transferMode, - transferCallerId, - cnamLookupEnabled, - authType, - symmetricRtpEnabled, - authTypeSet, - dateCreated, - dateUpdated, - sid, - url, - links + accountSid, + authType, + authTypeSet, + cnamLookupEnabled, + dateCreated, + dateUpdated, + disasterRecoveryMethod, + disasterRecoveryUrl, + domainName, + friendlyName, + links, + recording, + secure, + sid, + symmetricRtpEnabled, + transferCallerId, + transferMode, + url ); } - public enum TransferCallerId { - FROM_TRANSFEREE("from-transferee"), - FROM_TRANSFEROR("from-transferor"); - - private final String value; - - private TransferCallerId(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static TransferCallerId forValue(final String value) { - return Promoter.enumFromString(value, TransferCallerId.values()); - } - } - - public enum TransferSetting { - DISABLE_ALL("disable-all"), - ENABLE_ALL("enable-all"), - SIP_ONLY("sip-only"); - - private final String value; - private TransferSetting(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static TransferSetting forValue(final String value) { - return Promoter.enumFromString(value, TransferSetting.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/trunking/v1/TrunkCreator.java b/src/main/java/com/twilio/rest/trunking/v1/TrunkCreator.java index 8983fe45f8..573b49de15 100644 --- a/src/main/java/com/twilio/rest/trunking/v1/TrunkCreator.java +++ b/src/main/java/com/twilio/rest/trunking/v1/TrunkCreator.java @@ -14,9 +14,11 @@ package com.twilio.rest.trunking.v1; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; -import com.twilio.converter.Promoter; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,7 +27,7 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -import java.net.URI; + import java.net.URI; public class TrunkCreator extends Creator { @@ -39,88 +41,83 @@ public class TrunkCreator extends Creator { private Boolean cnamLookupEnabled; private Trunk.TransferCallerId transferCallerId; - public TrunkCreator() {} + public TrunkCreator() { + } + public TrunkCreator setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + public TrunkCreator setDomainName(final String domainName) { this.domainName = domainName; return this; } + public TrunkCreator setDisasterRecoveryUrl(final URI disasterRecoveryUrl) { this.disasterRecoveryUrl = disasterRecoveryUrl; return this; } - public TrunkCreator setDisasterRecoveryUrl( - final String disasterRecoveryUrl - ) { - return setDisasterRecoveryUrl( - Promoter.uriFromString(disasterRecoveryUrl) - ); - } - public TrunkCreator setDisasterRecoveryMethod( - final HttpMethod disasterRecoveryMethod - ) { + public TrunkCreator setDisasterRecoveryMethod(final HttpMethod disasterRecoveryMethod) { this.disasterRecoveryMethod = disasterRecoveryMethod; return this; } - public TrunkCreator setTransferMode( - final Trunk.TransferSetting transferMode - ) { + + public TrunkCreator setTransferMode(final Trunk.TransferSetting transferMode) { this.transferMode = transferMode; return this; } + public TrunkCreator setSecure(final Boolean secure) { this.secure = secure; return this; } + public TrunkCreator setCnamLookupEnabled(final Boolean cnamLookupEnabled) { this.cnamLookupEnabled = cnamLookupEnabled; return this; } - public TrunkCreator setTransferCallerId( - final Trunk.TransferCallerId transferCallerId - ) { + + public TrunkCreator setTransferCallerId(final Trunk.TransferCallerId transferCallerId) { this.transferCallerId = transferCallerId; return this; } + @Override public Trunk create(final TwilioRestClient client) { + String path = "/v1/Trunks"; + Request request = new Request( - HttpMethod.POST, - Domains.TRUNKING.toString(), - path + HttpMethod.POST, + Domains.TRUNKING.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Trunk creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("Trunk creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -129,41 +126,46 @@ public Trunk create(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + if (domainName != null) { - request.addPostParam("DomainName", domainName); + Serializer.toString(request, "DomainName", domainName, ParameterType.URLENCODED); } + + if (disasterRecoveryUrl != null) { - request.addPostParam( - "DisasterRecoveryUrl", - disasterRecoveryUrl.toString() - ); + Serializer.toString(request, "DisasterRecoveryUrl", disasterRecoveryUrl, ParameterType.URLENCODED); } + + if (disasterRecoveryMethod != null) { - request.addPostParam( - "DisasterRecoveryMethod", - disasterRecoveryMethod.toString() - ); + Serializer.toString(request, "DisasterRecoveryMethod", disasterRecoveryMethod, ParameterType.URLENCODED); } + + if (transferMode != null) { - request.addPostParam("TransferMode", transferMode.toString()); + Serializer.toString(request, "TransferMode", transferMode, ParameterType.URLENCODED); } + + if (secure != null) { - request.addPostParam("Secure", secure.toString()); + Serializer.toString(request, "Secure", secure, ParameterType.URLENCODED); } + + if (cnamLookupEnabled != null) { - request.addPostParam( - "CnamLookupEnabled", - cnamLookupEnabled.toString() - ); + Serializer.toString(request, "CnamLookupEnabled", cnamLookupEnabled, ParameterType.URLENCODED); } + + if (transferCallerId != null) { - request.addPostParam( - "TransferCallerId", - transferCallerId.toString() - ); + Serializer.toString(request, "TransferCallerId", transferCallerId, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/trunking/v1/TrunkDeleter.java b/src/main/java/com/twilio/rest/trunking/v1/TrunkDeleter.java index 36cfb87a7b..12eee3c6a3 100644 --- a/src/main/java/com/twilio/rest/trunking/v1/TrunkDeleter.java +++ b/src/main/java/com/twilio/rest/trunking/v1/TrunkDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.trunking.v1; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,40 +26,38 @@ public class TrunkDeleter extends Deleter { - private String pathSid; + private String pathsid; - public TrunkDeleter(final String pathSid) { - this.pathSid = pathSid; + public TrunkDeleter(final String pathsid) { + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/v1/Trunks/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.TRUNKING.toString(), - path + HttpMethod.DELETE, + Domains.TRUNKING.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Trunk delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("Trunk delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/trunking/v1/TrunkFetcher.java b/src/main/java/com/twilio/rest/trunking/v1/TrunkFetcher.java index bf6f782b08..b486457acf 100644 --- a/src/main/java/com/twilio/rest/trunking/v1/TrunkFetcher.java +++ b/src/main/java/com/twilio/rest/trunking/v1/TrunkFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.trunking.v1; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,44 +26,41 @@ public class TrunkFetcher extends Fetcher { - private String pathSid; + private String pathsid; - public TrunkFetcher(final String pathSid) { - this.pathSid = pathSid; + public TrunkFetcher(final String pathsid) { + this.pathsid = pathsid; } + @Override public Trunk fetch(final TwilioRestClient client) { + String path = "/v1/Trunks/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.TRUNKING.toString(), - path + HttpMethod.GET, + Domains.TRUNKING.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Trunk fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Trunk fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Trunk.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/trunking/v1/TrunkReader.java b/src/main/java/com/twilio/rest/trunking/v1/TrunkReader.java index fed0dda5ce..dbc42a1eb0 100644 --- a/src/main/java/com/twilio/rest/trunking/v1/TrunkReader.java +++ b/src/main/java/com/twilio/rest/trunking/v1/TrunkReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -31,105 +32,83 @@ public class TrunkReader extends Reader { private Long pageSize; - public TrunkReader() {} + public TrunkReader() { + } + public TrunkReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/Trunks"; + Request request = new Request( - HttpMethod.GET, - Domains.TRUNKING.toString(), - path + HttpMethod.GET, + Domains.TRUNKING.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Trunk read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Trunk read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "trunks", - response.getContent(), - Trunk.class, - client.getObjectMapper() - ); + "trunks", + response.getContent(), + Trunk.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.TRUNKING.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.TRUNKING.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/trunking/v1/TrunkUpdater.java b/src/main/java/com/twilio/rest/trunking/v1/TrunkUpdater.java index 61c54dcd26..eb183a7468 100644 --- a/src/main/java/com/twilio/rest/trunking/v1/TrunkUpdater.java +++ b/src/main/java/com/twilio/rest/trunking/v1/TrunkUpdater.java @@ -16,7 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; -import com.twilio.converter.Promoter; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,11 +26,11 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.net.URI; public class TrunkUpdater extends Updater { - - private String pathSid; + private String pathsid; private String friendlyName; private String domainName; private URI disasterRecoveryUrl; @@ -39,92 +40,86 @@ public class TrunkUpdater extends Updater { private Boolean cnamLookupEnabled; private Trunk.TransferCallerId transferCallerId; - public TrunkUpdater(final String pathSid) { - this.pathSid = pathSid; + public TrunkUpdater(final String pathsid) { + this.pathsid = pathsid; } + public TrunkUpdater setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + public TrunkUpdater setDomainName(final String domainName) { this.domainName = domainName; return this; } + public TrunkUpdater setDisasterRecoveryUrl(final URI disasterRecoveryUrl) { this.disasterRecoveryUrl = disasterRecoveryUrl; return this; } - public TrunkUpdater setDisasterRecoveryUrl( - final String disasterRecoveryUrl - ) { - return setDisasterRecoveryUrl( - Promoter.uriFromString(disasterRecoveryUrl) - ); - } - public TrunkUpdater setDisasterRecoveryMethod( - final HttpMethod disasterRecoveryMethod - ) { + public TrunkUpdater setDisasterRecoveryMethod(final HttpMethod disasterRecoveryMethod) { this.disasterRecoveryMethod = disasterRecoveryMethod; return this; } - public TrunkUpdater setTransferMode( - final Trunk.TransferSetting transferMode - ) { + + public TrunkUpdater setTransferMode(final Trunk.TransferSetting transferMode) { this.transferMode = transferMode; return this; } + public TrunkUpdater setSecure(final Boolean secure) { this.secure = secure; return this; } + public TrunkUpdater setCnamLookupEnabled(final Boolean cnamLookupEnabled) { this.cnamLookupEnabled = cnamLookupEnabled; return this; } - public TrunkUpdater setTransferCallerId( - final Trunk.TransferCallerId transferCallerId - ) { + + public TrunkUpdater setTransferCallerId(final Trunk.TransferCallerId transferCallerId) { this.transferCallerId = transferCallerId; return this; } + @Override public Trunk update(final TwilioRestClient client) { + String path = "/v1/Trunks/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.TRUNKING.toString(), - path + HttpMethod.POST, + Domains.TRUNKING.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Trunk update failed: Unable to connect to server" - ); + throw new ApiConnectionException("Trunk update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -133,41 +128,46 @@ public Trunk update(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + if (domainName != null) { - request.addPostParam("DomainName", domainName); + Serializer.toString(request, "DomainName", domainName, ParameterType.URLENCODED); } + + if (disasterRecoveryUrl != null) { - request.addPostParam( - "DisasterRecoveryUrl", - disasterRecoveryUrl.toString() - ); + Serializer.toString(request, "DisasterRecoveryUrl", disasterRecoveryUrl, ParameterType.URLENCODED); } + + if (disasterRecoveryMethod != null) { - request.addPostParam( - "DisasterRecoveryMethod", - disasterRecoveryMethod.toString() - ); + Serializer.toString(request, "DisasterRecoveryMethod", disasterRecoveryMethod, ParameterType.URLENCODED); } + + if (transferMode != null) { - request.addPostParam("TransferMode", transferMode.toString()); + Serializer.toString(request, "TransferMode", transferMode, ParameterType.URLENCODED); } + + if (secure != null) { - request.addPostParam("Secure", secure.toString()); + Serializer.toString(request, "Secure", secure, ParameterType.URLENCODED); } + + if (cnamLookupEnabled != null) { - request.addPostParam( - "CnamLookupEnabled", - cnamLookupEnabled.toString() - ); + Serializer.toString(request, "CnamLookupEnabled", cnamLookupEnabled, ParameterType.URLENCODED); } + + if (transferCallerId != null) { - request.addPostParam( - "TransferCallerId", - transferCallerId.toString() - ); + Serializer.toString(request, "TransferCallerId", transferCallerId, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/trunking/v1/trunk/CredentialList.java b/src/main/java/com/twilio/rest/trunking/v1/trunk/CredentialList.java index 7f3e4774fd..6dc55b2627 100644 --- a/src/main/java/com/twilio/rest/trunking/v1/trunk/CredentialList.java +++ b/src/main/java/com/twilio/rest/trunking/v1/trunk/CredentialList.java @@ -18,62 +18,63 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class CredentialList extends Resource { - private static final long serialVersionUID = 198091197266991L; - public static CredentialListCreator creator( - final String pathTrunkSid, - final String credentialListSid - ) { - return new CredentialListCreator(pathTrunkSid, credentialListSid); + public static CredentialListCreator creator(final String pathtrunkSid, final String credentialListSid) { + return new CredentialListCreator( + pathtrunkSid, credentialListSid + ); } - public static CredentialListDeleter deleter( - final String pathTrunkSid, - final String pathSid - ) { - return new CredentialListDeleter(pathTrunkSid, pathSid); + + public static CredentialListDeleter deleter(final String pathtrunkSid, final String pathsid) { + return new CredentialListDeleter( + pathtrunkSid, pathsid + ); } - public static CredentialListFetcher fetcher( - final String pathTrunkSid, - final String pathSid - ) { - return new CredentialListFetcher(pathTrunkSid, pathSid); + + public static CredentialListFetcher fetcher(final String pathtrunkSid, final String pathsid) { + return new CredentialListFetcher( + pathtrunkSid, pathsid + ); } - public static CredentialListReader reader(final String pathTrunkSid) { - return new CredentialListReader(pathTrunkSid); + + public static CredentialListReader reader(final String pathtrunkSid) { + return new CredentialListReader( + pathtrunkSid + ); } + /** * Converts a JSON String into a CredentialList object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return CredentialList object represented by the provided JSON */ - public static CredentialList fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static CredentialList fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, CredentialList.class); @@ -88,14 +89,11 @@ public static CredentialList fromJson( * Converts a JSON InputStream into a CredentialList object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return CredentialList object represented by the provided JSON */ - public static CredentialList fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static CredentialList fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, CredentialList.class); @@ -106,61 +104,55 @@ public static CredentialList fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String sid; - private final String trunkSid; - private final String friendlyName; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; + @Getter + private final String friendlyName; + @Getter + private final String sid; + @Getter + private final String trunkSid; + @Getter private final URI url; @JsonCreator private CredentialList( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("sid") final String sid, - @JsonProperty("trunk_sid") final String trunkSid, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("url") final URI url + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("sid") final String sid, + @JsonProperty("trunk_sid") final String trunkSid, + @JsonProperty("url") final URI url ) { this.accountSid = accountSid; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; + this.friendlyName = friendlyName; this.sid = sid; this.trunkSid = trunkSid; - this.friendlyName = friendlyName; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); this.url = url; } - public final String getAccountSid() { - return this.accountSid; - } - - public final String getSid() { - return this.sid; - } - - public final String getTrunkSid() { - return this.trunkSid; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final URI getUrl() { - return this.url; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -172,28 +164,30 @@ public boolean equals(final Object o) { } CredentialList other = (CredentialList) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(sid, other.sid) && - Objects.equals(trunkSid, other.trunkSid) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(url, other.url) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(sid, other.sid) && + Objects.equals(trunkSid, other.trunkSid) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - accountSid, - sid, - trunkSid, - friendlyName, - dateCreated, - dateUpdated, - url + accountSid, + dateCreated, + dateUpdated, + friendlyName, + sid, + trunkSid, + url ); } + + } + diff --git a/src/main/java/com/twilio/rest/trunking/v1/trunk/CredentialListCreator.java b/src/main/java/com/twilio/rest/trunking/v1/trunk/CredentialListCreator.java index ce8acf7527..fd62dfd315 100644 --- a/src/main/java/com/twilio/rest/trunking/v1/trunk/CredentialListCreator.java +++ b/src/main/java/com/twilio/rest/trunking/v1/trunk/CredentialListCreator.java @@ -14,8 +14,11 @@ package com.twilio.rest.trunking.v1.trunk; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,71 +30,61 @@ public class CredentialListCreator extends Creator { - private String pathTrunkSid; + private String pathtrunkSid; private String credentialListSid; - public CredentialListCreator( - final String pathTrunkSid, - final String credentialListSid - ) { - this.pathTrunkSid = pathTrunkSid; + public CredentialListCreator(final String pathtrunkSid, final String credentialListSid) { + this.pathtrunkSid = pathtrunkSid; this.credentialListSid = credentialListSid; } - public CredentialListCreator setCredentialListSid( - final String credentialListSid - ) { + + public CredentialListCreator setCredentialListSid(final String credentialListSid) { this.credentialListSid = credentialListSid; return this; } + @Override public CredentialList create(final TwilioRestClient client) { + String path = "/v1/Trunks/{TrunkSid}/CredentialLists"; - path = - path.replace("{" + "TrunkSid" + "}", this.pathTrunkSid.toString()); - path = - path.replace( - "{" + "CredentialListSid" + "}", - this.credentialListSid.toString() - ); + path = path.replace("{" + "TrunkSid" + "}", this.pathtrunkSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.TRUNKING.toString(), - path + HttpMethod.POST, + Domains.TRUNKING.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "CredentialList creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("CredentialList creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return CredentialList.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return CredentialList.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (credentialListSid != null) { - request.addPostParam("CredentialListSid", credentialListSid); + Serializer.toString(request, "CredentialListSid", credentialListSid, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/trunking/v1/trunk/CredentialListDeleter.java b/src/main/java/com/twilio/rest/trunking/v1/trunk/CredentialListDeleter.java index 7aca71f2d8..2674423393 100644 --- a/src/main/java/com/twilio/rest/trunking/v1/trunk/CredentialListDeleter.java +++ b/src/main/java/com/twilio/rest/trunking/v1/trunk/CredentialListDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.trunking.v1.trunk; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,47 +26,41 @@ public class CredentialListDeleter extends Deleter { - private String pathTrunkSid; - private String pathSid; + private String pathtrunkSid; + private String pathsid; - public CredentialListDeleter( - final String pathTrunkSid, - final String pathSid - ) { - this.pathTrunkSid = pathTrunkSid; - this.pathSid = pathSid; + public CredentialListDeleter(final String pathtrunkSid, final String pathsid) { + this.pathtrunkSid = pathtrunkSid; + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/v1/Trunks/{TrunkSid}/CredentialLists/{Sid}"; - path = - path.replace("{" + "TrunkSid" + "}", this.pathTrunkSid.toString()); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "TrunkSid" + "}", this.pathtrunkSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.TRUNKING.toString(), - path + HttpMethod.DELETE, + Domains.TRUNKING.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "CredentialList delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("CredentialList delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/trunking/v1/trunk/CredentialListFetcher.java b/src/main/java/com/twilio/rest/trunking/v1/trunk/CredentialListFetcher.java index 2ee3fd2244..91f339ff7a 100644 --- a/src/main/java/com/twilio/rest/trunking/v1/trunk/CredentialListFetcher.java +++ b/src/main/java/com/twilio/rest/trunking/v1/trunk/CredentialListFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.trunking.v1.trunk; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,54 +26,44 @@ public class CredentialListFetcher extends Fetcher { - private String pathTrunkSid; - private String pathSid; + private String pathtrunkSid; + private String pathsid; - public CredentialListFetcher( - final String pathTrunkSid, - final String pathSid - ) { - this.pathTrunkSid = pathTrunkSid; - this.pathSid = pathSid; + public CredentialListFetcher(final String pathtrunkSid, final String pathsid) { + this.pathtrunkSid = pathtrunkSid; + this.pathsid = pathsid; } + @Override public CredentialList fetch(final TwilioRestClient client) { + String path = "/v1/Trunks/{TrunkSid}/CredentialLists/{Sid}"; - path = - path.replace("{" + "TrunkSid" + "}", this.pathTrunkSid.toString()); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "TrunkSid" + "}", this.pathtrunkSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.TRUNKING.toString(), - path + HttpMethod.GET, + Domains.TRUNKING.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "CredentialList fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("CredentialList fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return CredentialList.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return CredentialList.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/trunking/v1/trunk/CredentialListReader.java b/src/main/java/com/twilio/rest/trunking/v1/trunk/CredentialListReader.java index 88e1af7006..f0c4b66702 100644 --- a/src/main/java/com/twilio/rest/trunking/v1/trunk/CredentialListReader.java +++ b/src/main/java/com/twilio/rest/trunking/v1/trunk/CredentialListReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,112 +30,88 @@ public class CredentialListReader extends Reader { - private String pathTrunkSid; + private String pathtrunkSid; private Long pageSize; - public CredentialListReader(final String pathTrunkSid) { - this.pathTrunkSid = pathTrunkSid; + public CredentialListReader(final String pathtrunkSid) { + this.pathtrunkSid = pathtrunkSid; } + public CredentialListReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/Trunks/{TrunkSid}/CredentialLists"; - path = - path.replace("{" + "TrunkSid" + "}", this.pathTrunkSid.toString()); + + path = path.replace("{" + "TrunkSid" + "}", this.pathtrunkSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.TRUNKING.toString(), - path + HttpMethod.GET, + Domains.TRUNKING.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "CredentialList read failed: Unable to connect to server" - ); + throw new ApiConnectionException("CredentialList read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "credential_lists", - response.getContent(), - CredentialList.class, - client.getObjectMapper() - ); + "credential_lists", + response.getContent(), + CredentialList.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.TRUNKING.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.TRUNKING.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/trunking/v1/trunk/IpAccessControlList.java b/src/main/java/com/twilio/rest/trunking/v1/trunk/IpAccessControlList.java index a354c2de69..f4adc518c4 100644 --- a/src/main/java/com/twilio/rest/trunking/v1/trunk/IpAccessControlList.java +++ b/src/main/java/com/twilio/rest/trunking/v1/trunk/IpAccessControlList.java @@ -18,65 +18,63 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class IpAccessControlList extends Resource { - private static final long serialVersionUID = 198091197266991L; - public static IpAccessControlListCreator creator( - final String pathTrunkSid, - final String ipAccessControlListSid - ) { + public static IpAccessControlListCreator creator(final String pathtrunkSid, final String ipAccessControlListSid) { return new IpAccessControlListCreator( - pathTrunkSid, - ipAccessControlListSid + pathtrunkSid, ipAccessControlListSid ); } - public static IpAccessControlListDeleter deleter( - final String pathTrunkSid, - final String pathSid - ) { - return new IpAccessControlListDeleter(pathTrunkSid, pathSid); + + public static IpAccessControlListDeleter deleter(final String pathtrunkSid, final String pathsid) { + return new IpAccessControlListDeleter( + pathtrunkSid, pathsid + ); } - public static IpAccessControlListFetcher fetcher( - final String pathTrunkSid, - final String pathSid - ) { - return new IpAccessControlListFetcher(pathTrunkSid, pathSid); + + public static IpAccessControlListFetcher fetcher(final String pathtrunkSid, final String pathsid) { + return new IpAccessControlListFetcher( + pathtrunkSid, pathsid + ); } - public static IpAccessControlListReader reader(final String pathTrunkSid) { - return new IpAccessControlListReader(pathTrunkSid); + + public static IpAccessControlListReader reader(final String pathtrunkSid) { + return new IpAccessControlListReader( + pathtrunkSid + ); } + /** * Converts a JSON String into a IpAccessControlList object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return IpAccessControlList object represented by the provided JSON */ - public static IpAccessControlList fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static IpAccessControlList fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, IpAccessControlList.class); @@ -91,14 +89,11 @@ public static IpAccessControlList fromJson( * Converts a JSON InputStream into a IpAccessControlList object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return IpAccessControlList object represented by the provided JSON */ - public static IpAccessControlList fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static IpAccessControlList fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, IpAccessControlList.class); @@ -109,61 +104,55 @@ public static IpAccessControlList fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String sid; - private final String trunkSid; - private final String friendlyName; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; + @Getter + private final String friendlyName; + @Getter + private final String sid; + @Getter + private final String trunkSid; + @Getter private final URI url; @JsonCreator private IpAccessControlList( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("sid") final String sid, - @JsonProperty("trunk_sid") final String trunkSid, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("url") final URI url + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("sid") final String sid, + @JsonProperty("trunk_sid") final String trunkSid, + @JsonProperty("url") final URI url ) { this.accountSid = accountSid; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; + this.friendlyName = friendlyName; this.sid = sid; this.trunkSid = trunkSid; - this.friendlyName = friendlyName; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); this.url = url; } - public final String getAccountSid() { - return this.accountSid; - } - - public final String getSid() { - return this.sid; - } - - public final String getTrunkSid() { - return this.trunkSid; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final URI getUrl() { - return this.url; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -175,28 +164,30 @@ public boolean equals(final Object o) { } IpAccessControlList other = (IpAccessControlList) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(sid, other.sid) && - Objects.equals(trunkSid, other.trunkSid) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(url, other.url) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(sid, other.sid) && + Objects.equals(trunkSid, other.trunkSid) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - accountSid, - sid, - trunkSid, - friendlyName, - dateCreated, - dateUpdated, - url + accountSid, + dateCreated, + dateUpdated, + friendlyName, + sid, + trunkSid, + url ); } + + } + diff --git a/src/main/java/com/twilio/rest/trunking/v1/trunk/IpAccessControlListCreator.java b/src/main/java/com/twilio/rest/trunking/v1/trunk/IpAccessControlListCreator.java index 8c6010229e..8e8d6ed616 100644 --- a/src/main/java/com/twilio/rest/trunking/v1/trunk/IpAccessControlListCreator.java +++ b/src/main/java/com/twilio/rest/trunking/v1/trunk/IpAccessControlListCreator.java @@ -14,8 +14,11 @@ package com.twilio.rest.trunking.v1.trunk; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,74 +30,61 @@ public class IpAccessControlListCreator extends Creator { - private String pathTrunkSid; + private String pathtrunkSid; private String ipAccessControlListSid; - public IpAccessControlListCreator( - final String pathTrunkSid, - final String ipAccessControlListSid - ) { - this.pathTrunkSid = pathTrunkSid; + public IpAccessControlListCreator(final String pathtrunkSid, final String ipAccessControlListSid) { + this.pathtrunkSid = pathtrunkSid; this.ipAccessControlListSid = ipAccessControlListSid; } - public IpAccessControlListCreator setIpAccessControlListSid( - final String ipAccessControlListSid - ) { + + public IpAccessControlListCreator setIpAccessControlListSid(final String ipAccessControlListSid) { this.ipAccessControlListSid = ipAccessControlListSid; return this; } + @Override public IpAccessControlList create(final TwilioRestClient client) { + String path = "/v1/Trunks/{TrunkSid}/IpAccessControlLists"; - path = - path.replace("{" + "TrunkSid" + "}", this.pathTrunkSid.toString()); - path = - path.replace( - "{" + "IpAccessControlListSid" + "}", - this.ipAccessControlListSid.toString() - ); + path = path.replace("{" + "TrunkSid" + "}", this.pathtrunkSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.TRUNKING.toString(), - path + HttpMethod.POST, + Domains.TRUNKING.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "IpAccessControlList creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("IpAccessControlList creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return IpAccessControlList.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return IpAccessControlList.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (ipAccessControlListSid != null) { - request.addPostParam( - "IpAccessControlListSid", - ipAccessControlListSid - ); + Serializer.toString(request, "IpAccessControlListSid", ipAccessControlListSid, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/trunking/v1/trunk/IpAccessControlListDeleter.java b/src/main/java/com/twilio/rest/trunking/v1/trunk/IpAccessControlListDeleter.java index 04004c241e..2216d187fe 100644 --- a/src/main/java/com/twilio/rest/trunking/v1/trunk/IpAccessControlListDeleter.java +++ b/src/main/java/com/twilio/rest/trunking/v1/trunk/IpAccessControlListDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.trunking.v1.trunk; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,47 +26,41 @@ public class IpAccessControlListDeleter extends Deleter { - private String pathTrunkSid; - private String pathSid; + private String pathtrunkSid; + private String pathsid; - public IpAccessControlListDeleter( - final String pathTrunkSid, - final String pathSid - ) { - this.pathTrunkSid = pathTrunkSid; - this.pathSid = pathSid; + public IpAccessControlListDeleter(final String pathtrunkSid, final String pathsid) { + this.pathtrunkSid = pathtrunkSid; + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/v1/Trunks/{TrunkSid}/IpAccessControlLists/{Sid}"; - path = - path.replace("{" + "TrunkSid" + "}", this.pathTrunkSid.toString()); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "TrunkSid" + "}", this.pathtrunkSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.TRUNKING.toString(), - path + HttpMethod.DELETE, + Domains.TRUNKING.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "IpAccessControlList delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("IpAccessControlList delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/trunking/v1/trunk/IpAccessControlListFetcher.java b/src/main/java/com/twilio/rest/trunking/v1/trunk/IpAccessControlListFetcher.java index b58eea3177..c551b8fb39 100644 --- a/src/main/java/com/twilio/rest/trunking/v1/trunk/IpAccessControlListFetcher.java +++ b/src/main/java/com/twilio/rest/trunking/v1/trunk/IpAccessControlListFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.trunking.v1.trunk; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,54 +26,44 @@ public class IpAccessControlListFetcher extends Fetcher { - private String pathTrunkSid; - private String pathSid; + private String pathtrunkSid; + private String pathsid; - public IpAccessControlListFetcher( - final String pathTrunkSid, - final String pathSid - ) { - this.pathTrunkSid = pathTrunkSid; - this.pathSid = pathSid; + public IpAccessControlListFetcher(final String pathtrunkSid, final String pathsid) { + this.pathtrunkSid = pathtrunkSid; + this.pathsid = pathsid; } + @Override public IpAccessControlList fetch(final TwilioRestClient client) { + String path = "/v1/Trunks/{TrunkSid}/IpAccessControlLists/{Sid}"; - path = - path.replace("{" + "TrunkSid" + "}", this.pathTrunkSid.toString()); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "TrunkSid" + "}", this.pathtrunkSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.TRUNKING.toString(), - path + HttpMethod.GET, + Domains.TRUNKING.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "IpAccessControlList fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("IpAccessControlList fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return IpAccessControlList.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return IpAccessControlList.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/trunking/v1/trunk/IpAccessControlListReader.java b/src/main/java/com/twilio/rest/trunking/v1/trunk/IpAccessControlListReader.java index 0bdbc00320..5ad69d2b0f 100644 --- a/src/main/java/com/twilio/rest/trunking/v1/trunk/IpAccessControlListReader.java +++ b/src/main/java/com/twilio/rest/trunking/v1/trunk/IpAccessControlListReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,114 +30,88 @@ public class IpAccessControlListReader extends Reader { - private String pathTrunkSid; + private String pathtrunkSid; private Long pageSize; - public IpAccessControlListReader(final String pathTrunkSid) { - this.pathTrunkSid = pathTrunkSid; + public IpAccessControlListReader(final String pathtrunkSid) { + this.pathtrunkSid = pathtrunkSid; } + public IpAccessControlListReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override - public ResourceSet read( - final TwilioRestClient client - ) { + public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/Trunks/{TrunkSid}/IpAccessControlLists"; - path = - path.replace("{" + "TrunkSid" + "}", this.pathTrunkSid.toString()); + + path = path.replace("{" + "TrunkSid" + "}", this.pathtrunkSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.TRUNKING.toString(), - path + HttpMethod.GET, + Domains.TRUNKING.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "IpAccessControlList read failed: Unable to connect to server" - ); + throw new ApiConnectionException("IpAccessControlList read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "ip_access_control_lists", - response.getContent(), - IpAccessControlList.class, - client.getObjectMapper() - ); + "ip_access_control_lists", + response.getContent(), + IpAccessControlList.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.TRUNKING.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.TRUNKING.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/trunking/v1/trunk/OriginationUrl.java b/src/main/java/com/twilio/rest/trunking/v1/trunk/OriginationUrl.java index 6b330365c8..123ab22bf0 100644 --- a/src/main/java/com/twilio/rest/trunking/v1/trunk/OriginationUrl.java +++ b/src/main/java/com/twilio/rest/trunking/v1/trunk/OriginationUrl.java @@ -18,80 +18,70 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class OriginationUrl extends Resource { - private static final long serialVersionUID = 133388691973992L; - public static OriginationUrlCreator creator( - final String pathTrunkSid, - final Integer weight, - final Integer priority, - final Boolean enabled, - final String friendlyName, - final URI sipUrl - ) { + public static OriginationUrlCreator creator(final String pathtrunkSid, final Integer weight, final Integer priority, final Boolean enabled, final String friendlyName, final URI sipUrl) { return new OriginationUrlCreator( - pathTrunkSid, - weight, - priority, - enabled, - friendlyName, - sipUrl + pathtrunkSid, weight, priority, enabled, friendlyName, sipUrl ); } - public static OriginationUrlDeleter deleter( - final String pathTrunkSid, - final String pathSid - ) { - return new OriginationUrlDeleter(pathTrunkSid, pathSid); + + public static OriginationUrlDeleter deleter(final String pathtrunkSid, final String pathsid) { + return new OriginationUrlDeleter( + pathtrunkSid, pathsid + ); } - public static OriginationUrlFetcher fetcher( - final String pathTrunkSid, - final String pathSid - ) { - return new OriginationUrlFetcher(pathTrunkSid, pathSid); + + public static OriginationUrlFetcher fetcher(final String pathtrunkSid, final String pathsid) { + return new OriginationUrlFetcher( + pathtrunkSid, pathsid + ); } - public static OriginationUrlReader reader(final String pathTrunkSid) { - return new OriginationUrlReader(pathTrunkSid); + + public static OriginationUrlReader reader(final String pathtrunkSid) { + return new OriginationUrlReader( + pathtrunkSid + ); } - public static OriginationUrlUpdater updater( - final String pathTrunkSid, - final String pathSid - ) { - return new OriginationUrlUpdater(pathTrunkSid, pathSid); + + public static OriginationUrlUpdater updater(final String pathtrunkSid, final String pathsid) { + return new OriginationUrlUpdater( + pathtrunkSid, pathsid + ); } + /** * Converts a JSON String into a OriginationUrl object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return OriginationUrl object represented by the provided JSON */ - public static OriginationUrl fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static OriginationUrl fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, OriginationUrl.class); @@ -106,14 +96,11 @@ public static OriginationUrl fromJson( * Converts a JSON InputStream into a OriginationUrl object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return OriginationUrl object represented by the provided JSON */ - public static OriginationUrl fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static OriginationUrl fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, OriginationUrl.class); @@ -124,87 +111,69 @@ public static OriginationUrl fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String sid; - private final String trunkSid; - private final Integer weight; + @Getter + private final ZonedDateTime dateCreated; + @Getter + private final ZonedDateTime dateUpdated; + @Getter private final Boolean enabled; - private final URI sipUrl; + @Getter private final String friendlyName; + @Getter private final Integer priority; - private final ZonedDateTime dateCreated; - private final ZonedDateTime dateUpdated; + @Getter + private final String sid; + @Getter + private final URI sipUrl; + @Getter + private final String trunkSid; + @Getter private final URI url; + @Getter + private final Integer weight; @JsonCreator private OriginationUrl( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("sid") final String sid, - @JsonProperty("trunk_sid") final String trunkSid, - @JsonProperty("weight") final Integer weight, - @JsonProperty("enabled") final Boolean enabled, - @JsonProperty("sip_url") final URI sipUrl, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("priority") final Integer priority, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("url") final URI url + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("enabled") final Boolean enabled, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("priority") final Integer priority, + @JsonProperty("sid") final String sid, + @JsonProperty("sip_url") final URI sipUrl, + @JsonProperty("trunk_sid") final String trunkSid, + @JsonProperty("url") final URI url, + @JsonProperty("weight") final Integer weight ) { this.accountSid = accountSid; - this.sid = sid; - this.trunkSid = trunkSid; - this.weight = weight; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.enabled = enabled; - this.sipUrl = sipUrl; this.friendlyName = friendlyName; this.priority = priority; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); + this.sid = sid; + this.sipUrl = sipUrl; + this.trunkSid = trunkSid; this.url = url; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getSid() { - return this.sid; - } - - public final String getTrunkSid() { - return this.trunkSid; - } - - public final Integer getWeight() { - return this.weight; - } - - public final Boolean getEnabled() { - return this.enabled; - } - - public final URI getSipUrl() { - return this.sipUrl; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final Integer getPriority() { - return this.priority; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final URI getUrl() { - return this.url; + this.weight = weight; } @Override @@ -218,36 +187,38 @@ public boolean equals(final Object o) { } OriginationUrl other = (OriginationUrl) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(sid, other.sid) && - Objects.equals(trunkSid, other.trunkSid) && - Objects.equals(weight, other.weight) && - Objects.equals(enabled, other.enabled) && - Objects.equals(sipUrl, other.sipUrl) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(priority, other.priority) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(url, other.url) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(enabled, other.enabled) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(priority, other.priority) && + Objects.equals(sid, other.sid) && + Objects.equals(sipUrl, other.sipUrl) && + Objects.equals(trunkSid, other.trunkSid) && + Objects.equals(url, other.url) && + Objects.equals(weight, other.weight) ); } @Override public int hashCode() { return Objects.hash( - accountSid, - sid, - trunkSid, - weight, - enabled, - sipUrl, - friendlyName, - priority, - dateCreated, - dateUpdated, - url + accountSid, + dateCreated, + dateUpdated, + enabled, + friendlyName, + priority, + sid, + sipUrl, + trunkSid, + url, + weight ); } + + } + diff --git a/src/main/java/com/twilio/rest/trunking/v1/trunk/OriginationUrlCreator.java b/src/main/java/com/twilio/rest/trunking/v1/trunk/OriginationUrlCreator.java index 7babd88aa1..f7ded6d8b4 100644 --- a/src/main/java/com/twilio/rest/trunking/v1/trunk/OriginationUrlCreator.java +++ b/src/main/java/com/twilio/rest/trunking/v1/trunk/OriginationUrlCreator.java @@ -14,9 +14,11 @@ package com.twilio.rest.trunking.v1.trunk; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; -import com.twilio.converter.Promoter; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,27 +27,20 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -import java.net.URI; + import java.net.URI; public class OriginationUrlCreator extends Creator { - private String pathTrunkSid; + private String pathtrunkSid; private Integer weight; private Integer priority; private Boolean enabled; private String friendlyName; private URI sipUrl; - public OriginationUrlCreator( - final String pathTrunkSid, - final Integer weight, - final Integer priority, - final Boolean enabled, - final String friendlyName, - final URI sipUrl - ) { - this.pathTrunkSid = pathTrunkSid; + public OriginationUrlCreator(final String pathtrunkSid, final Integer weight, final Integer priority, final Boolean enabled, final String friendlyName, final URI sipUrl) { + this.pathtrunkSid = pathtrunkSid; this.weight = weight; this.priority = priority; this.enabled = enabled; @@ -53,98 +48,97 @@ public OriginationUrlCreator( this.sipUrl = sipUrl; } + public OriginationUrlCreator setWeight(final Integer weight) { this.weight = weight; return this; } + public OriginationUrlCreator setPriority(final Integer priority) { this.priority = priority; return this; } + public OriginationUrlCreator setEnabled(final Boolean enabled) { this.enabled = enabled; return this; } + public OriginationUrlCreator setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + public OriginationUrlCreator setSipUrl(final URI sipUrl) { this.sipUrl = sipUrl; return this; } - public OriginationUrlCreator setSipUrl(final String sipUrl) { - return setSipUrl(Promoter.uriFromString(sipUrl)); - } @Override public OriginationUrl create(final TwilioRestClient client) { + String path = "/v1/Trunks/{TrunkSid}/OriginationUrls"; - path = - path.replace("{" + "TrunkSid" + "}", this.pathTrunkSid.toString()); - path = path.replace("{" + "Weight" + "}", this.weight.toString()); - path = path.replace("{" + "Priority" + "}", this.priority.toString()); - path = path.replace("{" + "Enabled" + "}", this.enabled.toString()); - path = - path.replace( - "{" + "FriendlyName" + "}", - this.friendlyName.toString() - ); - path = path.replace("{" + "SipUrl" + "}", this.sipUrl.toString()); + path = path.replace("{" + "TrunkSid" + "}", this.pathtrunkSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.TRUNKING.toString(), - path + HttpMethod.POST, + Domains.TRUNKING.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "OriginationUrl creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("OriginationUrl creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return OriginationUrl.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return OriginationUrl.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (weight != null) { - request.addPostParam("Weight", weight.toString()); + Serializer.toString(request, "Weight", weight, ParameterType.URLENCODED); } + + if (priority != null) { - request.addPostParam("Priority", priority.toString()); + Serializer.toString(request, "Priority", priority, ParameterType.URLENCODED); } + + if (enabled != null) { - request.addPostParam("Enabled", enabled.toString()); + Serializer.toString(request, "Enabled", enabled, ParameterType.URLENCODED); } + + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + if (sipUrl != null) { - request.addPostParam("SipUrl", sipUrl.toString()); + Serializer.toString(request, "SipUrl", sipUrl, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/trunking/v1/trunk/OriginationUrlDeleter.java b/src/main/java/com/twilio/rest/trunking/v1/trunk/OriginationUrlDeleter.java index 6bea21af65..b22112861a 100644 --- a/src/main/java/com/twilio/rest/trunking/v1/trunk/OriginationUrlDeleter.java +++ b/src/main/java/com/twilio/rest/trunking/v1/trunk/OriginationUrlDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.trunking.v1.trunk; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,47 +26,41 @@ public class OriginationUrlDeleter extends Deleter { - private String pathTrunkSid; - private String pathSid; + private String pathtrunkSid; + private String pathsid; - public OriginationUrlDeleter( - final String pathTrunkSid, - final String pathSid - ) { - this.pathTrunkSid = pathTrunkSid; - this.pathSid = pathSid; + public OriginationUrlDeleter(final String pathtrunkSid, final String pathsid) { + this.pathtrunkSid = pathtrunkSid; + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/v1/Trunks/{TrunkSid}/OriginationUrls/{Sid}"; - path = - path.replace("{" + "TrunkSid" + "}", this.pathTrunkSid.toString()); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "TrunkSid" + "}", this.pathtrunkSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.TRUNKING.toString(), - path + HttpMethod.DELETE, + Domains.TRUNKING.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "OriginationUrl delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("OriginationUrl delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/trunking/v1/trunk/OriginationUrlFetcher.java b/src/main/java/com/twilio/rest/trunking/v1/trunk/OriginationUrlFetcher.java index c1a2a44505..0857b18097 100644 --- a/src/main/java/com/twilio/rest/trunking/v1/trunk/OriginationUrlFetcher.java +++ b/src/main/java/com/twilio/rest/trunking/v1/trunk/OriginationUrlFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.trunking.v1.trunk; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,54 +26,44 @@ public class OriginationUrlFetcher extends Fetcher { - private String pathTrunkSid; - private String pathSid; + private String pathtrunkSid; + private String pathsid; - public OriginationUrlFetcher( - final String pathTrunkSid, - final String pathSid - ) { - this.pathTrunkSid = pathTrunkSid; - this.pathSid = pathSid; + public OriginationUrlFetcher(final String pathtrunkSid, final String pathsid) { + this.pathtrunkSid = pathtrunkSid; + this.pathsid = pathsid; } + @Override public OriginationUrl fetch(final TwilioRestClient client) { + String path = "/v1/Trunks/{TrunkSid}/OriginationUrls/{Sid}"; - path = - path.replace("{" + "TrunkSid" + "}", this.pathTrunkSid.toString()); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "TrunkSid" + "}", this.pathtrunkSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.TRUNKING.toString(), - path + HttpMethod.GET, + Domains.TRUNKING.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "OriginationUrl fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("OriginationUrl fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return OriginationUrl.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return OriginationUrl.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/trunking/v1/trunk/OriginationUrlReader.java b/src/main/java/com/twilio/rest/trunking/v1/trunk/OriginationUrlReader.java index 2a2c6a8ad1..92d0292fd8 100644 --- a/src/main/java/com/twilio/rest/trunking/v1/trunk/OriginationUrlReader.java +++ b/src/main/java/com/twilio/rest/trunking/v1/trunk/OriginationUrlReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,112 +30,88 @@ public class OriginationUrlReader extends Reader { - private String pathTrunkSid; + private String pathtrunkSid; private Long pageSize; - public OriginationUrlReader(final String pathTrunkSid) { - this.pathTrunkSid = pathTrunkSid; + public OriginationUrlReader(final String pathtrunkSid) { + this.pathtrunkSid = pathtrunkSid; } + public OriginationUrlReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/Trunks/{TrunkSid}/OriginationUrls"; - path = - path.replace("{" + "TrunkSid" + "}", this.pathTrunkSid.toString()); + + path = path.replace("{" + "TrunkSid" + "}", this.pathtrunkSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.TRUNKING.toString(), - path + HttpMethod.GET, + Domains.TRUNKING.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "OriginationUrl read failed: Unable to connect to server" - ); + throw new ApiConnectionException("OriginationUrl read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "origination_urls", - response.getContent(), - OriginationUrl.class, - client.getObjectMapper() - ); + "origination_urls", + response.getContent(), + OriginationUrl.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.TRUNKING.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.TRUNKING.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/trunking/v1/trunk/OriginationUrlUpdater.java b/src/main/java/com/twilio/rest/trunking/v1/trunk/OriginationUrlUpdater.java index 328d564d67..8988b207dd 100644 --- a/src/main/java/com/twilio/rest/trunking/v1/trunk/OriginationUrlUpdater.java +++ b/src/main/java/com/twilio/rest/trunking/v1/trunk/OriginationUrlUpdater.java @@ -16,7 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; -import com.twilio.converter.Promoter; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,110 +26,115 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.net.URI; public class OriginationUrlUpdater extends Updater { - - private String pathTrunkSid; - private String pathSid; + private String pathtrunkSid; + private String pathsid; private Integer weight; private Integer priority; private Boolean enabled; private String friendlyName; private URI sipUrl; - public OriginationUrlUpdater( - final String pathTrunkSid, - final String pathSid - ) { - this.pathTrunkSid = pathTrunkSid; - this.pathSid = pathSid; + public OriginationUrlUpdater(final String pathtrunkSid, final String pathsid) { + this.pathtrunkSid = pathtrunkSid; + this.pathsid = pathsid; } + public OriginationUrlUpdater setWeight(final Integer weight) { this.weight = weight; return this; } + public OriginationUrlUpdater setPriority(final Integer priority) { this.priority = priority; return this; } + public OriginationUrlUpdater setEnabled(final Boolean enabled) { this.enabled = enabled; return this; } + public OriginationUrlUpdater setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + public OriginationUrlUpdater setSipUrl(final URI sipUrl) { this.sipUrl = sipUrl; return this; } - public OriginationUrlUpdater setSipUrl(final String sipUrl) { - return setSipUrl(Promoter.uriFromString(sipUrl)); - } @Override public OriginationUrl update(final TwilioRestClient client) { + String path = "/v1/Trunks/{TrunkSid}/OriginationUrls/{Sid}"; - path = - path.replace("{" + "TrunkSid" + "}", this.pathTrunkSid.toString()); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "TrunkSid" + "}", this.pathtrunkSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.TRUNKING.toString(), - path + HttpMethod.POST, + Domains.TRUNKING.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "OriginationUrl update failed: Unable to connect to server" - ); + throw new ApiConnectionException("OriginationUrl update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return OriginationUrl.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return OriginationUrl.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (weight != null) { - request.addPostParam("Weight", weight.toString()); + Serializer.toString(request, "Weight", weight, ParameterType.URLENCODED); } + + if (priority != null) { - request.addPostParam("Priority", priority.toString()); + Serializer.toString(request, "Priority", priority, ParameterType.URLENCODED); } + + if (enabled != null) { - request.addPostParam("Enabled", enabled.toString()); + Serializer.toString(request, "Enabled", enabled, ParameterType.URLENCODED); } + + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + if (sipUrl != null) { - request.addPostParam("SipUrl", sipUrl.toString()); + Serializer.toString(request, "SipUrl", sipUrl, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/trunking/v1/trunk/PhoneNumber.java b/src/main/java/com/twilio/rest/trunking/v1/trunk/PhoneNumber.java index 733b18311c..fb00721a00 100644 --- a/src/main/java/com/twilio/rest/trunking/v1/trunk/PhoneNumber.java +++ b/src/main/java/com/twilio/rest/trunking/v1/trunk/PhoneNumber.java @@ -18,66 +18,89 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.http.HttpMethod; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class PhoneNumber extends Resource { - private static final long serialVersionUID = 92972440584956L; - public static PhoneNumberCreator creator( - final String pathTrunkSid, - final String phoneNumberSid - ) { - return new PhoneNumberCreator(pathTrunkSid, phoneNumberSid); + public static PhoneNumberCreator creator(final String pathtrunkSid, final String phoneNumberSid) { + return new PhoneNumberCreator( + pathtrunkSid, phoneNumberSid + ); } - public static PhoneNumberDeleter deleter( - final String pathTrunkSid, - final String pathSid - ) { - return new PhoneNumberDeleter(pathTrunkSid, pathSid); + + public static PhoneNumberDeleter deleter(final String pathtrunkSid, final String pathsid) { + return new PhoneNumberDeleter( + pathtrunkSid, pathsid + ); } - public static PhoneNumberFetcher fetcher( - final String pathTrunkSid, - final String pathSid - ) { - return new PhoneNumberFetcher(pathTrunkSid, pathSid); + + public static PhoneNumberFetcher fetcher(final String pathtrunkSid, final String pathsid) { + return new PhoneNumberFetcher( + pathtrunkSid, pathsid + ); } - public static PhoneNumberReader reader(final String pathTrunkSid) { - return new PhoneNumberReader(pathTrunkSid); + + public static PhoneNumberReader reader(final String pathtrunkSid) { + return new PhoneNumberReader( + pathtrunkSid + ); + } + + + public enum AddressRequirement { + NONE("none"), + ANY("any"), + LOCAL("local"), + FOREIGN("foreign"); + + private final String value; + + private AddressRequirement(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static AddressRequirement forValue(final String value) { + return Promoter.enumFromString(value, AddressRequirement.values()); + } } + /** * Converts a JSON String into a PhoneNumber object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return PhoneNumber object represented by the provided JSON */ - public static PhoneNumber fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static PhoneNumber fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, PhoneNumber.class); @@ -92,14 +115,11 @@ public static PhoneNumber fromJson( * Converts a JSON InputStream into a PhoneNumber object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return PhoneNumber object represented by the provided JSON */ - public static PhoneNumber fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static PhoneNumber fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, PhoneNumber.class); @@ -110,79 +130,110 @@ public static PhoneNumber fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; + @Getter private final PhoneNumber.AddressRequirement addressRequirements; + @Getter private final String apiVersion; + @Getter private final Boolean beta; + @Getter private final Map capabilities; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; + @Getter private final String friendlyName; + @Getter private final Map links; + @Getter private final com.twilio.type.PhoneNumber phoneNumber; + @Getter private final String sid; + @Getter private final String smsApplicationSid; + @Getter private final HttpMethod smsFallbackMethod; + @Getter private final URI smsFallbackUrl; + @Getter private final HttpMethod smsMethod; + @Getter private final URI smsUrl; + @Getter private final URI statusCallback; + @Getter private final HttpMethod statusCallbackMethod; + @Getter private final String trunkSid; + @Getter private final URI url; + @Getter private final String voiceApplicationSid; + @Getter private final Boolean voiceCallerIdLookup; + @Getter private final HttpMethod voiceFallbackMethod; + @Getter private final URI voiceFallbackUrl; + @Getter private final HttpMethod voiceMethod; + @Getter private final URI voiceUrl; @JsonCreator private PhoneNumber( - @JsonProperty("account_sid") final String accountSid, - @JsonProperty( - "address_requirements" - ) final PhoneNumber.AddressRequirement addressRequirements, - @JsonProperty("api_version") final String apiVersion, - @JsonProperty("beta") final Boolean beta, - @JsonProperty("capabilities") final Map capabilities, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("links") final Map links, - @JsonProperty( - "phone_number" - ) final com.twilio.type.PhoneNumber phoneNumber, - @JsonProperty("sid") final String sid, - @JsonProperty("sms_application_sid") final String smsApplicationSid, - @JsonProperty("sms_fallback_method") final HttpMethod smsFallbackMethod, - @JsonProperty("sms_fallback_url") final URI smsFallbackUrl, - @JsonProperty("sms_method") final HttpMethod smsMethod, - @JsonProperty("sms_url") final URI smsUrl, - @JsonProperty("status_callback") final URI statusCallback, - @JsonProperty( - "status_callback_method" - ) final HttpMethod statusCallbackMethod, - @JsonProperty("trunk_sid") final String trunkSid, - @JsonProperty("url") final URI url, - @JsonProperty("voice_application_sid") final String voiceApplicationSid, - @JsonProperty( - "voice_caller_id_lookup" - ) final Boolean voiceCallerIdLookup, - @JsonProperty( - "voice_fallback_method" - ) final HttpMethod voiceFallbackMethod, - @JsonProperty("voice_fallback_url") final URI voiceFallbackUrl, - @JsonProperty("voice_method") final HttpMethod voiceMethod, - @JsonProperty("voice_url") final URI voiceUrl + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("address_requirements") final PhoneNumber.AddressRequirement addressRequirements, + @JsonProperty("api_version") final String apiVersion, + @JsonProperty("beta") final Boolean beta, + @JsonProperty("capabilities") final Map capabilities, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("links") final Map links, + @JsonProperty("phone_number") final com.twilio.type.PhoneNumber phoneNumber, + @JsonProperty("sid") final String sid, + @JsonProperty("sms_application_sid") final String smsApplicationSid, + @JsonProperty("sms_fallback_method") final HttpMethod smsFallbackMethod, + @JsonProperty("sms_fallback_url") final URI smsFallbackUrl, + @JsonProperty("sms_method") final HttpMethod smsMethod, + @JsonProperty("sms_url") final URI smsUrl, + @JsonProperty("status_callback") final URI statusCallback, + @JsonProperty("status_callback_method") final HttpMethod statusCallbackMethod, + @JsonProperty("trunk_sid") final String trunkSid, + @JsonProperty("url") final URI url, + @JsonProperty("voice_application_sid") final String voiceApplicationSid, + @JsonProperty("voice_caller_id_lookup") final Boolean voiceCallerIdLookup, + @JsonProperty("voice_fallback_method") final HttpMethod voiceFallbackMethod, + @JsonProperty("voice_fallback_url") final URI voiceFallbackUrl, + @JsonProperty("voice_method") final HttpMethod voiceMethod, + @JsonProperty("voice_url") final URI voiceUrl ) { this.accountSid = accountSid; this.addressRequirements = addressRequirements; this.apiVersion = apiVersion; this.beta = beta; this.capabilities = capabilities; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.friendlyName = friendlyName; this.links = links; this.phoneNumber = phoneNumber; @@ -204,110 +255,6 @@ private PhoneNumber( this.voiceUrl = voiceUrl; } - public final String getAccountSid() { - return this.accountSid; - } - - public final PhoneNumber.AddressRequirement getAddressRequirements() { - return this.addressRequirements; - } - - public final String getApiVersion() { - return this.apiVersion; - } - - public final Boolean getBeta() { - return this.beta; - } - - public final Map getCapabilities() { - return this.capabilities; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final Map getLinks() { - return this.links; - } - - public final com.twilio.type.PhoneNumber getPhoneNumber() { - return this.phoneNumber; - } - - public final String getSid() { - return this.sid; - } - - public final String getSmsApplicationSid() { - return this.smsApplicationSid; - } - - public final HttpMethod getSmsFallbackMethod() { - return this.smsFallbackMethod; - } - - public final URI getSmsFallbackUrl() { - return this.smsFallbackUrl; - } - - public final HttpMethod getSmsMethod() { - return this.smsMethod; - } - - public final URI getSmsUrl() { - return this.smsUrl; - } - - public final URI getStatusCallback() { - return this.statusCallback; - } - - public final HttpMethod getStatusCallbackMethod() { - return this.statusCallbackMethod; - } - - public final String getTrunkSid() { - return this.trunkSid; - } - - public final URI getUrl() { - return this.url; - } - - public final String getVoiceApplicationSid() { - return this.voiceApplicationSid; - } - - public final Boolean getVoiceCallerIdLookup() { - return this.voiceCallerIdLookup; - } - - public final HttpMethod getVoiceFallbackMethod() { - return this.voiceFallbackMethod; - } - - public final URI getVoiceFallbackUrl() { - return this.voiceFallbackUrl; - } - - public final HttpMethod getVoiceMethod() { - return this.voiceMethod; - } - - public final URI getVoiceUrl() { - return this.voiceUrl; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -319,88 +266,68 @@ public boolean equals(final Object o) { } PhoneNumber other = (PhoneNumber) o; - return ( - Objects.equals(accountSid, other.accountSid) && - Objects.equals(addressRequirements, other.addressRequirements) && - Objects.equals(apiVersion, other.apiVersion) && - Objects.equals(beta, other.beta) && - Objects.equals(capabilities, other.capabilities) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(links, other.links) && - Objects.equals(phoneNumber, other.phoneNumber) && - Objects.equals(sid, other.sid) && - Objects.equals(smsApplicationSid, other.smsApplicationSid) && - Objects.equals(smsFallbackMethod, other.smsFallbackMethod) && - Objects.equals(smsFallbackUrl, other.smsFallbackUrl) && - Objects.equals(smsMethod, other.smsMethod) && - Objects.equals(smsUrl, other.smsUrl) && - Objects.equals(statusCallback, other.statusCallback) && - Objects.equals(statusCallbackMethod, other.statusCallbackMethod) && - Objects.equals(trunkSid, other.trunkSid) && - Objects.equals(url, other.url) && - Objects.equals(voiceApplicationSid, other.voiceApplicationSid) && - Objects.equals(voiceCallerIdLookup, other.voiceCallerIdLookup) && - Objects.equals(voiceFallbackMethod, other.voiceFallbackMethod) && - Objects.equals(voiceFallbackUrl, other.voiceFallbackUrl) && - Objects.equals(voiceMethod, other.voiceMethod) && - Objects.equals(voiceUrl, other.voiceUrl) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(addressRequirements, other.addressRequirements) && + Objects.equals(apiVersion, other.apiVersion) && + Objects.equals(beta, other.beta) && + Objects.equals(capabilities, other.capabilities) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(links, other.links) && + Objects.equals(phoneNumber, other.phoneNumber) && + Objects.equals(sid, other.sid) && + Objects.equals(smsApplicationSid, other.smsApplicationSid) && + Objects.equals(smsFallbackMethod, other.smsFallbackMethod) && + Objects.equals(smsFallbackUrl, other.smsFallbackUrl) && + Objects.equals(smsMethod, other.smsMethod) && + Objects.equals(smsUrl, other.smsUrl) && + Objects.equals(statusCallback, other.statusCallback) && + Objects.equals(statusCallbackMethod, other.statusCallbackMethod) && + Objects.equals(trunkSid, other.trunkSid) && + Objects.equals(url, other.url) && + Objects.equals(voiceApplicationSid, other.voiceApplicationSid) && + Objects.equals(voiceCallerIdLookup, other.voiceCallerIdLookup) && + Objects.equals(voiceFallbackMethod, other.voiceFallbackMethod) && + Objects.equals(voiceFallbackUrl, other.voiceFallbackUrl) && + Objects.equals(voiceMethod, other.voiceMethod) && + Objects.equals(voiceUrl, other.voiceUrl) ); } @Override public int hashCode() { return Objects.hash( - accountSid, - addressRequirements, - apiVersion, - beta, - capabilities, - dateCreated, - dateUpdated, - friendlyName, - links, - phoneNumber, - sid, - smsApplicationSid, - smsFallbackMethod, - smsFallbackUrl, - smsMethod, - smsUrl, - statusCallback, - statusCallbackMethod, - trunkSid, - url, - voiceApplicationSid, - voiceCallerIdLookup, - voiceFallbackMethod, - voiceFallbackUrl, - voiceMethod, - voiceUrl + accountSid, + addressRequirements, + apiVersion, + beta, + capabilities, + dateCreated, + dateUpdated, + friendlyName, + links, + phoneNumber, + sid, + smsApplicationSid, + smsFallbackMethod, + smsFallbackUrl, + smsMethod, + smsUrl, + statusCallback, + statusCallbackMethod, + trunkSid, + url, + voiceApplicationSid, + voiceCallerIdLookup, + voiceFallbackMethod, + voiceFallbackUrl, + voiceMethod, + voiceUrl ); } - public enum AddressRequirement { - NONE("none"), - ANY("any"), - LOCAL("local"), - FOREIGN("foreign"); - private final String value; - - private AddressRequirement(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static AddressRequirement forValue(final String value) { - return Promoter.enumFromString(value, AddressRequirement.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/trunking/v1/trunk/PhoneNumberCreator.java b/src/main/java/com/twilio/rest/trunking/v1/trunk/PhoneNumberCreator.java index 4408aac334..792ee0710d 100644 --- a/src/main/java/com/twilio/rest/trunking/v1/trunk/PhoneNumberCreator.java +++ b/src/main/java/com/twilio/rest/trunking/v1/trunk/PhoneNumberCreator.java @@ -14,8 +14,11 @@ package com.twilio.rest.trunking.v1.trunk; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,69 +30,61 @@ public class PhoneNumberCreator extends Creator { - private String pathTrunkSid; + private String pathtrunkSid; private String phoneNumberSid; - public PhoneNumberCreator( - final String pathTrunkSid, - final String phoneNumberSid - ) { - this.pathTrunkSid = pathTrunkSid; + public PhoneNumberCreator(final String pathtrunkSid, final String phoneNumberSid) { + this.pathtrunkSid = pathtrunkSid; this.phoneNumberSid = phoneNumberSid; } + public PhoneNumberCreator setPhoneNumberSid(final String phoneNumberSid) { this.phoneNumberSid = phoneNumberSid; return this; } + @Override public PhoneNumber create(final TwilioRestClient client) { + String path = "/v1/Trunks/{TrunkSid}/PhoneNumbers"; - path = - path.replace("{" + "TrunkSid" + "}", this.pathTrunkSid.toString()); - path = - path.replace( - "{" + "PhoneNumberSid" + "}", - this.phoneNumberSid.toString() - ); + path = path.replace("{" + "TrunkSid" + "}", this.pathtrunkSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.TRUNKING.toString(), - path + HttpMethod.POST, + Domains.TRUNKING.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "PhoneNumber creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("PhoneNumber creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return PhoneNumber.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return PhoneNumber.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (phoneNumberSid != null) { - request.addPostParam("PhoneNumberSid", phoneNumberSid); + Serializer.toString(request, "PhoneNumberSid", phoneNumberSid, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/trunking/v1/trunk/PhoneNumberDeleter.java b/src/main/java/com/twilio/rest/trunking/v1/trunk/PhoneNumberDeleter.java index f23455d65d..40d7eb48da 100644 --- a/src/main/java/com/twilio/rest/trunking/v1/trunk/PhoneNumberDeleter.java +++ b/src/main/java/com/twilio/rest/trunking/v1/trunk/PhoneNumberDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.trunking.v1.trunk; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,44 +26,41 @@ public class PhoneNumberDeleter extends Deleter { - private String pathTrunkSid; - private String pathSid; + private String pathtrunkSid; + private String pathsid; - public PhoneNumberDeleter(final String pathTrunkSid, final String pathSid) { - this.pathTrunkSid = pathTrunkSid; - this.pathSid = pathSid; + public PhoneNumberDeleter(final String pathtrunkSid, final String pathsid) { + this.pathtrunkSid = pathtrunkSid; + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/v1/Trunks/{TrunkSid}/PhoneNumbers/{Sid}"; - path = - path.replace("{" + "TrunkSid" + "}", this.pathTrunkSid.toString()); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "TrunkSid" + "}", this.pathtrunkSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.TRUNKING.toString(), - path + HttpMethod.DELETE, + Domains.TRUNKING.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "PhoneNumber delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("PhoneNumber delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/trunking/v1/trunk/PhoneNumberFetcher.java b/src/main/java/com/twilio/rest/trunking/v1/trunk/PhoneNumberFetcher.java index cbcc97336a..74b6a3c86a 100644 --- a/src/main/java/com/twilio/rest/trunking/v1/trunk/PhoneNumberFetcher.java +++ b/src/main/java/com/twilio/rest/trunking/v1/trunk/PhoneNumberFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.trunking.v1.trunk; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,51 +26,44 @@ public class PhoneNumberFetcher extends Fetcher { - private String pathTrunkSid; - private String pathSid; + private String pathtrunkSid; + private String pathsid; - public PhoneNumberFetcher(final String pathTrunkSid, final String pathSid) { - this.pathTrunkSid = pathTrunkSid; - this.pathSid = pathSid; + public PhoneNumberFetcher(final String pathtrunkSid, final String pathsid) { + this.pathtrunkSid = pathtrunkSid; + this.pathsid = pathsid; } + @Override public PhoneNumber fetch(final TwilioRestClient client) { + String path = "/v1/Trunks/{TrunkSid}/PhoneNumbers/{Sid}"; - path = - path.replace("{" + "TrunkSid" + "}", this.pathTrunkSid.toString()); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "TrunkSid" + "}", this.pathtrunkSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.TRUNKING.toString(), - path + HttpMethod.GET, + Domains.TRUNKING.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "PhoneNumber fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("PhoneNumber fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return PhoneNumber.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return PhoneNumber.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/trunking/v1/trunk/PhoneNumberReader.java b/src/main/java/com/twilio/rest/trunking/v1/trunk/PhoneNumberReader.java index 99ceb40470..c0a2ce4758 100644 --- a/src/main/java/com/twilio/rest/trunking/v1/trunk/PhoneNumberReader.java +++ b/src/main/java/com/twilio/rest/trunking/v1/trunk/PhoneNumberReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -29,112 +30,88 @@ public class PhoneNumberReader extends Reader { - private String pathTrunkSid; + private String pathtrunkSid; private Long pageSize; - public PhoneNumberReader(final String pathTrunkSid) { - this.pathTrunkSid = pathTrunkSid; + public PhoneNumberReader(final String pathtrunkSid) { + this.pathtrunkSid = pathtrunkSid; } + public PhoneNumberReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/Trunks/{TrunkSid}/PhoneNumbers"; - path = - path.replace("{" + "TrunkSid" + "}", this.pathTrunkSid.toString()); + + path = path.replace("{" + "TrunkSid" + "}", this.pathtrunkSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.TRUNKING.toString(), - path + HttpMethod.GET, + Domains.TRUNKING.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "PhoneNumber read failed: Unable to connect to server" - ); + throw new ApiConnectionException("PhoneNumber read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "phone_numbers", - response.getContent(), - PhoneNumber.class, - client.getObjectMapper() - ); + "phone_numbers", + response.getContent(), + PhoneNumber.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.TRUNKING.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.TRUNKING.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/trunking/v1/trunk/Recording.java b/src/main/java/com/twilio/rest/trunking/v1/trunk/Recording.java index 022e65d0b9..03bd90af8e 100644 --- a/src/main/java/com/twilio/rest/trunking/v1/trunk/Recording.java +++ b/src/main/java/com/twilio/rest/trunking/v1/trunk/Recording.java @@ -18,43 +18,91 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Recording extends Resource { - private static final long serialVersionUID = 230784342010429L; - public static RecordingFetcher fetcher(final String pathTrunkSid) { - return new RecordingFetcher(pathTrunkSid); + public static RecordingFetcher fetcher(final String pathtrunkSid) { + return new RecordingFetcher( + pathtrunkSid + ); + } + + + public static RecordingUpdater updater(final String pathtrunkSid) { + return new RecordingUpdater( + pathtrunkSid + ); + } + + + public enum RecordingMode { + DO_NOT_RECORD("do-not-record"), + RECORD_FROM_RINGING("record-from-ringing"), + RECORD_FROM_ANSWER("record-from-answer"), + RECORD_FROM_RINGING_DUAL("record-from-ringing-dual"), + RECORD_FROM_ANSWER_DUAL("record-from-answer-dual"); + + private final String value; + + private RecordingMode(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static RecordingMode forValue(final String value) { + return Promoter.enumFromString(value, RecordingMode.values()); + } } - public static RecordingUpdater updater(final String pathTrunkSid) { - return new RecordingUpdater(pathTrunkSid); + public enum RecordingTrim { + TRIM_SILENCE("trim-silence"), + DO_NOT_TRIM("do-not-trim"); + + private final String value; + + private RecordingTrim(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static RecordingTrim forValue(final String value) { + return Promoter.enumFromString(value, RecordingTrim.values()); + } } + /** * Converts a JSON String into a Recording object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Recording object represented by the provided JSON */ - public static Recording fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Recording fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Recording.class); @@ -69,14 +117,11 @@ public static Recording fromJson( * Converts a JSON InputStream into a Recording object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Recording object represented by the provided JSON */ - public static Recording fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Recording fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Recording.class); @@ -87,26 +132,33 @@ public static Recording fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final Recording.RecordingMode mode; + @Getter private final Recording.RecordingTrim trim; @JsonCreator private Recording( - @JsonProperty("mode") final Recording.RecordingMode mode, - @JsonProperty("trim") final Recording.RecordingTrim trim + @JsonProperty("mode") final Recording.RecordingMode mode, + @JsonProperty("trim") final Recording.RecordingTrim trim ) { this.mode = mode; this.trim = trim; } - public final Recording.RecordingMode getMode() { - return this.mode; - } - - public final Recording.RecordingTrim getTrim() { - return this.trim; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -118,57 +170,20 @@ public boolean equals(final Object o) { } Recording other = (Recording) o; - return ( - Objects.equals(mode, other.mode) && Objects.equals(trim, other.trim) + Objects.equals(mode, other.mode) && + Objects.equals(trim, other.trim) ); } @Override public int hashCode() { - return Objects.hash(mode, trim); - } - - public enum RecordingMode { - DO_NOT_RECORD("do-not-record"), - RECORD_FROM_RINGING("record-from-ringing"), - RECORD_FROM_ANSWER("record-from-answer"), - RECORD_FROM_RINGING_DUAL("record-from-ringing-dual"), - RECORD_FROM_ANSWER_DUAL("record-from-answer-dual"); - - private final String value; - - private RecordingMode(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static RecordingMode forValue(final String value) { - return Promoter.enumFromString(value, RecordingMode.values()); - } + return Objects.hash( + mode, + trim + ); } - public enum RecordingTrim { - TRIM_SILENCE("trim-silence"), - DO_NOT_TRIM("do-not-trim"); - private final String value; - - private RecordingTrim(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static RecordingTrim forValue(final String value) { - return Promoter.enumFromString(value, RecordingTrim.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/trunking/v1/trunk/RecordingFetcher.java b/src/main/java/com/twilio/rest/trunking/v1/trunk/RecordingFetcher.java index 280a1ce4c5..bf7ab59d6e 100644 --- a/src/main/java/com/twilio/rest/trunking/v1/trunk/RecordingFetcher.java +++ b/src/main/java/com/twilio/rest/trunking/v1/trunk/RecordingFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.trunking.v1.trunk; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,48 +26,41 @@ public class RecordingFetcher extends Fetcher { - private String pathTrunkSid; + private String pathtrunkSid; - public RecordingFetcher(final String pathTrunkSid) { - this.pathTrunkSid = pathTrunkSid; + public RecordingFetcher(final String pathtrunkSid) { + this.pathtrunkSid = pathtrunkSid; } + @Override public Recording fetch(final TwilioRestClient client) { + String path = "/v1/Trunks/{TrunkSid}/Recording"; - path = - path.replace("{" + "TrunkSid" + "}", this.pathTrunkSid.toString()); + path = path.replace("{" + "TrunkSid" + "}", this.pathtrunkSid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.TRUNKING.toString(), - path + HttpMethod.GET, + Domains.TRUNKING.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Recording fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Recording fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return Recording.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Recording.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/trunking/v1/trunk/RecordingUpdater.java b/src/main/java/com/twilio/rest/trunking/v1/trunk/RecordingUpdater.java index a6b4d03ce7..5c0086e297 100644 --- a/src/main/java/com/twilio/rest/trunking/v1/trunk/RecordingUpdater.java +++ b/src/main/java/com/twilio/rest/trunking/v1/trunk/RecordingUpdater.java @@ -16,6 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -26,70 +28,72 @@ import com.twilio.rest.Domains; public class RecordingUpdater extends Updater { - - private String pathTrunkSid; + private String pathtrunkSid; private Recording.RecordingMode mode; private Recording.RecordingTrim trim; - public RecordingUpdater(final String pathTrunkSid) { - this.pathTrunkSid = pathTrunkSid; + public RecordingUpdater(final String pathtrunkSid) { + this.pathtrunkSid = pathtrunkSid; } + public RecordingUpdater setMode(final Recording.RecordingMode mode) { this.mode = mode; return this; } + public RecordingUpdater setTrim(final Recording.RecordingTrim trim) { this.trim = trim; return this; } + @Override public Recording update(final TwilioRestClient client) { + String path = "/v1/Trunks/{TrunkSid}/Recording"; - path = - path.replace("{" + "TrunkSid" + "}", this.pathTrunkSid.toString()); + path = path.replace("{" + "TrunkSid" + "}", this.pathtrunkSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.TRUNKING.toString(), - path + HttpMethod.POST, + Domains.TRUNKING.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Recording update failed: Unable to connect to server" - ); + throw new ApiConnectionException("Recording update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Recording.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Recording.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (mode != null) { - request.addPostParam("Mode", mode.toString()); + Serializer.toString(request, "Mode", mode, ParameterType.URLENCODED); } + + if (trim != null) { - request.addPostParam("Trim", trim.toString()); + Serializer.toString(request, "Trim", trim, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/trusthub/v1/ComplianceInquiries.java b/src/main/java/com/twilio/rest/trusthub/v1/ComplianceInquiries.java index 07a57994e0..97123c2127 100644 --- a/src/main/java/com/twilio/rest/trusthub/v1/ComplianceInquiries.java +++ b/src/main/java/com/twilio/rest/trusthub/v1/ComplianceInquiries.java @@ -18,51 +18,47 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class ComplianceInquiries extends Resource { - private static final long serialVersionUID = 107785038422599L; - public static ComplianceInquiriesCreator creator( - final String primaryProfileSid - ) { - return new ComplianceInquiriesCreator(primaryProfileSid); + public static ComplianceInquiriesCreator creator(final String primaryProfileSid) { + return new ComplianceInquiriesCreator( + primaryProfileSid + ); } - public static ComplianceInquiriesUpdater updater( - final String pathCustomerId, - final String primaryProfileSid - ) { + + public static ComplianceInquiriesUpdater updater(final String pathcustomerId, final String primaryProfileSid) { return new ComplianceInquiriesUpdater( - pathCustomerId, - primaryProfileSid + pathcustomerId, primaryProfileSid ); } + /** * Converts a JSON String into a ComplianceInquiries object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return ComplianceInquiries object represented by the provided JSON */ - public static ComplianceInquiries fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static ComplianceInquiries fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, ComplianceInquiries.class); @@ -77,14 +73,11 @@ public static ComplianceInquiries fromJson( * Converts a JSON InputStream into a ComplianceInquiries object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return ComplianceInquiries object represented by the provided JSON */ - public static ComplianceInquiries fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static ComplianceInquiries fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, ComplianceInquiries.class); @@ -95,40 +88,41 @@ public static ComplianceInquiries fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter + private final String customerId; + @Getter private final String inquiryId; + @Getter private final String inquirySessionToken; - private final String customerId; + @Getter private final URI url; @JsonCreator private ComplianceInquiries( - @JsonProperty("inquiry_id") final String inquiryId, - @JsonProperty("inquiry_session_token") final String inquirySessionToken, - @JsonProperty("customer_id") final String customerId, - @JsonProperty("url") final URI url + @JsonProperty("customer_id") final String customerId, + @JsonProperty("inquiry_id") final String inquiryId, + @JsonProperty("inquiry_session_token") final String inquirySessionToken, + @JsonProperty("url") final URI url ) { + this.customerId = customerId; this.inquiryId = inquiryId; this.inquirySessionToken = inquirySessionToken; - this.customerId = customerId; this.url = url; } - public final String getInquiryId() { - return this.inquiryId; - } - - public final String getInquirySessionToken() { - return this.inquirySessionToken; - } - - public final String getCustomerId() { - return this.customerId; - } - - public final URI getUrl() { - return this.url; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -140,17 +134,24 @@ public boolean equals(final Object o) { } ComplianceInquiries other = (ComplianceInquiries) o; - return ( - Objects.equals(inquiryId, other.inquiryId) && - Objects.equals(inquirySessionToken, other.inquirySessionToken) && - Objects.equals(customerId, other.customerId) && - Objects.equals(url, other.url) + Objects.equals(customerId, other.customerId) && + Objects.equals(inquiryId, other.inquiryId) && + Objects.equals(inquirySessionToken, other.inquirySessionToken) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { - return Objects.hash(inquiryId, inquirySessionToken, customerId, url); + return Objects.hash( + customerId, + inquiryId, + inquirySessionToken, + url + ); } + + } + diff --git a/src/main/java/com/twilio/rest/trusthub/v1/ComplianceInquiriesCreator.java b/src/main/java/com/twilio/rest/trusthub/v1/ComplianceInquiriesCreator.java index d6d8cc535f..2cf19a5d9b 100644 --- a/src/main/java/com/twilio/rest/trusthub/v1/ComplianceInquiriesCreator.java +++ b/src/main/java/com/twilio/rest/trusthub/v1/ComplianceInquiriesCreator.java @@ -14,8 +14,11 @@ package com.twilio.rest.trusthub.v1; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -35,76 +38,73 @@ public ComplianceInquiriesCreator(final String primaryProfileSid) { this.primaryProfileSid = primaryProfileSid; } - public ComplianceInquiriesCreator setPrimaryProfileSid( - final String primaryProfileSid - ) { + + public ComplianceInquiriesCreator setPrimaryProfileSid(final String primaryProfileSid) { this.primaryProfileSid = primaryProfileSid; return this; } - public ComplianceInquiriesCreator setNotificationEmail( - final String notificationEmail - ) { + + public ComplianceInquiriesCreator setNotificationEmail(final String notificationEmail) { this.notificationEmail = notificationEmail; return this; } + public ComplianceInquiriesCreator setThemeSetId(final String themeSetId) { this.themeSetId = themeSetId; return this; } + @Override public ComplianceInquiries create(final TwilioRestClient client) { + String path = "/v1/ComplianceInquiries/Customers/Initialize"; - path = - path.replace( - "{" + "PrimaryProfileSid" + "}", - this.primaryProfileSid.toString() - ); Request request = new Request( - HttpMethod.POST, - Domains.TRUSTHUB.toString(), - path + HttpMethod.POST, + Domains.TRUSTHUB.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "ComplianceInquiries creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("ComplianceInquiries creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return ComplianceInquiries.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return ComplianceInquiries.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (primaryProfileSid != null) { - request.addPostParam("PrimaryProfileSid", primaryProfileSid); + Serializer.toString(request, "PrimaryProfileSid", primaryProfileSid, ParameterType.URLENCODED); } + + if (notificationEmail != null) { - request.addPostParam("NotificationEmail", notificationEmail); + Serializer.toString(request, "NotificationEmail", notificationEmail, ParameterType.URLENCODED); } + + if (themeSetId != null) { - request.addPostParam("ThemeSetId", themeSetId); + Serializer.toString(request, "ThemeSetId", themeSetId, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/trusthub/v1/ComplianceInquiriesUpdater.java b/src/main/java/com/twilio/rest/trusthub/v1/ComplianceInquiriesUpdater.java index c370246c28..6643173198 100644 --- a/src/main/java/com/twilio/rest/trusthub/v1/ComplianceInquiriesUpdater.java +++ b/src/main/java/com/twilio/rest/trusthub/v1/ComplianceInquiriesUpdater.java @@ -16,6 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -26,85 +28,73 @@ import com.twilio.rest.Domains; public class ComplianceInquiriesUpdater extends Updater { - - private String pathCustomerId; + private String pathcustomerId; private String primaryProfileSid; private String themeSetId; - public ComplianceInquiriesUpdater( - final String pathCustomerId, - final String primaryProfileSid - ) { - this.pathCustomerId = pathCustomerId; + public ComplianceInquiriesUpdater(final String pathcustomerId, final String primaryProfileSid) { + this.pathcustomerId = pathcustomerId; this.primaryProfileSid = primaryProfileSid; } - public ComplianceInquiriesUpdater setPrimaryProfileSid( - final String primaryProfileSid - ) { + + public ComplianceInquiriesUpdater setPrimaryProfileSid(final String primaryProfileSid) { this.primaryProfileSid = primaryProfileSid; return this; } + public ComplianceInquiriesUpdater setThemeSetId(final String themeSetId) { this.themeSetId = themeSetId; return this; } + @Override public ComplianceInquiries update(final TwilioRestClient client) { - String path = - "/v1/ComplianceInquiries/Customers/{CustomerId}/Initialize"; - path = - path.replace( - "{" + "CustomerId" + "}", - this.pathCustomerId.toString() - ); - path = - path.replace( - "{" + "PrimaryProfileSid" + "}", - this.primaryProfileSid.toString() - ); + String path = "/v1/ComplianceInquiries/Customers/{CustomerId}/Initialize"; + + path = path.replace("{" + "CustomerId" + "}", this.pathcustomerId.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.TRUSTHUB.toString(), - path + HttpMethod.POST, + Domains.TRUSTHUB.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "ComplianceInquiries update failed: Unable to connect to server" - ); + throw new ApiConnectionException("ComplianceInquiries update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return ComplianceInquiries.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return ComplianceInquiries.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (primaryProfileSid != null) { - request.addPostParam("PrimaryProfileSid", primaryProfileSid); + Serializer.toString(request, "PrimaryProfileSid", primaryProfileSid, ParameterType.URLENCODED); } + + if (themeSetId != null) { - request.addPostParam("ThemeSetId", themeSetId); + Serializer.toString(request, "ThemeSetId", themeSetId, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/trusthub/v1/ComplianceRegistrationInquiries.java b/src/main/java/com/twilio/rest/trusthub/v1/ComplianceRegistrationInquiries.java index b633de24f7..359534373a 100644 --- a/src/main/java/com/twilio/rest/trusthub/v1/ComplianceRegistrationInquiries.java +++ b/src/main/java/com/twilio/rest/trusthub/v1/ComplianceRegistrationInquiries.java @@ -18,153 +18,58 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class ComplianceRegistrationInquiries extends Resource { - private static final long serialVersionUID = 153862952025802L; - public static ComplianceRegistrationInquiriesCreator creator( - final ComplianceRegistrationInquiries.EndUserType endUserType, - final ComplianceRegistrationInquiries.PhoneNumberType phoneNumberType - ) { + public static ComplianceRegistrationInquiriesCreator creator(final ComplianceRegistrationInquiries.EndUserType endUserType, final ComplianceRegistrationInquiries.PhoneNumberType phoneNumberType) { return new ComplianceRegistrationInquiriesCreator( - endUserType, - phoneNumberType + endUserType, phoneNumberType ); } - public static ComplianceRegistrationInquiriesUpdater updater( - final String pathRegistrationId - ) { - return new ComplianceRegistrationInquiriesUpdater(pathRegistrationId); - } - /** - * Converts a JSON String into a ComplianceRegistrationInquiries object using the provided ObjectMapper. - * - * @param json Raw JSON String - * @param objectMapper Jackson ObjectMapper - * @return ComplianceRegistrationInquiries object represented by the provided JSON - */ - public static ComplianceRegistrationInquiries fromJson( - final String json, - final ObjectMapper objectMapper - ) { - // Convert all checked exceptions to Runtime - try { - return objectMapper.readValue( - json, - ComplianceRegistrationInquiries.class - ); - } catch (final JsonMappingException | JsonParseException e) { - throw new ApiException(e.getMessage(), e); - } catch (final IOException e) { - throw new ApiConnectionException(e.getMessage(), e); - } - } - - /** - * Converts a JSON InputStream into a ComplianceRegistrationInquiries object using the provided - * ObjectMapper. - * - * @param json Raw JSON InputStream - * @param objectMapper Jackson ObjectMapper - * @return ComplianceRegistrationInquiries object represented by the provided JSON - */ - public static ComplianceRegistrationInquiries fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { - // Convert all checked exceptions to Runtime - try { - return objectMapper.readValue( - json, - ComplianceRegistrationInquiries.class - ); - } catch (final JsonMappingException | JsonParseException e) { - throw new ApiException(e.getMessage(), e); - } catch (final IOException e) { - throw new ApiConnectionException(e.getMessage(), e); - } - } - - private final String inquiryId; - private final String inquirySessionToken; - private final String registrationId; - private final URI url; - - @JsonCreator - private ComplianceRegistrationInquiries( - @JsonProperty("inquiry_id") final String inquiryId, - @JsonProperty("inquiry_session_token") final String inquirySessionToken, - @JsonProperty("registration_id") final String registrationId, - @JsonProperty("url") final URI url - ) { - this.inquiryId = inquiryId; - this.inquirySessionToken = inquirySessionToken; - this.registrationId = registrationId; - this.url = url; - } - - public final String getInquiryId() { - return this.inquiryId; + public static ComplianceRegistrationInquiriesUpdater updater(final String pathregistrationId) { + return new ComplianceRegistrationInquiriesUpdater( + pathregistrationId + ); } - public final String getInquirySessionToken() { - return this.inquirySessionToken; - } - public final String getRegistrationId() { - return this.registrationId; - } + public enum EndUserType { + INDIVIDUAL("Individual"), + BUSINESS("Business"); - public final URI getUrl() { - return this.url; - } + private final String value; - @Override - public boolean equals(final Object o) { - if (this == o) { - return true; + private EndUserType(final String value) { + this.value = value; } - if (o == null || getClass() != o.getClass()) { - return false; + public String toString() { + return value; } - ComplianceRegistrationInquiries other = - (ComplianceRegistrationInquiries) o; - - return ( - Objects.equals(inquiryId, other.inquiryId) && - Objects.equals(inquirySessionToken, other.inquirySessionToken) && - Objects.equals(registrationId, other.registrationId) && - Objects.equals(url, other.url) - ); - } - - @Override - public int hashCode() { - return Objects.hash( - inquiryId, - inquirySessionToken, - registrationId, - url - ); + @JsonCreator + public static EndUserType forValue(final String value) { + return Promoter.enumFromString(value, EndUserType.values()); + } } public enum BusinessIdentityType { @@ -184,10 +89,30 @@ public String toString() { @JsonCreator public static BusinessIdentityType forValue(final String value) { - return Promoter.enumFromString( - value, - BusinessIdentityType.values() - ); + return Promoter.enumFromString(value, BusinessIdentityType.values()); + } + } + + public enum BusinessRegistrationAuthority { + UK_CRN("UK:CRN"), + US_EIN("US:EIN"), + CA_CBN("CA:CBN"), + AU_ACN("AU:ACN"), + OTHER("Other"); + + private final String value; + + private BusinessRegistrationAuthority(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static BusinessRegistrationAuthority forValue(final String value) { + return Promoter.enumFromString(value, BusinessRegistrationAuthority.values()); } } @@ -213,51 +138,108 @@ public static PhoneNumberType forValue(final String value) { } } - public enum BusinessRegistrationAuthority { - UK_CRN("UK:CRN"), - US_EIN("US:EIN"), - CA_CBN("CA:CBN"), - AU_ACN("AU:ACN"), - OTHER("Other"); - - private final String value; - private BusinessRegistrationAuthority(final String value) { - this.value = value; + /** + * Converts a JSON String into a ComplianceRegistrationInquiries object using the provided ObjectMapper. + * + * @param json Raw JSON String + * @param objectMapper Jackson ObjectMapper + * @return ComplianceRegistrationInquiries object represented by the provided JSON + */ + public static ComplianceRegistrationInquiries fromJson(final String json, final ObjectMapper objectMapper) { + // Convert all checked exceptions to Runtime + try { + return objectMapper.readValue(json, ComplianceRegistrationInquiries.class); + } catch (final JsonMappingException | JsonParseException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); } + } - public String toString() { - return value; + /** + * Converts a JSON InputStream into a ComplianceRegistrationInquiries object using the provided + * ObjectMapper. + * + * @param json Raw JSON InputStream + * @param objectMapper Jackson ObjectMapper + * @return ComplianceRegistrationInquiries object represented by the provided JSON + */ + public static ComplianceRegistrationInquiries fromJson(final InputStream json, final ObjectMapper objectMapper) { + // Convert all checked exceptions to Runtime + try { + return objectMapper.readValue(json, ComplianceRegistrationInquiries.class); + } catch (final JsonMappingException | JsonParseException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); } + } - @JsonCreator - public static BusinessRegistrationAuthority forValue( - final String value - ) { - return Promoter.enumFromString( - value, - BusinessRegistrationAuthority.values() - ); + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); } } - public enum EndUserType { - INDIVIDUAL("Individual"), - BUSINESS("Business"); - private final String value; + @Getter + private final String inquiryId; + @Getter + private final String inquirySessionToken; + @Getter + private final String registrationId; + @Getter + private final URI url; - private EndUserType(final String value) { - this.value = value; - } + @JsonCreator + private ComplianceRegistrationInquiries( + @JsonProperty("inquiry_id") final String inquiryId, + @JsonProperty("inquiry_session_token") final String inquirySessionToken, + @JsonProperty("registration_id") final String registrationId, + @JsonProperty("url") final URI url + ) { + this.inquiryId = inquiryId; + this.inquirySessionToken = inquirySessionToken; + this.registrationId = registrationId; + this.url = url; + } - public String toString() { - return value; + @Override + public boolean equals(final Object o) { + if (this == o) { + return true; } - @JsonCreator - public static EndUserType forValue(final String value) { - return Promoter.enumFromString(value, EndUserType.values()); + if (o == null || getClass() != o.getClass()) { + return false; } + + ComplianceRegistrationInquiries other = (ComplianceRegistrationInquiries) o; + return ( + Objects.equals(inquiryId, other.inquiryId) && + Objects.equals(inquirySessionToken, other.inquirySessionToken) && + Objects.equals(registrationId, other.registrationId) && + Objects.equals(url, other.url) + ); + } + + @Override + public int hashCode() { + return Objects.hash( + inquiryId, + inquirySessionToken, + registrationId, + url + ); } + + } + diff --git a/src/main/java/com/twilio/rest/trusthub/v1/ComplianceRegistrationInquiriesCreator.java b/src/main/java/com/twilio/rest/trusthub/v1/ComplianceRegistrationInquiriesCreator.java index a57d8d80bd..14d7ccc252 100644 --- a/src/main/java/com/twilio/rest/trusthub/v1/ComplianceRegistrationInquiriesCreator.java +++ b/src/main/java/com/twilio/rest/trusthub/v1/ComplianceRegistrationInquiriesCreator.java @@ -14,8 +14,11 @@ package com.twilio.rest.trusthub.v1; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,8 +28,7 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class ComplianceRegistrationInquiriesCreator - extends Creator { +public class ComplianceRegistrationInquiriesCreator extends Creator { private ComplianceRegistrationInquiries.EndUserType endUserType; private ComplianceRegistrationInquiries.PhoneNumberType phoneNumberType; @@ -68,506 +70,474 @@ public class ComplianceRegistrationInquiriesCreator private String statusCallbackUrl; private String themeSetId; - public ComplianceRegistrationInquiriesCreator( - final ComplianceRegistrationInquiries.EndUserType endUserType, - final ComplianceRegistrationInquiries.PhoneNumberType phoneNumberType - ) { + public ComplianceRegistrationInquiriesCreator(final ComplianceRegistrationInquiries.EndUserType endUserType, final ComplianceRegistrationInquiries.PhoneNumberType phoneNumberType) { this.endUserType = endUserType; this.phoneNumberType = phoneNumberType; } - public ComplianceRegistrationInquiriesCreator setEndUserType( - final ComplianceRegistrationInquiries.EndUserType endUserType - ) { + + public ComplianceRegistrationInquiriesCreator setEndUserType(final ComplianceRegistrationInquiries.EndUserType endUserType) { this.endUserType = endUserType; return this; } - public ComplianceRegistrationInquiriesCreator setPhoneNumberType( - final ComplianceRegistrationInquiries.PhoneNumberType phoneNumberType - ) { + + public ComplianceRegistrationInquiriesCreator setPhoneNumberType(final ComplianceRegistrationInquiries.PhoneNumberType phoneNumberType) { this.phoneNumberType = phoneNumberType; return this; } - public ComplianceRegistrationInquiriesCreator setBusinessIdentityType( - final ComplianceRegistrationInquiries.BusinessIdentityType businessIdentityType - ) { + + public ComplianceRegistrationInquiriesCreator setBusinessIdentityType(final ComplianceRegistrationInquiries.BusinessIdentityType businessIdentityType) { this.businessIdentityType = businessIdentityType; return this; } - public ComplianceRegistrationInquiriesCreator setBusinessRegistrationAuthority( - final ComplianceRegistrationInquiries.BusinessRegistrationAuthority businessRegistrationAuthority - ) { + + public ComplianceRegistrationInquiriesCreator setBusinessRegistrationAuthority(final ComplianceRegistrationInquiries.BusinessRegistrationAuthority businessRegistrationAuthority) { this.businessRegistrationAuthority = businessRegistrationAuthority; return this; } - public ComplianceRegistrationInquiriesCreator setBusinessLegalName( - final String businessLegalName - ) { + + public ComplianceRegistrationInquiriesCreator setBusinessLegalName(final String businessLegalName) { this.businessLegalName = businessLegalName; return this; } - public ComplianceRegistrationInquiriesCreator setNotificationEmail( - final String notificationEmail - ) { + + public ComplianceRegistrationInquiriesCreator setNotificationEmail(final String notificationEmail) { this.notificationEmail = notificationEmail; return this; } - public ComplianceRegistrationInquiriesCreator setAcceptedNotificationReceipt( - final Boolean acceptedNotificationReceipt - ) { + + public ComplianceRegistrationInquiriesCreator setAcceptedNotificationReceipt(final Boolean acceptedNotificationReceipt) { this.acceptedNotificationReceipt = acceptedNotificationReceipt; return this; } - public ComplianceRegistrationInquiriesCreator setBusinessRegistrationNumber( - final String businessRegistrationNumber - ) { + + public ComplianceRegistrationInquiriesCreator setBusinessRegistrationNumber(final String businessRegistrationNumber) { this.businessRegistrationNumber = businessRegistrationNumber; return this; } - public ComplianceRegistrationInquiriesCreator setBusinessWebsiteUrl( - final String businessWebsiteUrl - ) { + + public ComplianceRegistrationInquiriesCreator setBusinessWebsiteUrl(final String businessWebsiteUrl) { this.businessWebsiteUrl = businessWebsiteUrl; return this; } - public ComplianceRegistrationInquiriesCreator setFriendlyName( - final String friendlyName - ) { + + public ComplianceRegistrationInquiriesCreator setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } - public ComplianceRegistrationInquiriesCreator setAuthorizedRepresentative1FirstName( - final String authorizedRepresentative1FirstName - ) { - this.authorizedRepresentative1FirstName = - authorizedRepresentative1FirstName; + + public ComplianceRegistrationInquiriesCreator setAuthorizedRepresentative1FirstName(final String authorizedRepresentative1FirstName) { + this.authorizedRepresentative1FirstName = authorizedRepresentative1FirstName; return this; } - public ComplianceRegistrationInquiriesCreator setAuthorizedRepresentative1LastName( - final String authorizedRepresentative1LastName - ) { - this.authorizedRepresentative1LastName = - authorizedRepresentative1LastName; + + public ComplianceRegistrationInquiriesCreator setAuthorizedRepresentative1LastName(final String authorizedRepresentative1LastName) { + this.authorizedRepresentative1LastName = authorizedRepresentative1LastName; return this; } - public ComplianceRegistrationInquiriesCreator setAuthorizedRepresentative1Phone( - final String authorizedRepresentative1Phone - ) { + + public ComplianceRegistrationInquiriesCreator setAuthorizedRepresentative1Phone(final String authorizedRepresentative1Phone) { this.authorizedRepresentative1Phone = authorizedRepresentative1Phone; return this; } - public ComplianceRegistrationInquiriesCreator setAuthorizedRepresentative1Email( - final String authorizedRepresentative1Email - ) { + + public ComplianceRegistrationInquiriesCreator setAuthorizedRepresentative1Email(final String authorizedRepresentative1Email) { this.authorizedRepresentative1Email = authorizedRepresentative1Email; return this; } - public ComplianceRegistrationInquiriesCreator setAuthorizedRepresentative1DateOfBirth( - final String authorizedRepresentative1DateOfBirth - ) { - this.authorizedRepresentative1DateOfBirth = - authorizedRepresentative1DateOfBirth; + + public ComplianceRegistrationInquiriesCreator setAuthorizedRepresentative1DateOfBirth(final String authorizedRepresentative1DateOfBirth) { + this.authorizedRepresentative1DateOfBirth = authorizedRepresentative1DateOfBirth; return this; } - public ComplianceRegistrationInquiriesCreator setAddressStreet( - final String addressStreet - ) { + + public ComplianceRegistrationInquiriesCreator setAddressStreet(final String addressStreet) { this.addressStreet = addressStreet; return this; } - public ComplianceRegistrationInquiriesCreator setAddressStreetSecondary( - final String addressStreetSecondary - ) { + + public ComplianceRegistrationInquiriesCreator setAddressStreetSecondary(final String addressStreetSecondary) { this.addressStreetSecondary = addressStreetSecondary; return this; } - public ComplianceRegistrationInquiriesCreator setAddressCity( - final String addressCity - ) { + + public ComplianceRegistrationInquiriesCreator setAddressCity(final String addressCity) { this.addressCity = addressCity; return this; } - public ComplianceRegistrationInquiriesCreator setAddressSubdivision( - final String addressSubdivision - ) { + + public ComplianceRegistrationInquiriesCreator setAddressSubdivision(final String addressSubdivision) { this.addressSubdivision = addressSubdivision; return this; } - public ComplianceRegistrationInquiriesCreator setAddressPostalCode( - final String addressPostalCode - ) { + + public ComplianceRegistrationInquiriesCreator setAddressPostalCode(final String addressPostalCode) { this.addressPostalCode = addressPostalCode; return this; } - public ComplianceRegistrationInquiriesCreator setAddressCountryCode( - final String addressCountryCode - ) { + + public ComplianceRegistrationInquiriesCreator setAddressCountryCode(final String addressCountryCode) { this.addressCountryCode = addressCountryCode; return this; } - public ComplianceRegistrationInquiriesCreator setEmergencyAddressStreet( - final String emergencyAddressStreet - ) { + + public ComplianceRegistrationInquiriesCreator setEmergencyAddressStreet(final String emergencyAddressStreet) { this.emergencyAddressStreet = emergencyAddressStreet; return this; } - public ComplianceRegistrationInquiriesCreator setEmergencyAddressStreetSecondary( - final String emergencyAddressStreetSecondary - ) { + + public ComplianceRegistrationInquiriesCreator setEmergencyAddressStreetSecondary(final String emergencyAddressStreetSecondary) { this.emergencyAddressStreetSecondary = emergencyAddressStreetSecondary; return this; } - public ComplianceRegistrationInquiriesCreator setEmergencyAddressCity( - final String emergencyAddressCity - ) { + + public ComplianceRegistrationInquiriesCreator setEmergencyAddressCity(final String emergencyAddressCity) { this.emergencyAddressCity = emergencyAddressCity; return this; } - public ComplianceRegistrationInquiriesCreator setEmergencyAddressSubdivision( - final String emergencyAddressSubdivision - ) { + + public ComplianceRegistrationInquiriesCreator setEmergencyAddressSubdivision(final String emergencyAddressSubdivision) { this.emergencyAddressSubdivision = emergencyAddressSubdivision; return this; } - public ComplianceRegistrationInquiriesCreator setEmergencyAddressPostalCode( - final String emergencyAddressPostalCode - ) { + + public ComplianceRegistrationInquiriesCreator setEmergencyAddressPostalCode(final String emergencyAddressPostalCode) { this.emergencyAddressPostalCode = emergencyAddressPostalCode; return this; } - public ComplianceRegistrationInquiriesCreator setEmergencyAddressCountryCode( - final String emergencyAddressCountryCode - ) { + + public ComplianceRegistrationInquiriesCreator setEmergencyAddressCountryCode(final String emergencyAddressCountryCode) { this.emergencyAddressCountryCode = emergencyAddressCountryCode; return this; } - public ComplianceRegistrationInquiriesCreator setUseAddressAsEmergencyAddress( - final Boolean useAddressAsEmergencyAddress - ) { + + public ComplianceRegistrationInquiriesCreator setUseAddressAsEmergencyAddress(final Boolean useAddressAsEmergencyAddress) { this.useAddressAsEmergencyAddress = useAddressAsEmergencyAddress; return this; } - public ComplianceRegistrationInquiriesCreator setFileName( - final String fileName - ) { + + public ComplianceRegistrationInquiriesCreator setFileName(final String fileName) { this.fileName = fileName; return this; } + public ComplianceRegistrationInquiriesCreator set_file(final String _file) { this._file = _file; return this; } - public ComplianceRegistrationInquiriesCreator setFirstName( - final String firstName - ) { + + public ComplianceRegistrationInquiriesCreator setFirstName(final String firstName) { this.firstName = firstName; return this; } - public ComplianceRegistrationInquiriesCreator setLastName( - final String lastName - ) { + + public ComplianceRegistrationInquiriesCreator setLastName(final String lastName) { this.lastName = lastName; return this; } - public ComplianceRegistrationInquiriesCreator setDateOfBirth( - final String dateOfBirth - ) { + + public ComplianceRegistrationInquiriesCreator setDateOfBirth(final String dateOfBirth) { this.dateOfBirth = dateOfBirth; return this; } - public ComplianceRegistrationInquiriesCreator setIndividualEmail( - final String individualEmail - ) { + + public ComplianceRegistrationInquiriesCreator setIndividualEmail(final String individualEmail) { this.individualEmail = individualEmail; return this; } - public ComplianceRegistrationInquiriesCreator setIndividualPhone( - final String individualPhone - ) { + + public ComplianceRegistrationInquiriesCreator setIndividualPhone(final String individualPhone) { this.individualPhone = individualPhone; return this; } - public ComplianceRegistrationInquiriesCreator setIsIsvEmbed( - final Boolean isIsvEmbed - ) { + + public ComplianceRegistrationInquiriesCreator setIsIsvEmbed(final Boolean isIsvEmbed) { this.isIsvEmbed = isIsvEmbed; return this; } - public ComplianceRegistrationInquiriesCreator setIsvRegisteringForSelfOrTenant( - final String isvRegisteringForSelfOrTenant - ) { + + public ComplianceRegistrationInquiriesCreator setIsvRegisteringForSelfOrTenant(final String isvRegisteringForSelfOrTenant) { this.isvRegisteringForSelfOrTenant = isvRegisteringForSelfOrTenant; return this; } - public ComplianceRegistrationInquiriesCreator setStatusCallbackUrl( - final String statusCallbackUrl - ) { + + public ComplianceRegistrationInquiriesCreator setStatusCallbackUrl(final String statusCallbackUrl) { this.statusCallbackUrl = statusCallbackUrl; return this; } - public ComplianceRegistrationInquiriesCreator setThemeSetId( - final String themeSetId - ) { + + public ComplianceRegistrationInquiriesCreator setThemeSetId(final String themeSetId) { this.themeSetId = themeSetId; return this; } + @Override - public ComplianceRegistrationInquiries create( - final TwilioRestClient client - ) { - String path = - "/v1/ComplianceInquiries/Registration/RegulatoryCompliance/GB/Initialize"; - - path = - path.replace( - "{" + "EndUserType" + "}", - this.endUserType.toString() - ); - path = - path.replace( - "{" + "PhoneNumberType" + "}", - this.phoneNumberType.toString() - ); + public ComplianceRegistrationInquiries create(final TwilioRestClient client) { + + String path = "/v1/ComplianceInquiries/Registration/RegulatoryCompliance/GB/Initialize"; + Request request = new Request( - HttpMethod.POST, - Domains.TRUSTHUB.toString(), - path + HttpMethod.POST, + Domains.TRUSTHUB.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "ComplianceRegistrationInquiries creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("ComplianceRegistrationInquiries creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return ComplianceRegistrationInquiries.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return ComplianceRegistrationInquiries.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (endUserType != null) { - request.addPostParam("EndUserType", endUserType.toString()); + Serializer.toString(request, "EndUserType", endUserType, ParameterType.URLENCODED); } + + if (phoneNumberType != null) { - request.addPostParam("PhoneNumberType", phoneNumberType.toString()); + Serializer.toString(request, "PhoneNumberType", phoneNumberType, ParameterType.URLENCODED); } + + if (businessIdentityType != null) { - request.addPostParam( - "BusinessIdentityType", - businessIdentityType.toString() - ); + Serializer.toString(request, "BusinessIdentityType", businessIdentityType, ParameterType.URLENCODED); } + + if (businessRegistrationAuthority != null) { - request.addPostParam( - "BusinessRegistrationAuthority", - businessRegistrationAuthority.toString() - ); + Serializer.toString(request, "BusinessRegistrationAuthority", businessRegistrationAuthority, ParameterType.URLENCODED); } + + if (businessLegalName != null) { - request.addPostParam("BusinessLegalName", businessLegalName); + Serializer.toString(request, "BusinessLegalName", businessLegalName, ParameterType.URLENCODED); } + + if (notificationEmail != null) { - request.addPostParam("NotificationEmail", notificationEmail); + Serializer.toString(request, "NotificationEmail", notificationEmail, ParameterType.URLENCODED); } + + if (acceptedNotificationReceipt != null) { - request.addPostParam( - "AcceptedNotificationReceipt", - acceptedNotificationReceipt.toString() - ); + Serializer.toString(request, "AcceptedNotificationReceipt", acceptedNotificationReceipt, ParameterType.URLENCODED); } + + if (businessRegistrationNumber != null) { - request.addPostParam( - "BusinessRegistrationNumber", - businessRegistrationNumber - ); + Serializer.toString(request, "BusinessRegistrationNumber", businessRegistrationNumber, ParameterType.URLENCODED); } + + if (businessWebsiteUrl != null) { - request.addPostParam("BusinessWebsiteUrl", businessWebsiteUrl); + Serializer.toString(request, "BusinessWebsiteUrl", businessWebsiteUrl, ParameterType.URLENCODED); } + + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + if (authorizedRepresentative1FirstName != null) { - request.addPostParam( - "AuthorizedRepresentative1FirstName", - authorizedRepresentative1FirstName - ); + Serializer.toString(request, "AuthorizedRepresentative1FirstName", authorizedRepresentative1FirstName, ParameterType.URLENCODED); } + + if (authorizedRepresentative1LastName != null) { - request.addPostParam( - "AuthorizedRepresentative1LastName", - authorizedRepresentative1LastName - ); + Serializer.toString(request, "AuthorizedRepresentative1LastName", authorizedRepresentative1LastName, ParameterType.URLENCODED); } + + if (authorizedRepresentative1Phone != null) { - request.addPostParam( - "AuthorizedRepresentative1Phone", - authorizedRepresentative1Phone - ); + Serializer.toString(request, "AuthorizedRepresentative1Phone", authorizedRepresentative1Phone, ParameterType.URLENCODED); } + + if (authorizedRepresentative1Email != null) { - request.addPostParam( - "AuthorizedRepresentative1Email", - authorizedRepresentative1Email - ); + Serializer.toString(request, "AuthorizedRepresentative1Email", authorizedRepresentative1Email, ParameterType.URLENCODED); } + + if (authorizedRepresentative1DateOfBirth != null) { - request.addPostParam( - "AuthorizedRepresentative1DateOfBirth", - authorizedRepresentative1DateOfBirth - ); + Serializer.toString(request, "AuthorizedRepresentative1DateOfBirth", authorizedRepresentative1DateOfBirth, ParameterType.URLENCODED); } + + if (addressStreet != null) { - request.addPostParam("AddressStreet", addressStreet); + Serializer.toString(request, "AddressStreet", addressStreet, ParameterType.URLENCODED); } + + if (addressStreetSecondary != null) { - request.addPostParam( - "AddressStreetSecondary", - addressStreetSecondary - ); + Serializer.toString(request, "AddressStreetSecondary", addressStreetSecondary, ParameterType.URLENCODED); } + + if (addressCity != null) { - request.addPostParam("AddressCity", addressCity); + Serializer.toString(request, "AddressCity", addressCity, ParameterType.URLENCODED); } + + if (addressSubdivision != null) { - request.addPostParam("AddressSubdivision", addressSubdivision); + Serializer.toString(request, "AddressSubdivision", addressSubdivision, ParameterType.URLENCODED); } + + if (addressPostalCode != null) { - request.addPostParam("AddressPostalCode", addressPostalCode); + Serializer.toString(request, "AddressPostalCode", addressPostalCode, ParameterType.URLENCODED); } + + if (addressCountryCode != null) { - request.addPostParam("AddressCountryCode", addressCountryCode); + Serializer.toString(request, "AddressCountryCode", addressCountryCode, ParameterType.URLENCODED); } + + if (emergencyAddressStreet != null) { - request.addPostParam( - "EmergencyAddressStreet", - emergencyAddressStreet - ); + Serializer.toString(request, "EmergencyAddressStreet", emergencyAddressStreet, ParameterType.URLENCODED); } + + if (emergencyAddressStreetSecondary != null) { - request.addPostParam( - "EmergencyAddressStreetSecondary", - emergencyAddressStreetSecondary - ); + Serializer.toString(request, "EmergencyAddressStreetSecondary", emergencyAddressStreetSecondary, ParameterType.URLENCODED); } + + if (emergencyAddressCity != null) { - request.addPostParam("EmergencyAddressCity", emergencyAddressCity); + Serializer.toString(request, "EmergencyAddressCity", emergencyAddressCity, ParameterType.URLENCODED); } + + if (emergencyAddressSubdivision != null) { - request.addPostParam( - "EmergencyAddressSubdivision", - emergencyAddressSubdivision - ); + Serializer.toString(request, "EmergencyAddressSubdivision", emergencyAddressSubdivision, ParameterType.URLENCODED); } + + if (emergencyAddressPostalCode != null) { - request.addPostParam( - "EmergencyAddressPostalCode", - emergencyAddressPostalCode - ); + Serializer.toString(request, "EmergencyAddressPostalCode", emergencyAddressPostalCode, ParameterType.URLENCODED); } + + if (emergencyAddressCountryCode != null) { - request.addPostParam( - "EmergencyAddressCountryCode", - emergencyAddressCountryCode - ); + Serializer.toString(request, "EmergencyAddressCountryCode", emergencyAddressCountryCode, ParameterType.URLENCODED); } + + if (useAddressAsEmergencyAddress != null) { - request.addPostParam( - "UseAddressAsEmergencyAddress", - useAddressAsEmergencyAddress.toString() - ); + Serializer.toString(request, "UseAddressAsEmergencyAddress", useAddressAsEmergencyAddress, ParameterType.URLENCODED); } + + if (fileName != null) { - request.addPostParam("FileName", fileName); + Serializer.toString(request, "FileName", fileName, ParameterType.URLENCODED); } + + if (_file != null) { - request.addPostParam("File", _file); + Serializer.toString(request, "File", _file, ParameterType.URLENCODED); } + + if (firstName != null) { - request.addPostParam("FirstName", firstName); + Serializer.toString(request, "FirstName", firstName, ParameterType.URLENCODED); } + + if (lastName != null) { - request.addPostParam("LastName", lastName); + Serializer.toString(request, "LastName", lastName, ParameterType.URLENCODED); } + + if (dateOfBirth != null) { - request.addPostParam("DateOfBirth", dateOfBirth); + Serializer.toString(request, "DateOfBirth", dateOfBirth, ParameterType.URLENCODED); } + + if (individualEmail != null) { - request.addPostParam("IndividualEmail", individualEmail); + Serializer.toString(request, "IndividualEmail", individualEmail, ParameterType.URLENCODED); } + + if (individualPhone != null) { - request.addPostParam("IndividualPhone", individualPhone); + Serializer.toString(request, "IndividualPhone", individualPhone, ParameterType.URLENCODED); } + + if (isIsvEmbed != null) { - request.addPostParam("IsIsvEmbed", isIsvEmbed.toString()); + Serializer.toString(request, "IsIsvEmbed", isIsvEmbed, ParameterType.URLENCODED); } + + if (isvRegisteringForSelfOrTenant != null) { - request.addPostParam( - "IsvRegisteringForSelfOrTenant", - isvRegisteringForSelfOrTenant - ); + Serializer.toString(request, "IsvRegisteringForSelfOrTenant", isvRegisteringForSelfOrTenant, ParameterType.URLENCODED); } + + if (statusCallbackUrl != null) { - request.addPostParam("StatusCallbackUrl", statusCallbackUrl); + Serializer.toString(request, "StatusCallbackUrl", statusCallbackUrl, ParameterType.URLENCODED); } + + if (themeSetId != null) { - request.addPostParam("ThemeSetId", themeSetId); + Serializer.toString(request, "ThemeSetId", themeSetId, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/trusthub/v1/ComplianceRegistrationInquiriesUpdater.java b/src/main/java/com/twilio/rest/trusthub/v1/ComplianceRegistrationInquiriesUpdater.java index b7c30b0b9f..e863d298b0 100644 --- a/src/main/java/com/twilio/rest/trusthub/v1/ComplianceRegistrationInquiriesUpdater.java +++ b/src/main/java/com/twilio/rest/trusthub/v1/ComplianceRegistrationInquiriesUpdater.java @@ -16,6 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,84 +27,73 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class ComplianceRegistrationInquiriesUpdater - extends Updater { - - private String pathRegistrationId; +public class ComplianceRegistrationInquiriesUpdater extends Updater { + private String pathregistrationId; private Boolean isIsvEmbed; private String themeSetId; - public ComplianceRegistrationInquiriesUpdater( - final String pathRegistrationId - ) { - this.pathRegistrationId = pathRegistrationId; + public ComplianceRegistrationInquiriesUpdater(final String pathregistrationId) { + this.pathregistrationId = pathregistrationId; } - public ComplianceRegistrationInquiriesUpdater setIsIsvEmbed( - final Boolean isIsvEmbed - ) { + + public ComplianceRegistrationInquiriesUpdater setIsIsvEmbed(final Boolean isIsvEmbed) { this.isIsvEmbed = isIsvEmbed; return this; } - public ComplianceRegistrationInquiriesUpdater setThemeSetId( - final String themeSetId - ) { + + public ComplianceRegistrationInquiriesUpdater setThemeSetId(final String themeSetId) { this.themeSetId = themeSetId; return this; } + @Override - public ComplianceRegistrationInquiries update( - final TwilioRestClient client - ) { - String path = - "/v1/ComplianceInquiries/Registration/{RegistrationId}/RegulatoryCompliance/GB/Initialize"; - - path = - path.replace( - "{" + "RegistrationId" + "}", - this.pathRegistrationId.toString() - ); + public ComplianceRegistrationInquiries update(final TwilioRestClient client) { + + String path = "/v1/ComplianceInquiries/Registration/{RegistrationId}/RegulatoryCompliance/GB/Initialize"; + + path = path.replace("{" + "RegistrationId" + "}", this.pathregistrationId.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.TRUSTHUB.toString(), - path + HttpMethod.POST, + Domains.TRUSTHUB.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "ComplianceRegistrationInquiries update failed: Unable to connect to server" - ); + throw new ApiConnectionException("ComplianceRegistrationInquiries update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return ComplianceRegistrationInquiries.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return ComplianceRegistrationInquiries.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (isIsvEmbed != null) { - request.addPostParam("IsIsvEmbed", isIsvEmbed.toString()); + Serializer.toString(request, "IsIsvEmbed", isIsvEmbed, ParameterType.URLENCODED); } + + if (themeSetId != null) { - request.addPostParam("ThemeSetId", themeSetId); + Serializer.toString(request, "ThemeSetId", themeSetId, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/trusthub/v1/ComplianceTollfreeInquiries.java b/src/main/java/com/twilio/rest/trusthub/v1/ComplianceTollfreeInquiries.java index 65685d79ad..a27a51d9c7 100644 --- a/src/main/java/com/twilio/rest/trusthub/v1/ComplianceTollfreeInquiries.java +++ b/src/main/java/com/twilio/rest/trusthub/v1/ComplianceTollfreeInquiries.java @@ -18,52 +18,68 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class ComplianceTollfreeInquiries extends Resource { - private static final long serialVersionUID = 153862952025802L; - public static ComplianceTollfreeInquiriesCreator creator( - final com.twilio.type.PhoneNumber tollfreePhoneNumber, - final String notificationEmail - ) { + public static ComplianceTollfreeInquiriesCreator creator(final com.twilio.type.PhoneNumber tollfreePhoneNumber, final String notificationEmail) { return new ComplianceTollfreeInquiriesCreator( - tollfreePhoneNumber, - notificationEmail + tollfreePhoneNumber, notificationEmail ); } + + public enum OptInType { + VERBAL("VERBAL"), + WEB_FORM("WEB_FORM"), + PAPER_FORM("PAPER_FORM"), + VIA_TEXT("VIA_TEXT"), + MOBILE_QR_CODE("MOBILE_QR_CODE"); + + private final String value; + + private OptInType(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static OptInType forValue(final String value) { + return Promoter.enumFromString(value, OptInType.values()); + } + } + + /** * Converts a JSON String into a ComplianceTollfreeInquiries object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return ComplianceTollfreeInquiries object represented by the provided JSON */ - public static ComplianceTollfreeInquiries fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static ComplianceTollfreeInquiries fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { - return objectMapper.readValue( - json, - ComplianceTollfreeInquiries.class - ); + return objectMapper.readValue(json, ComplianceTollfreeInquiries.class); } catch (final JsonMappingException | JsonParseException e) { throw new ApiException(e.getMessage(), e); } catch (final IOException e) { @@ -75,20 +91,14 @@ public static ComplianceTollfreeInquiries fromJson( * Converts a JSON InputStream into a ComplianceTollfreeInquiries object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return ComplianceTollfreeInquiries object represented by the provided JSON */ - public static ComplianceTollfreeInquiries fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static ComplianceTollfreeInquiries fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { - return objectMapper.readValue( - json, - ComplianceTollfreeInquiries.class - ); + return objectMapper.readValue(json, ComplianceTollfreeInquiries.class); } catch (final JsonMappingException | JsonParseException e) { throw new ApiException(e.getMessage(), e); } catch (final IOException e) { @@ -96,17 +106,34 @@ public static ComplianceTollfreeInquiries fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String inquiryId; + @Getter private final String inquirySessionToken; + @Getter private final String registrationId; + @Getter private final URI url; @JsonCreator private ComplianceTollfreeInquiries( - @JsonProperty("inquiry_id") final String inquiryId, - @JsonProperty("inquiry_session_token") final String inquirySessionToken, - @JsonProperty("registration_id") final String registrationId, - @JsonProperty("url") final URI url + @JsonProperty("inquiry_id") final String inquiryId, + @JsonProperty("inquiry_session_token") final String inquirySessionToken, + @JsonProperty("registration_id") final String registrationId, + @JsonProperty("url") final URI url ) { this.inquiryId = inquiryId; this.inquirySessionToken = inquirySessionToken; @@ -114,22 +141,6 @@ private ComplianceTollfreeInquiries( this.url = url; } - public final String getInquiryId() { - return this.inquiryId; - } - - public final String getInquirySessionToken() { - return this.inquirySessionToken; - } - - public final String getRegistrationId() { - return this.registrationId; - } - - public final URI getUrl() { - return this.url; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -141,45 +152,24 @@ public boolean equals(final Object o) { } ComplianceTollfreeInquiries other = (ComplianceTollfreeInquiries) o; - return ( - Objects.equals(inquiryId, other.inquiryId) && - Objects.equals(inquirySessionToken, other.inquirySessionToken) && - Objects.equals(registrationId, other.registrationId) && - Objects.equals(url, other.url) + Objects.equals(inquiryId, other.inquiryId) && + Objects.equals(inquirySessionToken, other.inquirySessionToken) && + Objects.equals(registrationId, other.registrationId) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - inquiryId, - inquirySessionToken, - registrationId, - url + inquiryId, + inquirySessionToken, + registrationId, + url ); } - public enum OptInType { - VERBAL("VERBAL"), - WEB_FORM("WEB_FORM"), - PAPER_FORM("PAPER_FORM"), - VIA_TEXT("VIA_TEXT"), - MOBILE_QR_CODE("MOBILE_QR_CODE"); - - private final String value; - - private OptInType(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - @JsonCreator - public static OptInType forValue(final String value) { - return Promoter.enumFromString(value, OptInType.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/trusthub/v1/ComplianceTollfreeInquiriesCreator.java b/src/main/java/com/twilio/rest/trusthub/v1/ComplianceTollfreeInquiriesCreator.java index a4413dc4c8..10e708ce20 100644 --- a/src/main/java/com/twilio/rest/trusthub/v1/ComplianceTollfreeInquiriesCreator.java +++ b/src/main/java/com/twilio/rest/trusthub/v1/ComplianceTollfreeInquiriesCreator.java @@ -14,9 +14,12 @@ package com.twilio.rest.trusthub.v1; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; import com.twilio.converter.Promoter; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,11 +28,10 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -import java.util.List; + import java.util.List; -public class ComplianceTollfreeInquiriesCreator - extends Creator { +public class ComplianceTollfreeInquiriesCreator extends Creator { private com.twilio.type.PhoneNumber tollfreePhoneNumber; private String notificationEmail; @@ -55,353 +57,314 @@ public class ComplianceTollfreeInquiriesCreator private String themeSetId; private Boolean skipMessagingUseCase; - public ComplianceTollfreeInquiriesCreator( - final com.twilio.type.PhoneNumber tollfreePhoneNumber, - final String notificationEmail - ) { + public ComplianceTollfreeInquiriesCreator(final com.twilio.type.PhoneNumber tollfreePhoneNumber, final String notificationEmail) { this.tollfreePhoneNumber = tollfreePhoneNumber; this.notificationEmail = notificationEmail; } - public ComplianceTollfreeInquiriesCreator setTollfreePhoneNumber( - final com.twilio.type.PhoneNumber tollfreePhoneNumber - ) { + + public ComplianceTollfreeInquiriesCreator setTollfreePhoneNumber(final com.twilio.type.PhoneNumber tollfreePhoneNumber) { this.tollfreePhoneNumber = tollfreePhoneNumber; return this; } - public ComplianceTollfreeInquiriesCreator setTollfreePhoneNumber( - final String tollfreePhoneNumber - ) { - return setTollfreePhoneNumber( - Promoter.phoneNumberFromString(tollfreePhoneNumber) - ); + public ComplianceTollfreeInquiriesCreator setTollfreePhoneNumber(final String tollfreePhoneNumber) { + return setTollfreePhoneNumber(Promoter.phoneNumberFromString(tollfreePhoneNumber)); } - public ComplianceTollfreeInquiriesCreator setNotificationEmail( - final String notificationEmail - ) { + public ComplianceTollfreeInquiriesCreator setNotificationEmail(final String notificationEmail) { this.notificationEmail = notificationEmail; return this; } - public ComplianceTollfreeInquiriesCreator setBusinessName( - final String businessName - ) { + + public ComplianceTollfreeInquiriesCreator setBusinessName(final String businessName) { this.businessName = businessName; return this; } - public ComplianceTollfreeInquiriesCreator setBusinessWebsite( - final String businessWebsite - ) { + + public ComplianceTollfreeInquiriesCreator setBusinessWebsite(final String businessWebsite) { this.businessWebsite = businessWebsite; return this; } - public ComplianceTollfreeInquiriesCreator setUseCaseCategories( - final List useCaseCategories - ) { + + public ComplianceTollfreeInquiriesCreator setUseCaseCategories(final List useCaseCategories) { this.useCaseCategories = useCaseCategories; return this; } - public ComplianceTollfreeInquiriesCreator setUseCaseCategories( - final String useCaseCategories - ) { + public ComplianceTollfreeInquiriesCreator setUseCaseCategories(final String useCaseCategories) { return setUseCaseCategories(Promoter.listOfOne(useCaseCategories)); } - public ComplianceTollfreeInquiriesCreator setUseCaseSummary( - final String useCaseSummary - ) { + public ComplianceTollfreeInquiriesCreator setUseCaseSummary(final String useCaseSummary) { this.useCaseSummary = useCaseSummary; return this; } - public ComplianceTollfreeInquiriesCreator setProductionMessageSample( - final String productionMessageSample - ) { + + public ComplianceTollfreeInquiriesCreator setProductionMessageSample(final String productionMessageSample) { this.productionMessageSample = productionMessageSample; return this; } - public ComplianceTollfreeInquiriesCreator setOptInImageUrls( - final List optInImageUrls - ) { + + public ComplianceTollfreeInquiriesCreator setOptInImageUrls(final List optInImageUrls) { this.optInImageUrls = optInImageUrls; return this; } - public ComplianceTollfreeInquiriesCreator setOptInImageUrls( - final String optInImageUrls - ) { + public ComplianceTollfreeInquiriesCreator setOptInImageUrls(final String optInImageUrls) { return setOptInImageUrls(Promoter.listOfOne(optInImageUrls)); } - public ComplianceTollfreeInquiriesCreator setOptInType( - final ComplianceTollfreeInquiries.OptInType optInType - ) { + public ComplianceTollfreeInquiriesCreator setOptInType(final ComplianceTollfreeInquiries.OptInType optInType) { this.optInType = optInType; return this; } - public ComplianceTollfreeInquiriesCreator setMessageVolume( - final String messageVolume - ) { + + public ComplianceTollfreeInquiriesCreator setMessageVolume(final String messageVolume) { this.messageVolume = messageVolume; return this; } - public ComplianceTollfreeInquiriesCreator setBusinessStreetAddress( - final String businessStreetAddress - ) { + + public ComplianceTollfreeInquiriesCreator setBusinessStreetAddress(final String businessStreetAddress) { this.businessStreetAddress = businessStreetAddress; return this; } - public ComplianceTollfreeInquiriesCreator setBusinessStreetAddress2( - final String businessStreetAddress2 - ) { + + public ComplianceTollfreeInquiriesCreator setBusinessStreetAddress2(final String businessStreetAddress2) { this.businessStreetAddress2 = businessStreetAddress2; return this; } - public ComplianceTollfreeInquiriesCreator setBusinessCity( - final String businessCity - ) { + + public ComplianceTollfreeInquiriesCreator setBusinessCity(final String businessCity) { this.businessCity = businessCity; return this; } - public ComplianceTollfreeInquiriesCreator setBusinessStateProvinceRegion( - final String businessStateProvinceRegion - ) { + + public ComplianceTollfreeInquiriesCreator setBusinessStateProvinceRegion(final String businessStateProvinceRegion) { this.businessStateProvinceRegion = businessStateProvinceRegion; return this; } - public ComplianceTollfreeInquiriesCreator setBusinessPostalCode( - final String businessPostalCode - ) { + + public ComplianceTollfreeInquiriesCreator setBusinessPostalCode(final String businessPostalCode) { this.businessPostalCode = businessPostalCode; return this; } - public ComplianceTollfreeInquiriesCreator setBusinessCountry( - final String businessCountry - ) { + + public ComplianceTollfreeInquiriesCreator setBusinessCountry(final String businessCountry) { this.businessCountry = businessCountry; return this; } - public ComplianceTollfreeInquiriesCreator setAdditionalInformation( - final String additionalInformation - ) { + + public ComplianceTollfreeInquiriesCreator setAdditionalInformation(final String additionalInformation) { this.additionalInformation = additionalInformation; return this; } - public ComplianceTollfreeInquiriesCreator setBusinessContactFirstName( - final String businessContactFirstName - ) { + + public ComplianceTollfreeInquiriesCreator setBusinessContactFirstName(final String businessContactFirstName) { this.businessContactFirstName = businessContactFirstName; return this; } - public ComplianceTollfreeInquiriesCreator setBusinessContactLastName( - final String businessContactLastName - ) { + + public ComplianceTollfreeInquiriesCreator setBusinessContactLastName(final String businessContactLastName) { this.businessContactLastName = businessContactLastName; return this; } - public ComplianceTollfreeInquiriesCreator setBusinessContactEmail( - final String businessContactEmail - ) { + + public ComplianceTollfreeInquiriesCreator setBusinessContactEmail(final String businessContactEmail) { this.businessContactEmail = businessContactEmail; return this; } - public ComplianceTollfreeInquiriesCreator setBusinessContactPhone( - final com.twilio.type.PhoneNumber businessContactPhone - ) { + + public ComplianceTollfreeInquiriesCreator setBusinessContactPhone(final com.twilio.type.PhoneNumber businessContactPhone) { this.businessContactPhone = businessContactPhone; return this; } - public ComplianceTollfreeInquiriesCreator setBusinessContactPhone( - final String businessContactPhone - ) { - return setBusinessContactPhone( - Promoter.phoneNumberFromString(businessContactPhone) - ); + public ComplianceTollfreeInquiriesCreator setBusinessContactPhone(final String businessContactPhone) { + return setBusinessContactPhone(Promoter.phoneNumberFromString(businessContactPhone)); } - public ComplianceTollfreeInquiriesCreator setThemeSetId( - final String themeSetId - ) { + public ComplianceTollfreeInquiriesCreator setThemeSetId(final String themeSetId) { this.themeSetId = themeSetId; return this; } - public ComplianceTollfreeInquiriesCreator setSkipMessagingUseCase( - final Boolean skipMessagingUseCase - ) { + + public ComplianceTollfreeInquiriesCreator setSkipMessagingUseCase(final Boolean skipMessagingUseCase) { this.skipMessagingUseCase = skipMessagingUseCase; return this; } + @Override public ComplianceTollfreeInquiries create(final TwilioRestClient client) { + String path = "/v1/ComplianceInquiries/Tollfree/Initialize"; - path = - path.replace( - "{" + "TollfreePhoneNumber" + "}", - this.tollfreePhoneNumber.toString() - ); - path = - path.replace( - "{" + "NotificationEmail" + "}", - this.notificationEmail.toString() - ); Request request = new Request( - HttpMethod.POST, - Domains.TRUSTHUB.toString(), - path + HttpMethod.POST, + Domains.TRUSTHUB.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "ComplianceTollfreeInquiries creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("ComplianceTollfreeInquiries creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return ComplianceTollfreeInquiries.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return ComplianceTollfreeInquiries.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (tollfreePhoneNumber != null) { - request.addPostParam( - "TollfreePhoneNumber", - tollfreePhoneNumber.toString() - ); + Serializer.toString(request, "TollfreePhoneNumber", tollfreePhoneNumber, ParameterType.URLENCODED); } + + if (notificationEmail != null) { - request.addPostParam("NotificationEmail", notificationEmail); + Serializer.toString(request, "NotificationEmail", notificationEmail, ParameterType.URLENCODED); } + + if (businessName != null) { - request.addPostParam("BusinessName", businessName); + Serializer.toString(request, "BusinessName", businessName, ParameterType.URLENCODED); } + + if (businessWebsite != null) { - request.addPostParam("BusinessWebsite", businessWebsite); + Serializer.toString(request, "BusinessWebsite", businessWebsite, ParameterType.URLENCODED); } + + if (useCaseCategories != null) { - for (String prop : useCaseCategories) { - request.addPostParam("UseCaseCategories", prop); + for (String param : useCaseCategories) { + Serializer.toString(request, "UseCaseCategories", param, ParameterType.URLENCODED); } } + + if (useCaseSummary != null) { - request.addPostParam("UseCaseSummary", useCaseSummary); + Serializer.toString(request, "UseCaseSummary", useCaseSummary, ParameterType.URLENCODED); } + + if (productionMessageSample != null) { - request.addPostParam( - "ProductionMessageSample", - productionMessageSample - ); + Serializer.toString(request, "ProductionMessageSample", productionMessageSample, ParameterType.URLENCODED); } + + if (optInImageUrls != null) { - for (String prop : optInImageUrls) { - request.addPostParam("OptInImageUrls", prop); + for (String param : optInImageUrls) { + Serializer.toString(request, "OptInImageUrls", param, ParameterType.URLENCODED); } } + + if (optInType != null) { - request.addPostParam("OptInType", optInType.toString()); + Serializer.toString(request, "OptInType", optInType, ParameterType.URLENCODED); } + + if (messageVolume != null) { - request.addPostParam("MessageVolume", messageVolume); + Serializer.toString(request, "MessageVolume", messageVolume, ParameterType.URLENCODED); } + + if (businessStreetAddress != null) { - request.addPostParam( - "BusinessStreetAddress", - businessStreetAddress - ); + Serializer.toString(request, "BusinessStreetAddress", businessStreetAddress, ParameterType.URLENCODED); } + + if (businessStreetAddress2 != null) { - request.addPostParam( - "BusinessStreetAddress2", - businessStreetAddress2 - ); + Serializer.toString(request, "BusinessStreetAddress2", businessStreetAddress2, ParameterType.URLENCODED); } + + if (businessCity != null) { - request.addPostParam("BusinessCity", businessCity); + Serializer.toString(request, "BusinessCity", businessCity, ParameterType.URLENCODED); } + + if (businessStateProvinceRegion != null) { - request.addPostParam( - "BusinessStateProvinceRegion", - businessStateProvinceRegion - ); + Serializer.toString(request, "BusinessStateProvinceRegion", businessStateProvinceRegion, ParameterType.URLENCODED); } + + if (businessPostalCode != null) { - request.addPostParam("BusinessPostalCode", businessPostalCode); + Serializer.toString(request, "BusinessPostalCode", businessPostalCode, ParameterType.URLENCODED); } + + if (businessCountry != null) { - request.addPostParam("BusinessCountry", businessCountry); + Serializer.toString(request, "BusinessCountry", businessCountry, ParameterType.URLENCODED); } + + if (additionalInformation != null) { - request.addPostParam( - "AdditionalInformation", - additionalInformation - ); + Serializer.toString(request, "AdditionalInformation", additionalInformation, ParameterType.URLENCODED); } + + if (businessContactFirstName != null) { - request.addPostParam( - "BusinessContactFirstName", - businessContactFirstName - ); + Serializer.toString(request, "BusinessContactFirstName", businessContactFirstName, ParameterType.URLENCODED); } + + if (businessContactLastName != null) { - request.addPostParam( - "BusinessContactLastName", - businessContactLastName - ); + Serializer.toString(request, "BusinessContactLastName", businessContactLastName, ParameterType.URLENCODED); } + + if (businessContactEmail != null) { - request.addPostParam("BusinessContactEmail", businessContactEmail); + Serializer.toString(request, "BusinessContactEmail", businessContactEmail, ParameterType.URLENCODED); } + + if (businessContactPhone != null) { - request.addPostParam( - "BusinessContactPhone", - businessContactPhone.toString() - ); + Serializer.toString(request, "BusinessContactPhone", businessContactPhone, ParameterType.URLENCODED); } + + if (themeSetId != null) { - request.addPostParam("ThemeSetId", themeSetId); + Serializer.toString(request, "ThemeSetId", themeSetId, ParameterType.URLENCODED); } + + if (skipMessagingUseCase != null) { - request.addPostParam( - "SkipMessagingUseCase", - skipMessagingUseCase.toString() - ); + Serializer.toString(request, "SkipMessagingUseCase", skipMessagingUseCase, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/trusthub/v1/CustomerProfiles.java b/src/main/java/com/twilio/rest/trusthub/v1/CustomerProfiles.java index 9217f2067b..90c2e507f9 100644 --- a/src/main/java/com/twilio/rest/trusthub/v1/CustomerProfiles.java +++ b/src/main/java/com/twilio/rest/trusthub/v1/CustomerProfiles.java @@ -18,65 +18,97 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.List; import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class CustomerProfiles extends Resource { - private static final long serialVersionUID = 258820529618531L; - public static CustomerProfilesCreator creator( - final String friendlyName, - final String email, - final String policySid - ) { - return new CustomerProfilesCreator(friendlyName, email, policySid); + public static CustomerProfilesCreator creator(final String friendlyName, final String email, final String policySid) { + return new CustomerProfilesCreator( + friendlyName, email, policySid + ); } - public static CustomerProfilesDeleter deleter(final String pathSid) { - return new CustomerProfilesDeleter(pathSid); + + public static CustomerProfilesDeleter deleter(final String pathsid) { + return new CustomerProfilesDeleter( + pathsid + ); } - public static CustomerProfilesFetcher fetcher(final String pathSid) { - return new CustomerProfilesFetcher(pathSid); + + public static CustomerProfilesFetcher fetcher(final String pathsid) { + return new CustomerProfilesFetcher( + pathsid + ); } + public static CustomerProfilesReader reader() { - return new CustomerProfilesReader(); + return new CustomerProfilesReader( + + ); } - public static CustomerProfilesUpdater updater(final String pathSid) { - return new CustomerProfilesUpdater(pathSid); + + public static CustomerProfilesUpdater updater(final String pathsid) { + return new CustomerProfilesUpdater( + pathsid + ); } + + public enum Status { + DRAFT("draft"), + PENDING_REVIEW("pending-review"), + IN_REVIEW("in-review"), + TWILIO_REJECTED("twilio-rejected"), + TWILIO_APPROVED("twilio-approved"); + + private final String value; + + private Status(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static Status forValue(final String value) { + return Promoter.enumFromString(value, Status.values()); + } + } + + /** * Converts a JSON String into a CustomerProfiles object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return CustomerProfiles object represented by the provided JSON */ - public static CustomerProfiles fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static CustomerProfiles fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, CustomerProfiles.class); @@ -91,14 +123,11 @@ public static CustomerProfiles fromJson( * Converts a JSON InputStream into a CustomerProfiles object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return CustomerProfiles object represented by the provided JSON */ - public static CustomerProfiles fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static CustomerProfiles fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, CustomerProfiles.class); @@ -109,101 +138,78 @@ public static CustomerProfiles fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String policySid; + @Getter + private final ZonedDateTime dateCreated; + @Getter + private final ZonedDateTime dateUpdated; + @Getter + private final String email; + @Getter + private final List errors; + @Getter private final String friendlyName; + @Getter + private final Map links; + @Getter + private final String policySid; + @Getter + private final String sid; + @Getter private final CustomerProfiles.Status status; - private final ZonedDateTime validUntil; - private final String email; + @Getter private final URI statusCallback; - private final ZonedDateTime dateCreated; - private final ZonedDateTime dateUpdated; + @Getter private final URI url; - private final Map links; - private final List> errors; + @Getter + private final ZonedDateTime validUntil; @JsonCreator private CustomerProfiles( - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("policy_sid") final String policySid, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("status") final CustomerProfiles.Status status, - @JsonProperty("valid_until") final String validUntil, - @JsonProperty("email") final String email, - @JsonProperty("status_callback") final URI statusCallback, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("url") final URI url, - @JsonProperty("links") final Map links, - @JsonProperty("errors") final List> errors + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("email") final String email, + @JsonProperty("errors") final List errors, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("links") final Map links, + @JsonProperty("policy_sid") final String policySid, + @JsonProperty("sid") final String sid, + @JsonProperty("status") final CustomerProfiles.Status status, + @JsonProperty("status_callback") final URI statusCallback, + @JsonProperty("url") final URI url, + @JsonProperty("valid_until") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime validUntil ) { - this.sid = sid; this.accountSid = accountSid; - this.policySid = policySid; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; + this.email = email; + this.errors = errors; this.friendlyName = friendlyName; + this.links = links; + this.policySid = policySid; + this.sid = sid; this.status = status; - this.validUntil = DateConverter.iso8601DateTimeFromString(validUntil); - this.email = email; this.statusCallback = statusCallback; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); this.url = url; - this.links = links; - this.errors = errors; - } - - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getPolicySid() { - return this.policySid; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final CustomerProfiles.Status getStatus() { - return this.status; - } - - public final ZonedDateTime getValidUntil() { - return this.validUntil; - } - - public final String getEmail() { - return this.email; - } - - public final URI getStatusCallback() { - return this.statusCallback; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final URI getUrl() { - return this.url; - } - - public final Map getLinks() { - return this.links; - } - - public final List> getErrors() { - return this.errors; + this.validUntil = validUntil; } @Override @@ -217,63 +223,42 @@ public boolean equals(final Object o) { } CustomerProfiles other = (CustomerProfiles) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(policySid, other.policySid) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(status, other.status) && - Objects.equals(validUntil, other.validUntil) && - Objects.equals(email, other.email) && - Objects.equals(statusCallback, other.statusCallback) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(url, other.url) && - Objects.equals(links, other.links) && - Objects.equals(errors, other.errors) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(email, other.email) && + Objects.equals(errors, other.errors) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(links, other.links) && + Objects.equals(policySid, other.policySid) && + Objects.equals(sid, other.sid) && + Objects.equals(status, other.status) && + Objects.equals(statusCallback, other.statusCallback) && + Objects.equals(url, other.url) && + Objects.equals(validUntil, other.validUntil) ); } @Override public int hashCode() { return Objects.hash( - sid, - accountSid, - policySid, - friendlyName, - status, - validUntil, - email, - statusCallback, - dateCreated, - dateUpdated, - url, - links, - errors + accountSid, + dateCreated, + dateUpdated, + email, + errors, + friendlyName, + links, + policySid, + sid, + status, + statusCallback, + url, + validUntil ); } - public enum Status { - DRAFT("draft"), - PENDING_REVIEW("pending-review"), - IN_REVIEW("in-review"), - TWILIO_REJECTED("twilio-rejected"), - TWILIO_APPROVED("twilio-approved"); - private final String value; - - private Status(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static Status forValue(final String value) { - return Promoter.enumFromString(value, Status.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/trusthub/v1/CustomerProfilesCreator.java b/src/main/java/com/twilio/rest/trusthub/v1/CustomerProfilesCreator.java index 16348c7684..a227f6b356 100644 --- a/src/main/java/com/twilio/rest/trusthub/v1/CustomerProfilesCreator.java +++ b/src/main/java/com/twilio/rest/trusthub/v1/CustomerProfilesCreator.java @@ -14,9 +14,11 @@ package com.twilio.rest.trusthub.v1; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; -import com.twilio.converter.Promoter; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,7 +27,7 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -import java.net.URI; + import java.net.URI; public class CustomerProfilesCreator extends Creator { @@ -35,98 +37,90 @@ public class CustomerProfilesCreator extends Creator { private String policySid; private URI statusCallback; - public CustomerProfilesCreator( - final String friendlyName, - final String email, - final String policySid - ) { + public CustomerProfilesCreator(final String friendlyName, final String email, final String policySid) { this.friendlyName = friendlyName; this.email = email; this.policySid = policySid; } + public CustomerProfilesCreator setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + public CustomerProfilesCreator setEmail(final String email) { this.email = email; return this; } + public CustomerProfilesCreator setPolicySid(final String policySid) { this.policySid = policySid; return this; } + public CustomerProfilesCreator setStatusCallback(final URI statusCallback) { this.statusCallback = statusCallback; return this; } - public CustomerProfilesCreator setStatusCallback( - final String statusCallback - ) { - return setStatusCallback(Promoter.uriFromString(statusCallback)); - } @Override public CustomerProfiles create(final TwilioRestClient client) { + String path = "/v1/CustomerProfiles"; - path = - path.replace( - "{" + "FriendlyName" + "}", - this.friendlyName.toString() - ); - path = path.replace("{" + "Email" + "}", this.email.toString()); - path = path.replace("{" + "PolicySid" + "}", this.policySid.toString()); Request request = new Request( - HttpMethod.POST, - Domains.TRUSTHUB.toString(), - path + HttpMethod.POST, + Domains.TRUSTHUB.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "CustomerProfiles creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("CustomerProfiles creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return CustomerProfiles.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return CustomerProfiles.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + if (email != null) { - request.addPostParam("Email", email); + Serializer.toString(request, "Email", email, ParameterType.URLENCODED); } + + if (policySid != null) { - request.addPostParam("PolicySid", policySid); + Serializer.toString(request, "PolicySid", policySid, ParameterType.URLENCODED); } + + if (statusCallback != null) { - request.addPostParam("StatusCallback", statusCallback.toString()); + Serializer.toString(request, "StatusCallback", statusCallback, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/trusthub/v1/CustomerProfilesDeleter.java b/src/main/java/com/twilio/rest/trusthub/v1/CustomerProfilesDeleter.java index a97bdc501a..4c8c6921e2 100644 --- a/src/main/java/com/twilio/rest/trusthub/v1/CustomerProfilesDeleter.java +++ b/src/main/java/com/twilio/rest/trusthub/v1/CustomerProfilesDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.trusthub.v1; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,40 +26,38 @@ public class CustomerProfilesDeleter extends Deleter { - private String pathSid; + private String pathsid; - public CustomerProfilesDeleter(final String pathSid) { - this.pathSid = pathSid; + public CustomerProfilesDeleter(final String pathsid) { + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/v1/CustomerProfiles/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.TRUSTHUB.toString(), - path + HttpMethod.DELETE, + Domains.TRUSTHUB.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "CustomerProfiles delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("CustomerProfiles delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/trusthub/v1/CustomerProfilesFetcher.java b/src/main/java/com/twilio/rest/trusthub/v1/CustomerProfilesFetcher.java index b16e7bccc0..dcf458e8f1 100644 --- a/src/main/java/com/twilio/rest/trusthub/v1/CustomerProfilesFetcher.java +++ b/src/main/java/com/twilio/rest/trusthub/v1/CustomerProfilesFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.trusthub.v1; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,47 +26,41 @@ public class CustomerProfilesFetcher extends Fetcher { - private String pathSid; + private String pathsid; - public CustomerProfilesFetcher(final String pathSid) { - this.pathSid = pathSid; + public CustomerProfilesFetcher(final String pathsid) { + this.pathsid = pathsid; } + @Override public CustomerProfiles fetch(final TwilioRestClient client) { + String path = "/v1/CustomerProfiles/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.TRUSTHUB.toString(), - path + HttpMethod.GET, + Domains.TRUSTHUB.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "CustomerProfiles fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("CustomerProfiles fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return CustomerProfiles.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return CustomerProfiles.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/trusthub/v1/CustomerProfilesReader.java b/src/main/java/com/twilio/rest/trusthub/v1/CustomerProfilesReader.java index c448b309cb..92ba53db25 100644 --- a/src/main/java/com/twilio/rest/trusthub/v1/CustomerProfilesReader.java +++ b/src/main/java/com/twilio/rest/trusthub/v1/CustomerProfilesReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -34,131 +35,116 @@ public class CustomerProfilesReader extends Reader { private String policySid; private Long pageSize; - public CustomerProfilesReader() {} + public CustomerProfilesReader() { + } + - public CustomerProfilesReader setStatus( - final CustomerProfiles.Status status - ) { + public CustomerProfilesReader setStatus(final CustomerProfiles.Status status) { this.status = status; return this; } + public CustomerProfilesReader setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + public CustomerProfilesReader setPolicySid(final String policySid) { this.policySid = policySid; return this; } + public CustomerProfilesReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/CustomerProfiles"; + Request request = new Request( - HttpMethod.GET, - Domains.TRUSTHUB.toString(), - path + HttpMethod.GET, + Domains.TRUSTHUB.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "CustomerProfiles read failed: Unable to connect to server" - ); + throw new ApiConnectionException("CustomerProfiles read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "results", - response.getContent(), - CustomerProfiles.class, - client.getObjectMapper() - ); + "results", + response.getContent(), + CustomerProfiles.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.TRUSTHUB.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.TRUSTHUB.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (status != null) { - request.addQueryParam("Status", status.toString()); + Serializer.toString(request, "Status", status, ParameterType.QUERY); } + + if (friendlyName != null) { - request.addQueryParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.QUERY); } + + if (policySid != null) { - request.addQueryParam("PolicySid", policySid); + Serializer.toString(request, "PolicySid", policySid, ParameterType.QUERY); } + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/trusthub/v1/CustomerProfilesUpdater.java b/src/main/java/com/twilio/rest/trusthub/v1/CustomerProfilesUpdater.java index a61ef40b37..ecf652bb94 100644 --- a/src/main/java/com/twilio/rest/trusthub/v1/CustomerProfilesUpdater.java +++ b/src/main/java/com/twilio/rest/trusthub/v1/CustomerProfilesUpdater.java @@ -16,7 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; -import com.twilio.converter.Promoter; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,98 +26,100 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.net.URI; public class CustomerProfilesUpdater extends Updater { - - private String pathSid; + private String pathsid; private CustomerProfiles.Status status; private URI statusCallback; private String friendlyName; private String email; - public CustomerProfilesUpdater(final String pathSid) { - this.pathSid = pathSid; + public CustomerProfilesUpdater(final String pathsid) { + this.pathsid = pathsid; } - public CustomerProfilesUpdater setStatus( - final CustomerProfiles.Status status - ) { + + public CustomerProfilesUpdater setStatus(final CustomerProfiles.Status status) { this.status = status; return this; } + public CustomerProfilesUpdater setStatusCallback(final URI statusCallback) { this.statusCallback = statusCallback; return this; } - public CustomerProfilesUpdater setStatusCallback( - final String statusCallback - ) { - return setStatusCallback(Promoter.uriFromString(statusCallback)); - } public CustomerProfilesUpdater setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + public CustomerProfilesUpdater setEmail(final String email) { this.email = email; return this; } + @Override public CustomerProfiles update(final TwilioRestClient client) { + String path = "/v1/CustomerProfiles/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.TRUSTHUB.toString(), - path + HttpMethod.POST, + Domains.TRUSTHUB.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "CustomerProfiles update failed: Unable to connect to server" - ); + throw new ApiConnectionException("CustomerProfiles update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return CustomerProfiles.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return CustomerProfiles.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (status != null) { - request.addPostParam("Status", status.toString()); + Serializer.toString(request, "Status", status, ParameterType.URLENCODED); } + + if (statusCallback != null) { - request.addPostParam("StatusCallback", statusCallback.toString()); + Serializer.toString(request, "StatusCallback", statusCallback, ParameterType.URLENCODED); } + + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + if (email != null) { - request.addPostParam("Email", email); + Serializer.toString(request, "Email", email, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/trusthub/v1/EndUser.java b/src/main/java/com/twilio/rest/trusthub/v1/EndUser.java index 01ca7832c3..20252f71e5 100644 --- a/src/main/java/com/twilio/rest/trusthub/v1/EndUser.java +++ b/src/main/java/com/twilio/rest/trusthub/v1/EndUser.java @@ -18,62 +18,70 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; -import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class EndUser extends Resource { - private static final long serialVersionUID = 90504447987573L; - public static EndUserCreator creator( - final String friendlyName, - final String type - ) { - return new EndUserCreator(friendlyName, type); + public static EndUserCreator creator(final String friendlyName, final String type) { + return new EndUserCreator( + friendlyName, type + ); } - public static EndUserDeleter deleter(final String pathSid) { - return new EndUserDeleter(pathSid); + + public static EndUserDeleter deleter(final String pathsid) { + return new EndUserDeleter( + pathsid + ); } - public static EndUserFetcher fetcher(final String pathSid) { - return new EndUserFetcher(pathSid); + + public static EndUserFetcher fetcher(final String pathsid) { + return new EndUserFetcher( + pathsid + ); } + public static EndUserReader reader() { - return new EndUserReader(); + return new EndUserReader( + + ); } - public static EndUserUpdater updater(final String pathSid) { - return new EndUserUpdater(pathSid); + + public static EndUserUpdater updater(final String pathsid) { + return new EndUserUpdater( + pathsid + ); } + /** * Converts a JSON String into a EndUser object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return EndUser object represented by the provided JSON */ - public static EndUser fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static EndUser fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, EndUser.class); @@ -88,14 +96,11 @@ public static EndUser fromJson( * Converts a JSON InputStream into a EndUser object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return EndUser object represented by the provided JSON */ - public static EndUser fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static EndUser fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, EndUser.class); @@ -106,68 +111,59 @@ public static EndUser fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String friendlyName; - private final String type; - private final Map attributes; + @Getter + private final Object attributes; + @Getter private final ZonedDateTime dateCreated; + @Getter private final ZonedDateTime dateUpdated; + @Getter + private final String friendlyName; + @Getter + private final String sid; + @Getter + private final String type; + @Getter private final URI url; @JsonCreator private EndUser( - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("type") final String type, - @JsonProperty("attributes") final Map attributes, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("url") final URI url + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("attributes") final Object attributes, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("sid") final String sid, + @JsonProperty("type") final String type, + @JsonProperty("url") final URI url ) { - this.sid = sid; this.accountSid = accountSid; + this.attributes = attributes; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.friendlyName = friendlyName; + this.sid = sid; this.type = type; - this.attributes = attributes; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); this.url = url; } - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final String getType() { - return this.type; - } - - public final Map getAttributes() { - return this.attributes; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final URI getUrl() { - return this.url; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -179,30 +175,32 @@ public boolean equals(final Object o) { } EndUser other = (EndUser) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(type, other.type) && - Objects.equals(attributes, other.attributes) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(url, other.url) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(attributes, other.attributes) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(sid, other.sid) && + Objects.equals(type, other.type) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - sid, - accountSid, - friendlyName, - type, - attributes, - dateCreated, - dateUpdated, - url + accountSid, + attributes, + dateCreated, + dateUpdated, + friendlyName, + sid, + type, + url ); } + + } + diff --git a/src/main/java/com/twilio/rest/trusthub/v1/EndUserCreator.java b/src/main/java/com/twilio/rest/trusthub/v1/EndUserCreator.java index aaddaa97f9..2050e39df0 100644 --- a/src/main/java/com/twilio/rest/trusthub/v1/EndUserCreator.java +++ b/src/main/java/com/twilio/rest/trusthub/v1/EndUserCreator.java @@ -14,10 +14,11 @@ package com.twilio.rest.trusthub.v1; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; -import com.twilio.converter.Converter; -import com.twilio.converter.Converter; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -38,54 +39,50 @@ public EndUserCreator(final String friendlyName, final String type) { this.type = type; } + public EndUserCreator setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + public EndUserCreator setType(final String type) { this.type = type; return this; } + public EndUserCreator setAttributes(final Object attributes) { this.attributes = attributes; return this; } + @Override public EndUser create(final TwilioRestClient client) { + String path = "/v1/EndUsers"; - path = - path.replace( - "{" + "FriendlyName" + "}", - this.friendlyName.toString() - ); - path = path.replace("{" + "Type" + "}", this.type.toString()); Request request = new Request( - HttpMethod.POST, - Domains.TRUSTHUB.toString(), - path + HttpMethod.POST, + Domains.TRUSTHUB.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "EndUser creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("EndUser creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -94,17 +91,21 @@ public EndUser create(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + if (type != null) { - request.addPostParam("Type", type); + Serializer.toString(request, "Type", type, ParameterType.URLENCODED); } + + if (attributes != null) { - request.addPostParam( - "Attributes", - Converter.objectToJson(attributes) - ); + Serializer.toString(request, "Attributes", attributes, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/trusthub/v1/EndUserDeleter.java b/src/main/java/com/twilio/rest/trusthub/v1/EndUserDeleter.java index e3250a7ff2..c56d06bb25 100644 --- a/src/main/java/com/twilio/rest/trusthub/v1/EndUserDeleter.java +++ b/src/main/java/com/twilio/rest/trusthub/v1/EndUserDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.trusthub.v1; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,40 +26,38 @@ public class EndUserDeleter extends Deleter { - private String pathSid; + private String pathsid; - public EndUserDeleter(final String pathSid) { - this.pathSid = pathSid; + public EndUserDeleter(final String pathsid) { + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/v1/EndUsers/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.TRUSTHUB.toString(), - path + HttpMethod.DELETE, + Domains.TRUSTHUB.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "EndUser delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("EndUser delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/trusthub/v1/EndUserFetcher.java b/src/main/java/com/twilio/rest/trusthub/v1/EndUserFetcher.java index 0fa3ce41da..e2e8edde86 100644 --- a/src/main/java/com/twilio/rest/trusthub/v1/EndUserFetcher.java +++ b/src/main/java/com/twilio/rest/trusthub/v1/EndUserFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.trusthub.v1; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,44 +26,41 @@ public class EndUserFetcher extends Fetcher { - private String pathSid; + private String pathsid; - public EndUserFetcher(final String pathSid) { - this.pathSid = pathSid; + public EndUserFetcher(final String pathsid) { + this.pathsid = pathsid; } + @Override public EndUser fetch(final TwilioRestClient client) { + String path = "/v1/EndUsers/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.TRUSTHUB.toString(), - path + HttpMethod.GET, + Domains.TRUSTHUB.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "EndUser fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("EndUser fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return EndUser.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/trusthub/v1/EndUserReader.java b/src/main/java/com/twilio/rest/trusthub/v1/EndUserReader.java index 25a1099f3f..dc4c95303e 100644 --- a/src/main/java/com/twilio/rest/trusthub/v1/EndUserReader.java +++ b/src/main/java/com/twilio/rest/trusthub/v1/EndUserReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -31,105 +32,83 @@ public class EndUserReader extends Reader { private Long pageSize; - public EndUserReader() {} + public EndUserReader() { + } + public EndUserReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/EndUsers"; + Request request = new Request( - HttpMethod.GET, - Domains.TRUSTHUB.toString(), - path + HttpMethod.GET, + Domains.TRUSTHUB.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "EndUser read failed: Unable to connect to server" - ); + throw new ApiConnectionException("EndUser read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "results", - response.getContent(), - EndUser.class, - client.getObjectMapper() - ); + "results", + response.getContent(), + EndUser.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.TRUSTHUB.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.TRUSTHUB.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/trusthub/v1/EndUserType.java b/src/main/java/com/twilio/rest/trusthub/v1/EndUserType.java index 79b4a51626..b176fb7770 100644 --- a/src/main/java/com/twilio/rest/trusthub/v1/EndUserType.java +++ b/src/main/java/com/twilio/rest/trusthub/v1/EndUserType.java @@ -18,46 +18,48 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.util.List; -import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class EndUserType extends Resource { - private static final long serialVersionUID = 67038001521206L; - public static EndUserTypeFetcher fetcher(final String pathSid) { - return new EndUserTypeFetcher(pathSid); + public static EndUserTypeFetcher fetcher(final String pathsid) { + return new EndUserTypeFetcher( + pathsid + ); } + public static EndUserTypeReader reader() { - return new EndUserTypeReader(); + return new EndUserTypeReader( + + ); } + /** * Converts a JSON String into a EndUserType object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return EndUserType object represented by the provided JSON */ - public static EndUserType fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static EndUserType fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, EndUserType.class); @@ -72,14 +74,11 @@ public static EndUserType fromJson( * Converts a JSON InputStream into a EndUserType object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return EndUserType object represented by the provided JSON */ - public static EndUserType fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static EndUserType fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, EndUserType.class); @@ -90,47 +89,45 @@ public static EndUserType fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter + private final List fields; + @Getter private final String friendlyName; + @Getter private final String machineName; - private final List> fields; + @Getter + private final String sid; + @Getter private final URI url; @JsonCreator private EndUserType( - @JsonProperty("sid") final String sid, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("machine_name") final String machineName, - @JsonProperty("fields") final List> fields, - @JsonProperty("url") final URI url + @JsonProperty("fields") final List fields, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("machine_name") final String machineName, + @JsonProperty("sid") final String sid, + @JsonProperty("url") final URI url ) { - this.sid = sid; + this.fields = fields; this.friendlyName = friendlyName; this.machineName = machineName; - this.fields = fields; + this.sid = sid; this.url = url; } - public final String getSid() { - return this.sid; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final String getMachineName() { - return this.machineName; - } - - public final List> getFields() { - return this.fields; - } - - public final URI getUrl() { - return this.url; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -142,18 +139,26 @@ public boolean equals(final Object o) { } EndUserType other = (EndUserType) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(machineName, other.machineName) && - Objects.equals(fields, other.fields) && - Objects.equals(url, other.url) + Objects.equals(fields, other.fields) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(machineName, other.machineName) && + Objects.equals(sid, other.sid) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { - return Objects.hash(sid, friendlyName, machineName, fields, url); + return Objects.hash( + fields, + friendlyName, + machineName, + sid, + url + ); } + + } + diff --git a/src/main/java/com/twilio/rest/trusthub/v1/EndUserTypeFetcher.java b/src/main/java/com/twilio/rest/trusthub/v1/EndUserTypeFetcher.java index e419e6fa06..1ffe809992 100644 --- a/src/main/java/com/twilio/rest/trusthub/v1/EndUserTypeFetcher.java +++ b/src/main/java/com/twilio/rest/trusthub/v1/EndUserTypeFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.trusthub.v1; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,47 +26,41 @@ public class EndUserTypeFetcher extends Fetcher { - private String pathSid; + private String pathsid; - public EndUserTypeFetcher(final String pathSid) { - this.pathSid = pathSid; + public EndUserTypeFetcher(final String pathsid) { + this.pathsid = pathsid; } + @Override public EndUserType fetch(final TwilioRestClient client) { + String path = "/v1/EndUserTypes/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.TRUSTHUB.toString(), - path + HttpMethod.GET, + Domains.TRUSTHUB.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "EndUserType fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("EndUserType fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return EndUserType.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return EndUserType.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/trusthub/v1/EndUserTypeReader.java b/src/main/java/com/twilio/rest/trusthub/v1/EndUserTypeReader.java index 52c35e248a..8a1c230dbf 100644 --- a/src/main/java/com/twilio/rest/trusthub/v1/EndUserTypeReader.java +++ b/src/main/java/com/twilio/rest/trusthub/v1/EndUserTypeReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -31,105 +32,83 @@ public class EndUserTypeReader extends Reader { private Long pageSize; - public EndUserTypeReader() {} + public EndUserTypeReader() { + } + public EndUserTypeReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/EndUserTypes"; + Request request = new Request( - HttpMethod.GET, - Domains.TRUSTHUB.toString(), - path + HttpMethod.GET, + Domains.TRUSTHUB.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "EndUserType read failed: Unable to connect to server" - ); + throw new ApiConnectionException("EndUserType read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "end_user_types", - response.getContent(), - EndUserType.class, - client.getObjectMapper() - ); + "end_user_types", + response.getContent(), + EndUserType.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.TRUSTHUB.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.TRUSTHUB.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/trusthub/v1/EndUserUpdater.java b/src/main/java/com/twilio/rest/trusthub/v1/EndUserUpdater.java index 479a4a4ed9..95ca2e1504 100644 --- a/src/main/java/com/twilio/rest/trusthub/v1/EndUserUpdater.java +++ b/src/main/java/com/twilio/rest/trusthub/v1/EndUserUpdater.java @@ -16,7 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; -import com.twilio.converter.Converter; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,53 +28,54 @@ import com.twilio.rest.Domains; public class EndUserUpdater extends Updater { - - private String pathSid; + private String pathsid; private String friendlyName; private Object attributes; - public EndUserUpdater(final String pathSid) { - this.pathSid = pathSid; + public EndUserUpdater(final String pathsid) { + this.pathsid = pathsid; } + public EndUserUpdater setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + public EndUserUpdater setAttributes(final Object attributes) { this.attributes = attributes; return this; } + @Override public EndUser update(final TwilioRestClient client) { + String path = "/v1/EndUsers/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.TRUSTHUB.toString(), - path + HttpMethod.POST, + Domains.TRUSTHUB.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "EndUser update failed: Unable to connect to server" - ); + throw new ApiConnectionException("EndUser update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -82,14 +84,16 @@ public EndUser update(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + if (attributes != null) { - request.addPostParam( - "Attributes", - Converter.objectToJson(attributes) - ); + Serializer.toString(request, "Attributes", attributes, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/trusthub/v1/Policies.java b/src/main/java/com/twilio/rest/trusthub/v1/Policies.java index e9fec1bf84..f4e30971ff 100644 --- a/src/main/java/com/twilio/rest/trusthub/v1/Policies.java +++ b/src/main/java/com/twilio/rest/trusthub/v1/Policies.java @@ -18,45 +18,47 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; -import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Policies extends Resource { - private static final long serialVersionUID = 142613922631852L; - public static PoliciesFetcher fetcher(final String pathSid) { - return new PoliciesFetcher(pathSid); + public static PoliciesFetcher fetcher(final String pathsid) { + return new PoliciesFetcher( + pathsid + ); } + public static PoliciesReader reader() { - return new PoliciesReader(); + return new PoliciesReader( + + ); } + /** * Converts a JSON String into a Policies object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Policies object represented by the provided JSON */ - public static Policies fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Policies fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Policies.class); @@ -71,14 +73,11 @@ public static Policies fromJson( * Converts a JSON InputStream into a Policies object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Policies object represented by the provided JSON */ - public static Policies fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Policies fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Policies.class); @@ -89,40 +88,41 @@ public static Policies fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String friendlyName; - private final Map requirements; + @Getter + private final Object requirements; + @Getter + private final String sid; + @Getter private final URI url; @JsonCreator private Policies( - @JsonProperty("sid") final String sid, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("requirements") final Map requirements, - @JsonProperty("url") final URI url + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("requirements") final Object requirements, + @JsonProperty("sid") final String sid, + @JsonProperty("url") final URI url ) { - this.sid = sid; this.friendlyName = friendlyName; this.requirements = requirements; + this.sid = sid; this.url = url; } - public final String getSid() { - return this.sid; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final Map getRequirements() { - return this.requirements; - } - - public final URI getUrl() { - return this.url; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -134,17 +134,24 @@ public boolean equals(final Object o) { } Policies other = (Policies) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(requirements, other.requirements) && - Objects.equals(url, other.url) + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(requirements, other.requirements) && + Objects.equals(sid, other.sid) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { - return Objects.hash(sid, friendlyName, requirements, url); + return Objects.hash( + friendlyName, + requirements, + sid, + url + ); } + + } + diff --git a/src/main/java/com/twilio/rest/trusthub/v1/PoliciesFetcher.java b/src/main/java/com/twilio/rest/trusthub/v1/PoliciesFetcher.java index 3bab5d3568..8bedb5d756 100644 --- a/src/main/java/com/twilio/rest/trusthub/v1/PoliciesFetcher.java +++ b/src/main/java/com/twilio/rest/trusthub/v1/PoliciesFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.trusthub.v1; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,47 +26,41 @@ public class PoliciesFetcher extends Fetcher { - private String pathSid; + private String pathsid; - public PoliciesFetcher(final String pathSid) { - this.pathSid = pathSid; + public PoliciesFetcher(final String pathsid) { + this.pathsid = pathsid; } + @Override public Policies fetch(final TwilioRestClient client) { + String path = "/v1/Policies/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.TRUSTHUB.toString(), - path + HttpMethod.GET, + Domains.TRUSTHUB.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Policies fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Policies fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return Policies.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Policies.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/trusthub/v1/PoliciesReader.java b/src/main/java/com/twilio/rest/trusthub/v1/PoliciesReader.java index fbbb8f5712..724e8ec4ab 100644 --- a/src/main/java/com/twilio/rest/trusthub/v1/PoliciesReader.java +++ b/src/main/java/com/twilio/rest/trusthub/v1/PoliciesReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -31,105 +32,83 @@ public class PoliciesReader extends Reader { private Long pageSize; - public PoliciesReader() {} + public PoliciesReader() { + } + public PoliciesReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/Policies"; + Request request = new Request( - HttpMethod.GET, - Domains.TRUSTHUB.toString(), - path + HttpMethod.GET, + Domains.TRUSTHUB.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Policies read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Policies read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "results", - response.getContent(), - Policies.class, - client.getObjectMapper() - ); + "results", + response.getContent(), + Policies.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.TRUSTHUB.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.TRUSTHUB.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/trusthub/v1/SupportingDocument.java b/src/main/java/com/twilio/rest/trusthub/v1/SupportingDocument.java index fcb0e31305..4b5d0750bd 100644 --- a/src/main/java/com/twilio/rest/trusthub/v1/SupportingDocument.java +++ b/src/main/java/com/twilio/rest/trusthub/v1/SupportingDocument.java @@ -18,63 +18,96 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; -import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class SupportingDocument extends Resource { - private static final long serialVersionUID = 13014832865593L; - public static SupportingDocumentCreator creator( - final String friendlyName, - final String type - ) { - return new SupportingDocumentCreator(friendlyName, type); + public static SupportingDocumentCreator creator(final String friendlyName, final String type) { + return new SupportingDocumentCreator( + friendlyName, type + ); } - public static SupportingDocumentDeleter deleter(final String pathSid) { - return new SupportingDocumentDeleter(pathSid); + + public static SupportingDocumentDeleter deleter(final String pathsid) { + return new SupportingDocumentDeleter( + pathsid + ); } - public static SupportingDocumentFetcher fetcher(final String pathSid) { - return new SupportingDocumentFetcher(pathSid); + + public static SupportingDocumentFetcher fetcher(final String pathsid) { + return new SupportingDocumentFetcher( + pathsid + ); } + public static SupportingDocumentReader reader() { - return new SupportingDocumentReader(); + return new SupportingDocumentReader( + + ); } - public static SupportingDocumentUpdater updater(final String pathSid) { - return new SupportingDocumentUpdater(pathSid); + + public static SupportingDocumentUpdater updater(final String pathsid) { + return new SupportingDocumentUpdater( + pathsid + ); } + + public enum Status { + DRAFT("DRAFT"), + PENDING_REVIEW("PENDING_REVIEW"), + REJECTED("REJECTED"), + APPROVED("APPROVED"), + EXPIRED("EXPIRED"), + PROVISIONALLY_APPROVED("PROVISIONALLY_APPROVED"); + + private final String value; + + private Status(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static Status forValue(final String value) { + return Promoter.enumFromString(value, Status.values()); + } + } + + /** * Converts a JSON String into a SupportingDocument object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return SupportingDocument object represented by the provided JSON */ - public static SupportingDocument fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static SupportingDocument fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, SupportingDocument.class); @@ -89,14 +122,11 @@ public static SupportingDocument fromJson( * Converts a JSON InputStream into a SupportingDocument object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return SupportingDocument object represented by the provided JSON */ - public static SupportingDocument fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static SupportingDocument fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, SupportingDocument.class); @@ -107,82 +137,67 @@ public static SupportingDocument fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; + @Getter + private final Object attributes; + @Getter + private final ZonedDateTime dateCreated; + @Getter + private final ZonedDateTime dateUpdated; + @Getter private final String friendlyName; + @Getter private final String mimeType; + @Getter + private final String sid; + @Getter private final SupportingDocument.Status status; + @Getter private final String type; - private final Map attributes; - private final ZonedDateTime dateCreated; - private final ZonedDateTime dateUpdated; + @Getter private final URI url; @JsonCreator private SupportingDocument( - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("mime_type") final String mimeType, - @JsonProperty("status") final SupportingDocument.Status status, - @JsonProperty("type") final String type, - @JsonProperty("attributes") final Map attributes, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("url") final URI url + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("attributes") final Object attributes, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("mime_type") final String mimeType, + @JsonProperty("sid") final String sid, + @JsonProperty("status") final SupportingDocument.Status status, + @JsonProperty("type") final String type, + @JsonProperty("url") final URI url ) { - this.sid = sid; this.accountSid = accountSid; + this.attributes = attributes; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; this.friendlyName = friendlyName; this.mimeType = mimeType; + this.sid = sid; this.status = status; this.type = type; - this.attributes = attributes; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); this.url = url; } - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final String getMimeType() { - return this.mimeType; - } - - public final SupportingDocument.Status getStatus() { - return this.status; - } - - public final String getType() { - return this.type; - } - - public final Map getAttributes() { - return this.attributes; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final URI getUrl() { - return this.url; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -194,58 +209,36 @@ public boolean equals(final Object o) { } SupportingDocument other = (SupportingDocument) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(mimeType, other.mimeType) && - Objects.equals(status, other.status) && - Objects.equals(type, other.type) && - Objects.equals(attributes, other.attributes) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(url, other.url) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(attributes, other.attributes) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(mimeType, other.mimeType) && + Objects.equals(sid, other.sid) && + Objects.equals(status, other.status) && + Objects.equals(type, other.type) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - sid, - accountSid, - friendlyName, - mimeType, - status, - type, - attributes, - dateCreated, - dateUpdated, - url + accountSid, + attributes, + dateCreated, + dateUpdated, + friendlyName, + mimeType, + sid, + status, + type, + url ); } - public enum Status { - DRAFT("DRAFT"), - PENDING_REVIEW("PENDING_REVIEW"), - REJECTED("REJECTED"), - APPROVED("APPROVED"), - EXPIRED("EXPIRED"), - PROVISIONALLY_APPROVED("PROVISIONALLY_APPROVED"); - - private final String value; - - private Status(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - @JsonCreator - public static Status forValue(final String value) { - return Promoter.enumFromString(value, Status.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/trusthub/v1/SupportingDocumentCreator.java b/src/main/java/com/twilio/rest/trusthub/v1/SupportingDocumentCreator.java index 53f68a08d7..937253eda6 100644 --- a/src/main/java/com/twilio/rest/trusthub/v1/SupportingDocumentCreator.java +++ b/src/main/java/com/twilio/rest/trusthub/v1/SupportingDocumentCreator.java @@ -14,10 +14,11 @@ package com.twilio.rest.trusthub.v1; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; -import com.twilio.converter.Converter; -import com.twilio.converter.Converter; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -33,86 +34,78 @@ public class SupportingDocumentCreator extends Creator { private String type; private Object attributes; - public SupportingDocumentCreator( - final String friendlyName, - final String type - ) { + public SupportingDocumentCreator(final String friendlyName, final String type) { this.friendlyName = friendlyName; this.type = type; } - public SupportingDocumentCreator setFriendlyName( - final String friendlyName - ) { + + public SupportingDocumentCreator setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + public SupportingDocumentCreator setType(final String type) { this.type = type; return this; } + public SupportingDocumentCreator setAttributes(final Object attributes) { this.attributes = attributes; return this; } + @Override public SupportingDocument create(final TwilioRestClient client) { + String path = "/v1/SupportingDocuments"; - path = - path.replace( - "{" + "FriendlyName" + "}", - this.friendlyName.toString() - ); - path = path.replace("{" + "Type" + "}", this.type.toString()); Request request = new Request( - HttpMethod.POST, - Domains.TRUSTHUB.toString(), - path + HttpMethod.POST, + Domains.TRUSTHUB.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "SupportingDocument creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("SupportingDocument creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return SupportingDocument.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return SupportingDocument.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + if (type != null) { - request.addPostParam("Type", type); + Serializer.toString(request, "Type", type, ParameterType.URLENCODED); } + + if (attributes != null) { - request.addPostParam( - "Attributes", - Converter.objectToJson(attributes) - ); + Serializer.toString(request, "Attributes", attributes, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/trusthub/v1/SupportingDocumentDeleter.java b/src/main/java/com/twilio/rest/trusthub/v1/SupportingDocumentDeleter.java index f1289445bf..fe24879970 100644 --- a/src/main/java/com/twilio/rest/trusthub/v1/SupportingDocumentDeleter.java +++ b/src/main/java/com/twilio/rest/trusthub/v1/SupportingDocumentDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.trusthub.v1; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,40 +26,38 @@ public class SupportingDocumentDeleter extends Deleter { - private String pathSid; + private String pathsid; - public SupportingDocumentDeleter(final String pathSid) { - this.pathSid = pathSid; + public SupportingDocumentDeleter(final String pathsid) { + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/v1/SupportingDocuments/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.TRUSTHUB.toString(), - path + HttpMethod.DELETE, + Domains.TRUSTHUB.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "SupportingDocument delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("SupportingDocument delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/trusthub/v1/SupportingDocumentFetcher.java b/src/main/java/com/twilio/rest/trusthub/v1/SupportingDocumentFetcher.java index 289888a0f9..eb5ddb60be 100644 --- a/src/main/java/com/twilio/rest/trusthub/v1/SupportingDocumentFetcher.java +++ b/src/main/java/com/twilio/rest/trusthub/v1/SupportingDocumentFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.trusthub.v1; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,47 +26,41 @@ public class SupportingDocumentFetcher extends Fetcher { - private String pathSid; + private String pathsid; - public SupportingDocumentFetcher(final String pathSid) { - this.pathSid = pathSid; + public SupportingDocumentFetcher(final String pathsid) { + this.pathsid = pathsid; } + @Override public SupportingDocument fetch(final TwilioRestClient client) { + String path = "/v1/SupportingDocuments/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.TRUSTHUB.toString(), - path + HttpMethod.GET, + Domains.TRUSTHUB.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "SupportingDocument fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("SupportingDocument fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return SupportingDocument.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return SupportingDocument.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/trusthub/v1/SupportingDocumentReader.java b/src/main/java/com/twilio/rest/trusthub/v1/SupportingDocumentReader.java index a4311a04d2..b7749e7611 100644 --- a/src/main/java/com/twilio/rest/trusthub/v1/SupportingDocumentReader.java +++ b/src/main/java/com/twilio/rest/trusthub/v1/SupportingDocumentReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -31,105 +32,83 @@ public class SupportingDocumentReader extends Reader { private Long pageSize; - public SupportingDocumentReader() {} + public SupportingDocumentReader() { + } + public SupportingDocumentReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/SupportingDocuments"; + Request request = new Request( - HttpMethod.GET, - Domains.TRUSTHUB.toString(), - path + HttpMethod.GET, + Domains.TRUSTHUB.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "SupportingDocument read failed: Unable to connect to server" - ); + throw new ApiConnectionException("SupportingDocument read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "results", - response.getContent(), - SupportingDocument.class, - client.getObjectMapper() - ); + "results", + response.getContent(), + SupportingDocument.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.TRUSTHUB.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.TRUSTHUB.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/trusthub/v1/SupportingDocumentType.java b/src/main/java/com/twilio/rest/trusthub/v1/SupportingDocumentType.java index 4e5429cfd7..50f187537d 100644 --- a/src/main/java/com/twilio/rest/trusthub/v1/SupportingDocumentType.java +++ b/src/main/java/com/twilio/rest/trusthub/v1/SupportingDocumentType.java @@ -18,46 +18,48 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.util.List; -import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class SupportingDocumentType extends Resource { - private static final long serialVersionUID = 67038001521206L; - public static SupportingDocumentTypeFetcher fetcher(final String pathSid) { - return new SupportingDocumentTypeFetcher(pathSid); + public static SupportingDocumentTypeFetcher fetcher(final String pathsid) { + return new SupportingDocumentTypeFetcher( + pathsid + ); } + public static SupportingDocumentTypeReader reader() { - return new SupportingDocumentTypeReader(); + return new SupportingDocumentTypeReader( + + ); } + /** * Converts a JSON String into a SupportingDocumentType object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return SupportingDocumentType object represented by the provided JSON */ - public static SupportingDocumentType fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static SupportingDocumentType fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, SupportingDocumentType.class); @@ -72,14 +74,11 @@ public static SupportingDocumentType fromJson( * Converts a JSON InputStream into a SupportingDocumentType object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return SupportingDocumentType object represented by the provided JSON */ - public static SupportingDocumentType fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static SupportingDocumentType fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, SupportingDocumentType.class); @@ -90,47 +89,45 @@ public static SupportingDocumentType fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter + private final List fields; + @Getter private final String friendlyName; + @Getter private final String machineName; - private final List> fields; + @Getter + private final String sid; + @Getter private final URI url; @JsonCreator private SupportingDocumentType( - @JsonProperty("sid") final String sid, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("machine_name") final String machineName, - @JsonProperty("fields") final List> fields, - @JsonProperty("url") final URI url + @JsonProperty("fields") final List fields, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("machine_name") final String machineName, + @JsonProperty("sid") final String sid, + @JsonProperty("url") final URI url ) { - this.sid = sid; + this.fields = fields; this.friendlyName = friendlyName; this.machineName = machineName; - this.fields = fields; + this.sid = sid; this.url = url; } - public final String getSid() { - return this.sid; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final String getMachineName() { - return this.machineName; - } - - public final List> getFields() { - return this.fields; - } - - public final URI getUrl() { - return this.url; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -142,18 +139,26 @@ public boolean equals(final Object o) { } SupportingDocumentType other = (SupportingDocumentType) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(machineName, other.machineName) && - Objects.equals(fields, other.fields) && - Objects.equals(url, other.url) + Objects.equals(fields, other.fields) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(machineName, other.machineName) && + Objects.equals(sid, other.sid) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { - return Objects.hash(sid, friendlyName, machineName, fields, url); + return Objects.hash( + fields, + friendlyName, + machineName, + sid, + url + ); } + + } + diff --git a/src/main/java/com/twilio/rest/trusthub/v1/SupportingDocumentTypeFetcher.java b/src/main/java/com/twilio/rest/trusthub/v1/SupportingDocumentTypeFetcher.java index cc0a82fd59..5b4916ef5e 100644 --- a/src/main/java/com/twilio/rest/trusthub/v1/SupportingDocumentTypeFetcher.java +++ b/src/main/java/com/twilio/rest/trusthub/v1/SupportingDocumentTypeFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.trusthub.v1; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,50 +24,43 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class SupportingDocumentTypeFetcher - extends Fetcher { +public class SupportingDocumentTypeFetcher extends Fetcher { - private String pathSid; + private String pathsid; - public SupportingDocumentTypeFetcher(final String pathSid) { - this.pathSid = pathSid; + public SupportingDocumentTypeFetcher(final String pathsid) { + this.pathsid = pathsid; } + @Override public SupportingDocumentType fetch(final TwilioRestClient client) { + String path = "/v1/SupportingDocumentTypes/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.TRUSTHUB.toString(), - path + HttpMethod.GET, + Domains.TRUSTHUB.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "SupportingDocumentType fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("SupportingDocumentType fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return SupportingDocumentType.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return SupportingDocumentType.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/trusthub/v1/SupportingDocumentTypeReader.java b/src/main/java/com/twilio/rest/trusthub/v1/SupportingDocumentTypeReader.java index 3dd61c7e2c..53ee057fbe 100644 --- a/src/main/java/com/twilio/rest/trusthub/v1/SupportingDocumentTypeReader.java +++ b/src/main/java/com/twilio/rest/trusthub/v1/SupportingDocumentTypeReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,114 +28,87 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class SupportingDocumentTypeReader - extends Reader { +public class SupportingDocumentTypeReader extends Reader { private Long pageSize; - public SupportingDocumentTypeReader() {} + public SupportingDocumentTypeReader() { + } + public SupportingDocumentTypeReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override - public ResourceSet read( - final TwilioRestClient client - ) { + public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } - public Page firstPage( - final TwilioRestClient client - ) { + public Page firstPage(final TwilioRestClient client) { + String path = "/v1/SupportingDocumentTypes"; + Request request = new Request( - HttpMethod.GET, - Domains.TRUSTHUB.toString(), - path + HttpMethod.GET, + Domains.TRUSTHUB.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "SupportingDocumentType read failed: Unable to connect to server" - ); + throw new ApiConnectionException("SupportingDocumentType read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "supporting_document_types", - response.getContent(), - SupportingDocumentType.class, - client.getObjectMapper() - ); + "supporting_document_types", + response.getContent(), + SupportingDocumentType.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.TRUSTHUB.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.TRUSTHUB.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/trusthub/v1/SupportingDocumentUpdater.java b/src/main/java/com/twilio/rest/trusthub/v1/SupportingDocumentUpdater.java index ec523a8f85..de7a3b9055 100644 --- a/src/main/java/com/twilio/rest/trusthub/v1/SupportingDocumentUpdater.java +++ b/src/main/java/com/twilio/rest/trusthub/v1/SupportingDocumentUpdater.java @@ -16,7 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; -import com.twilio.converter.Converter; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,74 +28,72 @@ import com.twilio.rest.Domains; public class SupportingDocumentUpdater extends Updater { - - private String pathSid; + private String pathsid; private String friendlyName; private Object attributes; - public SupportingDocumentUpdater(final String pathSid) { - this.pathSid = pathSid; + public SupportingDocumentUpdater(final String pathsid) { + this.pathsid = pathsid; } - public SupportingDocumentUpdater setFriendlyName( - final String friendlyName - ) { + + public SupportingDocumentUpdater setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + public SupportingDocumentUpdater setAttributes(final Object attributes) { this.attributes = attributes; return this; } + @Override public SupportingDocument update(final TwilioRestClient client) { + String path = "/v1/SupportingDocuments/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.TRUSTHUB.toString(), - path + HttpMethod.POST, + Domains.TRUSTHUB.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "SupportingDocument update failed: Unable to connect to server" - ); + throw new ApiConnectionException("SupportingDocument update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return SupportingDocument.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return SupportingDocument.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + if (attributes != null) { - request.addPostParam( - "Attributes", - Converter.objectToJson(attributes) - ); + Serializer.toString(request, "Attributes", attributes, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/trusthub/v1/TrustProducts.java b/src/main/java/com/twilio/rest/trusthub/v1/TrustProducts.java index a1be16ed7e..b9d184d22e 100644 --- a/src/main/java/com/twilio/rest/trusthub/v1/TrustProducts.java +++ b/src/main/java/com/twilio/rest/trusthub/v1/TrustProducts.java @@ -18,65 +18,97 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.List; import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class TrustProducts extends Resource { - private static final long serialVersionUID = 79201442410217L; - public static TrustProductsCreator creator( - final String friendlyName, - final String email, - final String policySid - ) { - return new TrustProductsCreator(friendlyName, email, policySid); + public static TrustProductsCreator creator(final String friendlyName, final String email, final String policySid) { + return new TrustProductsCreator( + friendlyName, email, policySid + ); } - public static TrustProductsDeleter deleter(final String pathSid) { - return new TrustProductsDeleter(pathSid); + + public static TrustProductsDeleter deleter(final String pathsid) { + return new TrustProductsDeleter( + pathsid + ); } - public static TrustProductsFetcher fetcher(final String pathSid) { - return new TrustProductsFetcher(pathSid); + + public static TrustProductsFetcher fetcher(final String pathsid) { + return new TrustProductsFetcher( + pathsid + ); } + public static TrustProductsReader reader() { - return new TrustProductsReader(); + return new TrustProductsReader( + + ); } - public static TrustProductsUpdater updater(final String pathSid) { - return new TrustProductsUpdater(pathSid); + + public static TrustProductsUpdater updater(final String pathsid) { + return new TrustProductsUpdater( + pathsid + ); } + + public enum Status { + DRAFT("draft"), + PENDING_REVIEW("pending-review"), + IN_REVIEW("in-review"), + TWILIO_REJECTED("twilio-rejected"), + TWILIO_APPROVED("twilio-approved"); + + private final String value; + + private Status(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static Status forValue(final String value) { + return Promoter.enumFromString(value, Status.values()); + } + } + + /** * Converts a JSON String into a TrustProducts object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return TrustProducts object represented by the provided JSON */ - public static TrustProducts fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static TrustProducts fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, TrustProducts.class); @@ -91,14 +123,11 @@ public static TrustProducts fromJson( * Converts a JSON InputStream into a TrustProducts object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return TrustProducts object represented by the provided JSON */ - public static TrustProducts fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static TrustProducts fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, TrustProducts.class); @@ -109,101 +138,78 @@ public static TrustProducts fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String policySid; + @Getter + private final ZonedDateTime dateCreated; + @Getter + private final ZonedDateTime dateUpdated; + @Getter + private final String email; + @Getter + private final List errors; + @Getter private final String friendlyName; + @Getter + private final Map links; + @Getter + private final String policySid; + @Getter + private final String sid; + @Getter private final TrustProducts.Status status; - private final ZonedDateTime validUntil; - private final String email; + @Getter private final URI statusCallback; - private final ZonedDateTime dateCreated; - private final ZonedDateTime dateUpdated; + @Getter private final URI url; - private final Map links; - private final List> errors; + @Getter + private final ZonedDateTime validUntil; @JsonCreator private TrustProducts( - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("policy_sid") final String policySid, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("status") final TrustProducts.Status status, - @JsonProperty("valid_until") final String validUntil, - @JsonProperty("email") final String email, - @JsonProperty("status_callback") final URI statusCallback, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("url") final URI url, - @JsonProperty("links") final Map links, - @JsonProperty("errors") final List> errors + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("email") final String email, + @JsonProperty("errors") final List errors, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("links") final Map links, + @JsonProperty("policy_sid") final String policySid, + @JsonProperty("sid") final String sid, + @JsonProperty("status") final TrustProducts.Status status, + @JsonProperty("status_callback") final URI statusCallback, + @JsonProperty("url") final URI url, + @JsonProperty("valid_until") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime validUntil ) { - this.sid = sid; this.accountSid = accountSid; - this.policySid = policySid; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; + this.email = email; + this.errors = errors; this.friendlyName = friendlyName; + this.links = links; + this.policySid = policySid; + this.sid = sid; this.status = status; - this.validUntil = DateConverter.iso8601DateTimeFromString(validUntil); - this.email = email; this.statusCallback = statusCallback; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); this.url = url; - this.links = links; - this.errors = errors; - } - - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getPolicySid() { - return this.policySid; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final TrustProducts.Status getStatus() { - return this.status; - } - - public final ZonedDateTime getValidUntil() { - return this.validUntil; - } - - public final String getEmail() { - return this.email; - } - - public final URI getStatusCallback() { - return this.statusCallback; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final URI getUrl() { - return this.url; - } - - public final Map getLinks() { - return this.links; - } - - public final List> getErrors() { - return this.errors; + this.validUntil = validUntil; } @Override @@ -217,63 +223,42 @@ public boolean equals(final Object o) { } TrustProducts other = (TrustProducts) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(policySid, other.policySid) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(status, other.status) && - Objects.equals(validUntil, other.validUntil) && - Objects.equals(email, other.email) && - Objects.equals(statusCallback, other.statusCallback) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(url, other.url) && - Objects.equals(links, other.links) && - Objects.equals(errors, other.errors) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(email, other.email) && + Objects.equals(errors, other.errors) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(links, other.links) && + Objects.equals(policySid, other.policySid) && + Objects.equals(sid, other.sid) && + Objects.equals(status, other.status) && + Objects.equals(statusCallback, other.statusCallback) && + Objects.equals(url, other.url) && + Objects.equals(validUntil, other.validUntil) ); } @Override public int hashCode() { return Objects.hash( - sid, - accountSid, - policySid, - friendlyName, - status, - validUntil, - email, - statusCallback, - dateCreated, - dateUpdated, - url, - links, - errors + accountSid, + dateCreated, + dateUpdated, + email, + errors, + friendlyName, + links, + policySid, + sid, + status, + statusCallback, + url, + validUntil ); } - public enum Status { - DRAFT("draft"), - PENDING_REVIEW("pending-review"), - IN_REVIEW("in-review"), - TWILIO_REJECTED("twilio-rejected"), - TWILIO_APPROVED("twilio-approved"); - private final String value; - - private Status(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static Status forValue(final String value) { - return Promoter.enumFromString(value, Status.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/trusthub/v1/TrustProductsCreator.java b/src/main/java/com/twilio/rest/trusthub/v1/TrustProductsCreator.java index 2e30e7c64a..7bff9e4b01 100644 --- a/src/main/java/com/twilio/rest/trusthub/v1/TrustProductsCreator.java +++ b/src/main/java/com/twilio/rest/trusthub/v1/TrustProductsCreator.java @@ -14,9 +14,11 @@ package com.twilio.rest.trusthub.v1; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; -import com.twilio.converter.Promoter; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,7 +27,7 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -import java.net.URI; + import java.net.URI; public class TrustProductsCreator extends Creator { @@ -35,96 +37,90 @@ public class TrustProductsCreator extends Creator { private String policySid; private URI statusCallback; - public TrustProductsCreator( - final String friendlyName, - final String email, - final String policySid - ) { + public TrustProductsCreator(final String friendlyName, final String email, final String policySid) { this.friendlyName = friendlyName; this.email = email; this.policySid = policySid; } + public TrustProductsCreator setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + public TrustProductsCreator setEmail(final String email) { this.email = email; return this; } + public TrustProductsCreator setPolicySid(final String policySid) { this.policySid = policySid; return this; } + public TrustProductsCreator setStatusCallback(final URI statusCallback) { this.statusCallback = statusCallback; return this; } - public TrustProductsCreator setStatusCallback(final String statusCallback) { - return setStatusCallback(Promoter.uriFromString(statusCallback)); - } @Override public TrustProducts create(final TwilioRestClient client) { + String path = "/v1/TrustProducts"; - path = - path.replace( - "{" + "FriendlyName" + "}", - this.friendlyName.toString() - ); - path = path.replace("{" + "Email" + "}", this.email.toString()); - path = path.replace("{" + "PolicySid" + "}", this.policySid.toString()); Request request = new Request( - HttpMethod.POST, - Domains.TRUSTHUB.toString(), - path + HttpMethod.POST, + Domains.TRUSTHUB.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "TrustProducts creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("TrustProducts creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return TrustProducts.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return TrustProducts.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + if (email != null) { - request.addPostParam("Email", email); + Serializer.toString(request, "Email", email, ParameterType.URLENCODED); } + + if (policySid != null) { - request.addPostParam("PolicySid", policySid); + Serializer.toString(request, "PolicySid", policySid, ParameterType.URLENCODED); } + + if (statusCallback != null) { - request.addPostParam("StatusCallback", statusCallback.toString()); + Serializer.toString(request, "StatusCallback", statusCallback, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/trusthub/v1/TrustProductsDeleter.java b/src/main/java/com/twilio/rest/trusthub/v1/TrustProductsDeleter.java index bbae52b71b..3416f3ad3a 100644 --- a/src/main/java/com/twilio/rest/trusthub/v1/TrustProductsDeleter.java +++ b/src/main/java/com/twilio/rest/trusthub/v1/TrustProductsDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.trusthub.v1; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,40 +26,38 @@ public class TrustProductsDeleter extends Deleter { - private String pathSid; + private String pathsid; - public TrustProductsDeleter(final String pathSid) { - this.pathSid = pathSid; + public TrustProductsDeleter(final String pathsid) { + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/v1/TrustProducts/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.TRUSTHUB.toString(), - path + HttpMethod.DELETE, + Domains.TRUSTHUB.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "TrustProducts delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("TrustProducts delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/trusthub/v1/TrustProductsFetcher.java b/src/main/java/com/twilio/rest/trusthub/v1/TrustProductsFetcher.java index 97cb8e71de..ce78ae9a76 100644 --- a/src/main/java/com/twilio/rest/trusthub/v1/TrustProductsFetcher.java +++ b/src/main/java/com/twilio/rest/trusthub/v1/TrustProductsFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.trusthub.v1; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,47 +26,41 @@ public class TrustProductsFetcher extends Fetcher { - private String pathSid; + private String pathsid; - public TrustProductsFetcher(final String pathSid) { - this.pathSid = pathSid; + public TrustProductsFetcher(final String pathsid) { + this.pathsid = pathsid; } + @Override public TrustProducts fetch(final TwilioRestClient client) { + String path = "/v1/TrustProducts/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.TRUSTHUB.toString(), - path + HttpMethod.GET, + Domains.TRUSTHUB.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "TrustProducts fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("TrustProducts fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return TrustProducts.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return TrustProducts.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/trusthub/v1/TrustProductsReader.java b/src/main/java/com/twilio/rest/trusthub/v1/TrustProductsReader.java index b5c1e5892c..fbb0340b58 100644 --- a/src/main/java/com/twilio/rest/trusthub/v1/TrustProductsReader.java +++ b/src/main/java/com/twilio/rest/trusthub/v1/TrustProductsReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -34,129 +35,116 @@ public class TrustProductsReader extends Reader { private String policySid; private Long pageSize; - public TrustProductsReader() {} + public TrustProductsReader() { + } + public TrustProductsReader setStatus(final TrustProducts.Status status) { this.status = status; return this; } + public TrustProductsReader setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + public TrustProductsReader setPolicySid(final String policySid) { this.policySid = policySid; return this; } + public TrustProductsReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v1/TrustProducts"; + Request request = new Request( - HttpMethod.GET, - Domains.TRUSTHUB.toString(), - path + HttpMethod.GET, + Domains.TRUSTHUB.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "TrustProducts read failed: Unable to connect to server" - ); + throw new ApiConnectionException("TrustProducts read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "results", - response.getContent(), - TrustProducts.class, - client.getObjectMapper() - ); + "results", + response.getContent(), + TrustProducts.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.TRUSTHUB.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.TRUSTHUB.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (status != null) { - request.addQueryParam("Status", status.toString()); + Serializer.toString(request, "Status", status, ParameterType.QUERY); } + + if (friendlyName != null) { - request.addQueryParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.QUERY); } + + if (policySid != null) { - request.addQueryParam("PolicySid", policySid); + Serializer.toString(request, "PolicySid", policySid, ParameterType.QUERY); } + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/trusthub/v1/TrustProductsUpdater.java b/src/main/java/com/twilio/rest/trusthub/v1/TrustProductsUpdater.java index b17a089f87..a54dc38c2a 100644 --- a/src/main/java/com/twilio/rest/trusthub/v1/TrustProductsUpdater.java +++ b/src/main/java/com/twilio/rest/trusthub/v1/TrustProductsUpdater.java @@ -16,7 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; -import com.twilio.converter.Promoter; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,94 +26,100 @@ import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; + import java.net.URI; public class TrustProductsUpdater extends Updater { - - private String pathSid; + private String pathsid; private TrustProducts.Status status; private URI statusCallback; private String friendlyName; private String email; - public TrustProductsUpdater(final String pathSid) { - this.pathSid = pathSid; + public TrustProductsUpdater(final String pathsid) { + this.pathsid = pathsid; } + public TrustProductsUpdater setStatus(final TrustProducts.Status status) { this.status = status; return this; } + public TrustProductsUpdater setStatusCallback(final URI statusCallback) { this.statusCallback = statusCallback; return this; } - public TrustProductsUpdater setStatusCallback(final String statusCallback) { - return setStatusCallback(Promoter.uriFromString(statusCallback)); - } public TrustProductsUpdater setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + public TrustProductsUpdater setEmail(final String email) { this.email = email; return this; } + @Override public TrustProducts update(final TwilioRestClient client) { + String path = "/v1/TrustProducts/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.TRUSTHUB.toString(), - path + HttpMethod.POST, + Domains.TRUSTHUB.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "TrustProducts update failed: Unable to connect to server" - ); + throw new ApiConnectionException("TrustProducts update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return TrustProducts.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return TrustProducts.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (status != null) { - request.addPostParam("Status", status.toString()); + Serializer.toString(request, "Status", status, ParameterType.URLENCODED); } + + if (statusCallback != null) { - request.addPostParam("StatusCallback", statusCallback.toString()); + Serializer.toString(request, "StatusCallback", statusCallback, ParameterType.URLENCODED); } + + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + if (email != null) { - request.addPostParam("Email", email); + Serializer.toString(request, "Email", email, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/trusthub/v1/customerprofiles/CustomerProfilesChannelEndpointAssignment.java b/src/main/java/com/twilio/rest/trusthub/v1/customerprofiles/CustomerProfilesChannelEndpointAssignment.java index dc153515de..8712c07699 100644 --- a/src/main/java/com/twilio/rest/trusthub/v1/customerprofiles/CustomerProfilesChannelEndpointAssignment.java +++ b/src/main/java/com/twilio/rest/trusthub/v1/customerprofiles/CustomerProfilesChannelEndpointAssignment.java @@ -18,83 +18,66 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class CustomerProfilesChannelEndpointAssignment extends Resource { - private static final long serialVersionUID = 18267773562551L; - public static CustomerProfilesChannelEndpointAssignmentCreator creator( - final String pathCustomerProfileSid, - final String channelEndpointType, - final String channelEndpointSid - ) { + public static CustomerProfilesChannelEndpointAssignmentCreator creator(final String pathcustomerProfileSid, final String channelEndpointType, final String channelEndpointSid) { return new CustomerProfilesChannelEndpointAssignmentCreator( - pathCustomerProfileSid, - channelEndpointType, - channelEndpointSid + pathcustomerProfileSid, channelEndpointType, channelEndpointSid ); } - public static CustomerProfilesChannelEndpointAssignmentDeleter deleter( - final String pathCustomerProfileSid, - final String pathSid - ) { + + public static CustomerProfilesChannelEndpointAssignmentDeleter deleter(final String pathcustomerProfileSid, final String pathsid) { return new CustomerProfilesChannelEndpointAssignmentDeleter( - pathCustomerProfileSid, - pathSid + pathcustomerProfileSid, pathsid ); } - public static CustomerProfilesChannelEndpointAssignmentFetcher fetcher( - final String pathCustomerProfileSid, - final String pathSid - ) { + + public static CustomerProfilesChannelEndpointAssignmentFetcher fetcher(final String pathcustomerProfileSid, final String pathsid) { return new CustomerProfilesChannelEndpointAssignmentFetcher( - pathCustomerProfileSid, - pathSid + pathcustomerProfileSid, pathsid ); } - public static CustomerProfilesChannelEndpointAssignmentReader reader( - final String pathCustomerProfileSid - ) { + + public static CustomerProfilesChannelEndpointAssignmentReader reader(final String pathcustomerProfileSid) { return new CustomerProfilesChannelEndpointAssignmentReader( - pathCustomerProfileSid + pathcustomerProfileSid ); } + /** * Converts a JSON String into a CustomerProfilesChannelEndpointAssignment object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return CustomerProfilesChannelEndpointAssignment object represented by the provided JSON */ - public static CustomerProfilesChannelEndpointAssignment fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static CustomerProfilesChannelEndpointAssignment fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { - return objectMapper.readValue( - json, - CustomerProfilesChannelEndpointAssignment.class - ); + return objectMapper.readValue(json, CustomerProfilesChannelEndpointAssignment.class); } catch (final JsonMappingException | JsonParseException e) { throw new ApiException(e.getMessage(), e); } catch (final IOException e) { @@ -106,20 +89,14 @@ public static CustomerProfilesChannelEndpointAssignment fromJson( * Converts a JSON InputStream into a CustomerProfilesChannelEndpointAssignment object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return CustomerProfilesChannelEndpointAssignment object represented by the provided JSON */ - public static CustomerProfilesChannelEndpointAssignment fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static CustomerProfilesChannelEndpointAssignment fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { - return objectMapper.readValue( - json, - CustomerProfilesChannelEndpointAssignment.class - ); + return objectMapper.readValue(json, CustomerProfilesChannelEndpointAssignment.class); } catch (final JsonMappingException | JsonParseException e) { throw new ApiException(e.getMessage(), e); } catch (final IOException e) { @@ -127,61 +104,54 @@ public static CustomerProfilesChannelEndpointAssignment fromJson( } } - private final String sid; - private final String customerProfileSid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String channelEndpointType; + @Getter private final String channelEndpointSid; + @Getter + private final String channelEndpointType; + @Getter + private final String customerProfileSid; + @Getter private final ZonedDateTime dateCreated; + @Getter + private final String sid; + @Getter private final URI url; @JsonCreator private CustomerProfilesChannelEndpointAssignment( - @JsonProperty("sid") final String sid, - @JsonProperty("customer_profile_sid") final String customerProfileSid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("channel_endpoint_type") final String channelEndpointType, - @JsonProperty("channel_endpoint_sid") final String channelEndpointSid, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("url") final URI url + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("channel_endpoint_sid") final String channelEndpointSid, + @JsonProperty("channel_endpoint_type") final String channelEndpointType, + @JsonProperty("customer_profile_sid") final String customerProfileSid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("sid") final String sid, + @JsonProperty("url") final URI url ) { - this.sid = sid; - this.customerProfileSid = customerProfileSid; this.accountSid = accountSid; - this.channelEndpointType = channelEndpointType; this.channelEndpointSid = channelEndpointSid; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); + this.channelEndpointType = channelEndpointType; + this.customerProfileSid = customerProfileSid; + this.dateCreated = dateCreated; + this.sid = sid; this.url = url; } - public final String getSid() { - return this.sid; - } - - public final String getCustomerProfileSid() { - return this.customerProfileSid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getChannelEndpointType() { - return this.channelEndpointType; - } - - public final String getChannelEndpointSid() { - return this.channelEndpointSid; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final URI getUrl() { - return this.url; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -192,30 +162,31 @@ public boolean equals(final Object o) { return false; } - CustomerProfilesChannelEndpointAssignment other = - (CustomerProfilesChannelEndpointAssignment) o; - + CustomerProfilesChannelEndpointAssignment other = (CustomerProfilesChannelEndpointAssignment) o; return ( - Objects.equals(sid, other.sid) && - Objects.equals(customerProfileSid, other.customerProfileSid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(channelEndpointType, other.channelEndpointType) && - Objects.equals(channelEndpointSid, other.channelEndpointSid) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(url, other.url) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(channelEndpointSid, other.channelEndpointSid) && + Objects.equals(channelEndpointType, other.channelEndpointType) && + Objects.equals(customerProfileSid, other.customerProfileSid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(sid, other.sid) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - sid, - customerProfileSid, - accountSid, - channelEndpointType, - channelEndpointSid, - dateCreated, - url + accountSid, + channelEndpointSid, + channelEndpointType, + customerProfileSid, + dateCreated, + sid, + url ); } + + } + diff --git a/src/main/java/com/twilio/rest/trusthub/v1/customerprofiles/CustomerProfilesChannelEndpointAssignmentCreator.java b/src/main/java/com/twilio/rest/trusthub/v1/customerprofiles/CustomerProfilesChannelEndpointAssignmentCreator.java index 170a472215..41ad8d25d0 100644 --- a/src/main/java/com/twilio/rest/trusthub/v1/customerprofiles/CustomerProfilesChannelEndpointAssignmentCreator.java +++ b/src/main/java/com/twilio/rest/trusthub/v1/customerprofiles/CustomerProfilesChannelEndpointAssignmentCreator.java @@ -14,8 +14,11 @@ package com.twilio.rest.trusthub.v1.customerprofiles; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,98 +28,76 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class CustomerProfilesChannelEndpointAssignmentCreator - extends Creator { +public class CustomerProfilesChannelEndpointAssignmentCreator extends Creator { - private String pathCustomerProfileSid; + private String pathcustomerProfileSid; private String channelEndpointType; private String channelEndpointSid; - public CustomerProfilesChannelEndpointAssignmentCreator( - final String pathCustomerProfileSid, - final String channelEndpointType, - final String channelEndpointSid - ) { - this.pathCustomerProfileSid = pathCustomerProfileSid; + public CustomerProfilesChannelEndpointAssignmentCreator(final String pathcustomerProfileSid, final String channelEndpointType, final String channelEndpointSid) { + this.pathcustomerProfileSid = pathcustomerProfileSid; this.channelEndpointType = channelEndpointType; this.channelEndpointSid = channelEndpointSid; } - public CustomerProfilesChannelEndpointAssignmentCreator setChannelEndpointType( - final String channelEndpointType - ) { + + public CustomerProfilesChannelEndpointAssignmentCreator setChannelEndpointType(final String channelEndpointType) { this.channelEndpointType = channelEndpointType; return this; } - public CustomerProfilesChannelEndpointAssignmentCreator setChannelEndpointSid( - final String channelEndpointSid - ) { + + public CustomerProfilesChannelEndpointAssignmentCreator setChannelEndpointSid(final String channelEndpointSid) { this.channelEndpointSid = channelEndpointSid; return this; } + @Override - public CustomerProfilesChannelEndpointAssignment create( - final TwilioRestClient client - ) { - String path = - "/v1/CustomerProfiles/{CustomerProfileSid}/ChannelEndpointAssignments"; - - path = - path.replace( - "{" + "CustomerProfileSid" + "}", - this.pathCustomerProfileSid.toString() - ); - path = - path.replace( - "{" + "ChannelEndpointType" + "}", - this.channelEndpointType.toString() - ); - path = - path.replace( - "{" + "ChannelEndpointSid" + "}", - this.channelEndpointSid.toString() - ); + public CustomerProfilesChannelEndpointAssignment create(final TwilioRestClient client) { + + String path = "/v1/CustomerProfiles/{CustomerProfileSid}/ChannelEndpointAssignments"; + + path = path.replace("{" + "CustomerProfileSid" + "}", this.pathcustomerProfileSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.TRUSTHUB.toString(), - path + HttpMethod.POST, + Domains.TRUSTHUB.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "CustomerProfilesChannelEndpointAssignment creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("CustomerProfilesChannelEndpointAssignment creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return CustomerProfilesChannelEndpointAssignment.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return CustomerProfilesChannelEndpointAssignment.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (channelEndpointType != null) { - request.addPostParam("ChannelEndpointType", channelEndpointType); + Serializer.toString(request, "ChannelEndpointType", channelEndpointType, ParameterType.URLENCODED); } + + if (channelEndpointSid != null) { - request.addPostParam("ChannelEndpointSid", channelEndpointSid); + Serializer.toString(request, "ChannelEndpointSid", channelEndpointSid, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/trusthub/v1/customerprofiles/CustomerProfilesChannelEndpointAssignmentDeleter.java b/src/main/java/com/twilio/rest/trusthub/v1/customerprofiles/CustomerProfilesChannelEndpointAssignmentDeleter.java index 20153ee1a1..97fc38b27a 100644 --- a/src/main/java/com/twilio/rest/trusthub/v1/customerprofiles/CustomerProfilesChannelEndpointAssignmentDeleter.java +++ b/src/main/java/com/twilio/rest/trusthub/v1/customerprofiles/CustomerProfilesChannelEndpointAssignmentDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.trusthub.v1.customerprofiles; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,54 +24,43 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class CustomerProfilesChannelEndpointAssignmentDeleter - extends Deleter { +public class CustomerProfilesChannelEndpointAssignmentDeleter extends Deleter { - private String pathCustomerProfileSid; - private String pathSid; + private String pathcustomerProfileSid; + private String pathsid; - public CustomerProfilesChannelEndpointAssignmentDeleter( - final String pathCustomerProfileSid, - final String pathSid - ) { - this.pathCustomerProfileSid = pathCustomerProfileSid; - this.pathSid = pathSid; + public CustomerProfilesChannelEndpointAssignmentDeleter(final String pathcustomerProfileSid, final String pathsid) { + this.pathcustomerProfileSid = pathcustomerProfileSid; + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { - String path = - "/v1/CustomerProfiles/{CustomerProfileSid}/ChannelEndpointAssignments/{Sid}"; - path = - path.replace( - "{" + "CustomerProfileSid" + "}", - this.pathCustomerProfileSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/v1/CustomerProfiles/{CustomerProfileSid}/ChannelEndpointAssignments/{Sid}"; + + path = path.replace("{" + "CustomerProfileSid" + "}", this.pathcustomerProfileSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.TRUSTHUB.toString(), - path + HttpMethod.DELETE, + Domains.TRUSTHUB.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "CustomerProfilesChannelEndpointAssignment delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("CustomerProfilesChannelEndpointAssignment delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/trusthub/v1/customerprofiles/CustomerProfilesChannelEndpointAssignmentFetcher.java b/src/main/java/com/twilio/rest/trusthub/v1/customerprofiles/CustomerProfilesChannelEndpointAssignmentFetcher.java index 85e31693ed..76e5ae0195 100644 --- a/src/main/java/com/twilio/rest/trusthub/v1/customerprofiles/CustomerProfilesChannelEndpointAssignmentFetcher.java +++ b/src/main/java/com/twilio/rest/trusthub/v1/customerprofiles/CustomerProfilesChannelEndpointAssignmentFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.trusthub.v1.customerprofiles; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,63 +24,46 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class CustomerProfilesChannelEndpointAssignmentFetcher - extends Fetcher { +public class CustomerProfilesChannelEndpointAssignmentFetcher extends Fetcher { - private String pathCustomerProfileSid; - private String pathSid; + private String pathcustomerProfileSid; + private String pathsid; - public CustomerProfilesChannelEndpointAssignmentFetcher( - final String pathCustomerProfileSid, - final String pathSid - ) { - this.pathCustomerProfileSid = pathCustomerProfileSid; - this.pathSid = pathSid; + public CustomerProfilesChannelEndpointAssignmentFetcher(final String pathcustomerProfileSid, final String pathsid) { + this.pathcustomerProfileSid = pathcustomerProfileSid; + this.pathsid = pathsid; } + @Override - public CustomerProfilesChannelEndpointAssignment fetch( - final TwilioRestClient client - ) { - String path = - "/v1/CustomerProfiles/{CustomerProfileSid}/ChannelEndpointAssignments/{Sid}"; + public CustomerProfilesChannelEndpointAssignment fetch(final TwilioRestClient client) { + + String path = "/v1/CustomerProfiles/{CustomerProfileSid}/ChannelEndpointAssignments/{Sid}"; + + path = path.replace("{" + "CustomerProfileSid" + "}", this.pathcustomerProfileSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); - path = - path.replace( - "{" + "CustomerProfileSid" + "}", - this.pathCustomerProfileSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.TRUSTHUB.toString(), - path + HttpMethod.GET, + Domains.TRUSTHUB.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "CustomerProfilesChannelEndpointAssignment fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("CustomerProfilesChannelEndpointAssignment fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return CustomerProfilesChannelEndpointAssignment.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return CustomerProfilesChannelEndpointAssignment.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/trusthub/v1/customerprofiles/CustomerProfilesChannelEndpointAssignmentReader.java b/src/main/java/com/twilio/rest/trusthub/v1/customerprofiles/CustomerProfilesChannelEndpointAssignmentReader.java index 6910d3b560..f8381b039c 100644 --- a/src/main/java/com/twilio/rest/trusthub/v1/customerprofiles/CustomerProfilesChannelEndpointAssignmentReader.java +++ b/src/main/java/com/twilio/rest/trusthub/v1/customerprofiles/CustomerProfilesChannelEndpointAssignmentReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,149 +28,114 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class CustomerProfilesChannelEndpointAssignmentReader - extends Reader { +public class CustomerProfilesChannelEndpointAssignmentReader extends Reader { - private String pathCustomerProfileSid; + private String pathcustomerProfileSid; private String channelEndpointSid; private String channelEndpointSids; private Long pageSize; - public CustomerProfilesChannelEndpointAssignmentReader( - final String pathCustomerProfileSid - ) { - this.pathCustomerProfileSid = pathCustomerProfileSid; + public CustomerProfilesChannelEndpointAssignmentReader(final String pathcustomerProfileSid) { + this.pathcustomerProfileSid = pathcustomerProfileSid; } - public CustomerProfilesChannelEndpointAssignmentReader setChannelEndpointSid( - final String channelEndpointSid - ) { + + public CustomerProfilesChannelEndpointAssignmentReader setChannelEndpointSid(final String channelEndpointSid) { this.channelEndpointSid = channelEndpointSid; return this; } - public CustomerProfilesChannelEndpointAssignmentReader setChannelEndpointSids( - final String channelEndpointSids - ) { + + public CustomerProfilesChannelEndpointAssignmentReader setChannelEndpointSids(final String channelEndpointSids) { this.channelEndpointSids = channelEndpointSids; return this; } - public CustomerProfilesChannelEndpointAssignmentReader setPageSize( - final Long pageSize - ) { + + public CustomerProfilesChannelEndpointAssignmentReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override - public ResourceSet read( - final TwilioRestClient client - ) { + public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } - public Page firstPage( - final TwilioRestClient client - ) { - String path = - "/v1/CustomerProfiles/{CustomerProfileSid}/ChannelEndpointAssignments"; - path = - path.replace( - "{" + "CustomerProfileSid" + "}", - this.pathCustomerProfileSid.toString() - ); + public Page firstPage(final TwilioRestClient client) { + + String path = "/v1/CustomerProfiles/{CustomerProfileSid}/ChannelEndpointAssignments"; + + path = path.replace("{" + "CustomerProfileSid" + "}", this.pathcustomerProfileSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.TRUSTHUB.toString(), - path + HttpMethod.GET, + Domains.TRUSTHUB.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "CustomerProfilesChannelEndpointAssignment read failed: Unable to connect to server" - ); + throw new ApiConnectionException("CustomerProfilesChannelEndpointAssignment read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "results", - response.getContent(), - CustomerProfilesChannelEndpointAssignment.class, - client.getObjectMapper() - ); + "results", + response.getContent(), + CustomerProfilesChannelEndpointAssignment.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.TRUSTHUB.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.TRUSTHUB.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (channelEndpointSid != null) { - request.addQueryParam("ChannelEndpointSid", channelEndpointSid); + Serializer.toString(request, "ChannelEndpointSid", channelEndpointSid, ParameterType.QUERY); } + + if (channelEndpointSids != null) { - request.addQueryParam("ChannelEndpointSids", channelEndpointSids); + Serializer.toString(request, "ChannelEndpointSids", channelEndpointSids, ParameterType.QUERY); } + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/trusthub/v1/customerprofiles/CustomerProfilesEntityAssignments.java b/src/main/java/com/twilio/rest/trusthub/v1/customerprofiles/CustomerProfilesEntityAssignments.java index 144f6b10ee..a7082a16ee 100644 --- a/src/main/java/com/twilio/rest/trusthub/v1/customerprofiles/CustomerProfilesEntityAssignments.java +++ b/src/main/java/com/twilio/rest/trusthub/v1/customerprofiles/CustomerProfilesEntityAssignments.java @@ -18,81 +18,66 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class CustomerProfilesEntityAssignments extends Resource { - private static final long serialVersionUID = 178139363614511L; - public static CustomerProfilesEntityAssignmentsCreator creator( - final String pathCustomerProfileSid, - final String objectSid - ) { + public static CustomerProfilesEntityAssignmentsCreator creator(final String pathcustomerProfileSid, final String objectSid) { return new CustomerProfilesEntityAssignmentsCreator( - pathCustomerProfileSid, - objectSid + pathcustomerProfileSid, objectSid ); } - public static CustomerProfilesEntityAssignmentsDeleter deleter( - final String pathCustomerProfileSid, - final String pathSid - ) { + + public static CustomerProfilesEntityAssignmentsDeleter deleter(final String pathcustomerProfileSid, final String pathsid) { return new CustomerProfilesEntityAssignmentsDeleter( - pathCustomerProfileSid, - pathSid + pathcustomerProfileSid, pathsid ); } - public static CustomerProfilesEntityAssignmentsFetcher fetcher( - final String pathCustomerProfileSid, - final String pathSid - ) { + + public static CustomerProfilesEntityAssignmentsFetcher fetcher(final String pathcustomerProfileSid, final String pathsid) { return new CustomerProfilesEntityAssignmentsFetcher( - pathCustomerProfileSid, - pathSid + pathcustomerProfileSid, pathsid ); } - public static CustomerProfilesEntityAssignmentsReader reader( - final String pathCustomerProfileSid - ) { + + public static CustomerProfilesEntityAssignmentsReader reader(final String pathcustomerProfileSid) { return new CustomerProfilesEntityAssignmentsReader( - pathCustomerProfileSid + pathcustomerProfileSid ); } + /** * Converts a JSON String into a CustomerProfilesEntityAssignments object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return CustomerProfilesEntityAssignments object represented by the provided JSON */ - public static CustomerProfilesEntityAssignments fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static CustomerProfilesEntityAssignments fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { - return objectMapper.readValue( - json, - CustomerProfilesEntityAssignments.class - ); + return objectMapper.readValue(json, CustomerProfilesEntityAssignments.class); } catch (final JsonMappingException | JsonParseException e) { throw new ApiException(e.getMessage(), e); } catch (final IOException e) { @@ -104,20 +89,14 @@ public static CustomerProfilesEntityAssignments fromJson( * Converts a JSON InputStream into a CustomerProfilesEntityAssignments object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return CustomerProfilesEntityAssignments object represented by the provided JSON */ - public static CustomerProfilesEntityAssignments fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static CustomerProfilesEntityAssignments fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { - return objectMapper.readValue( - json, - CustomerProfilesEntityAssignments.class - ); + return objectMapper.readValue(json, CustomerProfilesEntityAssignments.class); } catch (final JsonMappingException | JsonParseException e) { throw new ApiException(e.getMessage(), e); } catch (final IOException e) { @@ -125,54 +104,50 @@ public static CustomerProfilesEntityAssignments fromJson( } } - private final String sid; - private final String customerProfileSid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String objectSid; + @Getter + private final String customerProfileSid; + @Getter private final ZonedDateTime dateCreated; + @Getter + private final String objectSid; + @Getter + private final String sid; + @Getter private final URI url; @JsonCreator private CustomerProfilesEntityAssignments( - @JsonProperty("sid") final String sid, - @JsonProperty("customer_profile_sid") final String customerProfileSid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("object_sid") final String objectSid, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("url") final URI url + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("customer_profile_sid") final String customerProfileSid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("object_sid") final String objectSid, + @JsonProperty("sid") final String sid, + @JsonProperty("url") final URI url ) { - this.sid = sid; - this.customerProfileSid = customerProfileSid; this.accountSid = accountSid; + this.customerProfileSid = customerProfileSid; + this.dateCreated = dateCreated; this.objectSid = objectSid; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); + this.sid = sid; this.url = url; } - public final String getSid() { - return this.sid; - } - - public final String getCustomerProfileSid() { - return this.customerProfileSid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getObjectSid() { - return this.objectSid; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final URI getUrl() { - return this.url; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -183,28 +158,29 @@ public boolean equals(final Object o) { return false; } - CustomerProfilesEntityAssignments other = - (CustomerProfilesEntityAssignments) o; - + CustomerProfilesEntityAssignments other = (CustomerProfilesEntityAssignments) o; return ( - Objects.equals(sid, other.sid) && - Objects.equals(customerProfileSid, other.customerProfileSid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(objectSid, other.objectSid) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(url, other.url) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(customerProfileSid, other.customerProfileSid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(objectSid, other.objectSid) && + Objects.equals(sid, other.sid) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - sid, - customerProfileSid, - accountSid, - objectSid, - dateCreated, - url + accountSid, + customerProfileSid, + dateCreated, + objectSid, + sid, + url ); } + + } + diff --git a/src/main/java/com/twilio/rest/trusthub/v1/customerprofiles/CustomerProfilesEntityAssignmentsCreator.java b/src/main/java/com/twilio/rest/trusthub/v1/customerprofiles/CustomerProfilesEntityAssignmentsCreator.java index 4bac719554..77df86c918 100644 --- a/src/main/java/com/twilio/rest/trusthub/v1/customerprofiles/CustomerProfilesEntityAssignmentsCreator.java +++ b/src/main/java/com/twilio/rest/trusthub/v1/customerprofiles/CustomerProfilesEntityAssignmentsCreator.java @@ -14,8 +14,11 @@ package com.twilio.rest.trusthub.v1.customerprofiles; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,76 +28,63 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class CustomerProfilesEntityAssignmentsCreator - extends Creator { +public class CustomerProfilesEntityAssignmentsCreator extends Creator { - private String pathCustomerProfileSid; + private String pathcustomerProfileSid; private String objectSid; - public CustomerProfilesEntityAssignmentsCreator( - final String pathCustomerProfileSid, - final String objectSid - ) { - this.pathCustomerProfileSid = pathCustomerProfileSid; + public CustomerProfilesEntityAssignmentsCreator(final String pathcustomerProfileSid, final String objectSid) { + this.pathcustomerProfileSid = pathcustomerProfileSid; this.objectSid = objectSid; } - public CustomerProfilesEntityAssignmentsCreator setObjectSid( - final String objectSid - ) { + + public CustomerProfilesEntityAssignmentsCreator setObjectSid(final String objectSid) { this.objectSid = objectSid; return this; } + @Override - public CustomerProfilesEntityAssignments create( - final TwilioRestClient client - ) { - String path = - "/v1/CustomerProfiles/{CustomerProfileSid}/EntityAssignments"; - - path = - path.replace( - "{" + "CustomerProfileSid" + "}", - this.pathCustomerProfileSid.toString() - ); - path = path.replace("{" + "ObjectSid" + "}", this.objectSid.toString()); + public CustomerProfilesEntityAssignments create(final TwilioRestClient client) { + + String path = "/v1/CustomerProfiles/{CustomerProfileSid}/EntityAssignments"; + + path = path.replace("{" + "CustomerProfileSid" + "}", this.pathcustomerProfileSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.TRUSTHUB.toString(), - path + HttpMethod.POST, + Domains.TRUSTHUB.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "CustomerProfilesEntityAssignments creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("CustomerProfilesEntityAssignments creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return CustomerProfilesEntityAssignments.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return CustomerProfilesEntityAssignments.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (objectSid != null) { - request.addPostParam("ObjectSid", objectSid); + Serializer.toString(request, "ObjectSid", objectSid, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/trusthub/v1/customerprofiles/CustomerProfilesEntityAssignmentsDeleter.java b/src/main/java/com/twilio/rest/trusthub/v1/customerprofiles/CustomerProfilesEntityAssignmentsDeleter.java index f8a436088c..cb43100625 100644 --- a/src/main/java/com/twilio/rest/trusthub/v1/customerprofiles/CustomerProfilesEntityAssignmentsDeleter.java +++ b/src/main/java/com/twilio/rest/trusthub/v1/customerprofiles/CustomerProfilesEntityAssignmentsDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.trusthub.v1.customerprofiles; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,54 +24,43 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class CustomerProfilesEntityAssignmentsDeleter - extends Deleter { +public class CustomerProfilesEntityAssignmentsDeleter extends Deleter { - private String pathCustomerProfileSid; - private String pathSid; + private String pathcustomerProfileSid; + private String pathsid; - public CustomerProfilesEntityAssignmentsDeleter( - final String pathCustomerProfileSid, - final String pathSid - ) { - this.pathCustomerProfileSid = pathCustomerProfileSid; - this.pathSid = pathSid; + public CustomerProfilesEntityAssignmentsDeleter(final String pathcustomerProfileSid, final String pathsid) { + this.pathcustomerProfileSid = pathcustomerProfileSid; + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { - String path = - "/v1/CustomerProfiles/{CustomerProfileSid}/EntityAssignments/{Sid}"; - path = - path.replace( - "{" + "CustomerProfileSid" + "}", - this.pathCustomerProfileSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/v1/CustomerProfiles/{CustomerProfileSid}/EntityAssignments/{Sid}"; + + path = path.replace("{" + "CustomerProfileSid" + "}", this.pathcustomerProfileSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.TRUSTHUB.toString(), - path + HttpMethod.DELETE, + Domains.TRUSTHUB.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "CustomerProfilesEntityAssignments delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("CustomerProfilesEntityAssignments delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/trusthub/v1/customerprofiles/CustomerProfilesEntityAssignmentsFetcher.java b/src/main/java/com/twilio/rest/trusthub/v1/customerprofiles/CustomerProfilesEntityAssignmentsFetcher.java index 848704a5fe..bc8e90958a 100644 --- a/src/main/java/com/twilio/rest/trusthub/v1/customerprofiles/CustomerProfilesEntityAssignmentsFetcher.java +++ b/src/main/java/com/twilio/rest/trusthub/v1/customerprofiles/CustomerProfilesEntityAssignmentsFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.trusthub.v1.customerprofiles; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,63 +24,46 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class CustomerProfilesEntityAssignmentsFetcher - extends Fetcher { +public class CustomerProfilesEntityAssignmentsFetcher extends Fetcher { - private String pathCustomerProfileSid; - private String pathSid; + private String pathcustomerProfileSid; + private String pathsid; - public CustomerProfilesEntityAssignmentsFetcher( - final String pathCustomerProfileSid, - final String pathSid - ) { - this.pathCustomerProfileSid = pathCustomerProfileSid; - this.pathSid = pathSid; + public CustomerProfilesEntityAssignmentsFetcher(final String pathcustomerProfileSid, final String pathsid) { + this.pathcustomerProfileSid = pathcustomerProfileSid; + this.pathsid = pathsid; } + @Override - public CustomerProfilesEntityAssignments fetch( - final TwilioRestClient client - ) { - String path = - "/v1/CustomerProfiles/{CustomerProfileSid}/EntityAssignments/{Sid}"; + public CustomerProfilesEntityAssignments fetch(final TwilioRestClient client) { + + String path = "/v1/CustomerProfiles/{CustomerProfileSid}/EntityAssignments/{Sid}"; + + path = path.replace("{" + "CustomerProfileSid" + "}", this.pathcustomerProfileSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); - path = - path.replace( - "{" + "CustomerProfileSid" + "}", - this.pathCustomerProfileSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.TRUSTHUB.toString(), - path + HttpMethod.GET, + Domains.TRUSTHUB.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "CustomerProfilesEntityAssignments fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("CustomerProfilesEntityAssignments fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return CustomerProfilesEntityAssignments.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return CustomerProfilesEntityAssignments.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/trusthub/v1/customerprofiles/CustomerProfilesEntityAssignmentsReader.java b/src/main/java/com/twilio/rest/trusthub/v1/customerprofiles/CustomerProfilesEntityAssignmentsReader.java index 4bdfdc3d97..6de2b1140b 100644 --- a/src/main/java/com/twilio/rest/trusthub/v1/customerprofiles/CustomerProfilesEntityAssignmentsReader.java +++ b/src/main/java/com/twilio/rest/trusthub/v1/customerprofiles/CustomerProfilesEntityAssignmentsReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,138 +28,102 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class CustomerProfilesEntityAssignmentsReader - extends Reader { +public class CustomerProfilesEntityAssignmentsReader extends Reader { - private String pathCustomerProfileSid; + private String pathcustomerProfileSid; private String objectType; private Long pageSize; - public CustomerProfilesEntityAssignmentsReader( - final String pathCustomerProfileSid - ) { - this.pathCustomerProfileSid = pathCustomerProfileSid; + public CustomerProfilesEntityAssignmentsReader(final String pathcustomerProfileSid) { + this.pathcustomerProfileSid = pathcustomerProfileSid; } - public CustomerProfilesEntityAssignmentsReader setObjectType( - final String objectType - ) { + + public CustomerProfilesEntityAssignmentsReader setObjectType(final String objectType) { this.objectType = objectType; return this; } - public CustomerProfilesEntityAssignmentsReader setPageSize( - final Long pageSize - ) { + + public CustomerProfilesEntityAssignmentsReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override - public ResourceSet read( - final TwilioRestClient client - ) { + public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } - public Page firstPage( - final TwilioRestClient client - ) { - String path = - "/v1/CustomerProfiles/{CustomerProfileSid}/EntityAssignments"; - path = - path.replace( - "{" + "CustomerProfileSid" + "}", - this.pathCustomerProfileSid.toString() - ); + public Page firstPage(final TwilioRestClient client) { + + String path = "/v1/CustomerProfiles/{CustomerProfileSid}/EntityAssignments"; + + path = path.replace("{" + "CustomerProfileSid" + "}", this.pathcustomerProfileSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.TRUSTHUB.toString(), - path + HttpMethod.GET, + Domains.TRUSTHUB.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "CustomerProfilesEntityAssignments read failed: Unable to connect to server" - ); + throw new ApiConnectionException("CustomerProfilesEntityAssignments read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "results", - response.getContent(), - CustomerProfilesEntityAssignments.class, - client.getObjectMapper() - ); + "results", + response.getContent(), + CustomerProfilesEntityAssignments.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.TRUSTHUB.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.TRUSTHUB.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (objectType != null) { - request.addQueryParam("ObjectType", objectType); + Serializer.toString(request, "ObjectType", objectType, ParameterType.QUERY); } + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/trusthub/v1/customerprofiles/CustomerProfilesEvaluations.java b/src/main/java/com/twilio/rest/trusthub/v1/customerprofiles/CustomerProfilesEvaluations.java index 27d0116ac0..d8f329d27e 100644 --- a/src/main/java/com/twilio/rest/trusthub/v1/customerprofiles/CustomerProfilesEvaluations.java +++ b/src/main/java/com/twilio/rest/trusthub/v1/customerprofiles/CustomerProfilesEvaluations.java @@ -18,73 +18,82 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.List; -import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class CustomerProfilesEvaluations extends Resource { - private static final long serialVersionUID = 45516903020077L; - public static CustomerProfilesEvaluationsCreator creator( - final String pathCustomerProfileSid, - final String policySid - ) { + public static CustomerProfilesEvaluationsCreator creator(final String pathcustomerProfileSid, final String policySid) { return new CustomerProfilesEvaluationsCreator( - pathCustomerProfileSid, - policySid + pathcustomerProfileSid, policySid ); } - public static CustomerProfilesEvaluationsFetcher fetcher( - final String pathCustomerProfileSid, - final String pathSid - ) { + + public static CustomerProfilesEvaluationsFetcher fetcher(final String pathcustomerProfileSid, final String pathsid) { return new CustomerProfilesEvaluationsFetcher( - pathCustomerProfileSid, - pathSid + pathcustomerProfileSid, pathsid ); } - public static CustomerProfilesEvaluationsReader reader( - final String pathCustomerProfileSid - ) { - return new CustomerProfilesEvaluationsReader(pathCustomerProfileSid); + + public static CustomerProfilesEvaluationsReader reader(final String pathcustomerProfileSid) { + return new CustomerProfilesEvaluationsReader( + pathcustomerProfileSid + ); + } + + + public enum Status { + COMPLIANT("compliant"), + NONCOMPLIANT("noncompliant"); + + private final String value; + + private Status(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static Status forValue(final String value) { + return Promoter.enumFromString(value, Status.values()); + } } + /** * Converts a JSON String into a CustomerProfilesEvaluations object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return CustomerProfilesEvaluations object represented by the provided JSON */ - public static CustomerProfilesEvaluations fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static CustomerProfilesEvaluations fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { - return objectMapper.readValue( - json, - CustomerProfilesEvaluations.class - ); + return objectMapper.readValue(json, CustomerProfilesEvaluations.class); } catch (final JsonMappingException | JsonParseException e) { throw new ApiException(e.getMessage(), e); } catch (final IOException e) { @@ -96,20 +105,14 @@ public static CustomerProfilesEvaluations fromJson( * Converts a JSON InputStream into a CustomerProfilesEvaluations object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return CustomerProfilesEvaluations object represented by the provided JSON */ - public static CustomerProfilesEvaluations fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static CustomerProfilesEvaluations fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { - return objectMapper.readValue( - json, - CustomerProfilesEvaluations.class - ); + return objectMapper.readValue(json, CustomerProfilesEvaluations.class); } catch (final JsonMappingException | JsonParseException e) { throw new ApiException(e.getMessage(), e); } catch (final IOException e) { @@ -117,68 +120,58 @@ public static CustomerProfilesEvaluations fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String policySid; + @Getter private final String customerProfileSid; - private final CustomerProfilesEvaluations.Status status; - private final List> results; + @Getter private final ZonedDateTime dateCreated; + @Getter + private final String policySid; + @Getter + private final List results; + @Getter + private final String sid; + @Getter + private final CustomerProfilesEvaluations.Status status; + @Getter private final URI url; @JsonCreator private CustomerProfilesEvaluations( - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("policy_sid") final String policySid, - @JsonProperty("customer_profile_sid") final String customerProfileSid, - @JsonProperty("status") final CustomerProfilesEvaluations.Status status, - @JsonProperty("results") final List> results, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("url") final URI url + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("customer_profile_sid") final String customerProfileSid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("policy_sid") final String policySid, + @JsonProperty("results") final List results, + @JsonProperty("sid") final String sid, + @JsonProperty("status") final CustomerProfilesEvaluations.Status status, + @JsonProperty("url") final URI url ) { - this.sid = sid; this.accountSid = accountSid; - this.policySid = policySid; this.customerProfileSid = customerProfileSid; - this.status = status; + this.dateCreated = dateCreated; + this.policySid = policySid; this.results = results; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); + this.sid = sid; + this.status = status; this.url = url; } - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getPolicySid() { - return this.policySid; - } - - public final String getCustomerProfileSid() { - return this.customerProfileSid; - } - - public final CustomerProfilesEvaluations.Status getStatus() { - return this.status; - } - - public final List> getResults() { - return this.results; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final URI getUrl() { - return this.url; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -190,50 +183,32 @@ public boolean equals(final Object o) { } CustomerProfilesEvaluations other = (CustomerProfilesEvaluations) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(policySid, other.policySid) && - Objects.equals(customerProfileSid, other.customerProfileSid) && - Objects.equals(status, other.status) && - Objects.equals(results, other.results) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(url, other.url) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(customerProfileSid, other.customerProfileSid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(policySid, other.policySid) && + Objects.equals(results, other.results) && + Objects.equals(sid, other.sid) && + Objects.equals(status, other.status) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - sid, - accountSid, - policySid, - customerProfileSid, - status, - results, - dateCreated, - url + accountSid, + customerProfileSid, + dateCreated, + policySid, + results, + sid, + status, + url ); } - public enum Status { - COMPLIANT("compliant"), - NONCOMPLIANT("noncompliant"); - - private final String value; - - private Status(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - @JsonCreator - public static Status forValue(final String value) { - return Promoter.enumFromString(value, Status.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/trusthub/v1/customerprofiles/CustomerProfilesEvaluationsCreator.java b/src/main/java/com/twilio/rest/trusthub/v1/customerprofiles/CustomerProfilesEvaluationsCreator.java index b5b5b364c0..e1ea33330b 100644 --- a/src/main/java/com/twilio/rest/trusthub/v1/customerprofiles/CustomerProfilesEvaluationsCreator.java +++ b/src/main/java/com/twilio/rest/trusthub/v1/customerprofiles/CustomerProfilesEvaluationsCreator.java @@ -14,8 +14,11 @@ package com.twilio.rest.trusthub.v1.customerprofiles; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,73 +28,63 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class CustomerProfilesEvaluationsCreator - extends Creator { +public class CustomerProfilesEvaluationsCreator extends Creator { - private String pathCustomerProfileSid; + private String pathcustomerProfileSid; private String policySid; - public CustomerProfilesEvaluationsCreator( - final String pathCustomerProfileSid, - final String policySid - ) { - this.pathCustomerProfileSid = pathCustomerProfileSid; + public CustomerProfilesEvaluationsCreator(final String pathcustomerProfileSid, final String policySid) { + this.pathcustomerProfileSid = pathcustomerProfileSid; this.policySid = policySid; } - public CustomerProfilesEvaluationsCreator setPolicySid( - final String policySid - ) { + + public CustomerProfilesEvaluationsCreator setPolicySid(final String policySid) { this.policySid = policySid; return this; } + @Override public CustomerProfilesEvaluations create(final TwilioRestClient client) { + String path = "/v1/CustomerProfiles/{CustomerProfileSid}/Evaluations"; - path = - path.replace( - "{" + "CustomerProfileSid" + "}", - this.pathCustomerProfileSid.toString() - ); - path = path.replace("{" + "PolicySid" + "}", this.policySid.toString()); + path = path.replace("{" + "CustomerProfileSid" + "}", this.pathcustomerProfileSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.TRUSTHUB.toString(), - path + HttpMethod.POST, + Domains.TRUSTHUB.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "CustomerProfilesEvaluations creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("CustomerProfilesEvaluations creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return CustomerProfilesEvaluations.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return CustomerProfilesEvaluations.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (policySid != null) { - request.addPostParam("PolicySid", policySid); + Serializer.toString(request, "PolicySid", policySid, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/trusthub/v1/customerprofiles/CustomerProfilesEvaluationsFetcher.java b/src/main/java/com/twilio/rest/trusthub/v1/customerprofiles/CustomerProfilesEvaluationsFetcher.java index e195f666aa..02c91e68d4 100644 --- a/src/main/java/com/twilio/rest/trusthub/v1/customerprofiles/CustomerProfilesEvaluationsFetcher.java +++ b/src/main/java/com/twilio/rest/trusthub/v1/customerprofiles/CustomerProfilesEvaluationsFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.trusthub.v1.customerprofiles; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,61 +24,46 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class CustomerProfilesEvaluationsFetcher - extends Fetcher { +public class CustomerProfilesEvaluationsFetcher extends Fetcher { - private String pathCustomerProfileSid; - private String pathSid; + private String pathcustomerProfileSid; + private String pathsid; - public CustomerProfilesEvaluationsFetcher( - final String pathCustomerProfileSid, - final String pathSid - ) { - this.pathCustomerProfileSid = pathCustomerProfileSid; - this.pathSid = pathSid; + public CustomerProfilesEvaluationsFetcher(final String pathcustomerProfileSid, final String pathsid) { + this.pathcustomerProfileSid = pathcustomerProfileSid; + this.pathsid = pathsid; } + @Override public CustomerProfilesEvaluations fetch(final TwilioRestClient client) { - String path = - "/v1/CustomerProfiles/{CustomerProfileSid}/Evaluations/{Sid}"; - path = - path.replace( - "{" + "CustomerProfileSid" + "}", - this.pathCustomerProfileSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/v1/CustomerProfiles/{CustomerProfileSid}/Evaluations/{Sid}"; + + path = path.replace("{" + "CustomerProfileSid" + "}", this.pathcustomerProfileSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.TRUSTHUB.toString(), - path + HttpMethod.GET, + Domains.TRUSTHUB.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "CustomerProfilesEvaluations fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("CustomerProfilesEvaluations fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return CustomerProfilesEvaluations.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return CustomerProfilesEvaluations.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/trusthub/v1/customerprofiles/CustomerProfilesEvaluationsReader.java b/src/main/java/com/twilio/rest/trusthub/v1/customerprofiles/CustomerProfilesEvaluationsReader.java index 12e5a1d5d9..f81334f11c 100644 --- a/src/main/java/com/twilio/rest/trusthub/v1/customerprofiles/CustomerProfilesEvaluationsReader.java +++ b/src/main/java/com/twilio/rest/trusthub/v1/customerprofiles/CustomerProfilesEvaluationsReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,124 +28,90 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class CustomerProfilesEvaluationsReader - extends Reader { +public class CustomerProfilesEvaluationsReader extends Reader { - private String pathCustomerProfileSid; + private String pathcustomerProfileSid; private Long pageSize; - public CustomerProfilesEvaluationsReader( - final String pathCustomerProfileSid - ) { - this.pathCustomerProfileSid = pathCustomerProfileSid; + public CustomerProfilesEvaluationsReader(final String pathcustomerProfileSid) { + this.pathcustomerProfileSid = pathcustomerProfileSid; } + public CustomerProfilesEvaluationsReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override - public ResourceSet read( - final TwilioRestClient client - ) { + public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } - public Page firstPage( - final TwilioRestClient client - ) { + public Page firstPage(final TwilioRestClient client) { + String path = "/v1/CustomerProfiles/{CustomerProfileSid}/Evaluations"; - path = - path.replace( - "{" + "CustomerProfileSid" + "}", - this.pathCustomerProfileSid.toString() - ); + + path = path.replace("{" + "CustomerProfileSid" + "}", this.pathcustomerProfileSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.TRUSTHUB.toString(), - path + HttpMethod.GET, + Domains.TRUSTHUB.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "CustomerProfilesEvaluations read failed: Unable to connect to server" - ); + throw new ApiConnectionException("CustomerProfilesEvaluations read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "results", - response.getContent(), - CustomerProfilesEvaluations.class, - client.getObjectMapper() - ); + "results", + response.getContent(), + CustomerProfilesEvaluations.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.TRUSTHUB.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.TRUSTHUB.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/trusthub/v1/trustproducts/TrustProductsChannelEndpointAssignment.java b/src/main/java/com/twilio/rest/trusthub/v1/trustproducts/TrustProductsChannelEndpointAssignment.java index bd2dc17915..8451f8c1ad 100644 --- a/src/main/java/com/twilio/rest/trusthub/v1/trustproducts/TrustProductsChannelEndpointAssignment.java +++ b/src/main/java/com/twilio/rest/trusthub/v1/trustproducts/TrustProductsChannelEndpointAssignment.java @@ -18,83 +18,66 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class TrustProductsChannelEndpointAssignment extends Resource { - private static final long serialVersionUID = 19553243454529L; - public static TrustProductsChannelEndpointAssignmentCreator creator( - final String pathTrustProductSid, - final String channelEndpointType, - final String channelEndpointSid - ) { + public static TrustProductsChannelEndpointAssignmentCreator creator(final String pathtrustProductSid, final String channelEndpointType, final String channelEndpointSid) { return new TrustProductsChannelEndpointAssignmentCreator( - pathTrustProductSid, - channelEndpointType, - channelEndpointSid + pathtrustProductSid, channelEndpointType, channelEndpointSid ); } - public static TrustProductsChannelEndpointAssignmentDeleter deleter( - final String pathTrustProductSid, - final String pathSid - ) { + + public static TrustProductsChannelEndpointAssignmentDeleter deleter(final String pathtrustProductSid, final String pathsid) { return new TrustProductsChannelEndpointAssignmentDeleter( - pathTrustProductSid, - pathSid + pathtrustProductSid, pathsid ); } - public static TrustProductsChannelEndpointAssignmentFetcher fetcher( - final String pathTrustProductSid, - final String pathSid - ) { + + public static TrustProductsChannelEndpointAssignmentFetcher fetcher(final String pathtrustProductSid, final String pathsid) { return new TrustProductsChannelEndpointAssignmentFetcher( - pathTrustProductSid, - pathSid + pathtrustProductSid, pathsid ); } - public static TrustProductsChannelEndpointAssignmentReader reader( - final String pathTrustProductSid - ) { + + public static TrustProductsChannelEndpointAssignmentReader reader(final String pathtrustProductSid) { return new TrustProductsChannelEndpointAssignmentReader( - pathTrustProductSid + pathtrustProductSid ); } + /** * Converts a JSON String into a TrustProductsChannelEndpointAssignment object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return TrustProductsChannelEndpointAssignment object represented by the provided JSON */ - public static TrustProductsChannelEndpointAssignment fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static TrustProductsChannelEndpointAssignment fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { - return objectMapper.readValue( - json, - TrustProductsChannelEndpointAssignment.class - ); + return objectMapper.readValue(json, TrustProductsChannelEndpointAssignment.class); } catch (final JsonMappingException | JsonParseException e) { throw new ApiException(e.getMessage(), e); } catch (final IOException e) { @@ -106,20 +89,14 @@ public static TrustProductsChannelEndpointAssignment fromJson( * Converts a JSON InputStream into a TrustProductsChannelEndpointAssignment object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return TrustProductsChannelEndpointAssignment object represented by the provided JSON */ - public static TrustProductsChannelEndpointAssignment fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static TrustProductsChannelEndpointAssignment fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { - return objectMapper.readValue( - json, - TrustProductsChannelEndpointAssignment.class - ); + return objectMapper.readValue(json, TrustProductsChannelEndpointAssignment.class); } catch (final JsonMappingException | JsonParseException e) { throw new ApiException(e.getMessage(), e); } catch (final IOException e) { @@ -127,61 +104,54 @@ public static TrustProductsChannelEndpointAssignment fromJson( } } - private final String sid; - private final String trustProductSid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String channelEndpointType; + @Getter private final String channelEndpointSid; + @Getter + private final String channelEndpointType; + @Getter private final ZonedDateTime dateCreated; + @Getter + private final String sid; + @Getter + private final String trustProductSid; + @Getter private final URI url; @JsonCreator private TrustProductsChannelEndpointAssignment( - @JsonProperty("sid") final String sid, - @JsonProperty("trust_product_sid") final String trustProductSid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("channel_endpoint_type") final String channelEndpointType, - @JsonProperty("channel_endpoint_sid") final String channelEndpointSid, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("url") final URI url + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("channel_endpoint_sid") final String channelEndpointSid, + @JsonProperty("channel_endpoint_type") final String channelEndpointType, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("sid") final String sid, + @JsonProperty("trust_product_sid") final String trustProductSid, + @JsonProperty("url") final URI url ) { - this.sid = sid; - this.trustProductSid = trustProductSid; this.accountSid = accountSid; - this.channelEndpointType = channelEndpointType; this.channelEndpointSid = channelEndpointSid; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); + this.channelEndpointType = channelEndpointType; + this.dateCreated = dateCreated; + this.sid = sid; + this.trustProductSid = trustProductSid; this.url = url; } - public final String getSid() { - return this.sid; - } - - public final String getTrustProductSid() { - return this.trustProductSid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getChannelEndpointType() { - return this.channelEndpointType; - } - - public final String getChannelEndpointSid() { - return this.channelEndpointSid; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final URI getUrl() { - return this.url; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -192,30 +162,31 @@ public boolean equals(final Object o) { return false; } - TrustProductsChannelEndpointAssignment other = - (TrustProductsChannelEndpointAssignment) o; - + TrustProductsChannelEndpointAssignment other = (TrustProductsChannelEndpointAssignment) o; return ( - Objects.equals(sid, other.sid) && - Objects.equals(trustProductSid, other.trustProductSid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(channelEndpointType, other.channelEndpointType) && - Objects.equals(channelEndpointSid, other.channelEndpointSid) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(url, other.url) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(channelEndpointSid, other.channelEndpointSid) && + Objects.equals(channelEndpointType, other.channelEndpointType) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(sid, other.sid) && + Objects.equals(trustProductSid, other.trustProductSid) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - sid, - trustProductSid, - accountSid, - channelEndpointType, - channelEndpointSid, - dateCreated, - url + accountSid, + channelEndpointSid, + channelEndpointType, + dateCreated, + sid, + trustProductSid, + url ); } + + } + diff --git a/src/main/java/com/twilio/rest/trusthub/v1/trustproducts/TrustProductsChannelEndpointAssignmentCreator.java b/src/main/java/com/twilio/rest/trusthub/v1/trustproducts/TrustProductsChannelEndpointAssignmentCreator.java index f7388d0bb2..de54cc9881 100644 --- a/src/main/java/com/twilio/rest/trusthub/v1/trustproducts/TrustProductsChannelEndpointAssignmentCreator.java +++ b/src/main/java/com/twilio/rest/trusthub/v1/trustproducts/TrustProductsChannelEndpointAssignmentCreator.java @@ -14,8 +14,11 @@ package com.twilio.rest.trusthub.v1.trustproducts; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,98 +28,76 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class TrustProductsChannelEndpointAssignmentCreator - extends Creator { +public class TrustProductsChannelEndpointAssignmentCreator extends Creator { - private String pathTrustProductSid; + private String pathtrustProductSid; private String channelEndpointType; private String channelEndpointSid; - public TrustProductsChannelEndpointAssignmentCreator( - final String pathTrustProductSid, - final String channelEndpointType, - final String channelEndpointSid - ) { - this.pathTrustProductSid = pathTrustProductSid; + public TrustProductsChannelEndpointAssignmentCreator(final String pathtrustProductSid, final String channelEndpointType, final String channelEndpointSid) { + this.pathtrustProductSid = pathtrustProductSid; this.channelEndpointType = channelEndpointType; this.channelEndpointSid = channelEndpointSid; } - public TrustProductsChannelEndpointAssignmentCreator setChannelEndpointType( - final String channelEndpointType - ) { + + public TrustProductsChannelEndpointAssignmentCreator setChannelEndpointType(final String channelEndpointType) { this.channelEndpointType = channelEndpointType; return this; } - public TrustProductsChannelEndpointAssignmentCreator setChannelEndpointSid( - final String channelEndpointSid - ) { + + public TrustProductsChannelEndpointAssignmentCreator setChannelEndpointSid(final String channelEndpointSid) { this.channelEndpointSid = channelEndpointSid; return this; } + @Override - public TrustProductsChannelEndpointAssignment create( - final TwilioRestClient client - ) { - String path = - "/v1/TrustProducts/{TrustProductSid}/ChannelEndpointAssignments"; - - path = - path.replace( - "{" + "TrustProductSid" + "}", - this.pathTrustProductSid.toString() - ); - path = - path.replace( - "{" + "ChannelEndpointType" + "}", - this.channelEndpointType.toString() - ); - path = - path.replace( - "{" + "ChannelEndpointSid" + "}", - this.channelEndpointSid.toString() - ); + public TrustProductsChannelEndpointAssignment create(final TwilioRestClient client) { + + String path = "/v1/TrustProducts/{TrustProductSid}/ChannelEndpointAssignments"; + + path = path.replace("{" + "TrustProductSid" + "}", this.pathtrustProductSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.TRUSTHUB.toString(), - path + HttpMethod.POST, + Domains.TRUSTHUB.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "TrustProductsChannelEndpointAssignment creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("TrustProductsChannelEndpointAssignment creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return TrustProductsChannelEndpointAssignment.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return TrustProductsChannelEndpointAssignment.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (channelEndpointType != null) { - request.addPostParam("ChannelEndpointType", channelEndpointType); + Serializer.toString(request, "ChannelEndpointType", channelEndpointType, ParameterType.URLENCODED); } + + if (channelEndpointSid != null) { - request.addPostParam("ChannelEndpointSid", channelEndpointSid); + Serializer.toString(request, "ChannelEndpointSid", channelEndpointSid, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/trusthub/v1/trustproducts/TrustProductsChannelEndpointAssignmentDeleter.java b/src/main/java/com/twilio/rest/trusthub/v1/trustproducts/TrustProductsChannelEndpointAssignmentDeleter.java index 49f3c473df..9047fc914c 100644 --- a/src/main/java/com/twilio/rest/trusthub/v1/trustproducts/TrustProductsChannelEndpointAssignmentDeleter.java +++ b/src/main/java/com/twilio/rest/trusthub/v1/trustproducts/TrustProductsChannelEndpointAssignmentDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.trusthub.v1.trustproducts; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,54 +24,43 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class TrustProductsChannelEndpointAssignmentDeleter - extends Deleter { +public class TrustProductsChannelEndpointAssignmentDeleter extends Deleter { - private String pathTrustProductSid; - private String pathSid; + private String pathtrustProductSid; + private String pathsid; - public TrustProductsChannelEndpointAssignmentDeleter( - final String pathTrustProductSid, - final String pathSid - ) { - this.pathTrustProductSid = pathTrustProductSid; - this.pathSid = pathSid; + public TrustProductsChannelEndpointAssignmentDeleter(final String pathtrustProductSid, final String pathsid) { + this.pathtrustProductSid = pathtrustProductSid; + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { - String path = - "/v1/TrustProducts/{TrustProductSid}/ChannelEndpointAssignments/{Sid}"; - path = - path.replace( - "{" + "TrustProductSid" + "}", - this.pathTrustProductSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/v1/TrustProducts/{TrustProductSid}/ChannelEndpointAssignments/{Sid}"; + + path = path.replace("{" + "TrustProductSid" + "}", this.pathtrustProductSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.TRUSTHUB.toString(), - path + HttpMethod.DELETE, + Domains.TRUSTHUB.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "TrustProductsChannelEndpointAssignment delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("TrustProductsChannelEndpointAssignment delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/trusthub/v1/trustproducts/TrustProductsChannelEndpointAssignmentFetcher.java b/src/main/java/com/twilio/rest/trusthub/v1/trustproducts/TrustProductsChannelEndpointAssignmentFetcher.java index 791420945c..543aa8ea51 100644 --- a/src/main/java/com/twilio/rest/trusthub/v1/trustproducts/TrustProductsChannelEndpointAssignmentFetcher.java +++ b/src/main/java/com/twilio/rest/trusthub/v1/trustproducts/TrustProductsChannelEndpointAssignmentFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.trusthub.v1.trustproducts; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,63 +24,46 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class TrustProductsChannelEndpointAssignmentFetcher - extends Fetcher { +public class TrustProductsChannelEndpointAssignmentFetcher extends Fetcher { - private String pathTrustProductSid; - private String pathSid; + private String pathtrustProductSid; + private String pathsid; - public TrustProductsChannelEndpointAssignmentFetcher( - final String pathTrustProductSid, - final String pathSid - ) { - this.pathTrustProductSid = pathTrustProductSid; - this.pathSid = pathSid; + public TrustProductsChannelEndpointAssignmentFetcher(final String pathtrustProductSid, final String pathsid) { + this.pathtrustProductSid = pathtrustProductSid; + this.pathsid = pathsid; } + @Override - public TrustProductsChannelEndpointAssignment fetch( - final TwilioRestClient client - ) { - String path = - "/v1/TrustProducts/{TrustProductSid}/ChannelEndpointAssignments/{Sid}"; + public TrustProductsChannelEndpointAssignment fetch(final TwilioRestClient client) { + + String path = "/v1/TrustProducts/{TrustProductSid}/ChannelEndpointAssignments/{Sid}"; + + path = path.replace("{" + "TrustProductSid" + "}", this.pathtrustProductSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); - path = - path.replace( - "{" + "TrustProductSid" + "}", - this.pathTrustProductSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.TRUSTHUB.toString(), - path + HttpMethod.GET, + Domains.TRUSTHUB.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "TrustProductsChannelEndpointAssignment fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("TrustProductsChannelEndpointAssignment fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return TrustProductsChannelEndpointAssignment.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return TrustProductsChannelEndpointAssignment.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/trusthub/v1/trustproducts/TrustProductsChannelEndpointAssignmentReader.java b/src/main/java/com/twilio/rest/trusthub/v1/trustproducts/TrustProductsChannelEndpointAssignmentReader.java index 3ce0f6ede9..5e3ab1f562 100644 --- a/src/main/java/com/twilio/rest/trusthub/v1/trustproducts/TrustProductsChannelEndpointAssignmentReader.java +++ b/src/main/java/com/twilio/rest/trusthub/v1/trustproducts/TrustProductsChannelEndpointAssignmentReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,149 +28,114 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class TrustProductsChannelEndpointAssignmentReader - extends Reader { +public class TrustProductsChannelEndpointAssignmentReader extends Reader { - private String pathTrustProductSid; + private String pathtrustProductSid; private String channelEndpointSid; private String channelEndpointSids; private Long pageSize; - public TrustProductsChannelEndpointAssignmentReader( - final String pathTrustProductSid - ) { - this.pathTrustProductSid = pathTrustProductSid; + public TrustProductsChannelEndpointAssignmentReader(final String pathtrustProductSid) { + this.pathtrustProductSid = pathtrustProductSid; } - public TrustProductsChannelEndpointAssignmentReader setChannelEndpointSid( - final String channelEndpointSid - ) { + + public TrustProductsChannelEndpointAssignmentReader setChannelEndpointSid(final String channelEndpointSid) { this.channelEndpointSid = channelEndpointSid; return this; } - public TrustProductsChannelEndpointAssignmentReader setChannelEndpointSids( - final String channelEndpointSids - ) { + + public TrustProductsChannelEndpointAssignmentReader setChannelEndpointSids(final String channelEndpointSids) { this.channelEndpointSids = channelEndpointSids; return this; } - public TrustProductsChannelEndpointAssignmentReader setPageSize( - final Long pageSize - ) { + + public TrustProductsChannelEndpointAssignmentReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override - public ResourceSet read( - final TwilioRestClient client - ) { + public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } - public Page firstPage( - final TwilioRestClient client - ) { - String path = - "/v1/TrustProducts/{TrustProductSid}/ChannelEndpointAssignments"; - path = - path.replace( - "{" + "TrustProductSid" + "}", - this.pathTrustProductSid.toString() - ); + public Page firstPage(final TwilioRestClient client) { + + String path = "/v1/TrustProducts/{TrustProductSid}/ChannelEndpointAssignments"; + + path = path.replace("{" + "TrustProductSid" + "}", this.pathtrustProductSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.TRUSTHUB.toString(), - path + HttpMethod.GET, + Domains.TRUSTHUB.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "TrustProductsChannelEndpointAssignment read failed: Unable to connect to server" - ); + throw new ApiConnectionException("TrustProductsChannelEndpointAssignment read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "results", - response.getContent(), - TrustProductsChannelEndpointAssignment.class, - client.getObjectMapper() - ); + "results", + response.getContent(), + TrustProductsChannelEndpointAssignment.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.TRUSTHUB.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.TRUSTHUB.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (channelEndpointSid != null) { - request.addQueryParam("ChannelEndpointSid", channelEndpointSid); + Serializer.toString(request, "ChannelEndpointSid", channelEndpointSid, ParameterType.QUERY); } + + if (channelEndpointSids != null) { - request.addQueryParam("ChannelEndpointSids", channelEndpointSids); + Serializer.toString(request, "ChannelEndpointSids", channelEndpointSids, ParameterType.QUERY); } + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/trusthub/v1/trustproducts/TrustProductsEntityAssignments.java b/src/main/java/com/twilio/rest/trusthub/v1/trustproducts/TrustProductsEntityAssignments.java index 7b65213d7e..27da242fb4 100644 --- a/src/main/java/com/twilio/rest/trusthub/v1/trustproducts/TrustProductsEntityAssignments.java +++ b/src/main/java/com/twilio/rest/trusthub/v1/trustproducts/TrustProductsEntityAssignments.java @@ -18,79 +18,66 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class TrustProductsEntityAssignments extends Resource { - private static final long serialVersionUID = 11655766001892L; - public static TrustProductsEntityAssignmentsCreator creator( - final String pathTrustProductSid, - final String objectSid - ) { + public static TrustProductsEntityAssignmentsCreator creator(final String pathtrustProductSid, final String objectSid) { return new TrustProductsEntityAssignmentsCreator( - pathTrustProductSid, - objectSid + pathtrustProductSid, objectSid ); } - public static TrustProductsEntityAssignmentsDeleter deleter( - final String pathTrustProductSid, - final String pathSid - ) { + + public static TrustProductsEntityAssignmentsDeleter deleter(final String pathtrustProductSid, final String pathsid) { return new TrustProductsEntityAssignmentsDeleter( - pathTrustProductSid, - pathSid + pathtrustProductSid, pathsid ); } - public static TrustProductsEntityAssignmentsFetcher fetcher( - final String pathTrustProductSid, - final String pathSid - ) { + + public static TrustProductsEntityAssignmentsFetcher fetcher(final String pathtrustProductSid, final String pathsid) { return new TrustProductsEntityAssignmentsFetcher( - pathTrustProductSid, - pathSid + pathtrustProductSid, pathsid ); } - public static TrustProductsEntityAssignmentsReader reader( - final String pathTrustProductSid - ) { - return new TrustProductsEntityAssignmentsReader(pathTrustProductSid); + + public static TrustProductsEntityAssignmentsReader reader(final String pathtrustProductSid) { + return new TrustProductsEntityAssignmentsReader( + pathtrustProductSid + ); } + /** * Converts a JSON String into a TrustProductsEntityAssignments object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return TrustProductsEntityAssignments object represented by the provided JSON */ - public static TrustProductsEntityAssignments fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static TrustProductsEntityAssignments fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { - return objectMapper.readValue( - json, - TrustProductsEntityAssignments.class - ); + return objectMapper.readValue(json, TrustProductsEntityAssignments.class); } catch (final JsonMappingException | JsonParseException e) { throw new ApiException(e.getMessage(), e); } catch (final IOException e) { @@ -102,20 +89,14 @@ public static TrustProductsEntityAssignments fromJson( * Converts a JSON InputStream into a TrustProductsEntityAssignments object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return TrustProductsEntityAssignments object represented by the provided JSON */ - public static TrustProductsEntityAssignments fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static TrustProductsEntityAssignments fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { - return objectMapper.readValue( - json, - TrustProductsEntityAssignments.class - ); + return objectMapper.readValue(json, TrustProductsEntityAssignments.class); } catch (final JsonMappingException | JsonParseException e) { throw new ApiException(e.getMessage(), e); } catch (final IOException e) { @@ -123,54 +104,50 @@ public static TrustProductsEntityAssignments fromJson( } } - private final String sid; - private final String trustProductSid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String objectSid; + @Getter private final ZonedDateTime dateCreated; + @Getter + private final String objectSid; + @Getter + private final String sid; + @Getter + private final String trustProductSid; + @Getter private final URI url; @JsonCreator private TrustProductsEntityAssignments( - @JsonProperty("sid") final String sid, - @JsonProperty("trust_product_sid") final String trustProductSid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("object_sid") final String objectSid, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("url") final URI url + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("object_sid") final String objectSid, + @JsonProperty("sid") final String sid, + @JsonProperty("trust_product_sid") final String trustProductSid, + @JsonProperty("url") final URI url ) { - this.sid = sid; - this.trustProductSid = trustProductSid; this.accountSid = accountSid; + this.dateCreated = dateCreated; this.objectSid = objectSid; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); + this.sid = sid; + this.trustProductSid = trustProductSid; this.url = url; } - public final String getSid() { - return this.sid; - } - - public final String getTrustProductSid() { - return this.trustProductSid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getObjectSid() { - return this.objectSid; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final URI getUrl() { - return this.url; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -181,28 +158,29 @@ public boolean equals(final Object o) { return false; } - TrustProductsEntityAssignments other = - (TrustProductsEntityAssignments) o; - + TrustProductsEntityAssignments other = (TrustProductsEntityAssignments) o; return ( - Objects.equals(sid, other.sid) && - Objects.equals(trustProductSid, other.trustProductSid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(objectSid, other.objectSid) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(url, other.url) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(objectSid, other.objectSid) && + Objects.equals(sid, other.sid) && + Objects.equals(trustProductSid, other.trustProductSid) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - sid, - trustProductSid, - accountSid, - objectSid, - dateCreated, - url + accountSid, + dateCreated, + objectSid, + sid, + trustProductSid, + url ); } + + } + diff --git a/src/main/java/com/twilio/rest/trusthub/v1/trustproducts/TrustProductsEntityAssignmentsCreator.java b/src/main/java/com/twilio/rest/trusthub/v1/trustproducts/TrustProductsEntityAssignmentsCreator.java index 51150f5b52..1ad5d0960f 100644 --- a/src/main/java/com/twilio/rest/trusthub/v1/trustproducts/TrustProductsEntityAssignmentsCreator.java +++ b/src/main/java/com/twilio/rest/trusthub/v1/trustproducts/TrustProductsEntityAssignmentsCreator.java @@ -14,8 +14,11 @@ package com.twilio.rest.trusthub.v1.trustproducts; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,75 +28,63 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class TrustProductsEntityAssignmentsCreator - extends Creator { +public class TrustProductsEntityAssignmentsCreator extends Creator { - private String pathTrustProductSid; + private String pathtrustProductSid; private String objectSid; - public TrustProductsEntityAssignmentsCreator( - final String pathTrustProductSid, - final String objectSid - ) { - this.pathTrustProductSid = pathTrustProductSid; + public TrustProductsEntityAssignmentsCreator(final String pathtrustProductSid, final String objectSid) { + this.pathtrustProductSid = pathtrustProductSid; this.objectSid = objectSid; } - public TrustProductsEntityAssignmentsCreator setObjectSid( - final String objectSid - ) { + + public TrustProductsEntityAssignmentsCreator setObjectSid(final String objectSid) { this.objectSid = objectSid; return this; } + @Override - public TrustProductsEntityAssignments create( - final TwilioRestClient client - ) { + public TrustProductsEntityAssignments create(final TwilioRestClient client) { + String path = "/v1/TrustProducts/{TrustProductSid}/EntityAssignments"; - path = - path.replace( - "{" + "TrustProductSid" + "}", - this.pathTrustProductSid.toString() - ); - path = path.replace("{" + "ObjectSid" + "}", this.objectSid.toString()); + path = path.replace("{" + "TrustProductSid" + "}", this.pathtrustProductSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.TRUSTHUB.toString(), - path + HttpMethod.POST, + Domains.TRUSTHUB.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "TrustProductsEntityAssignments creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("TrustProductsEntityAssignments creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return TrustProductsEntityAssignments.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return TrustProductsEntityAssignments.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (objectSid != null) { - request.addPostParam("ObjectSid", objectSid); + Serializer.toString(request, "ObjectSid", objectSid, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/trusthub/v1/trustproducts/TrustProductsEntityAssignmentsDeleter.java b/src/main/java/com/twilio/rest/trusthub/v1/trustproducts/TrustProductsEntityAssignmentsDeleter.java index b3892618f5..c04877af2a 100644 --- a/src/main/java/com/twilio/rest/trusthub/v1/trustproducts/TrustProductsEntityAssignmentsDeleter.java +++ b/src/main/java/com/twilio/rest/trusthub/v1/trustproducts/TrustProductsEntityAssignmentsDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.trusthub.v1.trustproducts; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,54 +24,43 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class TrustProductsEntityAssignmentsDeleter - extends Deleter { +public class TrustProductsEntityAssignmentsDeleter extends Deleter { - private String pathTrustProductSid; - private String pathSid; + private String pathtrustProductSid; + private String pathsid; - public TrustProductsEntityAssignmentsDeleter( - final String pathTrustProductSid, - final String pathSid - ) { - this.pathTrustProductSid = pathTrustProductSid; - this.pathSid = pathSid; + public TrustProductsEntityAssignmentsDeleter(final String pathtrustProductSid, final String pathsid) { + this.pathtrustProductSid = pathtrustProductSid; + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { - String path = - "/v1/TrustProducts/{TrustProductSid}/EntityAssignments/{Sid}"; - path = - path.replace( - "{" + "TrustProductSid" + "}", - this.pathTrustProductSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/v1/TrustProducts/{TrustProductSid}/EntityAssignments/{Sid}"; + + path = path.replace("{" + "TrustProductSid" + "}", this.pathtrustProductSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.TRUSTHUB.toString(), - path + HttpMethod.DELETE, + Domains.TRUSTHUB.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "TrustProductsEntityAssignments delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("TrustProductsEntityAssignments delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/trusthub/v1/trustproducts/TrustProductsEntityAssignmentsFetcher.java b/src/main/java/com/twilio/rest/trusthub/v1/trustproducts/TrustProductsEntityAssignmentsFetcher.java index fdf5564067..29f296aa3b 100644 --- a/src/main/java/com/twilio/rest/trusthub/v1/trustproducts/TrustProductsEntityAssignmentsFetcher.java +++ b/src/main/java/com/twilio/rest/trusthub/v1/trustproducts/TrustProductsEntityAssignmentsFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.trusthub.v1.trustproducts; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,61 +24,46 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class TrustProductsEntityAssignmentsFetcher - extends Fetcher { +public class TrustProductsEntityAssignmentsFetcher extends Fetcher { - private String pathTrustProductSid; - private String pathSid; + private String pathtrustProductSid; + private String pathsid; - public TrustProductsEntityAssignmentsFetcher( - final String pathTrustProductSid, - final String pathSid - ) { - this.pathTrustProductSid = pathTrustProductSid; - this.pathSid = pathSid; + public TrustProductsEntityAssignmentsFetcher(final String pathtrustProductSid, final String pathsid) { + this.pathtrustProductSid = pathtrustProductSid; + this.pathsid = pathsid; } + @Override public TrustProductsEntityAssignments fetch(final TwilioRestClient client) { - String path = - "/v1/TrustProducts/{TrustProductSid}/EntityAssignments/{Sid}"; - path = - path.replace( - "{" + "TrustProductSid" + "}", - this.pathTrustProductSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + String path = "/v1/TrustProducts/{TrustProductSid}/EntityAssignments/{Sid}"; + + path = path.replace("{" + "TrustProductSid" + "}", this.pathtrustProductSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.TRUSTHUB.toString(), - path + HttpMethod.GET, + Domains.TRUSTHUB.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "TrustProductsEntityAssignments fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("TrustProductsEntityAssignments fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return TrustProductsEntityAssignments.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return TrustProductsEntityAssignments.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/trusthub/v1/trustproducts/TrustProductsEntityAssignmentsReader.java b/src/main/java/com/twilio/rest/trusthub/v1/trustproducts/TrustProductsEntityAssignmentsReader.java index e317198083..54eac94180 100644 --- a/src/main/java/com/twilio/rest/trusthub/v1/trustproducts/TrustProductsEntityAssignmentsReader.java +++ b/src/main/java/com/twilio/rest/trusthub/v1/trustproducts/TrustProductsEntityAssignmentsReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,137 +28,102 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class TrustProductsEntityAssignmentsReader - extends Reader { +public class TrustProductsEntityAssignmentsReader extends Reader { - private String pathTrustProductSid; + private String pathtrustProductSid; private String objectType; private Long pageSize; - public TrustProductsEntityAssignmentsReader( - final String pathTrustProductSid - ) { - this.pathTrustProductSid = pathTrustProductSid; + public TrustProductsEntityAssignmentsReader(final String pathtrustProductSid) { + this.pathtrustProductSid = pathtrustProductSid; } - public TrustProductsEntityAssignmentsReader setObjectType( - final String objectType - ) { + + public TrustProductsEntityAssignmentsReader setObjectType(final String objectType) { this.objectType = objectType; return this; } - public TrustProductsEntityAssignmentsReader setPageSize( - final Long pageSize - ) { + + public TrustProductsEntityAssignmentsReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override - public ResourceSet read( - final TwilioRestClient client - ) { + public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } - public Page firstPage( - final TwilioRestClient client - ) { + public Page firstPage(final TwilioRestClient client) { + String path = "/v1/TrustProducts/{TrustProductSid}/EntityAssignments"; - path = - path.replace( - "{" + "TrustProductSid" + "}", - this.pathTrustProductSid.toString() - ); + + path = path.replace("{" + "TrustProductSid" + "}", this.pathtrustProductSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.TRUSTHUB.toString(), - path + HttpMethod.GET, + Domains.TRUSTHUB.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "TrustProductsEntityAssignments read failed: Unable to connect to server" - ); + throw new ApiConnectionException("TrustProductsEntityAssignments read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "results", - response.getContent(), - TrustProductsEntityAssignments.class, - client.getObjectMapper() - ); + "results", + response.getContent(), + TrustProductsEntityAssignments.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.TRUSTHUB.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.TRUSTHUB.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (objectType != null) { - request.addQueryParam("ObjectType", objectType); + Serializer.toString(request, "ObjectType", objectType, ParameterType.QUERY); } + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/trusthub/v1/trustproducts/TrustProductsEvaluations.java b/src/main/java/com/twilio/rest/trusthub/v1/trustproducts/TrustProductsEvaluations.java index c2aee8cf6b..35bf877539 100644 --- a/src/main/java/com/twilio/rest/trusthub/v1/trustproducts/TrustProductsEvaluations.java +++ b/src/main/java/com/twilio/rest/trusthub/v1/trustproducts/TrustProductsEvaluations.java @@ -18,67 +18,79 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.List; -import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class TrustProductsEvaluations extends Resource { - private static final long serialVersionUID = 86634042597263L; - public static TrustProductsEvaluationsCreator creator( - final String pathTrustProductSid, - final String policySid - ) { + public static TrustProductsEvaluationsCreator creator(final String pathtrustProductSid, final String policySid) { return new TrustProductsEvaluationsCreator( - pathTrustProductSid, - policySid + pathtrustProductSid, policySid ); } - public static TrustProductsEvaluationsFetcher fetcher( - final String pathTrustProductSid, - final String pathSid - ) { + + public static TrustProductsEvaluationsFetcher fetcher(final String pathtrustProductSid, final String pathsid) { return new TrustProductsEvaluationsFetcher( - pathTrustProductSid, - pathSid + pathtrustProductSid, pathsid ); } - public static TrustProductsEvaluationsReader reader( - final String pathTrustProductSid - ) { - return new TrustProductsEvaluationsReader(pathTrustProductSid); + + public static TrustProductsEvaluationsReader reader(final String pathtrustProductSid) { + return new TrustProductsEvaluationsReader( + pathtrustProductSid + ); + } + + + public enum Status { + COMPLIANT("compliant"), + NONCOMPLIANT("noncompliant"); + + private final String value; + + private Status(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static Status forValue(final String value) { + return Promoter.enumFromString(value, Status.values()); + } } + /** * Converts a JSON String into a TrustProductsEvaluations object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return TrustProductsEvaluations object represented by the provided JSON */ - public static TrustProductsEvaluations fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static TrustProductsEvaluations fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, TrustProductsEvaluations.class); @@ -93,14 +105,11 @@ public static TrustProductsEvaluations fromJson( * Converts a JSON InputStream into a TrustProductsEvaluations object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return TrustProductsEvaluations object represented by the provided JSON */ - public static TrustProductsEvaluations fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static TrustProductsEvaluations fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, TrustProductsEvaluations.class); @@ -111,68 +120,58 @@ public static TrustProductsEvaluations fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; + @Getter + private final ZonedDateTime dateCreated; + @Getter private final String policySid; - private final String trustProductSid; + @Getter + private final List results; + @Getter + private final String sid; + @Getter private final TrustProductsEvaluations.Status status; - private final List> results; - private final ZonedDateTime dateCreated; + @Getter + private final String trustProductSid; + @Getter private final URI url; @JsonCreator private TrustProductsEvaluations( - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("policy_sid") final String policySid, - @JsonProperty("trust_product_sid") final String trustProductSid, - @JsonProperty("status") final TrustProductsEvaluations.Status status, - @JsonProperty("results") final List> results, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("url") final URI url + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("policy_sid") final String policySid, + @JsonProperty("results") final List results, + @JsonProperty("sid") final String sid, + @JsonProperty("status") final TrustProductsEvaluations.Status status, + @JsonProperty("trust_product_sid") final String trustProductSid, + @JsonProperty("url") final URI url ) { - this.sid = sid; this.accountSid = accountSid; + this.dateCreated = dateCreated; this.policySid = policySid; - this.trustProductSid = trustProductSid; - this.status = status; this.results = results; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); + this.sid = sid; + this.status = status; + this.trustProductSid = trustProductSid; this.url = url; } - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getPolicySid() { - return this.policySid; - } - - public final String getTrustProductSid() { - return this.trustProductSid; - } - - public final TrustProductsEvaluations.Status getStatus() { - return this.status; - } - - public final List> getResults() { - return this.results; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final URI getUrl() { - return this.url; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -184,50 +183,32 @@ public boolean equals(final Object o) { } TrustProductsEvaluations other = (TrustProductsEvaluations) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(policySid, other.policySid) && - Objects.equals(trustProductSid, other.trustProductSid) && - Objects.equals(status, other.status) && - Objects.equals(results, other.results) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(url, other.url) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(policySid, other.policySid) && + Objects.equals(results, other.results) && + Objects.equals(sid, other.sid) && + Objects.equals(status, other.status) && + Objects.equals(trustProductSid, other.trustProductSid) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { return Objects.hash( - sid, - accountSid, - policySid, - trustProductSid, - status, - results, - dateCreated, - url + accountSid, + dateCreated, + policySid, + results, + sid, + status, + trustProductSid, + url ); } - public enum Status { - COMPLIANT("compliant"), - NONCOMPLIANT("noncompliant"); - - private final String value; - - private Status(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - @JsonCreator - public static Status forValue(final String value) { - return Promoter.enumFromString(value, Status.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/trusthub/v1/trustproducts/TrustProductsEvaluationsCreator.java b/src/main/java/com/twilio/rest/trusthub/v1/trustproducts/TrustProductsEvaluationsCreator.java index 5310d85645..70a898bf77 100644 --- a/src/main/java/com/twilio/rest/trusthub/v1/trustproducts/TrustProductsEvaluationsCreator.java +++ b/src/main/java/com/twilio/rest/trusthub/v1/trustproducts/TrustProductsEvaluationsCreator.java @@ -14,8 +14,11 @@ package com.twilio.rest.trusthub.v1.trustproducts; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,73 +28,63 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class TrustProductsEvaluationsCreator - extends Creator { +public class TrustProductsEvaluationsCreator extends Creator { - private String pathTrustProductSid; + private String pathtrustProductSid; private String policySid; - public TrustProductsEvaluationsCreator( - final String pathTrustProductSid, - final String policySid - ) { - this.pathTrustProductSid = pathTrustProductSid; + public TrustProductsEvaluationsCreator(final String pathtrustProductSid, final String policySid) { + this.pathtrustProductSid = pathtrustProductSid; this.policySid = policySid; } - public TrustProductsEvaluationsCreator setPolicySid( - final String policySid - ) { + + public TrustProductsEvaluationsCreator setPolicySid(final String policySid) { this.policySid = policySid; return this; } + @Override public TrustProductsEvaluations create(final TwilioRestClient client) { + String path = "/v1/TrustProducts/{TrustProductSid}/Evaluations"; - path = - path.replace( - "{" + "TrustProductSid" + "}", - this.pathTrustProductSid.toString() - ); - path = path.replace("{" + "PolicySid" + "}", this.policySid.toString()); + path = path.replace("{" + "TrustProductSid" + "}", this.pathtrustProductSid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.TRUSTHUB.toString(), - path + HttpMethod.POST, + Domains.TRUSTHUB.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "TrustProductsEvaluations creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("TrustProductsEvaluations creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return TrustProductsEvaluations.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return TrustProductsEvaluations.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (policySid != null) { - request.addPostParam("PolicySid", policySid); + Serializer.toString(request, "PolicySid", policySid, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/trusthub/v1/trustproducts/TrustProductsEvaluationsFetcher.java b/src/main/java/com/twilio/rest/trusthub/v1/trustproducts/TrustProductsEvaluationsFetcher.java index a7a5193750..488034b7c7 100644 --- a/src/main/java/com/twilio/rest/trusthub/v1/trustproducts/TrustProductsEvaluationsFetcher.java +++ b/src/main/java/com/twilio/rest/trusthub/v1/trustproducts/TrustProductsEvaluationsFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.trusthub.v1.trustproducts; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -25,60 +24,46 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class TrustProductsEvaluationsFetcher - extends Fetcher { +public class TrustProductsEvaluationsFetcher extends Fetcher { - private String pathTrustProductSid; - private String pathSid; + private String pathtrustProductSid; + private String pathsid; - public TrustProductsEvaluationsFetcher( - final String pathTrustProductSid, - final String pathSid - ) { - this.pathTrustProductSid = pathTrustProductSid; - this.pathSid = pathSid; + public TrustProductsEvaluationsFetcher(final String pathtrustProductSid, final String pathsid) { + this.pathtrustProductSid = pathtrustProductSid; + this.pathsid = pathsid; } + @Override public TrustProductsEvaluations fetch(final TwilioRestClient client) { + String path = "/v1/TrustProducts/{TrustProductSid}/Evaluations/{Sid}"; - path = - path.replace( - "{" + "TrustProductSid" + "}", - this.pathTrustProductSid.toString() - ); - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "TrustProductSid" + "}", this.pathtrustProductSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.TRUSTHUB.toString(), - path + HttpMethod.GET, + Domains.TRUSTHUB.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "TrustProductsEvaluations fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("TrustProductsEvaluations fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return TrustProductsEvaluations.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return TrustProductsEvaluations.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/trusthub/v1/trustproducts/TrustProductsEvaluationsReader.java b/src/main/java/com/twilio/rest/trusthub/v1/trustproducts/TrustProductsEvaluationsReader.java index d027402ce2..4c169185c0 100644 --- a/src/main/java/com/twilio/rest/trusthub/v1/trustproducts/TrustProductsEvaluationsReader.java +++ b/src/main/java/com/twilio/rest/trusthub/v1/trustproducts/TrustProductsEvaluationsReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,122 +28,90 @@ import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; -public class TrustProductsEvaluationsReader - extends Reader { +public class TrustProductsEvaluationsReader extends Reader { - private String pathTrustProductSid; + private String pathtrustProductSid; private Long pageSize; - public TrustProductsEvaluationsReader(final String pathTrustProductSid) { - this.pathTrustProductSid = pathTrustProductSid; + public TrustProductsEvaluationsReader(final String pathtrustProductSid) { + this.pathtrustProductSid = pathtrustProductSid; } + public TrustProductsEvaluationsReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override - public ResourceSet read( - final TwilioRestClient client - ) { + public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } - public Page firstPage( - final TwilioRestClient client - ) { + public Page firstPage(final TwilioRestClient client) { + String path = "/v1/TrustProducts/{TrustProductSid}/Evaluations"; - path = - path.replace( - "{" + "TrustProductSid" + "}", - this.pathTrustProductSid.toString() - ); + + path = path.replace("{" + "TrustProductSid" + "}", this.pathtrustProductSid.toString()); Request request = new Request( - HttpMethod.GET, - Domains.TRUSTHUB.toString(), - path + HttpMethod.GET, + Domains.TRUSTHUB.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "TrustProductsEvaluations read failed: Unable to connect to server" - ); + throw new ApiConnectionException("TrustProductsEvaluations read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "results", - response.getContent(), - TrustProductsEvaluations.class, - client.getObjectMapper() - ); + "results", + response.getContent(), + TrustProductsEvaluations.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.TRUSTHUB.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.TRUSTHUB.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/verify/v2/Form.java b/src/main/java/com/twilio/rest/verify/v2/Form.java index c6f82158f9..4b26af8e67 100644 --- a/src/main/java/com/twilio/rest/verify/v2/Form.java +++ b/src/main/java/com/twilio/rest/verify/v2/Form.java @@ -18,42 +18,61 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; -import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Form extends Resource { - private static final long serialVersionUID = 202517967097226L; - public static FormFetcher fetcher(final Form.FormTypes formType) { - return new FormFetcher(formType); + public static FormFetcher fetcher(final Form.FormTypes pathformType) { + return new FormFetcher( + pathformType + ); + } + + + public enum FormTypes { + FORM_PUSH("form-push"); + + private final String value; + + private FormTypes(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static FormTypes forValue(final String value) { + return Promoter.enumFromString(value, FormTypes.values()); + } } + /** * Converts a JSON String into a Form object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Form object represented by the provided JSON */ - public static Form fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Form fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Form.class); @@ -68,14 +87,11 @@ public static Form fromJson( * Converts a JSON InputStream into a Form object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Form object represented by the provided JSON */ - public static Form fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Form fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Form.class); @@ -86,40 +102,41 @@ public static Form fromJson( } } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter + private final Object formMeta; + @Getter private final Form.FormTypes formType; - private final Map forms; - private final Map formMeta; + @Getter + private final Object forms; + @Getter private final URI url; @JsonCreator private Form( - @JsonProperty("form_type") final Form.FormTypes formType, - @JsonProperty("forms") final Map forms, - @JsonProperty("form_meta") final Map formMeta, - @JsonProperty("url") final URI url + @JsonProperty("form_meta") final Object formMeta, + @JsonProperty("form_type") final Form.FormTypes formType, + @JsonProperty("forms") final Object forms, + @JsonProperty("url") final URI url ) { + this.formMeta = formMeta; this.formType = formType; this.forms = forms; - this.formMeta = formMeta; this.url = url; } - public final Form.FormTypes getFormType() { - return this.formType; - } - - public final Map getForms() { - return this.forms; - } - - public final Map getFormMeta() { - return this.formMeta; - } - - public final URI getUrl() { - return this.url; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -131,36 +148,24 @@ public boolean equals(final Object o) { } Form other = (Form) o; - return ( - Objects.equals(formType, other.formType) && - Objects.equals(forms, other.forms) && - Objects.equals(formMeta, other.formMeta) && - Objects.equals(url, other.url) + Objects.equals(formMeta, other.formMeta) && + Objects.equals(formType, other.formType) && + Objects.equals(forms, other.forms) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { - return Objects.hash(formType, forms, formMeta, url); + return Objects.hash( + formMeta, + formType, + forms, + url + ); } - public enum FormTypes { - FORM_PUSH("form-push"); - private final String value; - - private FormTypes(final String value) { - this.value = value; - } - - public String toString() { - return value; - } - - @JsonCreator - public static FormTypes forValue(final String value) { - return Promoter.enumFromString(value, FormTypes.values()); - } - } } + diff --git a/src/main/java/com/twilio/rest/verify/v2/FormFetcher.java b/src/main/java/com/twilio/rest/verify/v2/FormFetcher.java index bdee54b3b4..02fe567ec7 100644 --- a/src/main/java/com/twilio/rest/verify/v2/FormFetcher.java +++ b/src/main/java/com/twilio/rest/verify/v2/FormFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.verify.v2; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,44 +26,41 @@ public class FormFetcher extends Fetcher
{ - private Form.FormTypes formType; + private Form.FormTypes pathformType; - public FormFetcher(final Form.FormTypes formType) { - this.formType = formType; + public FormFetcher(final Form.FormTypes pathformType) { + this.pathformType = pathformType; } + @Override public Form fetch(final TwilioRestClient client) { + String path = "/v2/Forms/{FormType}"; - path = path.replace("{" + "FormType" + "}", this.formType.toString()); + path = path.replace("{" + "FormType" + "}", this.pathformType.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.VERIFY.toString(), - path + HttpMethod.GET, + Domains.VERIFY.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Form fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Form fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Form.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/verify/v2/NewChallenge.java b/src/main/java/com/twilio/rest/verify/v2/NewChallenge.java new file mode 100644 index 0000000000..73b975dd31 --- /dev/null +++ b/src/main/java/com/twilio/rest/verify/v2/NewChallenge.java @@ -0,0 +1,334 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Verify + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package com.twilio.rest.verify.v2; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.twilio.base.Resource; +import com.twilio.converter.Promoter; +import com.twilio.exception.ApiConnectionException; +import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +import java.io.IOException; +import java.io.InputStream; +import java.net.URI; +import java.time.ZonedDateTime; +import java.util.Map; +import java.util.Objects; + +@JsonIgnoreProperties(ignoreUnknown = true) +@ToString +public class NewChallenge extends Resource { + + + public static NewChallengeCreator creator(final String pathserviceSid, final NewChallenge.CreatePasskeysChallengeRequest createPasskeysChallengeRequest) { + return new NewChallengeCreator( + pathserviceSid, createPasskeysChallengeRequest + ); + } + + + public enum Status { + PENDING("pending"), + EXPIRED("expired"), + APPROVED("approved"), + DENIED("denied"); + + private final String value; + + private Status(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static Status forValue(final String value) { + return Promoter.enumFromString(value, Status.values()); + } + } + + public enum RespondedReason { + NONE("none"), + NOT_NEEDED("not_needed"), + NOT_REQUESTED("not_requested"); + + private final String value; + + private RespondedReason(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static RespondedReason forValue(final String value) { + return Promoter.enumFromString(value, RespondedReason.values()); + } + } + + public enum FactorType { + PUSH("push"), + TOTP("totp"), + PASSKEYS("passkeys"); + + private final String value; + + private FactorType(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static FactorType forValue(final String value) { + return Promoter.enumFromString(value, FactorType.values()); + } + } + + + //@JsonDeserialize(builder = CreatePasskeysChallengeRequest.Builder.class) + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @ToString + public static class CreatePasskeysChallengeRequest { + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("identity") + @Getter + @Setter + private String identity; + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("factor_sid") + @Getter + @Setter + private String factorSid; + + } + + /** + * Converts a JSON String into a NewChallenge object using the provided ObjectMapper. + * + * @param json Raw JSON String + * @param objectMapper Jackson ObjectMapper + * @return NewChallenge object represented by the provided JSON + */ + public static NewChallenge fromJson(final String json, final ObjectMapper objectMapper) { + // Convert all checked exceptions to Runtime + try { + return objectMapper.readValue(json, NewChallenge.class); + } catch (final JsonMappingException | JsonParseException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + /** + * Converts a JSON InputStream into a NewChallenge object using the provided + * ObjectMapper. + * + * @param json Raw JSON InputStream + * @param objectMapper Jackson ObjectMapper + * @return NewChallenge object represented by the provided JSON + */ + public static NewChallenge fromJson(final InputStream json, final ObjectMapper objectMapper) { + // Convert all checked exceptions to Runtime + try { + return objectMapper.readValue(json, NewChallenge.class); + } catch (final JsonMappingException | JsonParseException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter + private final String accountSid; + @Getter + private final ZonedDateTime dateCreated; + @Getter + private final ZonedDateTime dateResponded; + @Getter + private final ZonedDateTime dateUpdated; + @Getter + private final Object details; + @Getter + private final String entitySid; + @Getter + private final ZonedDateTime expirationDate; + @Getter + private final String factorSid; + @Getter + private final NewChallenge.FactorType factorType; + @Getter + private final Object hiddenDetails; + @Getter + private final String identity; + @Getter + private final Map links; + @Getter + private final Object metadata; + @Getter + private final Object options; + @Getter + private final NewChallenge.RespondedReason respondedReason; + @Getter + private final String serviceSid; + @Getter + private final String sid; + @Getter + private final NewChallenge.Status status; + @Getter + private final URI url; + + @JsonCreator + private NewChallenge( + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_responded") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateResponded, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("details") final Object details, + @JsonProperty("entity_sid") final String entitySid, + @JsonProperty("expiration_date") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime expirationDate, + @JsonProperty("factor_sid") final String factorSid, + @JsonProperty("factor_type") final NewChallenge.FactorType factorType, + @JsonProperty("hidden_details") final Object hiddenDetails, + @JsonProperty("identity") final String identity, + @JsonProperty("links") final Map links, + @JsonProperty("metadata") final Object metadata, + @JsonProperty("options") final Object options, + @JsonProperty("responded_reason") final NewChallenge.RespondedReason respondedReason, + @JsonProperty("service_sid") final String serviceSid, + @JsonProperty("sid") final String sid, + @JsonProperty("status") final NewChallenge.Status status, + @JsonProperty("url") final URI url + ) { + this.accountSid = accountSid; + this.dateCreated = dateCreated; + this.dateResponded = dateResponded; + this.dateUpdated = dateUpdated; + this.details = details; + this.entitySid = entitySid; + this.expirationDate = expirationDate; + this.factorSid = factorSid; + this.factorType = factorType; + this.hiddenDetails = hiddenDetails; + this.identity = identity; + this.links = links; + this.metadata = metadata; + this.options = options; + this.respondedReason = respondedReason; + this.serviceSid = serviceSid; + this.sid = sid; + this.status = status; + this.url = url; + } + + @Override + public boolean equals(final Object o) { + if (this == o) { + return true; + } + + if (o == null || getClass() != o.getClass()) { + return false; + } + + NewChallenge other = (NewChallenge) o; + return ( + Objects.equals(accountSid, other.accountSid) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateResponded, other.dateResponded) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(details, other.details) && + Objects.equals(entitySid, other.entitySid) && + Objects.equals(expirationDate, other.expirationDate) && + Objects.equals(factorSid, other.factorSid) && + Objects.equals(factorType, other.factorType) && + Objects.equals(hiddenDetails, other.hiddenDetails) && + Objects.equals(identity, other.identity) && + Objects.equals(links, other.links) && + Objects.equals(metadata, other.metadata) && + Objects.equals(options, other.options) && + Objects.equals(respondedReason, other.respondedReason) && + Objects.equals(serviceSid, other.serviceSid) && + Objects.equals(sid, other.sid) && + Objects.equals(status, other.status) && + Objects.equals(url, other.url) + ); + } + + @Override + public int hashCode() { + return Objects.hash( + accountSid, + dateCreated, + dateResponded, + dateUpdated, + details, + entitySid, + expirationDate, + factorSid, + factorType, + hiddenDetails, + identity, + links, + metadata, + options, + respondedReason, + serviceSid, + sid, + status, + url + ); + } + + +} + diff --git a/src/main/java/com/twilio/rest/verify/v2/NewChallengeCreator.java b/src/main/java/com/twilio/rest/verify/v2/NewChallengeCreator.java new file mode 100644 index 0000000000..7cbeadedff --- /dev/null +++ b/src/main/java/com/twilio/rest/verify/v2/NewChallengeCreator.java @@ -0,0 +1,86 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Twilio - Verify + * This is the public Twilio REST API. + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package com.twilio.rest.verify.v2; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.twilio.base.Creator; +import com.twilio.constant.EnumConstants; +import com.twilio.exception.ApiConnectionException; +import com.twilio.exception.ApiException; +import com.twilio.exception.RestException; +import com.twilio.http.HttpMethod; +import com.twilio.http.Request; +import com.twilio.http.Response; +import com.twilio.http.TwilioRestClient; +import com.twilio.rest.Domains; + +public class NewChallengeCreator extends Creator { + + private String pathserviceSid; + private NewChallenge.CreatePasskeysChallengeRequest createPasskeysChallengeRequest; + + public NewChallengeCreator(final String pathserviceSid, final NewChallenge.CreatePasskeysChallengeRequest createPasskeysChallengeRequest) { + this.pathserviceSid = pathserviceSid; + this.createPasskeysChallengeRequest = createPasskeysChallengeRequest; + } + + + public NewChallengeCreator setCreatePasskeysChallengeRequest(final NewChallenge.CreatePasskeysChallengeRequest createPasskeysChallengeRequest) { + this.createPasskeysChallengeRequest = createPasskeysChallengeRequest; + return this; + } + + + @Override + public NewChallenge create(final TwilioRestClient client) { + + String path = "/v2/Services/{ServiceSid}/Passkeys/Challenges"; + + path = path.replace("{" + "ServiceSid" + "}", this.pathserviceSid.toString()); + + + Request request = new Request( + HttpMethod.POST, + Domains.VERIFY.toString(), + path + ); + request.setContentType(EnumConstants.ContentType.JSON); + addPostParams(request, client); + + Response response = client.request(request); + + if (response == null) { + throw new ApiConnectionException("NewChallenge creation failed: Unable to connect to server"); + } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { + RestException restException = RestException.fromJson( + response.getStream(), + client.getObjectMapper() + ); + if (restException == null) { + throw new ApiException("Server Error, no content", response.getStatusCode()); + } + throw new ApiException(restException); + } + + return NewChallenge.fromJson(response.getStream(), client.getObjectMapper()); + } + + private void addPostParams(final Request request, TwilioRestClient client) { + ObjectMapper objectMapper = client.getObjectMapper(); + if (createPasskeysChallengeRequest != null) { + request.setBody(NewChallenge.toJson(createPasskeysChallengeRequest, objectMapper)); + } + } +} diff --git a/src/main/java/com/twilio/rest/verify/v2/Safelist.java b/src/main/java/com/twilio/rest/verify/v2/Safelist.java index 2e675aecab..ccacb8b19f 100644 --- a/src/main/java/com/twilio/rest/verify/v2/Safelist.java +++ b/src/main/java/com/twilio/rest/verify/v2/Safelist.java @@ -18,47 +18,54 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Safelist extends Resource { - private static final long serialVersionUID = 83566412587236L; public static SafelistCreator creator(final String phoneNumber) { - return new SafelistCreator(phoneNumber); + return new SafelistCreator( + phoneNumber + ); } - public static SafelistDeleter deleter(final String pathPhoneNumber) { - return new SafelistDeleter(pathPhoneNumber); + + public static SafelistDeleter deleter(final String pathphoneNumber) { + return new SafelistDeleter( + pathphoneNumber + ); } - public static SafelistFetcher fetcher(final String pathPhoneNumber) { - return new SafelistFetcher(pathPhoneNumber); + + public static SafelistFetcher fetcher(final String pathphoneNumber) { + return new SafelistFetcher( + pathphoneNumber + ); } + /** * Converts a JSON String into a Safelist object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Safelist object represented by the provided JSON */ - public static Safelist fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Safelist fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Safelist.class); @@ -73,14 +80,11 @@ public static Safelist fromJson( * Converts a JSON InputStream into a Safelist object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Safelist object represented by the provided JSON */ - public static Safelist fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Safelist fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Safelist.class); @@ -91,33 +95,37 @@ public static Safelist fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String phoneNumber; + @Getter + private final String sid; + @Getter private final URI url; @JsonCreator private Safelist( - @JsonProperty("sid") final String sid, - @JsonProperty("phone_number") final String phoneNumber, - @JsonProperty("url") final URI url + @JsonProperty("phone_number") final String phoneNumber, + @JsonProperty("sid") final String sid, + @JsonProperty("url") final URI url ) { - this.sid = sid; this.phoneNumber = phoneNumber; + this.sid = sid; this.url = url; } - public final String getSid() { - return this.sid; - } - - public final String getPhoneNumber() { - return this.phoneNumber; - } - - public final URI getUrl() { - return this.url; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -129,16 +137,22 @@ public boolean equals(final Object o) { } Safelist other = (Safelist) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(phoneNumber, other.phoneNumber) && - Objects.equals(url, other.url) + Objects.equals(phoneNumber, other.phoneNumber) && + Objects.equals(sid, other.sid) && + Objects.equals(url, other.url) ); } @Override public int hashCode() { - return Objects.hash(sid, phoneNumber, url); + return Objects.hash( + phoneNumber, + sid, + url + ); } + + } + diff --git a/src/main/java/com/twilio/rest/verify/v2/SafelistCreator.java b/src/main/java/com/twilio/rest/verify/v2/SafelistCreator.java index 74a49d08ba..3c975a7156 100644 --- a/src/main/java/com/twilio/rest/verify/v2/SafelistCreator.java +++ b/src/main/java/com/twilio/rest/verify/v2/SafelistCreator.java @@ -14,8 +14,11 @@ package com.twilio.rest.verify.v2; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -33,56 +36,51 @@ public SafelistCreator(final String phoneNumber) { this.phoneNumber = phoneNumber; } + public SafelistCreator setPhoneNumber(final String phoneNumber) { this.phoneNumber = phoneNumber; return this; } + @Override public Safelist create(final TwilioRestClient client) { + String path = "/v2/SafeList/Numbers"; - path = - path.replace( - "{" + "PhoneNumber" + "}", - this.phoneNumber.toString() - ); Request request = new Request( - HttpMethod.POST, - Domains.VERIFY.toString(), - path + HttpMethod.POST, + Domains.VERIFY.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Safelist creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("Safelist creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Safelist.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Safelist.fromJson(response.getStream(), client.getObjectMapper()); } private void addPostParams(final Request request) { + if (phoneNumber != null) { - request.addPostParam("PhoneNumber", phoneNumber); + Serializer.toString(request, "PhoneNumber", phoneNumber, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/verify/v2/SafelistDeleter.java b/src/main/java/com/twilio/rest/verify/v2/SafelistDeleter.java index 27c8ae5051..a8d7228b7c 100644 --- a/src/main/java/com/twilio/rest/verify/v2/SafelistDeleter.java +++ b/src/main/java/com/twilio/rest/verify/v2/SafelistDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.verify.v2; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,44 +26,38 @@ public class SafelistDeleter extends Deleter { - private String pathPhoneNumber; + private String pathphoneNumber; - public SafelistDeleter(final String pathPhoneNumber) { - this.pathPhoneNumber = pathPhoneNumber; + public SafelistDeleter(final String pathphoneNumber) { + this.pathphoneNumber = pathphoneNumber; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/v2/SafeList/Numbers/{PhoneNumber}"; - path = - path.replace( - "{" + "PhoneNumber" + "}", - this.pathPhoneNumber.toString() - ); + path = path.replace("{" + "PhoneNumber" + "}", this.pathphoneNumber.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.VERIFY.toString(), - path + HttpMethod.DELETE, + Domains.VERIFY.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Safelist delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("Safelist delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/verify/v2/SafelistFetcher.java b/src/main/java/com/twilio/rest/verify/v2/SafelistFetcher.java index 1193e725ca..eb7fa35f2c 100644 --- a/src/main/java/com/twilio/rest/verify/v2/SafelistFetcher.java +++ b/src/main/java/com/twilio/rest/verify/v2/SafelistFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.verify.v2; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,51 +26,41 @@ public class SafelistFetcher extends Fetcher { - private String pathPhoneNumber; + private String pathphoneNumber; - public SafelistFetcher(final String pathPhoneNumber) { - this.pathPhoneNumber = pathPhoneNumber; + public SafelistFetcher(final String pathphoneNumber) { + this.pathphoneNumber = pathphoneNumber; } + @Override public Safelist fetch(final TwilioRestClient client) { + String path = "/v2/SafeList/Numbers/{PhoneNumber}"; - path = - path.replace( - "{" + "PhoneNumber" + "}", - this.pathPhoneNumber.toString() - ); + path = path.replace("{" + "PhoneNumber" + "}", this.pathphoneNumber.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.VERIFY.toString(), - path + HttpMethod.GET, + Domains.VERIFY.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Safelist fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Safelist fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - - return Safelist.fromJson( - response.getStream(), - client.getObjectMapper() - ); + return Safelist.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/verify/v2/Service.java b/src/main/java/com/twilio/rest/verify/v2/Service.java index 2692351b04..f1258f2372 100644 --- a/src/main/java/com/twilio/rest/verify/v2/Service.java +++ b/src/main/java/com/twilio/rest/verify/v2/Service.java @@ -18,59 +18,71 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.twilio.base.Resource; -import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Service extends Resource { - private static final long serialVersionUID = 189237551129366L; public static ServiceCreator creator(final String friendlyName) { - return new ServiceCreator(friendlyName); + return new ServiceCreator( + friendlyName + ); } - public static ServiceDeleter deleter(final String pathSid) { - return new ServiceDeleter(pathSid); + + public static ServiceDeleter deleter(final String pathsid) { + return new ServiceDeleter( + pathsid + ); } - public static ServiceFetcher fetcher(final String pathSid) { - return new ServiceFetcher(pathSid); + + public static ServiceFetcher fetcher(final String pathsid) { + return new ServiceFetcher( + pathsid + ); } + public static ServiceReader reader() { - return new ServiceReader(); + return new ServiceReader( + + ); } - public static ServiceUpdater updater(final String pathSid) { - return new ServiceUpdater(pathSid); + + public static ServiceUpdater updater(final String pathsid) { + return new ServiceUpdater( + pathsid + ); } + /** * Converts a JSON String into a Service object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Service object represented by the provided JSON */ - public static Service fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Service fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Service.class); @@ -85,14 +97,11 @@ public static Service fromJson( * Converts a JSON InputStream into a Service object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Service object represented by the provided JSON */ - public static Service fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Service fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Service.class); @@ -103,161 +112,109 @@ public static Service fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String friendlyName; + @Getter private final Integer codeLength; + @Getter + private final Boolean customCodeEnabled; + @Getter + private final ZonedDateTime dateCreated; + @Getter + private final ZonedDateTime dateUpdated; + @Getter + private final String defaultTemplateSid; + @Getter + private final Boolean doNotShareWarningEnabled; + @Getter + private final Boolean dtmfInputRequired; + @Getter + private final String friendlyName; + @Getter + private final Map links; + @Getter private final Boolean lookupEnabled; + @Getter + private final Object passkeys; + @Getter private final Boolean psd2Enabled; + @Getter + private final Object push; + @Getter + private final String sid; + @Getter private final Boolean skipSmsToLandlines; - private final Boolean dtmfInputRequired; + @Getter + private final Object totp; + @Getter private final String ttsName; - private final Boolean doNotShareWarningEnabled; - private final Boolean customCodeEnabled; - private final Map push; - private final Map totp; - private final String defaultTemplateSid; - private final Map whatsapp; - private final Map passkeys; - private final Boolean verifyEventSubscriptionEnabled; - private final ZonedDateTime dateCreated; - private final ZonedDateTime dateUpdated; + @Getter private final URI url; - private final Map links; + @Getter + private final Boolean verifyEventSubscriptionEnabled; + @Getter + private final Object whatsapp; @JsonCreator private Service( - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("code_length") final Integer codeLength, - @JsonProperty("lookup_enabled") final Boolean lookupEnabled, - @JsonProperty("psd2_enabled") final Boolean psd2Enabled, - @JsonProperty("skip_sms_to_landlines") final Boolean skipSmsToLandlines, - @JsonProperty("dtmf_input_required") final Boolean dtmfInputRequired, - @JsonProperty("tts_name") final String ttsName, - @JsonProperty( - "do_not_share_warning_enabled" - ) final Boolean doNotShareWarningEnabled, - @JsonProperty("custom_code_enabled") final Boolean customCodeEnabled, - @JsonProperty("push") final Map push, - @JsonProperty("totp") final Map totp, - @JsonProperty("default_template_sid") final String defaultTemplateSid, - @JsonProperty("whatsapp") final Map whatsapp, - @JsonProperty("passkeys") final Map passkeys, - @JsonProperty( - "verify_event_subscription_enabled" - ) final Boolean verifyEventSubscriptionEnabled, - @JsonProperty("date_created") final String dateCreated, - @JsonProperty("date_updated") final String dateUpdated, - @JsonProperty("url") final URI url, - @JsonProperty("links") final Map links + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("code_length") final Integer codeLength, + @JsonProperty("custom_code_enabled") final Boolean customCodeEnabled, + @JsonProperty("date_created") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateCreated, + @JsonProperty("date_updated") + @JsonDeserialize(using = com.twilio.converter.ISO8601Deserializer.class) final ZonedDateTime dateUpdated, + @JsonProperty("default_template_sid") final String defaultTemplateSid, + @JsonProperty("do_not_share_warning_enabled") final Boolean doNotShareWarningEnabled, + @JsonProperty("dtmf_input_required") final Boolean dtmfInputRequired, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("links") final Map links, + @JsonProperty("lookup_enabled") final Boolean lookupEnabled, + @JsonProperty("passkeys") final Object passkeys, + @JsonProperty("psd2_enabled") final Boolean psd2Enabled, + @JsonProperty("push") final Object push, + @JsonProperty("sid") final String sid, + @JsonProperty("skip_sms_to_landlines") final Boolean skipSmsToLandlines, + @JsonProperty("totp") final Object totp, + @JsonProperty("tts_name") final String ttsName, + @JsonProperty("url") final URI url, + @JsonProperty("verify_event_subscription_enabled") final Boolean verifyEventSubscriptionEnabled, + @JsonProperty("whatsapp") final Object whatsapp ) { - this.sid = sid; this.accountSid = accountSid; - this.friendlyName = friendlyName; this.codeLength = codeLength; + this.customCodeEnabled = customCodeEnabled; + this.dateCreated = dateCreated; + this.dateUpdated = dateUpdated; + this.defaultTemplateSid = defaultTemplateSid; + this.doNotShareWarningEnabled = doNotShareWarningEnabled; + this.dtmfInputRequired = dtmfInputRequired; + this.friendlyName = friendlyName; + this.links = links; this.lookupEnabled = lookupEnabled; + this.passkeys = passkeys; this.psd2Enabled = psd2Enabled; - this.skipSmsToLandlines = skipSmsToLandlines; - this.dtmfInputRequired = dtmfInputRequired; - this.ttsName = ttsName; - this.doNotShareWarningEnabled = doNotShareWarningEnabled; - this.customCodeEnabled = customCodeEnabled; this.push = push; + this.sid = sid; + this.skipSmsToLandlines = skipSmsToLandlines; this.totp = totp; - this.defaultTemplateSid = defaultTemplateSid; - this.whatsapp = whatsapp; - this.passkeys = passkeys; - this.verifyEventSubscriptionEnabled = verifyEventSubscriptionEnabled; - this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); - this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); + this.ttsName = ttsName; this.url = url; - this.links = links; - } - - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final Integer getCodeLength() { - return this.codeLength; - } - - public final Boolean getLookupEnabled() { - return this.lookupEnabled; - } - - public final Boolean getPsd2Enabled() { - return this.psd2Enabled; - } - - public final Boolean getSkipSmsToLandlines() { - return this.skipSmsToLandlines; - } - - public final Boolean getDtmfInputRequired() { - return this.dtmfInputRequired; - } - - public final String getTtsName() { - return this.ttsName; - } - - public final Boolean getDoNotShareWarningEnabled() { - return this.doNotShareWarningEnabled; - } - - public final Boolean getCustomCodeEnabled() { - return this.customCodeEnabled; - } - - public final Map getPush() { - return this.push; - } - - public final Map getTotp() { - return this.totp; - } - - public final String getDefaultTemplateSid() { - return this.defaultTemplateSid; - } - - public final Map getWhatsapp() { - return this.whatsapp; - } - - public final Map getPasskeys() { - return this.passkeys; - } - - public final Boolean getVerifyEventSubscriptionEnabled() { - return this.verifyEventSubscriptionEnabled; - } - - public final ZonedDateTime getDateCreated() { - return this.dateCreated; - } - - public final ZonedDateTime getDateUpdated() { - return this.dateUpdated; - } - - public final URI getUrl() { - return this.url; - } - - public final Map getLinks() { - return this.links; + this.verifyEventSubscriptionEnabled = verifyEventSubscriptionEnabled; + this.whatsapp = whatsapp; } @Override @@ -271,62 +228,58 @@ public boolean equals(final Object o) { } Service other = (Service) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(codeLength, other.codeLength) && - Objects.equals(lookupEnabled, other.lookupEnabled) && - Objects.equals(psd2Enabled, other.psd2Enabled) && - Objects.equals(skipSmsToLandlines, other.skipSmsToLandlines) && - Objects.equals(dtmfInputRequired, other.dtmfInputRequired) && - Objects.equals(ttsName, other.ttsName) && - Objects.equals( - doNotShareWarningEnabled, - other.doNotShareWarningEnabled - ) && - Objects.equals(customCodeEnabled, other.customCodeEnabled) && - Objects.equals(push, other.push) && - Objects.equals(totp, other.totp) && - Objects.equals(defaultTemplateSid, other.defaultTemplateSid) && - Objects.equals(whatsapp, other.whatsapp) && - Objects.equals(passkeys, other.passkeys) && - Objects.equals( - verifyEventSubscriptionEnabled, - other.verifyEventSubscriptionEnabled - ) && - Objects.equals(dateCreated, other.dateCreated) && - Objects.equals(dateUpdated, other.dateUpdated) && - Objects.equals(url, other.url) && - Objects.equals(links, other.links) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(codeLength, other.codeLength) && + Objects.equals(customCodeEnabled, other.customCodeEnabled) && + Objects.equals(dateCreated, other.dateCreated) && + Objects.equals(dateUpdated, other.dateUpdated) && + Objects.equals(defaultTemplateSid, other.defaultTemplateSid) && + Objects.equals(doNotShareWarningEnabled, other.doNotShareWarningEnabled) && + Objects.equals(dtmfInputRequired, other.dtmfInputRequired) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(links, other.links) && + Objects.equals(lookupEnabled, other.lookupEnabled) && + Objects.equals(passkeys, other.passkeys) && + Objects.equals(psd2Enabled, other.psd2Enabled) && + Objects.equals(push, other.push) && + Objects.equals(sid, other.sid) && + Objects.equals(skipSmsToLandlines, other.skipSmsToLandlines) && + Objects.equals(totp, other.totp) && + Objects.equals(ttsName, other.ttsName) && + Objects.equals(url, other.url) && + Objects.equals(verifyEventSubscriptionEnabled, other.verifyEventSubscriptionEnabled) && + Objects.equals(whatsapp, other.whatsapp) ); } @Override public int hashCode() { return Objects.hash( - sid, - accountSid, - friendlyName, - codeLength, - lookupEnabled, - psd2Enabled, - skipSmsToLandlines, - dtmfInputRequired, - ttsName, - doNotShareWarningEnabled, - customCodeEnabled, - push, - totp, - defaultTemplateSid, - whatsapp, - passkeys, - verifyEventSubscriptionEnabled, - dateCreated, - dateUpdated, - url, - links + accountSid, + codeLength, + customCodeEnabled, + dateCreated, + dateUpdated, + defaultTemplateSid, + doNotShareWarningEnabled, + dtmfInputRequired, + friendlyName, + links, + lookupEnabled, + passkeys, + psd2Enabled, + push, + sid, + skipSmsToLandlines, + totp, + ttsName, + url, + verifyEventSubscriptionEnabled, + whatsapp ); } + + } + diff --git a/src/main/java/com/twilio/rest/verify/v2/ServiceCreator.java b/src/main/java/com/twilio/rest/verify/v2/ServiceCreator.java index ae9ed50518..1f6082578b 100644 --- a/src/main/java/com/twilio/rest/verify/v2/ServiceCreator.java +++ b/src/main/java/com/twilio/rest/verify/v2/ServiceCreator.java @@ -14,8 +14,11 @@ package com.twilio.rest.verify.v2; + import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -58,198 +61,188 @@ public ServiceCreator(final String friendlyName) { this.friendlyName = friendlyName; } + public ServiceCreator setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + public ServiceCreator setCodeLength(final Integer codeLength) { this.codeLength = codeLength; return this; } + public ServiceCreator setLookupEnabled(final Boolean lookupEnabled) { this.lookupEnabled = lookupEnabled; return this; } - public ServiceCreator setSkipSmsToLandlines( - final Boolean skipSmsToLandlines - ) { + + public ServiceCreator setSkipSmsToLandlines(final Boolean skipSmsToLandlines) { this.skipSmsToLandlines = skipSmsToLandlines; return this; } - public ServiceCreator setDtmfInputRequired( - final Boolean dtmfInputRequired - ) { + + public ServiceCreator setDtmfInputRequired(final Boolean dtmfInputRequired) { this.dtmfInputRequired = dtmfInputRequired; return this; } + public ServiceCreator setTtsName(final String ttsName) { this.ttsName = ttsName; return this; } + public ServiceCreator setPsd2Enabled(final Boolean psd2Enabled) { this.psd2Enabled = psd2Enabled; return this; } - public ServiceCreator setDoNotShareWarningEnabled( - final Boolean doNotShareWarningEnabled - ) { + + public ServiceCreator setDoNotShareWarningEnabled(final Boolean doNotShareWarningEnabled) { this.doNotShareWarningEnabled = doNotShareWarningEnabled; return this; } - public ServiceCreator setCustomCodeEnabled( - final Boolean customCodeEnabled - ) { + + public ServiceCreator setCustomCodeEnabled(final Boolean customCodeEnabled) { this.customCodeEnabled = customCodeEnabled; return this; } + public ServiceCreator setPushIncludeDate(final Boolean pushIncludeDate) { this.pushIncludeDate = pushIncludeDate; return this; } - public ServiceCreator setPushApnCredentialSid( - final String pushApnCredentialSid - ) { + + public ServiceCreator setPushApnCredentialSid(final String pushApnCredentialSid) { this.pushApnCredentialSid = pushApnCredentialSid; return this; } - public ServiceCreator setPushFcmCredentialSid( - final String pushFcmCredentialSid - ) { + + public ServiceCreator setPushFcmCredentialSid(final String pushFcmCredentialSid) { this.pushFcmCredentialSid = pushFcmCredentialSid; return this; } + public ServiceCreator setTotpIssuer(final String totpIssuer) { this.totpIssuer = totpIssuer; return this; } + public ServiceCreator setTotpTimeStep(final Integer totpTimeStep) { this.totpTimeStep = totpTimeStep; return this; } + public ServiceCreator setTotpCodeLength(final Integer totpCodeLength) { this.totpCodeLength = totpCodeLength; return this; } + public ServiceCreator setTotpSkew(final Integer totpSkew) { this.totpSkew = totpSkew; return this; } - public ServiceCreator setDefaultTemplateSid( - final String defaultTemplateSid - ) { + + public ServiceCreator setDefaultTemplateSid(final String defaultTemplateSid) { this.defaultTemplateSid = defaultTemplateSid; return this; } - public ServiceCreator setWhatsappMsgServiceSid( - final String whatsappMsgServiceSid - ) { + + public ServiceCreator setWhatsappMsgServiceSid(final String whatsappMsgServiceSid) { this.whatsappMsgServiceSid = whatsappMsgServiceSid; return this; } + public ServiceCreator setWhatsappFrom(final String whatsappFrom) { this.whatsappFrom = whatsappFrom; return this; } - public ServiceCreator setPasskeysRelyingPartyId( - final String passkeysRelyingPartyId - ) { + + public ServiceCreator setPasskeysRelyingPartyId(final String passkeysRelyingPartyId) { this.passkeysRelyingPartyId = passkeysRelyingPartyId; return this; } - public ServiceCreator setPasskeysRelyingPartyName( - final String passkeysRelyingPartyName - ) { + + public ServiceCreator setPasskeysRelyingPartyName(final String passkeysRelyingPartyName) { this.passkeysRelyingPartyName = passkeysRelyingPartyName; return this; } - public ServiceCreator setPasskeysRelyingPartyOrigins( - final String passkeysRelyingPartyOrigins - ) { + + public ServiceCreator setPasskeysRelyingPartyOrigins(final String passkeysRelyingPartyOrigins) { this.passkeysRelyingPartyOrigins = passkeysRelyingPartyOrigins; return this; } - public ServiceCreator setPasskeysAuthenticatorAttachment( - final String passkeysAuthenticatorAttachment - ) { + + public ServiceCreator setPasskeysAuthenticatorAttachment(final String passkeysAuthenticatorAttachment) { this.passkeysAuthenticatorAttachment = passkeysAuthenticatorAttachment; return this; } - public ServiceCreator setPasskeysDiscoverableCredentials( - final String passkeysDiscoverableCredentials - ) { + + public ServiceCreator setPasskeysDiscoverableCredentials(final String passkeysDiscoverableCredentials) { this.passkeysDiscoverableCredentials = passkeysDiscoverableCredentials; return this; } - public ServiceCreator setPasskeysUserVerification( - final String passkeysUserVerification - ) { + + public ServiceCreator setPasskeysUserVerification(final String passkeysUserVerification) { this.passkeysUserVerification = passkeysUserVerification; return this; } - public ServiceCreator setVerifyEventSubscriptionEnabled( - final Boolean verifyEventSubscriptionEnabled - ) { + + public ServiceCreator setVerifyEventSubscriptionEnabled(final Boolean verifyEventSubscriptionEnabled) { this.verifyEventSubscriptionEnabled = verifyEventSubscriptionEnabled; return this; } + @Override public Service create(final TwilioRestClient client) { + String path = "/v2/Services"; - path = - path.replace( - "{" + "FriendlyName" + "}", - this.friendlyName.toString() - ); Request request = new Request( - HttpMethod.POST, - Domains.VERIFY.toString(), - path + HttpMethod.POST, + Domains.VERIFY.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Service creation failed: Unable to connect to server" - ); + throw new ApiConnectionException("Service creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -258,122 +251,136 @@ public Service create(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + if (codeLength != null) { - request.addPostParam("CodeLength", codeLength.toString()); + Serializer.toString(request, "CodeLength", codeLength, ParameterType.URLENCODED); } + + if (lookupEnabled != null) { - request.addPostParam("LookupEnabled", lookupEnabled.toString()); + Serializer.toString(request, "LookupEnabled", lookupEnabled, ParameterType.URLENCODED); } + + if (skipSmsToLandlines != null) { - request.addPostParam( - "SkipSmsToLandlines", - skipSmsToLandlines.toString() - ); + Serializer.toString(request, "SkipSmsToLandlines", skipSmsToLandlines, ParameterType.URLENCODED); } + + if (dtmfInputRequired != null) { - request.addPostParam( - "DtmfInputRequired", - dtmfInputRequired.toString() - ); + Serializer.toString(request, "DtmfInputRequired", dtmfInputRequired, ParameterType.URLENCODED); } + + if (ttsName != null) { - request.addPostParam("TtsName", ttsName); + Serializer.toString(request, "TtsName", ttsName, ParameterType.URLENCODED); } + + if (psd2Enabled != null) { - request.addPostParam("Psd2Enabled", psd2Enabled.toString()); + Serializer.toString(request, "Psd2Enabled", psd2Enabled, ParameterType.URLENCODED); } + + if (doNotShareWarningEnabled != null) { - request.addPostParam( - "DoNotShareWarningEnabled", - doNotShareWarningEnabled.toString() - ); + Serializer.toString(request, "DoNotShareWarningEnabled", doNotShareWarningEnabled, ParameterType.URLENCODED); } + + if (customCodeEnabled != null) { - request.addPostParam( - "CustomCodeEnabled", - customCodeEnabled.toString() - ); + Serializer.toString(request, "CustomCodeEnabled", customCodeEnabled, ParameterType.URLENCODED); } + + if (pushIncludeDate != null) { - request.addPostParam( - "Push.IncludeDate", - pushIncludeDate.toString() - ); + Serializer.toString(request, "Push.IncludeDate", pushIncludeDate, ParameterType.URLENCODED); } + + if (pushApnCredentialSid != null) { - request.addPostParam("Push.ApnCredentialSid", pushApnCredentialSid); + Serializer.toString(request, "Push.ApnCredentialSid", pushApnCredentialSid, ParameterType.URLENCODED); } + + if (pushFcmCredentialSid != null) { - request.addPostParam("Push.FcmCredentialSid", pushFcmCredentialSid); + Serializer.toString(request, "Push.FcmCredentialSid", pushFcmCredentialSid, ParameterType.URLENCODED); } + + if (totpIssuer != null) { - request.addPostParam("Totp.Issuer", totpIssuer); + Serializer.toString(request, "Totp.Issuer", totpIssuer, ParameterType.URLENCODED); } + + if (totpTimeStep != null) { - request.addPostParam("Totp.TimeStep", totpTimeStep.toString()); + Serializer.toString(request, "Totp.TimeStep", totpTimeStep, ParameterType.URLENCODED); } + + if (totpCodeLength != null) { - request.addPostParam("Totp.CodeLength", totpCodeLength.toString()); + Serializer.toString(request, "Totp.CodeLength", totpCodeLength, ParameterType.URLENCODED); } + + if (totpSkew != null) { - request.addPostParam("Totp.Skew", totpSkew.toString()); + Serializer.toString(request, "Totp.Skew", totpSkew, ParameterType.URLENCODED); } + + if (defaultTemplateSid != null) { - request.addPostParam("DefaultTemplateSid", defaultTemplateSid); + Serializer.toString(request, "DefaultTemplateSid", defaultTemplateSid, ParameterType.URLENCODED); } + + if (whatsappMsgServiceSid != null) { - request.addPostParam( - "Whatsapp.MsgServiceSid", - whatsappMsgServiceSid - ); + Serializer.toString(request, "Whatsapp.MsgServiceSid", whatsappMsgServiceSid, ParameterType.URLENCODED); } + + if (whatsappFrom != null) { - request.addPostParam("Whatsapp.From", whatsappFrom); + Serializer.toString(request, "Whatsapp.From", whatsappFrom, ParameterType.URLENCODED); } + + if (passkeysRelyingPartyId != null) { - request.addPostParam( - "Passkeys.RelyingParty.Id", - passkeysRelyingPartyId - ); + Serializer.toString(request, "Passkeys.RelyingParty.Id", passkeysRelyingPartyId, ParameterType.URLENCODED); } + + if (passkeysRelyingPartyName != null) { - request.addPostParam( - "Passkeys.RelyingParty.Name", - passkeysRelyingPartyName - ); + Serializer.toString(request, "Passkeys.RelyingParty.Name", passkeysRelyingPartyName, ParameterType.URLENCODED); } + + if (passkeysRelyingPartyOrigins != null) { - request.addPostParam( - "Passkeys.RelyingParty.Origins", - passkeysRelyingPartyOrigins - ); + Serializer.toString(request, "Passkeys.RelyingParty.Origins", passkeysRelyingPartyOrigins, ParameterType.URLENCODED); } + + if (passkeysAuthenticatorAttachment != null) { - request.addPostParam( - "Passkeys.AuthenticatorAttachment", - passkeysAuthenticatorAttachment - ); + Serializer.toString(request, "Passkeys.AuthenticatorAttachment", passkeysAuthenticatorAttachment, ParameterType.URLENCODED); } + + if (passkeysDiscoverableCredentials != null) { - request.addPostParam( - "Passkeys.DiscoverableCredentials", - passkeysDiscoverableCredentials - ); + Serializer.toString(request, "Passkeys.DiscoverableCredentials", passkeysDiscoverableCredentials, ParameterType.URLENCODED); } + + if (passkeysUserVerification != null) { - request.addPostParam( - "Passkeys.UserVerification", - passkeysUserVerification - ); + Serializer.toString(request, "Passkeys.UserVerification", passkeysUserVerification, ParameterType.URLENCODED); } + + if (verifyEventSubscriptionEnabled != null) { - request.addPostParam( - "VerifyEventSubscriptionEnabled", - verifyEventSubscriptionEnabled.toString() - ); + Serializer.toString(request, "VerifyEventSubscriptionEnabled", verifyEventSubscriptionEnabled, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/verify/v2/ServiceDeleter.java b/src/main/java/com/twilio/rest/verify/v2/ServiceDeleter.java index f303b5f53b..65fb14e5ee 100644 --- a/src/main/java/com/twilio/rest/verify/v2/ServiceDeleter.java +++ b/src/main/java/com/twilio/rest/verify/v2/ServiceDeleter.java @@ -15,7 +15,6 @@ package com.twilio.rest.verify.v2; import com.twilio.base.Deleter; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,40 +26,38 @@ public class ServiceDeleter extends Deleter { - private String pathSid; + private String pathsid; - public ServiceDeleter(final String pathSid) { - this.pathSid = pathSid; + public ServiceDeleter(final String pathsid) { + this.pathsid = pathsid; } + @Override public boolean delete(final TwilioRestClient client) { + String path = "/v2/Services/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.DELETE, - Domains.VERIFY.toString(), - path + HttpMethod.DELETE, + Domains.VERIFY.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Service delete failed: Unable to connect to server" - ); + throw new ApiConnectionException("Service delete failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } diff --git a/src/main/java/com/twilio/rest/verify/v2/ServiceFetcher.java b/src/main/java/com/twilio/rest/verify/v2/ServiceFetcher.java index c8410e5623..bb58590dc6 100644 --- a/src/main/java/com/twilio/rest/verify/v2/ServiceFetcher.java +++ b/src/main/java/com/twilio/rest/verify/v2/ServiceFetcher.java @@ -15,7 +15,6 @@ package com.twilio.rest.verify.v2; import com.twilio.base.Fetcher; -import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -27,44 +26,41 @@ public class ServiceFetcher extends Fetcher { - private String pathSid; + private String pathsid; - public ServiceFetcher(final String pathSid) { - this.pathSid = pathSid; + public ServiceFetcher(final String pathsid) { + this.pathsid = pathsid; } + @Override public Service fetch(final TwilioRestClient client) { + String path = "/v2/Services/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.GET, - Domains.VERIFY.toString(), - path + HttpMethod.GET, + Domains.VERIFY.toString(), + path ); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + Response response = client.request(request); if (response == null) { - throw new ApiConnectionException( - "Service fetch failed: Unable to connect to server" - ); + throw new ApiConnectionException("Service fetch failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } - return Service.fromJson(response.getStream(), client.getObjectMapper()); } } diff --git a/src/main/java/com/twilio/rest/verify/v2/ServiceReader.java b/src/main/java/com/twilio/rest/verify/v2/ServiceReader.java index 33de1e2fe1..32a99d534d 100644 --- a/src/main/java/com/twilio/rest/verify/v2/ServiceReader.java +++ b/src/main/java/com/twilio/rest/verify/v2/ServiceReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -31,105 +32,83 @@ public class ServiceReader extends Reader { private Long pageSize; - public ServiceReader() {} + public ServiceReader() { + } + public ServiceReader setPageSize(final Long pageSize) { this.pageSize = pageSize; return this; } + @Override public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage(final TwilioRestClient client) { + String path = "/v2/Services"; + Request request = new Request( - HttpMethod.GET, - Domains.VERIFY.toString(), - path + HttpMethod.GET, + Domains.VERIFY.toString(), + path ); - addQueryParams(request); - request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + return pageForRequest(client, request); } - private Page pageForRequest( - final TwilioRestClient client, - final Request request - ) { + private Page pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException( - "Service read failed: Unable to connect to server" - ); + throw new ApiConnectionException("Service read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() - ); + response.getStream(), + client.getObjectMapper()); + if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } return Page.fromJson( - "services", - response.getContent(), - Service.class, - client.getObjectMapper() - ); + "services", + response.getContent(), + Service.class, + client.getObjectMapper()); } @Override - public Page previousPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getPreviousPageUrl(Domains.VERIFY.toString()) - ); + public Page previousPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page nextPage( - final Page page, - final TwilioRestClient client - ) { - Request request = new Request( - HttpMethod.GET, - page.getNextPageUrl(Domains.VERIFY.toString()) - ); + public Page nextPage(final Page page, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); return pageForRequest(client, request); } @Override - public Page getPage( - final String targetUrl, - final TwilioRestClient client - ) { + public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); } private void addQueryParams(final Request request) { + + if (pageSize != null) { - request.addQueryParam("PageSize", pageSize.toString()); + Serializer.toString(request, "PageSize", pageSize, ParameterType.QUERY); } - if (getPageSize() != null) { - request.addQueryParam("PageSize", Integer.toString(getPageSize())); - } + } } diff --git a/src/main/java/com/twilio/rest/verify/v2/ServiceUpdater.java b/src/main/java/com/twilio/rest/verify/v2/ServiceUpdater.java index 52469c145f..d133605b12 100644 --- a/src/main/java/com/twilio/rest/verify/v2/ServiceUpdater.java +++ b/src/main/java/com/twilio/rest/verify/v2/ServiceUpdater.java @@ -16,6 +16,8 @@ import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -26,8 +28,7 @@ import com.twilio.rest.Domains; public class ServiceUpdater extends Updater { - - private String pathSid; + private String pathsid; private String friendlyName; private Integer codeLength; private Boolean lookupEnabled; @@ -55,198 +56,194 @@ public class ServiceUpdater extends Updater { private String passkeysUserVerification; private Boolean verifyEventSubscriptionEnabled; - public ServiceUpdater(final String pathSid) { - this.pathSid = pathSid; + public ServiceUpdater(final String pathsid) { + this.pathsid = pathsid; } + public ServiceUpdater setFriendlyName(final String friendlyName) { this.friendlyName = friendlyName; return this; } + public ServiceUpdater setCodeLength(final Integer codeLength) { this.codeLength = codeLength; return this; } + public ServiceUpdater setLookupEnabled(final Boolean lookupEnabled) { this.lookupEnabled = lookupEnabled; return this; } - public ServiceUpdater setSkipSmsToLandlines( - final Boolean skipSmsToLandlines - ) { + + public ServiceUpdater setSkipSmsToLandlines(final Boolean skipSmsToLandlines) { this.skipSmsToLandlines = skipSmsToLandlines; return this; } - public ServiceUpdater setDtmfInputRequired( - final Boolean dtmfInputRequired - ) { + + public ServiceUpdater setDtmfInputRequired(final Boolean dtmfInputRequired) { this.dtmfInputRequired = dtmfInputRequired; return this; } + public ServiceUpdater setTtsName(final String ttsName) { this.ttsName = ttsName; return this; } + public ServiceUpdater setPsd2Enabled(final Boolean psd2Enabled) { this.psd2Enabled = psd2Enabled; return this; } - public ServiceUpdater setDoNotShareWarningEnabled( - final Boolean doNotShareWarningEnabled - ) { + + public ServiceUpdater setDoNotShareWarningEnabled(final Boolean doNotShareWarningEnabled) { this.doNotShareWarningEnabled = doNotShareWarningEnabled; return this; } - public ServiceUpdater setCustomCodeEnabled( - final Boolean customCodeEnabled - ) { + + public ServiceUpdater setCustomCodeEnabled(final Boolean customCodeEnabled) { this.customCodeEnabled = customCodeEnabled; return this; } + public ServiceUpdater setPushIncludeDate(final Boolean pushIncludeDate) { this.pushIncludeDate = pushIncludeDate; return this; } - public ServiceUpdater setPushApnCredentialSid( - final String pushApnCredentialSid - ) { + + public ServiceUpdater setPushApnCredentialSid(final String pushApnCredentialSid) { this.pushApnCredentialSid = pushApnCredentialSid; return this; } - public ServiceUpdater setPushFcmCredentialSid( - final String pushFcmCredentialSid - ) { + + public ServiceUpdater setPushFcmCredentialSid(final String pushFcmCredentialSid) { this.pushFcmCredentialSid = pushFcmCredentialSid; return this; } + public ServiceUpdater setTotpIssuer(final String totpIssuer) { this.totpIssuer = totpIssuer; return this; } + public ServiceUpdater setTotpTimeStep(final Integer totpTimeStep) { this.totpTimeStep = totpTimeStep; return this; } + public ServiceUpdater setTotpCodeLength(final Integer totpCodeLength) { this.totpCodeLength = totpCodeLength; return this; } + public ServiceUpdater setTotpSkew(final Integer totpSkew) { this.totpSkew = totpSkew; return this; } - public ServiceUpdater setDefaultTemplateSid( - final String defaultTemplateSid - ) { + + public ServiceUpdater setDefaultTemplateSid(final String defaultTemplateSid) { this.defaultTemplateSid = defaultTemplateSid; return this; } - public ServiceUpdater setWhatsappMsgServiceSid( - final String whatsappMsgServiceSid - ) { + + public ServiceUpdater setWhatsappMsgServiceSid(final String whatsappMsgServiceSid) { this.whatsappMsgServiceSid = whatsappMsgServiceSid; return this; } + public ServiceUpdater setWhatsappFrom(final String whatsappFrom) { this.whatsappFrom = whatsappFrom; return this; } - public ServiceUpdater setPasskeysRelyingPartyId( - final String passkeysRelyingPartyId - ) { + + public ServiceUpdater setPasskeysRelyingPartyId(final String passkeysRelyingPartyId) { this.passkeysRelyingPartyId = passkeysRelyingPartyId; return this; } - public ServiceUpdater setPasskeysRelyingPartyName( - final String passkeysRelyingPartyName - ) { + + public ServiceUpdater setPasskeysRelyingPartyName(final String passkeysRelyingPartyName) { this.passkeysRelyingPartyName = passkeysRelyingPartyName; return this; } - public ServiceUpdater setPasskeysRelyingPartyOrigins( - final String passkeysRelyingPartyOrigins - ) { + + public ServiceUpdater setPasskeysRelyingPartyOrigins(final String passkeysRelyingPartyOrigins) { this.passkeysRelyingPartyOrigins = passkeysRelyingPartyOrigins; return this; } - public ServiceUpdater setPasskeysAuthenticatorAttachment( - final String passkeysAuthenticatorAttachment - ) { + + public ServiceUpdater setPasskeysAuthenticatorAttachment(final String passkeysAuthenticatorAttachment) { this.passkeysAuthenticatorAttachment = passkeysAuthenticatorAttachment; return this; } - public ServiceUpdater setPasskeysDiscoverableCredentials( - final String passkeysDiscoverableCredentials - ) { + + public ServiceUpdater setPasskeysDiscoverableCredentials(final String passkeysDiscoverableCredentials) { this.passkeysDiscoverableCredentials = passkeysDiscoverableCredentials; return this; } - public ServiceUpdater setPasskeysUserVerification( - final String passkeysUserVerification - ) { + + public ServiceUpdater setPasskeysUserVerification(final String passkeysUserVerification) { this.passkeysUserVerification = passkeysUserVerification; return this; } - public ServiceUpdater setVerifyEventSubscriptionEnabled( - final Boolean verifyEventSubscriptionEnabled - ) { + + public ServiceUpdater setVerifyEventSubscriptionEnabled(final Boolean verifyEventSubscriptionEnabled) { this.verifyEventSubscriptionEnabled = verifyEventSubscriptionEnabled; return this; } + @Override public Service update(final TwilioRestClient client) { + String path = "/v2/Services/{Sid}"; - path = path.replace("{" + "Sid" + "}", this.pathSid.toString()); + path = path.replace("{" + "Sid" + "}", this.pathsid.toString()); + Request request = new Request( - HttpMethod.POST, - Domains.VERIFY.toString(), - path + HttpMethod.POST, + Domains.VERIFY.toString(), + path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); addPostParams(request); + Response response = client.request(request); + if (response == null) { - throw new ApiConnectionException( - "Service update failed: Unable to connect to server" - ); + throw new ApiConnectionException("Service update failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper() + response.getStream(), + client.getObjectMapper() ); if (restException == null) { - throw new ApiException( - "Server Error, no content", - response.getStatusCode() - ); + throw new ApiException("Server Error, no content", response.getStatusCode()); } throw new ApiException(restException); } @@ -255,122 +252,136 @@ public Service update(final TwilioRestClient client) { } private void addPostParams(final Request request) { + if (friendlyName != null) { - request.addPostParam("FriendlyName", friendlyName); + Serializer.toString(request, "FriendlyName", friendlyName, ParameterType.URLENCODED); } + + if (codeLength != null) { - request.addPostParam("CodeLength", codeLength.toString()); + Serializer.toString(request, "CodeLength", codeLength, ParameterType.URLENCODED); } + + if (lookupEnabled != null) { - request.addPostParam("LookupEnabled", lookupEnabled.toString()); + Serializer.toString(request, "LookupEnabled", lookupEnabled, ParameterType.URLENCODED); } + + if (skipSmsToLandlines != null) { - request.addPostParam( - "SkipSmsToLandlines", - skipSmsToLandlines.toString() - ); + Serializer.toString(request, "SkipSmsToLandlines", skipSmsToLandlines, ParameterType.URLENCODED); } + + if (dtmfInputRequired != null) { - request.addPostParam( - "DtmfInputRequired", - dtmfInputRequired.toString() - ); + Serializer.toString(request, "DtmfInputRequired", dtmfInputRequired, ParameterType.URLENCODED); } + + if (ttsName != null) { - request.addPostParam("TtsName", ttsName); + Serializer.toString(request, "TtsName", ttsName, ParameterType.URLENCODED); } + + if (psd2Enabled != null) { - request.addPostParam("Psd2Enabled", psd2Enabled.toString()); + Serializer.toString(request, "Psd2Enabled", psd2Enabled, ParameterType.URLENCODED); } + + if (doNotShareWarningEnabled != null) { - request.addPostParam( - "DoNotShareWarningEnabled", - doNotShareWarningEnabled.toString() - ); + Serializer.toString(request, "DoNotShareWarningEnabled", doNotShareWarningEnabled, ParameterType.URLENCODED); } + + if (customCodeEnabled != null) { - request.addPostParam( - "CustomCodeEnabled", - customCodeEnabled.toString() - ); + Serializer.toString(request, "CustomCodeEnabled", customCodeEnabled, ParameterType.URLENCODED); } + + if (pushIncludeDate != null) { - request.addPostParam( - "Push.IncludeDate", - pushIncludeDate.toString() - ); + Serializer.toString(request, "Push.IncludeDate", pushIncludeDate, ParameterType.URLENCODED); } + + if (pushApnCredentialSid != null) { - request.addPostParam("Push.ApnCredentialSid", pushApnCredentialSid); + Serializer.toString(request, "Push.ApnCredentialSid", pushApnCredentialSid, ParameterType.URLENCODED); } + + if (pushFcmCredentialSid != null) { - request.addPostParam("Push.FcmCredentialSid", pushFcmCredentialSid); + Serializer.toString(request, "Push.FcmCredentialSid", pushFcmCredentialSid, ParameterType.URLENCODED); } + + if (totpIssuer != null) { - request.addPostParam("Totp.Issuer", totpIssuer); + Serializer.toString(request, "Totp.Issuer", totpIssuer, ParameterType.URLENCODED); } + + if (totpTimeStep != null) { - request.addPostParam("Totp.TimeStep", totpTimeStep.toString()); + Serializer.toString(request, "Totp.TimeStep", totpTimeStep, ParameterType.URLENCODED); } + + if (totpCodeLength != null) { - request.addPostParam("Totp.CodeLength", totpCodeLength.toString()); + Serializer.toString(request, "Totp.CodeLength", totpCodeLength, ParameterType.URLENCODED); } + + if (totpSkew != null) { - request.addPostParam("Totp.Skew", totpSkew.toString()); + Serializer.toString(request, "Totp.Skew", totpSkew, ParameterType.URLENCODED); } + + if (defaultTemplateSid != null) { - request.addPostParam("DefaultTemplateSid", defaultTemplateSid); + Serializer.toString(request, "DefaultTemplateSid", defaultTemplateSid, ParameterType.URLENCODED); } + + if (whatsappMsgServiceSid != null) { - request.addPostParam( - "Whatsapp.MsgServiceSid", - whatsappMsgServiceSid - ); + Serializer.toString(request, "Whatsapp.MsgServiceSid", whatsappMsgServiceSid, ParameterType.URLENCODED); } + + if (whatsappFrom != null) { - request.addPostParam("Whatsapp.From", whatsappFrom); + Serializer.toString(request, "Whatsapp.From", whatsappFrom, ParameterType.URLENCODED); } + + if (passkeysRelyingPartyId != null) { - request.addPostParam( - "Passkeys.RelyingParty.Id", - passkeysRelyingPartyId - ); + Serializer.toString(request, "Passkeys.RelyingParty.Id", passkeysRelyingPartyId, ParameterType.URLENCODED); } + + if (passkeysRelyingPartyName != null) { - request.addPostParam( - "Passkeys.RelyingParty.Name", - passkeysRelyingPartyName - ); + Serializer.toString(request, "Passkeys.RelyingParty.Name", passkeysRelyingPartyName, ParameterType.URLENCODED); } + + if (passkeysRelyingPartyOrigins != null) { - request.addPostParam( - "Passkeys.RelyingParty.Origins", - passkeysRelyingPartyOrigins - ); + Serializer.toString(request, "Passkeys.RelyingParty.Origins", passkeysRelyingPartyOrigins, ParameterType.URLENCODED); } + + if (passkeysAuthenticatorAttachment != null) { - request.addPostParam( - "Passkeys.AuthenticatorAttachment", - passkeysAuthenticatorAttachment - ); + Serializer.toString(request, "Passkeys.AuthenticatorAttachment", passkeysAuthenticatorAttachment, ParameterType.URLENCODED); } + + if (passkeysDiscoverableCredentials != null) { - request.addPostParam( - "Passkeys.DiscoverableCredentials", - passkeysDiscoverableCredentials - ); + Serializer.toString(request, "Passkeys.DiscoverableCredentials", passkeysDiscoverableCredentials, ParameterType.URLENCODED); } + + if (passkeysUserVerification != null) { - request.addPostParam( - "Passkeys.UserVerification", - passkeysUserVerification - ); + Serializer.toString(request, "Passkeys.UserVerification", passkeysUserVerification, ParameterType.URLENCODED); } + + if (verifyEventSubscriptionEnabled != null) { - request.addPostParam( - "VerifyEventSubscriptionEnabled", - verifyEventSubscriptionEnabled.toString() - ); + Serializer.toString(request, "VerifyEventSubscriptionEnabled", verifyEventSubscriptionEnabled, ParameterType.URLENCODED); } + + } } diff --git a/src/main/java/com/twilio/rest/verify/v2/Template.java b/src/main/java/com/twilio/rest/verify/v2/Template.java index 5bf3b5da29..4147e41101 100644 --- a/src/main/java/com/twilio/rest/verify/v2/Template.java +++ b/src/main/java/com/twilio/rest/verify/v2/Template.java @@ -18,41 +18,40 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; +import lombok.Getter; +import lombok.ToString; + import java.io.IOException; import java.io.InputStream; import java.util.List; -import java.util.Map; -import java.util.Map; import java.util.Objects; -import lombok.ToString; -import lombok.ToString; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Template extends Resource { - private static final long serialVersionUID = 229000530855919L; public static TemplateReader reader() { - return new TemplateReader(); + return new TemplateReader( + + ); } + /** * Converts a JSON String into a Template object using the provided ObjectMapper. * - * @param json Raw JSON String + * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Template object represented by the provided JSON */ - public static Template fromJson( - final String json, - final ObjectMapper objectMapper - ) { + public static Template fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Template.class); @@ -67,14 +66,11 @@ public static Template fromJson( * Converts a JSON InputStream into a Template object using the provided * ObjectMapper. * - * @param json Raw JSON InputStream + * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Template object represented by the provided JSON */ - public static Template fromJson( - final InputStream json, - final ObjectMapper objectMapper - ) { + public static Template fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Template.class); @@ -85,47 +81,45 @@ public static Template fromJson( } } - private final String sid; + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + + @Getter private final String accountSid; - private final String friendlyName; + @Getter private final List channels; - private final Map translations; + @Getter + private final String friendlyName; + @Getter + private final String sid; + @Getter + private final Object translations; @JsonCreator private Template( - @JsonProperty("sid") final String sid, - @JsonProperty("account_sid") final String accountSid, - @JsonProperty("friendly_name") final String friendlyName, - @JsonProperty("channels") final List channels, - @JsonProperty("translations") final Map translations + @JsonProperty("account_sid") final String accountSid, + @JsonProperty("channels") final List channels, + @JsonProperty("friendly_name") final String friendlyName, + @JsonProperty("sid") final String sid, + @JsonProperty("translations") final Object translations ) { - this.sid = sid; this.accountSid = accountSid; - this.friendlyName = friendlyName; this.channels = channels; + this.friendlyName = friendlyName; + this.sid = sid; this.translations = translations; } - public final String getSid() { - return this.sid; - } - - public final String getAccountSid() { - return this.accountSid; - } - - public final String getFriendlyName() { - return this.friendlyName; - } - - public final List getChannels() { - return this.channels; - } - - public final Map getTranslations() { - return this.translations; - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -137,24 +131,26 @@ public boolean equals(final Object o) { } Template other = (Template) o; - return ( - Objects.equals(sid, other.sid) && - Objects.equals(accountSid, other.accountSid) && - Objects.equals(friendlyName, other.friendlyName) && - Objects.equals(channels, other.channels) && - Objects.equals(translations, other.translations) + Objects.equals(accountSid, other.accountSid) && + Objects.equals(channels, other.channels) && + Objects.equals(friendlyName, other.friendlyName) && + Objects.equals(sid, other.sid) && + Objects.equals(translations, other.translations) ); } @Override public int hashCode() { return Objects.hash( - sid, - accountSid, - friendlyName, - channels, - translations + accountSid, + channels, + friendlyName, + sid, + translations ); } + + } + diff --git a/src/main/java/com/twilio/rest/verify/v2/TemplateReader.java b/src/main/java/com/twilio/rest/verify/v2/TemplateReader.java index 06487e5c63..cec41b401b 100644 --- a/src/main/java/com/twilio/rest/verify/v2/TemplateReader.java +++ b/src/main/java/com/twilio/rest/verify/v2/TemplateReader.java @@ -17,7 +17,8 @@ import com.twilio.base.Page; import com.twilio.base.Reader; import com.twilio.base.ResourceSet; -import com.twilio.constant.EnumConstants; +import com.twilio.constant.EnumConstants.ParameterType; +import com.twilio.converter.Serializer; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; @@ -32,113 +33,94 @@ public class TemplateReader extends Reader